http://stackoverflow.com/q/47986565
tagged with: windows
tagged with: python
tagged with: kivy
tagged with: macos
tagged with: python-3.x
score: 0
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47986604
has body: I get the following errors when running a python file using kivy on a new Windows 10: C:\Users\Me\AppData\Local\Programs\Python\Python36-32\python.exe C:/Users/Me/Desktop/PycharmProjects/music_game_kivy/music_game_kivy.py [INFO ] [Logger ] Record log in C:\Users\Me\.kivy\logs\kivy_17-12-26_10.txt [INFO ] [Kivy ] v1.10.0 [INFO ] [Python ] v3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] [INFO ] [Factory ] 194 symbols loaded [INFO ] [Image ] Providers: img_tex, img_dds, img_gif (img_sdl2, img_pil, img_ffpyplayer ignored) [CRITICAL] [Text ] Unable to find any valuable Text provider. sdl2 - ImportError: DLL load failed: The specified module could not be found. File "C:\Users\Me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\core\__init__.py", line 59, in core_select_lib fromlist=[modulename], level=0) File "C:\Users\Me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\core\text\text_sdl2.py", line 12, in &lt;module&gt; from kivy.core.text._text_sdl2 import (_SurfaceContainer, _get_extents, pil - ModuleNotFoundError: No module named 'PIL' File "C:\Users\Me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\core\__init__.py", line 59, in core_select_lib fromlist=[modulename], level=0) File "C:\Users\Me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\core\text\text_pil.py", line 7, in &lt;module&gt; from PIL import Image, ImageFont, ImageDraw [CRITICAL] [App ] Unable to get a Text provider, abort. Process finished with exit code 1 The exact same python file was running just fine on my old Mac. I'm not posting the entire code, because it is almost 1500 lines long... In case it's helpful, here are my imports from the top of the code: from kivy.app import App from kivy.clock import Clock from kivy.graphics import Color, Rectangle from kivy.uix.button import Button from kivy.uix.image import Image from kivy.uix.label import Label from kivy.uix.widget import Widget from random import randr…
answer count: 1
accepted answer: http://stackoverflow.com/a/47986604
has title: Kivy errors on a new Windows 10 (same code worked fine on an old Mac)

http://stackoverflow.com/q/48006202
has body: I am using python 3.5. I am trying to define an array with set of characters. I tried the below. import array my_char_array = array.array('c', ['g','e','e','k']) When I run, I get the following error: ValueError: bad typecode (must be b, B, u, h, H, i, I, l, L, q, Q, f or d) Isn't 'c' a valid typecode for characters? Please enlighten me.
tagged with: python
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48006823
downvote count: 0
has title: typecode 'c' is not available for array definition in python 3.5
has answer: http://stackoverflow.com/a/48006285
accepted answer: http://stackoverflow.com/a/48006285
type: Question
has answer: http://stackoverflow.com/a/48006299
has answer: http://stackoverflow.com/a/48006823
upvote count: 2
answer count: 3
tagged with: arrays
favorite count: 0

http://stackoverflow.com/q/47994082
tagged with: bjoern
has title: python 3 bjoern error compiler with msvc flag cl.exe failed with exit status 2
type: Question
has comment: http://stackoverflow.com/comment/82957392
has comment: http://stackoverflow.com/comment/82966092
has comment: http://stackoverflow.com/comment/82956419
score: 0
linked to: http://stackoverflow.com/q/37534000
tagged with: python
has body: I can not compile bjoern for version 3 of python these are the versions I'm using windows 10 python 3.4 bjoern-py3 -> [https://github.com/isaiah/bjoern-py3][1][1]: https://github.com/isaiah/bjoern-py3 visual c++ -> Visual C++ for Python-9.0 this is the console output python 2.7 command -> python setup.py build --compiler=msvc running build running build_ext building 'bjoern' extension C:\Users\franciskiko\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -DWANT_SENDFILE=1 -DWANT_SIGINT_HANDLING=1 -Ihttp-parser -IC:\Python34\include -IC:\Python34\include /Tchttp-parser\http_parser.c /Fobuild\temp.win32-3.4\Release\http-parser\http_parser.obj -std=c99 -fno-strict-aliasing -fcommon -fPIC -Wall -g http_parser.c http-parser\http_parser.h(206) : warning C4214: nonstandard extension used : bit field types other than int http-parser\http_parser.h(207) : warning C4214: nonstandard extension used : bit field types other than int http-parser\http_parser.h(234) : warning C4820: 'http_parser' : '4' bytes padding added after data member 'data' http-parser\http_parser.c(389) : warning C4127: conditional expression is constant http-parser\http_parser.c(389) : warning C4127: conditional expression is constant http-parser\http_parser.c(399) : warning C4127: conditional expression is constant http-parser\http_parser.c(407) : error C2143: syntax error : missing ';' before 'const' http-parser\http_parser.c(408) : error C2143: syntax error : missing ';' before 'const' http-parser\http_parser.c(409) : error C2143: syntax error : missing ';' before 'const' http-parser\http_parser.c(410) : error C2143: syntax error : missing ';' before 'const' http-parser\http_parser.c(411) : error C2143: syntax error : missing ';' before 'const' http-parser\http_parser.c(412) : error C2143: syntax error : missing ';' before 'const' http-parser\http_parser.c(415) : error C2065: 'header_field_mark' : undeclared identifier http-parser\http_par…
tagged with: c++
answer count: 0
type: UnansweredQuestion
tagged with: build

http://stackoverflow.com/comment/82965009
type: Comment
type: QuestionComment
has text: @AnsgarWiechers Yea I said that this error appeared on the PowerShell, but didn't necessarily mean it had something to do with PowerShell. If you look closely at the first part of the question, I mentioned that I think it was because I am converting a program that uses VPython.
comment on: http://stackoverflow.com/q/47988942
score: 0

linechart
tags question: http://stackoverflow.com/q/47989704
tag name: linechart
type: Tag

http://stackoverflow.com/q/47952062
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47952248
downvote count: 1
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/82873814
score: -1
has comment: http://stackoverflow.com/comment/82874909
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/47952248
answer count: 1
linked to: http://stackoverflow.com/q/40890068
favorite count: 0
has title: Static file in django without Using {% static "abc.jpg" %}
has comment: http://stackoverflow.com/comment/82873802
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82875122
has body: I had static files in django. Project Structure Sample I have project structure like above i want to use js and img from asset folder. How can i do this ? How i can avoid using {% static "abc.jpg" %} ?

http://stackoverflow.com/q/47892502
has answer: http://stackoverflow.com/a/47892599
accepted answer: http://stackoverflow.com/a/47892599
possible better answer: http://stackoverflow.com/a/47892851
tagged with: curve-fitting
upvote count: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/82786868
tagged with: python
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/82752766
tagged with: scipy
type: Question
answer count: 2
has title: Conditional curve fit with scipy?
has body: Let's say I want to fit a straight line to my data recorded with lights off. Now I accidentally left the lights on, and my data has a constant offset from datapoint 101 and onwards. How can I fit this? I've tried to incorporate a condition for x, but I get the error ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() Remember to uncomment the remainder of the code (to encounter the error). import numpy as np from scipy import optimize import matplotlib.pyplot as plt d1 = np.random.normal(0,0.1, 100) d2 = np.random.normal(3,0.1, 100) x = np.arange(0,200) y = np.concatenate((d1,d2)) plt.plot(x, y) # def line(x, a, b, offset): # if x &lt; 101: # y = a * x + b # else: # y = (a * x + b) + offset # return y # # popt, pcov = optimize.curve_fit(line, xdata = x, ydata = y) # # plt.plot(x, line(x, *popt), color = "firebrick") plt.show() Expected output:
has answer: http://stackoverflow.com/a/47892851
score: 4

http://stackoverflow.com/comment/82714667
has text: @SuperStew Would I have to include timeit into every single file?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47874623

http://stackoverflow.com/comment/82749982
comment on: http://stackoverflow.com/q/47887790
score: 0
type: QuestionComment
has text: @Koshur: you mean that you cannot copy the profile in your home directory to a **new** file and in that new file keep only what is relevant for your non interactive commands???
type: Comment

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

http://stackoverflow.com/comment/82775263
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47888369
has text: @user8706644 you could fill only the first row, and instead of drop duplicate, keep only the 1st row. Might be better indeed if you have a huge df.
type: AnswerComment

http://stackoverflow.com/a/47933971
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47932025
upvote count: 10
type: Answer
answers question: http://stackoverflow.com/q/47932025
score: 10
type: AcceptedAnswer
has body: Since all you need to know is which words match, form a set of all lemmas and look up your words there. Forming the set is very fast (and of course set lookups are even faster). wn_lemmas = set(wordnet.all_lemma_names()) ... if word in wn_lemmas: &lt;do something&gt;

http://stackoverflow.com/comment/82677108
comment on: http://stackoverflow.com/q/47856472
score: 3
has text: Read about `list.sort()` function, especially about the `key` parameter.
type: Comment
type: QuestionComment

sikuli
tags question: http://stackoverflow.com/q/47918011
tags question: http://stackoverflow.com/q/47982244
tag name: sikuli
type: Tag
tags question: http://stackoverflow.com/q/47960637

http://stackoverflow.com/q/47941740
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82852838
tagged with: python
has comment: http://stackoverflow.com/comment/82852941
type: AnsweredQuestion
score: 1
upvote count: 1
duplicate of: http://stackoverflow.com/q/12201928
has answer: http://stackoverflow.com/a/47941810
type: Question
linked to: http://stackoverflow.com/q/12201928
possible better answer: http://stackoverflow.com/a/47941822
has body: Using the following bit of code: for root, dirs, files in os.walk(corpus_name): for file in files: if file.endswith(".v4_gold_conll"): f= open(file) lines = f.readlines() tokens = [line.split()[3] for line in lines if line.strip() and not line.startswith("#")] print(tokens) I get the following error: Traceback (most recent call last): File "text_statistics.py", line 28, in corpus_reading_pos(corpus_name, option) File "text_statistics.py", line 13, in corpus_reading_pos f= open(file) FileNotFoundError: [Errno 2] No such file or directory: 'abc_0001.v4_gold_conll' As you can see, the file was, in fact, located, but then when I try to open the file, it... can't find it? Edit: using this updated code, it stops after reading 7 files, but there are 172 files. def corpus_reading_token_count(corpus_name, option="token"): for root, dirs, files in os.walk(corpus_name): tokens = [] file_count = 0 for file in files: if file.endswith(".v4_gold_conll"): with open((os.path.join(root, file))) as f: tokens += [line.split()[3] for line in f if line.strip() and not line.startswith("#")] file_count += 1 print(tokens) print("File count:", file_count)
has answer: http://stackoverflow.com/a/47941822
answer count: 2
has title: File not found error, even though file was found
downvote count: 0
accepted answer: http://stackoverflow.com/a/47941810
favorite count: 0

http://stackoverflow.com/q/47883843
tagged with: http://stackoverflow.com/tag/csv
has body: i have a csv file with tons of data and each piece of data is stored in a dictionary i need it in a readable format e.g. id name product temperature density timestamp water 1 1001 14 30 40 40 40 2 1002 14 30 50 50 50 i would like these headers only when ive tried it keeps the whole data and doesn't format it here is the data file i hope you guys can help with this: p.s sorry about the amount of data https://www.dropbox.com/sh/qdcl2lrrqj6sttb/AABo_AMGzFqetgRne_7XTPy7a?dl=0 currently ive tried def funcScript(): from data import tankOBJ as tank with open(os.path.join(os.path.join(APP_ROOT, '/csv tester/motherwell.csv')),'r',newline='') as output_file: fieldnames = ['id','name','product','temperature','density','timestamp','water'] writer = csv.Dictwriter(output_file, fieldnames=fieldnames) csv_writer.writeheader() for line in csv_reader: del line['shortname','state','shape','pos_x','pos_y','datum',',max_work','min_work','offset_bottom','offset_volume','offset_level','roof_density','roof_weight','roof_start','roof_end','shell_insulated','shell_cte','shell_temperature','dimension_a','dimension_b','dimension_c','dimension_d','knee_forth','knee_third','knee_second','knee_first','suction_forth,','suction_third','suction_second','suction_first','rundown_forth','rundown_third','rundown_second','rundown_first','suction_low_forth','suction_low_third','suction_low_second','suction_low_first','rundown_low_forth','rundown_low_third','rundown_low_second','rundown_low_first','sll','slu','svl','suv','swlv','swuv','swll','swul','volume','innage','flow','pressure','maximum_volume',] writer.writerow(tank) return 'Hello World!' basically ive ripped the data from another file and got it to download off my webapp in csv format which gives live readings
answer count: 0
has comment: http://stackoverflow.com/comment/82734414
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82734720
has comment: http://stackoverflow.com/comment/82733771
type: Question
has comment: http://stackoverflow.com/comment/82734554
score: 0
has title: csv rearrange the data in a readable way

http://stackoverflow.com/a/59921563
upvote count: 18
type: Answer
answers question: http://stackoverflow.com/q/47884976
score: 17
downvote count: 1
has body: While png is lossless, this does not mean it is uncompressed by default. I specify compression using the IMWRITE_PNG_COMPRESSION flag. It varies between 0 (no compression) and 9 (maximum compression). So if you want uncompressed png: cv2.imwrite(filename, data, [cv2.IMWRITE_PNG_COMPRESSION, 0]) The more you compress, the longer it takes to save. Link to docs

http://stackoverflow.com/a/72808086
score: -2
upvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/135051063
downvote count: 2
answers question: http://stackoverflow.com/q/47896877
has body: The Answer marked as answer works, but it can be improved. it's a actually a built in feature json.dumps(mydict, indent = None, sort_keys=True, default=str, separators=(',', ':')) The argument indent=None is the key argument.

http://stackoverflow.com/comment/84795874
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48861231
has text: @j.k. I just wrote some boilerplate code around your solution, which actually does the work, so I have to thank you for the main effort! @ Cameron Taylor: not sure, but it seems likely, I hope you're able to try it with another driver.
score: 0

http://stackoverflow.com/q/47946942
type: Question
tagged with: random-forest
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47947831
tagged with: scikit-learn
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I have an extremely large dataset and would like to train several random forest models on partitions of the dataset, then average these models to come up with my final classifier. Since random forest is an ensemble method, this is an intuitively sound approach but I'm unsure whether it's possible to do using scikit-learn's random forest classifier. Any ideas? I'd also be open to using a random forest classifier from another package as well, just not sure where to look.
has title: Averaging Multiple Random Forest Models in scikit-learn
score: 1
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/82863782
upvote count: 1
has comment: http://stackoverflow.com/comment/82863974
linked to: http://stackoverflow.com/q/46874061

http://stackoverflow.com/a/48008672
has comment: http://stackoverflow.com/comment/82988959
has comment: http://stackoverflow.com/comment/82986301
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/48006466
answers question: http://stackoverflow.com/q/48006466
has body: You effectively want to map sha256.update over an iterator of file chunks: hasher = hashlib.sha256() chunks = read_those_chunks() map(hasher.update, chunks) return hasher.hexdigest() Note that the explicit iteration from the original calculate_checksums (using the while loop) is now hidden inside of map. Basically, map has replaced the iteration. The obstacle is that you want to avoid a read_those_chunks which loads the whole file into memory (presumably). So, as a first step, implement that piece: def read_those_chunks(open_file, chunk_size): offset = 0 while True: yield open_file.readChunk(offset, chunk_size) offset += chunk_size There's a generator that yields Deferreds that fire with subsequent chunks (or EOFError). Unfortunately, you can't use this with map. So now implement a map-alike that can deal with this: def async_map(function, iterable): try: d = next(iterable) except StopIteration: return d.addCallback(function) d.addCallback(lambda ignored: async_map(function, iterable)) return d Since async_map is going to replace map and map replaced the iteration from the original implementation, async_map is still responsible for making sure we visit every chunk from the iterable. However, iteration (with either for or while) doesn't mix well with Deferred (mixing them is when you typically pull out inlineCallbacks). So async_map doesn't iterate. It recurses - a common alternative to iteration. Each recursive call operates on the next element of the iterable until there are no more (or until a Deferred fails, as will happen in this case due to EOFError). Recursion works better than iteration with Deferred because recursion operates on functions and function calls. Deferred can deal with functions and function calls - pass a function to addCallback and Deferred will eventually call that function. Iteration is made up of small pieces of a function (sometimes called "blocks" or "suites") and Deferred can't deal with these. You can't pass a block to addCallback. Now u…

http://stackoverflow.com/a/47973602
has body: Use json.dumps(..., ensure_ascii=False): foo = "C V M College of Fine Arts,\u00a0 Vallabh Vidyanagar" import json print(json.dumps({'foo':foo}, ensure_ascii=False)) returns: {"foo": "C V M College of Fine Arts, Vallabh Vidyanagar"}
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47973512
answers question: http://stackoverflow.com/q/47973512
type: AcceptedAnswer
downvote count: 0

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

http://stackoverflow.com/comment/83004270
type: AnswerComment
has text: @Georgy I couldn't find any way to make a copy like you said, probably if you store the data in a file and read the file whenever you need the data. Still, in my update the only list modified is the peaksList, if OP needs the data after processing that list he could use the method again, or simply store the data in a file first and then retrieve it as many times as he wants. If you come up with a better idea tell me so I can update answer.
type: Comment
comment on: http://stackoverflow.com/a/48008982
score: 0

http://stackoverflow.com/a/47881272
has body: Instead of using RGB color range to filter the background color you should use HSV color space. Select a hsv range to filter your background color. Here is simple implementation of the same. image = cv2.imread("D:\Image\VaS38.jpg") r = 150.0 / image.shape[1] dim = (150, int(image.shape[0] * r)) resized = cv2.resize(image, dim, interpolation=cv2.INTER_AREA) lower_white = np.array([80, 1, 1],np.uint8) #lower hsv value upper_white = np.array([130, 255, 255],np.uint8) #upper hsv value hsv_img = cv2.cvtColor(resized,cv2.COLOR_BGR2HSV) #rgb to hsv color space #filter the background pixels frame_threshed = cv2.inRange(hsv_img, lower_white, upper_white) kernel = np.ones((5,5),np.uint8) #dilate the resultant image to remove noises in the background #Number of iterations and kernal size will depend on the backgound noises size dilation = cv2.dilate(frame_threshed,kernel,iterations = 2) resized[dilation==255] = (0,0,0) #convert background pixels to black color cv2.imshow('res', resized) cv2.waitKey(0) Result image: PS: Please note that in your case there are slight variations of HSV values near foreground object boundaries so the final result is not perfect. May be you can tune the HSV color range more precisely to get better result, or you can use foreground objects outermost edge as a limiting line to erosion.
has comment: http://stackoverflow.com/comment/83092866
answers question: http://stackoverflow.com/q/47871556
score: 0
has comment: http://stackoverflow.com/comment/83092821
type: Answer

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/47864742
tags question: http://stackoverflow.com/q/47925776
tags question: http://stackoverflow.com/q/47874008
tags question: http://stackoverflow.com/q/47947113
tags question: http://stackoverflow.com/q/47856274
tags question: http://stackoverflow.com/q/47894732
tags question: http://stackoverflow.com/q/47971410
tags question: http://stackoverflow.com/q/47988065
tags question: http://stackoverflow.com/q/47966310
tags question: http://stackoverflow.com/q/47967084
tags question: http://stackoverflow.com/q/47915487
tags question: http://stackoverflow.com/q/47947912
tags question: http://stackoverflow.com/q/47907784
tags question: http://stackoverflow.com/q/47878296
tags question: http://stackoverflow.com/q/47911897
tags question: http://stackoverflow.com/q/47974624
tags question: http://stackoverflow.com/q/47889024
tags question: http://stackoverflow.com/q/47868631
tags question: http://stackoverflow.com/q/47866193
tags question: http://stackoverflow.com/q/47893991
tags question: http://stackoverflow.com/q/47924357
tags question: http://stackoverflow.com/q/47962580
tags question: http://stackoverflow.com/q/48004236
tags question: http://stackoverflow.com/q/47878367
tags question: http://stackoverflow.com/q/47863175
type: Tag
tags question: http://stackoverflow.com/q/47893317
tags question: http://stackoverflow.com/q/47965482
tags question: http://stackoverflow.com/q/47921673
tags question: http://stackoverflow.com/q/48000475
tags question: http://stackoverflow.com/q/47875472
tags question: http://stackoverflow.com/q/47864573
tags question: http://stackoverflow.com/q/47993825
tags question: http://stackoverflow.com/q/47929110
tags question: http://stackoverflow.com/q/47907506
tags question: http://stackoverflow.com/q/47913326
tags question: http://stackoverflow.com/q/47939678
tags question: http://stackoverflow.com/q/47959104
tags question: http://stackoverflow.com/q/47982570
tags question: http://stackoverflow.com/q/47948728
tags question: http://stackoverflow.com/q/47960839
tags question: http://stackoverflow.com/q/47874121
tags question: http://stackoverflow.com/q/47952433
tags question: http://stackoverflow.com/q/47958607
tags question: http://stackoverflow.com/q/47906761
tags question: http://stackoverflow.com/q/47892954
tags question: http://stackoverflow.com/q/47962752
tags question: http://stackoverflow.com/q/47940530

http://stackoverflow.com/a/64598493
has body: You can test that the multiprocessor is working fine by doing the following commands: $ docker run -it --rm ubuntu:20.04 root@somehash:/# apt update &amp;&amp; apt install stress root@somehash:/# stress --cpu 8 # 8 if you have 8 cores If you have multiple cores, you can test in another terminal the command htop or top and you should see all the cores running. If you used htop you should see something as follows. If you are at this step. Then everything is working fine. Furthermore, as I run the script you provided I see my processors being used as they should, you can the the image below. (I also add the process to show it, I run your script inside an ipython terminal. I also changed from sklearn.externals.joblib.parallel import Parallel, delayed to from joblib.parallel import Parallel, delayed because it was not working for me otherwise). I hope the information provided helps. For other clues, you might like to check your version of docker.
type: Answer
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/47989418
score: 4

http://stackoverflow.com/comment/82752549
type: Comment
comment on: http://stackoverflow.com/q/47892625
score: 0
has text: and the problem is that by adding consecutive paths it is easy to disrupt the previously found shortest paths.
type: QuestionComment

http://stackoverflow.com/comment/82957353
comment on: http://stackoverflow.com/a/47994655
score: 0
has text: This is not an answer. Could you add it as a comment in the question?
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47987636
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47987412
has comment: http://stackoverflow.com/comment/121162493
score: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Early Exit BubbleSort The first loop has no bearing on what happens inside The second loop does all the heavy lifting. You can get rid of count by using enumerate To swap elements, use the pythonic swap - a, b = b, a. As per this comment, make use of an early exit. If there are no swaps to be made at any point in the inner loop, that means the list is sorted, and no further iteration is necessary. This is the intuition behind changed. By definition, after the ith iteration of the outer loop, the last i elements will have been sorted, so you can further reduce the constant factor associated with the algorithm. foo = [7, 0, 3, 4, -1] for i in range(len(foo)): changed = False for j, x in enumerate(foo[:-i-1]): if x &gt; foo[j + 1]: foo[j], foo[j + 1] = foo[j + 1], foo[j] changed = True if not changed: break print(foo) [-1, 0, 3, 4, 7] Note that none of these optimisations change the asymptotic (Big-O) complexity of BubbleSort (which remains O(N ** 2)), instead, only reduces the constant factors associated.
answers question: http://stackoverflow.com/q/47987412

http://stackoverflow.com/comment/82799187
type: QuestionComment
comment on: http://stackoverflow.com/q/47915560
score: 2
has text: Try with `y = x // i` which performs integer division.
type: Comment

http://stackoverflow.com/a/47939010
has body: I believe you can create list of all masks and then reduce: masks = [(df.val==x.val)&amp;(df.date &gt;= x.date) for x in df_condition.itertuples()] print (masks) [0 False 1 False 2 False 3 False 4 False 5 False 6 True 7 False dtype: bool, 0 False 1 False 2 False 3 False 4 False 5 False 6 False 7 True dtype: bool] df1 = df[np.logical_and.reduce(masks)]
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47938804
upvote count: 2
answers question: http://stackoverflow.com/q/47938804
type: Answer
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82848715
score: 2

http://stackoverflow.com/comment/82866203
has text: @JessicaWarren Using `x.decode()` to convert `x` which is bytes back to string.
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47948061

http://stackoverflow.com/a/63223628
has body: Step 1:- Upgrade PIP python.exe -m pip install --upgrade pip --u Step2 : make sure its upgraded in your virtual environment (venv) D:\dMig\venv\Lib\site-packages>pip install --upgrade pip --user Requirement already up-to-date: pip in d:\python38\lib\site-packages (20.2) Step3: Uninstall earlier version (venv) D:\dMig\venv\Lib\site-packages>pip3 uninstall tabula-py Step4: Install again pip3 install tabula-py Step5: Verify by below code from tabula import read_pdf #declare the path of your file file_path = "E:\Activity.pdf" #Convert your file df = read_pdf(file_path) print(df)
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47939921
downvote count: 0
type: Answer

http://stackoverflow.com/comment/83002421
has text: The detail is in link https://stackoverflow.com/questions/48005490/why-the-supervisor-make-the-celery-worker-changing-form-running-to-starting-all
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48003587
type: Comment

pyqt
type: Tag
tags question: http://stackoverflow.com/q/47997230
tags question: http://stackoverflow.com/q/47856004
tags question: http://stackoverflow.com/q/47941743
tags question: http://stackoverflow.com/q/47964897
tags question: http://stackoverflow.com/q/47982890
tags question: http://stackoverflow.com/q/47885885
tags question: http://stackoverflow.com/q/47893393
tags question: http://stackoverflow.com/q/47870440
tags question: http://stackoverflow.com/q/47890913
tags question: http://stackoverflow.com/q/47889281
tags question: http://stackoverflow.com/q/48001210
tags question: http://stackoverflow.com/q/47915414
tags question: http://stackoverflow.com/q/47928724
tags question: http://stackoverflow.com/q/47874952
tags question: http://stackoverflow.com/q/47867572
tags question: http://stackoverflow.com/q/47858623
tags question: http://stackoverflow.com/q/48004836
tags question: http://stackoverflow.com/q/47862036
tags question: http://stackoverflow.com/q/47899901
tags question: http://stackoverflow.com/q/47863400
tags question: http://stackoverflow.com/q/47972386
tags question: http://stackoverflow.com/q/47944013
tags question: http://stackoverflow.com/q/47952546
tags question: http://stackoverflow.com/q/47972275
tags question: http://stackoverflow.com/q/47880568
tags question: http://stackoverflow.com/q/47965618
tags question: http://stackoverflow.com/q/47964195
tags question: http://stackoverflow.com/q/47971275
tags question: http://stackoverflow.com/q/47947828
tags question: http://stackoverflow.com/q/47998099
tags question: http://stackoverflow.com/q/47859456
tags question: http://stackoverflow.com/q/47962839
tags question: http://stackoverflow.com/q/47982535
tags question: http://stackoverflow.com/q/48013190
tags question: http://stackoverflow.com/q/47921540
tags question: http://stackoverflow.com/q/47904685
tags question: http://stackoverflow.com/q/47910192
tags question: http://stackoverflow.com/q/47946828
tags question: http://stackoverflow.com/q/47858801
tags question: http://stackoverflow.com/q/47960494
tag name: pyqt
tags question: http://stackoverflow.com/q/47996657
tags question: http://stackoverflow.com/q/47915941
tags question: http://stackoverflow.com/q/47943676
tags question: http://stackoverflow.com/q/47879413
tags question: http://stackoverflow.com/q/47930677
tags question: http://stackoverflow.com/q/47880279
tags question: http://stackoverflow.com/q/48002748

http://stackoverflow.com/a/47930033
has comment: http://stackoverflow.com/comment/82832277
has comment: http://stackoverflow.com/comment/82859639
has body: If i understand correctly you want to use DataFrame.to_sql() method: df_sql.to_sql('dbo.SCORE_TABLE', conn, index=False, if_exists='append')
score: 0
answers question: http://stackoverflow.com/q/47929592
has comment: http://stackoverflow.com/comment/82858438
type: Answer
has comment: http://stackoverflow.com/comment/82857585
has comment: http://stackoverflow.com/comment/82844830

http://stackoverflow.com/a/48003099
score: 2
answers question: http://stackoverflow.com/q/48002785
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/82974612
has body: I've just tried your code in Jupyter Notebook. It ran just fine. I'm using Python 3.6 and this is on Windows 10: In [1]: import logging logging.basicConfig(filename='logs.log', level=logging.INFO) logging.info('something happened') In [2]: with open("logs.log") as log: print(log.read()) INFO:root:something happened
has comment: http://stackoverflow.com/comment/82974810
has comment: http://stackoverflow.com/comment/82974553
downvote count: 0

http://stackoverflow.com/q/47931749
tagged with: excel-formula
has body: I'm running into a strange issue with scipy's percentileofscore function. In Excel, I have the following rows: 0 1 3 3 3 3 3 4 6 8 9 11 11 11 12 45 Next, I have a column that calculates the percentilerank.inc for each row: =100 * (1-PERCENTRANK.INC($A:$A,A1)) The results are as follows: 100 94 87 87 87 87 87 54 47 40 34 27 27 27 7 0 I then take the same data and put them into an array and calculate the percentilofscore using scipy 100 - stats.percentileofscore(array, score, kind='strict') However, my results are as follows: 100 94 88 88 88 88 88 56 50 44 38 31 31 31 13 7 Here are the results side by side to show the differences: Data Excel Scipy 0 100 100 1 94 94 3 87 88 3 87 88 3 87 88 3 87 88 3 87 88 4 54 56 6 47 50 8 40 44 9 34 38 11 27 31 11 27 31 11 27 31 12 7 13 45 0 7 There are clearly some differences in the results. Some of them off by 4 digits. Any thoughts on how to mimic Excel's PERCENTILERANK.INC function? I'm using scipy 1.0.0, numpy 1.13.3, python 3.5.2, Excel 2016 Edit If I do not include the max value of 45, the numbers jive. Could this be how PERCENTILERANK.INC works?
accepted answer: http://stackoverflow.com/a/47932005
tagged with: python
has comment: http://stackoverflow.com/comment/82832531
type: AnsweredQuestion
has title: Why is Scipy's percentileofscore returning a different result than Excel's PERCENTRANK.INC?
score: 2
upvote count: 2
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/82832595
has answer: http://stackoverflow.com/a/47932005
has comment: http://stackoverflow.com/comment/82832956
tagged with: percentile
has comment: http://stackoverflow.com/comment/82833012
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/47908657
has comment: http://stackoverflow.com/comment/82785045
tagged with: python
favorite count: 0
type: UnansweredQuestion
has body: I have models Reserved and Room (default status is Free). And i want get list of all Rooms. Their statuses is Reserved (I have such table) Free (not price, state) Busy So in short i need to get all Rooms with their status. I don't need status fields and will not add it. No status field in my models. How can i get certain statuses? Shortly model class Room(models.Model): # Default all rooms are Free (Rooms state) number = models.ForeignKey(RoomNumber) expiry_date = models.DateTimeField() class Reserved(models.Model): visitor = models.ForeignKey(Visitor, on_delete=models.PROTECT) room = models.OneToOneField(Room) reserved_date = models.DateTimeField() begin_date = models.DateTimeField() I tried to do Subquery but no result :( reserved = Reserved.objects\ .filter(room=OuterRef('pk'))\ .filter(begin_date=timezone.now())\ .values(count=Count('pk')) Room.objects.annotate(reserved=Subquery(reserved[:1])) If 1 room is Reserved if 0 empty
tagged with: django
has comment: http://stackoverflow.com/comment/82784967
downvote count: 1
score: -1
has title: Get list from two models (With addtional fields). Make Subquery
type: Question
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47909069

http://stackoverflow.com/q/48009243
upvote count: 2
type: UnansweredQuestion
tagged with: cpu
has answer: http://stackoverflow.com/a/48164720
tagged with: tensorflow
score: 2
has title: tensorflow build - CPU / MKL / Windows
type: Question
has answer: http://stackoverflow.com/a/49187554
downvote count: 0
tagged with: intel-mkl
answer count: 3
has body: Has anyone succeeded to build tensorflow python wheel with the following configuration: CPU (not GPU) OS: Windows 7 / server 2012 Using Intel MKL and/or mkl-dnn Python 3.6 I am struggling, for days now, trying to tweak bazel files and cmake files without success. Would like to know if someone succeeded and willing to share what he did. Thanks, Lior
tagged with: windows
has answer: http://stackoverflow.com/a/72921433
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/82706943
has text: new error as follows Traceback (most recent call last): File "/Users/jonathonlenoury/Desktop/Scraper_v.01", line 19, in <module> name = product.find(attrs=product_name).text.strip() AttributeError: 'NoneType' object has no attribute 'text' [Finished in 1.277s]
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47867589

http://stackoverflow.com/a/48001232
answers question: http://stackoverflow.com/q/48001210
has comment: http://stackoverflow.com/comment/82971170
score: 1
has comment: http://stackoverflow.com/comment/82971100
has body: In Qt, and therefore also in PyQt, if the parent dies the children too, so only pass as a parent of the QDialog to self.mainWin: self.popup = QDialog(self.mainWin)
upvote count: 1
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/82971226
has comment: http://stackoverflow.com/comment/82971055
has comment: http://stackoverflow.com/comment/82971165
accepted answer of: http://stackoverflow.com/q/48001210
has comment: http://stackoverflow.com/comment/82971231
downvote count: 0

http://stackoverflow.com/comment/82977859
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/47995294
has text: I copied the wrong error, I just edited the question with the correct error and your advice implemented. I still get the same error.

http://stackoverflow.com/comment/82924642
comment on: http://stackoverflow.com/q/47975983
score: 0
has text: I don't see problem in Traceback so maybe you have wrong indentions and `name = 'Trip_advisor'` is not inside `class Tripadvisor(scrapy.Spider)`, or file with `class Tripadvisor` is in wrong place - it has to be in subfolder `spiders`
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47926317
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/47926723
has comment: http://stackoverflow.com/comment/82820919
has comment: http://stackoverflow.com/comment/82820867
has body: I am trying to produce a number of plots of temperature (te) versus time (t), where for each plot, a different timestep (dt) is used to calculate the temperature. . Initially my code ran fine and I produced the plot shown (the plot is made up of a number of plots, more visible when zoomed in). However after making an adjustment to my values for dt_values I have not been able to run the code, and am getting the 'x and y must have same first dimension' error message but I cannot see why. import numpy as np import matplotlib.pyplot as plt r = 0.024 #cooling rate per minute te_init = 90.0 te_surr = 17 dt_values = [0.05, 0.025, 0.01, 0.005, 0.001] for j in dt_values: t = np.arange(0,100,j) te = np.zeros(len(t)) te[0] = te_init def f(te): y = -r*(te - te_surr) # y is the derivative return y for i in range(1,len(t)): te[i] = te[i-1] + f(te[i-1])*j plt.plot(t, te[i], label = j) plt.xlabel('Time, [min]') plt.ylabel('Temperature, [C]') plt.title('Adaptive Time Steps') plt.legend(loc=4)
has comment: http://stackoverflow.com/comment/82820811
type: AnsweredQuestion
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/82820590
accepted answer: http://stackoverflow.com/a/47926723
type: Question
tagged with: numpy
tagged with: python-2.7
has title: Unable to plot due to size of x and y arrays
answer count: 1

http://stackoverflow.com/q/47937566
has answer: http://stackoverflow.com/a/47937738
score: 10
has comment: http://stackoverflow.com/comment/82844309
upvote count: 10
has answer: http://stackoverflow.com/a/47937728
downvote count: 0
favorite count: 0
tagged with: python
answer count: 4
has body: How do I calculate the response time from the moment where the user input the search criteria until the relevant information are loaded/displayed onto the portal?
has comment: http://stackoverflow.com/comment/82844818
has answer: http://stackoverflow.com/a/59688095
type: UnansweredQuestion
tagged with: django
has title: How to calculate response time in Django
type: Question
has answer: http://stackoverflow.com/a/47937685

http://stackoverflow.com/comment/82714477
score: 1
has text: I am not in the position to interpret the C code. But I understand from this that `log(x), log2(x), log10(x)` should have the same speed, because they use the same C library strategies. And `log(x, n)` is slower, because it uses the logarithmic formula from my question.
comment on: http://stackoverflow.com/a/47874195
type: AnswerComment
type: Comment

http://stackoverflow.com/a/47958630
answers question: http://stackoverflow.com/q/47957018
score: 0
type: Answer
has body: The answer is yes, but it is detailed so I can only give you high level steps here. Jenkins can execute command line statements, and python modules can be run from the command line. I would start by using the begins library to create a python file to run from the command line with arguments. Get it working on your local machine that way. You will want to use either virtualenv or venv, and do all your pip installs using that virtual environment. Then you can copy the virtual environment to your Jenkins machine, or create a new one. Look into the freeze tool. When calling your python from jenkins, you must first activate your virtual environment just as if you were working on it yourself. You have a lot of research to do, but is very doable. I can help with follow up questions if needed.

http://stackoverflow.com/q/47970106
upvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47971451
possible better answer: http://stackoverflow.com/a/47970211
score: 1
has answer: http://stackoverflow.com/a/47970211
type: Question
answer count: 2
has body: Model.py: class Match(models.Model): home_team = models.CharField(max_length=200) away_team = models.CharField(max_length=200) class Stat(models.Model): match = models.ForeignKey(Match) team = models.CharField(max_length=100) goals = models.IntegerField(default=0) assists = models.IntegerField(default=0) views.py context_dict = {} match = Match.objects.get(pk=1) home_stat = Stat.objects.get(match=match, team=match.home_team) away_stat = Stat.objects.get(match=match, team=match.away_team) context_dict['home_stat'] = home_stat context_dict['away_stat'] = away_stat return render(request, 'index.html', context_dict) template goals: {{ home_stat.goals }} : {{ away_stat.goals }} assists: {{ home_stat.assists }} : {{ away_stat.assists }} django-debug-toolbar shows two duplicated queries: https://sfault-image.b0.upaiyun.com/220/984/2209840587-5a3e5ccccec87_articlex SELECT "myapp_stat"."id", "myapp_stat"."match_id", "myapp_stat"."team", "myapp_stat"."goals", "myapp_stat"."assists" FROM "myapp_stat" WHERE ("myapp_stat"."match_id" = '1' AND "myapp_stat"."team" = '''TeamA''') Duplicated 2 times. F:\myproject\myapp/views.py in index(11) home_stat = Stat.objects.get(match=match, team=match.home_team) SELECT "myapp_stat"."id", "myapp_stat"."match_id", "myapp_stat"."team", "myapp_stat"."goals", "myapp_stat"."assists" FROM "myapp_stat" WHERE ("myapp_stat"."match_id" = '1' AND "myapp_stat"."team" = '''TeamB''') Duplicated 2 times. F:\myproject\myapp/views.py in index(12) away_stat = Stat.objects.get(match=match, team=match.away_team) how to fix this?
downvote count: 0
accepted answer: http://stackoverflow.com/a/47971451
has title: Django SQL query duplicated 2 times
tagged with: python
favorite count: 0
tagged with: django

http://stackoverflow.com/q/47963972
answer count: 1
score: 1
accepted answer: http://stackoverflow.com/a/47964000
favorite count: 0
tagged with: python
type: AnsweredQuestion
upvote count: 1
has body: Suppose I have the following list: temp = ['Ok', 'Whoa. Robot?'] How do I get a string that looks like "1) 'Ok', 2) 'Whoa. Robot?'" I'm trying to do this for a list comprehension. I can obviously join them using: " ".join(temp) I can do it in a loop in a fairly ugly way: mystring = "" temp = ['Ok', 'Whoa. Robot?'] for i in range(len(temp)): mystring += str(i) + ") " + temp[i] + " " Is there a pythonic way to do it in one step with a list comprehension?
linked to: http://stackoverflow.com/q/37782066
type: Question
has answer: http://stackoverflow.com/a/47964000
downvote count: 0
has title: List comprehension in python with numbering
tagged with: list-comprehension

http://stackoverflow.com/q/47944567
answer count: 1
tagged with: aws-lambda
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has title: Use AWS Lambda to create CSV and save to S3 (Python)
tagged with: amazon-s3
has body: I've got some Python code that goes to a URL, parses an HTML table, and saves the result to a CSV. Changes to the table happen frequently, and I'd like a trending view of these changes. To accomplish this, I'd like my code to run as a function in Lambda, and save snapshots of the table to S3 every 12 hours. I've created the Lambda, used CloudWatch to trigger the function based on time, and given it permissions to access the relevant S3 bucket, BUT I can't find any resources on how to save the output of the function to said bucket. Any pointers or alternate suggestions would be greatly appreciated. Thanks! (Note: I have found a resource on here that describes this process using Node, which isn't out of the question, but I'd prefer to remain in Python if possible.)
has comment: http://stackoverflow.com/comment/82858941
type: Question
has answer: http://stackoverflow.com/a/47944808
has comment: http://stackoverflow.com/comment/82860961
tagged with: amazon-web-services
score: 0

http://stackoverflow.com/comment/82791552
score: 0
comment on: http://stackoverflow.com/q/47911859
type: QuestionComment
type: Comment
has text: This sounds like an excellent opportunity to learn.

http://stackoverflow.com/a/48009662
has comment: http://stackoverflow.com/comment/82987825
score: 1
answers question: http://stackoverflow.com/q/48009566
upvote count: 1
downvote count: 0
type: Answer
has body: You can solve it by creating your tuple-inputs from a list like so: def GetTuple(): data=[] number=input("Enter the how many elements you want :") for i in range(0,number): ele=input("Enter the element :") data.append(ele) return tuple(data) myTup = GetTuple() print(myTup) If you need multiple tuples you have to call this multiple times and put each tumple inside another list. After the tuple is created, you cannot modify it.

annotations
tags question: http://stackoverflow.com/q/47862215
type: Tag
tag name: annotations

http://stackoverflow.com/comment/83092866
type: AnswerComment
has text: are you able to extract the foreground object with fine boundaries?
type: Comment
comment on: http://stackoverflow.com/a/47881272
score: 0

http://stackoverflow.com/comment/82807116
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47919423
has text: yes, but no IoT sensor alone will send you a 17GB JSON file. Somewhere, you aggregated that data and decided to dump it in a single JSON file. And that was a mistake. If it's in Hadoop, I'm sure there's better export formats than JSON.
type: Comment

http://stackoverflow.com/comment/82725197
has text: `key = re.findall(r'clientname', self.cacheDictionary.keys())` and then retrieve the key maybe?
score: 1
comment on: http://stackoverflow.com/q/47879585
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82829685
has text: @Graipher My previous comment/answer was unclear: I mean, what if the "subfiles" have common dependencies? I would have to do a `from common_file import *` in all subfiles. I might even have crossed dependencies. I wish I could do kind of a _raw_ import, much like a command line `cat` but in Python.
comment on: http://stackoverflow.com/q/47928796
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47963180
type: Answer
has body: What happens is that the interactive Python interpreter compiles every statement separately. Compilation not only produces bytecode, it also produces constants, for any built-in immutable type, including integers. Those constants are stored with the code object as the co_consts attribute. Your x = -10 is compiled separately from the y = -10 assignment, and you end up with entirely separate co_consts structures. Your x, y = [-10, -10] iterable assignment on the other hand, is a single assignment statement, passed to the compiler all at once, so the compiler can re-use constants. You can put simple statements (like assignments) on a single line with a semicolon between them, at which point, in Python 2.7, you get the same -10 object again: &gt;&gt;&gt; x = -10; y = -10 &gt;&gt;&gt; x is y True Here we compiled a single statement again, so the compiler can decide it that it only needs a single object to represent the -10 value: &gt;&gt;&gt; compile('x = -10; y = -10', '', 'single').co_consts (-10, None) 'single' is the compilation mode the interactive interpreter uses. The compiled bytecode loads the -10 value from those constants. You'd get the same thing if you put everything in a function, compiled as a single compound statement: &gt;&gt;&gt; def foo(): ... x = -10 ... y = -10 ... return x is y ... &gt;&gt;&gt; foo() True &gt;&gt;&gt; foo.__code__.co_consts (None, -10) Modules are also compiled in one pass, so globals in a module can share constants. All this is an implementation detail. You should never, ever count on this. For example, in Python 3.6, the unary minus operator is handled separately (rather than -10 being seen as a single integer literal), and the -10 value is reached after constant folding during the peephole optimisation. This gets you get two separate -10 values: &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.version_info sys.version_info(major=3, minor=6, micro=3, releaselevel='final', serial=0) &gt;&gt;&gt; compile('x = -10; y = -10', '', 'single').co…
upvote count: 6
answers question: http://stackoverflow.com/q/47958141
score: 6
downvote count: 0

http://stackoverflow.com/comment/82932466
has text: I get the following error: "ValueError: cannot join with no level specified and no overlapping names" Do you know what it means or how to fix it ?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47981476

http://stackoverflow.com/q/47956902
tagged with: http-status-code-404
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/38627393
has title: Getting 404 error messages after placing Django Python app in Docker Container
type: Question
has body: I am trying to get some template information to display on a web page served in from a Docker container. It is using uWSGI. The name of the template is base.html There are "decorations" associated with the base.html file that are located in the static directory. To be more specific, it resides in the static/wforms/assets directory. Below is how the assets directory is being used in the template. &lt;link href="{% static 'wforms/assets/global/plugins/font-awesome/css/font-awesome.min.css' %}" rel="stylesheet" type="text/css" /&gt; &lt;link href="{% static 'wforms/assets/global/plugins/simple-line-icons/simple-line-icons.min.css' %}" rel="stylesheet" type="text/css" /&gt; &lt;link href="{% static 'wforms/assets/global/plugins/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet" type="text/css" /&gt; Whenever I go to a page that uses the base.html template, the decorations are not found and the resulting web page is a mess. Everything works fine in PyCharm. The problem happens when moving everything to the directory structure in a Docker Container. Below is the directory structure in PyCharm. I start the container like this: docker run -it --rm -p 8888:8888 -v /home/dockcclubdjango/apps/wforms/assets:/code/backendworkproj/static/wforms/assets --name my-running-app my-python-app As an FYI, the /home/dockcclubdjango/apps/wforms/assets does exist and has the correct info in it. Then, I attempt to go to the web home page. The page shows up but all of the "decorations" are not present. So, the page looks somewhat messy. Like this: I look at the source code of the page and see the following below. &lt;link href="/static/wforms/assets/global/plugins/bootstrap-daterangepicker/daterangepicker.min.css" rel="stylesheet" type="text/css" /&gt; &lt;&lt;&lt; got 404 error in log file &lt;link href="/static/wforms/assets/global/plugins/morris/morris.css" rel="stylesheet" type="text/css" /&gt; &lt;&lt;&lt; got 404 error in log file &lt;link href="/static/wforms/assets/global/plugins/f…
downvote count: 0
has answer: http://stackoverflow.com/a/47961894
tagged with: docker
answer count: 2
possible better answer: http://stackoverflow.com/a/47956975
has answer: http://stackoverflow.com/a/47956975
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/47961894
tagged with: django
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/82982505
type: QuestionComment
comment on: http://stackoverflow.com/q/48004925
has text: you mean after step 3 user2.username is a
score: 0
type: Comment

http://stackoverflow.com/comment/83011691
score: 0
comment on: http://stackoverflow.com/q/48009727
type: Comment
type: QuestionComment
has text: Ref: https://github.com/cherrypy/cherrypy/issues/1680

http://stackoverflow.com/a/47977665
type: Answer
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/47977449
answers question: http://stackoverflow.com/q/47977449
downvote count: 0
has comment: http://stackoverflow.com/comment/82925050
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82925195
has body: The repeated cloning and exhausting of only one of the resulting iterators is not very efficient. As per the itertools.tee docs: In general, if one iterator uses most or all of the data before another iterator starts, it is faster to use list() instead of tee(). from itertools import islice my_list = [1, 2, 3] # or, more generally # my_list = list(my_gen()) for i, a in enumerate(my_list): for b in islice(my_list, i+1, None): print((a, b)) (1, 2) (1, 3) (2, 3)

http://stackoverflow.com/comment/82717869
comment on: http://stackoverflow.com/a/47874513
type: Comment
has text: @ ahed87 - I tried your first solution (`for cell, in rows:`) and I am getting this error: `ValueError: too many values to unpack (expected 1)`. I assume this is because there is more than 1 element in tuple? Thank you for your answer.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82781401
type: QuestionComment
has text: It's actually mentioned in the [docs](https://docs.python.org/3.3/library/functions.html#id)... "Two objects with non-overlapping lifetimes may have the same id() value."
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47907032

http://stackoverflow.com/q/47877516
downvote count: 1
type: Question
tagged with: dataframe
score: 0
has answer: http://stackoverflow.com/a/47912029
tagged with: concatenation
tagged with: pandas
answer count: 1
has title: Dataframes columns get lost after using pd.concat
has body: I have the following situation: I have a dataframe with a column 'revisions' which is formated as a dictionary containing multiple other dictionaries with the keys 'a' and 'b'. The revisions belong to the key column id. What I was trying to do is get rid of the dict format. Thus I wanted to list for every subdictionary its values along with the other columns of the dataframe. The new columns should then adopt the name of the keys ('a' and 'b') Initial Dataframe: id column2 (dict_column) column3 0 {{'a': 91125, 'b': 233}{'a': 955, 'b': 267}} Marc 1 {{'a': 91875, 'b': 455}{'a': 115, 'b': 267}} Robert 2 {{'a': 91955, 'b': 354}{'a': 255, 'b': 267}} George 3 {{'a': 91565, 'b': 987}} Peter 4 {{'a': 95925, 'b': 896}} Hans My objective: id a b column3 0 91125 233 Marc 0 955 267 Marc 1 91875 455 Robert 1 115 267 Robert 2 91955 354 George 2 255 267 George 3 91565 987 Peter 4 95925 896 Hans Now, I searched for a way to do that and found a nice solution by using pd.concat. df = pd.concat([pd.DataFrame(x) for x in df['column2']],keys=df['id']).reset_index(level=1, drop=True).reset_index() Now my Problem is that the 'column 3' get lost and it returns the following dataframe: id a b 0 91125 233 0 955 267 1 91875 455 1 115 267 2 91955 354 2 255 267 3 91565 987 4 95925 896 ´ Do you guys have an idea what I do wrong? Many thanks advance, Greetz
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
upvote count: 1
linked to: http://stackoverflow.com/q/45322552

http://stackoverflow.com/a/47919216
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/47919179
upvote count: 1
type: Answer
has body: You can use join() and pass list to it as follows: a=['a is apple','b is banana','c is cherry'] print("\n".join(a)) print("====================") print("\n".join(a)) output a is apple b is banana c is cherry ==================== a is apple b is banana c is cherry

http://stackoverflow.com/q/47943413
possible better answer: http://stackoverflow.com/a/47945352
has comment: http://stackoverflow.com/comment/82856414
has answer: http://stackoverflow.com/a/47945352
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/47945818
accepted answer: http://stackoverflow.com/a/47945759
has comment: http://stackoverflow.com/comment/82856481
tagged with: python
has body: I'm creating simple notepad program in Tkinter. I decided to put functions in separate file. Is it possible if the functions are operating on variables declared in main file? This is snippet of the code: main.py from tkinter import * from otherfile import cut root = Tk() .... menu_edit.add_command(label='Cut', compound='left', command=cut) ... main_text = Text(root, wrap ='word') main_text.pack(expand='yes', fill = 'both') now I have otherfile.py def cut(): main_text.event_generate('&lt;&lt;Cut&gt;&gt;') return 'break' Once I run it I'll get: Exception in Tkinter callback Traceback (most recent call last): File "C:...\tkinter\__init__.py", line 1699, in __call__ return self.func(*args) File "C:\....otherfile.py", line 3, in cut main_text.event_generate('&lt;&lt;Cut&gt;&gt;') NameError: name 'main_text' is not defined So I guess otherfile.py does not understand main_text which is defined in main.py. Is there a way to bypass it and allow me to put all the functions in different py file?
type: AnsweredQuestion
has title: Calling function from another file, which contains variable declared in main file
has answer: http://stackoverflow.com/a/47945759
type: Question

pytest
tags question: http://stackoverflow.com/q/48013672
tags question: http://stackoverflow.com/q/47997183
tags question: http://stackoverflow.com/q/47900727
tags question: http://stackoverflow.com/q/47958166
tag name: pytest
tags question: http://stackoverflow.com/q/47914934
tags question: http://stackoverflow.com/q/47983156
tags question: http://stackoverflow.com/q/47994575
tags question: http://stackoverflow.com/q/48006939
tags question: http://stackoverflow.com/q/47871091
tags question: http://stackoverflow.com/q/47966456
tags question: http://stackoverflow.com/q/47988664
tags question: http://stackoverflow.com/q/47872074
tags question: http://stackoverflow.com/q/47884473
tags question: http://stackoverflow.com/q/47865002
tags question: http://stackoverflow.com/q/47884709
tags question: http://stackoverflow.com/q/47859986
tags question: http://stackoverflow.com/q/47946239
tags question: http://stackoverflow.com/q/47904245
tags question: http://stackoverflow.com/q/47876766
tags question: http://stackoverflow.com/q/47879490
type: Tag

http://stackoverflow.com/q/47872639
has title: Matplotlib set_data xdata and ydata must be same length error
upvote count: 5
answer count: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/47872809
score: 5
tagged with: python
accepted answer: http://stackoverflow.com/a/47872809
has body: I have a simple matplotlibchart that I would like to add points to via a function. It seems that when I extend the arrays the store x and y values, I get the error RuntimeError: xdata and ydata must be the same length despite both arrays being 6 values. import matplotlib.pyplot as plt import numpy as np import time x = np.array([1, 2, 3]) y = np.array([1, 7, 5]) plt.ion() fig = plt.figure() ax = fig.add_subplot(111) line1, = ax.plot(x, y, 'r-') plt.show() def update_points(new_x, new_y): global x, y, fig, line1, ax time.sleep(2) x = np.append(x, new_x) y = np.append(y, new_y) line1.set_xdata(x) line1.set_xdata(y) ax.relim() ax.autoscale_view() fig.canvas.draw() update_points(np.array([4, 5, 6]), np.array([4, 5, 3]))
type: AnsweredQuestion
tagged with: matplotlib
possible better answer: http://stackoverflow.com/a/62786037
has answer: http://stackoverflow.com/a/62786037
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/114298183

http://stackoverflow.com/comment/82807244
type: AnswerComment
has text: Hmmm, it is a bit old, is possible upgrade?
type: Comment
comment on: http://stackoverflow.com/a/47919506
score: 0

http://stackoverflow.com/a/47871834
has comment: http://stackoverflow.com/comment/82711438
has body: Because you defined health1 - a (string, int) tuple - as hp1 was still 100 and didn't change it since then. This is not a pointer in C/C++ sense, just a copy by value.
score: 0
has comment: http://stackoverflow.com/comment/82709084
type: Answer
answers question: http://stackoverflow.com/q/47871806
has comment: http://stackoverflow.com/comment/82709126

http://stackoverflow.com/q/47944706
has answer: http://stackoverflow.com/a/47944829
favorite count: 0
has answer: http://stackoverflow.com/a/47944823
upvote count: 8
type: UnansweredQuestion
downvote count: 2
score: 6
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/47944785
has answer: http://stackoverflow.com/a/47944998
has answer: http://stackoverflow.com/a/47944775
type: Question
linked to: http://stackoverflow.com/q/5753597
has title: How to Create Nested Dictionary in Python with 3 lists
has answer: http://stackoverflow.com/a/47945470
has comment: http://stackoverflow.com/comment/95328195
has body: Let us Suppose, I have created 3 lists and I want to create a dictionary for it. e.g. a= ['A', 'B', 'C', 'D'] b =[1, 2, 3, 4] c = [9, 8, 7, 6] Now What I want is to create a dictionary like this: {'A':{'1' :'9'} , 'B':{'2':'8'}, 'C':{'3':'7'} , 'D':{'4':'6'}} is it possible, Can Someone Help me on this?
answer count: 7
linked to: http://stackoverflow.com/q/46831228
linked to: http://stackoverflow.com/q/2481421
has answer: http://stackoverflow.com/a/47945386

http://stackoverflow.com/comment/82768906
type: Comment
type: QuestionComment
score: 0
has text: https://docs.google.com/spreadsheets/d/1278lc1zanIKxIWzL6IH1ZzpqkjLeIP_m8Db_FxdBMZ4/edit
comment on: http://stackoverflow.com/q/47901157

http://stackoverflow.com/a/47901225
upvote count: 1
has body: Here is a duplicate-safe version of @Akavall's solution. If there are multiple occurrences of a value the first index is returned: a = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]] b = [3,4,7,11] # introduce a repeated value a[1][1] = a[1][0] a # [[1, 2, 3], [4, 4, 6], [7, 8, 9], [10, 11, 12]] i, j = np.where(a == np.c_[b]) j[i.searchsorted(range(len(b)))] # array([2, 0, 0, 1])
answers question: http://stackoverflow.com/q/47900463
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/q/47912931
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/82793586
tagged with: dataframe
tagged with: multi-index
has comment: http://stackoverflow.com/comment/82794094
tagged with: pandas-groupby
tagged with: pandas
has comment: http://stackoverflow.com/comment/82793742
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/71206960
has comment: http://stackoverflow.com/comment/82794218
type: UnansweredQuestion
has title: Pandas DataFrame.rolling window with MultiIndex
tagged with: python
has comment: http://stackoverflow.com/comment/82794812
has comment: http://stackoverflow.com/comment/82796562
score: 1
has body: How can I apply a DataFrame.rolling function and assign the values back to the original DataFrame? E.g., i = pd.MultiIndex.from_product([['A','B','C'], np.arange(1, 11, 1)], names=['Name','Num']) df = pd.DataFrame(np.random.randn(30), i, columns=['Vals']) window = df.groupby(['Name']).rolling(3, min_periods=3) df['Window'] = window['Vals'].apply(lambda x: x[1] + x[2]) In this case, I want the rolling lambda to reset with each Name value, so Window would be NaN for the first 3 rows of each Name. However, the assignment to a new column of the DataFrame at the end produces a column that is entirely NaN The sample window lambda essentially works correctly, but I am noticing that it adds the grouped value to the MultiIndex. Note in the following that there are two levels called Name: window['Vals'].apply(lambda x: x[1] + x[2]) # Returns: Name Name Num A A 1 NaN 2 NaN 3 -2.408704 4 -3.184169 5 0.207093 6 1.649017 7 0.789064 8 0.706335 9 -0.487192 10 -1.625869 B B 1 NaN 2 NaN 3 0.023201 4 -0.044582 5 0.409526 Am I using these methods incorrectly, or failing to do something necessary to get the window.apply() to align with the DataFrame?

http://stackoverflow.com/q/48010179
has answer: http://stackoverflow.com/a/48010353
has body: I have the following string: s = " 3434 garbage workorders: 138 waiting, 2 running, 3 failed, 134 completed" I would like to parse the statuses and counts after "workorders". I've tried the following regex: r = r"workorders:( (\d+) (\w+),?)*" but this only returns the last group. How can I return all groups? p.s. I know I could do this in python, but was wondering if there's a pure regex solution &gt;&gt;&gt; s = " 3434 garbage workorders: 138 waiting, 2 running, 3 failed, 134 completed" &gt;&gt;&gt; r = r"workorders:( (\d+) (\w+),?)*" &gt;&gt;&gt; re.findall(r, s) [(' 134 completed', '134', 'completed')] &gt;&gt;&gt; output should be close to [('138', 'waiting'), ('2', 'running'), ('3', 'failed'), ('134', 'completed')]
has comment: http://stackoverflow.com/comment/82989049
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48010313
has answer: http://stackoverflow.com/a/48010375
has comment: http://stackoverflow.com/comment/82989078
upvote count: 2
answer count: 5
type: UnansweredQuestion
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/82988909
score: 2
has comment: http://stackoverflow.com/comment/82988771
has answer: http://stackoverflow.com/a/48010376
has title: regex matching multiple repeating groups
has answer: http://stackoverflow.com/a/48010473
type: Question

http://stackoverflow.com/comment/83073900
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48030229
has text: The might be an `OPTIONS` in or near the same place where `use_unicode` goes.
type: AnswerComment

http://stackoverflow.com/q/47995757
tagged with: python
has answer: http://stackoverflow.com/a/48026034
has comment: http://stackoverflow.com/comment/82986948
type: AnsweredQuestion
score: 1
tagged with: error-handling
type: Question
has comment: http://stackoverflow.com/comment/82961577
has title: Python 3.6: Using object instance name for raising errors
accepted answer: http://stackoverflow.com/a/48026034
tagged with: custom-errors
tagged with: typeerror
has body: I'm attempting to create a 3-d graphics engine using Python 3.6, Tkinter, and specifically NOT pygame (or any other 3d graphics engines) as part of a university assignment. Within this project, I have had to create a "matrix" class, which allows me to easily create and manipulate mxn matrices. I believe this to be crucial for transforming vectors in order to display items on a 2d display. One method I would like my Matrix class to contain is matrix multiplication. I figured the first (and most important) thing to check when performing this method is to ensure that the width of the first matrix is equal to the height of the second matrix, as that is necessary for multiplying two matrices together. If the two matrices cannot be multiplied together, I raise an TypeError, in which I want to say "Matrix multiplication not possible. Width of {first matrix's name}: ({value}) is not equal to height of {second matrix's name}: ({value})". eg apple = Matrix(2, 3, List_of_values) #creates a matrix instance that is 2x3 and contains 6 values from a list pear = Matrix(4, 3, Another_list_of_values) #creates a matrix that is 4x3 and contains 12 values from another list apple.multiply(pear) This should, when all is working, attempt to perform {apple x pear} mathematical operation, specifically with apple first and pear second In this case, multiplication is obviously not possible: apple is 2 high and 3 wide, and pear is 5 high and 3 wide. I would like to raise an error like: TypeError: Matrix multiplication not possible: Width of apple (3) is not equal to height of pear (4) Instead, I get this: TypeError: Matrix multiplication not possible: Width of &lt;__main__.Matrix object at 0x1056117b8&gt; (3) is not equal to height of &lt;__main__.Matrix object at 0x105618e80&gt; (4) I believe I need to define the __name__ attribute within my matrix class, such that when apple.__name__ is called, it returns a string that contains the name "apple". Is this possible? Is this even a good idea? Is …
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82959573
upvote count: 1

http://stackoverflow.com/comment/82943735
has text: Bubble sort is an example for a bad sorting algorithm. The only thing you can do is, early escape from the loop, which will be a little faster...
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/47987412

http://stackoverflow.com/q/48007784
has title: Negative sign in Python Subseting operations
downvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/48008509
has comment: http://stackoverflow.com/comment/82983783
favorite count: 0
has body: I have the following array: np.random.seed(12) s = np.random.randn(5, 5) What does the negative sign implies in sub setting operation? I.e s[1:-1, :] Does it simply means the removal of a row in this case?
tagged with: subset
type: AnsweredQuestion
upvote count: 0
score: -1
has answer: http://stackoverflow.com/a/48008509
has answer: http://stackoverflow.com/a/48007939
accepted answer: http://stackoverflow.com/a/48007939
type: Question
has comment: http://stackoverflow.com/comment/82983795
answer count: 2

dataframe
tags question: http://stackoverflow.com/q/47994917
tags question: http://stackoverflow.com/q/48000487
tags question: http://stackoverflow.com/q/47989173
tags question: http://stackoverflow.com/q/47980402
tags question: http://stackoverflow.com/q/47986166
tags question: http://stackoverflow.com/q/47883487
tags question: http://stackoverflow.com/q/47911863
tags question: http://stackoverflow.com/q/47890665
tags question: http://stackoverflow.com/q/47879262
tags question: http://stackoverflow.com/q/47966848
tags question: http://stackoverflow.com/q/47983093
tags question: http://stackoverflow.com/q/47980907
tags question: http://stackoverflow.com/q/47951784
tags question: http://stackoverflow.com/q/47906226
tags question: http://stackoverflow.com/q/47980917
tags question: http://stackoverflow.com/q/48010317
tags question: http://stackoverflow.com/q/47949386
tags question: http://stackoverflow.com/q/47895143
tags question: http://stackoverflow.com/q/47884034
tags question: http://stackoverflow.com/q/47930345
tags question: http://stackoverflow.com/q/47958859
tags question: http://stackoverflow.com/q/47898162
tags question: http://stackoverflow.com/q/47954929
tags question: http://stackoverflow.com/q/47926434
tags question: http://stackoverflow.com/q/47969852
tags question: http://stackoverflow.com/q/47963927
tags question: http://stackoverflow.com/q/47929077
tags question: http://stackoverflow.com/q/47997914
tags question: http://stackoverflow.com/q/47979810
tags question: http://stackoverflow.com/q/48005748
tags question: http://stackoverflow.com/q/47986702
tags question: http://stackoverflow.com/q/47890416
tags question: http://stackoverflow.com/q/47945912
tags question: http://stackoverflow.com/q/47914274
tags question: http://stackoverflow.com/q/47951839
tags question: http://stackoverflow.com/q/47963548
tags question: http://stackoverflow.com/q/47947281
tags question: http://stackoverflow.com/q/47908340
tags question: http://stackoverflow.com/q/47890756
tags question: http://stackoverflow.com/q/47878646
tags question: http://stackoverflow.com/q/47880671
tags question: http://stackoverflow.com/q/47994041
tags question: http://stackoverflow.com/q/47897003
tags question: http://stackoverflow.com/q/47985787
tags question: http://stackoverflow.com/q/47908050
tags question: http://stackoverflow.com/q/47978178
tags question: http://stackoverflow.com/q/47912611
tags question: http://stackoverflow.com/q/47881048
tags question: http://stackoverflow.com/q/48012197
tags question: http://stackoverflow.com/q/47934376
tags question: http://stackoverflow.com/q/47861085
tags question: http://stackoverflow.com/q/47932605
tags question: http://stackoverflow.com/q/47941113
tags question: http://stackoverflow.com/q/47879737
tags question: http://stackoverflow.com/q/47868802
tags question: http://stackoverflow.com/q/47962856
tags question: http://stackoverflow.com/q/47948967
tags question: http://stackoverflow.com/q/48000225
tags question: http://stackoverflow.com/q/47969149
tags question: http://stackoverflow.com/q/47993977
tags question: http://stackoverflow.com/q/47897166
tags question: http://stackoverflow.com/q/47993060
tags question: http://stackoverflow.com/q/48012916
tags question: http://stackoverflow.com/q/48005129
tags question: http://stackoverflow.com/q/47926966
tags question: http://stackoverflow.com/q/47901728
tags question: http://stackoverflow.com/q/47995848
tags question: http://stackoverflow.com/q/47878204
tags question: http://stackoverflow.com/q/47981341
tags question: http://stackoverflow.com/q/47914985
tags question: http://stackoverflow.com/q/48011404
tags question: http://stackoverflow.com/q/47911861
tags question: http://stackoverflow.com/q/47926045
tags question: http://stackoverflow.com/q/47978649
tags question: http://stackoverflow.com/q/47916288
tags question: http://stackoverflow.com/q/47887365
tag name: dataframe
tags question: http://stackoverflow.com/q/48000347
tags question: http://stackoverflow.com/q/47966081
tags question: http://stackoverflow.com/q/47942122

python
tags question: http://stackoverflow.com/q/47916196
tags question: http://stackoverflow.com/q/47959726
tags question: http://stackoverflow.com/q/47863640
tags question: http://stackoverflow.com/q/47972499
tags question: http://stackoverflow.com/q/47907620
tags question: http://stackoverflow.com/q/47948249
tags question: http://stackoverflow.com/q/47858960
tags question: http://stackoverflow.com/q/48000143
tags question: http://stackoverflow.com/q/47869308
tags question: http://stackoverflow.com/q/47863085
tags question: http://stackoverflow.com/q/47988877
tags question: http://stackoverflow.com/q/47938133
tags question: http://stackoverflow.com/q/47986269
tags question: http://stackoverflow.com/q/47944641
tags question: http://stackoverflow.com/q/47954552
tags question: http://stackoverflow.com/q/47895434
tags question: http://stackoverflow.com/q/47921144
tags question: http://stackoverflow.com/q/48012761
tags question: http://stackoverflow.com/q/47901580
tags question: http://stackoverflow.com/q/47856996
tags question: http://stackoverflow.com/q/47970758
tags question: http://stackoverflow.com/q/47996516
tags question: http://stackoverflow.com/q/47915951
tags question: http://stackoverflow.com/q/47871352
tags question: http://stackoverflow.com/q/47879598
tags question: http://stackoverflow.com/q/47880657
tags question: http://stackoverflow.com/q/47997953
tags question: http://stackoverflow.com/q/47883029
tags question: http://stackoverflow.com/q/47955785
tags question: http://stackoverflow.com/q/47989131
tags question: http://stackoverflow.com/q/47945540
tags question: http://stackoverflow.com/q/47895059
tags question: http://stackoverflow.com/q/47972282
tags question: http://stackoverflow.com/q/47860271
tags question: http://stackoverflow.com/q/47975155
tags question: http://stackoverflow.com/q/47903850
tags question: http://stackoverflow.com/q/47957520
tags question: http://stackoverflow.com/q/47970238
tags question: http://stackoverflow.com/q/47876879
tags question: http://stackoverflow.com/q/48013449
tags question: http://stackoverflow.com/q/47946251
tags question: http://stackoverflow.com/q/47939588
tags question: http://stackoverflow.com/q/47908281
tags question: http://stackoverflow.com/q/47966717
tags question: http://stackoverflow.com/q/47945972
tags question: http://stackoverflow.com/q/47928838
tags question: http://stackoverflow.com/q/47903478
tags question: http://stackoverflow.com/q/47932190
tags question: http://stackoverflow.com/q/47952601
tags question: http://stackoverflow.com/q/47866353
tags question: http://stackoverflow.com/q/47928440
tags question: http://stackoverflow.com/q/47985835
tags question: http://stackoverflow.com/q/47927475
tags question: http://stackoverflow.com/q/47898711
tags question: http://stackoverflow.com/q/47871390
tags question: http://stackoverflow.com/q/47905464
tags question: http://stackoverflow.com/q/47958956
tags question: http://stackoverflow.com/q/47899596
tags question: http://stackoverflow.com/q/47989140
tags question: http://stackoverflow.com/q/47970964
tags question: http://stackoverflow.com/q/47966982
tags question: http://stackoverflow.com/q/47923755
tags question: http://stackoverflow.com/q/48013656
tags question: http://stackoverflow.com/q/47864768
tags question: http://stackoverflow.com/q/47954059
tags question: http://stackoverflow.com/q/47891813
tags question: http://stackoverflow.com/q/47945139
tags question: http://stackoverflow.com/q/47924400
tags question: http://stackoverflow.com/q/47989609
tags question: http://stackoverflow.com/q/47976768
tags question: http://stackoverflow.com/q/47879986
tags question: http://stackoverflow.com/q/47952756
tags question: http://stackoverflow.com/q/47960566
tags question: http://stackoverflow.com/q/47888396
tags question: http://stackoverflow.com/q/47953069
tags question: http://stackoverflow.com/q/47936144
tags question: http://stackoverflow.com/q/47935339
tags question: http://stackoverflow.com/q/47906801
tags question: http://stackoverflow.com/q/47959639
tags question: http://stackoverflow.com/q/47973980

http://stackoverflow.com/a/71970755
score: 0
answers question: http://stackoverflow.com/q/47944089
type: Answer
has body: If your array is an array of form width, height and filled with tuples, this code converts it to an array of arrays, which can be read by Image.fromarray. import numpy as np from PIL import Image arr = np.array( [ [(178, 158, 165), (185, 196, 191), (207, 222, 226)], [(202, 184, 176), (68, 58, 66), (69, 57, 60)], [(194, 158, 179), (109, 119, 116), (70, 64, 57)] ] ) # a small example array shape = arr.shape new_arr = np.empty((shape[0], shape[1], 3), dtype=np.uint8) for y, row in enumerate(arr): for x, color in enumerate(row): new_arr[y, x] = np.array(color) Image.fromarray(new_arr, "RGB").show() This is probably slow for larger images compared to the other answer, but that one didn't work for me.

http://stackoverflow.com/a/47948346
score: 6
answers question: http://stackoverflow.com/q/47948131
has body: You can use itertools izip_longest (py2) or itertools zip longest (py3) too: import itertools list(map(list,itertools.izip_longest([], list1, fillvalue=list2[0]))) Returns: [[4, 1], [4, 2], [4, 3]]
has comment: http://stackoverflow.com/comment/82890168
has comment: http://stackoverflow.com/comment/82887555
upvote count: 6
type: Answer
downvote count: 0

http://stackoverflow.com/comment/82894866
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47958919
score: 1
has text: I think you need add `m1 = df.index.get_level_values(1) == 'Impresiones two' df.index = np.where(m1, 'Impresiones two', df.index.get_level_values(0))`, but I am on phone only, so untested.

http://stackoverflow.com/q/47876205
type: Question
has comment: http://stackoverflow.com/comment/82717941
has title: For loop is overwriting dictionary values in list
tagged with: python
tagged with: dictionary
linked to: http://stackoverflow.com/q/12753099
has comment: http://stackoverflow.com/comment/82718034
answer count: 3
has comment: http://stackoverflow.com/comment/82718109
upvote count: 7
has answer: http://stackoverflow.com/a/47876349
downvote count: 1
duplicate of: http://stackoverflow.com/q/12753099
has answer: http://stackoverflow.com/a/47876366
tagged with: for-loop
type: UnansweredQuestion
score: 6
has body: Issue I've made a for loop reading the contents of a list however when assigning two values to a dictionary and then appending that output to a list, the next value overwrites everything in the list Desired outcome I want to append multiple dictionaries to a list so when I run a for loop and print everything related to 'ip' it will print all the values associated with the dictionary value 'ip'. Code device = { 'ip': '', 'mac': '', 'username': 'admin', 'password': [], 'device type': '', } listofdevices = [] def begin(): file = open("outputfromterminal") contents = file.read() contents = contents.split(',')[1:] for x in contents: # do some text stripping x = x.split(' ') device['ip']=x[0] device['mac']=x[1] listofdevices.append(device) Sample code the 1st index of contents is: x[0] = '10.10.10.1' x[1] = 'aa:bb:cc:dd' The 2nd index of contents is: x[0] = '20.20.20.1' x[1] = 'qq:ww:ee:ee:rr' What actually happens listofdevices[0] 'ip': 20.20.20.1, 'mac': 'qq:ww:ee:ee:rr' listofdevices[1] 'ip': 20.20.20.1, 'mac': 'qq:ww:ee:ee:rr'
has comment: http://stackoverflow.com/comment/82718104
has answer: http://stackoverflow.com/a/47876376
has comment: http://stackoverflow.com/comment/82717839
favorite count: 0

http://stackoverflow.com/q/48004509
has comment: http://stackoverflow.com/comment/82977200
has comment: http://stackoverflow.com/comment/82977101
answer count: 1
has answer: http://stackoverflow.com/a/48005005
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has title: Extracting contact information from html
tagged with: regex
has comment: http://stackoverflow.com/comment/82977162
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82977207
has body: I want to extract the contact numbers from a portion of html . and I used import codecs from bs4 import BeautifulSoup page = codecs.open('D:/Edureka/Sample Addresses!.html', 'r+') page1 =page.read() soup = BeautifulSoup(page1, 'html.parser') soup.prettify() for script in soup(["script", "style"]): script.extract() text = soup.get_text() lines = (line.strip() for line in text.splitlines()) chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) text = '\n'.join(chunk for chunk in chunks if chunk) contacts = re.findall("\d{3} \d{3}-\d{4}", text) for j in contacts: print(j) This is not giving me desired answer. If I use contacts = re.findall("\d{3} \d{3}", text) It's giving me first six digits. whenever I am giving -\d{4} it's not working. Please help. I need 10 digit contact numbers. Sample of text Ivor DelgadoAp #310-1678 Ut Av.Santa Barbara MT 88317(689) 721-5145 Pascale PattonP.O. Box 399 4275 Amet StreetWest Allis NC 36734(676) 334-2174 Nasim StrongAp #630-3889 Nulla. StreetWatervliet Oklahoma 70863(437) 994-5270 Keaton UnderwoodAp #636-8082 Arcu AvenueThiensville Maryland 19587(564) 908-6970 Keegan BlairAp #761-2515 Egestas. Rd.Manitowoc TN 07528(577) 333-6244 Tamara Howe3415 Lobortis. AvenueRocky Mount WA 48580(655) 840-6139 '''
accepted answer: http://stackoverflow.com/a/48005005
type: Question
has comment: http://stackoverflow.com/comment/82977323
has comment: http://stackoverflow.com/comment/82977981
has comment: http://stackoverflow.com/comment/82977634
score: 0

http://stackoverflow.com/comment/82855657
type: QuestionComment
has text: @Nae well thats true right now, but i want to do it anyway, both to learn new things and also to make it cleaner to the user
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47942973

http://stackoverflow.com/q/47935339
score: 1
has title: How to replace camelCasing in all files in a folder using Python or c#?
upvote count: 1
has body: I have a folder that has a mix and match of camelCase and non camel case filenames. I have used this in Python to remove underscores and was hoping I could easily tweak it to replace 'camelCaseExample' with 'camel Case Example': folder = r"C:/....." import os pathiter = (os.path.join(root, filename) for root, _, filenames in os.walk(folder) for filename in filenames ) for path in pathiter: newname = path.replace('_', ' ') if newname != path: os.rename(path,newname) Could anyone help me edit this to get it working for regex? I have tried this with no luck: newname = path.replace('%[A-Z][a-z]%', ' ') I would also be able to use a c# solution if that would be easier
type: Question
tagged with: c#
has comment: http://stackoverflow.com/comment/82840194
accepted answer: http://stackoverflow.com/a/47935389
has comment: http://stackoverflow.com/comment/82840157
tagged with: camelcasing
has comment: http://stackoverflow.com/comment/82840146
has comment: http://stackoverflow.com/comment/82840371
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82840319
tagged with: python
has answer: http://stackoverflow.com/a/47935389
type: AnsweredQuestion

http://stackoverflow.com/comment/82712508
has text: Give some example code to make clear what's going on. If the wrapper handles all arguments, it doesn't matter whether the main ignores the ones it can't handle. In the linked answer the first parser uses partial, and passes the extras to the second. You might try a dummy parser that captures `arg3/4` and passes the rest as its `extras`.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47866170

http://stackoverflow.com/a/49349791
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/47985835
downvote count: 0
score: 3
has body: I also had the same sort of problem while running tensorboard from cmd, if your tensorflow installation was done using conda, then you can launch tensorboard from the Anaconda prompt as follows: activate tensorflow tensorboard --logdir=path to your log files

http://stackoverflow.com/a/47903922
has comment: http://stackoverflow.com/comment/82807129
has comment: http://stackoverflow.com/comment/82778535
has comment: http://stackoverflow.com/comment/82778810
has comment: http://stackoverflow.com/comment/82775192
has comment: http://stackoverflow.com/comment/131451025
upvote count: 5
has comment: http://stackoverflow.com/comment/82807533
has comment: http://stackoverflow.com/comment/82807915
has comment: http://stackoverflow.com/comment/82774573
score: 5
has comment: http://stackoverflow.com/comment/82808068
has body: You can try to use list_route for example: from rest_framework.response import Response from rest_framework.decorators import list_route class NotificationListAPIView(ReadOnlyModelViewSet): #YOUR PARAMS HERE @list_route() def read_all(self, request): qs = Notification.objects.filter(is_read=False) qs.update(is_read=True) serializer = self.get_serializer(qs, many=True) return Response(serializer.data) the api is available by ^YOUCURRENTURL/read_all/$ more details marking-extra-actions-for-routing NOTE! since DRF 3.10 @list_route() decorator was removed, you should use @action(detail=False) instead, I used @action(detail=False, methods=['PATCH']) to bulk patch, for example Thank you @PolYarBear
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47902913
has comment: http://stackoverflow.com/comment/82778439
has comment: http://stackoverflow.com/comment/82807216
has comment: http://stackoverflow.com/comment/82775514
has comment: http://stackoverflow.com/comment/82807751
has comment: http://stackoverflow.com/comment/82774766
type: Answer
answers question: http://stackoverflow.com/q/47902913
has comment: http://stackoverflow.com/comment/82774905
has comment: http://stackoverflow.com/comment/82791490
has comment: http://stackoverflow.com/comment/82806565
has comment: http://stackoverflow.com/comment/82774688

http://stackoverflow.com/comment/82975315
type: Comment
score: 0
has text: is that from within docker?
type: QuestionComment
comment on: http://stackoverflow.com/q/47989418

permutation
tags question: http://stackoverflow.com/q/47888396
tag name: permutation
type: Tag
tags question: http://stackoverflow.com/q/47954890
tags question: http://stackoverflow.com/q/47905076
tags question: http://stackoverflow.com/q/47993740
tags question: http://stackoverflow.com/q/47952987

http://stackoverflow.com/a/47881467
upvote count: 0
has body: Try split() instead. &gt;&gt;&gt; str = 'MOST INTERESTED IN NUT BUTTERS' &gt;&gt;&gt; str.split(' ', 3) # 3 tells the number of splits it should do. ['MOST', 'INTERESTED', 'IN', 'NUT BUTTERS']
type: Answer
answers question: http://stackoverflow.com/q/47881392
downvote count: 1
score: -1

http://stackoverflow.com/q/47864091
has title: Good practice with python conditional import
has comment: http://stackoverflow.com/comment/82693090
has comment: http://stackoverflow.com/comment/82693372
score: 0
has comment: http://stackoverflow.com/comment/82693229
linked to: http://stackoverflow.com/q/2386714
type: UnansweredQuestion
has body: I have a common utils named utils.py, which is shared across different target (dataset, for example). So, I have to define some target specific attributes, like function and variables. I have try to do something like this def setup(name): if ...: var = val import module elif ...: do something But from module import * is prohibited within function. Is there any good practice or any elegant way to do this?
tagged with: python
answer count: 0
type: Question

http://stackoverflow.com/q/47882363
has answer: http://stackoverflow.com/a/47882542
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/14714181
score: 19
type: Question
has comment: http://stackoverflow.com/comment/82730467
has answer: http://stackoverflow.com/a/47882388
accepted answer: http://stackoverflow.com/a/47882388
has comment: http://stackoverflow.com/comment/82730479
possible better answer: http://stackoverflow.com/a/47882542
has comment: http://stackoverflow.com/comment/82730531
upvote count: 19
has body: How can I check if all values under col1 satisfy a condition such as &gt; 2? import pandas as pd d = [ {'col1': 3, 'col2': 'wasteful'}, {'col1': 0, 'col2': 'hardly'}, ] df = pd.DataFrame(d) I could go if all(col1 &gt; 2 for i, col1, col2 in df.itertuples()): #do stuff but is there a more readable, faster and/or has less memory footprint way?
answer count: 3
tagged with: pandas
downvote count: 0
has title: How to check whether all values in a column satisfy a condition in Data Frame?
has answer: http://stackoverflow.com/a/71153786
favorite count: 0

http://stackoverflow.com/q/47863645
score: 2
upvote count: 2
type: UnansweredQuestion
tagged with: google-cloud-bigtable
has title: Bigtable bulk insert
type: Question
has answer: http://stackoverflow.com/a/54059447
downvote count: 0
favorite count: 0
answer count: 3
has body: Can I perform bulk insert in Bigtable using python. I am using below method to insert which is very slow. I have millions of rows to insert. def row(self, row_key, filter_=None, append=False): """Factory to create a row associated with this table. Ref Document: https://googlecloudplatform.github.io/google-cloud-python/latest/bigtable/table.html Thanks.
has answer: http://stackoverflow.com/a/47876375
tagged with: python
has answer: http://stackoverflow.com/a/50989589

http://stackoverflow.com/comment/82904967
comment on: http://stackoverflow.com/q/47967584
type: Comment
has text: Perfect, thank you so much!
type: QuestionComment
score: 0

http://stackoverflow.com/q/47867995
tagged with: python
has comment: http://stackoverflow.com/comment/82700915
has answer: http://stackoverflow.com/a/47868159
has comment: http://stackoverflow.com/comment/82701052
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/47868745
has body: I am using AWS, boto3 and Pycharm to write a very simple program on python that compare one faces from one face image to another face from another face image. I written the following simple source code: import boto3 s3 = boto3.resource('s3', aws_access_key_id = "xxx", aws_secret_access_key = "yyy") BUCKET = "eyeglasses-images" KEY_SOURCE = "Foucault.jpg" KEY_TARGET = "Ricoeur.jpg" def compare_faces(bucket, key, bucket_target, key_target, threshold=80, region="eu-west-1"): rekognition = boto3.client("rekognition", region) response = rekognition.compare_faces( SourceImage={ "S3Object": { "Bucket": bucket, "Name": key, } }, TargetImage={ "S3Object": { "Bucket": bucket_target, "Name": key_target, } }, SimilarityThreshold=threshold, ) return response['SourceImageFace'], response['FaceMatches'] source_face, matches = compare_faces(BUCKET, KEY_SOURCE, BUCKET, KEY_TARGET) # the main source face print "Source Face ({Confidence}%)".format(**source_face) # one match for each target face for match in matches: print "Target Face ({Confidence}%)".format(**match['Face']) print " Similarity : {}%".format(match['Similarity']) However I get the following error: raise NoCredentialsError botocore.exceptions.NoCredentialsError: Unable to locate credentials (Obviously in the place of xxx and yyy I am using the real keys) What is the problem and how can I fix this?
has title: AWS - Does not recognise access key ID and secret access key
tagged with: boto3
tagged with: amazon-web-services
score: 0
answer count: 2
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/93416164
type: Comment
comment on: http://stackoverflow.com/a/52969689
type: AnswerComment
has text: And for Member Not Found, check [this](https://support.microsoft.com/en-gb/help/172108/howto-troubleshoot-member-not-found-0x80020003-error) out, maybe it helps.
score: 0

http://stackoverflow.com/q/47973024
has body: I'm implementing a DFS algorithm and I want to create a list of dictionaries. But I found that if I use [dict()] * n, I got unexpected result. I'm not sure what is the difference between "[dict()] * n" and a "for loop with .append(dict())". Any hint is appreciated. def DFS1(nums, level, target, dp): if level == len(nums): if target == 0: return 1 else: return 0 if target in dp[level]: return dp[level][target] cnt1 = DFS1(nums, level + 1, target + nums[level], dp) cnt2 = DFS1(nums, level + 1, target - nums[level], dp) dp[level][target] = cnt1 + cnt2 return cnt1 + cnt2 test code is: nums = [1,1,1,1,1] n = len(nums) target = -3 #dp = [dict()] * n #&lt;== This does not work as expected dp = [] for i in range(0, n): dp.append(dict()) resCnt = DFS1(nums, 0, target, dp) print(resCnt)
duplicate of: http://stackoverflow.com/q/240178
has comment: http://stackoverflow.com/comment/82915657
score: 0
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/240178
has answer: http://stackoverflow.com/a/47973049
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has title: What is the difference between "[dict()] * n" and a "for loop with .append(dict())"?
accepted answer: http://stackoverflow.com/a/47973049
upvote count: 1
tagged with: collections
downvote count: 1
type: Question

http://stackoverflow.com/comment/82923498
type: QuestionComment
comment on: http://stackoverflow.com/q/47975339
has text: @COLDSPEED sorry，I should modify my question. I just read some else's code using a[...] notation, the a is a numpy's ndarray.
score: 0
type: Comment

http://stackoverflow.com/comment/82847156
has text: The answer lies in using regex and using it to sort.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47938945

http://stackoverflow.com/q/47856273
upvote count: 2
tagged with: python-2.7
answer count: 1
has comment: http://stackoverflow.com/comment/82679763
favorite count: 0
tagged with: beautifulsoup
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/82676750
has comment: http://stackoverflow.com/comment/82679667
type: UnansweredQuestion
score: -3
has comment: http://stackoverflow.com/comment/82678631
has body: Suppose I am scraping a reviews from the url https://www.tripadvisor.com/Hotel_Review-g562819-d289642-Reviews-Hotel_Caserio-Playa_del_Ingles_Maspalomas_Gran_Canaria_Canary_Islands.html It contents no of pages which contains the reviews which I want to scrape. So how can I scrape the reviews of all the next pages. I used the below code but still shows only the reviews in first page only! from bs4 import BeautifulSoup import requests URL_BASE = "https://www.tripadvisor.com/Hotel_Review-g562819-d289642-Reviews-Hotel_Caserio-Playa_del_Ingles_Maspalomas_Gran_Canaria_Canary_Islands.html" MAX_PAGES = 30 counter = 0 for i in range(1, MAX_PAGES): if i &gt; 1: url = "%spage/%d/" % (URL_BASE, i) else: url = URL_BASE req = requests.get(url) statusCode = req.status_code if statusCode == 200: html = BeautifulSoup(req.text, "html.parser") resultsoup = html.find_all('P', {'class': 'partial_entry'}) else: break for review in resultsoup: review_list = review.get_text() print(review_list)
type: Question
has answer: http://stackoverflow.com/a/47858268
has title: Scraping reviews from tripadvisor
downvote count: 5

http://stackoverflow.com/comment/82713470
type: Comment
comment on: http://stackoverflow.com/q/47873982
has text: Could you please create a [mcve] for your problem? This will make it much more likely that you'll receive quality help.
score: 0
type: QuestionComment

http://stackoverflow.com/a/48005487
has body: One fast way of doing to is by divide and merge i.e one = df[df['ID'].isin(links['ID1'])].copy() two = df[df['ID'].isin(links['ID2'])].copy() two['NEW_ID'] = two['ID'].map(links.set_index('ID2')['ID1']) one.merge(two,left_on='ID',right_on='NEW_ID',suffixes=('1', '2')) ID1 LANG1 TEXT1 ID2 LANG2 TEXT2 NEW_ID 0 123 eng I want you to meet my parents. 567 kor 부모님을 만나길 원해. 123 1 2352 jpn 私はあなたの側にいます。 456 eng I'm on your side. 2352 Mapping didn't work due to the presence of duplicate IDs, So you can use dual merge i.e one.merge(two.merge(links,left_on='ID',right_on='ID2'),left_on='ID',right_on='ID1',suffixes=('1', '2'))) ID1 LANG1 TEXT1 ID2 LANG2 TEXT2 \ 0 123 eng I want you to meet my parents. 567 kor 부모님을 만나길 원해. 1 2352 jpn 私はあなたの側にいます。 456 eng I'm on your side. ID1 ID2 0 123 567 1 2352 456 Based on the actual data you can simply cross merge same dataframe since you have the same column names i.e sec = sent_details.merge(links) sec.merge(sec, left_on=['Sentence id','Translation id'],right_on=['Translation id','Sentence id'], suffixes=(1,2))
type: Answer
has comment: http://stackoverflow.com/comment/83117368
has comment: http://stackoverflow.com/comment/83117950
score: 3
has comment: http://stackoverflow.com/comment/83118167
upvote count: 3
has comment: http://stackoverflow.com/comment/83117178
accepted answer of: http://stackoverflow.com/q/48005341
has comment: http://stackoverflow.com/comment/83117313
answers question: http://stackoverflow.com/q/48005341
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83003135
downvote count: 0

http://stackoverflow.com/q/48007236
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48007324
tagged with: list
upvote count: 3
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/48007371
has title: Computing mean of all tuple values where 1st number is similar
has answer: http://stackoverflow.com/a/48007371
tagged with: mean
has answer: http://stackoverflow.com/a/48007324
favorite count: 0
has body: Consider list of tuples [(7751, 0.9407466053962708), (6631, 0.03942129), (7751, 0.1235432)] how to compute mean of all tuple values in pythonic way where 1st number is similar? for example the answer has to be [(7751, 0.532144902698135), (6631, 0.03942129)]
tagged with: tuples
answer count: 3
has answer: http://stackoverflow.com/a/48007394

pyopengl
tags question: http://stackoverflow.com/q/47950801
tag name: pyopengl
tags question: http://stackoverflow.com/q/47913978
tags question: http://stackoverflow.com/q/47896860
type: Tag
tags question: http://stackoverflow.com/q/47965081

http://stackoverflow.com/comment/84448812
comment on: http://stackoverflow.com/q/47994825
type: Comment
has text: I got rid of this error after creating a new set of Access keys
score: 0
type: QuestionComment

http://stackoverflow.com/q/47973341
has title: Python YouTube Page Token Issue
score: 1
type: Question
downvote count: 0
favorite count: 0
has body: I'm running into an intermittent issue when I run the code below. I'm trying to collect all the page_tokens in the ajax calls made by pressing the "load more" button if it exists. Basically, I'm trying to get all the page tokens from a YouTube Channel. Sometimes it will retrieve the tokens, and other times it doesn't. My best guess is either I made a mistake in my "find_embedded_page_token" function or that I need some sort of delay/sleep inserted somewhere. Below is the full code: import requests import pprint import urllib.parse import lxml def find_XSRF_token(html, key, num_chars=2): pos_begin = html.find(key) + len(key) + num_chars pos_end = html.find('"', pos_begin) return html[pos_begin: pos_end] def find_page_token(html, key, num_chars=2): pos_begin = html.find(key) + len(key) + num_chars pos_end = html.find('&amp;', pos_begin) return html[pos_begin: pos_end] def find_embedded_page_token(html, key, num_chars=2): pos_begin = html.find(key) + len(key) + num_chars pos_end = html.find('&amp;', pos_begin) excess_str = html[pos_begin: pos_end] sep = '\\' rest = excess_str.split(sep,1)[0] return rest sxeVid = 'https://www.youtube.com/user/sxephil/videos' ajaxStr = 'https://www.youtube.com/browse_ajax?action_continuation=1&amp;amp;continuation=' s = requests.Session() r = s.get(sxeVid) html = r.text session_token = find_XSRF_token(html, 'XSRF_TOKEN', 4) page_token = find_page_token(html, ';continuation=', 0) print(page_token) s = requests.Session() r = s.get(ajaxStr+page_token) ajxHtml = r.text ajax_page_token = find_embedded_page_token(ajxHtml, ';continuation=', 0) while page_token: ajxBtn = ajxHtml.find('data-uix-load-more-href=') if ajxBtn != -1: s = requests.Session() r = s.get(ajaxStr+ajax_page_token) ajxHtml = r.text ajax_page_token = find_embedded_page_token(ajxHtml, ';continuation=', 0) print(ajax_page_token) else: break This is what's returning randomly that is unexpected. It's pulling not just the token, but also the HTML after the desired cut off. 4qmFsgJA…
tagged with: python
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: web-scraping
tagged with: python-requests

http://stackoverflow.com/a/47950285
upvote count: 1
answers question: http://stackoverflow.com/q/47950259
has body: To print text with a space instead of a newline at the end you can use the end parameter. print("text", end=" ") in python2 this can be achieved with a trailing comma: print "text", for Example, c = 5 for i in range(10): print c, c += 1
score: -1
type: Answer
has comment: http://stackoverflow.com/comment/82870190
has comment: http://stackoverflow.com/comment/82870130
downvote count: 2

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

http://stackoverflow.com/a/62038950
has comment: http://stackoverflow.com/comment/116817687
downvote count: 0
upvote count: 8
has comment: http://stackoverflow.com/comment/115871375
has comment: http://stackoverflow.com/comment/117684533
type: Answer
has comment: http://stackoverflow.com/comment/117679955
score: 8
has body: The above answer references textacy, this is all achievable with Spacy directly with the Matcher, no need for the wrapper library. import spacy from spacy.matcher import Matcher nlp = spacy.load('en_core_web_sm') # download model first sentence = 'The author was staring pensively as she wrote' pattern=[{'POS': 'VERB', 'OP': '?'}, {'POS': 'ADV', 'OP': '*'}, {'OP': '*'}, # additional wildcard - match any text in between {'POS': 'VERB', 'OP': '+'}] # instantiate a Matcher instance matcher = Matcher(nlp.vocab) # Add pattern to matcher matcher.add("verb-phrases", None, pattern) doc = nlp(sentence) # call the matcher to find matches matches = matcher(doc) N.b. this returns a list of tuples containing the match ID and the start, end index for each match, e.g.: [(15658055046270554203, 0, 4), (15658055046270554203, 1, 4), (15658055046270554203, 2, 4), (15658055046270554203, 3, 4), (15658055046270554203, 0, 8), (15658055046270554203, 1, 8), (15658055046270554203, 2, 8), (15658055046270554203, 3, 8), (15658055046270554203, 4, 8), (15658055046270554203, 5, 8), (15658055046270554203, 6, 8), (15658055046270554203, 7, 8)] You can turn these matches into spans using the indexes. spans = [doc[start:end] for _, start, end in matches] # output """ The author was staring author was staring was staring staring The author was staring pensively as she wrote author was staring pensively as she wrote was staring pensively as she wrote staring pensively as she wrote pensively as she wrote as she wrote she wrote wrote """ Note, the I added the additional {'OP': '*'}, to the pattern which serves as a wildcard when note specified with a specific POS/DEP (i.e. it will match any text). This is useful here as the question is about verb phrases - the format VERB, ADV, VERB is an unusual structure (try to think of some example sentences), however VERB, ADV, [other text], VERB is likely (as given in the example sentence 'The author was staring pensively as she wrote'). Optionally, you can refine the …
has comment: http://stackoverflow.com/comment/115896236
answers question: http://stackoverflow.com/q/47856247

http://stackoverflow.com/comment/82798986
has text: My solution is just some code I am trying. The question is how this should be done properly?
comment on: http://stackoverflow.com/q/47915356
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/47939713
score: 5
has body: I am trying below commands python -c 'import sample; sample.Functionname()' python -c 'import sample; sample.printFxn("helloWorld")' Both of these work well but when I pass a variable as an argument, I get the following error. File "&lt;string&gt;", line 1 import sample; sample.printFxn($filename) SyntaxError: invalid syntax What is the proper way to pass a variable as an argument to a python function from bash?
accepted answer: http://stackoverflow.com/a/47943114
has comment: http://stackoverflow.com/comment/82849705
answer count: 2
tagged with: bash
has comment: http://stackoverflow.com/comment/82848639
tagged with: shell
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/47943114
upvote count: 6
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82848597
possible better answer: http://stackoverflow.com/a/47939777
has answer: http://stackoverflow.com/a/47939777
downvote count: 1
has title: passing an argument to a python function from bash
type: Question

http://stackoverflow.com/q/47877011
score: 0
tagged with: http://stackoverflow.com/tag/html
has body: I have very simple code - Im looking for better solution my case: I have: - 2 input text + submit button Input forms always returns text as string. Do you know better solution (and shorter) to pass only numeric values (and for non numeric - show "error") except gather all letters in list and check statement if text from input is not in list with letters? from flask import Flask, render_template, request app = Flask(__name__) @app.route("/licz/", methods=['GET']) def search(): licz1 = request.args.get('liczba1') licz2 = request.args.get('liczba2') notnumbers = ['q','w','e','r','t','y'] if licz1 and licz2 != None: if licz1 not in notnumbers: sumaliczenia = int(licz1) + int(licz2) return render_template('liczenie.html', suma=sumaliczenia) else: sumaliczenia = "error" return render_template('liczenie.html', suma=sumaliczenia) else: return render_template('liczenie.html') app.run(debug=True) Template code (from comment below): Formularz Result is {{ suma }} Send
has answer: http://stackoverflow.com/a/47877316
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82720036
tagged with: python
has title: Python/FLASK - html form return strings. How check if it containt number?
has comment: http://stackoverflow.com/comment/82720106
has comment: http://stackoverflow.com/comment/82720254
tagged with: forms
type: Question
tagged with: isnumeric
answer count: 1
has comment: http://stackoverflow.com/comment/82720092
tagged with: flask

http://stackoverflow.com/comment/82925653
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47978275
has text: Well its dimensions are 962*800 vertically then horizontaly
type: Comment

http://stackoverflow.com/comment/82937445
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47984171
has text: I get this error message though: TypeError: 'NoneType' object is not callable when executing your code.

http://stackoverflow.com/q/47916065
has body: Have a dataframe that represents a network with directed edges between nodes A, B and C. I want to sum the flows between nodes to measure the strength of connections between nodes. Below is the df I have.. To From Flow A A 1 A B 4 A C 2 B A 5 B B 2 B C 6 C A 3 C B 5 C C 2 And the below is what I'd like to get to. A A 1 B B 2 C C 2 A B 9 A C 5 B C 11 What's the best way to do this?
has title: Summing edges in pandas
tagged with: pandas
favorite count: 0
has answer: http://stackoverflow.com/a/47916156
has answer: http://stackoverflow.com/a/47916429
type: UnansweredQuestion
tagged with: python
score: 1
upvote count: 1
type: Question
answer count: 2
downvote count: 0

http://stackoverflow.com/q/47991802
answer count: 1
tagged with: pandas
has body: I was looking at the code on this page: https://ahmedbesbes.com/how-to-mine-newsfeed-data-and-extract-interactive-insights-in-python.html news = pd.DataFrame(reduce(lambda x,y: x+y ,map(lambda r: r['articles'], responses))) Can someone explain this line ? What is the map / reduce operation doing here ?
has title: How is map reduce being used to create pandas data frame?
has answer: http://stackoverflow.com/a/47991926
favorite count: 0
tagged with: python
tagged with: lambda
score: 4
type: AnsweredQuestion
upvote count: 5
accepted answer: http://stackoverflow.com/a/47991926
downvote count: 1
type: Question

http://stackoverflow.com/q/48009792
type: UnansweredQuestion
tagged with: multithreading
tagged with: python
has comment: http://stackoverflow.com/comment/82988875
has body: My code (I don't know if I need to show the entire code or not for this problem, sorry if I don't): class GridWithWeights(SquareGrid): def __init__(self, width, height): self.weights = {} def cost(self, from_node, to_node): x = from_node[0] y = from_node[1] results = {(x-1, y+1):14, (x, y+1):10, (x+1, y+1):14, (x-1, y):10, (x+1,y):10, (x-1, y-1):14, (x, y-1):10, (x+1, y-1):14 } try: return results[to_node] except Exception: return 0 def in_bounds(self, id): (x, y) = id return 0 &lt;= x &lt; self.width and 0 &lt;= y &lt; self.height def passable(self, id): return id not in self.walls def neighbors(self, id): (x, y) = id results = [(x-1, y+1), (x, y+1), (x+1, y+1), (x-1, y), (x+1,y), (x-1, y-1), (x, y-1), (x+1, y-1) ] if (x + y) % 2 == 0: results.reverse() # aesthetics results = filter(self.in_bounds, results) results = filter(self.passable, results) return results def reconstruct_path(came_from, start, goal): current = goal path = [] while current != start: path.append(current) current = came_from[current] path.append(start) # optional path.reverse() # optional return path def heuristic(a, b): (x1, y1) = a (x2, y2) = b return abs(x1 - x2) + abs(y1 - y2) def a_star_search(graph, start, goal): frontier = PriorityQueue() frontier.put(start, 0) came_from = {} cost_so_far = {} came_from[start] = None cost_so_far[start] = 0 while not frontier.empty(): current = frontier.get() if current == goal: break # The thing I want to multiprocess for next in graph.neighbors(current) new_cost = cost_so_far[current] + graph.cost(current, next) if next not in cost_so_far or new_cost &lt; cost_so_far[next]: cost_so_far[next] = new_cost priority = new_cost + heuristic(goal, next) frontier.put(next, priority) came_from[next] = current return came_from, cost_so_far diagram4 = GridWithWeights(360, 240) diagram4.walls = [(2,5),(1, 7), (1, 8), (2, 7), (2, 8), (3, 7), (3, 8)] # Obstructions start, goal = (141, 42), (54, 190) came_from, _ = a_star_search(diagram4, start, goal) print(reconstruct_…
type: Question
has title: Multithreading with nested functions with dependant variables
answer count: 0
has comment: http://stackoverflow.com/comment/82989330
score: 0

http://stackoverflow.com/q/47938345
accepted answer: http://stackoverflow.com/a/47938593
has comment: http://stackoverflow.com/comment/82845773
type: AnsweredQuestion
has body: I have several regexps like this, Data['SUMMARY']=Data['SUMMARY'].str.replace(r'([^\w])',' ') Data['SUMMARY']=Data['SUMMARY'].str.replace(r'x{2,}',' ') Data['SUMMARY']=Data['SUMMARY'].str.replace(r'_+',' ') Data['SUMMARY']=Data['SUMMARY'].str.replace(r'\d+',' ') Data['SUMMARY']=Data['SUMMARY'].str.replace(r'\s{2,}',' ') i want to replace all punctuations, XXXXXXXX,all digits, all non alphanumeric to the empty string ''. How can I combine it all into one replacing regexp?
favorite count: 0
type: Question
tagged with: pandas
tagged with: python
tagged with: regex
possible better answer: http://stackoverflow.com/a/47938626
has comment: http://stackoverflow.com/comment/82846091
has answer: http://stackoverflow.com/a/47938593
has answer: http://stackoverflow.com/a/47938626
score: 0
answer count: 2
tagged with: data-cleaning
upvote count: 1
has title: Data cleaning with pandas using regular expressions
downvote count: 1

http://stackoverflow.com/comment/82758803
has text: "you can't really" is ambigous. Either you can or you can't. And you can, but you'll not be able to get the expected behaviour when overriding special methods.
comment on: http://stackoverflow.com/a/47895864
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/a/47970241
downvote count: 3
answers question: http://stackoverflow.com/q/47969850
upvote count: 0
has comment: http://stackoverflow.com/comment/82909901
type: Answer
has body: Its a bit tricky. You have to use a form to send the data to a PHP-Web Server. Then use shell_exec($command) to run your Python Script with parameters. Your PHP Script should look like this: &lt;?php $input = $_GET['mySelect']; //sanitize and check the input $cmd = escapeshellcmd('/usr/custom/test.py -p ' . $input); //escape the command $output = shell_exec($cmd); //run the script echo $output; ?&gt; It's very important to sanitize and check your user input otherwise an attacker could easily get acces to your server. See more: http://php.net/manual/en/function.shell-exec.php Notes from php.net This function can return NULL both when an error occurs or the program produces >no output. It is not possible to detect execution failures using this function. >exec() should be used when access to the program exit code is required." This function is disabled when PHP is running in safe mode.
has comment: http://stackoverflow.com/comment/82909873
score: -3

http://stackoverflow.com/comment/82933084
type: AnswerComment
has text: @COLDSPEED hm it doesnt work, but gives me some more columns ("index", "indicator" and "level_0" with different values). think it would be easier to have just another column indicating from which dataframe the max_value is extracted (which the indicator column from your code is not doing, right?)
type: Comment
comment on: http://stackoverflow.com/a/47976981
score: 0

http://stackoverflow.com/a/48222705
accepted answer of: http://stackoverflow.com/q/48003741
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48003741
has body: By adding a rules to the spec, i could overcome this issue. apiVersion: extensions/v1beta1 kind: Ingress metadata: name: controller-ingress namespace: ns-app spec: backend: serviceName: controller servicePort: 5001 rules: - host: foo.bar.com http: paths: - path: /* backend: serviceName: controller servicePort: 5001
type: Answer
score: 0

http://stackoverflow.com/a/47969543
score: 1
accepted answer of: http://stackoverflow.com/q/47965783
answers question: http://stackoverflow.com/q/47965783
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: You must use reshape to fix matrix dimensions.My solution is like that theta = theta - (alpha / m) * np.dot(X.T.reshape(2, 97), np.dot(X, theta).flatten() - y).reshape(2, 1)
downvote count: 0

http://stackoverflow.com/q/47988306
has answer: http://stackoverflow.com/a/47990190
type: Question
linked to: http://stackoverflow.com/q/4140437
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82945327
has comment: http://stackoverflow.com/comment/82945355
has title: Entry accept only float 8,2
linked to: http://stackoverflow.com/q/1018729
tagged with: python
has body: I have the need with tkinter python, to define an entry field that only accepts a float field with 8 integers and 2 decimals, perhaps with an error message if it does not respect the format 8.2. You can help me define a format for this field.
tagged with: tkinter-entry
downvote count: 6
tagged with: tkinter
type: UnansweredQuestion
upvote count: 1
score: -5
has comment: http://stackoverflow.com/comment/82945359
linked to: http://stackoverflow.com/q/8579267

http://stackoverflow.com/comment/82728500
has text: anywhere you place them, you can apply the same principle as convolution is tranlsation invariant
comment on: http://stackoverflow.com/a/47874506
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/83003562
type: AnswerComment
comment on: http://stackoverflow.com/a/48014521
has text: @BlueShrapnel. Nvm. I found and corrected the error. Thanks for the catch.
type: Comment
score: 0

http://stackoverflow.com/comment/82946833
score: 0
type: Comment
type: QuestionComment
has text: can you provide more detail steps of this?
comment on: http://stackoverflow.com/q/47988942

http://stackoverflow.com/a/47944369
type: AcceptedAnswer
score: 0
answers question: http://stackoverflow.com/q/47942901
type: Answer
has body: Based on the output from which it seems clear that your python and pip belong to two different instances. So all libraries you install will be installed for some other python instance. The acute fix is to force pip to run through your specified interpreter: python -m pip list --local python -m pip install cvxopt
accepted answer of: http://stackoverflow.com/q/47942901

http://stackoverflow.com/comment/83016770
type: Comment
type: QuestionComment
has text: Both are correct. In a long term they should converge to each other. And in many trading terminals or websites like Google Finance slightly different implementations used. For [example](https://www.quantopian.com/posts/ta-dot-macd-values-dont-match-google-or-yahoo-finance-charts#5212576dab562def9f000136).
score: 0
comment on: http://stackoverflow.com/q/47986840

http://stackoverflow.com/comment/82987434
has text: this compares the first line of f1 with every line of f2, then the second line of f1 with every line of f2, and so on and so on
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47996043
type: AnswerComment

http://stackoverflow.com/q/47931539
accepted answer: http://stackoverflow.com/a/47931644
has answer: http://stackoverflow.com/a/47932070
possible better answer: http://stackoverflow.com/a/47931731
linked to: http://stackoverflow.com/q/36455083
has comment: http://stackoverflow.com/comment/82831959
has comment: http://stackoverflow.com/comment/82832115
has title: How can I forward fill -9999 values in python?
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/82832110
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47931731
upvote count: 1
has comment: http://stackoverflow.com/comment/82832024
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/82832422
has comment: http://stackoverflow.com/comment/82832344
answer count: 3
tagged with: pandas
has body: I have a pandas dataframe which I need to plot by ignoring the -9999 values. If I use ylim, it creates drops like in this question (Working with NaN values in matplotlib) I know this can be used to forward fill NAN values: fillna(method='ffill', limit=1) But, I have -9999 values that need to be filled. How to do this?
has comment: http://stackoverflow.com/comment/82832035
tagged with: python
has answer: http://stackoverflow.com/a/47931644

http://stackoverflow.com/q/47949386
has comment: http://stackoverflow.com/comment/82869315
score: 0
has answer: http://stackoverflow.com/a/47951547
has title: Getting indexes of search results
has comment: http://stackoverflow.com/comment/82869271
answer count: 1
has body: The code below gets the index of matching values: x = ["Moon", "Earth", "Jupiter", "Neptune", "Earth", "Venus"] get_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y] print(get_indexes("Earth", x)) The code below extracts the peaks satisfying the conditions: intensitySortedPeaks = sorted(peaks, key=lambda p: p.Intensity, reverse=True) for i in range(len(intensitySortedPeaks)): testMass = intensitySortedPeaks[i].MZ + 1.0033 results = [p for p in intensitySortedPeaks if abs(GetPPMError(p.MZ,testMass)) &lt; 10] ###how do we get the indexes saved as indeResults How do I get the indices of the elements that were stored in the results variable. I want to remove those elements from the original intensitySortedList in the loop How do I modify the above code to achieve this task?
tagged with: dataframe
tagged with: scipy
has comment: http://stackoverflow.com/comment/82869238
tagged with: numpy
accepted answer: http://stackoverflow.com/a/47951547
type: AnsweredQuestion
type: Question
tagged with: python

http://stackoverflow.com/comment/82846731
score: 0
type: AnswerComment
type: Comment
has text: For the code to the other question df.groupby(pd.to_datetime(df['Index']).dt.weekday_name).size‌​().to_frame('Count')‌​.......i got a syntax error:invalid character in identifier
comment on: http://stackoverflow.com/a/47935755

http://stackoverflow.com/q/47915483
score: 1
type: Question
has answer: http://stackoverflow.com/a/47929167
upvote count: 1
answer count: 1
favorite count: 0
type: UnansweredQuestion
has title: pyodbc cant connect mssql (Timeout)
tagged with: python
tagged with: pyodbc
has body: I have mssql in my windows host machine, and ubuntu in VMware. I try to connect this mssql from virtual machine with pyodbc module in python. import pyodbc server = '192.168.0.19'//host ip database = 'mytestdb' username = 'sa' port = "1433" password = 'mypassword' cnxn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER='+server+';PORT='+port+';DATABASE='+database+';UID='+username+';PWD='+ password) cursor = cnxn.cursor() remote connection to my mssql instance is already enabled and I can login using same credentials so what might be problem here?
downvote count: 0

hiveql
tag name: hiveql
tags question: http://stackoverflow.com/q/47913700
type: Tag

http://stackoverflow.com/comment/82915495
type: Comment
comment on: http://stackoverflow.com/a/47972905
type: AnswerComment
score: 0
has text: It's just a mask. For example: `array([ True, True, True, ..., True, True, True], dtype=bool)`

http://stackoverflow.com/q/47930021
downvote count: 2
has answer: http://stackoverflow.com/a/47930099
tagged with: loops
has comment: http://stackoverflow.com/comment/82828568
type: Question
score: -2
has body: I am Trying to simplify my program but it says "invalid syntax" on the "=" in "B=tkinter.Button(start, text=x)" Code import tkinter from tkinter import * start = tkinter.Tk() for x in ["New","Load"]:( B=tkinter.Button(start, text=x) B.pack() ) #N = tkinter.Button(start, text="New") #L = tkinter.Button(start, text="Load") #N.pack() #L.pack() start.mainloop()
upvote count: 0
accepted answer: http://stackoverflow.com/a/47930099
answer count: 1
tagged with: variables
favorite count: 0
has comment: http://stackoverflow.com/comment/82828573
tagged with: python
has title: Python: Variable in Loop error
type: AnsweredQuestion

http://stackoverflow.com/comment/82706150
score: 0
has text: Sparsity (working with 3D arrays) is typically >90% zeros. Thanks @hpaulj for the link
type: QuestionComment
comment on: http://stackoverflow.com/q/47857372
type: Comment

http://stackoverflow.com/q/47947049
downvote count: 0
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/82865103
has title: Linear regression: Cost function working independently, but not within a scipy.optimize function
type: Question
tagged with: linear-regression
upvote count: 2
has comment: http://stackoverflow.com/comment/82865121
answer count: 1
accepted answer: http://stackoverflow.com/a/49532673
favorite count: 0
has body: I am implementing regularised linear regression. The data can be found here: https://onedrive.live.com/?cid=506A31CDF6E4A865&amp;id=506A31CDF6E4A865%21107&amp;parId=root&amp;o=OneUp My code is below: import numpy as np import scipy.optimize as optimize from scipy.io import loadmat data = loadmat('ex5data1.mat') X = data['X'] X = np.insert(X, 0, 1, axis=1) y = data['y'] theta = np.ones((2, 1)) def cost_function(theta, X, y, reg_param): theta = np.matrix(theta) X = np.matrix(X) y = np.matrix(y) m = y.shape[0] h = X * theta error = np.power((h - y), 2) error = np.sum(error) term = error / (2*m) reg = (reg_param * np.sum(np.power(theta[1:, :], 2))) / (2*m) return term + reg print "Cost function: \n %s" % (cost_function(theta, X, y, 1)) def cost_function_gradient(theta, X, y, reg_param): theta = np.matrix(theta) X = np.matrix(X) y = np.matrix(y) m = y.shape[0] grad = np.zeros((len(X[0]) + 1, 1)) reg = np.multiply(theta[1:, :], reg_param/m) for j in xrange(len(X[0])): term = np.multiply((X * theta) - y, X[:, j + 1]) term = np.sum(term) / m grad[j + 1, 0] = term + reg grad[0, 0] = np.sum(np.multiply((X*theta - y), X[:, 0])) / m return grad print "Cost function gradient: \n %s" % (cost_function_gradient(theta, X, y, 1)) reg_param = 1 opt = optimize.fmin_cg(cost_function, theta, args=(X, y, reg_param), maxiter=200) My problem Before I start trying to optimise the parameters to minimise the cost function, the cost_function() and cost_function_gradient() functions work fine, outputting the correct result. However, then I start optimising the parameters, I get the following error: Traceback (most recent call last): File "ex5.py", line 49, in &lt;module&gt; opt = optimize.fmin_cg(cost_function, theta, args=(X, y, reg_param), maxiter=200) File "/Users/Olly/anaconda2/lib/python2.7/site-packages/scipy/optimize/optimize.py", line 1177, in fmin_cg res = _minimize_cg(f, x0, args, fprime, callback=callback, **opts) File "/Users/Olly/anaconda2/lib/python2.7/site-packages/scipy/optimize/…
has comment: http://stackoverflow.com/comment/82865159
has comment: http://stackoverflow.com/comment/82865528
tagged with: python
has comment: http://stackoverflow.com/comment/82864063
has answer: http://stackoverflow.com/a/49532673
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/47996396
tagged with: apache-spark
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/128135720
has body: I get the following error when I add --conf spark.driver.maxResultSize=2050 to my spark-submit command. 17/12/27 18:33:19 ERROR TransportResponseHandler: Still have 1 requests outstanding when connection from /XXX.XX.XXX.XX:36245 is closed 17/12/27 18:33:19 WARN Executor: Issue communicating with driver in heartbeater org.apache.spark.SparkException: Exception thrown in awaitResult: at org.apache.spark.util.ThreadUtils$.awaitResult(ThreadUtils.scala:205) at org.apache.spark.rpc.RpcTimeout.awaitResult(RpcTimeout.scala:75) at org.apache.spark.rpc.RpcEndpointRef.askSync(RpcEndpointRef.scala:92) at org.apache.spark.executor.Executor.org$apache$spark$executor$Executor$$reportHeartBeat(Executor.scala:726) at org.apache.spark.executor.Executor$$anon$2$$anonfun$run$1.apply$mcV$sp(Executor.scala:755) at org.apache.spark.executor.Executor$$anon$2$$anonfun$run$1.apply(Executor.scala:755) at org.apache.spark.executor.Executor$$anon$2$$anonfun$run$1.apply(Executor.scala:755) at org.apache.spark.util.Utils$.logUncaughtExceptions(Utils.scala:1954) at org.apache.spark.executor.Executor$$anon$2.run(Executor.scala:755) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) Caused by: java.io.IOException: Connection from /XXX.XX.XXX.XX:36245 closed at org.apache.spark.network.client.TransportResponseHandler.channelInactive(TransportResponseHandler.java:146) The reason of adding this configuration was the error: py4j.protocol.Py4JJavaError: An error occurred while c…
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/47999105
has comment: http://stackoverflow.com/comment/82961294
type: Question
tagged with: python
has title: Total size of serialized results of 16 tasks (1048.5 MB) is bigger than spark.driver.maxResultSize (1024.0 MB)
answer count: 2
accepted answer: http://stackoverflow.com/a/47999105
score: 70
tagged with: apache-spark-sql
has comment: http://stackoverflow.com/comment/82961396
possible better answer: http://stackoverflow.com/a/57090116
has comment: http://stackoverflow.com/comment/82976856
tagged with: pyspark
has answer: http://stackoverflow.com/a/57090116
upvote count: 70

http://stackoverflow.com/comment/82681444
has text: @jonrsharpe it appears the padding is based on the total characters i.e the numbers both before and after the decimal place as well as the decimal point itself. So `%7.4f` still produces `34.1867` but `%8.4f` produces ` 34.1867`.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47858275
type: QuestionComment

http://stackoverflow.com/a/47981553
accepted answer of: http://stackoverflow.com/q/47977440
score: 1
has body: vars(obj) is syntactic sugar for obj.__dict__, so it doesn't work on any object without __dict__. This includes stuff like: User-defined objects where every level in the class hierarchy defined __slots__ (without a __dict__ slot) to reduce memory usage Objects of built-in types that don't opt-in to a tp_dict slot Worse, there are in-between cases, where some attributes are set on the __dict__, while others aren't (e.g. a class hierarchy where __slots__ was used for some levels, but other levels didn't use __slots__ and relied on the implicit __dict__). In cases like that, you wouldn't get an error to let you know something had gone wrong, you'd just serialize the __dict__ part of the object state and silently ignore the rest. You'd have similar problems if the interface uses @propertys; they're used like attributes, but they're not on the instance __dict__, so you'd either lose the information completely (if there is no hidden underlying attribute), or serialize the "wrong" value (the internal name, rather than the API name exposed as an @property). In short, lots of things can go subtly wrong by trying to guess at the correct behavior like this, which is why The Zen of Python (type import this in an interactive terminal to see it) includes stuff like: Errors should never pass silently. and In the face of ambiguity, refuse the temptation to guess. Beyond these errors, there's also the general problem of reversability. A general encoder of this form is definitionally incapable of being handled by a general decoder (because you lose all the type information). Offering an easy way to lose important information is... suboptimal.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47977440
has comment: http://stackoverflow.com/comment/83235799
has comment: http://stackoverflow.com/comment/83235962
type: Answer
upvote count: 1

http://stackoverflow.com/comment/82952258
comment on: http://stackoverflow.com/q/47991371
has text: Can you please add this statement "print(i, F)"just below "print('bu')", and share the output?
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/47984171
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/82938326
answers question: http://stackoverflow.com/q/47984103
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/82937445
has body: A decorator will be called. In your case you receive the function as a parameter in the __call__ method class MyClass: def __init__(self): self.start = 0 class Decorator: def __init__(self, msg): self.msg = msg def __call__(self, f): self.f = f return self def __get__(self, instance, _): def wrapper(test): print(self.msg) self.f(instance, test) return self.f return wrapper @Decorator(msg='p1') def p1(self, sent): print(sent) @Decorator(msg='p2') def p2(self, sent): print(sent) Your first example works because calling the Class creates an instance and the function is the parameter. But in your second example you call the Class manually to set the msg parameter, so you the decoration process calls what's left, i.e.: the instance and that goes to the __call__ method.

http://stackoverflow.com/comment/82953844
type: Comment
type: QuestionComment
has text: Glad to hear that!
comment on: http://stackoverflow.com/q/47981652
score: 0

http://stackoverflow.com/comment/82832685
has text: @ArtemDumanov, There is no parent tag for all those text nodes in provided piece of HTML. Can you update HTML again?
comment on: http://stackoverflow.com/q/47931534
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82754059
type: QuestionComment
score: 5
has text: If the DataFrame is a single block (no mixed dtypes) then it doesn't create a new array; otherwise it does.
comment on: http://stackoverflow.com/q/47893677
type: Comment

http://stackoverflow.com/comment/82794828
comment on: http://stackoverflow.com/q/47913568
score: 2
has text: What's the input? What data do you have in `chessboard`?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82894173
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47962474
score: 0
has text: post the code on how are you populating `grocery_history`

http://stackoverflow.com/comment/82938477
comment on: http://stackoverflow.com/a/47978594
score: 0
type: AnswerComment
has text: Hi Fatih , and thanks for providing me some guidance. The code works however I need to count every single individual word. For example : BILE BEANS FOR BILIOUSNESS B , the result shoul be BILE 1 , BEANS 1 ... Not BILE BEANS FOR BILIOUSNESS B 1.
type: Comment

http://stackoverflow.com/q/47964195
has comment: http://stackoverflow.com/comment/82898329
tagged with: pyqt5
has body: I'm building an application (mostly a simulation) that has a GUI with a main image such that when the user presses a button, this image will change every second or so and display an updated image each time (the update is actually just painting various things onto the parent image). Just to test, I have a loop that runs in my 'start simulation' slot that does all of the model changing and picture updating for 10 steps of the simulation. The central image should therefore update 10 times. However, it only updates one time at the very end when the callback returns. My underlying model is updating properly at each step, and the image I see at the end is the correct image for the 10th time step. I'm new to Qt and I'm sure the problem is something widget/update related, but I've been having no luck at all. The callback I have registered to the start simulation button, which starts the image update process. The self is a subclass of QMainWindow def start_simulation(self): self.map_view.place_initial_population(250, 250) for i in range(1, 10): self.map_view.simulation_step() self.map_view.update() time.sleep(1) Relevant functions in the map_view class (which is a subclass of QGraphicsView): def simulation_step(self): self.load_map() self.draw_dot() def load_map(self): self.map_image = QImage("ancient_map_seed1.png") self.current_pixmap = QPixmap.fromImage(self.map_image) self.map_scene = QGraphicsScene(self) self.map_graphics_item = self.map_scene.addPixmap(self.current_pixmap) self.setScene(self.map_scene) def draw_dot(self): founder_pop = self.map_objects.populations[0] print("Height: +" + str(founder_pop.x)+ "; width: " + str(founder_pop.y)) dot = QGraphicsPixmapItem(QPixmap.fromImage(self.red_dot), parent = self.map_graphics_item) dot.setPos(founder_pop.x, founder_pop.y) new_x = founder_pop.x + random.randint(-5, 5) new_y = founder_pop.y + random.randint(-5, 5) self.map_objects.populations[0].x = new_x self.map_objects.populations[0].y = new_y self.map_objects.populatio…
tagged with: pyqt
type: UnansweredQuestion
answer count: 1
tagged with: simulation
type: Question
tagged with: python
has title: Running simulation in PyQt5 - QGraphicsScene not updated until simulation ends
has comment: http://stackoverflow.com/comment/82898221
tagged with: qt
has comment: http://stackoverflow.com/comment/82898028
score: 0
has answer: http://stackoverflow.com/a/47964530

http://stackoverflow.com/a/47961604
answers question: http://stackoverflow.com/q/47957997
has comment: http://stackoverflow.com/comment/82896001
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/82896390
score: 1
upvote count: 1
has body: You can use this simple recursive function which will analyze all possible groups: import itertools import copy words = ["ALI", "SIN", "ASI", "LIR", "IRI", "INI", "KAR"] def get_pairs(word_group, current_words, found): if not current_words: return found new_group = list(word_group)+[current_words[0]] if all(''.join(i) in words and ''.join(i) not in new_group for i in zip(*new_group)): return get_pairs(word_group, current_words[1:], new_group) return get_pairs(word_group, current_words[1:], found) starting_pairs = [i for i in itertools.combinations(words, 2)] final_listing = filter(lambda x:x, [get_pairs(i, copy.deepcopy(words), []) for i in starting_pairs]) Output: [['ALI', 'SIN', 'IRI'], ['ASI', 'LIR', 'INI']] Which yields all combinations of valid matrices. Or, without using itertools: def get_combos(word, new_words): if new_words[1:]: new_list = [(yield (word, i)) for i in new_words if i != word] for b in get_combos(new_words[0], new_words[1:]): yield b starting_pairs = get_combos(words[0], words[1:]) final_listing = filter(lambda x:x, [get_pairs(i, copy.deepcopy(words), []) for i in starting_pairs])

http://stackoverflow.com/q/47887942
has comment: http://stackoverflow.com/comment/82742022
has comment: http://stackoverflow.com/comment/82741866
tagged with: regex
has comment: http://stackoverflow.com/comment/82742406
upvote count: 2
score: 0
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/82741680
tagged with: python
has comment: http://stackoverflow.com/comment/82741876
has comment: http://stackoverflow.com/comment/82741828
has title: Find matching words in a database and a long string
has body: I have a large database of cities and towns (around 300 000) and I am trying -using python- to check if a given string contains one of these cities. What is the optimal way to achieve this?
has comment: http://stackoverflow.com/comment/82741739
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/82741736
has answer: http://stackoverflow.com/a/47888419
favorite count: 0
has comment: http://stackoverflow.com/comment/82741723
tagged with: python-2.7

http://stackoverflow.com/comment/82902576
comment on: http://stackoverflow.com/a/47966202
type: AnswerComment
score: 0
type: Comment
has text: Thanks, good catch on where its posting to. I have posted an update! @furas

http://stackoverflow.com/q/47928768
answer count: 1
accepted answer: http://stackoverflow.com/a/47933667
has comment: http://stackoverflow.com/comment/82835944
tagged with: beautifulsoup
tagged with: python
has comment: http://stackoverflow.com/comment/82835607
has comment: http://stackoverflow.com/comment/82836042
type: AnsweredQuestion
tagged with: web-scraping
has body: I have written the code below to scrape the cargurus website. A search shows 15 entries per page. I want to iteratively move from page 1 to n and scrape each page. The code below is supposed to do that, however at the end of the script I have a dataframe df which duplicates the 1st page numPages times. I thought the code wasn't giving the computer time to receive the request so I added a time.sleep(1) line but that doesn't seem to work. What am I doing wrong? # Import Modules from bs4 import BeautifulSoup as bs import requests import pandas as pd import seaborn as sns import time #Utility Functions def to_number(s): #Convert to Number numval = int(s.replace(',','')) return numval def get_location(s): #Convert to City, State (SS), and zip (string) s = s.replace(',','') sList = s.split() n = len(sList)-1 City = '' for word in sList[0:n-1]: City += word + ' ' City = City[:-1] State = sList[n-1] Zip = sList[n] return City, State, Zip def get_YearMakeModelTrim(s): #Convert to Year, Make, Model, Trim sList = s.split() n = len(sList)-1 Year = sList[0] Make = sList[1] Model = sList[2] if n == 3: Trim = sList[3] else: Trim = "None" return Year, Make, Model, Trim numPages = 10 baseURL = 'https://www.cargurus.com/Cars/inventorylisting/viewDetailsFilterViewInventoryListing.action?sourceContext=forSaleTab_false_0&amp;newSearchFromOverviewPage=true&amp;inventorySearchWidgetType=AUTO&amp;entitySelectingHelper.selectedEntity=c24578&amp;entitySelectingHelper.selectedEntity2=c25202&amp;zip=03062&amp;distance=50000&amp;searchChanged=true&amp;modelChanged=false&amp;filtersModified=true#resultsPage={}' data = [] for ii in range(numPages): URL = baseURL.format(ii+1) print(URL) r = requests.get(URL).text time.sleep(1) soup = bs(r,'html.parser') stats = soup.find_all("div", attrs = {"class": "cg-dealFinder-result-stats"}) deals = soup.find_all("div", attrs = {"class": "cg-dealFinder-result-deal"}) titles = soup.find_all("h4", {"class":"cg-dealFinder-result-model"}) for title, deal, stat in…
tagged with: python-requests
has comment: http://stackoverflow.com/comment/82835864
has answer: http://stackoverflow.com/a/47933667
type: Question
score: 0
has comment: http://stackoverflow.com/comment/82836040
has title: How to Step Through Pages When Web-Scraping

http://stackoverflow.com/comment/82783437
comment on: http://stackoverflow.com/q/47906952
score: 0
has text: Why a query of 8 words returns a list of only 6...? And what do you mean by in place? Your title seems a bit misleading.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82824441
has text: Your example is going to have an `IndexError` after 10 loops; you indexed to `i` (unreduced), not `point` (`i` reduced to within the appropriate range).
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47928003
type: AnswerComment

http://stackoverflow.com/comment/82760440
has text: Each of your processes reads the whole file, even though it only processes a subset of the lines. `loadtxt` is much like your inner loop, except I don't think it converts each line into an array. It's left as a list. So the final `np.array` works from a list of lists.
type: QuestionComment
comment on: http://stackoverflow.com/q/47896022
score: 0
type: Comment

http://stackoverflow.com/comment/82692476
type: QuestionComment
has text: `for i in range(10, -5, 5):`?
comment on: http://stackoverflow.com/q/47863776
score: 0
type: Comment

http://stackoverflow.com/comment/82941607
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47984542
has text: This fixed it. Thanks a lot

http://stackoverflow.com/q/47879683
downvote count: 0
tagged with: http://stackoverflow.com/tag/xlsx
answer count: 1
accepted answer: http://stackoverflow.com/a/47879795
favorite count: 0
has comment: http://stackoverflow.com/comment/82725638
tagged with: http://stackoverflow.com/tag/csv
tagged with: datetime
has body: I need to write a python script to change from .xlsx file to .csv file: my code : import xlrd import csv def csv_from_excel(): wb = xlrd.open_workbook("Book1.xlsx") sh = wb.sheet_by_name('Att1FF5.tmp') your_csv_file = open('your_csv_file.csv', 'wb') wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL) for rownum in xrange(sh.nrows): wr.writerow([unicode(entry).encode("utf-8") for entry in sh.row_values(rownum)]) your_csv_file.close() csv_from_excel() However , all the date format was changing to integer . for example : 4/13/2018 --> 43203 So is there anyway i can alter my code to keep the date format. My date format is believed to be MM/DD/YYYY thanks.
tagged with: python
type: AnsweredQuestion
has title: Python xlsx to csv without change date to interger
has comment: http://stackoverflow.com/comment/82725418
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/47879795

http://stackoverflow.com/q/47991379
tagged with: deep-learning
has title: What is the best way to convolve two matrices in tensorflow?
has answer: http://stackoverflow.com/a/47992680
score: 0
tagged with: convolution
tagged with: python
type: UnansweredQuestion
has body: Suppose A = [[1,2,3],[4,5,6],[7,8,9]] B = [[1,2,1],[2,1,1],[1,1,2]] After convolving with kernel_size=2*2 and stride=1 , the output should be [[18,18],[28,37]] We need to apply convolution operation between every 2*2 portion of A to every 2*2 portion of B. How to perform this operation efficiently using tensorflow? Does tensorflow has any method to do this directly?
tagged with: machine-learning
tagged with: tensorflow
has answer: http://stackoverflow.com/a/47992609
type: Question
answer count: 2

http://stackoverflow.com/a/78510865
type: Answer
answers question: http://stackoverflow.com/q/47901273
has body: Your processor is 32 bits ARM processor, and the file you try to install for Anaconda is x86 installer file. If you have a 64-bits ARM processor, instead you should download installer for ARM64 architecture; https://repo.anaconda.com/archive/Anaconda3-2024.02-1-Linux-aarch64.sh from the Anaconda downloads page https://www.anaconda.com/download/.
score: 0

http://stackoverflow.com/a/48182153
answers question: http://stackoverflow.com/q/47926990
accepted answer of: http://stackoverflow.com/q/47926990
score: 0
type: AcceptedAnswer
has body: I suggest you uninstall from pip and install with the .exe installer from the official repository. This has always worked for me. Remember to select the right version for your version of python.
type: Answer

http://stackoverflow.com/a/47970280
answers question: http://stackoverflow.com/q/47968143
type: Answer
score: 1
upvote count: 1
downvote count: 0
has body: Your find_obj method is actually a generator because of the yield keyword. For a thorough explanation on generators and yield I recommend this StackOverflow question. In order to get results from your method you should call it in a manner similar to this : for logo_scrape_item in a.find_obj(response): # perform an action on your logo_scrape_item

http://stackoverflow.com/a/47938687
accepted answer of: http://stackoverflow.com/q/47938150
answers question: http://stackoverflow.com/q/47938150
type: AcceptedAnswer
downvote count: 0
has body: If you want to create a nested defaultdict to as many depths as you want then you want to set the default type of the defaultdict to a function that returns a defaultdict with the same type. So it looks a bit recursive. from collections import defaultdict def nest_defaultdict(): return defaultdict(nest_defaultdict) d = defaultdict(nest_defaultdict) d[1][2][3] = 'some value' print(d) print(d[1][2][3]) # Or with lambda f = lambda: defaultdict(f) d = defaultdict(f) If you don't require any arbitrary depth then Fuji Clado's answer demonstrates setting up the nested dict and accessing it.
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/a/47922933
has body: The Evernote SDK for Python only supports Python 2. You get the error because your virtual environment in Python 3. When you have activated the virtualenv, pip will install into the Python 3 virtualenv as well. The README has a link to an experimental repository for Python 3. You could try installing this instead, but you may find other incompatibilities in your project. Your other option is to run your project in Python 2. If you decide to use Python 2, then make sure you use Python 2 when you create your virtualenv, e.g. virtualenv -p python2 v Then activate your virtualenv before installing your requirements.
has comment: http://stackoverflow.com/comment/82814314
answers question: http://stackoverflow.com/q/47922700
has comment: http://stackoverflow.com/comment/82813808
has comment: http://stackoverflow.com/comment/82814200
score: 0
has comment: http://stackoverflow.com/comment/82814245
has comment: http://stackoverflow.com/comment/82813687
has comment: http://stackoverflow.com/comment/82814462
has comment: http://stackoverflow.com/comment/82814350
has comment: http://stackoverflow.com/comment/82815683
has comment: http://stackoverflow.com/comment/82813619
type: Answer

http://stackoverflow.com/comment/82984545
comment on: http://stackoverflow.com/q/48007987
type: QuestionComment
type: Comment
has text: There are numerous problems with this code. It's not indented correctly. It uses several undefined variables. `for` should be lower case. `else:` is missing a colon. And why do you have 2 `break` statements in that `else` block? Also, `H`, `A` and `g` are **not** functions, they are simple expression assignments using those undefined variables I mentioned earlier.
score: 0

http://stackoverflow.com/q/47953245
tagged with: python-3.6
upvote count: 4
answer count: 1
downvote count: 0
tagged with: decorator
accepted answer: http://stackoverflow.com/a/47953281
favorite count: 0
tagged with: python
type: AnsweredQuestion
has title: Decorator inside a class throw warning in Pycharm
has body: I am using PyCharm IDE and below is a fragment of code where I am using a decorator. The decorator is basically checking whether the argument extract is an integer >= 0. This code is working as far as I can tell however I noticed some syntax error in PyCharm. class MyClass(object): def _argument_test_extract(func): def _helper(*args, **kwargs): kwargs = inspect.getcallargs(func, *args, **kwargs) if 'rule' in kwargs: extract = kwargs['rule']['extract'] if type(extract) == int and extract &gt;= 0: return func(**kwargs) else: raise Exception("Argument `extract` is not an integer") return _helper @_argument_test_extract def _perform_split_model_string(self, rule): # do some stuff PyCharm indicates the following message for the line where I decorate the function with @_argument_test_extract: Function '_argument_test_extract' lacks a positional argument The line where the decorator function is defined def _argument_test_extract(func): indicates the following message Usually first parameter of a function is 'self' Finally the line return func(**kwargs) indicates the following message: 'MyClass' is not callable Obviously, if I decorate the function _argument_test_extract with @staticmethod all the warning of PyCharm disappear but the code is not working anymore because of this error, TypeError: 'staticmethod' object is not callable. Is there something wrong with my syntax? Thanks
tagged with: pycharm
has comment: http://stackoverflow.com/comment/82875830
type: Question
has answer: http://stackoverflow.com/a/47953281
score: 4

http://stackoverflow.com/q/47858703
type: Question
has title: Wagtail admin ,CheckboxSelectMultiple not saving data
tagged with: django
tagged with: python
answer count: 1
upvote count: 3
accepted answer: http://stackoverflow.com/a/47859090
has body: @register_snippet class Numbers(models.Model): number = models.IntegerField() class State(models.Model): state = models.CharField(max_length=100) number = ParentalManyToManyField(Numbers) class HomeStateNumber(State): page = ParentalKey('home.HomePage', related_name='helpline') api_fields = ['state', 'number'] panels = [ FieldPanel('state'), FieldPanel('number',widget=forms.CheckboxSelectMultiple), ] class HomePage(Page): content_panels = [ FieldPanel('title'), ImageChooserPanel('cover_page'), InlinePanel('ticker', label="ticker"), InlinePanel('helpline', label="helpline"), ] I want to add one than more number in a state , wagtail shows correct order in admin , when you select number from multiple and save the page, data is not saved. It remains None (queryset) Is there any other way to do this ? I think i am doing wrong somewhere Please help
tagged with: django-admin
tagged with: wagtail
downvote count: 0
type: AnsweredQuestion
tagged with: wagtail-snippet
score: 3
has answer: http://stackoverflow.com/a/47859090
favorite count: 0

http://stackoverflow.com/a/47883922
has body: Yes, you can create a custom template (based on django_tables2/table.html) and set a specific table's template Meta attribute to its path: import django_tables2 as tables class Table(tables.Table): # columns class Meta: template = 'table-blocks.html' or use the template argument to the Table constructor: table = Table(queryset, template='table-blocks.html') or use the second argument of the {% render_table %} templatetag: {% load django_tables2 %} {% render_table queryset 'table-blocks.html' %}
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47871550
accepted answer of: http://stackoverflow.com/q/47871550
type: Answer
upvote count: 3
score: 3

http://stackoverflow.com/comment/82815666
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47919853
has text: The never5classifier dont learn anything and always predict all data to be negative. i.e. not 5.
score: 0

http://stackoverflow.com/comment/82745599
type: AnswerComment
has text: Not bad at all :)
type: Comment
comment on: http://stackoverflow.com/a/47889679
score: 0

http://stackoverflow.com/q/47912110
answer count: 2
score: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/47912659
favorite count: 0
has comment: http://stackoverflow.com/comment/82792145
tagged with: pandas
has title: Creating a new column in Pandas based on another dataframe
tagged with: python
has answer: http://stackoverflow.com/a/47912252
upvote count: 2
has body: I need to add a column to an existing pandas dataframe based on an attribute from a second dataframe. I've made a minimal example to illustrate my exact requirements. I've got two dataframes, one representing pairs of names, and the other representing an interaction between two individuals: &gt;&gt;&gt; names id_a id_b 0 ben jack 1 jack ben 2 jill amir 3 wilma jill 4 amir wilma &gt;&gt;&gt; interactions individual1 individual2 0 jill jack 1 jack jill 2 wilma jill 3 amir jill 4 amir jack 5 jack amir 6 jill amir What I need is essentially this: for each pair of names in names, I need a count of the number of interactions between those two names, so the number of rows in interactions in which names['id_a'] is either interactions['individual1'] or interactions['individual2'] AND names['id_b'] is either interactions['individual1'] or interactions['individual2']. This count needs to be included in a column num_interactions for all rows in names, even if the names are duplicate (i.e. if there is a row in which id_a is ben and id_b is jack AND a row in which those names are reversed (id_a is jack and id_b is ben), the num_interactions should be included for both of those rows) The resulting dataframe would look like this: &gt;&gt;&gt; names id_a id_b num_interactions 0 ben jack 0.0 1 jack ben 0.0 2 jill amir 2.0 3 wilma jill 1.0 4 amir wilma 0.0 enter code here What I've Done This works just fine, but it's ugly, hard to read, inefficient, and I know there must be a better way! Maybe with some sort of merge, but I don't really know how that works with complicated criteria... for i in range(len(names)): names.loc[i, 'num_interactions'] = len( interactions[((interactions['individual1'] == names.loc[i, 'id_a']) &amp; (interactions['individual2'] == names.loc[i, 'id_b'])) | ((interactions['individual2'] == names.loc[i, 'id_a']) &amp; (interactions['individual1'] == names.loc[i, 'id_b'])) ]) To Reproduce my example dataframes In case you want to play around with this, you can use…
has comment: http://stackoverflow.com/comment/82792038
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47912252
tagged with: dataframe
has answer: http://stackoverflow.com/a/47912659
type: Question

http://stackoverflow.com/q/47981061
accepted answer: http://stackoverflow.com/a/47981175
has comment: http://stackoverflow.com/comment/82930672
type: Question
has body: I am trying to convert this complicated datetime format after getting this error: [u"'Nov 11, 2017 5:19:38 AM PST' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."] I am building this function but I am not sure how to handle the Month as a word. This is an example of the date as it is in the CSV file: Nov 1, 2017 12:00:13 AM PDT I am not having any luck: def process_datetime(self,dt): d_time = datetime.strptime(dt, '') return datetime.strftime(d_time, 'YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]')
linked to: http://stackoverflow.com/q/26435530
score: 0
answer count: 1
has title: convert 'Nov 11, 2017 5:19:38 AM PST' to YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format
has comment: http://stackoverflow.com/comment/82930732
tagged with: timezone
tagged with: datetime
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47981175

http://stackoverflow.com/comment/82831030
score: 0
has text: Can you specify in detail what happened when you ran your code? And what prevents you to get all article tags from the html?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47931105

http://stackoverflow.com/comment/82696595
type: QuestionComment
comment on: http://stackoverflow.com/q/47865706
has text: I suspect you also need to explicitly identify `data` as being "html". `data = MIMEText(whatever, "html")`.
score: 0
type: Comment

http://stackoverflow.com/q/47945899
tagged with: python
has answer: http://stackoverflow.com/a/64497493
has title: Anaconda (Windows) alternative to nano?
tagged with: anaconda
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/82861626
has comment: http://stackoverflow.com/comment/82865093
has body: So I've been following this tutorial to download Keras with a Tensorflow backend: https://github.com/antoniosehk/keras-tensorflow-windows-installation It has gone fairly smoothly, and I'm only stuck for a stupid reason on the final step. It asks me to run mnist_mlp.py to test if it is working, but I don't have that file downloaded. I figured I could just type 'nano mnist_mlp.py' and then copy over the code for the file and then run it, as I would do in Linux. However, since I am on windows, it is telling me in the Anaconda prompt that nano is not a recognized command. So, how can I create a python file in Anaconda? I've tried looking it up several times, but nothing helpful has come up. Perhaps I am asking the wrong question, for I am quite new to python. Thank you!
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/19497399
has comment: http://stackoverflow.com/comment/82861566
tagged with: nano
favorite count: 0
has comment: http://stackoverflow.com/comment/82861822
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/82861753
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82861744

http://stackoverflow.com/q/47917234
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82802730
linked to: http://stackoverflow.com/q/11904981
has comment: http://stackoverflow.com/comment/82802742
tagged with: python
score: 1
has body: Adding a number to the variable isn't working? (This is once again the rock paper scissors program.) import random hscore = 0 cscore = 0 tries = 0 #computer choice rock = ("rock") paper = ("paper") scissors= ("scissors") rps = (rock, paper, scissors) #human wins def humanfunction(): hscore +=1 if choice == "rock": if cchoice == scissors: hscore +=1 print("Human wins this round.") if choice == "scissors": if cchoice == paper: hscore +=1 print("Human wins this round.") if choice == "paper": if cchoice == rock: hscore +=1 print("Human wins this round.") def computerwin(): #computer wins cscore +=1 if cchoice == "rock": if choice == scissors: cscore +=1 print("Computer wins this round.") if cchoice == "scissors": if choice == paper: cscore +=1 print("Computer wins this round.") if cchoice == "paper": if choice == rock: cscore +=1 print("Computer wins this round.") def tie(): if cchoice == choice: print("It's a tie!") #choosing while 0 == 0: choice = input("\nWhat do you choose? &lt;rock, paper, scissors&gt;: ") tries +=1 cchoice = random.choice(rps) humanfunction() computerwin() tie() print(hscore, cscore) print("Human choice: ",choice) print("Computer choice: ",cchoice) print("Finished game number", tries) if tries == 10: print("limit reached") break When I run the code it shows this (ignore the error beforehand): The human chose paper and the computer chose rock, which means the human beats the computer--but the score for the human didn't increase the next game. Functions have been messing up my code super badly for some reason. The hscore is there again in the function because without it, the output will say something about a local variable being reference beforehand. (This is a class assignment and we cannot use things we haven't gone over yet.) So adding a global would not help. The choices are defined in the code later on. I just didn't include it as I wanted to just show the part where the variable is being added to.
has comment: http://stackoverflow.com/comment/82802732
favorite count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47917539
has comment: http://stackoverflow.com/comment/82802501
upvote count: 1
has comment: http://stackoverflow.com/comment/82802646
has comment: http://stackoverflow.com/comment/82802510
has answer: http://stackoverflow.com/a/47917345
has comment: http://stackoverflow.com/comment/82803513
has title: Adding to a variable not working?
has comment: http://stackoverflow.com/comment/82802481
downvote count: 0
has comment: http://stackoverflow.com/comment/82802507

http://stackoverflow.com/a/47894299
has comment: http://stackoverflow.com/comment/82756413
upvote count: 2
has comment: http://stackoverflow.com/comment/82756365
has comment: http://stackoverflow.com/comment/82756460
has comment: http://stackoverflow.com/comment/129275452
has comment: http://stackoverflow.com/comment/82756573
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47894052
has body: IMO working against reddits anti-crawl mechanisms will cost you too much time, I would not try to follow this road. They have an API to get all the posts of one subreddit, e.g. https://www.reddit.com/r/subreddit/top.json?sort=top gets the all the posts of in /r/subreddit as json format, it looks like the same content as you see on their websites. Also, their doc suggest that you use oauth. Then they let you do 60 requests per minute. I would go this road instead. This is also a lot more safer than scraping as scraping will fall over whenever they change something in their HTML layout.
type: Answer

http://stackoverflow.com/q/48002965
score: 1
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/48003765
has comment: http://stackoverflow.com/comment/83133118
tagged with: python
tagged with: psycopg2
type: AnsweredQuestion
has title: AttributeError: 'PGDialect_psycopg2' object has no attribute 'dbapi_type_map'
downvote count: 1
tagged with: sqlalchemy
type: Question
accepted answer: http://stackoverflow.com/a/48003765
has body: After updating all the plugins on the python server, it now raises File "D:\Python362\lib\site-packages\aiopg\utils.py", line 72, in __await__ resp = yield from self._coro File "D:\Python362\lib\site-packages\aiopg\sa\connection.py", line 116, in _execute return ResultProxy(self, cursor, self._dialect, result_map) File "D:\Python362\lib\site-packages\aiopg\sa\result.py", line 234, in __init__ self._metadata = ResultMetaData(self, cursor.description) File "D:\Python362\lib\site-packages\aiopg\sa\result.py", line 103, in __init__ typemap = dialect.dbapi_type_map AttributeError: 'PGDialect_psycopg2' object has no attribute 'dbapi_type_map' Plugins List
tagged with: aiopg
answer count: 1

http://stackoverflow.com/comment/82761414
comment on: http://stackoverflow.com/a/47894478
type: Comment
has text: You are referencing something that has not been assigned a value yet. By the 'date' parameter inside of ``def format_data(date):`` I assume you meant to type 'data' instead, if you were to use the name 'data' as a parameter you would not get the unbounded reference error, thus the definition should be ``def format_data(data):``
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82860789
has text: Is that a feature of the filesystem?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47945481

http://stackoverflow.com/q/48007936
has title: Get Average by group in python
has comment: http://stackoverflow.com/comment/82984206
has comment: http://stackoverflow.com/comment/82984102
answer count: 2
has comment: http://stackoverflow.com/comment/82984226
has body: Input is like this: G1: 12 G2: 15 G1: 9 G3: 18 G2: 17 G3: 6 G1: 20 Output should be average of individual groups like G1: 12+9+20/3 = 13.67, G2: 15+17/2 = 16, G3: 6+18/2 = 12
has comment: http://stackoverflow.com/comment/82984105
has answer: http://stackoverflow.com/a/48008488
has comment: http://stackoverflow.com/comment/82984077
downvote count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48008519
upvote count: 0
score: -5
linked to: http://stackoverflow.com/q/48007236
favorite count: 0
has comment: http://stackoverflow.com/comment/82984203
type: Question
tagged with: python

http://stackoverflow.com/comment/108326868
type: Comment
comment on: http://stackoverflow.com/a/57090116
score: 0
type: AnswerComment
has text: Is there a way we can do this using Luigi PySparkTask properties?

http://stackoverflow.com/comment/82771264
score: 0
type: AnswerComment
type: Comment
has text: @JohannesReichard I didn't get you. Since its a pandas question I think all OP is expected is to get the dataframe as an output. And since I saw only a partial string I imported everything to avoid future issues.
comment on: http://stackoverflow.com/a/47902109

http://stackoverflow.com/q/47898326
downvote count: 0
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/82882803
favorite count: 0
has body: I'm trying to understand the following code from sklearn.feature_extraction.text import CountVectorizer vectorizer = CountVectorizer() corpus = ['This is the first document.','This is the second second document.','And the third one.','Is this the first document?'] X = vectorizer.fit_transform(corpus) When I try to print X to see what will be return, I got this result : (0, 1) 1 (0, 2) 1 (0, 6) 1 (0, 3) 1 (0, 8) 1 (1, 5) 2 (1, 1) 1 (1, 6) 1 (1, 3) 1 (1, 8) 1 (2, 4) 1 (2, 7) 1 (2, 0) 1 (2, 6) 1 (3, 1) 1 (3, 2) 1 (3, 6) 1 (3, 3) 1 (3, 8) 1 However, I don't understand the meaning of this result ?
has comment: http://stackoverflow.com/comment/82853924
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82763454
upvote count: 11
has answer: http://stackoverflow.com/a/54212001
has comment: http://stackoverflow.com/comment/82809188
has answer: http://stackoverflow.com/a/52315610
tagged with: machine-learning
type: Question
has comment: http://stackoverflow.com/comment/82853043
has title: How vectorizer fit_transform work in sklearn?
score: 11
has answer: http://stackoverflow.com/a/54350840
answer count: 3
has comment: http://stackoverflow.com/comment/82815392

http://stackoverflow.com/comment/84676548
score: 0
type: Comment
type: AnswerComment
has text: @Pylander I think it is, otherwise sqlalchemy wouldn't be used at all. Just not sure how to piece it together
comment on: http://stackoverflow.com/a/48065082

http://stackoverflow.com/a/47935924
has body: Here you go , you need to specify the indices there : import numpy as np test_list = [3, 4, 6, 3, 8, 4, 7, 8, 12, 14, 1, 6, 7, 3, 7, 8, 3, 3, 7] def ema(x, n): x = np.array(x) emaint = np.zeros(len(x)) k = 2 / float(n + 1) emaint[0:n] = np.average(x[:n]) for i in range(n, len(x)): [emaint.__setitem__(i, ((x[i] * k) + (emaint[i - 1] * (1 - k)))) for i in range(n, len(x))] return emaint print(ema(test_list, 5)) output: [ 4.8 4.8 4.8 4.8 4.8 4.53333333 5.35555556 6.23703704 8.15802469 10.10534979 7.0702332 6.7134888 6.80899253 5.53932835 6.0262189 6.68414594 5.45609729 4.63739819 5.42493213]
answers question: http://stackoverflow.com/q/47935694
score: 0
type: Answer

http://stackoverflow.com/q/47954465
favorite count: 0
linked to: http://stackoverflow.com/q/5389507
linked to: http://stackoverflow.com/q/3849625
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/82879306
upvote count: 1
tagged with: python
duplicate of: http://stackoverflow.com/q/3849625
has body: Let's say I have the following code arr = ["a", "b", "c", "d"...] I don't know how many items there may be, but I know it'll be a multiple of two. How would I go about appending every pair of items together, leaving me with arr = ["ab", "cd"...]?
has comment: http://stackoverflow.com/comment/82878203
has answer: http://stackoverflow.com/a/47954502
type: Question
linked to: http://stackoverflow.com/q/312443
has answer: http://stackoverflow.com/a/47954494
score: -1
has answer: http://stackoverflow.com/a/47954473
has title: Attach every 2 items in an array together
duplicate of: http://stackoverflow.com/q/312443
has comment: http://stackoverflow.com/comment/82878241
has answer: http://stackoverflow.com/a/47954549
answer count: 4

http://stackoverflow.com/comment/82756638
comment on: http://stackoverflow.com/q/47890399
type: Comment
type: QuestionComment
score: 0
has text: @ChesuCR — OK thank you so much.

http://stackoverflow.com/comment/82734434
type: Comment
comment on: http://stackoverflow.com/a/47883443
has text: I tried in jupyter notebook , it displayed the output but there is no change in index order
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82739475
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47879232
score: 2
has text: I suggest contacting Heroku support. They should be able to tell you your billing cycle, but more importantly they'll be able to talk to you about your dyno hours more knowledgeably than we can.

http://stackoverflow.com/q/47981828
linked to: http://stackoverflow.com/q/6866600
type: UnansweredQuestion
has title: How do I import text file dictionary into python dictionary
has body: I am creating a tournament scoring system application. There are many sections to this app, for example, Participants, Team, Events and Award points. Right now I am working on the team section. I was able to create something that will allow the user to create teams. The code looks like this. teamname = input("Team Name: ").title() First_member = input("First Member Full Name: ").title() if any(i.isdigit() for i in First_member): print("Invalid Entry") else: There can only be 5 members in each team. This is how the data is saved combine = '\''+teamname+'\' : \''+First_member+'\', \''+Second_member+'\', \''+Third_member+'\', \''+Forth_member+'\', \''+Fifth_member+'\'', myfile = open("teams.txt", "a+") myfile.writelines(combine) myfile.writelines('\n') myfile.close() Now If I want to remove a team how do I do that? Apologies if you feel like i am wasting your time but still thanks for stopping by. If you want to see everything please check out this link https://repl.it/@DaxitMahendra/pythoncode>
tagged with: external
has comment: http://stackoverflow.com/comment/82933461
has comment: http://stackoverflow.com/comment/82932122
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/82932904
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82932210
has answer: http://stackoverflow.com/a/47981873
score: 0
tagged with: file
has answer: http://stackoverflow.com/a/47982708

http://stackoverflow.com/comment/82787478
type: AnswerComment
comment on: http://stackoverflow.com/a/47898378
score: 0
type: Comment
has text: when using djangorestframework-jwt no need to create extra login views am i right because jwt already provided.In that case only registration(using username&password) view is enough.Is it?

http://stackoverflow.com/a/47988676
has comment: http://stackoverflow.com/comment/82957255
score: 1
has comment: http://stackoverflow.com/comment/82956921
has comment: http://stackoverflow.com/comment/82948572
has comment: http://stackoverflow.com/comment/82954552
upvote count: 1
has body: def get(self, timeout): """ :param timeout: How many seconds to wait :type timeout: int :rtype: threading.Event """ # tricks here return self._latest This is a reStructuredText format for writing a python docstring (a multiline string that appear right after function definition. You can document there all parameter types, and what the function return along with their datatypes. pylint can parse that docstring to figure out the datatype of that function's return value. This stackoverflow answer has more comprehensive explanation What is the standard Python docstring format?
has comment: http://stackoverflow.com/comment/82961070
has comment: http://stackoverflow.com/comment/82949996
downvote count: 0
answers question: http://stackoverflow.com/q/47988540
type: Answer

logging
tags question: http://stackoverflow.com/q/47886582
tags question: http://stackoverflow.com/q/47969034
tags question: http://stackoverflow.com/q/47936254
tags question: http://stackoverflow.com/q/47924507
tags question: http://stackoverflow.com/q/47927877
tags question: http://stackoverflow.com/q/47961289
tag name: logging
tags question: http://stackoverflow.com/q/47924256
tags question: http://stackoverflow.com/q/47970761
tags question: http://stackoverflow.com/q/47887547
tags question: http://stackoverflow.com/q/47965473
tags question: http://stackoverflow.com/q/47873937
tags question: http://stackoverflow.com/q/47863085
tags question: http://stackoverflow.com/q/48013656
tags question: http://stackoverflow.com/q/48002785
tags question: http://stackoverflow.com/q/47899678
tags question: http://stackoverflow.com/q/47963763
tags question: http://stackoverflow.com/q/47888855
tags question: http://stackoverflow.com/q/47957841
type: Tag

http://stackoverflow.com/a/47890407
type: Answer
answers question: http://stackoverflow.com/q/47884375
score: 0
has body: After 1 login attempt on the linked site, I noticed that the username and password are posted in a JSON object, instead of a form-like encoding like in the OP. Luckily that is excessibely simple with requests. You should simply use the json param to .post(): r = s.post(url, json=payload)

http://stackoverflow.com/comment/82840316
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47935442
has text: I got an error in samtools for merge there are something about the add ReadGroup and picard seems like don't have this error
score: 0

http://stackoverflow.com/q/47963316
type: Question
has body: I have a Python code to run my CNC machine, The code is below: import serial import time # Open grbl serial port s = serial.Serial('COM3',9600) # Open g-code file f = open('grbl.gcode.txt','r'); # Wake up grbl s.write("\r\n\r\n") time.sleep(2) # Wait for grbl to initialize s.flushInput() # Flush startup text in serial input # Stream g-code to grbl for line in f: l = line.strip() # Strip all EOL characters for consistency print 'Sending: ' + l, s.write(l + '\n') # Send g-code block to grbl grbl_out = s.readline() # Wait for grbl response with carriage return print ' : ' + grbl_out.strip() # Wait here until grbl is finished to close serial port and file. raw_input(" Press &lt;Enter&gt; to exit and disable grbl.") # Close file and serial port f.close() s.close() This code opens the g-code file (it is a text file) and executes the lines. My question is can I get rid of the text file of g-code and put it directly in the code above?
has comment: http://stackoverflow.com/comment/82904872
has title: How to embed a text file in code?
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82896773
has answer: http://stackoverflow.com/a/47963408
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/47946818
has answer: http://stackoverflow.com/a/47947869
accepted answer: http://stackoverflow.com/a/47947869
has body: I have 'train.csv' and 'test.csv' files. The former contains 'Id', a list of features, and a 'Status' column with values in it, the 'test.csv' file contains the same columns except the 'Status' one. My task is to train an XGboost model on the 'train.csv' file and predict binary outcome of 'Status' for the 'test.csv' file, then to save 'Id' and 'Status' to a separate csv file for submission. I am able to train XGboost on the 'train' file, and the roc_auc score is pretty good (above 0.8). I have spent hours searching the internet how to make predictions for the 'test' file and save them to the 'submission' file. To my surprise, and although this is quite a common task, I couldn't find any scripts that would reliably perform the operations described above. My working code for the 'train.csv' file just in case: predict = pd.read_csv("train.csv") predictors =['par48','par52','par75','par82','par84','par85','par86','par87','par89','par108','par109','par132','par156','par165','par167','par175','par190','par197'] X, y = predict[predictors], predict['Status'] X_train, X_test, y_train, y_test= train_test_split(X, y, test_size=0.2, random_state=123) xg_cl=xgb.XGBClassifier(objective='binary:logistic',n_estimators=10,seed=123) xg_cl.fit(X_train, y_train) preds=xg_cl.predict(X_test) accuracy = float(np.sum(preds==y_test))/y_test.shape[0] print("accuracy: %f" % (accuracy)) print(xg_cl.feature_importances_) print(roc_auc_score(y_test, xg_cl.predict_proba(X_test)[:,1])) Do you have a working code to share? Thanks!
upvote count: 1
downvote count: 0
answer count: 1
tagged with: xgboost
favorite count: 0
tagged with: binary
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: AnsweredQuestion
tagged with: prediction
score: 1
has title: Saving xgboost binary prediction to submission csv file
type: Question

http://stackoverflow.com/comment/82687667
type: QuestionComment
comment on: http://stackoverflow.com/q/47861343
score: 0
has text: command `self = self.__init__(...)` is the most unusual line of code - it means that you have to better organize code and move some code from `__init__` to separated method - and then run this method insife `__init__` and in place of `self = self.__init__()`
type: Comment

http://stackoverflow.com/comment/82977323
comment on: http://stackoverflow.com/q/48004509
has text: you can see it under the tags
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83006482
has text: Thank you, now I got it to get all lines/paths into dictionary! Now I need to think, how to process them – how to search for individual file and get its path.
type: AnswerComment
comment on: http://stackoverflow.com/a/47869422
score: 0
type: Comment

http://stackoverflow.com/q/47977653
tagged with: algorithm
type: UnansweredQuestion
has body: I have four model as bellow: class AModel(models.Model): name = models.CharField(max_length=11) class BModel(models.Model): name = models.CharField(max_length=11) a = models.ForeignKey(AModel, related_name="bs") class CModel(models.Model): name = models.CharField(max_length=11) b = models.ForeignKey(BModel, related_name="cs") class DModel(model.Model): name = models.CharField(max_length=11) c = models.ForeignKey(CModel, related_name="ds") Now I want to get the bellow data: [ {"name":"a1", "value":1, "image":"xxxxx.png", "children":[ {"name":"b1", "value":1, "image":"xxxxx.png", "children":[ {"name":"c1", "value":1, "image":"xxxx.png", "children":[ {"name":"d1", "value":1, "image":"xxxx.png", } ] } ] } ] } ] note, the value and image key-value are add by myself. I know use the Django-Rest-Framework can get the data like: [ { "id":1, "name":"a1", "bs":[ { "id":1, "name":"b1", "cs":[ "id":1, "name":"c1", "ds":[ { "id":1, "name":"d1", } ] ] } ] } ] But how can I get my requirement data? I also tried query the AModel instance first, the forloop the AModel instance's bs, and then do the next, but I find that is too complex, not a simple and convenient way to get it.
answer count: 1
type: Question
linked to: http://stackoverflow.com/q/15306897
tagged with: python
has title: How can I get the custom nested data in Django?
has answer: http://stackoverflow.com/a/47977799
score: 0
tagged with: django

http://stackoverflow.com/comment/118270121
comment on: http://stackoverflow.com/a/48154139
type: AnswerComment
has text: what do you mean by startup scripts ? and init scripts ?
score: 0
type: Comment

http://stackoverflow.com/comment/82746413
score: 0
type: AnswerComment
has text: Thanks! I had assumed that running the pipeline was a blocking call. Adding a sleep timer makes it work. I also now no longer get complaints about my keyframe settings.
type: Comment
comment on: http://stackoverflow.com/a/47883994

http://stackoverflow.com/q/47958564
has title: Creating array of options menu using python tkinter
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82886769
has body: I am trying to create options menu runtime by getting how many options menu they want in runtime. import tkinter import tkinter.messagebox from tkinter import * top = tkinter.Tk() number_of_pd = Label(top, text="Number of Products") list2 = ['1','2','3','4','5'] E_Name=['','','','','',''] a=['','','','','',''] def New_number_of_pd(oE_number_of_pd): y_axis=300 num=1 for num in range(int(oE_number_of_pd)): y_axis=y_axis+75 E_Name[num]= OptionMenu(top,a[num],*list2) E_Name[num].place(x=y_axis,y=150) oE_number_of_pd=StringVar() E_number_of_pd= OptionMenu(top, oE_number_of_pd, *list2,command=New_number_of_pd) number_of_pd.place(x=150,y=75) E_number_of_pd.place(x=300,y=75) top.title('Sri Sai') top.geometry('2000x1000') # Size 200, 200 top.mainloop() In number of products text box enter the number of options menu that is required.The buttons are getting created.However I am getting error as below
has answer: http://stackoverflow.com/a/47958792
tagged with: tkinter
has answer: http://stackoverflow.com/a/47959055
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/47966301
tagged with: python
has comment: http://stackoverflow.com/comment/82904101
has comment: http://stackoverflow.com/comment/82887110
score: 0

http://stackoverflow.com/a/47987212
answers question: http://stackoverflow.com/q/47986662
score: 3
downvote count: 0
type: Answer
has body: Yes, tf.contrib.layers.xavier_initializer and tf.glorot_uniform_initializer both implement the same concept described in this JMLR paper: Understanding the difficulty of training deep feedforward neural networks, which can be seen in the code: tf.glorot_uniform_initializer tf.contrib.layers.xavier_initializer With typical values for fan_in, fan_out, mode = FAN_AVG , and uniform = True, both implementations sample values from the standard uniform distribution over the limit [-sqrt(3), sqrt(3)) Because tf.initializer has support for a wide variety of initialization strategies, it's highly likely that it will stay whereas the initialization from contrib which just has xavier_initialization will most probably be deprecated in future versions. So, yes it's highly likely that in future versions the tf.contrib.layers.xavier_initialier way of initialization might go away.
upvote count: 3

http://stackoverflow.com/a/48003830
score: 2
downvote count: 0
has body: list() creates a new list. The newly created list equal (==) to the original but not identical (is).
answers question: http://stackoverflow.com/q/48003739
upvote count: 2
type: Answer

http://stackoverflow.com/q/47883128
has body: I am running a python script on both my laptop and home computer with: os.startfile(r'C:\\A file.xlsx') This works great, however I want it full size. Any idea on how I can make it full size through python? The following tends to work: import win32gui, win32con, os, time os.startfile('C:\\A File.xlsx') time.sleep(10) hwnd = win32gui.GetForegroundWindow() win32gui.ShowWindow(hwnd, win32con.SW_MAXIMIZE) Without time.sleep, it does not go full size so time.sleep is needed. I need a high time.sleep because of my slow laptop, however this means it runs slow on my home pc. I use both Apache OpenOffice and microsoft Excel Any idea how I can make an excel open full size reliably without time.sleep?
has comment: http://stackoverflow.com/comment/82736836
has title: Reliably method to open xlsx to full size (wait until file is open)
score: 0
tagged with: http://stackoverflow.com/tag/xlsx
answer count: 1
type: UnansweredQuestion
tagged with: python
tagged with: win32com
tagged with: winapi
has comment: http://stackoverflow.com/comment/82737610
type: Question
has answer: http://stackoverflow.com/a/49699440

http://stackoverflow.com/a/47900113
answers question: http://stackoverflow.com/q/47900005
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer
has body: I think you need assign back and for new values use numpy.where: patient_data = patient_data.assign(gender=np.where(patient_data['sex']&lt;0, 'male', 'female')) print(patient_data.head(10)) id name dob sex state gender 0 0.588686 1.333191 2.559850 0.034903 0.232650 female 1 1.606597 0.168722 0.275342 -0.630618 -1.394375 male 2 0.912688 -1.273570 1.140656 -0.788166 0.265234 male 3 -0.372272 1.174600 0.300846 1.959095 -1.083678 female 4 0.413863 0.047342 0.279944 1.595921 0.585318 female 5 -1.147525 0.533511 -0.415619 -0.473355 1.045857 male 6 -0.602340 -0.379730 0.032407 0.946186 0.581590 female 7 -0.234415 -0.272176 -1.160130 -0.759835 -0.654381 male 8 -0.149291 1.986763 -0.675469 -0.295829 -2.052398 male 9 0.600571 -1.577449 -0.906590 1.042335 -2.104928 female
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47900005

recursion
type: Tag
tags question: http://stackoverflow.com/q/47909472
tags question: http://stackoverflow.com/q/47982604
tags question: http://stackoverflow.com/q/47874864
tags question: http://stackoverflow.com/q/47895499
tags question: http://stackoverflow.com/q/47974823
tag name: recursion
tags question: http://stackoverflow.com/q/47926650
tags question: http://stackoverflow.com/q/47913377
tags question: http://stackoverflow.com/q/47964903
tags question: http://stackoverflow.com/q/47970683
tags question: http://stackoverflow.com/q/47909793
tags question: http://stackoverflow.com/q/47970707
tags question: http://stackoverflow.com/q/47998759
tags question: http://stackoverflow.com/q/47881454
tags question: http://stackoverflow.com/q/47914178
tags question: http://stackoverflow.com/q/47945163
tags question: http://stackoverflow.com/q/47965868
tags question: http://stackoverflow.com/q/47856548
tags question: http://stackoverflow.com/q/47907585
tags question: http://stackoverflow.com/q/47999547
tags question: http://stackoverflow.com/q/47963422

http://stackoverflow.com/comment/82895303
comment on: http://stackoverflow.com/a/47963005
score: 1
type: AnswerComment
has text: Side note: this only holds for Python 3, but if OP is using Python 2, the user input gets interpreted (and `raw_input()` is what should probably be used))
type: Comment

http://stackoverflow.com/q/47949053
linked to: http://stackoverflow.com/q/39824914
tagged with: data-science
has comment: http://stackoverflow.com/comment/82868039
has answer: http://stackoverflow.com/a/47949362
has answer: http://stackoverflow.com/a/47949148
has answer: http://stackoverflow.com/a/47949084
tagged with: pandas
has title: Round to nearest 1000 in pandas
has answer: http://stackoverflow.com/a/68678575
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/47949152
accepted answer: http://stackoverflow.com/a/47949152
answer count: 5
score: 13
tagged with: python
upvote count: 13
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82875340
has comment: http://stackoverflow.com/comment/82868056
has body: I've searched the pandas documentation and cookbook recipes and it's clear you can round to the nearest decimal place easily using dataframe.columnName.round(decimalplace). How do you do this with larger numbers? Example, I have a column of housing prices and I want them rounded to the nearest 10000 or 1000 or whatever. df.SalesPrice.WhatDoIDo(1000)?
type: Question
possible better answer: http://stackoverflow.com/a/47949148

http://stackoverflow.com/comment/82699398
comment on: http://stackoverflow.com/a/47866960
type: AnswerComment
has text: Let's say that on click you want it to do a random selection and then fig.canvas.draw(), if you want it to happen once without you clicking, just execute those commands at the start of the script.
score: 0
type: Comment

http://stackoverflow.com/comment/82913411
comment on: http://stackoverflow.com/a/47971867
type: AnswerComment
has text: @EchchamaNayak, i couldn't find `State` column in your sample DF... Consider posting a __reproducible__ data sets and more generic desired data set...
type: Comment
score: 1

http://stackoverflow.com/comment/82727355
comment on: http://stackoverflow.com/a/47880479
type: AnswerComment
type: Comment
has text: So How can I get keys from this list returned from re.findall ?
score: 0

http://stackoverflow.com/a/47984195
type: Answer
answers question: http://stackoverflow.com/q/47983728
has body: This question might be more suitable for CodeReview. Since your code is working, here are a few hints: namedtuple returns a class. holding should be written Holding. lst is too generic. It's a list of Holding instances, it could be called holdings. index0 is not a list index but a dict key. You could use nested defaultdicts instead of calling setdefault repeatedly. Here's an example: from collections import namedtuple, defaultdict import pprint Holding = namedtuple('holding', ['portfolio', 'ticker', 'shares']) holdings = [ Holding('Large Cap', 'TSLA', 100), Holding('Large Cap', 'MSFT', 200), Holding('Small Cap', 'UTSI', 500) ] def default_tree(depth, leaf): if depth == 1: return defaultdict(leaf) else: return defaultdict(lambda: default_tree(depth - 1, leaf)) def indexer(lst, attributes): """Creates a dynamic nested dictionary based on indexes.""" root = default_tree(len(attributes), list) for item in lst: node = root for attribute in attributes: key = getattr(item, attribute) node = node[key] node.append(item) return root d = indexer(holdings, ['portfolio', 'ticker', 'shares']) pp = pprint.PrettyPrinter() pp.pprint(d)
score: 0
has comment: http://stackoverflow.com/comment/82937605

http://stackoverflow.com/a/47893408
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47885698
score: 1
has comment: http://stackoverflow.com/comment/82784472
has comment: http://stackoverflow.com/comment/82754328
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/82758182
has body: The easiest way is to build the op locally, upload to your GCS bucket, copy it to the VM(container), and use it via tf.load_op_library. You can use the preinstalled gsutil cli or GCS python client to perform the copy. Back to the original question: When we start a user job, we first install user code package as root, so in case of python 2.7, it's located at /root/.local/lib/python2.7/site-packages/YOUR_PACKAGE_NAME
has comment: http://stackoverflow.com/comment/82771408
accepted answer of: http://stackoverflow.com/q/47885698

http://stackoverflow.com/comment/82942944
score: 0
has text: yes sorry, forgot to add the update, you can try again? requests i guess is more lightweight
type: Comment
comment on: http://stackoverflow.com/a/47987022
type: AnswerComment

bidi
tag name: bidi
tags question: http://stackoverflow.com/q/47874091
type: Tag

http://stackoverflow.com/comment/83869118
type: Comment
has text: I know I'm late, but I forgot to thank you for the answer, thanks alot!
comment on: http://stackoverflow.com/a/47952999
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82839557
type: Comment
type: QuestionComment
has text: Scraping Amazon is against their terms of use. Use their API instead.
score: 1
comment on: http://stackoverflow.com/q/47935006

http://stackoverflow.com/a/53333043
downvote count: 1
upvote count: 9
has comment: http://stackoverflow.com/comment/93545904
type: Answer
score: 8
accepted answer of: http://stackoverflow.com/q/47993099
answers question: http://stackoverflow.com/q/47993099
has body: Hope this is still relevant. But you can try using blob.upload_from_string method def cloud_upload(self, buffer, bucket, filename): client = storage.Client() bucket = client.get_bucket(bucket) blob = bucket.blob(filename) blob.upload_from_string(buffer.getvalue(),content_type='text/csv') Do take note to modify the content_type parameter if you want to save the file as other file types. I placed 'text/csv' as an example. The default value is 'text/plain'.
type: AcceptedAnswer

http://stackoverflow.com/q/47993443
upvote count: 21
downvote count: 1
tagged with: webdriver
type: Question
has title: Selenium "selenium.common.exceptions.NoSuchElementException" when using Chrome
score: 20
linked to: http://stackoverflow.com/q/45576958
linked to: http://stackoverflow.com/q/48369043
has answer: http://stackoverflow.com/a/47995294
has body: I'm trying to play QWOP using Selenium on Chrome but I keep getting the following error: selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element {"method":"id","selector":"window1" (Session info: chrome=63.0.3239.108 (Driver info: chromedriver=2.34.522913 (36222509aa6e819815938cbf2709b4849735537c), platform=Linux 4.10.0-42-generic x86_64) while using the following code: from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains import time browser = webdriver.Chrome() browser.set_window_size(640, 480) browser.get('http://www.foddy.net/Athletics.html?webgl=true') browser.implicitly_wait(10) canvas = browser.find_element_by_id("window1") canvas.click() while (True): action = ActionChains(browser) action.move_to_element(canvas).perform() canvas.click() canvas.send_keys("q") The same code works perfectly on Firefox, but because I want to use chrome's capability to run an webgl game in headless mode I can't really switch to Firefox. Any workarounds to get this working?
answer count: 1
linked to: http://stackoverflow.com/q/47770144
favorite count: 0
linked to: http://stackoverflow.com/q/46700764
tagged with: python
accepted answer: http://stackoverflow.com/a/47995294
tagged with: selenium-webdriver
linked to: http://stackoverflow.com/q/54459701
type: AnsweredQuestion
tagged with: nosuchelementexception
linked to: http://stackoverflow.com/q/48471321
tagged with: selenium

http://stackoverflow.com/q/47959532
linked to: http://stackoverflow.com/q/21122540
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/21122540
has body: python 2.7.9 so i wanted to make a script to run constantly where i can take notes on names and characteristics but i don't know why its throwing this error. eventually i would like it to be exported to a file so it can save the inputted information. Traceback (most recent call last): File "C:\Users\Admin\Desktop\PythonFiles\Dictionary.py", line 18, in key = input("Enter a player name: ") File "", line 1, in Name Error: name 'bob' is not defined basket = {} print(""" Note Program: ___________ 1: Add Item 2: Remove Item 3: View 0: Exit Program """) option = int(input("Enter an Option: ")) while option != 0: if option == 1: key = input("Enter a player name: ") if key in basket: print("Name Found!...") value = input("adding notes: ") basket[key] += value else: value = input("Notes: ") basket[key] = value elif option == 2: key = input("Enter a player name: ") del(basket[key]) elif option == 3: for key in basket: print(key,":",basket[key]) elif option !=0: print("please enter a valid option") option = str(input("\n\nEnter an option: ")) else: print("Note Program Closed.")
has answer: http://stackoverflow.com/a/47959558
downvote count: 1
type: Question
score: -1
tagged with: for-loop
upvote count: 0
accepted answer: http://stackoverflow.com/a/47959558
answer count: 1
has title: Python Note script with dictionary throwing error
tagged with: string
favorite count: 0
tagged with: python
tagged with: dictionary

http://stackoverflow.com/q/47893111
favorite count: 0
upvote count: 2
has title: How to catch RecursionError in Python?
possible better answer: http://stackoverflow.com/a/47893708
tagged with: python
has comment: http://stackoverflow.com/comment/82752941
has body: I am testing a function to find the root of a mathematical function in Python and if there is no root on the interval, a RecursionError is raised. However, when I try to handle the exception with a try-except block, it isn't raised anymore. What am I missing? import math sgn = lambda x: math.copysign(1, x) def bisect(f, a, b, eps=1e-6): """ Find an approximate root of f in the interval [a, b]. Parameters ---------- f : function A mathematical function, defined and with root on [a, b] a, b : numbers Endpoints of the interval. a &lt; b. eps : number, optional, default 1e-6 Tolerance of error. Returns ------- x : number Approximate root of f on [a, b] """ if a &gt; b: raise ValueError("`b` needs to be greater than `a` for the interval [a, b] to exist.") x = (a + b) / 2 if abs(f(x)) &lt; eps: return x try: if sgn(f(a)) != sgn(f(x)): return bisect(f, a, x, eps) else: return bisect(f, x, b, eps) except RecursionError as e: raise RecursionError(f"There seems to be no root of f on the interval [{a}, {b}]") def test_bisect(): """Verify `bisect` using `f` = cos(pi * x), `a` = 0 `b` = 0.82 and `eps` = 1e-12.""" from math import cos, pi f = lambda x: cos(pi * x) a = 0 b = 0.4 eps = 1e-12 expected = 0.5 computed = bisect(f, a, b, eps) error = abs(expected - computed) tolerance = 1e-12 success = error &lt; tolerance msg = f""" Error testing `piecewise`. Expected: {expected} Computed: {computed} Error: {error:13.6e} Tolerance: {tolerance:13.6e}""" assert success, msg test_bisect()
score: 2
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/82752802
has comment: http://stackoverflow.com/comment/82795775
has answer: http://stackoverflow.com/a/47893712
answer count: 2
has comment: http://stackoverflow.com/comment/82752838
downvote count: 0
has comment: http://stackoverflow.com/comment/82754269
accepted answer: http://stackoverflow.com/a/47893712
has answer: http://stackoverflow.com/a/47893708

psycopg2
tags question: http://stackoverflow.com/q/47986098
tags question: http://stackoverflow.com/q/47912529
type: Tag
tags question: http://stackoverflow.com/q/47956425
tags question: http://stackoverflow.com/q/48002965
tags question: http://stackoverflow.com/q/47928883
tag name: psycopg2

http://stackoverflow.com/q/47893138
score: 14
has comment: http://stackoverflow.com/comment/82753722
tagged with: ipython
linked to: http://stackoverflow.com/q/2856344
type: Question
has comment: http://stackoverflow.com/comment/82754471
answer count: 3
has comment: http://stackoverflow.com/comment/82752989
has comment: http://stackoverflow.com/comment/82752926
favorite count: 0
upvote count: 14
tagged with: linux
tagged with: bash
has answer: http://stackoverflow.com/a/53982647
has answer: http://stackoverflow.com/a/58986393
tagged with: python
tagged with: shell
has comment: http://stackoverflow.com/comment/82753840
has body: Python version : Python 3.5.4 |Anaconda custom (64-bit). Ipython version : IPython 4.2.0 Problem: Backspace key misbehaves. It brings the cursor forward a few spaces like the tab key... I'm running bash version: GNU bash, version 4.4.12(1)-release (x86_64-unknown-linux-gnu) on linux manjaro 17.0.6 Gallivera. kernel 4.9.58.1-manjaro I expect it's the Anaconda Python installation as the python 2.7 behaves normally. This version of Anaconda and IPython I can't really update, because of competability issues with Emacs-python-mode so I don't know in what way I can test what is causing the problem.
has answer: http://stackoverflow.com/a/56238716
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82752947
has comment: http://stackoverflow.com/comment/82753154
has title: <back space> not functional in python and ipython in shell

deep-learning
tags question: http://stackoverflow.com/q/47956261
tags question: http://stackoverflow.com/q/47959726
tags question: http://stackoverflow.com/q/47911093
tags question: http://stackoverflow.com/q/47880161
tags question: http://stackoverflow.com/q/47955463
tags question: http://stackoverflow.com/q/48006574
tags question: http://stackoverflow.com/q/47976616
tags question: http://stackoverflow.com/q/47890612
tags question: http://stackoverflow.com/q/47974502
tags question: http://stackoverflow.com/q/47990621
tags question: http://stackoverflow.com/q/47857750
tags question: http://stackoverflow.com/q/47987202
tags question: http://stackoverflow.com/q/47945175
tags question: http://stackoverflow.com/q/47969112
tags question: http://stackoverflow.com/q/48004017
tags question: http://stackoverflow.com/q/47943081
tags question: http://stackoverflow.com/q/48003535
tags question: http://stackoverflow.com/q/47946413
tags question: http://stackoverflow.com/q/47972820
tags question: http://stackoverflow.com/q/47954926
tags question: http://stackoverflow.com/q/47929557
tags question: http://stackoverflow.com/q/47968975
tags question: http://stackoverflow.com/q/47991379
tags question: http://stackoverflow.com/q/47930176
tags question: http://stackoverflow.com/q/47964765
tags question: http://stackoverflow.com/q/48008998
tags question: http://stackoverflow.com/q/47935253
type: Tag
tags question: http://stackoverflow.com/q/47984976
tags question: http://stackoverflow.com/q/47986662
tags question: http://stackoverflow.com/q/48001759
tags question: http://stackoverflow.com/q/47902295
tags question: http://stackoverflow.com/q/47864509
tags question: http://stackoverflow.com/q/47979852
tags question: http://stackoverflow.com/q/47933858
tags question: http://stackoverflow.com/q/48001598
tags question: http://stackoverflow.com/q/47963978
tags question: http://stackoverflow.com/q/48010637
tags question: http://stackoverflow.com/q/47884862
tag name: deep-learning
tags question: http://stackoverflow.com/q/47907306
tags question: http://stackoverflow.com/q/47902118
tags question: http://stackoverflow.com/q/47941891
tags question: http://stackoverflow.com/q/47865695
tags question: http://stackoverflow.com/q/47889999
tags question: http://stackoverflow.com/q/47922435
tags question: http://stackoverflow.com/q/47897666
tags question: http://stackoverflow.com/q/48003732
tags question: http://stackoverflow.com/q/47955437

http://stackoverflow.com/comment/82966966
type: Comment
score: 2
comment on: http://stackoverflow.com/q/47999119
has text: Your code is **not** complete. It will not run as written: `NameError: name 'f_step' is not defined`. Please [edit] your question to include a [mcve].
type: QuestionComment

http://stackoverflow.com/a/48130563
has body: There is an Repl package that brings up a separate python shell console. I find it very useful and you can open the console for python2 or python 3.
score: 0
answers question: http://stackoverflow.com/q/47955588
type: Answer
has comment: http://stackoverflow.com/comment/88467700
has comment: http://stackoverflow.com/comment/88468689

http://stackoverflow.com/comment/82698364
score: 0
type: Comment
type: QuestionComment
has text: I'd go with the same approach. In order to daisy-chain requests on the client side, I'd suggest that you use [redux-sagas](https://www.google.de/search?q=redux+sagas&oq=redux+sagas&aqs=chrome..69i57j69i65l2.1780j0j7&sourceid=chrome&ie=UTF-8).
comment on: http://stackoverflow.com/q/47856476

http://stackoverflow.com/comment/82896213
has text: I am not a Mac user. From your comment it looks like you have a Python library path problem. https://stackoverflow.com/questions/2741496/location-of-global-libraries-for-python-on-mac
comment on: http://stackoverflow.com/a/47946618
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/47876045
has answer: http://stackoverflow.com/a/47876111
accepted answer: http://stackoverflow.com/a/47876111
type: AnsweredQuestion
type: Question
has title: Average Dataframe using Summary Information
has body: I have a dataframe full of historical data where not every row actually has a "complete" data set. In the example below, data was only collected for parameter "C" in a single row. I'd like to be able to get an average of this data set where I only perform the average if the total number of real samples is > n. import pandas as pd import numpy as np columns = ['A', 'B', 'C'] rows = range(5) data = [ [5, 2, np.NaN], [2, 2, np.NaN], [4, 4, 3], [1, 2, np.NaN], [1, np.NaN, np.NaN] ] history = pd.DataFrame(columns=columns, index=rows, data=data) non_nan_values = history.notnull().sum() # -&gt; A: 5, B: 4, C: 1 means = history.mean() # -&gt; A: 2.6, B: 2.5, C: 3.0 If I were to attempt history[history.notnull().sum() &gt; 3].mean() I get an IndexingError as this isn't actually a valid mask. Aside from iterating over the mean variable retroactively and replacing certain values with NaN depending on my non_nan_values variable, is there a better solution to this? The target result would be a mean variable that looks like this: A: 2.6, B: 2.5, C: NaN
score: 0
tagged with: pandas
answer count: 1
tagged with: python

stateless
tags question: http://stackoverflow.com/q/47913203
type: Tag
tag name: stateless

http://stackoverflow.com/comment/82904946
score: 0
type: Comment
type: QuestionComment
has text: How can I remove default values specified for it?
comment on: http://stackoverflow.com/q/47967705

http://stackoverflow.com/a/60138234
downvote count: 0
score: 6
answers question: http://stackoverflow.com/q/47905546
has comment: http://stackoverflow.com/comment/115426923
upvote count: 6
has body: A convenient solution in general IMO is using setuptools. It will come into handy when your project has too many dependent packages (Python file). First, put an empty __init__ file on each directory which has the code file to be imported. This will help the package to be visible to the import statement. After installing setuptools, create a simple set_up.py file (sample here). Remember to place it at the outermost directory which is your src folder. from setuptools import setup, find_packages setup( name = "name_of_lib", version = "0.0.1", author = "your name", packages = find_packages() ) The find_packages config will collect all your packages within that folder recursively. Run python set_up.py bdist_egg, and finally check out the .egg file in the dist folder. Submit your job using either --py-files oraddPyFile of SparkContext. And it works like a charm!
type: Answer

http://stackoverflow.com/comment/82720470
comment on: http://stackoverflow.com/a/47877281
type: Comment
has text: Makes sense. Might be zero sometimes, just by chance. Others, it some random value.
score: 0
type: AnswerComment

http://stackoverflow.com/a/48010102
type: Answer
accepted answer of: http://stackoverflow.com/q/48010030
score: 2
has comment: http://stackoverflow.com/comment/82996991
answers question: http://stackoverflow.com/q/48010030
upvote count: 2
has comment: http://stackoverflow.com/comment/82996959
has body: You can use get_dummies and add_prefix: df.Parts.str.get_dummies().add_prefix('Part_') Output: Part_12 Part_34 Part_56 0 1 1 1 Edit for comment and counting duplicates. df = pd.DataFrame({'Parts':['12|34|56|12']}, index=[0]) pd.get_dummies(df.Parts.str.split('|',expand=True).stack()).sum(level=0).add_prefix('Part_') Output: Part_12 Part_34 Part_56 0 2 1 1
has comment: http://stackoverflow.com/comment/82995489
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82995598
has comment: http://stackoverflow.com/comment/82998055

http://stackoverflow.com/a/47915771
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/47915716
type: Answer
has body: If you only need to extract consecutive identical digits, you may use a matching approach using r'(\d)\1*' regex: import re s='2223334441214844' print([x.group() for x in re.finditer(r'(\d)\1*', s)]) # =&gt; ['222', '333', '444', '1', '2', '1', '4', '8', '44'] See the Python demo Here, (\d) - matches and captures into Group 1 any digit \1* - a backreference to Group 1 matching the same value, 0+ repetitions. This solution can be customized to match any specific consecutive chars (instead of \d, you may use \S - non-whitespace, \w - word, [a-fA-F] - a specific set, etc.). If you replace \d with . and use re.DOTALL modifier, it will work as the itertools solutions posted above.

http://stackoverflow.com/a/47924197
type: Answer
answers question: http://stackoverflow.com/q/47922435
has comment: http://stackoverflow.com/comment/82841163
has body: Distribute model to each machine (you can use SparkFiles). Rewr def predict(rows, worker_session_path): with tf.Session(graph=graph) as sess: # load the trained model saver.restore(sess, worker_session_path) # lib is the RDD, each Row has the form of Row(key = ..., values = ..., indcies =..., shape = ...) return map(lambda e: Row(key = e["key"], prob = y_proba.eval(feed_dict={values: e["values"], indices: e["indices"], shape: [1,2318]})), rows) Use it with mapPartitions lib.mapPartitions(lambda rows: predict(rows, worker_session_path))
score: 0

http://stackoverflow.com/q/47987707
has answer: http://stackoverflow.com/a/47988808
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82944455
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48015835
has comment: http://stackoverflow.com/comment/82945513
linked to: http://stackoverflow.com/q/483666
type: Question
score: 5
tagged with: python-itertools
tagged with: group-by
upvote count: 5
has answer: http://stackoverflow.com/a/47987770
downvote count: 0
has comment: http://stackoverflow.com/comment/82944829
has answer: http://stackoverflow.com/a/47987916
has title: Pythonic way to group a list using a dictionary that has lists as values
favorite count: 0
possible better answer: http://stackoverflow.com/a/47987916
accepted answer: http://stackoverflow.com/a/47987770
has comment: http://stackoverflow.com/comment/83000518
has answer: http://stackoverflow.com/a/47988075
answer count: 5
has body: I'm looking for a Pythonic way or more efficient way to solve this problem. I have a dictionary which has sets as values (duplicates allowed across keys). Given a list I must create a dictionary which maps each category to the element using the key from the master dictionary. I'll give an example to illustrate. Master Dictionary { "KeyA": ['Aron', 'Ranom Value', 'Abhishek'], "KeyB": ['Ball', 'Foo', 'Bar', 'Badge', 'Dog'], "KeyZ": ['Random Value', 'Foo', 'Bar'] } Input ['Foo', 'Bar', 'Dog', 'Aron'] Output { "KeyA": ['Aron'], "KeyB": ['Bar', 'Foo', 'Dog'], "KeyZ": ['Foo', 'Bar'] } My Current Thoughts Invert individual items in the sets as keys and then do a lookup. { 'Aron' : ['KeyA'], 'Foo' : ['KeyB', 'KeyZ'], 'Bar' : ['KeyB', 'KeyZ'], 'Random Value' : ['KeyA', 'KeyZ'] } I'd initialise the inverted dictionary by going through every item in every set. Approx time to create such a dictionary is O(n). Look for an item in the list in the inverted dictionary so created. Say the value Bar. Create a new dictionary using the information 'Bar': ['KeyB', 'KeyZ']. Resultant dictionary would be {'KeyB': ['Bar'], 'KeyZ': ['Bar']}. For the next item I'd have to do some bookkeeping on the existing dictionary like key exists or not, if yes then append to the existing list and so on. Use the in operator on the set mapped (check for membership) to every key The master dictionary and input list are going to be pretty small most of the times. (less than 500 unique items in all the sets together). So I could check for membership in the set returned by each key and create a dictionary. This is obviously less efficient but works for most cases. I have a few more manipulations that are similar to the example given above. I don't want to do manual bookkeeping for all of them because they are error prone and slower than inbuilt functions. What I need? Better approaches (faster algorithm) Inbuilt functions in itertools because these are faster 3rd Party Library Some esoteric comprehensions tha…

http://stackoverflow.com/a/47944814
accepted answer of: http://stackoverflow.com/q/47944357
answers question: http://stackoverflow.com/q/47944357
downvote count: 0
has body: Your problem is the encoding of the redirect operators is unicode (UTF16-LE). $CS = Get-CimInstance -ClassName CIM_ComputerSystem $OS = (Get-CimInstance -ClassName Win32_OperatingSystem).Caption $CPU = Get-CimInstance -ClassName Win32_Processor @" $($CS.Manufacturer) $($CS.Model) $OS $($CPU.Name) $($CPU.NumberOfCores) $($CPU.NumberOfLogicalProcessors) $($CPU.ThreadCount) $($CPU.MaxClockSpeed) $($CPU.CurrentClockSpeed) "@ | Out-File -FilePath C:\Mike\Output\SysConfig.txt -Encoding UTF8 Cleaned up: $CS = Get-CimInstance -ClassName CIM_ComputerSystem $OS = (Get-CimInstance -ClassName Win32_OperatingSystem).Caption $CPU = Get-CimInstance -ClassName Win32_Processor "{0}`n{1}`n{2}`n{3}`n{4}`n{5}`n{6}`n{7}`n{8}" -f @( $CS.Manufacturer $CS.Model $OS $CPU.Name $CPU.NumberOfCores $CPU.NumberOfLogicalProcessors $CPU.ThreadCount $CPU.MaxClockSpeed $CPU.CurrentClockSpeed ) | Out-File -FilePath C:\Mike\Output\SysConfig.txt -Encoding UTF8
score: 4
type: AcceptedAnswer
type: Answer
upvote count: 4

http://stackoverflow.com/q/48014173
type: Question
type: AnsweredQuestion
score: 1
has body: I'm trying to display the attributes in the Disease Model and Evidence Model, but the attributes that is displayed on the end link are only those attributes that are present in the Rule Model. Models.py :- class Rule(models.Model): disease = models.ForeignKey(Disease, default=0,related_name="DRules") evidence = models.ForeignKey(Evidence, default=0,related_name="ERules") measure_of_belief = models.PositiveIntegerField( \ help_text="The measure of belief (percentage) that a disease is present given this evidence exists", \ default=0,validators=[MinValueValidator(0), MaxValueValidator(100)]) measure_of_disbelief = models.PositiveIntegerField( \ help_text="The measure of disbelief (percentage) that a disease is present given an evidence does not exists", \ default=0,validators=[MinValueValidator(0), MaxValueValidator(100)]) archived = models.BooleanField(default=False) def __str__(self): return "{}-{}".format(self.disease, self.evidence) class Meta: verbose_name = "Rule" verbose_name_plural = "Rules" unique_together = ('disease', 'evidence',) class Disease(models.Model): """ The model where the category will be stored """ name = models.CharField(max_length=255) advise = models.CharField(max_length=500,blank=True) archived = models.BooleanField(default=False) def __str__(self): return self.name class Meta: verbose_name = "Disease" verbose_name_plural = "Diseases" class Evidence(models.Model): evidence_choices = { ("Observable Evidence", ("Observable Evidence")), ("Cause", ("Cause")) } name = models.CharField(max_length=255) question = models.CharField(max_length=500) evidence_type = models.CharField(choices = evidence_choices,max_length=20,default="Observable Evidences") archived = models.BooleanField(default=False) image_name = models.ImageField(upload_to='media/', default='media/None/no-img.jpg') def __str__(self): return self.name class Meta: verbose_name = "Evidence" verbose_name_plural = "Evidences" Serializers.py class DiseaseSerializer(serializers.ModelSerializer…
tagged with: django-serializer
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48023315
tagged with: django-rest-framework
favorite count: 0
has title: Nested Relationship Serializer Rest Framework Not Displaying Properly
tagged with: python
tagged with: django
upvote count: 1
has answer: http://stackoverflow.com/a/48023315

http://stackoverflow.com/a/47964198
answers question: http://stackoverflow.com/q/47963287
has body: Did you try using "URL" encoding? In your case replacing " with %22could help. See also https://www.w3schools.com/tags/ref_urlencode.asp for reference.
score: 0
has comment: http://stackoverflow.com/comment/82898192
has comment: http://stackoverflow.com/comment/82898224
type: Answer
has comment: http://stackoverflow.com/comment/82898216
has comment: http://stackoverflow.com/comment/82897994
has comment: http://stackoverflow.com/comment/82898050

http://stackoverflow.com/comment/83540209
comment on: http://stackoverflow.com/a/48164720
has text: Tx for your help. I checked this wheel and unfortunately it does **not have MKL**.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47914127
tagged with: web
has body: I'm trying to get data from a website that uses pc parts, and I have this link that have over 3500 parts on that page, the problem is that if I use the clean link: https://www.komplett.no/search?q=pc it only get the data that is there before I scroll down and it loads new items. So I took the link edited like this: https://www.komplett.no/search?q=pc&amp;hits=1000 Now it gets all the info from over 1000 products but I can't go over that because the script just don't want to work, I don't get an error or anything. BTW, I only get the things on sale so its not that much data. I want a way to go through the hole page without having to write the limit to how many products I want to go through.
tagged with: python
has answer: http://stackoverflow.com/a/47915718
type: AnsweredQuestion
tagged with: web-scraping
type: Question
accepted answer: http://stackoverflow.com/a/47915718
has title: Web scrape with python | Limited objects
score: 0
answer count: 1

list
tags question: http://stackoverflow.com/q/47856432
tags question: http://stackoverflow.com/q/48012557
type: Tag
tags question: http://stackoverflow.com/q/47926096
tags question: http://stackoverflow.com/q/47888054
tags question: http://stackoverflow.com/q/47957841
tags question: http://stackoverflow.com/q/47934348
tags question: http://stackoverflow.com/q/47940236
tags question: http://stackoverflow.com/q/47892689
tags question: http://stackoverflow.com/q/47978380
tags question: http://stackoverflow.com/q/47998941
tags question: http://stackoverflow.com/q/48000528
tags question: http://stackoverflow.com/q/47957954
tags question: http://stackoverflow.com/q/47875531
tags question: http://stackoverflow.com/q/47880511
tags question: http://stackoverflow.com/q/47879737
tags question: http://stackoverflow.com/q/48000786
tags question: http://stackoverflow.com/q/47865128
tags question: http://stackoverflow.com/q/47970818
tags question: http://stackoverflow.com/q/47905783
tags question: http://stackoverflow.com/q/47914234
tags question: http://stackoverflow.com/q/47890929
tags question: http://stackoverflow.com/q/47983117
tags question: http://stackoverflow.com/q/47983317
tags question: http://stackoverflow.com/q/47999547
tags question: http://stackoverflow.com/q/47896510
tags question: http://stackoverflow.com/q/47916457
tags question: http://stackoverflow.com/q/47972377
tags question: http://stackoverflow.com/q/47911773
tags question: http://stackoverflow.com/q/47986224
tags question: http://stackoverflow.com/q/47979374
tags question: http://stackoverflow.com/q/48013457
tags question: http://stackoverflow.com/q/47860097
tags question: http://stackoverflow.com/q/47857973
tags question: http://stackoverflow.com/q/48005152
tags question: http://stackoverflow.com/q/47962660
tags question: http://stackoverflow.com/q/47956057
tags question: http://stackoverflow.com/q/47933184
tags question: http://stackoverflow.com/q/47938945
tags question: http://stackoverflow.com/q/48003834
tags question: http://stackoverflow.com/q/47982117
tags question: http://stackoverflow.com/q/47993740
tags question: http://stackoverflow.com/q/48007411
tags question: http://stackoverflow.com/q/47969616
tags question: http://stackoverflow.com/q/47979125
tags question: http://stackoverflow.com/q/47985695
tags question: http://stackoverflow.com/q/47891130
tag name: list
tags question: http://stackoverflow.com/q/47948423
tags question: http://stackoverflow.com/q/47932493
tags question: http://stackoverflow.com/q/48006242
tags question: http://stackoverflow.com/q/48011386
tags question: http://stackoverflow.com/q/47964926
tags question: http://stackoverflow.com/q/48009171
tags question: http://stackoverflow.com/q/47986878
tags question: http://stackoverflow.com/q/47914515
tags question: http://stackoverflow.com/q/47905378
tags question: http://stackoverflow.com/q/47925610
tags question: http://stackoverflow.com/q/47958793
tags question: http://stackoverflow.com/q/47925828
tags question: http://stackoverflow.com/q/47900922
tags question: http://stackoverflow.com/q/48002240
tags question: http://stackoverflow.com/q/47934894
tags question: http://stackoverflow.com/q/47963080
tags question: http://stackoverflow.com/q/47954431
tags question: http://stackoverflow.com/q/47991145
tags question: http://stackoverflow.com/q/47865223
tags question: http://stackoverflow.com/q/47956567
tags question: http://stackoverflow.com/q/47993554
tags question: http://stackoverflow.com/q/47925894
tags question: http://stackoverflow.com/q/47948298
tags question: http://stackoverflow.com/q/47916762
tags question: http://stackoverflow.com/q/47980588
tags question: http://stackoverflow.com/q/47875765
tags question: http://stackoverflow.com/q/47943319
tags question: http://stackoverflow.com/q/47973360
tags question: http://stackoverflow.com/q/47859209
tags question: http://stackoverflow.com/q/47955532
tags question: http://stackoverflow.com/q/47976874
tags question: http://stackoverflow.com/q/47859229

http://stackoverflow.com/q/47952176
downvote count: 1
has body: I read this : https://stackoverflow.com/a/37605582/6426449 and this part occurred an error START_TIME = time.time() #at some time def make_id(): t = int(time.time()*1000) - START_TIME u = random.SystemRandom().getrandbits(23) id = (t &lt;&lt; 23 ) | u #This part has problem return id unsupported operand type(s) for &lt;&lt; Can't I use this operation &lt;&lt;? Or How can I use &lt;&lt;?
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47952256
accepted answer: http://stackoverflow.com/a/47952220
has answer: http://stackoverflow.com/a/47952256
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/37558821
score: 0
has title: python3.4, unsupported operand type(s) for <<, How can I fix it?
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/47952220
upvote count: 1

http://stackoverflow.com/comment/82891810
type: Comment
comment on: http://stackoverflow.com/a/47954571
score: 0
type: AnswerComment
has text: I will try to implement this as my dataframe is slightly complicated. I will get back as soon as I have some breakthrough or questions. I will currently keep this query open and close it once I find a suitable resolution. Thanks John for helping out

http://stackoverflow.com/comment/82833733
type: Comment
has text: I was using UID and PWD. I changed that to Trusted_Connection and it didn&#39;t change anything. I also removed the { } from the command and now it works. Thanks for reaching out to help. The documentation threw me off.
score: 0
comment on: http://stackoverflow.com/q/47932032
type: QuestionComment

http://stackoverflow.com/comment/82983473
type: QuestionComment
comment on: http://stackoverflow.com/q/48006213
has text: It isn't immediately clear what you want. Am I correct in assuming you want to: 1) Select rows from a matrix, in the order specified by the indexes in your bfs-output array. 2) Select the non-zero elements in the selected rows starting from the first column in each row (does the order matter?) 3) present a list of the non-zero elements? example: bfs_output=[1,2,0]; matrix=[[0 3 1] [0 2 0] [4 0 0]]; list=[2 4 3 1]. Also what indexes do you want to start from 1 rather than 0 and why?
score: 1
type: Comment

http://stackoverflow.com/a/47999409
downvote count: 0
type: Answer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/47999097
has body: Django prepends HTTP_ to the custom headers. I think (not sure, though) that it might be related to some security issues described here. It also capitalizes them, so your custom header becomes HTTP_CUSTOM from rest_framework.decorators import api_view from rest_framework.response import Response import logging logger = logging.getLogger('django.test') @api_view(['GET']) def TestView(request): logger.info('Meta: %s' % request.META['HTTP_CUSTOM']) return Response({'message': 'test'}) Correctly outputs (if the logging has been properly configured as described here): Django version 2.0, using settings 'django_server.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. "GET /test HTTP/1.1" 301 0 Meta: test "GET /test/ HTTP/1.1" 200 18 Also, as you can see in the output above, Django gives a 301 redirect when the API is hit (I believe this is for authentication purposes? Not sure either) so you'll have to tell your cURL to follow the redirects using --location: curl --location --request GET \ --header 'custom: test' http://localhost:8000/test Also note that all the hyphens (-) in your header's name are transformed to underline symbols (_) so if you call your header something like my-custom, Django will transform it to HTTP_MY_CUSTOM
answers question: http://stackoverflow.com/q/47999097
score: 6
has comment: http://stackoverflow.com/comment/82968052
has comment: http://stackoverflow.com/comment/82969291
type: AcceptedAnswer

http://stackoverflow.com/comment/82825211
type: Comment
comment on: http://stackoverflow.com/q/47928195
has text: What exactly would be the desired output here
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82967539
type: Comment
has text: Well, unpickling always creates a new instance.
score: 0
comment on: http://stackoverflow.com/a/47999504
type: AnswerComment

matrix
tags question: http://stackoverflow.com/q/48006213
tags question: http://stackoverflow.com/q/47862425
tags question: http://stackoverflow.com/q/47930889
tag name: matrix
tags question: http://stackoverflow.com/q/47897108
tags question: http://stackoverflow.com/q/47891130
tags question: http://stackoverflow.com/q/47857382
tags question: http://stackoverflow.com/q/47918691
tags question: http://stackoverflow.com/q/47934252
tags question: http://stackoverflow.com/q/47929814
tags question: http://stackoverflow.com/q/47861235
tags question: http://stackoverflow.com/q/47972832
tags question: http://stackoverflow.com/q/47933724
tags question: http://stackoverflow.com/q/47971514
tags question: http://stackoverflow.com/q/47970040
tags question: http://stackoverflow.com/q/47878173
tags question: http://stackoverflow.com/q/47916701
tags question: http://stackoverflow.com/q/47984126
tags question: http://stackoverflow.com/q/47867249
tags question: http://stackoverflow.com/q/47984870
tags question: http://stackoverflow.com/q/47859656
tags question: http://stackoverflow.com/q/47916639
type: Tag

postgresql
tags question: http://stackoverflow.com/q/47965573
tags question: http://stackoverflow.com/q/47941234
tags question: http://stackoverflow.com/q/47867760
tags question: http://stackoverflow.com/q/47928883
tags question: http://stackoverflow.com/q/47884649
tags question: http://stackoverflow.com/q/47967705
tags question: http://stackoverflow.com/q/48008814
tags question: http://stackoverflow.com/q/47945824
tags question: http://stackoverflow.com/q/47904931
tags question: http://stackoverflow.com/q/47966215
tags question: http://stackoverflow.com/q/47972246
tags question: http://stackoverflow.com/q/47866334
tags question: http://stackoverflow.com/q/47972594
tags question: http://stackoverflow.com/q/47884228
tag name: postgresql
tags question: http://stackoverflow.com/q/47912529
tags question: http://stackoverflow.com/q/47898473
tags question: http://stackoverflow.com/q/47857173
tags question: http://stackoverflow.com/q/47959383
tags question: http://stackoverflow.com/q/47951927
tags question: http://stackoverflow.com/q/47878076
type: Tag
tags question: http://stackoverflow.com/q/47909457
tags question: http://stackoverflow.com/q/48010835
tags question: http://stackoverflow.com/q/47979906
tags question: http://stackoverflow.com/q/47959790
tags question: http://stackoverflow.com/q/48010792
tags question: http://stackoverflow.com/q/47896615
tags question: http://stackoverflow.com/q/47947145
tags question: http://stackoverflow.com/q/47880166
tags question: http://stackoverflow.com/q/47983379
tags question: http://stackoverflow.com/q/47898514
tags question: http://stackoverflow.com/q/48006939
tags question: http://stackoverflow.com/q/47960299
tags question: http://stackoverflow.com/q/47972513
tags question: http://stackoverflow.com/q/47953854
tags question: http://stackoverflow.com/q/47946856

http://stackoverflow.com/comment/82755922
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47894415
has text: I am not using my waypoint.py yet, am pretty new to pygame and python in general and am trying to figure out how to get my cars to move along waypoints i predefine. I already have movement, for example when i press '1', my car moves from left to right.

http://stackoverflow.com/q/47857950
favorite count: 0
type: Question
has body: I was parsing a binary file using python..I got the first few values correctly from the file. But when I try to read a hash string which is 32 bytes I am getting a wrong output output ( 32 bit is not posted here ) b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 What type of encoding Is the above text ? How can parse it right to string ?
tagged with: python
has comment: http://stackoverflow.com/comment/82681357
answer count: 1
tagged with: blockchain
has title: Byte string to string from binary file
has comment: http://stackoverflow.com/comment/82681656
downvote count: 1
has comment: http://stackoverflow.com/comment/82681453
upvote count: 0
has comment: http://stackoverflow.com/comment/82680277
type: UnansweredQuestion
tagged with: ubuntu
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/82680579
has answer: http://stackoverflow.com/a/47858519
has comment: http://stackoverflow.com/comment/82681331
score: -1

http://stackoverflow.com/a/47936163
has comment: http://stackoverflow.com/comment/82843308
score: 5
has comment: http://stackoverflow.com/comment/82842369
has comment: http://stackoverflow.com/comment/82843501
upvote count: 5
has comment: http://stackoverflow.com/comment/82843518
has comment: http://stackoverflow.com/comment/82841723
has body: serializers.py class UserDetailSerializer(ModelSerializer): relationship_to_user = SerializerMethodField() class Meta: model = User fields = [ 'id', 'relationship_to_user', ] def get_relationship_to_user(self, instance): request = self.context.get('request') if FriendshipRequest.objects.filter(from_user=request.user, to_user=instance).exists(): return 'Existed' else: return 'Not Existed' views.py class MyUser(RetrieveAPIView): serializer_class = UserDetailSerializer # you can override this method or not def retrieve(self, request, *args, **kwargs): to_user = self.get_object() serializer = UserDetailSerializer(to_user, context={'request': request}) return Response(serializer.data)
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82841785
downvote count: 0
has comment: http://stackoverflow.com/comment/82841818
has comment: http://stackoverflow.com/comment/82841807
type: Answer
has comment: http://stackoverflow.com/comment/82843465
has comment: http://stackoverflow.com/comment/82841809
accepted answer of: http://stackoverflow.com/q/47936083
answers question: http://stackoverflow.com/q/47936083

http://stackoverflow.com/a/47866685
answers question: http://stackoverflow.com/q/47865223
has comment: http://stackoverflow.com/comment/82709376
score: 0
has comment: http://stackoverflow.com/comment/82711803
type: Answer
has body: Suppose you parse your csv and already have a list with [(start, stop, index), ....] as [(int, int, float), ...] then you can sort it with the following: from operator import itemgetter data = sorted(data, key=itemgetter(2), reverse=True) This means that you sort by third position and return the result in reverse order from max to min. def nonoverlap(data): result = [data[0]] for cand in data[1:]: start, stop, _ = cand current_span = range(start, stop+1) for item in result: i, j, _ = item span = range(i, j+1) if (start in span) or (stop in span): break elif (i in current_span) or (j in current_span): break else: result.append(cand) return result Then with the above function you will obtain the desired result. For the provided snippet you will obtain [(504, 789, 9.68), (1024, 1257, 7.52)]. I use here the fact that you can use 1 in range(0, 10) which will return True. While this is a naive implementation, you can use it as a starting point. If you want to return only starts and stops replace the return line with return [i[:2] for i in result]. Note: Also I want to add that your code has a logical mistake. You make a decision after each comparison, but must make a decision after you have compared to all the elements already present in yours best_list. That is why (504, 789) and (1027, 1305) passes your test, but should not. I wish this note will help you.

http://stackoverflow.com/a/47972756
has comment: http://stackoverflow.com/comment/83507823
has comment: http://stackoverflow.com/comment/84006173
has comment: http://stackoverflow.com/comment/83554846
has comment: http://stackoverflow.com/comment/83445427
has comment: http://stackoverflow.com/comment/83446951
has body: I tried replicating the problem with the given intel, but it was impossible, so I created a small example (as close as possible to what's described in the question) - Also referred to as [SO]: How to create a Minimal, Reproducible Example (reprex (mcve)) (that should be included in the question BTW) So, the problem that I'm illustrating here, is: C++ Load the Python engine Load a Python module From that module, load a function which: Receives a (string) argument representing a file name Reads the file contents (text) and returns it In case of error, simply returns the file name Call that function Get the function call result I am using (on Win 10 x64 (10.0.16299.125)): Python 3.5.4 x64 VStudio 2015 Community Edition The structure consists of: VStudio project / solution Source file (main00.cpp (renamed it from main.cpp, but didn't feel like doing all the screenshots (containing it) all over again)) Python module (experiment_test.py) Test file (test_file.txt) main00.cpp: #include <iostream> #include <string> #if defined(_DEBUG) # undef _DEBUG # define _DEBUG_UNDEFINED #endif #include <Python.h> #if defined(_DEBUG_UNDEFINED) # define _DEBUG # undef _DEBUG_UNDEFINED #endif #define MOD_NAME "experiment_test" #define FUNC_NAME "function_name" #define TEST_FILE_NAME "..\\test_dir\\test_file.txt" using std::cout; using std::cin; using std::endl; using std::string; int cleanup(const string &text = string(), int exitCode = 1) { Py_Finalize(); if (!text.empty()) cout << text << endl; cout << "Press ENTER to return...\n"; cin.get(); return exitCode; } int main() { string fName = TEST_FILE_NAME, result; PyObject *pName = NULL, *pModule = NULL, *pDict = NULL, *pFunc = NULL, *pArgs = NULL, *pValue = NULL, *pResult = NULL; Py_Initialize(); pName = PyUnicode_FromString(MOD_NAME); if (pName == NULL) { return cleanup("PyUnicode_FromString returned NULL"); } pModule = PyImport_Import(pName); Py_DECREF(pName); if (pModule == NULL) { return cleanup(string("NULL module: '") + MOD_NAME + "…
has comment: http://stackoverflow.com/comment/83919670
has comment: http://stackoverflow.com/comment/83445627
upvote count: 7
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83020153
accepted answer of: http://stackoverflow.com/q/47942845
answers question: http://stackoverflow.com/q/47942845
type: Answer
has comment: http://stackoverflow.com/comment/83507479
has comment: http://stackoverflow.com/comment/83919483
downvote count: 0
score: 7
has comment: http://stackoverflow.com/comment/83375371

http://stackoverflow.com/a/47944046
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47936144
upvote count: 4
score: 4
has body: Turns out, all python configuration files are in standard ini format. https://en.wikipedia.org/wiki/INI_file Thus, for enabling syntax highlighting in pycharm, I had to follow the following steps. Right click setup.cfg file Select "Associate with File Type option" Select Ini
answers question: http://stackoverflow.com/q/47936144

http://stackoverflow.com/comment/82833715
type: Comment
type: QuestionComment
has text: Just one row with a single INSERT statement.
score: 0
comment on: http://stackoverflow.com/q/47931861

http://stackoverflow.com/q/47866482
tagged with: structure
upvote count: 1
has title: python ctypes: get pointed type from a pointer variable
tagged with: ctypes
has body: I have a structure which contains primitive fields (int, uint8, ...) and also pointers. These pointers often point to an array of different structures type in order to keep a deeply nested structure. For example in C: struct A { int field1; int field2; struct B *fields3; unsigned int countofb; } struct B { int anotherfield1; int anotherfield2; } In python with ctypes I create a wrapper of the structures A and B. iterating over _fields_ of structure A I reach the third field field3 and I get a ctype variable of type LP_struct_B . The question is, is there a way, a function, a method of ctypes that convert a pointer to the pointed type ? I need something like a=A() st=pointedtype(a.field3) # or also st = pointedtype2(LP_struct_B) #desired output: st = struct_B thanks
downvote count: 0
type: UnansweredQuestion
tagged with: pointers
tagged with: types
has answer: http://stackoverflow.com/a/47866671
answer count: 1
score: 1
favorite count: 0
type: Question
tagged with: python

http://stackoverflow.com/comment/82916580
type: Comment
type: QuestionComment
has text: These two users just seem definitely the same except for their class names. I think what you want is to determine users' permissions. In this case, you can just add a property named `permission` which could be `admin` or `normal user` or something else.
comment on: http://stackoverflow.com/q/47973490
score: 1

beautifulsoup
tags question: http://stackoverflow.com/q/47951987
tags question: http://stackoverflow.com/q/47912149
tags question: http://stackoverflow.com/q/47963586
tags question: http://stackoverflow.com/q/47968568
tags question: http://stackoverflow.com/q/48014229
tags question: http://stackoverflow.com/q/47968739
tags question: http://stackoverflow.com/q/47985750
tags question: http://stackoverflow.com/q/47910374
tags question: http://stackoverflow.com/q/47864803
tags question: http://stackoverflow.com/q/48003815
tags question: http://stackoverflow.com/q/47958281
tags question: http://stackoverflow.com/q/48004462
tags question: http://stackoverflow.com/q/47986874
tags question: http://stackoverflow.com/q/47959327
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/48005396
tags question: http://stackoverflow.com/q/47953076
tags question: http://stackoverflow.com/q/47946640
tags question: http://stackoverflow.com/q/47872975
tags question: http://stackoverflow.com/q/47914460
tags question: http://stackoverflow.com/q/47983921
tags question: http://stackoverflow.com/q/47879140
tags question: http://stackoverflow.com/q/47968108
tags question: http://stackoverflow.com/q/47971406
tags question: http://stackoverflow.com/q/47996863
tags question: http://stackoverflow.com/q/47958230
tags question: http://stackoverflow.com/q/47978702
tags question: http://stackoverflow.com/q/47941954
tags question: http://stackoverflow.com/q/47897109
tags question: http://stackoverflow.com/q/47863781
tags question: http://stackoverflow.com/q/47939702
tags question: http://stackoverflow.com/q/47964719
tags question: http://stackoverflow.com/q/47980622
tags question: http://stackoverflow.com/q/47950628
tags question: http://stackoverflow.com/q/47928608
tags question: http://stackoverflow.com/q/47880624
tags question: http://stackoverflow.com/q/47903134
tags question: http://stackoverflow.com/q/47920386
tags question: http://stackoverflow.com/q/47861065
tags question: http://stackoverflow.com/q/47909011
tags question: http://stackoverflow.com/q/47978623
tags question: http://stackoverflow.com/q/47955660
tags question: http://stackoverflow.com/q/47879574
tags question: http://stackoverflow.com/q/47928768
tags question: http://stackoverflow.com/q/47900151
tags question: http://stackoverflow.com/q/47947475
tags question: http://stackoverflow.com/q/47863031
tags question: http://stackoverflow.com/q/47913140
type: Tag
tags question: http://stackoverflow.com/q/47858650
tags question: http://stackoverflow.com/q/47978213
tags question: http://stackoverflow.com/q/48010839
tags question: http://stackoverflow.com/q/47886090
tags question: http://stackoverflow.com/q/47890071
tags question: http://stackoverflow.com/q/47918306
tags question: http://stackoverflow.com/q/47869382
tags question: http://stackoverflow.com/q/47929402
tags question: http://stackoverflow.com/q/47965265
tags question: http://stackoverflow.com/q/47935298
tags question: http://stackoverflow.com/q/47856273
tags question: http://stackoverflow.com/q/47956702
tags question: http://stackoverflow.com/q/47925511
tags question: http://stackoverflow.com/q/47867589
tags question: http://stackoverflow.com/q/47985869
tags question: http://stackoverflow.com/q/47955558
tags question: http://stackoverflow.com/q/47970818
tags question: http://stackoverflow.com/q/47881857
tags question: http://stackoverflow.com/q/47883911
tags question: http://stackoverflow.com/q/47878402
tags question: http://stackoverflow.com/q/47939632
tags question: http://stackoverflow.com/q/47987345
tags question: http://stackoverflow.com/q/47948298
tags question: http://stackoverflow.com/q/47994573
tags question: http://stackoverflow.com/q/47873388
tags question: http://stackoverflow.com/q/47861821
tags question: http://stackoverflow.com/q/47908234
tags question: http://stackoverflow.com/q/47900991
tags question: http://stackoverflow.com/q/47908372
tags question: http://stackoverflow.com/q/47961214
tags question: http://stackoverflow.com/q/47977846

http://stackoverflow.com/q/47893288
tagged with: sed
upvote count: 1
tagged with: perl
tagged with: awk
has comment: http://stackoverflow.com/comment/82765189
has body: I have a typical .json file for Chef e.g. servername.json { "name": "myserver123", "chef_environment": "test", "run_list": [ "role[base-pkg]", "role[interesting_stuff]", "role[user_apps]" ] } What I would like to do is use a "one liner" to add a new role after the last role found in the file. Since I never know what roles or how many are in a file i thought to search for the final closing "]" bracket and add the new role above that. I tried the following: tac servername.json | sed -i '0,/\]/a "role[My_New_Role]"' thinking that this would find the (now) first "]" and add the new line after it. However when I run the cmd it adds the line "role[My_New_Role]" 3 times. Twice before the "]" and once in the correct place after the "]" Questions: 1) Why is the line added 3 times when the "0" says match once ? 2) Would this be better done using AWK, Perl or Python (2.7.5) ? How ? 3) Should I use regex lookahead/behind instead of tac ? 4) Since I will need to process the file again to add a comma to the second to last role perhapes my whole approach is wrong ? What would be a better approach ?
has answer: http://stackoverflow.com/a/47893538
accepted answer: http://stackoverflow.com/a/47893538
favorite count: 0
possible better answer: http://stackoverflow.com/a/47894338
linked to: http://stackoverflow.com/q/41842875
tagged with: chef-infra
has title: Add a new role to a Chef .json file with Sed
has comment: http://stackoverflow.com/comment/82755601
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47894338

http://stackoverflow.com/q/47882420
tagged with: wolfram-mathematica
has comment: http://stackoverflow.com/comment/82740130
tagged with: matlab
has comment: http://stackoverflow.com/comment/82730590
downvote count: 3
score: -3
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82738162
type: Question
has answer: http://stackoverflow.com/a/47882579
upvote count: 0
has comment: http://stackoverflow.com/comment/82741048
answer count: 1
has comment: http://stackoverflow.com/comment/82730595
accepted answer: http://stackoverflow.com/a/47882579
favorite count: 0
has title: Collect Specific Rows from txt file
has body: sample of the txt file I want to extract the whole lines from a txt file which has NVSS keyword and export it as a new txt file but I have no idea how to do this. Thank you
tagged with: python

http://stackoverflow.com/a/47986015
accepted answer of: http://stackoverflow.com/q/47985981
answers question: http://stackoverflow.com/q/47985981
type: Answer
has comment: http://stackoverflow.com/comment/82942872
score: 2
has body: There are two steps: To get the key with the max value of a dictionary you can do best = max(keywords, key=keywords.get). This will get the max value of the dictionary, as it uses the key to get the value for each item in the dictionary. Then you can simply check if its within your bounds: return best if .89 &lt; keywords[best] &lt; 1 else []. This will return an empty array if the value is not between .89 and 1
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47954604
linked to: http://stackoverflow.com/q/25062969
downvote count: 1
upvote count: 6
has answer: http://stackoverflow.com/a/47984008
type: Question
answer count: 2
score: 5
tagged with: python
favorite count: 0
tagged with: selenium-webdriver
has answer: http://stackoverflow.com/a/48012718
has title: time.sleep gives desired scrape but wait until does not
type: UnansweredQuestion
has body: Why is it when I add time.sleep(2), I get my desired output but if I add wait until specific xpath it gives less results? Output with time.sleep(2) (also desired): Adelaide Utd Tottenham Dundee Fc ... Count: 145 names Remove time.sleep Adelaide Utd Tottenham Dundee Fc ... Count: 119 names I have added: clickMe = wait(driver, 13).until(EC.element_to_be_clickable((By.CSS_SELECTOR, ("#page-container &gt; div:nth-child(4) &gt; div &gt; div.ubet-sports-section-page &gt; div &gt; div:nth-child(2) &gt; div &gt; div &gt; div:nth-child(1) &gt; div &gt; div &gt; div.page-title-new &gt; h1")))) As this element is present on all pages. Seems to be significantly less. How can I get around this issue? Script: import csv import os from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.ui import WebDriverWait as wait driver = webdriver.Chrome() driver.set_window_size(1024, 600) driver.maximize_window() driver.get('https://ubet.com/sports/soccer') clickMe = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, ('//select[./option="Soccer"]/option')))) options = driver.find_elements_by_xpath('//select[./option="Soccer"]/option') indexes = [index for index in range(len(options))] for index in indexes: try: try: zz = wait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, '(//select/optgroup/option)[%s]' % str(index + 1)))) zz.click() except StaleElementReferenceException: pass from selenium.webdriver.support.ui import WebDriverWait def find(driver): pass from selenium.common.exceptions import StaleElementReferenceException, NoSuchElementException import time clickMe = wait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, ("#page-container &gt; div:nth-child(4) &gt; div &gt; div.ubet-sports-section-page &gt; div &gt; div:nth-…
has comment: http://stackoverflow.com/comment/83091846
tagged with: selenium

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

http://stackoverflow.com/q/47892471
has answer: http://stackoverflow.com/a/47910712
has body: I am quite new to django and python, and I have an issue using methods and define them properly. I would like to store calculation in a method .. and call that method in another method here is how it looks : def get_info_array(self, format=None, *args, **kwargs): current_response_list = get_current_team(self) member_info_array = [] for response_dic in current_response_list: current_response = list(response_dic.values())[0] chunk_score = get_chunk_score3() print(chunk_score) return chunk_score def get_chunk_score3(self, format=None, *args, **kwargs): answer_question1 = current_response.answers.get(question_id = 2) answer_question2 = current_response.answers.get(question_id = 3) json_answer_question1 = json.loads(answer_question1.body) json_answer_question2 = json.loads(answer_question2.body) answer_key_question1 = list(json_answer_question1.keys())[0][0] answer_key_question2 = list(json_answer_question2.keys())[0][0] if answer_key_question1 == "1" or "3": score1 = list(json_answer_question1.values())[0] else: score1 = -list(json_answer_question1.values())[0] if answer_key_question2 == "1" or "3": score2 = list(json_answer_question2.values())[0] else: score2 = -list(json_answer_question2.values())[0] chunk_score = math.ceil((score1+score2)/2) return chunk_score when I try to run that code I get that in current_response in get_chunk_score3 is not define, how can I access variable from other methods ? Any tips is well welcome to progress. edit: complete code : class EmployeeChartData(APIView): #import pdb; pdb.set_trace() queryset = MyUser.objects.all() serializer_class = MyUserSerializer permission_classes = [] http_method_names = ['get',] #authentication_classes = [] #permission_classes = [] #serializer_class = MyUserSerializer def get_serializer_class(self): return self.serializer_class def get(self, request, format=None, *args, **kwargs): chunk2 = get_chunk_score2(self) info2 = get_info_relationship2(self) rep_system2 = get_rep_system2(self) reality = get_reality_st…
has comment: http://stackoverflow.com/comment/82770072
score: 0
answer count: 2
linked to: http://stackoverflow.com/q/31707546
has comment: http://stackoverflow.com/comment/82751503
has comment: http://stackoverflow.com/comment/82786440
has title: Accessing variables from other methods in a django app
tagged with: python
has comment: http://stackoverflow.com/comment/82758263
has answer: http://stackoverflow.com/a/47911674
has comment: http://stackoverflow.com/comment/82751462
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/82790375
type: Question
has comment: http://stackoverflow.com/comment/82758208
has comment: http://stackoverflow.com/comment/82758518

http://stackoverflow.com/a/47937685
has comment: http://stackoverflow.com/comment/127924968
answers question: http://stackoverflow.com/q/47937566
downvote count: 0
has comment: http://stackoverflow.com/comment/83039014
has comment: http://stackoverflow.com/comment/82906915
has comment: http://stackoverflow.com/comment/104067341
type: Answer
score: 13
upvote count: 13
has body: Django is a python framework for backend operations. It's purpose is to process http requests, hence your question "from the moment where the user input the search criteria until the relevant information are loaded/displayed" is very vague in this context. Your question suggests you are looking at some interactive Javascript/Ajax based frontend? If you are curious about render times for individual http requests, you may approach this with a custom middleware, something along these lines: class StatsMiddleware(object): def process_request(self, request): "Start time at request coming in" request.start_time = time.time() def process_response(self, request, response): "End of request, take time" total = time.time() - request.start_time # Add the header. response["X-total-time"] = int(total * 1000) return response Then, add this middleware in the corresponding Django settings.py section: MIDDLEWARE_CLASSES = ( ... 'app.stats.StatsMiddleware', ... ) The time it took to produce the response will be added to a custom http header "X-total-time". Note this will involve all rendering, calculation, 3rd party system and DB ops.

python-3.x
tags question: http://stackoverflow.com/q/47969842
tags question: http://stackoverflow.com/q/47971968
tags question: http://stackoverflow.com/q/47895351
tags question: http://stackoverflow.com/q/47950571
tags question: http://stackoverflow.com/q/47952308
tags question: http://stackoverflow.com/q/47914388
tags question: http://stackoverflow.com/q/47910355
tags question: http://stackoverflow.com/q/47984024
tags question: http://stackoverflow.com/q/47877338
tags question: http://stackoverflow.com/q/47909793
tags question: http://stackoverflow.com/q/47869526
tags question: http://stackoverflow.com/q/47971794
tags question: http://stackoverflow.com/q/47917242
tags question: http://stackoverflow.com/q/48011502
tags question: http://stackoverflow.com/q/47977251
tags question: http://stackoverflow.com/q/47965487
tags question: http://stackoverflow.com/q/47884390
tags question: http://stackoverflow.com/q/47857713
tags question: http://stackoverflow.com/q/48002240
tags question: http://stackoverflow.com/q/47963739
tags question: http://stackoverflow.com/q/47956169
tags question: http://stackoverflow.com/q/47999145
tags question: http://stackoverflow.com/q/47877144
tags question: http://stackoverflow.com/q/47985058
tags question: http://stackoverflow.com/q/47957712
tags question: http://stackoverflow.com/q/47862036
tags question: http://stackoverflow.com/q/47903414
tags question: http://stackoverflow.com/q/47973216
tags question: http://stackoverflow.com/q/48009911
tags question: http://stackoverflow.com/q/47906761
tags question: http://stackoverflow.com/q/47885300
tags question: http://stackoverflow.com/q/47900005
tags question: http://stackoverflow.com/q/47955375
tags question: http://stackoverflow.com/q/47899901
tags question: http://stackoverflow.com/q/47954300
tags question: http://stackoverflow.com/q/48006078
tags question: http://stackoverflow.com/q/47907059
tags question: http://stackoverflow.com/q/47907076
tags question: http://stackoverflow.com/q/47881270
tags question: http://stackoverflow.com/q/47917286
tags question: http://stackoverflow.com/q/47960190
tags question: http://stackoverflow.com/q/48006671
tags question: http://stackoverflow.com/q/47957962
tags question: http://stackoverflow.com/q/47950320
tags question: http://stackoverflow.com/q/47878846
tags question: http://stackoverflow.com/q/47972274
tags question: http://stackoverflow.com/q/47856472
tags question: http://stackoverflow.com/q/47924996
tags question: http://stackoverflow.com/q/48009878
tags question: http://stackoverflow.com/q/47934409
tags question: http://stackoverflow.com/q/47978625
tags question: http://stackoverflow.com/q/47895699
tags question: http://stackoverflow.com/q/47934222
tags question: http://stackoverflow.com/q/48003894
tags question: http://stackoverflow.com/q/48012824
tags question: http://stackoverflow.com/q/48010702
tags question: http://stackoverflow.com/q/47995210
tags question: http://stackoverflow.com/q/47857297
tags question: http://stackoverflow.com/q/47941191
tags question: http://stackoverflow.com/q/47972958
tags question: http://stackoverflow.com/q/47968578
tags question: http://stackoverflow.com/q/48012513
tags question: http://stackoverflow.com/q/47994603
tags question: http://stackoverflow.com/q/47947082
tags question: http://stackoverflow.com/q/47951637
tags question: http://stackoverflow.com/q/47935881
tags question: http://stackoverflow.com/q/47951760
tags question: http://stackoverflow.com/q/47917657
tags question: http://stackoverflow.com/q/47908781
tags question: http://stackoverflow.com/q/47899103
tags question: http://stackoverflow.com/q/47981362
tags question: http://stackoverflow.com/q/47909971
tags question: http://stackoverflow.com/q/47981933
tags question: http://stackoverflow.com/q/47995054
tags question: http://stackoverflow.com/q/47899347
tags question: http://stackoverflow.com/q/47954529
tags question: http://stackoverflow.com/q/47922801
tags question: http://stackoverflow.com/q/47930431
tags question: http://stackoverflow.com/q/47871270
tags question: http://stackoverflow.com/q/47866058

http://stackoverflow.com/q/47886401
tagged with: multi-index
downvote count: 1
possible better answer: http://stackoverflow.com/a/47886433
type: Question
score: 10
has answer: http://stackoverflow.com/a/47886432
has title: Selecting rows in a MultiIndex dataframe by index without losing any levels
answer count: 3
tagged with: pandas
favorite count: 0
has body: I would like to select a row called 'Mid', without losing it's index 'Site' Following code shows the dataframe: m.commodity price max maxperstep Site Commodity Type Mid Biomass Stock 6.0 inf inf CO2 Env 0.0 inf inf Coal Stock 7.0 inf inf Elec Demand NaN NaN NaN Gas Stock 27.0 inf inf Hydro SupIm NaN NaN NaN Lignite Stock 4.0 inf inf Slack Stock 999.0 inf inf Solar SupIm NaN NaN NaN Wind SupIm NaN NaN NaN North Biomass Stock 6.0 inf inf CO2 Env 0.0 inf inf Coal Stock 7.0 inf inf Elec Demand NaN NaN NaN Gas Stock 27.0 inf inf Hydro SupIm NaN NaN NaN Lignite Stock 4.0 inf inf Slack Stock 999.0 inf inf Solar SupIm NaN NaN NaN Wind SupIm NaN NaN NaN South Biomass Stock 6.0 inf inf CO2 Env 0.0 inf inf Coal Stock 7.0 inf inf Elec Demand NaN NaN NaN Gas Stock 27.0 inf inf Hydro SupIm NaN NaN NaN Lignite Stock 4.0 inf inf Slack Stock 999.0 inf inf Solar SupIm NaN NaN NaN Wind SupIm NaN NaN NaN desired outcome would be following: price max maxperstep Site Commodity Type Mid Biomass Stock 6.0 inf inf CO2 Env 0.0 inf inf Coal Stock 7.0 inf inf Elec Demand NaN NaN NaN Gas Stock 27.0 inf inf Hydro SupIm NaN NaN NaN Lignite Stock 4.0 inf inf Slack Stock 999.0 inf inf Solar SupIm NaN NaN NaN Wind SupIm NaN NaN NaN following answers give the desired outcome: m.commodity.xs('Mid', drop_level=False) m.commodity.loc'Mid' m.commodity.loc['Mid', :, :] ty MaxU, COLDSPEED and jezrael for the answers :)
linked to: http://stackoverflow.com/q/28757389
tagged with: python
has answer: http://stackoverflow.com/a/47886464
upvote count: 11
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47886433
linked to: http://stackoverflow.com/q/31593201
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/47886464

http://stackoverflow.com/a/47860321
answers question: http://stackoverflow.com/q/47860292
has comment: http://stackoverflow.com/comment/82685843
has body: IIUC: first make sure that the date column is of datetime dtype: df['date'] = pd.to_datetime(df['date'], errors='coerce') then you can group, sum and unstack: In [289]: (df.groupby(['name', pd.Grouper(freq='W', key='date')]) ['number'] .sum() .unstack(fill_value=0)) Out[289]: date 2017-01-01 2017-01-08 2017-01-15 name a 0 8 20 b 0 9 12 c 4 8 2 d 0 5 2 or as proposed by @thanasissdr: In [328]: (df.groupby(['name', pd.Grouper(freq='W', key='date', closed='left')]) ['number'] .sum() .unstack(fill_value=0)) Out[328]: date 2017-01-08 2017-01-15 name a 4 24 b 6 15 c 12 2 d 5 2 or In [330]: (df.assign(date=df['date']-pd.offsets.Day(7)) ...: .groupby(['name', pd.Grouper(freq='W', key='date', closed='left')]) ...: ['number'] ...: .sum() ...: .unstack(fill_value=0)) ...: Out[330]: date 2017-01-01 2017-01-08 name a 4 24 b 6 15 c 12 2 d 5 2
has comment: http://stackoverflow.com/comment/82685717
has comment: http://stackoverflow.com/comment/82685559
has comment: http://stackoverflow.com/comment/82685822
type: Answer
accepted answer of: http://stackoverflow.com/q/47860292
upvote count: 5
score: 5
has comment: http://stackoverflow.com/comment/82685490
downvote count: 0
has comment: http://stackoverflow.com/comment/82685517
has comment: http://stackoverflow.com/comment/82685796
type: AcceptedAnswer

http://stackoverflow.com/q/47893426
has answer: http://stackoverflow.com/a/47893500
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/82753456
has comment: http://stackoverflow.com/comment/82753486
score: 0
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/82753797
downvote count: 1
has comment: http://stackoverflow.com/comment/82753542
accepted answer: http://stackoverflow.com/a/47893500
has comment: http://stackoverflow.com/comment/82753681
has body: I have some text that looks like so, PIN ABC DIRECTION IN; PORT RECT 10 20 20 40; END END ABC PIN ABC2 DIRECTION OUT; PORT RECT 10 20 20 40; END END ABC2 I need to extract the block of PIN definition that lives between PIN xxx and END xxx. I am trying to parse the text file with regex and I am not getting the desired result since I have nested END statement. with open(f,'r') as fh: all = fh.read() re.search('PIN(.*)END', all, re.DOTALL) I really need to search for PIN xxx and END xxx as block markers Is there a way
type: AnsweredQuestion
has title: Matching blocks of text
has comment: http://stackoverflow.com/comment/82753519
favorite count: 0
tagged with: python-3.x
type: Question

http://stackoverflow.com/comment/82959864
has text: better post the actual code then.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47982933

http://stackoverflow.com/q/47985931
has answer: http://stackoverflow.com/a/47985980
has title: convert multiple text files to csv
favorite count: 0
has comment: http://stackoverflow.com/comment/82940804
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: text
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82940818
downvote count: 1
score: -1
has body: I have 3 text files in this example and would like to convert them to csv files : I can do it for one file but for multiple files i am aseeing errors after tweaking the code multiple times : import os import glob3 count =1 file_name = "COUNT16_DISTRIBUTION" + str(count*1) + ".txt" def data_parser(text, dic): for i, j in dic.iteritems(): text = text.replace(i,j) return text while count&lt;=3: for count in file_name: inputfile = open(file_name) outputfile = open("COUNT16_DISTRIBUTION" + str(count*1)+ '.csv', 'w') reps = {'"DUT 1"':' ', ' ':' ', ' ':' ' } for i in range(7): inputfile.next() count = count + 1 file_name = "COUNT16_DISTRIBUTION" + str(count * 1) + ".txt" for line in inputfile: outputfile.writelines(data_parser(line, reps)) inputfile.close() outputfile.close() In this particular case now i am running into problem because first i converted count to string and later i want to use it as integer in order to increment and check the condition. Any other thoughts or way to do it or any suggestions to improve this way ?
type: Question
upvote count: 0
answer count: 1

http://stackoverflow.com/comment/82692392
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47862462
has text: I just figured out the problem! I need to send cookies with my request!
type: AnswerComment

http://stackoverflow.com/comment/82940687
type: QuestionComment
has text: If you want handle all error msg not based on DRF,this is help.If you want keep DRF error just change format,this's not.Answer the question i ask you before,how do you handle `"username": [ "A user with that username already exists." ], "password": ["This field is required."] `,to `"promptmsg": [ "A user with that username already exists." ], "password": ["This field is required."] `?
comment on: http://stackoverflow.com/q/47985717
score: 0
type: Comment

http://stackoverflow.com/q/47913079
tagged with: clr
tagged with: python
upvote count: 29
answer count: 4
has answer: http://stackoverflow.com/a/49622800
has body: Am trying to use clr.AddReference and clr.AddReferenceToFile to import an assembly, but python(2.7) keeps making this error: Traceback (most recent call last): File "&lt;pyshell#5&gt;", line 1, in &lt;module&gt; clr.AddReference("UnityEngine") AttributeError: 'module' object has no attribute 'AddReference' Can anyone tell me how to fix this.
score: 29
tagged with: ironpython
has title: Python: AttributeError: 'module' object has no attribute 'AddReference'?
type: Question
has answer: http://stackoverflow.com/a/49352377
tagged with: .net
has answer: http://stackoverflow.com/a/75598805
tagged with: python.net
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/65056541
type: UnansweredQuestion

http://stackoverflow.com/a/47889626
has comment: http://stackoverflow.com/comment/82746537
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47889011
has comment: http://stackoverflow.com/comment/82746434
has body: fileListA and fileListB are global variables. In functions SetFilePath1 and SetFilePath2 you create local variables fileListA and fileListB. You have to use global in functions to inform them that you want to assign to global variables. BTW: you don't have to use global if you only get value from global variable - like in Calculate. fileListA = "" # it is global variable (automatically) fileListB = "" # it is global variable (automatically) def SetFilePath1(): global fileListA # inform function to assign value (when you use `=`) # to external variable instead of creating local variable #Getting the file from PC filepath = fd.askopenfilename(filetypes =(('Excel Files', '.xls'), ('Excel Files','*.xlsx')),parent=root) if isinstance(filepath, str): fileListA = filepath.split(" ") elif isinstance(filepath, tuple): fileListA = list(filepath) elif isinstance(filepath, list): fileListA = filepath def SetFilePath2(): global fileListB # inform function to assign value (when you use `=`) # to external variable instead of creating local #Getting the file from PC filepath = fd.askopenfilename(filetypes =(('Excel Files', '.xls'), ('Excel Files','*.xlsx')),parent=root) if isinstance(filepath, str): fileListB = filepath.split(" ") elif isinstance(filepath, tuple): fileListB = list(filepath) elif isinstance(filepath, list): fileListB = filepath def Calculate(): file1 = fileListA file2 = fileListB print("Inside Calculate") print(file1) # ... rest ...
answers question: http://stackoverflow.com/q/47889011
type: Answer

http://stackoverflow.com/q/47954552
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/82879598
has comment: http://stackoverflow.com/comment/82878389
has body: I have a dataframe with a column which represents customer name. I have made an ndarray with the customer names, and I trying to write a loop for i in customer.values: print df[df[cust_name == i]] But it gives me an error saying that the length should be the same. If I take a string value and assign it to i for one particular value, it works perfectly. I also tried to change the I type to a string, but I get the same issue. Any pointers on what I am doing wrong?
tagged with: dataframe
has title: Utilizing an array value in a for loop for data frames
has comment: http://stackoverflow.com/comment/82879683
has answer: http://stackoverflow.com/a/47955229
has comment: http://stackoverflow.com/comment/82878603
answer count: 1
has comment: http://stackoverflow.com/comment/82879438
tagged with: python
score: 0

http://stackoverflow.com/a/47970511
score: 0
type: Answer
has body: Since you are already passing on the csrf token from django.core.context_processors.csrf to the context manager. Check whether the form HTML has something like this or not: &lt;input type='hidden' name='csrfmiddlewaretoken' value="jqhdwjavwjagjzbefjwdjqlkkop2j3ofje" /&gt; A couple of other things are required to make the csrf protection work (check out the docs): Your browser has to accept cookies from your server Make sure you have 'django.middleware.csrf.CsrfViewMiddleware' included as middleware in your settings.py (alternatively use the decorator csrf_protect() on particular views you want to protect)
answers question: http://stackoverflow.com/q/47962592

http://stackoverflow.com/comment/83047961
comment on: http://stackoverflow.com/q/48012287
score: 1
has text: In my case, it is a multi-label classification so there is no possibility to think about the problem as Top-1 or Top-5 because one image have 19 different classes (not only one major one as applied in the multi-class classification). I've added the losses plots
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47872106
has comment: http://stackoverflow.com/comment/82710679
has comment: http://stackoverflow.com/comment/82709975
has title: Python - Decoding Error ('ascii' codec can't decode byte 0x94 in position 19.....)
has comment: http://stackoverflow.com/comment/82710202
tagged with: encode
accepted answer: http://stackoverflow.com/a/47872461
tagged with: python
type: AnsweredQuestion
tagged with: gzip
has comment: http://stackoverflow.com/comment/82709762
type: Question
tagged with: ascii
tagged with: decode
has comment: http://stackoverflow.com/comment/82709946
has body: Hello :) I have a big bin file which has been gzipped (so it's a blabla.bin.gz). I need to decompress and write it to a txt file with ascii format. Here's my code : import gzip with gzip.open("GoogleNews-vectors-negative300.bin.gz", "rb") as f: file_content = f.read() file_content.decode("ascii") output = open("new_file.txt", "w", encoding="ascii") output.write(file_content) output.close() But I got this error : file_content.decode("ascii") UnicodeDecodeError: 'ascii' codec can't decode byte 0x94 in position 19: ordinal not in range(128) I'm not so new to Python but format/coding problems have always been my greatest weakness :( Please, could you help me? Thank you !!!
has answer: http://stackoverflow.com/a/47872461
score: 0
has comment: http://stackoverflow.com/comment/82709861
has comment: http://stackoverflow.com/comment/82710643
answer count: 1

http://stackoverflow.com/comment/82869089
type: Comment
comment on: http://stackoverflow.com/a/47949588
score: 0
type: AnswerComment
has text: @Ryan ohh i didn't gave attention on that , i implemented my own logic , Now i see that when you pointed out , bdw `tuple(sorted(x))` is just little part , its not main logic.

http://stackoverflow.com/q/47995101
has answer: http://stackoverflow.com/a/48000520
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82964164
has comment: http://stackoverflow.com/comment/82958762
tagged with: tkinter
has comment: http://stackoverflow.com/comment/82960191
has comment: http://stackoverflow.com/comment/82960961
type: Question
has comment: http://stackoverflow.com/comment/82958365
has comment: http://stackoverflow.com/comment/82958498
has body: I'm working on a script using Tkinter and the Peewee ORM. I've got: db = SqliteDatabase('data.db') introspector = Introspector.from_database(db) models = introspector.generate_models() cities_list = [] account_obj = models['accounts'] recordset= account_obj.select() for r in recordset: city = str(r.city) elapsed_hours = (time.time()-int(r.datetime))/3600 cities_list.append(str(r.city)+'-'+str(elapsed_hours)) master = tk.Tk() variable = StringVar(master) variable.set(cities_list[0]) # default value w = OptionMenu(master, variable, *cities_list) w.pack() def ok(): print ("value is:" + variable.get()) v_list = variable.get().split('-') print type(account_obj) recordset = account_obj.select().where(account_obj.city.contains(v_list[0])).get() for r in recordset: r.datetime=int(time.time()) r.update() button = Button(master, text="OK", command=ok) button.pack() mainloop() At the second select statement: recordset = account_obj.select().where(account_obj.city.contains(v_list[0])).get() I'm getting : Traceback (most recent call last): &lt;class 'peewee.BaseModel'&gt; File "...lib\lib-tk\Tkinter.py", line 1542, in __call__ return self.func(*args) File "... myscript.py", line 46, in ok for r in recordset: TypeError: 'accounts' object is not iterable What am I doing wrong?
has comment: http://stackoverflow.com/comment/82961157
score: 0
tagged with: peewee
upvote count: 1
has comment: http://stackoverflow.com/comment/82967582
answer count: 1
downvote count: 1
favorite count: 0
has title: TypeError: 'accounts' object is not iterable

http://stackoverflow.com/q/48009911
answer count: 3
downvote count: 0
favorite count: 0
has title: Set Python Pub/Sub asynchronous pull subscriber threads count
has answer: http://stackoverflow.com/a/73129703
tagged with: google-cloud-pubsub
tagged with: python
tagged with: asynchronous
tagged with: python-3.x
upvote count: 3
has answer: http://stackoverflow.com/a/48017862
type: UnansweredQuestion
tagged with: multithreading
type: Question
score: 3
has body: I implemented asynchronous pull subscriber using Python. This is the basic code def receive_messages(project, subscription_name): subscriber = pubsub_v1.SubscriberClient() subscription_path = subscriber.subscription_path( project, subscription_name) def callback(message): print ("A") time.sleep(2) print('Received message: {}'.format(message)) message.ack() print ("B") subscriber.subscribe(subscription_path, callback=callback) print('Listening for messages on {}'.format(subscription_path)) while True: time.sleep(60) I need to print like A, message B A message B (I need to run sequentially) or receive messages via given no of threads. I don't find a way to limit no of threads. My program given Segmentation fault due to many threads. How I control no of threads to receive messages.
has answer: http://stackoverflow.com/a/55800668

http://stackoverflow.com/a/47897690
answers question: http://stackoverflow.com/q/47897457
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/47897457
score: 2
has body: Blocking when a multiprocessing.Queue is empty/full and get()/put() is called on it happens automatically. This behavior is transparent to calling functions. Use self._worker.daemon = True before self._worker.start() so the worker(s) will automatically be killed when main process exits
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/82771061
type: Comment
comment on: http://stackoverflow.com/a/47902028
type: AnswerComment
score: 0
has text: But `str("u'date'")` is still `"u'date'"`.

http://stackoverflow.com/a/47986095
downvote count: 0
has comment: http://stackoverflow.com/comment/82965229
answers question: http://stackoverflow.com/q/47985981
has comment: http://stackoverflow.com/comment/82969842
type: Answer
score: 1
has body: max((k for k, v in keywords.items() if .89 &lt; v &lt; 1), default=None, key=keywords.get) # 'dog' The first argument filters the dictionary for items that meet the condition, i.e. .89 &lt; v &lt; 1. The second argument is a default value that is returned if no items meet the condition, e.g. {u'dog': 0.88628395, u'cat': 0.87454434} -&gt; None. The last argument is a key function that applies max() to the values of the original dictionary.
has comment: http://stackoverflow.com/comment/82969920
upvote count: 1

http://stackoverflow.com/comment/82723602
comment on: http://stackoverflow.com/q/47878705
has text: no prob will update display
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47940238
score: -1
has answer: http://stackoverflow.com/a/47940420
type: UnansweredQuestion
tagged with: bigdata
has body: I have a .csv file of about 100 GB and want to split it into 1 GB files with python 3.5.4 (for the record :) ). I have written the function split_csv('filename.csv') below. My question is how can I make it faster. That is needed, because I will be regularly splitting new versions of the huge .csv file. Notes (contain edits): I want to do it on disk. It cannot fit into RAM. The 1GB .csv files should be split where the line ends. So they will be "about" 1GB. Not exactly. import os import pandas as pd import csv import time def split_csv(file,filesize=1000, header='T'): start = time.time() with open(file, 'r', encoding='utf8', newline='') as infile: datareader = csv.reader(infile) outfile_iterator=100001 outfilename = file.split('.')[0] outfilename = outfilename+'_'+str(outfile_iterator)+'.csv' o = open(outfilename, 'w',newline='') outfile = csv.writer(o, delimiter=',', lineterminator="\r\n") print('writing to ',outfilename) total_row_count=0 row_count = 0 for row in datareader: if header=='T' and total_row_count==0: header_row=row print('header: ',header_row) outfile.writerow(row) row_count = row_count + 1 total_row_count=total_row_count+1 if os.stat(outfilename).st_size &gt; (filesize*1048576) : print('rowcount: ',row_count) row_count = 0 o.close() outfile_iterator = outfile_iterator + 1 outfilename = file.split('.')[0] outfilename = outfilename+'_'+str(outfile_iterator)+'.csv' o = open(outfilename, 'w',newline='') outfile = csv.writer(o, delimiter=',', lineterminator="\r\n") print('writing to ',outfilename) if header=='T': outfile.writerow(header_row) print('header: ',header_row) print('rowcount: ',row_count) infile.close() o.close() elapsed = (time.time() - start) print(elapsed, " seconds")
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/82849915
upvote count: 0
answer count: 1
has title: Fast splitting huge .csv onto disk with python
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python

http://stackoverflow.com/comment/82808375
has text: Thanks for that, could you propose an alternative to `eval` that will be less risky for my example?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47920334

http://stackoverflow.com/comment/107886601
comment on: http://stackoverflow.com/q/47887746
score: 0
has text: See these answers: https://stackoverflow.com/questions/26577516/how-to-test-if-a-string-contains-one-of-the-substrings-in-a-list-in-pandas/60980656#60980656
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82832020
type: QuestionComment
comment on: http://stackoverflow.com/q/47931233
has text: I'm not familiar with tweepy (looks like fun though, I'll have to try it). but maybe check out page 6-7 here: http://coding2day.com/TwitterPython.pdf
score: 0
type: Comment

http://stackoverflow.com/comment/82845636
type: Comment
comment on: http://stackoverflow.com/a/47935352
type: AnswerComment
has text: I checked xpath version, and it is 1.0. Is it possible to do the same with xpath 1.0? Anyway, thanks for your response
score: 0

http://stackoverflow.com/q/47958584
has comment: http://stackoverflow.com/comment/82893960
has comment: http://stackoverflow.com/comment/82921295
has comment: http://stackoverflow.com/comment/82893588
has comment: http://stackoverflow.com/comment/82899485
score: 0
has comment: http://stackoverflow.com/comment/82894067
has comment: http://stackoverflow.com/comment/82894390
has comment: http://stackoverflow.com/comment/82899461
has comment: http://stackoverflow.com/comment/82891722
has comment: http://stackoverflow.com/comment/82894099
has comment: http://stackoverflow.com/comment/82894429
has comment: http://stackoverflow.com/comment/82891736
type: UnansweredQuestion
tagged with: encryption
tagged with: python
has comment: http://stackoverflow.com/comment/82894064
answer count: 0
has title: Python MYSQL store AES BINARY
has body: I have a MYSQL table which I access from python, this table must keep the username, password and email encrypted. I'm encrypting the name and email using aes crypto. And argon2 for the password. My table is on a cloud server and was created with direct MYSQL command: CREATE TABLE members(member SMALLINT UNIQUE PRIMARY KEY NOT NULL AUTO_INCREMENT, name BINARY(35) NOT NULL, pseudonym VARCHAR(20) NOT NULL, password BINARY(16) NOT NULL, gender CHAR(1) NOT NULL, birthday DATE NOT NULL, email BINARY(40) NOT NULL); I'm having problems with the size of the encrypted blocks, some of them are of 1 byte and others of 3 bytes or that's what I'm understanding. This is my python query: member_id = i_member name = aes_encrypt('Name First second') pseudonym = 'lala' gender = 'm' birthday = '2017-12-12' email = aes_encrypt('email@email.com') password = ph.hash("password") self.cur.execute("INSERT IGNORE INTO members VALUES(%s,%s,%s,%s,%s,%s,%s)", (member_id, name, pseudonym, password, gender, birthday, email)) self.con.commit() The output error is: [22:34:21] SQLCloudDb.py:155: Warning: (1300, "Invalid utf8 character string: 'C8CCA6'") member_id, name, pseudonym, password, gender, birthday, height, weight, email, )) ... Similar to password and email If I go to my cloud SQL I can see the inserted members but seems like they have been trimmed, the columns look odd, maybe because some of these bytes are a CLRL?? The following picture includes more columns than my posted code. Every help is appreciated Thanks :)
tagged with: mysql
type: Question

http://stackoverflow.com/a/47978609
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47978384
answers question: http://stackoverflow.com/q/47978384
type: Answer
has body: RDDs are not indexed, in majority of cases don't guarantee the order and don't support efficient single item access. You can zipWithIndex and filter. zipWithIndex, swap elements and lookup. but this is not advised, requires linear scan, and might have non-deterministic behavior.
score: 1
upvote count: 1

django
tags question: http://stackoverflow.com/q/47937813
tags question: http://stackoverflow.com/q/47888003
tags question: http://stackoverflow.com/q/47856300
tags question: http://stackoverflow.com/q/47955544
tags question: http://stackoverflow.com/q/47983474
tags question: http://stackoverflow.com/q/47931241
tags question: http://stackoverflow.com/q/47954451
tags question: http://stackoverflow.com/q/47860672
tags question: http://stackoverflow.com/q/47916030
tags question: http://stackoverflow.com/q/47893991
tags question: http://stackoverflow.com/q/47950507
tags question: http://stackoverflow.com/q/47859554
tags question: http://stackoverflow.com/q/48007982
tags question: http://stackoverflow.com/q/47903011
tags question: http://stackoverflow.com/q/47879965
tags question: http://stackoverflow.com/q/47949022
tags question: http://stackoverflow.com/q/47944443
tags question: http://stackoverflow.com/q/47956902
tags question: http://stackoverflow.com/q/47999929
tags question: http://stackoverflow.com/q/47924357
tags question: http://stackoverflow.com/q/47962580
tags question: http://stackoverflow.com/q/47873707
tags question: http://stackoverflow.com/q/47968231
tags question: http://stackoverflow.com/q/47979710
tags question: http://stackoverflow.com/q/47968535
tags question: http://stackoverflow.com/q/47878367
tags question: http://stackoverflow.com/q/47922700
tags question: http://stackoverflow.com/q/47912530
tags question: http://stackoverflow.com/q/47910907
tags question: http://stackoverflow.com/q/47977485
tags question: http://stackoverflow.com/q/47919913
tags question: http://stackoverflow.com/q/47994336
tags question: http://stackoverflow.com/q/47996392
tags question: http://stackoverflow.com/q/47949807
tags question: http://stackoverflow.com/q/47892002
tags question: http://stackoverflow.com/q/47961349
tags question: http://stackoverflow.com/q/47861521
tags question: http://stackoverflow.com/q/47971506
tags question: http://stackoverflow.com/q/47952609
tags question: http://stackoverflow.com/q/47957230
tags question: http://stackoverflow.com/q/47917291
tags question: http://stackoverflow.com/q/47890241
tags question: http://stackoverflow.com/q/48007916
tags question: http://stackoverflow.com/q/47955849
tags question: http://stackoverflow.com/q/47947999
tags question: http://stackoverflow.com/q/47930411
tags question: http://stackoverflow.com/q/47892208
tags question: http://stackoverflow.com/q/47861212
tags question: http://stackoverflow.com/q/47907784
type: Tag
tags question: http://stackoverflow.com/q/47937256
tags question: http://stackoverflow.com/q/47895053
tags question: http://stackoverflow.com/q/47968310
tags question: http://stackoverflow.com/q/47903042
tags question: http://stackoverflow.com/q/47889741
tags question: http://stackoverflow.com/q/47948203
tags question: http://stackoverflow.com/q/48003587
tags question: http://stackoverflow.com/q/47856921
tags question: http://stackoverflow.com/q/47860572
tags question: http://stackoverflow.com/q/47965482
tags question: http://stackoverflow.com/q/47884601
tags question: http://stackoverflow.com/q/47898868
tags question: http://stackoverflow.com/q/47878296
tags question: http://stackoverflow.com/q/47925867
tags question: http://stackoverflow.com/q/47858295
tags question: http://stackoverflow.com/q/47977653
tags question: http://stackoverflow.com/q/47904732
tags question: http://stackoverflow.com/q/47921552
tags question: http://stackoverflow.com/q/48000475
tags question: http://stackoverflow.com/q/47974935
tags question: http://stackoverflow.com/q/47865897
tags question: http://stackoverflow.com/q/47942308
tags question: http://stackoverflow.com/q/47904142
tags question: http://stackoverflow.com/q/47961670
tags question: http://stackoverflow.com/q/47952896
tags question: http://stackoverflow.com/q/47995159
tags question: http://stackoverflow.com/q/47949290
tags question: http://stackoverflow.com/q/47957499
tags question: http://stackoverflow.com/q/47859929
tags question: http://stackoverflow.com/q/47866503

http://stackoverflow.com/comment/82713323
comment on: http://stackoverflow.com/a/47873794
type: AnswerComment
score: 0
has text: And I thought Google was fast... thank you for the quick reply and the link to the documentation.
type: Comment

http://stackoverflow.com/comment/82996973
has text: Reddit has an API.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48014031
score: 1

http://stackoverflow.com/comment/82718084
comment on: http://stackoverflow.com/a/47862970
type: Comment
has text: @lisa If you read the `pip`, `pip3`, `pip3.5` in plain text, you will see they are all identical. My version does not come with `pip3` nor `pip3.5`. In this case, you don't need to create a symbolic link. You just need to put the whole folder in your `PATH`.
score: 0
type: AnswerComment

http://stackoverflow.com/q/47954451
has comment: http://stackoverflow.com/comment/82879549
has body: I have a project in AWS cloud9. When I tried to login via LinkedIn or Facebook, after pressing the "allow access" to my LinkedIn or Facebook account, I get this error page: Facebook: LinkedIn: Traceback: Environment: Request Method: GET Request URL: http://8011118167a14663bf26f276beae74fe.vfs.cloud9.us-east-2.amazonaws.com:80/complete/facebook/?redirect_state=s9F0XdwpzEpFx26DcClydCC2TI5gRICR&code=AQCHwhQV29jyqzxZ8_qtAQD6D_baKZvcdaMOL889co7q6N_rerhEvteJ3-1iE-vIhyX87qAHfCTN4XgoFF0IQT_MyWHsIf28ggfZt3IqUMXFODBsXaYY_PJJCvDRniv20gqMF9Pq1Lm2L1x-OFAOsqLsIboYZDrmG6ceFpADyzdKOXZRsy44uiXKhZIzht3VI45je8JbWowZJa-YUcRD1zY5OQnniW5ujq3IYe2l0z6nha6hq7Lk0lzLD5BR4I5O9sd7CdMxeRXX0NBmc9Qz4av2j2xsiHQq9zBASy03dSwENwQ2veIOhpQCMrIkkXwfNGQ&state=s9F0XdwpzEpFx26DcClydCC2TI5gRICR Django Version: 1.8.4 Python Version: 2.7.12 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_social_project', 'django_social_app', 'social.apps.django_app.default', 'facebook_auth') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Traceback: File "/usr/local/lib64/python2.7/site-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib64/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/usr/local/lib64/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func…
answer count: 0
type: UnansweredQuestion
has title: How to solve faceook/linkedin Authentication process canceled error?
tagged with: authentication
tagged with: django
linked to: http://stackoverflow.com/q/31958246
tagged with: cloud9
has comment: http://stackoverflow.com/comment/82888779
has comment: http://stackoverflow.com/comment/82897274
has comment: http://stackoverflow.com/comment/82880966
type: Question
score: 0
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/82897271
tagged with: python

http://stackoverflow.com/q/47990512
type: Question
tagged with: variables
has title: Difference between Python object reference and variables in cases of mutable and immutable objects
answer count: 2
favorite count: 0
has answer: http://stackoverflow.com/a/48000818
has body: I was reading a book on python: Once we have some data types, the next thing we need are variables in which to store them. Python doesn’t have variables as such, but instead has object references. When it comes to immutable objects like ints and strs, there is no discernable difference between a variable and an object reference. As for mutable objects, there is a difference, but it rarely matters in practice." Now it is not mentioned what is the difference and I am unable to clear myself on this concept. What is object reference (Is it the memory address for cpython)? Actually what is a variable is it a name that is bound to the object reference (my understanding of memory reference is, that it is a address in the memory for cpython, clear me on this if I am wrong). It will be helpful if it can be explained in the light of it's internal implementation in C and how are these things managed and working internally. Also it would be helpful if some resources may be provided that explain cpython implementation in detail.
upvote count: 2
type: UnansweredQuestion
tagged with: cpython
tagged with: python
has answer: http://stackoverflow.com/a/47990722
has comment: http://stackoverflow.com/comment/82949452
tagged with: object
score: 1
downvote count: 1
linked to: http://stackoverflow.com/q/986006

http://stackoverflow.com/comment/82722720
score: 0
type: Comment
has text: yes, in the other question (link in description) somebody else also came up with using dicts in a list. so basically now i have 2 ways to shorten my old way of open all the dicts. 1 = your solution (have to fully test it yet, but i do believe you know it works) 2 = putting all the dicts inside 1 list, and thus only dump and load from 1 txt file. the load part of this and assigning to unique dicts again i already have under control now
comment on: http://stackoverflow.com/a/47878288
type: AnswerComment

http://stackoverflow.com/comment/82824155
score: 0
type: AnswerComment
has text: Okay - with that I get `from ..cvImageUtils import ColorUtils ValueError: attempted relative import beyond top-level package`
type: Comment
comment on: http://stackoverflow.com/a/47927445

http://stackoverflow.com/comment/82882381
type: Comment
comment on: http://stackoverflow.com/a/47956445
score: 0
type: AnswerComment
has text: I can't believe it was such a simple fix - I've literally been searching for hours on how to fix this, Thank you Bernie! I will mark as correct answer as soon as this lets me - Merry Christmas!

http://stackoverflow.com/a/47992027
downvote count: 0
has body: I hope this will help you: for x in range(1,4): col_text = 'col' + str(x) + '_expense' print(getattr(obj,col_text).text)
type: Answer
has comment: http://stackoverflow.com/comment/82952404
upvote count: 1
answers question: http://stackoverflow.com/q/47991909
score: 1
has comment: http://stackoverflow.com/comment/82952342

http://stackoverflow.com/a/47938642
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/47937719
upvote count: 1
has body: You are attempting to plot a line plot of single values. This is the same as plt.plot([1],[5]) which does not show up, because a line needs two points at least to become a line. You may use a marker to display single points in case this is what you're after plt.plot([1],[5], marker="o")

http://stackoverflow.com/comment/82839840
comment on: http://stackoverflow.com/q/47935107
type: Comment
has text: yes that ffixed it, now the folder new is not being made, its moving the files but not to a newly created folder...
type: QuestionComment
score: 0

http://stackoverflow.com/q/47882151
upvote count: 4
answer count: 2
has answer: http://stackoverflow.com/a/47882220
has comment: http://stackoverflow.com/comment/82730148
downvote count: 0
favorite count: 0
has body: I have recently started studying python programming language and in the process come across the following statement : [1,2] &lt; [2,1] evaluating to True I seem not to figure out how the comparison is being done internally by python.
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47882220
possible better answer: http://stackoverflow.com/a/47882182
has answer: http://stackoverflow.com/a/47882182
has title: why does the statement [1,2] < [2,1] evaluate to True in python
type: Question
score: 4

http://stackoverflow.com/q/47965937
upvote count: 0
has answer: http://stackoverflow.com/a/47966015
favorite count: 0
tagged with: python
has body: i need to send a post request to this url : http://lastsecond.ir/hotels/ajax you can see the other parameters send by this request here: formdata: filter_score: sort:reviewed_at duration:0 page:1 base_location_id:1 request header: :authority:lastsecond.ir :method:POST :path:/hotels/ajax :scheme:https accept:*/* accept-encoding:gzip, deflate, br accept-language:en-US,en;q=0.9,fa;q=0.8,ja;q=0.7 content-length:67 content-type:application/x-www-form-urlencoded; charset=UTF-8 cookie:_jsuid=2453861291; read_announcements=,11,11; _ga=GA1.2.2083988810.1511607903; _gid=GA1.2.1166842676.1513922852; XSRF-TOKEN=[binary]%3D; lastsecond-session=[binary]%3D origin:https://lastsecond.ir referer:https://lastsecond.ir/hotels?score=&amp;page=1&amp;sort=reviewed_at&amp;duration=0 user-agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36 x-csrf-token:oMpQTG0wN0YveJIk2WhkesvzjZE2FqHkDqPiW8Dy x-requested-with:XMLHttpRequest the result of this code suppose to be a json file, by it redirect the request to the its parent url. i'm using scrapy with python to send this request, here is scrapy code : class HotelsSpider(scrapy.Spider): name = 'hotels' allowed_domains = ['lastsecond.ir'] start_urls = ['http://lastsecond.ir/hotels'] def parse(self, response): data = { 'filter_score': '', 'sort': 'reviewed_at', 'duration': '0', 'page': '1', 'base_location_id': '1' } headers = { 'user-agent': 'Mozilla/5.0', 'x-csrf-token': 'oMpQTG0wN0YveJIk2WhkesvzjZE2FqHkDqPiW8Dy', 'x-requested-with': 'XMLHttpRequest' } url = 'https://lastsecond.ir/hotels/ajax' return FormRequest( url=url, callback=self.parse_details, formdata=data, method="POST", headers=headers, dont_filter=True ) def parse_details(self, response): data = response.body_as_unicode() print(data) #f = open('output.json', 'w') #f.write(data) #f.close() i've changed my code so it gets the fresh csrf-token everytime it sends a request: class HotelsSpider(scrapy.Spider): name = 'hotels'…
has comment: http://stackoverflow.com/comment/82911676
type: UnansweredQuestion
downvote count: 3
tagged with: scrapy
tagged with: http
type: Question
has comment: http://stackoverflow.com/comment/82901918
has answer: http://stackoverflow.com/a/47966207
has comment: http://stackoverflow.com/comment/82910866
score: -3
has title: 302 Redirect in xhr request
has comment: http://stackoverflow.com/comment/82907260
answer count: 2

http://stackoverflow.com/comment/82889106
type: Comment
comment on: http://stackoverflow.com/a/47953205
has text: You need `result[result.index.get_level_valurs(0).str[-1] == 'a']` if need check first level of multindex and last character.
score: 1
type: AnswerComment

http://stackoverflow.com/comment/82736332
has text: I would recommend to get base64encode values and accept in database with text input, and while displaying it either create hard file of it and save OR you can directly put into image tag.
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/47885274

http://stackoverflow.com/q/48004264
has body: I'm unable to run my Python code from node.js. The following is the Python code I'd like to run: from preprocessor import pad_vec_sequences, labels from keras.models import load_model import spacy from preprocessor import nlp import numpy as np import sys from dependency_tree import to_nltk_tree , to_spacy_desc print('Hi') This code runs successfully from terminal using python demo.py and all the libraries are installed. I'm using python 3.5. Now I'd like to call this code from JS using: app.post( '/api/message', function(req, res) { PythonShell.run('demo.py', { args: [req.body.input.text], pythonPath : '/usr/bin/python3' }, function (err, results) { console.log(results); return res.json({ 'input' : { 'text' : '' }, 'output': { 'text': results //+ //'&lt;img src="http://localhost:8080/Finance/image1.jpg" class="imageclass"&gt;' } }) }); }); In the code above, I've set the pythonPath option to python3.5, and thus the python shell started by node.js is python3.5. I would expect the Python code to return Hi to JS. But this does not work. The JS does not receive any text from demo.py. If I remove all the import statements, the code works. On removing the import statements the Python code called successfully returns the Hi. So it looks like the Python code when called from JS does not work because of the import statements. But the same Python code works when called from terminal. I have also ensured that both cases use python3.5. What is the problem here? UPDATE: import sys print(sys.executable) ... outputs /usr/bin/python3. I have put this in the JS code for pythonPath but my code is still not working.
has title: import python statements not working when called from JS
upvote count: 1
tagged with: python-3.5
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82978289
has comment: http://stackoverflow.com/comment/82977817
tagged with: node.js
has comment: http://stackoverflow.com/comment/82976648
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/82977682
has comment: http://stackoverflow.com/comment/82977639
type: Question
score: 1
tagged with: javascript

http://stackoverflow.com/comment/82755226
type: AnswerComment
score: 0
type: Comment
has text: 'res' is a list of tagged documents and corresponding tags
comment on: http://stackoverflow.com/a/47892410

http://stackoverflow.com/comment/82807467
type: Comment
has text: also ... if my column is not normally distributed ... can I run CI on it?
score: 0
comment on: http://stackoverflow.com/a/47918727
type: AnswerComment

http://stackoverflow.com/a/75043123
answers question: http://stackoverflow.com/q/47994336
type: Answer
has body: Add the argument method You can add the method argument in every attribute like this: class SearchFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='icontains') is_dangerous = django_filters.BooleanFilter( widget=CheckboxInput(), method='unchecked_means_any_value', ) is_secret = django_filters.BooleanFilter( widget=CheckboxInput(), method='unchecked_means_any_value', ) is_active = django_filters.BooleanFilter( widget=CheckboxInput(), method='unchecked_means_any_value', ) def unchecked_means_any_value(self, queryset, name, value): if not value: return queryset return queryset.filter(**{name: value}) If the value is False, it will return the original QuerySet. Otherwise, it will filter the queryset with the names and values: is_dangerous=True, is_secret=True, or is_active=True.
score: 0

http://stackoverflow.com/comment/82824329
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/47927980
has text: Possible duplicate of [Regex lookahead, lookbehind and atomic groups](https://stackoverflow.com/questions/2973436/regex-lookahead-lookbehind-and-atomic-groups)

http://stackoverflow.com/a/72123287
type: Answer
answers question: http://stackoverflow.com/q/47872609
has body: the init fun. will make a difference in the whole map, you can try like this: class PostPipeline(object): def __init__(self): self.ids_seen = set() self.file = open('fokSpider1.xml', 'w+b') self.exporter = XmlItemExporter(self.file)
score: 0

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

http://stackoverflow.com/a/48005992
score: 4
type: AcceptedAnswer
has body: Map using a dict and multiply the values i.e vals = {'MT':1000, 'LBS':0.453592, 'GM': 0.001, 'MG':0.000001, 'KG':1} df['new'] = df['quantity']*df['uom'].map(vals) quantity uom new 0 100.0 KG 100.0000 1 910.0 GM 0.9100 2 500.0 KG 500.0000 3 50.0 KG 50.0000 4 0.5 GM 0.0005 5 22.5 MT 22500.0000 6 1300.0 GM 1.3000 7 600.0 GM 0.6000 8 20.0 MT 20000.0000 If you want to add 'KG' as a column values then use df['new_unit'] = 'KG'
type: Answer
upvote count: 4
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48005748
answers question: http://stackoverflow.com/q/48005748

http://stackoverflow.com/comment/82677365
comment on: http://stackoverflow.com/q/47856548
type: Comment
type: QuestionComment
has text: Indentation is off. Without a return statement a function returns `None`.
score: 0

http://stackoverflow.com/a/47859002
downvote count: 0
answers question: http://stackoverflow.com/q/47858941
type: Answer
has comment: http://stackoverflow.com/comment/82682659
score: 3
upvote count: 3
has body: Yeah, abs() doesn't do what you think it does (hint: it operates on integers). Instead, use fabsf() from math.h: https://ideone.com/4HphCr

http://stackoverflow.com/q/47889448
tagged with: django
tagged with: python
score: 2
has title: Django Debug Toolbar Time Panel doesn't work
has answer: http://stackoverflow.com/a/51390865
tagged with: django-debug-toolbar
type: Question
downvote count: 0
answer count: 1
favorite count: 0
has body: I have installed Django Debug Toolbar. All other panels work very well but the Time Panel. There is Time Panel showed there, but when I click there is no response. When I click all other panels, it can display the related information such as sql panel, version panel etc. How can get the Time Panel work, BTW, for my site, the SQL panel show only 3 to 4 seconds, but the Time panel show around 10 seconds, what is the diff, where is the 6 seconds?
upvote count: 2
tagged with: time
type: UnansweredQuestion

http://stackoverflow.com/q/47905546
has answer: http://stackoverflow.com/a/60138234
has answer: http://stackoverflow.com/a/47907086
upvote count: 14
has answer: http://stackoverflow.com/a/47906345
has answer: http://stackoverflow.com/a/72940497
type: Question
has title: how to pass python package to spark job and invoke main file from package with arguments
has comment: http://stackoverflow.com/comment/88376079
tagged with: pyspark
answer count: 6
has answer: http://stackoverflow.com/a/52066867
has answer: http://stackoverflow.com/a/68839424
tagged with: apache-spark
downvote count: 0
favorite count: 0
has body: I have my python code with a structure like, Project1 --src ----util.py ----job1.py ----job2.py --config ----config1.json ----config2.json I want to run this job1 in spark but these I just cannot invoke job1.py because its dependent on other files like util.py and job2.py and config files and thus I need to pass complete package as an input to spark. I tried running spark-submit job1.py but it fails with dependencies like job2.py and util.py because they are not available to executors. Based on spark documentation, I see --files is an option to do this but it works by passing all filenames to spark-submit which looks difficult if number of files in codebase in future. Another option I see is passing code zip file with --archive option but still it fails because not able to reference files in zip. So Can anyone suggest any other way to run such codebase in spark?
type: UnansweredQuestion
tagged with: python
score: 14

http://stackoverflow.com/comment/82906096
comment on: http://stackoverflow.com/a/47968276
type: AnswerComment
has text: Isn't regular expressions a bit overkill?
type: Comment
score: 1

scikit-learn
tags question: http://stackoverflow.com/q/47860212
tags question: http://stackoverflow.com/q/47894387
tags question: http://stackoverflow.com/q/47892066
tags question: http://stackoverflow.com/q/47895434
tags question: http://stackoverflow.com/q/47995738
tags question: http://stackoverflow.com/q/47943183
tags question: http://stackoverflow.com/q/47942417
tags question: http://stackoverflow.com/q/47962917
tags question: http://stackoverflow.com/q/47891655
tags question: http://stackoverflow.com/q/47856092
tags question: http://stackoverflow.com/q/47970629
tags question: http://stackoverflow.com/q/47926343
tags question: http://stackoverflow.com/q/47896198
tags question: http://stackoverflow.com/q/47899463
tags question: http://stackoverflow.com/q/47958697
tags question: http://stackoverflow.com/q/47890210
tags question: http://stackoverflow.com/q/47895064
tags question: http://stackoverflow.com/q/47915290
tags question: http://stackoverflow.com/q/47886227
tags question: http://stackoverflow.com/q/47923258
tags question: http://stackoverflow.com/q/47910446
tags question: http://stackoverflow.com/q/47997029
tags question: http://stackoverflow.com/q/47917287
tags question: http://stackoverflow.com/q/47926352
tags question: http://stackoverflow.com/q/47998371
tags question: http://stackoverflow.com/q/47887247
tags question: http://stackoverflow.com/q/47941232
tags question: http://stackoverflow.com/q/47927732
tags question: http://stackoverflow.com/q/47961536
tags question: http://stackoverflow.com/q/48000890
tags question: http://stackoverflow.com/q/47918219
tags question: http://stackoverflow.com/q/47985052
tags question: http://stackoverflow.com/q/47980936
tags question: http://stackoverflow.com/q/47951486
tag name: scikit-learn
tags question: http://stackoverflow.com/q/48003185
tags question: http://stackoverflow.com/q/47904508
tags question: http://stackoverflow.com/q/47890333
type: Tag
tags question: http://stackoverflow.com/q/47872546
tags question: http://stackoverflow.com/q/47909126
tags question: http://stackoverflow.com/q/47878901
tags question: http://stackoverflow.com/q/47968153
tags question: http://stackoverflow.com/q/47977694
tags question: http://stackoverflow.com/q/47940731
tags question: http://stackoverflow.com/q/47900056
tags question: http://stackoverflow.com/q/47960828
tags question: http://stackoverflow.com/q/47909588
tags question: http://stackoverflow.com/q/47876999
tags question: http://stackoverflow.com/q/47873366
tags question: http://stackoverflow.com/q/47946942
tags question: http://stackoverflow.com/q/47898326
tags question: http://stackoverflow.com/q/47919853
tags question: http://stackoverflow.com/q/47981756
tags question: http://stackoverflow.com/q/47890515
tags question: http://stackoverflow.com/q/47986354
tags question: http://stackoverflow.com/q/47916335
tags question: http://stackoverflow.com/q/47929831
tags question: http://stackoverflow.com/q/47968453
tags question: http://stackoverflow.com/q/47884566
tags question: http://stackoverflow.com/q/47999271
tags question: http://stackoverflow.com/q/47957151
tags question: http://stackoverflow.com/q/47905757
tags question: http://stackoverflow.com/q/48007580
tags question: http://stackoverflow.com/q/47876157

http://stackoverflow.com/a/47936469
accepted answer of: http://stackoverflow.com/q/47936384
has body: For reasons unspecified in your question (likely a setting in ansible.cfg) you are trying to execute Python executable on your router with the following absolute path: /home/testuser/networking/networking_env/bin/python. Ansible reports: "No such file or directory", which is likely true, considering it's a router. You need to run blockinfile as a local action on the control machine. The easiest would probably be to set a local connection for this particular task: - name: Append to file connection: local blockinfile: create: yes path: '/home/testuser/ansible/output/{{ inventory_hostname }}.txt' block: | '{{ command_output.stdout }}' You can also use local_action: - name: Append to file local_action: module: blockinfile create: yes path: '/home/testuser/ansible/output/{{ inventory_hostname }}.txt' block: | '{{ command_output.stdout }}' or delegate_to declaration: - name: Append to file delegate_to: localhost blockinfile: create: yes path: '/home/testuser/ansible/output/{{ inventory_hostname }}.txt' block: | '{{ command_output.stdout }}'
type: AcceptedAnswer
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47936384

http://stackoverflow.com/comment/82758125
comment on: http://stackoverflow.com/q/47895609
score: 0
type: Comment
type: QuestionComment
has text: Have a go and find out. ;-)

http://stackoverflow.com/q/47856186
downvote count: 1
type: Question
answer count: 2
has body: I have created static web site which I am planning to host in S3 bucket. This HTML has a form and attachment feature which will be sent to my email id when user will attach a file and hit 'Upload'. Below is my HTML code snippets - Your email address: Custom file label: File to stash: ​ and then Jquery to trigger POST request to AWS API gateway $('#upload').on("click", function (){ var oOutput = document.querySelector("div"), oData = new FormData(form); var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { // Typical action to be performed when the document is ready: console.log(xhttp.responseText); console.log(xhttp.statusText); console.log(xhttp.status); oOutput.innerHTML = xhttp.responseText; } else { oOutput.innerHTML = "Error " + xhttp.status + " occurred when trying to upload your file. "; } }; xhttp.open("POST", "https://myLambdaAPIURL", true); xhttp.setRequestHeader("Content-type", "application/json;charset=UTF-8"); xhttp.send(JSON.stringify({Email:$('#email').val(),fileUpload:$('#fileUpload').val()})); API gateway in AWS has all the default configurations to process the json format. My AWS lambda code which works fine to send just an email. import smtplib , os from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication from email.mime.base import MIMEBase from email.message import Message from email.encoders import encode_base64 from email.mime.text import MIMEText from mimetypes import guess_type def lambda_handler(event, context): msg = MIMEMultipart() msg['Subject'] = 'File Uploaded' msg['From'] = 'user@gmail.com' msg['To'] = 'user@gmail.com' emailFrom = "user@gmail.com" emailTo ="user@gmail.com" for file in event['fileUpload']: mimetype, encoding = guess_type(file) if mimetype == None: mimetype = "text/plain" mimetype = mimetype.split('/',1) fp = open(file, "rb") attachment.set_payload(fp.read()) fp.close() en…
tagged with: email-attachments
upvote count: 0
score: -1
has answer: http://stackoverflow.com/a/53913255
has comment: http://stackoverflow.com/comment/82680994
has answer: http://stackoverflow.com/a/47874604
tagged with: aws-lambda
favorite count: 0
has comment: http://stackoverflow.com/comment/82689354
has title: AWS Lambda in Python to send email with attachment
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/5587973
tagged with: python

http://stackoverflow.com/comment/82717421
score: 0
type: AnswerComment
type: Comment
has text: have a look at hamiltonian cycles (its np complete) and see this probabilistic algorithm: https://ac.els-cdn.com/002200007990045X/1-s2.0-002200007990045X-main.pdf?_tid=b9164068-e432-11e7-98c2-00000aab0f6b&acdnat=1513629396_b7d1cdb744e6370e9999e30b66e2d157
comment on: http://stackoverflow.com/a/47871837

http://stackoverflow.com/comment/82967215
type: AnswerComment
type: Comment
has text: Ah, I hadn't checked the old style's documentation. Thanks.
comment on: http://stackoverflow.com/a/47945948
score: 0

django-1.11
tags question: http://stackoverflow.com/q/47900598
tag name: django-1.11
tags question: http://stackoverflow.com/q/47887158
type: Tag

http://stackoverflow.com/comment/82720438
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47877251
type: Comment
has text: [pyglet](https://pyglet.readthedocs.io/en/pyglet-1.3-maintenance/) supports both python2.x and python3.x, i've just tried here on windows with python3.6 and it works out of the box, try uninstalling first and installing back without using the cache and please report the installation process, otherwise we don't have any clues to help you out to figure out what's going on. For instance, `--no-cache-dir`

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

http://stackoverflow.com/comment/82865296
has text: @StevePiercy Thanks. I am trying to see what my options are. When you say unique variables, are you talking about the Python side, like the configuration file or an extension? I guess I could have a couple of custom directives which respectively set and get a property for a key (ie. a dict).
score: 0
comment on: http://stackoverflow.com/q/47944831
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47856872
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47858386
score: 3
downvote count: 0
has body: I have a QHBoxLayout with a QLabel in it, and I'm trying to get both an icon and window title text in the QLabel. Is that possible? Or even to add the icon directly to the QHBoxLayout, so that is is laying just before the window title text? Here is my code: class MyBar(QWidget): def __init__(self, parent): super(MyBar, self).__init__() self.parent = parent self.layout = QHBoxLayout() self.layout.setContentsMargins(0,0,0,0) self.title = QLabel("Main Window") def changetitle(self, msg): self.title.setText(msg) Edit: Here is the code where I used two labels side by side: self.label3 = QLabel(self) self.title = QLabel("Main Window") self.pixmap = QPixmap('res/myIcon.ico') self.label3.setPixmap(self.pixmap) self.label3.setAlignment(Qt.AlignCenter) self.title.setFixedHeight(35) self.title.setAlignment(Qt.AlignCenter) self.layout.addWidget(self.label3) self.layout.addWidget(self.title) self.label3.setStyleSheet(""" background-color: black; """) self.title.setStyleSheet(""" background-color: black; color: white; """)
has comment: http://stackoverflow.com/comment/82680240
tagged with: pyqt5
type: Question
tagged with: layout
tagged with: qpixmap
upvote count: 3
has comment: http://stackoverflow.com/comment/82680024
answer count: 1
favorite count: 0
tagged with: python
has title: How to add both an image and text to a QLabel
has answer: http://stackoverflow.com/a/47858386
tagged with: qlabel

http://stackoverflow.com/q/47869778
has body: Consider the following pandas.Series: import pandas as pd import numpy as np s = pd.Series([np.nan, 1, 1, np.nan]) s 0 NaN 1 1.0 2 1.0 3 NaN dtype: float64 I want to find only unique values in this particular series using the built-in set function: unqs = set(s) unqs {nan, 1.0, nan} Why are there duplicate NaNs in the resultant set? Using a similar function (pandas.unique) does not produce this result, so what's the difference, here? pd.unique(s) array([ nan, 1.])
linked to: http://stackoverflow.com/q/47721635
tagged with: python
has answer: http://stackoverflow.com/a/47869872
accepted answer: http://stackoverflow.com/a/47869872
type: AnsweredQuestion
has title: Unique values from pandas.Series
has comment: http://stackoverflow.com/comment/82704848
linked to: http://stackoverflow.com/q/8819738
has comment: http://stackoverflow.com/comment/82704551
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82704742
has comment: http://stackoverflow.com/comment/82706484
duplicate of: http://stackoverflow.com/q/47721635
has comment: http://stackoverflow.com/comment/82705299
linked to: http://stackoverflow.com/q/41723419
score: 0
has comment: http://stackoverflow.com/comment/82704634
has comment: http://stackoverflow.com/comment/82704689
tagged with: pandas
answer count: 1

http://stackoverflow.com/a/57090116
type: Answer
has comment: http://stackoverflow.com/comment/113148849
downvote count: 0
score: 24
has comment: http://stackoverflow.com/comment/108326868
answers question: http://stackoverflow.com/q/47996396
has body: Cause: caused by actions like RDD's collect() that send big chunk of data to the driver Solution: set by SparkConf: conf.set("spark.driver.maxResultSize", "4g") OR set by spark-defaults.conf: spark.driver.maxResultSize 4g OR set when calling spark-submit: --conf spark.driver.maxResultSize=4g
upvote count: 24

http://stackoverflow.com/comment/83123262
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48031158
has text: I tried your solution it worked. But all the logging info output is getting printed outside the table. Like in your case too, you have 2 test cases but logging info is getting printed at the top of the table. Is it possible to get the logging.info of respective test case in the table. Example: if I click detail of basicTestCase, then logging info related to test case 1 should be displayed in testcase1 detail. same for test case-2. Is it possible
type: AnswerComment

http://stackoverflow.com/comment/82820932
type: Comment
comment on: http://stackoverflow.com/a/47926473
score: 0
type: AnswerComment
has text: He wants to inspect the class itself, not an _instance_ of the class.

http://stackoverflow.com/a/52163944
has body: This happens because the pyLDAvis program expects that all document topics in the model show up in the corpus at least once. This can happen when you do some preprocessing after making your corpus/text and before making your model. A word in the model's internal dictionary that is not used in the dictionary you provide will cause this to fail because now the probability is slightly less than one. You can fix this by either adding the missing words to your corpus dictionary (or adding the words to the corpus and making a dictionary from that) or you can add this line to the site-packages\pyLDAvis\gensim.py code before "assert topic_term_dists.shape[0] == doc_topic_dists.shape[1]" (should be ~line 67) topic_term_dists = topic_term_dists / topic_term_dists.sum(axis=1)[:, None] Assuming your code ran till that point, this should renormalize the topic distribution without the missing dict items. But note that it would be better to include all terms in the corpus.
upvote count: 5
downvote count: 0
answers question: http://stackoverflow.com/q/47998685
score: 5
type: Answer

http://stackoverflow.com/comment/82932131
score: 0
comment on: http://stackoverflow.com/a/47981811
has text: Thanks for this one. Will check on this .
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/82759970
type: Comment
comment on: http://stackoverflow.com/q/47896006
has text: Thank you so much!!! This may help. It makes total sense and I didn't think of that. :-)
score: 0
type: QuestionComment

http://stackoverflow.com/a/47887975
has body: UrlRequest should be passed a str object as request body. You can serialize the request dictionary as a string object by dumping it. Pass this dumped dictionary as the request body to UrlRequest. import json req_body=json.dumps({'search_text': search_text, 'num_results': 1}) req = UrlRequest( 'http://127.0.0.1:5000/search', req_body=req_body, on_success=Test.got_json, req_headers=header)
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/82741923
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47886673
type: Answer
answers question: http://stackoverflow.com/q/47886673

http://stackoverflow.com/q/47993825
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: IntegrityError when delete model instance
has answer: http://stackoverflow.com/a/47994759
downvote count: 0
has body: I have two models like class A(models.Model): title = models.CharField(max_length=255) class B(models.Model): recommendation = models.ForeignKey(A, related_name="+") title = models.CharField(max_length=255) When I remove the A model instance, I get something like: IntegrityError: update or delete on table "myapp_a" violates foreign key constraint "myapp_relate_recommendation_id_4a7c5340_fk_myapp_a_id" on table "myapp_b" Detail: Key (id)=(27527) is still referenced from table "myapp_b". I can't figure out why it happens, I thought FKs should be deleted by default.
tagged with: django
type: Question
score: 1
tagged with: django-models
upvote count: 1

http://stackoverflow.com/comment/82713282
has text: this is known as the "flip-flop operator" in Perl (and it's two dots `..`, not three). google "flip-flop operator in Python" for more info
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47871639
score: 0

http://stackoverflow.com/a/47987099
has body: I have tried and i got my expected output. py: import os from PIL import Image img=[] path="C:/Users/admin/PycharmProjects/my_module/static/files/" for f in os.listdir(path): ext = os.path.splitext(f)[1] os.listdir(path).append(f) image = Image.open(f) image.show()
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47977609
score: 1
has comment: http://stackoverflow.com/comment/82977295
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47977609

http://stackoverflow.com/comment/82994232
comment on: http://stackoverflow.com/a/48012721
type: AnswerComment
has text: Pickle is a module that lets you convert python objects to bytes and back. The best way to learn it is to read through the documentation for it: https://docs.python.org/3.6/library/pickle.html
type: Comment
score: 1

http://stackoverflow.com/a/47925801
has body: You should copy object in cases like this. from copy import copy obj1 = MyClass(1,2) obj2 = copy(obj1) obj2.1st_att = 5 Or deepcopy if your class is complicated and has lots of references.
type: Answer
has comment: http://stackoverflow.com/comment/82819488
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/82820353
answers question: http://stackoverflow.com/q/47925677
has comment: http://stackoverflow.com/comment/82821535
upvote count: 1

http://stackoverflow.com/comment/82971754
type: Comment
type: QuestionComment
has text: Sir? Who are you talking to? There are women here too. Also, where is your data? I want to see your data, not an explanation.
comment on: http://stackoverflow.com/q/48001630
score: 0

http://stackoverflow.com/comment/82988686
type: Comment
comment on: http://stackoverflow.com/a/48009970
has text: But you _do_ need to change it to `(testNumber - 2 >> 1 << 1) | 1` because the OP wants the largest odd number that's strictly smaller than `testNumber`.
score: 1
type: AnswerComment

http://stackoverflow.com/comment/82914109
score: 4
type: QuestionComment
type: Comment
has text: Build a string containing the whole triangle and print it.
comment on: http://stackoverflow.com/q/47972224

http://stackoverflow.com/a/48314811
type: Answer
score: 2
answers question: http://stackoverflow.com/q/47950466
has body: Hi I am a newbie looking to use quantopian Have an interest in using Aroon.Found this in my search. Looks simpler than your code and believe it uses ta-lib. https://github.com/FreddieWitherden/ta/blob/master/ta.py
downvote count: 0
upvote count: 2

http://stackoverflow.com/q/47864505
has title: Text detection in images
tagged with: coreml
has comment: http://stackoverflow.com/comment/82694260
tagged with: ios
has comment: http://stackoverflow.com/comment/82694108
has comment: http://stackoverflow.com/comment/82734220
tagged with: python
tagged with: ocr
favorite count: 0
score: 2
answer count: 0
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82726146
has comment: http://stackoverflow.com/comment/82694008
tagged with: swift
has body: I am using below sample code for text detection in images (not handwritten) using coreml and vision. https://github.com/DrNeuroSurg/OCRwithVisionAndCoreML-Part2 In this they have used machine learning model which supports only uppercase and numbers. Where as in my project I want upper case, lower case , numbers and few of special characters (like : ,- ). I do not have any experience in python to do required changes and generate the required .mlmodel file using train data (which again I don't have for my requirement) Below is the link where it is given how to create .mlmodel http://www.neurosurg.de/2017/10/18/part-3-train-your-own-model-using-keras/ does anyone has such .mlmodel? or can somebody help me how to achieve this? this is the image in which I want to detect text
type: Question
upvote count: 2

http://stackoverflow.com/comment/138277046
has text: That ignores all long lines, but OP only wanted long comment lines ignored, not long code lines.
comment on: http://stackoverflow.com/a/78429060
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/82682184
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47858801
has text: If you want us to help you, you must provide a [mcve]
type: Comment

http://stackoverflow.com/comment/82995923
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47975154
has text: I can't emphasize this enough: you need to hard-code some representative datasets into your questions like i did with my answer here: https://stackoverflow.com/a/47972529/1552748
type: Comment

http://stackoverflow.com/comment/82926518
type: Comment
has text: You are such a gem @RomanPerekhrest. It worked just perfect. Could you provide me with any link to the usage of `contents` so that I can learn a bit more. Thanks.
comment on: http://stackoverflow.com/a/47978607
score: 0
type: AnswerComment

http://stackoverflow.com/q/47897138
score: 0
has comment: http://stackoverflow.com/comment/82761512
type: UnansweredQuestion
has body: I had Python 2.7.6 installed on my system at /usr/bin/python2.7. Now I have downloaded, built, and installed Python 2.7.14 as root. The location was different: /usr/local/bin/python2.7. I changed to /usr/bin/python symlink to the later one. But now I have all other packages missing like mercurial, cx-oracle, easy_install, pip, etc. If I try to install those, it says they are already installed which is true as if I revert python symlink to python2.7.6, everything works again. How do I install all those packages to Python 2.7.14? $ sudo python -V Python 2.7.14 $ sudo which python /usr/local/bin/python $ python -V Python 2.7.6 $ which python /usr/bin/python
has comment: http://stackoverflow.com/comment/82761136
tagged with: python
has comment: http://stackoverflow.com/comment/82761525
has title: Upgrading packages from python 2.7.6 to 2.7.14
answer count: 0
has comment: http://stackoverflow.com/comment/82761508
type: Question
linked to: http://stackoverflow.com/q/122327
has comment: http://stackoverflow.com/comment/82761336
has comment: http://stackoverflow.com/comment/82761624

http://stackoverflow.com/q/47961407
has answer: http://stackoverflow.com/a/47961504
tagged with: python
tagged with: module
type: AnsweredQuestion
downvote count: 2
type: Question
accepted answer: http://stackoverflow.com/a/47961504
has body: I tried following this tutorial The Instructions I Followed but I think I messed it up somehow (I am relatively new to python) I get this error when I try to import it. Does anyone have any ideas how to fix it or what I did wrong. (I tried looking for help but they were all a bit confusing for me) This is the contents of vigenere.py
has comment: http://stackoverflow.com/comment/82891975
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/82891947
answer count: 1
has title: Python can't find my custom module
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/82837137
type: Comment
type: QuestionComment
has text: @Blurp Thanks, but then I'm missing the class where I'm calling it from (ie. self).
comment on: http://stackoverflow.com/q/47933718
score: 0

http://stackoverflow.com/a/47940723
accepted answer of: http://stackoverflow.com/q/47940521
has comment: http://stackoverflow.com/comment/82856769
has comment: http://stackoverflow.com/comment/82872395
has comment: http://stackoverflow.com/comment/82854891
has comment: http://stackoverflow.com/comment/82869114
has comment: http://stackoverflow.com/comment/82863453
score: 0
type: AcceptedAnswer
type: Answer
has body: Although I can't understand you well as your explanation is really confusing. I guess you are printing dbname in this way: # edit.py from xxx import dbname print(dbname) crud(another_value) print(dbname) And then you find you get the same values. That is because when you from xxx import dbname, you get a local copy of original dbname. To get the original dbname, you need to use sys.modules["xxx"].dbname.
answers question: http://stackoverflow.com/q/47940521

http://stackoverflow.com/comment/82802158
comment on: http://stackoverflow.com/q/47916802
has text: So value of what element are you trying to get?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82991689
has text: Related https://stackoverflow.com/a/47882550/5320906
score: 0
comment on: http://stackoverflow.com/q/48011386
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48005005
upvote count: 1
has comment: http://stackoverflow.com/comment/82978446
has comment: http://stackoverflow.com/comment/82978204
has body: You are not matching the braces, and your regex would search only for numbers like 111 222-3333. I think you can work your way with this &gt;&gt;&gt; text = "Keaton UnderwoodAp #636-8082 Arcu AvenueThiensville Maryland 19587(564) 908-6970 Keegan BlairAp #761-2515 Egestas. Rd.Manitowoc TN 07528(577) 333-6244 Tamara Howe3415 Lobortis. AvenueRocky Mount WA 48580(655) 840-6139" &gt;&gt;&gt; re.findall("\(\d{3}\) \d{3}-\d{4}", text) ['(564) 908-6970', '(577) 333-6244', '(655) 840-6139']
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82978493
accepted answer of: http://stackoverflow.com/q/48004509
answers question: http://stackoverflow.com/q/48004509
downvote count: 0
type: Answer

http://stackoverflow.com/comment/82848060
comment on: http://stackoverflow.com/a/47934416
has text: Oh wow! That's exactly what I needed. I didn't know a bunch of the convenient sympy features here
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/47966665
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/47969450
score: 2
type: AnsweredQuestion
upvote count: 2
has body: I have 2 Numpy arrays 1st with 210 rows and 2nd with 30 rows and both contains 4 columns and I want to apply condition/filter on 4th column of both arrays which contains only 0 or 1. So, I want to detect 0 of 1st array as Train_Safe, 1 of 1st array as Train_Cracked, 0 of 2nd Array as Test_Safe and 1 of 2nd Array as Test_Cracked and plot these values on a 3D scatter plot with Matplotlib, I tried with this code : for i in X_train_merge[0:, 3]: if i == 0: x_vals_train_0 = X_train_merge[0:, 0:1] y_vals_train_0 = X_train_merge[0:, 1:2] z_vals_train_0 = X_train_merge[0:, 2:3] elif i == 1: x_vals_train_1 = X_train_merge[0:, 0:1] y_vals_train_1 = X_train_merge[0:, 1:2] z_vals_train_1 = X_train_merge[0:, 2:3] for j in X_test_merge[0:, 3]: if j == 0: x_vals_test_0 = X_test_merge[0:, 0:1] y_vals_test_0 = X_test_merge[0:, 1:2] z_vals_test_0 = X_test_merge[0:, 2:3] elif j == 1: x_vals_test_1 = X_test_merge[0:, 0:1] y_vals_test_1 = X_test_merge[0:, 1:2] z_vals_test_1 = X_test_merge[0:, 2:3] ax.scatter(x_vals_train_0, y_vals_train_0, z_vals_train_0, c='g', marker='o', label="Train_Safe") ax.scatter(x_vals_train_1, y_vals_train_1, z_vals_train_1, c='b', marker='o', label="Train_Cracked") ax.scatter(x_vals_test_0, y_vals_test_0, z_vals_test_0, c='black', marker='*', label="Test_Safe") ax.scatter(x_vals_test_1, y_vals_test_1, z_vals_test_1, c='brown', marker='*', label="Test_Cracked") it plot/gives all data points without distrubting/divding it into Train_Safe, Train_Cracked, Test_Safe and Test_Cracked. Any suggestion/solution for this task. Thanks in Advance.
tagged with: machine-learning
type: Question
tagged with: matplotlib
tagged with: numpy
has answer: http://stackoverflow.com/a/47969450
downvote count: 0
answer count: 1
has title: Applying condition/filters on a column of Numpy Array

http://stackoverflow.com/q/47965256
answer count: 1
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/82937902
has comment: http://stackoverflow.com/comment/82939433
accepted answer: http://stackoverflow.com/a/47986005
type: AnsweredQuestion
downvote count: 0
score: 1
has title: internal variables in BasicRNNCell
favorite count: 0
has body: I have the following example code to test BasicRNNCell. I'd like to get its internal matrix so that I can calculate the values of output_res, newstate_res using my own code to make sure that I can reproduce the values of output_res, newstate_res. In tensorflow source code, it says output = new_state = act(W * input + U * state + B). Does anybody know how I can get W and U? (I tried to access cell._kernel, but it is not available.) $ cat ./main.py #!/usr/bin/env python # vim: set noexpandtab tabstop=2 shiftwidth=2 softtabstop=-1 fileencoding=utf-8: import tensorflow as tf import numpy as np batch_size = 4 vector_size = 3 inputs = tf.placeholder( tf.float32 , [batch_size, vector_size] ) num_units = 2 state = tf.zeros([batch_size, num_units], tf.float32) cell = tf.contrib.rnn.BasicRNNCell(num_units=num_units) output, newstate = cell(inputs = inputs, state = state) X = np.zeros([batch_size, vector_size]) #X = np.ones([batch_size, vector_size]) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) output_res, newstate_res = sess.run([output, newstate], feed_dict = {inputs: X}) print(output_res) print(newstate_res) sess.close() $ ./main.py [[ 0. 0.] [ 0. 0.] [ 0. 0.] [ 0. 0.]] [[ 0. 0.] [ 0. 0.] [ 0. 0.] [ 0. 0.]]
type: Question
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47986005
tagged with: recurrent-neural-network
linked to: http://stackoverflow.com/q/47640455

http://stackoverflow.com/a/47905435
score: 383
upvote count: 383
type: Answer
has comment: http://stackoverflow.com/comment/82780119
has body: Check documentation for model.fit here. By setting verbose 0, 1 or 2 you just say how do you want to 'see' the training progress for each epoch. verbose=0 will show you nothing (silent) verbose=1 will show you an animated progress bar like this: verbose=2 will just mention the number of epoch like this:
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47902295
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47902295
has comment: http://stackoverflow.com/comment/96656336
has comment: http://stackoverflow.com/comment/137118299

http://stackoverflow.com/comment/82691245
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47862662
has text: @furas Thanks a lot dude. I'll keep that in mind next time:)
score: 0

http://stackoverflow.com/q/47987590
tagged with: python
type: AnsweredQuestion
tagged with: django
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/47988048
score: 1
answer count: 1
downvote count: 0
tagged with: google-ads-api
favorite count: 0
has body: I am testing out google adwords api features (NOTE: This question isn't directly aimed at Google Ad Words API). I am facing an error that says: main() takes 2 positional arguments but 3 were given Heres what I have done: 1) Created a Keyword model that has a keyword Charfield 2) Created a KeywordForm that has a form element of type CharField 3) Used the form in a HTML page to get the keyword through the POST method 4) After the POST, the URL is routed to a view keyword_add which sets two values namely adwords_client = adwords.AdWordsClient.LoadFromStorage() ad_group_id = 'XXXXXXXXX` Also, it gets the value of keyword model using new_keyword = Keyword.objects.all() It then calls a function located in a python script using the function call ad_group_update.main(adwords_client, ad_group_id, new_keyword) 5) The function main in the python script add_keywords is executed using the three arguments adwords_client, ad_group_id &amp; new_keyword The following error arises when I do this : 1) error while executing main() Apart from this error, I have another question in the code: from googleads import adwords AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' def main(client, ad_group_id, keyword): # Initialize appropriate service. ad_group_criterion_service = client.GetService( 'AdGroupCriterionService', version='v201710') # Construct keyword ad group criterion object. keyword1 = { 'xsi_type': 'BiddableAdGroupCriterion', 'adGroupId': ad_group_id, 'criterion': { 'xsi_type': 'Keyword', 'matchType': 'BROAD', 'text': 'MARS' }, # These fields are optional. 'userStatus': 'PAUSED', 'finalUrls': { 'urls': ['http://example.com/keyword'] } } keyword2 = { 'xsi_type': 'NegativeAdGroupCriterion', 'adGroupId': ad_group_id, 'criterion': { 'xsi_type': 'Keyword', 'matchType': 'EXACT', 'text': 'pluto' } } # Construct operations and add ad group criteria. operations = [ { 'operator': 'ADD', 'operand': keyword1 }, { 'operator': 'ADD', 'operand': keyword2 } ] ad_group_criteria = ad_group_criterion_service.…
has title: EDITGetting error main() takes 2 positional arguments but 3 were given
has answer: http://stackoverflow.com/a/47988048

http://stackoverflow.com/comment/82969297
comment on: http://stackoverflow.com/a/47990354
type: AnswerComment
has text: I see. Good recommendation. I'll try that. Thanks
score: 0
type: Comment

http://stackoverflow.com/a/47957937
has body: Assuming 64 is a stable value and does not change for this particular element and the attribute name is data-reactid (and not the data-reacid - looks like a typo): driver.find_element_by_xpath("//h3[@data-reactid = '64']").text Equivalent CSS selector based solution: driver.find_element_by_css_selector("h3[data-reactid=64]").text Of course, you need to account for the possible timing issues and other situations like an element being inside an iframe. This is specific to your particular situation.
score: 8
downvote count: 0
answers question: http://stackoverflow.com/q/47957930
upvote count: 8
type: Answer
has comment: http://stackoverflow.com/comment/82885251

http://stackoverflow.com/q/47894484
tagged with: while-loop
tagged with: input
has comment: http://stackoverflow.com/comment/82755684
tagged with: python
has body: I'm completely new to python, and I wanted to create a program that "loads" a number that the user would have entered. To do this, I made a function with an input variable, percentage that I then tried to transform to an interfer, percentage_int To then put in a while loop. However, I get an error message, why? def loader(): percentage = input("what percentage do you want?") percentage_int =int(percentage) x = 0 print("Goal:{} %".format(percentage_int)) while x &lt; percentage_int: x+=1 print(x) loader()
tagged with: python-3.x
downvote count: 2
has answer: http://stackoverflow.com/a/47894552
type: AnsweredQuestion
score: -2
accepted answer: http://stackoverflow.com/a/47894552
type: Question
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82755600
has title: Transforming an input variable into an interger
favorite count: 0

http://stackoverflow.com/comment/82854144
has text: You'd need to give a clear *example* of what you want to do.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47936254

http://stackoverflow.com/q/47958342
has body: Already registered user name can be registered in user creation form. I'm making Django application. I wrote in views.py def regist(request): regist_form = RegisterForm(request.POST or None) context = { 'regist_form': regist_form, } return render(request, 'registration/regist.html', context) def regist_save(request): regist_form = RegisterForm(request.POST or None) if request.method == "POST" and regist_form.is_valid(): regist = regist_form.save(commit=False) regist.is_staff = True regist.save() advertisements = Advertisement.objects.all() return render(request, 'registration/detail.html', {'advertisements': advertisements}) in regist.html Username {{ regist_form.username }} {{ regist_form.username.help_text }} Email {{ regist_form.email }} {{ regist_form.email.help_text }} Password {{ regist_form.password1 }} {{ regist_form.password1.help_text }} Password(Confirmation) {{ regist_form.password2 }} {{ regist_form.password2.help_text }} Register {% csrf_token %} in forms.py class RegisterForm(UserCreationForm): class Meta: model = User fields = ('username', 'email','password1','password1',) def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['email'].widget.attrs['class'] = 'form-control' self.fields['password1'].widget.attrs['class'] = 'form-control' self.fields['password2'].widget.attrs['class'] = 'form-control' Now in this user registration form, if I write already registered user name&email&password, these data is not registered but detail.html is load. I wanna show alert if I do so like "this user name is already registered". Why isn't my web page not my ideal one? Why can I resist already registered user name in my site? How should I fix this? I did not make User model in models.py.
type: Question
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47958389
has comment: http://stackoverflow.com/comment/82886077
tagged with: http://stackoverflow.com/tag/html
tagged with: python
accepted answer: http://stackoverflow.com/a/47958389
tagged with: django
possible better answer: http://stackoverflow.com/a/47958439
type: AnsweredQuestion
has title: Already registered user name can be registered
has answer: http://stackoverflow.com/a/47958439

http://stackoverflow.com/comment/82793418
has text: I do have one question about the call to super. What args are been used in this instance. Also I gladly upvoted and will accept it.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47912545
type: Comment

http://stackoverflow.com/comment/82689842
comment on: http://stackoverflow.com/q/47862425
score: 0
type: QuestionComment
type: Comment
has text: Why do you feel this is not correct? Does this cause errors?

http://stackoverflow.com/q/47923452
upvote count: 2
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/54382571
score: 2
has title: Schedule lambda invocation from another lambda AWS
type: Question
has body: I have 2 AWS lambda function A and B , both written in Python. Every time i have A executed , i want B to be executed 3 minutes later. Is it possible to achieve that? If yes how?
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/82824249
has comment: http://stackoverflow.com/comment/82826637
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82823545
favorite count: 0
has comment: http://stackoverflow.com/comment/82830185
tagged with: aws-lambda

http://stackoverflow.com/comment/82991495
comment on: http://stackoverflow.com/q/48011275
type: Comment
type: QuestionComment
has text: please specify django version
score: 0

http://stackoverflow.com/comment/82749747
comment on: http://stackoverflow.com/a/47891371
score: 0
type: AnswerComment
has text: >>> import sys >>> print(sys.executable) /usr/local/bin/python3
type: Comment

batch-normalization
tag name: batch-normalization
tags question: http://stackoverflow.com/q/48004017
tags question: http://stackoverflow.com/q/48001759
tags question: http://stackoverflow.com/q/48000890
tags question: http://stackoverflow.com/q/47950183
type: Tag
tags question: http://stackoverflow.com/q/47976616

group-by
tags question: http://stackoverflow.com/q/47906226
tags question: http://stackoverflow.com/q/47945097
tags question: http://stackoverflow.com/q/47858798
tag name: group-by
type: Tag
tags question: http://stackoverflow.com/q/47876663
tags question: http://stackoverflow.com/q/47898768
tags question: http://stackoverflow.com/q/47987707
tags question: http://stackoverflow.com/q/47991907
tags question: http://stackoverflow.com/q/47927851
tags question: http://stackoverflow.com/q/47907817
tags question: http://stackoverflow.com/q/47924400
tags question: http://stackoverflow.com/q/47976858
tags question: http://stackoverflow.com/q/48012841
tags question: http://stackoverflow.com/q/47989173
tags question: http://stackoverflow.com/q/47980402
tags question: http://stackoverflow.com/q/47980907

http://stackoverflow.com/q/47938150
has answer: http://stackoverflow.com/a/47938278
linked to: http://stackoverflow.com/q/19189274
type: Question
has body: I want to deal with a nested dictionary in python for purpose of storing unique data. However, I don't know what the right way to do it. I tried the following: my_dict = collections.defaultdict(dict) my_dict[id1][id2][id2][id4] = value but it causes KeyError. What is the right way to do so?
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47938687
tagged with: defaultdict
duplicate of: http://stackoverflow.com/q/19189274
has title: Python3.6 4-level dictionaries giving KeyError
tagged with: python
accepted answer: http://stackoverflow.com/a/47938687
tagged with: dictionary
tagged with: python-3.x
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47938278

http://stackoverflow.com/q/47864028
has body: I'm trying to write a version of cumulative sum in python using the reduce function. Here is my code so far: from functools import reduce def my_cum_sum(arg): return reduce(lambda a, x: (a.append(a[-1] + x)) if len(a) &gt; 0 else a.append(x), arg, []) assert(my_cum_sum([1, 1, 1, 1]) == [1, 2, 3, 4])) But the problem is that in my lambda function, python doesn't know that a (my accumulator parameter) is a list object, and that I want my reduce function to return a list. In other functional programming languages, it might ask me to specify the type of a and x. But I'm new to python, and haven't quite figured out how it handles types and stuff. What is the pythonic way of solving this problem?
has title: python cumsum with reduce function
answer count: 3
tagged with: functional-programming
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/47864202
has answer: http://stackoverflow.com/a/78192061
type: Question
has answer: http://stackoverflow.com/a/78194877

http://stackoverflow.com/comment/82882903
has text: Have you tried `plt.tight_layout()`? That might help
comment on: http://stackoverflow.com/q/47956746
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82817813
type: QuestionComment
comment on: http://stackoverflow.com/q/47925094
has text: Your question is not entirely clear since you haven't posted any sample code and output. Have a look at [six](https://pypi.python.org/pypi/six) package to see if this fulfils your requirements.
score: 0
type: Comment

http://stackoverflow.com/comment/82922501
type: AnswerComment
comment on: http://stackoverflow.com/a/47908153
type: Comment
score: 0
has text: thanks so much for you're response. can you please give me the complete code for this. in the challenge i did everything i could but the code is still not passing. i would appreciate it if you could give me the complete code. thanks in advance.

http://stackoverflow.com/q/47935102
tagged with: python
tagged with: easy-install
type: UnansweredQuestion
score: 1
has title: easy_install creates an egg directory instead of egg file
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/57390737
has body: I ran 'easy_install .' for one of my packages, in hopes of creating an egg file to use elsewhere. It successfully installs the package; however, instead of creating an egg file in my /usr/local/lib/python2.7/dist-packages directory, it creates a directory there called my_package.egg, which contains two directories: EGG-INFO, and another named after my package containing the source code (.py and .pyc files). I have another similar package, which "successfully" creates the desired .egg file when easy_install is run, and I don't know what's different about the packages and why easy_install produces different results. I couldn't find any documentation about .egg directories (rather than files) and why they're created. I'd like to know how to remedy this to get a .egg file.
tagged with: egg
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/47983467
has answer: http://stackoverflow.com/a/47983505
has comment: http://stackoverflow.com/comment/82935969
score: -2
possible better answer: http://stackoverflow.com/a/47983751
answer count: 2
tagged with: arrays
favorite count: 0
has title: Rearrange string into 2D array python
has body: I have the following string after using urllib: 459,2277,617459268\n14619,99,19600737\n11297,99,18666551\n16603,99,19761406\n12660,99,28741324\n4543 after using replace and split: data = data.replace('\\n', ',').split(',') ['459', '2277', '617459268', '14619', '99', '19600737', '11297', '99', '18666551', '16603', '99', '19761406', '12660', '99', '28741324', '4543'] However, I had like to get the following 2D array: 459 2277 617459268 14619 99 19600737 11297 99 18666551... Is there a way to break this 1D array into a 2D array without using numpy? When I say 2D array I mean column list when each row is 1x3 list. Easy ways will be appreciated. Thank you.
has answer: http://stackoverflow.com/a/47983751
tagged with: python
accepted answer: http://stackoverflow.com/a/47983505
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/82936050
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/82797621
has text: @PM 2Ring - I was hoping not to manually define dictionaries as the data is variable.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47898630

http://stackoverflow.com/q/47966110
has body: I am attempting to scrape this website but it requires a login. I am struggling to successfully log in through the use of the requests library in python. Looking through the form in the html, there are no hidden values and while intercepting http requests in the console, the login post request for forms contains username:"username here" password:"password here". I have also attempted adjusting the headers, as I read that that some servers might deny access to non browser header types. Here are my attempts import requests from fake_useragent import UserAgent ua = UserAgent() headers = {"User-Agent": str(ua.chrome)} payload = {"username": "username", "password": "password" } login = requests.get("https://scsctennis.gametime.net/auth", headers=headers) response = requests.post("https://scsctennis.gametime.net/auth", data=payload, cookies=login.cookies, headers=headers) print(response.text) and as well import requests from fake_useragent import UserAgent ua = UserAgent() headers = {"User-Agent": str(ua.chrome)} payload = {"username": "username", "password": "password" } s = requests.session() login = s.get("https://scsctennis.gametime.net/auth", headers=headers) response = s.post("https://scsctennis.gametime.net/auth", data=payload, headers=headers) print(response.text) One thing I have noticed, after the post request, if I attempt to view the cookie - print(response.cookies) there is no cookie, but for the get request, print(login.cookies) there is a cookie. I have followed and read through this blog and the requests documentation, and have gone through many stackoverflow posts. Any help would be appreciated, thanks. Edit You are right, it posts to "https://scsctennis.gametime.net/auth/json-index" Here is changed up code with recommendations. import requests # headers = {'x-requested-with': 'XMLHttpRequest'} headers = {"Content-Type": "application/x-www-form-urlencoded; charset=UTF- 8"} payload = {"username": "username", "password": "password" } s = requests.session() …
type: Question
score: 3
tagged with: cookies
has title: Python-requests, how to login to website
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82902842
favorite count: 0
has answer: http://stackoverflow.com/a/47966202
accepted answer: http://stackoverflow.com/a/47966202
tagged with: http://stackoverflow.com/tag/html
tagged with: python
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/82902141
tagged with: web-scraping
tagged with: python-requests

http://stackoverflow.com/comment/82893319
comment on: http://stackoverflow.com/q/47962048
score: 0
type: Comment
has text: @SoumeshBanerjee no, I'm trying to read the tuples from file
type: QuestionComment

http://stackoverflow.com/comment/82967009
comment on: http://stackoverflow.com/a/47999207
has text: I got the answer of one of my questions! However, I have the list of functions as strings which is coming from somewhere else. For instance f = ['m', 'n', 'z'] rather than f = [m, n, z]. Rest of the things are exactly same as what you did. Now would you please tell me how I can modify it? @Stelios
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/47958141
upvote count: 24
has comment: http://stackoverflow.com/comment/82890200
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82891058
has comment: http://stackoverflow.com/comment/82902919
has comment: http://stackoverflow.com/comment/82885675
score: 21
has comment: http://stackoverflow.com/comment/82891613
has comment: http://stackoverflow.com/comment/82885712
has comment: http://stackoverflow.com/comment/82895733
has comment: http://stackoverflow.com/comment/82885702
has comment: http://stackoverflow.com/comment/82885891
has comment: http://stackoverflow.com/comment/82885591
has comment: http://stackoverflow.com/comment/82885607
type: Question
possible better answer: http://stackoverflow.com/a/47963180
answer count: 2
has comment: http://stackoverflow.com/comment/82931168
has answer: http://stackoverflow.com/a/47963180
has comment: http://stackoverflow.com/comment/82885626
has comment: http://stackoverflow.com/comment/82885727
has body: I was playing around in the python 2.7.6 REPL and came across this behavior. &gt;&gt;&gt; x = -10 &gt;&gt;&gt; y = -10 &gt;&gt;&gt; x is y False &gt;&gt;&gt; x, y = [-10, -10] &gt;&gt;&gt; x is y True It seems that destructured assignment returns the same reference for equivalent values. Why is this?
has comment: http://stackoverflow.com/comment/82885683
favorite count: 0
has answer: http://stackoverflow.com/a/47960543
linked to: http://stackoverflow.com/q/34147515
has comment: http://stackoverflow.com/comment/82885654
has comment: http://stackoverflow.com/comment/82885792
has comment: http://stackoverflow.com/comment/82888710
linked to: http://stackoverflow.com/q/15171695
duplicate of: http://stackoverflow.com/q/34147515
has title: What is the difference between destructured assignment and "normal" assignment?
has comment: http://stackoverflow.com/comment/82902889
downvote count: 3
tagged with: python
accepted answer: http://stackoverflow.com/a/47960543
linked to: http://stackoverflow.com/q/306313

http://stackoverflow.com/a/47936790
accepted answer of: http://stackoverflow.com/q/47936735
downvote count: 0
answers question: http://stackoverflow.com/q/47936735
has comment: http://stackoverflow.com/comment/82843377
has comment: http://stackoverflow.com/comment/82843317
type: Answer
score: 3
has comment: http://stackoverflow.com/comment/82843280
has body: Import ast and use literal_eval. That does the job. import ast lst = ["{'Collaboration':5,'Communication':5,'Creativity':4,'Critical Thinking':4}", "{'Collaboration':5,'Communication':5,'Creativity':5,'Critical Thinking':4}"] res = [ast.literal_eval(x) for x in lst] print(res)
upvote count: 3
has comment: http://stackoverflow.com/comment/82843269
type: AcceptedAnswer

http://stackoverflow.com/a/47995155
has comment: http://stackoverflow.com/comment/82992638
type: Answer
accepted answer of: http://stackoverflow.com/q/47995054
answers question: http://stackoverflow.com/q/47995054
has body: Use dictionary, like this: players = {'player-{}'.format(num): 0 for num in range(1, num_players + 1)} Maybe defaultdict from collections would fit even better for this task: from collections import defaultdict players = defaultdict(int) players['Dirk'] # Returns 0 players['John'] += 1 print(players) # Prints {'John': 1, 'Dirk': 0}
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/47908153
has body: Here's some psuedo code to get you started: def squared(num): try: # convert num to int # do multiplication logic except: # int conversion failed, # multiply num by its length return num Some useful python docs you should read: Getting the length of an object Conversion to int Try and except
accepted answer of: http://stackoverflow.com/q/47907761
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82922501
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/47907761

http://stackoverflow.com/q/47908741
type: Question
accepted answer: http://stackoverflow.com/a/47910729
tagged with: levenshtein-distance
has answer: http://stackoverflow.com/a/47910729
score: 0
tagged with: pandas
upvote count: 1
downvote count: 1
answer count: 1
tagged with: string
favorite count: 0
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
has body: As introduction, I am pretty new to python, I just know how to use pandas mainly for data analysis. I currently have 2 lists of 100+ entries, "Keywords" and "Groups". I would like to generate an output (ideally a dataframe in pandas), where for every entry of the list "Keywords", the closest entry of the list "Groups" is assigned, using the levenshtein distance method. Thank you for your support!
has title: Python - Assign the closest string from List A to List B based on Levenshtein distance - (ideally with pandas)

http://stackoverflow.com/q/47945118
upvote count: 2
has body: Does anyone use pygal.maps.world in pygal to draw a world map? I have 5 different categories that includes several countries for each category. How can I set specific color for each category? Below are part of my code: supra = pygal.maps.world.SupranationalWorld() supra.add('Asia', Asia_list) supra.add('Europe', Europe_list) supra.add('Africa', Africa_list) supra.render() Asia_list, Europe_list, and Africa_list are three lists I defined that include certain countries. How can I set color by myself? Thanks!
tagged with: python-2.7
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/49015779
type: UnansweredQuestion
tagged with: python
score: 2
has title: How to set specific color for each category when using "pygal.maps.world" drawing world map?
tagged with: pygal
type: Question

http://stackoverflow.com/comment/82724513
type: Comment
has text: Well this works also. Can you please test to confirm? So you can mark as correct for visitors to read. It's working perfectly on my computer.
comment on: http://stackoverflow.com/a/47878467
score: 0
type: AnswerComment

http://stackoverflow.com/q/47874307
favorite count: 0
tagged with: python-3.x
tagged with: web-scraping
tagged with: python
has answer: http://stackoverflow.com/a/47874456
tagged with: selenium-webdriver
has title: Trouble getting few items from a webpage
type: AnsweredQuestion
upvote count: 5
tagged with: selenium
has body: I've written a script in python in combination with selenium to parse some items from a webpage. I can't get it working in anyway. The items I'm after are (perhaps) within iframe. I tried to switch it but that doesn't have any effect. I'm still getting nothing except for TimeoutException when it hits the line where I tried to switch the iframe. How can i get it working. Thanks in advance: Here goes the webpage link: URL 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 url = "replace_with_above_url" driver = webdriver.Chrome() driver.get(url) wait = WebDriverWait(driver, 10) wait.until(EC.frame_to_be_available_and_switch_to_it((By.ID, "tradingview_fe623"))) for item in wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, ".quick .apply-common-tooltip"))): print(item.text) driver.quit() Elements within which the items I'm after: 5 1h 1D 1M 1D This is the output I'm expecting to have (it works locally when i try to get them using css selectors): 5 1h 1D 1M 1D This is how it looks in the web:
type: Question
score: 5
accepted answer: http://stackoverflow.com/a/47874456
answer count: 1
downvote count: 0

http://stackoverflow.com/q/47860672
tagged with: django
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47860693
has comment: http://stackoverflow.com/comment/82686208
tagged with: django-views
tagged with: django-urls
has title: Django urls.py mistaking two close urls
type: Question
linked to: http://stackoverflow.com/q/40023708
answer count: 1
score: 0
has body: i'm adding forms to my app to modify my lobbys (my custom model). In urls.py, here is my urlpattern: urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^lobbys/$', views.LobbyListView.as_view(), name='lobbys'), url(r'^lobby/(?P&lt;pk&gt;[\w-]+)/$', views.LobbyDetailView.as_view(), name='lobby-detail'), url(r'^lobby/create/$', views.LobbyCreate.as_view(), name='lobby_create'), url(r'^lobby/(?P&lt;pk&gt;\d+)/update/$', views.LobbyUpdate.as_view(), name='lobby_update'), url(r'^lobby/(?P&lt;pk&gt;\d+)/delete/$', views.LobbyDelete.as_view(), name='lobby_delete'), ] The problem is the following: The third url is supposed to link to a single lobby template identifed with a UUID field as the primary key. Without the three last lines everything worked fine, but when I added my three urls for the forms, I'm getting the error Exception Value: ["'create' is not a valid UUID."] I understand urls.py is taking "create" as a primary key instead of considering it as an urls to an other view. How can I bypass this problem? Thank you very much.
tagged with: django-templates
accepted answer: http://stackoverflow.com/a/47860693

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

http://stackoverflow.com/comment/82863158
type: Comment
type: QuestionComment
score: 1
has text: Possible duplicate of [ImportError: DLL load failed: %1 is not a valid Win32 application. But the DLL's are there](https://stackoverflow.com/questions/19019720/importerror-dll-load-failed-1-is-not-a-valid-win32-application-but-the-dlls)
comment on: http://stackoverflow.com/q/47946187

http://stackoverflow.com/q/47877346
has comment: http://stackoverflow.com/comment/82720842
has comment: http://stackoverflow.com/comment/82720716
type: AnsweredQuestion
type: Question
has body: Based on the documentation for strptime, I believe my code is correct for a 3 character timezone and AM/PM. Why does Python 2.5 and Python 3.6 not like the string time format I am using? import datetime ts = datetime.datetime.strptime( "11/30/2017 01:08:05 PM CST", '%m/%d/%Y %I:%M:%S %p %z' ) or import datetime ts = datetime.datetime.strptime( "11/30/2017 01:08:05 PM CST", '%m/%d/%Y %I:%M:%S %p %Z' ) When run both return: ValueError: time data '11/30/2017 01:08:05 PM CST' does not match format '%m/%d/%Y %I:%M:%S %p %Z'
answer count: 1
score: 0
tagged with: strptime
has comment: http://stackoverflow.com/comment/82720635
has answer: http://stackoverflow.com/a/47877494
tagged with: python
has title: strptime with 3 character timezone and AM/PM
has comment: http://stackoverflow.com/comment/82720771
accepted answer: http://stackoverflow.com/a/47877494

http://stackoverflow.com/q/47915166
has comment: http://stackoverflow.com/comment/82798747
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/82798795
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82798466
accepted answer: http://stackoverflow.com/a/47915221
tagged with: conda
has comment: http://stackoverflow.com/comment/82798882
answer count: 1
has title: Why does conda install pip/setuptools etc...?
favorite count: 0
has body: I am using conda to create clean environments for each my my python projects. I'd like to bootstrap the environmetn with only python, and not muddy it up wtih dependencies that aren't necessary. I noticed that when creating a barebones venv with anaconda: conda create --name myenv python It must install the following new packages, certifi: 2017.11.5-py36hb8ac631_0 pip: 9.0.1-py36h226ae91_4 python: 3.6.3-h3b118a2_4 setuptools: 36.5.0-py36h65f9e6e_0 vc: 14-h2379b0c_2 vs2015_runtime: 14.0.25123-hd4c4e62_2 wheel: 0.30.0-py36h6c3ec14_1 wincertstore: 0.2-py36h7fe50ca_0 Does conda require these in some sense to operate? Can they be kept out of the installation if one only plans to use the python standard library?
tagged with: python
has comment: http://stackoverflow.com/comment/82798472
score: 2
has answer: http://stackoverflow.com/a/47915221
upvote count: 3

http://stackoverflow.com/a/47958689
score: 1
answers question: http://stackoverflow.com/q/47958651
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/82886610
upvote count: 1
has body: Nevermind guys, I found the answer! I simply put it in a while loop like this: while found == 0: repeatTimes += 1 for i in itertools.product([0,1],repeat=repeatTimes): x += 1 print i if binNum == i: found = 1 pos = x break
has comment: http://stackoverflow.com/comment/82886693

http://stackoverflow.com/a/47866245
has comment: http://stackoverflow.com/comment/82701847
score: 5
type: AcceptedAnswer
type: Answer
upvote count: 5
accepted answer of: http://stackoverflow.com/q/47866144
has body: You need manually change years by mask, e.g. all years more as 2017 are subtracted by 100 years: df['Birth Date']= pd.to_datetime(df['Birth Date'],format='%d/%m/%y') df['Birth Date'] = df['Birth Date'].mask(df['Birth Date'].dt.year &gt; 2017, df['Birth Date'] - pd.offsets.DateOffset(years=100)) print (df) Birth Date 0 1973-04-22 1 1953-03-22 2 1973-04-22 3 1977-08-14 4 1950-05-08
answers question: http://stackoverflow.com/q/47866144
downvote count: 0
has comment: http://stackoverflow.com/comment/82703614

http://stackoverflow.com/comment/82989233
type: AnswerComment
has text: His new answer does not include a lambda.
type: Comment
comment on: http://stackoverflow.com/a/48009885
score: 0

pandas
tags question: http://stackoverflow.com/q/47909595
tags question: http://stackoverflow.com/q/47905348
tags question: http://stackoverflow.com/q/47973172
tags question: http://stackoverflow.com/q/47983896
tags question: http://stackoverflow.com/q/47985340
tags question: http://stackoverflow.com/q/47998025
tags question: http://stackoverflow.com/q/47878410
tags question: http://stackoverflow.com/q/47903305
tags question: http://stackoverflow.com/q/47971809
tags question: http://stackoverflow.com/q/47937697
tags question: http://stackoverflow.com/q/47895434
tags question: http://stackoverflow.com/q/47871352
tags question: http://stackoverflow.com/q/47877712
tags question: http://stackoverflow.com/q/47864691
tags question: http://stackoverflow.com/q/48001630
tags question: http://stackoverflow.com/q/47958700
tags question: http://stackoverflow.com/q/47901631
tags question: http://stackoverflow.com/q/47885072
tags question: http://stackoverflow.com/q/47992947
tags question: http://stackoverflow.com/q/47935681
tags question: http://stackoverflow.com/q/48014555
tags question: http://stackoverflow.com/q/47883715
tags question: http://stackoverflow.com/q/47888396
tags question: http://stackoverflow.com/q/47889565
tags question: http://stackoverflow.com/q/47966558
tags question: http://stackoverflow.com/q/47890602
tags question: http://stackoverflow.com/q/47992919
tags question: http://stackoverflow.com/q/47946967
tags question: http://stackoverflow.com/q/47861688
tags question: http://stackoverflow.com/q/47983662
tags question: http://stackoverflow.com/q/47997303
tags question: http://stackoverflow.com/q/47863283
tags question: http://stackoverflow.com/q/47924112
tags question: http://stackoverflow.com/q/47879813
tags question: http://stackoverflow.com/q/47905393
tags question: http://stackoverflow.com/q/47967584
tags question: http://stackoverflow.com/q/47963083
tags question: http://stackoverflow.com/q/47862796
tags question: http://stackoverflow.com/q/47887093
tags question: http://stackoverflow.com/q/47971794
tags question: http://stackoverflow.com/q/48011502
tags question: http://stackoverflow.com/q/47929046
tags question: http://stackoverflow.com/q/47943183
tags question: http://stackoverflow.com/q/47868632
tags question: http://stackoverflow.com/q/47906076
tags question: http://stackoverflow.com/q/47942417
tags question: http://stackoverflow.com/q/47910328
tags question: http://stackoverflow.com/q/47974035
tags question: http://stackoverflow.com/q/47987741
tags question: http://stackoverflow.com/q/47991907
tags question: http://stackoverflow.com/q/47993087
tags question: http://stackoverflow.com/q/47982042
tags question: http://stackoverflow.com/q/47903414
tags question: http://stackoverflow.com/q/47912110
tags question: http://stackoverflow.com/q/47930267
tags question: http://stackoverflow.com/q/47885300
tags question: http://stackoverflow.com/q/47973209
tags question: http://stackoverflow.com/q/48000347
tags question: http://stackoverflow.com/q/47934073
tags question: http://stackoverflow.com/q/47990806
tags question: http://stackoverflow.com/q/47919045
tags question: http://stackoverflow.com/q/47913881
tags question: http://stackoverflow.com/q/47882363
tags question: http://stackoverflow.com/q/47958318
tags question: http://stackoverflow.com/q/47881124
tags question: http://stackoverflow.com/q/47932987
tags question: http://stackoverflow.com/q/48011315
tags question: http://stackoverflow.com/q/47913310
tags question: http://stackoverflow.com/q/47912899
tags question: http://stackoverflow.com/q/47963769
tags question: http://stackoverflow.com/q/47917943
tags question: http://stackoverflow.com/q/47957962
tags question: http://stackoverflow.com/q/47961303
tags question: http://stackoverflow.com/q/47946170
tags question: http://stackoverflow.com/q/47938608
tags question: http://stackoverflow.com/q/48009878
tags question: http://stackoverflow.com/q/47972386
tags question: http://stackoverflow.com/q/47909152
tags question: http://stackoverflow.com/q/47919737
tags question: http://stackoverflow.com/q/47982568

http://stackoverflow.com/a/47966580
downvote count: 0
has body: This statement with tf.device('device:GPU:1') tells tensorflow specifically to use GPU-1, so it won't attempt to use any other device you have. When the model is too big, the recommended way is to use model parallelism via manually splitting your graph into different GPUs. The complication in your case is that the model definition is in the library, so you can't insert tf.device statements for different layers unless you patch tensorflow. But there is a workaround You can define and place variables before invoking inception_v3 builder. This way inception_v3 will reuse these variables and not change its placement. Example: with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE): with tf.device('device:GPU:1'): tf.get_variable("InceptionV3/Logits/Conv2d_1c_1x1/biases", shape=[1000]) tf.get_variable("InceptionV3/Logits/Conv2d_1c_1x1/weights", shape=[1, 1, 2048, 1000]) with tf.device('device:GPU:0'): logits, end_points = inception_v3(inputs) Upon running, you'll see that all variables except Conv2d_1c_1x1 are placed onto GPU-0, while Conv2d_1c_1x1 layer is on GPU-1. The drawback is that you need to know the shape of each variable you want to replace. But it is doable and at least can get your model running.
type: Answer
accepted answer of: http://stackoverflow.com/q/47954926
upvote count: 1
answers question: http://stackoverflow.com/q/47954926
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/82740338
type: QuestionComment
has text: Is `Total` always the last column?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47886931

replace
tags question: http://stackoverflow.com/q/47873033
tags question: http://stackoverflow.com/q/47916288
tags question: http://stackoverflow.com/q/47992385
tags question: http://stackoverflow.com/q/47901931
type: Tag
tags question: http://stackoverflow.com/q/47953966
tags question: http://stackoverflow.com/q/47994373
tag name: replace
tags question: http://stackoverflow.com/q/47931380
tags question: http://stackoverflow.com/q/47930650

http://stackoverflow.com/comment/82795679
has text: @StefanPochmann They didn't claim to have written it. This is obviously homework.
comment on: http://stackoverflow.com/q/47913824
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82924874
type: AnswerComment
comment on: http://stackoverflow.com/a/47977299
type: Comment
has text: @Divakar No problems at all. Thanks for weighing in with your expertise :-)
score: 0

http://stackoverflow.com/q/47971617
has comment: http://stackoverflow.com/comment/82912878
has body: I have a program that creates a GUI form: win=Tk() win.resizeable(width=True, height=True) I have a quit button that was originally defined as: quitButton=tk.Button(win,text="Quit", fg="red",underline=0, command=win.destroy) When it was defined this way, the quit button worked quite well, shutting down the app and closing the window completely. I wanted to wrap this in a dialog box to protect against unexpected checking of the quit button. I, therefore, created a QuitAction function to pop up a dialog box and verify that the user intended to press the button. def QuitAction(): qtitle = 'You pressed the quit button' qmessage = 'Any unsaved changes will be lost!\nDo you want to quit?' q = messagebox.askyesno(qtitle, qmessage) if q: win.destroy When I replace command=win.destroy with command=QuitAction, the function executes (I get the dialog box),dialog box but when I click the YES button (which should execute win.destroy), nothing happens. If I replace win.destroy with any other code (e.g., print('You pressed yes')) it works just fine. If I make another referent to win (e.g.(print(win.minsize())), it works fine. So I appear to be able to reference win from within my QuitAction function. Why is win.destroy not executing?
type: Question
has answer: http://stackoverflow.com/a/47971724
has comment: http://stackoverflow.com/comment/82913317
score: 0
answer count: 1
type: UnansweredQuestion
has title: quit action not being executed from button
tagged with: python
tagged with: tkinter

http://stackoverflow.com/a/47934208
has body: What's being formatted are the five arguments following the format string. Each argument has a corresponding element in the format string. For the sake of the explanation, let's assume that var_name_len has the value 12 (presumably because var_name is a string of length 12 in this hypothetical case). So the format string will be !HHBH12s Breaking that down according to the docs: ! Big-ending byte ordering will be used H self.msg_id will be packed as a two-byte unsigned short H req_len will be packed as above B flag will be packed as a one-byte unsigned char H var_name_len will be packed as a two-byte unsigned short 12s self.varname will be packed as a 12-byte string
has comment: http://stackoverflow.com/comment/82838154
has comment: http://stackoverflow.com/comment/82838067
answers question: http://stackoverflow.com/q/47933042
type: Answer
score: 0

http://stackoverflow.com/comment/82714660
type: QuestionComment
has text: @TheTank that dictionary only maintains the last value for the `'id'` key...
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47873034

http://stackoverflow.com/q/47907505
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/47907978
has comment: http://stackoverflow.com/comment/82782118
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47907637
has title: Get first record from csv file using DictReader
has answer: http://stackoverflow.com/a/47907637
accepted answer: http://stackoverflow.com/a/47907978
type: Question
upvote count: 4
answer count: 2
has comment: http://stackoverflow.com/comment/82782193
downvote count: 0
has body: I am trying to get the first record as a dict from a csv file using the DictReader. I am unable to understand as the documentation only talk about iterating the reader object with open(filename, 'r') as f_in: # Use the csv library to set up a DictReader object. trip_reader = csv.DictReader(f_in) # Use a function on the DictReader object to read the # first trip from the data file and store it in a variable. for row in trip_reader: pprint(row) Is there any function to get the first record as trip_reader[0]?
has comment: http://stackoverflow.com/comment/82782275
favorite count: 0
has comment: http://stackoverflow.com/comment/82782693

http://stackoverflow.com/q/47970574
tagged with: python
has body: I use tornado 4.5.2 with routing implementation. My server have two versions of API, let them call base and fancy. So a client is able to use both of them: GET /base/foo GET /base/baz GET /fancy/foo GET /fancy/baz However, some fancy handlers may not be implemented; In this case a base one should be used. In example: application = web.Application([ (r"/base/foo", handlers.BaseFooHandler, {"some": "settings"}), (r"/base/baz", handlers.BaseBazHandler, {"some": "settings"}), (r"/fancy/foo", handlers.FancyFooHandler, {"some": "settings"}), ]) when cilent requests GET /fancy/baz the BaseBazHandler should do the job. How can I achieve that with tornado routing?
tagged with: tornado
type: Question
has answer: http://stackoverflow.com/a/47970997
answer count: 1
downvote count: 0
tagged with: routes
has title: Tornado routing to a "base" handler
favorite count: 0
score: 2
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/82813022
type: Comment
score: 2
comment on: http://stackoverflow.com/a/47920046
has text: Update the question with your Code trial, relevant `HTML` and `Error Stack Trace`.
type: AnswerComment

http://stackoverflow.com/comment/82871729
type: QuestionComment
score: 2
has text: You edit the text of a *class*. All entry fields have the same class.
comment on: http://stackoverflow.com/q/47951097
type: Comment

http://stackoverflow.com/q/47958793
has body: I want to add 5 to my specific list indices using list comprehension Input arr=[0,0,0,0,0] Output arr=[0,0,5,5,5] I tried [arr[i]+=5 for i in range(2,4)] but it gives an error.
has comment: http://stackoverflow.com/comment/82886900
favorite count: 0
linked to: http://stackoverflow.com/q/8537824
tagged with: python
answer count: 4
type: AnsweredQuestion
score: 3
tagged with: list
upvote count: 3
has comment: http://stackoverflow.com/comment/82886842
has answer: http://stackoverflow.com/a/47958825
has comment: http://stackoverflow.com/comment/82886835
has comment: http://stackoverflow.com/comment/82886952
tagged with: list-comprehension
has answer: http://stackoverflow.com/a/47959661
type: Question
has comment: http://stackoverflow.com/comment/82886927
linked to: http://stackoverflow.com/q/39650471
downvote count: 0
has title: Updating list elements by indices
duplicate of: http://stackoverflow.com/q/39650471
has comment: http://stackoverflow.com/comment/82886832
possible better answer: http://stackoverflow.com/a/47958846
has answer: http://stackoverflow.com/a/47959705
has comment: http://stackoverflow.com/comment/82886878
has comment: http://stackoverflow.com/comment/82886815
has answer: http://stackoverflow.com/a/47958846
accepted answer: http://stackoverflow.com/a/47958825
has comment: http://stackoverflow.com/comment/82886818

http://stackoverflow.com/comment/82910066
type: AnswerComment
type: Comment
has text: @HameerAbbasi `tensordot` expects a tuple of two tuples as the axes param. That's what we are feeding here.
comment on: http://stackoverflow.com/a/47969388
score: 0

http://stackoverflow.com/comment/82994014
type: Comment
comment on: http://stackoverflow.com/q/48012630
type: QuestionComment
score: 2
has text: Your `for` loop stops after it's tested the second-last entry in `users`. But you should break out of that loop as soon as you've found a match: it's silly to keep looking after you've found what you're looking for. Also, `users[index, 0]` won't work, as mentioned in comments to [your previous question](https://stackoverflow.com/questions/48010959/code-not-working-using-python-tried-converting-from-pseudo-code-to-python-a).

http://stackoverflow.com/comment/82762463
has text: that didnt work, its the same as the original problem. it did not trim https://imgur.com/a/qVF2i.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47897482
type: Comment

http://stackoverflow.com/q/47859236
score: 2
downvote count: 0
has body: I have a dataFrame like import pandas as pd current = pd.DataFrame([{ 'a1': 'ab', 'a2': 'value' }, { 'a1': 'ef', 'a2': 'value' }]) I need to create a new dataFrame like below. new = pd.DataFrame([{ 'a1': 'ab', 'a2': 'value', 'a1Val': 'a' }, { 'a1': 'ab', 'a2': 'value', 'a1Val': 'b' }, { 'a1': 'ef', 'a2': 'value', 'a1Val': 'e' }, { 'a1': 'ef', 'a2': 'value', 'a1Val': 'f' }]) Iterating through a dataFrame with iterrows() or itertuples() and modifying or adding rows to a newDatafromve with df.loc() seems like extremely slow. How can I create a dataFrame or modify the current like new in a faster way ?
has title: Expand dataFrame in pandas
type: Question
tagged with: pandas
type: AnsweredQuestion
favorite count: 0
has answer: http://stackoverflow.com/a/47859291
upvote count: 2
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/82683239
tagged with: performance
tagged with: dataframe
tagged with: rows
accepted answer: http://stackoverflow.com/a/47859291
has comment: http://stackoverflow.com/comment/82683321

http://stackoverflow.com/a/48861231
has comment: http://stackoverflow.com/comment/140031572
has body: EDIT (2019-03-08): Gord Thompson commented below with good news from the update logs of sqlalchemy: Since SQLAlchemy 1.3.0, released 2019-03-04, sqlalchemy now supports engine = create_engine(sqlalchemy_url, fast_executemany=True) for the mssql+pyodbc dialect. I.e., it is no longer necessary to define a function and use @event.listens_for(engine, 'before_cursor_execute') Meaning the below function can be removed and only the flag needs to be set in the create_engine statement - and still retaining the speed-up. Original Post: Just made an account to post this. I wanted to comment beneath the above thread as it's a followup on the already provided answer. The solution above worked for me with the Version 17 SQL driver on a Microsft SQL storage writing from a Ubuntu based install. The complete code I used to speed things up significantly (talking >100x speed-up) is below. This is a turn-key snippet provided that you alter the connection string with your relevant details. To the poster above, thank you very much for the solution as I was looking quite some time for this already. import pandas as pd import numpy as np import time from sqlalchemy import create_engine, event from urllib.parse import quote_plus conn = "DRIVER={ODBC Driver 17 for SQL Server};SERVER=IP_ADDRESS;DATABASE=DataLake;UID=USER;PWD=PASS" quoted = quote_plus(conn) new_con = 'mssql+pyodbc:///?odbc_connect={}'.format(quoted) engine = create_engine(new_con) @event.listens_for(engine, 'before_cursor_execute') def receive_before_cursor_execute(conn, cursor, statement, params, context, executemany): print("FUNC call") if executemany: cursor.fast_executemany = True table_name = 'fast_executemany_test' df = pd.DataFrame(np.random.random((10**4, 100))) s = time.time() df.to_sql(table_name, engine, if_exists = 'replace', chunksize = None) print(time.time() - s) Based on the comments below I wanted to take some time to explain some limitations about the pandas to_sql implementation and the way the query is hand…
has comment: http://stackoverflow.com/comment/117744714
has comment: http://stackoverflow.com/comment/84794542
has comment: http://stackoverflow.com/comment/92493249
has comment: http://stackoverflow.com/comment/92508087
has comment: http://stackoverflow.com/comment/84725767
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/93669062
accepted answer of: http://stackoverflow.com/q/48006551
has comment: http://stackoverflow.com/comment/96821447
upvote count: 90
answers question: http://stackoverflow.com/q/48006551
has comment: http://stackoverflow.com/comment/92498220
has comment: http://stackoverflow.com/comment/94172983
type: Answer
has comment: http://stackoverflow.com/comment/96869787
has comment: http://stackoverflow.com/comment/84795874
has comment: http://stackoverflow.com/comment/84797002
has comment: http://stackoverflow.com/comment/92491511
has comment: http://stackoverflow.com/comment/84945748
has comment: http://stackoverflow.com/comment/84960657
has comment: http://stackoverflow.com/comment/84810423
score: 89
has comment: http://stackoverflow.com/comment/84949946
has comment: http://stackoverflow.com/comment/92528633
downvote count: 1
has comment: http://stackoverflow.com/comment/84834402
has comment: http://stackoverflow.com/comment/99912290
has comment: http://stackoverflow.com/comment/84954016
has comment: http://stackoverflow.com/comment/92505669
has comment: http://stackoverflow.com/comment/88142014
has comment: http://stackoverflow.com/comment/86791432
has comment: http://stackoverflow.com/comment/93667237

http://stackoverflow.com/a/58217896
has comment: http://stackoverflow.com/comment/102812070
score: 1
has comment: http://stackoverflow.com/comment/102839630
type: Answer
answers question: http://stackoverflow.com/q/47945077
upvote count: 2
downvote count: 1
has body: I resolved it using python36 -m pip install tensorflow-gpu==1.14

delimiter
tags question: http://stackoverflow.com/q/47895825
tag name: delimiter
type: Tag
tags question: http://stackoverflow.com/q/47906177
tags question: http://stackoverflow.com/q/47889565

http://stackoverflow.com/comment/82837585
score: 0
type: QuestionComment
type: Comment
has text: 3*1024 for a 32x32 pixel RGB image sounds like it's just raw pixel data. `imdecode` is unnecessary in that case, as there's no image format to decode. What's the problem right now?
comment on: http://stackoverflow.com/q/47933073

http://stackoverflow.com/q/47946855
accepted answer: http://stackoverflow.com/a/47947327
tagged with: python
has title: no stdlib hinting in Goland IDE with custom GOPATH and govendor
upvote count: 2
score: 1
tagged with: goland
has comment: http://stackoverflow.com/comment/82864349
downvote count: 1
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82864030
has answer: http://stackoverflow.com/a/47947327
has body: I'm using Goland 2017.3 with Go 1.9.2, and have a custom GOPATH with govendor that replicates the DigitalOcean monorepo, as explained here: https://blog.digitalocean.com/cthulhu-organizing-go-code-in-a-scalable-repo/ The structure looks like this: gocode ├── .env.sh ├── bin ├── src │ └── acmecorp │ ├── teams │ └── vendor ├── pkg and .env.sh looks like this: SCRIPT=`python -c "import os,sys; print(os.path.realpath(os.path.expanduser(sys.argv[1])))" "${0}"` GOCODE=$(dirname $SCRIPT) export GOPATH="$GOCODE" export PATH="$PATH:$GOPATH/bin" I have no issue building code with source .env.sh and govendor build. govendor resolves all dependencies and builds the project. However, when I attempt to set up GOPATH in GoLand and set PROJECT GOPATH to $HOME/gocode, GoLand stops recognizing the stdlib because it starts looking for the stdlib in vendor: $HOME/gocode/src/acmecorp/vendor/time has no buildable Go source files. If I remove the PROJECT GOPATH it finds the stdlib but not the code in the mono repo. How can I get GoLand to stop looking in vendor for the stdlib? Edit: GOROOT is kept as standard in the IDE: screenshot of GOROOT
answer count: 1
favorite count: 0
tagged with: go

http://stackoverflow.com/q/48010571
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
has body: I have a csv file like this: Martin 2/12/17 ECPM_medio 0.23 smaller than 0.27 Incremento Martin 2/12/17 Fill_rate 1.53% smaller than 2.19% Incremento I want to add some headers and save my CSV: Cliente Fecha Data Numbers Info Numbers2 Analisys Martin 2/12/17 ECPM_medio 0.23 smaller than 0.27 Incremento Martin 2/12/17 Fill_rate 1.53% smaller than 2.19% Incremento I work with python 2.7. I can use CSV or Pandas libs!
linked to: http://stackoverflow.com/q/39469325
type: UnansweredQuestion
tagged with: python
has title: How to add headers to a CSV file?
has answer: http://stackoverflow.com/a/48010668
duplicate of: http://stackoverflow.com/q/39469325
type: Question
tagged with: python-2.7
score: 0

http://stackoverflow.com/q/47874643
has title: Python: Efficiently check if value in a list is in another list
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/47874687
possible better answer: http://stackoverflow.com/a/47874830
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47874830
upvote count: 3
type: Question
accepted answer: http://stackoverflow.com/a/47874687
has body: I have a dataframe, user_df, with ~500,000 rows with the following format: | id | other_ids | |------|--------------| | 1 |['abc', efg'] | | 2 |['bbb'] | | 3 |['ccc', 'ddd']| I also have a list, other_ids_that_clicked, with ~5000 items full of other ids: ['abc', 'efg', 'ccc'] I'm looking to de-dupe other_ids_that_clicked using user_df by adding another column in df for when a value in other_ids is in user_df['other_ids'] as such: | id | other_ids | clicked | |------|--------------|-----------| | 1 |['abc', efg'] | 1 | | 2 |['bbb'] | 0 | | 3 |['ccc', 'ddd']| 1 | The way I'm checking is by looping through other_ids_that_clicked for each row in user_df. def otheridInList(row): isin = False for other_id in other_ids_that_clicked: if other_id in row['other_ids']: isin = True break else: isin = False if isin: return 1 else: return 0 This is taking forever, so I was looking for suggestions on best ways to approach this. Thanks!
answer count: 2
tagged with: pandas
score: 3
downvote count: 0

http://stackoverflow.com/q/47957240
tagged with: google-cloud-ml
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82915303
tagged with: python
score: 2
tagged with: tensorflow
type: Question
tagged with: numpy
downvote count: 0
answer count: 1
favorite count: 0
has title: Tensorflow file_io.read_file_to_string says unexpected keyword argument binary_mode
has body: I have just started using google cloud ml engine to train my models however, I keep running into a problem when trying to load the data: My data files are in a compressed .npz(numpy archive) format. pathtodata = os.path.join(FLAGS.inputdir,'input_data_1.npz') f = file_io.read_file_to_string(pathtodata, binary_mode=True) data1 = np.load(BytesIO(f)) Whenever I try to run this on my computer, it works perfectly. The data is loaded from the correct directory. However, when I tried to run a job on CloudML, it says f = file_io.read_file_to_string(pathtodata, binary_mode=True) TypeError: read_file_to_string() got an unexpected keyword argument 'binary_mode' I've tried using with file_io.FileIO(pathtodata, mode='r') as f: f._binary_mode = True data1 = np.load(f) Once again, this works on my own device, but when I load it to google cloud, I get the error File "/root/.local/lib/python2.7/site-packages/trainer/task.py", line 35, in get_data data1 = np.load(f) File "/usr/local/lib/python2.7/dist-packages/numpy/lib/npyio.py", line 405, in load fid.seek(-min(N, len(magic)), 1) # back-up TypeError: seek() takes exactly 2 arguments (3 given) I've looked at all the different ways to import data to a cloudml job from a cloud storage bucket, to no avail. And if you are wondering why, I explicitly told the FileIO object to have _binary_mode to be true, its because it would throw the error that mode wasn't 'r' 'w' 'a' 'r+'. My computer is running Tensorflow 1.2.1. The latest runtime version seemed to be Tensorflow 1.4.0. I checked the source code on github, and it looks correct to me.
has answer: http://stackoverflow.com/a/55371852
upvote count: 2

http://stackoverflow.com/q/47972588
type: Question
has answer: http://stackoverflow.com/a/47972964
has comment: http://stackoverflow.com/comment/82915468
has comment: http://stackoverflow.com/comment/82914897
has comment: http://stackoverflow.com/comment/82914918
tagged with: numpy
score: 0
has comment: http://stackoverflow.com/comment/82914961
has title: How to pass training data to a neural network
answer count: 1
has comment: http://stackoverflow.com/comment/82914827
has comment: http://stackoverflow.com/comment/82914790
tagged with: python
has body: I have the following Python script: import numpy as np from PIL import Image names = [] X = [] labels = [] with open('data.txt', 'r') as f: for line in f.readlines(): tokens = line.split(' ') names.append(tokens[0]) labels.append(int(tokens[1])) for img in range(len(names)): for name in names: img = np.array(Image.open(name)) X.append(img) X = np.array(X) X_to_text_file = np.savetxt('x.txt', X.reshape(np.shape(X)), fmt='%5f') X_data = import_data('x.txt') Is this a correct way to pass image file names and their labels? Provided that data.txt has the following format: img1.png 1 img2.png 1 img3.png 2 img4.png 1 img5.png 1 I'm also getting the error below on the line: X_to_text_file = np.savetxt('x.txt', X.reshape(np.shape(X)), fmt='%5f') TypeError: float argument required, not numpy.ndarray Any ideas on that? Thanks.
has comment: http://stackoverflow.com/comment/82914934
type: UnansweredQuestion

http://stackoverflow.com/q/47971765
answer count: 0
has body: Is there a way to use multithreading here, so that if 4 nodes are created, the file will be sent parallely to 4 nodes. #!/usr/bin/python2 import os x = raw_input("Enter no. of nodes you want to create: ") print "\nEnter ip as follows -- 1 192.168.0.1 \n" d = dict(raw_input().split() for _ in range(int(x))) for i in d: os.system("sshpass -p 'abc@abc' scp /root/Desktop/abc.py root@" + d[i] +":/root/Desktop/md/") print "configured successfully " + i Thanks in advance
type: Question
has comment: http://stackoverflow.com/comment/82913915
tagged with: network-programming
has title: unable to put multithreading logic in this python code
has comment: http://stackoverflow.com/comment/82913284
tagged with: python-2.7
score: 0
type: UnansweredQuestion
tagged with: multithreading
tagged with: python
tagged with: scp

http://stackoverflow.com/q/48000143
has comment: http://stackoverflow.com/comment/82969589
has comment: http://stackoverflow.com/comment/82970310
downvote count: 0
has body: I have a CSV with with 8 keys. Each key contains a list of a variable length for its values. I used csv.DictWriter to create the csv, now I want to read in the csv into a dictionary. I've poured through the docs on csv.DictReader and csv.reader and this is what I've come up with: def ReadCSVasDict(csv_file): with open(csv_file) as file: reader= csv.reader(file) DataTree= {"Class":[],"ClassID":[],"Ship":[],"ShipID":[],"Range":[],"RangeID":[],"AOB":[],"AOBID":[]} keys= list(DataTree.keys()) for rowIndex, row in enumerate(reader): if rowIndex != 0: DataTree[keys[rowIndex-1]]= row[rowIndex-1] ReadCSVasDict("DataTree.csv") The first row of the CSV are the keys (which is why I skip row 0) and this ALMOST works, but I can't figure out how to parse through the entries while preserving their type since DictWriter converts everything to string. How can I read in the csv AND extract the type of each element in each list? Sample data looks like this: Class,ClassID,Ship,ShipID,Range,RangeID,AOB,AOBID "['Unknown', 'Sailboat']",,,,,,, ,"[1, 2]",,,,,, ,,"[['Unknown 1'], ['Sail 1', 'Sail 2', 'Sail 3']]",,,,, ,,,"[[11], [21, 22, 23]]",,,, ,,,,"[1000, [[500, 1000], [1000], [500, 2000]]]",,, ,,,,,"[111, [[211, 212], [221], [231, 232]]]",, ,,,,,,[], ,,,,,,,[] with the code that generated it: def WriteDictasCSV(csv_file, dataDict): with open(csv_file, 'w', newline='') as file: fieldnames = ["Class","ClassID","Ship","ShipID", "Range","RangeID","AOB","AOBID"] writer = csv.DictWriter(file, fieldnames=fieldnames) writer.writeheader() for key in dataDict: writer.writerow({key: dataDict[key]}) sampleDict= {"Class":["Unknown", "Sailboat"],"ClassID":[1,2],"Ship": [["Unknown 1"],["Sail 1","Sail 2","Sail 3"]], "ShipID":[[11],[21,22,23]],"Range":[1000,[[500,1000],[1000], [500,2000]]],"RangeID":[111, [[211,212],[221],[231,232]]],"AOB": [],"AOBID":[]} WriteDictasCSV("DataTree.csv", sampleDict)
has comment: http://stackoverflow.com/comment/82968879
favorite count: 0
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: dictionary
tagged with: parsing
answer count: 0
has comment: http://stackoverflow.com/comment/82969738
upvote count: 1
has comment: http://stackoverflow.com/comment/82969926
has comment: http://stackoverflow.com/comment/82969524
has comment: http://stackoverflow.com/comment/82968933
has comment: http://stackoverflow.com/comment/82969784
has comment: http://stackoverflow.com/comment/82969675
type: Question
score: 1
has title: Create a dictionary from a csv with variable length entries

http://stackoverflow.com/q/47942154
upvote count: 6
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/29390360
type: Question
has comment: http://stackoverflow.com/comment/82855450
tagged with: boto3
tagged with: amazon-web-services
possible better answer: http://stackoverflow.com/a/47946618
has answer: http://stackoverflow.com/a/48127245
accepted answer: http://stackoverflow.com/a/48127245
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/68477873
linked to: http://stackoverflow.com/q/2741496
has answer: http://stackoverflow.com/a/47946618
has title: Python import boto3 error: cannot import name ClientError
favorite count: 0
has body: I am trying to use AWS Simple Email Service with Python. I followed the Send an Email Using the AWS SDK for Python (Boto) sample code. The program cannot correctly import boto3. When it tries to import boto3 for the first time, Python gives error ImportError: cannot import name ClientError. If I try to import again, the error becomes ImportError: cannot import name certs. I have also checked the installed boto3 version and it has same version as the sample code. boto3 Version: 1.4.4 botocore Version: 1.5.95
score: 6
tagged with: python

http://stackoverflow.com/q/47881339
has answer: http://stackoverflow.com/a/58686209
tagged with: sudo
favorite count: 0
has answer: http://stackoverflow.com/a/47890144
tagged with: linux
upvote count: 5
accepted answer: http://stackoverflow.com/a/47890144
answer count: 5
tagged with: python
has body: I'm writing a script in python 3.6 that uses many sudo commands. The script runs on linux machines, as my user. The script is creating a sort of a report, doing ssh to many servers and running commands like lsof. I need a way of making python give my password any time I use sudo. Obviously in the first time I'll enter my password, and it can be saved in the script's memory. I've been using python subprocess to run my sudo commands, for example: cmd = SSH + '-t ' + source + " ' " + SUDO + "-k " + LSOF + "-p " + pid + " ' " output = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True, universal_newlines=True) (out,error) = output.communicate() Is it possible? constraints: Root kit is not allowed Running the script with sudo is not an option, since the script does ssh to many servers, and for security reasons I'm not allowed to do so. Can't change anything in sudoers file.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47892226
downvote count: 0
has comment: http://stackoverflow.com/comment/82728876
possible better answer: http://stackoverflow.com/a/58686209
has comment: http://stackoverflow.com/comment/82746601
type: Question
has answer: http://stackoverflow.com/a/47881489
linked to: http://stackoverflow.com/q/567542
score: 5
has title: How to make python script to give sudo prompt my password
has answer: http://stackoverflow.com/a/63844676
has comment: http://stackoverflow.com/comment/121950308

http://stackoverflow.com/comment/82718297
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47876134
has text: Why do you want them in a Listbox? If you want a scrolled window you can put your Checkboxes in a ScrolledText widget.

http://stackoverflow.com/q/47988038
score: 0
has comment: http://stackoverflow.com/comment/82944844
type: UnansweredQuestion
tagged with: python
has title: How to call/use one ps.1 script functions, variables and classes to another ps.1 files without using psm1 and full directory path?
has answer: http://stackoverflow.com/a/47993136
type: Question
has body: D:\NoName\testfolder1\test1.ps1: function restapi { Write-Host "Initiating Rest Call" $test_value = "1" } D:\NoName\Testfolder1\testfolder2\test2.ps1: Invoke-Expression -Command D:\NoName\testfolder1\test1.ps1 function Invoke-Rest { restapi Write-Host "Invoking rest call and value of test is $test_value" } How I can invoke/import the test1.ps1 file without giving full path, like we do it in Python: import testfolder1 from .testfolder1 import test1
answer count: 1
tagged with: powershell

http://stackoverflow.com/a/47893282
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47874060
has body: The space between the subplots can be adjusted using the following codes plt.subplots_adjust(top=1.5,bottom=0.18, left=0.2, right=2, hspace=0.4, wspace=0.2)
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47874060

http://stackoverflow.com/comment/83011657
comment on: http://stackoverflow.com/q/48009727
type: Comment
type: QuestionComment
has text: And it's my personal wish, because I don't always track SO.
score: 0

http://stackoverflow.com/q/47987124
has comment: http://stackoverflow.com/comment/82943696
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/82943107
tagged with: python-3.x
type: UnansweredQuestion
has body: I am unable to update repository using "add-apt-repository" using- xxx@yyy-HP-ProBook-430-G3:~/Downloads/packages$ sudo add-apt-repository ppa:ondrej/php5-5.6 I am getting the following python error: Traceback (most recent call last): File "/usr/bin/add-apt-repository", line 11, in &lt;module&gt; from softwareproperties.SoftwareProperties import SoftwareProperties, shortcut_handler File "/usr/lib/python3/dist-packages/softwareproperties/SoftwareProperties.py", line 27, in &lt;module&gt; import apt_pkg ModuleNotFoundError: No module named 'apt_pkg' Error in sys.excepthook: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook from apport.fileutils import likely_packaged, get_recent_crashes File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in &lt;module&gt; from apport.report import Report File "/usr/lib/python3/dist-packages/apport/report.py", line 30, in &lt;module&gt; import apport.fileutils File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 23, in &lt;module&gt; from apport.packaging_impl import impl as packaging File "/usr/lib/python3/dist-packages/apport/packaging_impl.py", line 23, in &lt;module&gt; import apt File "/usr/lib/python3/dist-packages/apt/__init__.py", line 23, in &lt;module&gt; import apt_pkg ModuleNotFoundError: No module named 'apt_pkg' Original exception was: Traceback (most recent call last): File "/usr/bin/add-apt-repository", line 11, in &lt;module&gt; from softwareproperties.SoftwareProperties import SoftwareProperties, shortcut_handler File "/usr/lib/python3/dist-packages/softwareproperties/SoftwareProperties.py", line 27, in &lt;module&gt; import apt_pkg ModuleNotFoundError: No module named 'apt_pkg' I have already purged and installed python-apt as described in python-dev installation error: ImportError: No module named apt_pkg but I am still unable to fix the error. I am using Ubuntu-16.04 having default python(2.7.12) with along with Pyt…
tagged with: python
answer count: 0
linked to: http://stackoverflow.com/q/13708180
has title: Unable to update repository using "add-apt-repository" in ubuntu 16.04
has comment: http://stackoverflow.com/comment/82945530
type: Question
tagged with: ubuntu-16.04
has comment: http://stackoverflow.com/comment/82951065

http://stackoverflow.com/comment/82892337
score: 0
type: Comment
has text: @tugkan please see my answer below
type: QuestionComment
comment on: http://stackoverflow.com/q/47957997

http://stackoverflow.com/q/48003894
has body: I tried but I was not able to find similar questions. If there are duplicate questions, please give me the link. I saw someone asked an interesting algorithm problem on a forum. The problem asks how many ways can you split 106 into a linear combination of 10, 20, 50, 1, 2 and 5? For instance, 106=10*6+1*6, 106=50*2+2*1+1*4. I used python to resolve this problem, but it is super slow. And I also generalized my function so it can be applied to not only 106 but also other numbers. Is there any way to make my algorithm faster? It takes me minutes to get 160 ways, which is a very small part of the all solutions and I don't have the patience to wait for more results because as recursion goes one solution will take more and more time. def main(total,*args): def recursion(Sum,method): for arg in args: if Sum&lt;arg: continue method[arg]+=1 if Sum&gt;arg: recursion(Sum-arg,method) else: methods.append(method.copy()) method[arg]-=1 methods=[] recursion(total,{ arg:0 for arg in args}) return len(methods) main(106,10,20,50,1,2,5)
answer count: 1
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48003995
accepted answer: http://stackoverflow.com/a/48003995
tagged with: python
type: AnsweredQuestion
has title: Find linear combinations of integers
type: Question
tagged with: algorithm
score: 0
tagged with: dynamic-programming

http://stackoverflow.com/comment/82856749
type: Comment
comment on: http://stackoverflow.com/q/47943458
has text: If you only want the email (not the `<>`) you can modify @anubhava's regex to `(?<=<)[^>]+(?=>)`
score: 0
type: QuestionComment

http://stackoverflow.com/a/47950638
has comment: http://stackoverflow.com/comment/82871148
score: 2
answers question: http://stackoverflow.com/q/47950507
upvote count: 2
type: AcceptedAnswer
has body: Try to use variables without quotes and without braces like this: {% trans username %}
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47950507

http://stackoverflow.com/comment/82688695
type: QuestionComment
comment on: http://stackoverflow.com/q/47861189
has text: Yes, that is why they are considered as same sale. Product_ID is same, within one month and have 10$ difference. So considered as same sale and sale_group_id is same. Nope, they don't need to be in sequence.
score: 0
type: Comment

http://stackoverflow.com/comment/82814440
comment on: http://stackoverflow.com/q/47920789
type: Comment
has text: What is the average size of a blob you are hoping to find?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82811264
score: 1
has text: row = data( oDate = oDate, building_id =building_list.objects.get(building_id = building_id) , content = content )
comment on: http://stackoverflow.com/q/47921673
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47961586
score: 1
has comment: http://stackoverflow.com/comment/82892556
upvote count: 1
has comment: http://stackoverflow.com/comment/82892378
answers question: http://stackoverflow.com/q/47961214
has comment: http://stackoverflow.com/comment/82892589
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47961214
has body: I think you would like to give this a shot to get all the data in a slightly organized manner: import requests from urllib.parse import urljoin from bs4 import BeautifulSoup url = 'https://www.ceda.com.au/Events/Upcoming-events' res = requests.get(url) soup = BeautifulSoup(res.text,"lxml") for items in soup.select(".list-bx"): event_name = ''.join([item.text for item in items.select(".event-detail-bx a h1")]) event_links = urljoin(url,''.join([item['href'] for item in items.select(".event-detail-bx a")])) speaker_info = items.select(".sub-content-txt h3")[0].next_sibling.strip() event_date = ''.join([' '.join(item.find_parent().select("span")[0].text.split()) for item in items.select(".icon-calendar")]) event_location = ''.join([' '.join(item.find_parent().select("span")[0].text.split()) for item in items.select(".icon-map-marker")]) print("Name: {}\nLink: {}\nSpeaker: {}\nDate: {}\nLocation: {}\n".format(event_name,event_links,speaker_info,event_date,event_location)) Partial Output: Name: 2018 Trustee welcome back Link: https://www.ceda.com.au/Events/Library/Q180124 Speaker: Melinda Cilento, Chief Executive, CEDA Date: 24/01/2018 Location: Brisbane Convention and Exhibition Centre Name: NSW Trustee welcome back 2018 Link: https://www.ceda.com.au/Events/Library/N180130 Speaker: Luke Foley MP, NSW Opposition Leader, Parliament of NSW Date: 30/01/2018 Location: Shangri-La Hotel
type: Answer
has comment: http://stackoverflow.com/comment/82907782

http://stackoverflow.com/comment/82956552
type: QuestionComment
comment on: http://stackoverflow.com/q/47993317
type: Comment
has text: @Daniel web server is nginx and hosting is digital ocean (ubuntu 16.04). also more information added to post.
score: 0

http://stackoverflow.com/a/47859430
upvote count: 2
downvote count: 0
has body: Instead of for k in range(0,100): use for k in range(i + 1, 100): so that k is always greater than i.
answers question: http://stackoverflow.com/q/47859384
type: Answer
score: 2

http://stackoverflow.com/comment/82950982
has text: @james, df["STREET"] = df["name"] + "_" + df["cluster"].astype(str) to get street name. Ill put the explanation in the answer shortly.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47991016
type: Comment

http://stackoverflow.com/a/47876020
type: Answer
score: 1
has body: Try upgrading cx_Freeze. This was fixed in recent versions. Source: cx_Freeze: “No module named 'codecs'” Windows 10
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/47875854

http://stackoverflow.com/comment/115476315
type: AnswerComment
comment on: http://stackoverflow.com/a/54677416
type: Comment
has text: Just want to point out that Anaconda is not essential to the solution. Simply installing the compiled Twisted whl file as @Bishwas describes can solve this without needing Anaconda.
score: 0

http://stackoverflow.com/q/47888054
has comment: http://stackoverflow.com/comment/82742103
favorite count: 0
has comment: http://stackoverflow.com/comment/82742379
tagged with: python-3.x
has title: what is arr = [int(arr_temp) for arr_temp in input().strip().split(' ')] in python
accepted answer: http://stackoverflow.com/a/47888539
has comment: http://stackoverflow.com/comment/82743249
has comment: http://stackoverflow.com/comment/82742147
has comment: http://stackoverflow.com/comment/82741952
tagged with: python
type: AnsweredQuestion
tagged with: list
score: -5
has body: I am new to python and not able to understand what this command means. arr = [int(arr_temp) for arr_temp in input().strip().split(' ')]
type: Question
upvote count: 0
tagged with: arrays
answer count: 1
downvote count: 5
has answer: http://stackoverflow.com/a/47888539

http://stackoverflow.com/comment/83016918
comment on: http://stackoverflow.com/a/48023361
score: 0
type: AnswerComment
type: Comment
has text: I'm afraid I don't know an easy way of using an external lib from choregraphe on a virtual robot. What you can more easily do on a virtual (and real!) robot is write code as standalone Python; like that you can import tweety and manipulate the robot. To get started, look at this: http://doc.aldebaran.com/2-5/getting_started/helloworld_python.html (as IP use "localhost", and as port, instead of 9559 get it here: http://doc.aldebaran.com/2-5/software/choregraphe/choregraphe_preference.html#virtual-robot . Does that make sense?

user-interface
tags question: http://stackoverflow.com/q/47863400
tags question: http://stackoverflow.com/q/47975482
tags question: http://stackoverflow.com/q/47908650
type: Tag
tags question: http://stackoverflow.com/q/47934173
tags question: http://stackoverflow.com/q/47888350
tags question: http://stackoverflow.com/q/47940276
tags question: http://stackoverflow.com/q/47982261
tags question: http://stackoverflow.com/q/47895765
tags question: http://stackoverflow.com/q/47986012
tags question: http://stackoverflow.com/q/47986770
tags question: http://stackoverflow.com/q/48006139
tags question: http://stackoverflow.com/q/47994355
tags question: http://stackoverflow.com/q/47908930
tags question: http://stackoverflow.com/q/47996423
tags question: http://stackoverflow.com/q/47895320
tags question: http://stackoverflow.com/q/47938014
tag name: user-interface
tags question: http://stackoverflow.com/q/47942032

http://stackoverflow.com/q/47878771
has title: python $pred and $folds dont work
has body: I'm trying to use KernelKnnCv using the HOG-descriptors to solve the cifar-10 dataset classification. I found this code snippet: X, y = data, labels hog = HOG_apply(X,cells = 6,orientations = 9,rows = 32,columns = 32,threads = 6) fit_hog = KernelKnnCV(hog, y, k = 20, folds = 4, method = 'braycurtis', weights_function = 'biweight_tricube_MULT', regression = F, threads = 6, Levels = sort(unique(y))) acc_fit_hog = unlist(lapply(1:length(fit_hog$preds),function(x) acc(y[fit_hog$foldsx] ,fit_hog$predsx))) and i get syntax error because of the $preds and $folds. how to fix it?
type: Question
has comment: http://stackoverflow.com/comment/82724067
score: 0
tagged with: knn
answer count: 0
tagged with: classification
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82724073
tagged with: python

http://stackoverflow.com/comment/82785423
type: Comment
type: QuestionComment
has text: `comments[0].div.find_all('div')[-1].text`... maybe?
score: 0
comment on: http://stackoverflow.com/q/47909011

http://stackoverflow.com/comment/82983695
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48007374
score: 2
has text: You’ve created a variable `py` that is shadowing the Python object.

http://stackoverflow.com/comment/82769553
score: 1
comment on: http://stackoverflow.com/a/47901200
type: AnswerComment
has text: Try sudo apt-get python3-h5py and look on the following link: http://www.donkeycar.com/faq/how-do-i-manually-install-the-software-on-raspberry-pi
type: Comment

http://stackoverflow.com/comment/82747256
has text: Sorry, yes, if you just call it on `self` you'll get a never-ending recursion. You need `super().tableInsert(...)`, to call the parent class version of the method, just like you have in `__init__`. And if the wrapper interface is identical to the parent interface, there's really no benefit.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47890059

http://stackoverflow.com/comment/82869998
type: QuestionComment
comment on: http://stackoverflow.com/q/47950107
has text: can you show what context variable you are passing from your view?
score: 0
type: Comment

multiprocessing
tags question: http://stackoverflow.com/q/47859537
tags question: http://stackoverflow.com/q/47910707
tags question: http://stackoverflow.com/q/47875527
tags question: http://stackoverflow.com/q/47896904
tags question: http://stackoverflow.com/q/47908930
tags question: http://stackoverflow.com/q/47876274
tags question: http://stackoverflow.com/q/47955375
tags question: http://stackoverflow.com/q/47897457
tags question: http://stackoverflow.com/q/47951760
tags question: http://stackoverflow.com/q/47889252
tags question: http://stackoverflow.com/q/47885759
tags question: http://stackoverflow.com/q/47881694
tags question: http://stackoverflow.com/q/47933420
tags question: http://stackoverflow.com/q/47905464
tags question: http://stackoverflow.com/q/47971968
tags question: http://stackoverflow.com/q/47863095
tags question: http://stackoverflow.com/q/47997812
tags question: http://stackoverflow.com/q/47861821
tags question: http://stackoverflow.com/q/47929477
tags question: http://stackoverflow.com/q/47897199
tags question: http://stackoverflow.com/q/47885357
tags question: http://stackoverflow.com/q/48004243
tags question: http://stackoverflow.com/q/47894090
tags question: http://stackoverflow.com/q/47916816
tags question: http://stackoverflow.com/q/47929533
tags question: http://stackoverflow.com/q/47862128
tags question: http://stackoverflow.com/q/47952171
tags question: http://stackoverflow.com/q/47978171
type: Tag
tags question: http://stackoverflow.com/q/47894191
tags question: http://stackoverflow.com/q/47909126
tags question: http://stackoverflow.com/q/47925690
tag name: multiprocessing

http://stackoverflow.com/q/48010487
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82989969
has title: What if the hosting Django server don't have the module I imported?
type: Question
has body: I have imported "smtplib" in the code, and I doubt that the server won't have this installed. Is there a CDN for modules in python ?
has comment: http://stackoverflow.com/comment/82989396
has comment: http://stackoverflow.com/comment/82991887
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82989410
has answer: http://stackoverflow.com/a/48010534

http://stackoverflow.com/comment/82971087
comment on: http://stackoverflow.com/a/48001265
type: AnswerComment
has text: OP is using Python 2.7., pip3 is for Python 3
type: Comment
score: 1

http://stackoverflow.com/q/47970982
downvote count: 1
tagged with: discord.py
has answer: http://stackoverflow.com/a/50212681
type: UnansweredQuestion
has body: Recently, I built a discord bot for my personal server using discord.py. I was able to deploy the bot's code onto heroku using git, but when I deployed the code and tried accessing a function of the bot, I did not receive the response. I know the code works as I tested it locally initially. The github link is: https://github.com/ayushboss/Baylor-Discord-Bot All I did on heroku was click on this github link.
has title: How do I deploy a Discord Bot in Python to Heroku?
score: 1
favorite count: 0
type: Question
upvote count: 2
tagged with: python
answer count: 1
tagged with: heroku
tagged with: bots

numpy
tags question: http://stackoverflow.com/q/47946061
tags question: http://stackoverflow.com/q/47918691
tags question: http://stackoverflow.com/q/47933745
tags question: http://stackoverflow.com/q/47970683
tags question: http://stackoverflow.com/q/47920650
tags question: http://stackoverflow.com/q/47932922
tags question: http://stackoverflow.com/q/47928826
tags question: http://stackoverflow.com/q/47984203
tags question: http://stackoverflow.com/q/47878173
tags question: http://stackoverflow.com/q/47893884
tags question: http://stackoverflow.com/q/47945512
tags question: http://stackoverflow.com/q/47969305
tags question: http://stackoverflow.com/q/47880657
tags question: http://stackoverflow.com/q/47995738
tags question: http://stackoverflow.com/q/47975155
tags question: http://stackoverflow.com/q/47945972
tags question: http://stackoverflow.com/q/47866353
tags question: http://stackoverflow.com/q/47945139
tags question: http://stackoverflow.com/q/47888396
tags question: http://stackoverflow.com/q/48012083
tags question: http://stackoverflow.com/q/47974959
tags question: http://stackoverflow.com/q/47946967
tags question: http://stackoverflow.com/q/47983662
tags question: http://stackoverflow.com/q/47914320
tags question: http://stackoverflow.com/q/47916610
tags question: http://stackoverflow.com/q/48002267
tags question: http://stackoverflow.com/q/47923381
tags question: http://stackoverflow.com/q/47897997
tags question: http://stackoverflow.com/q/47987741
tags question: http://stackoverflow.com/q/47888677
tags question: http://stackoverflow.com/q/47959593
tags question: http://stackoverflow.com/q/47957305
tags question: http://stackoverflow.com/q/47962917
tags question: http://stackoverflow.com/q/47929814
tags question: http://stackoverflow.com/q/48005523
tags question: http://stackoverflow.com/q/47917286
tags question: http://stackoverflow.com/q/47982785
tags question: http://stackoverflow.com/q/47972588
tags question: http://stackoverflow.com/q/47884976
tags question: http://stackoverflow.com/q/47902323
tags question: http://stackoverflow.com/q/48012765
tags question: http://stackoverflow.com/q/47891168
tags question: http://stackoverflow.com/q/47959140
tags question: http://stackoverflow.com/q/48011393
tags question: http://stackoverflow.com/q/48013431
tags question: http://stackoverflow.com/q/47933724
tags question: http://stackoverflow.com/q/47954529
tags question: http://stackoverflow.com/q/47887414
tags question: http://stackoverflow.com/q/47857372
tags question: http://stackoverflow.com/q/47972932
tags question: http://stackoverflow.com/q/47983576
tags question: http://stackoverflow.com/q/47957942
tags question: http://stackoverflow.com/q/47954401
tags question: http://stackoverflow.com/q/47957314
tags question: http://stackoverflow.com/q/47932955
tags question: http://stackoverflow.com/q/47908187
tags question: http://stackoverflow.com/q/47882092
tags question: http://stackoverflow.com/q/47891866
tags question: http://stackoverflow.com/q/47870663
tags question: http://stackoverflow.com/q/48006966
tags question: http://stackoverflow.com/q/47954453
tags question: http://stackoverflow.com/q/47866972
tags question: http://stackoverflow.com/q/47909107
tags question: http://stackoverflow.com/q/47886509
tags question: http://stackoverflow.com/q/47892698
tags question: http://stackoverflow.com/q/47867440
tags question: http://stackoverflow.com/q/48008287
tags question: http://stackoverflow.com/q/48007987
tags question: http://stackoverflow.com/q/48005748
tags question: http://stackoverflow.com/q/47948939
tags question: http://stackoverflow.com/q/47920985
tags question: http://stackoverflow.com/q/47986305
tags question: http://stackoverflow.com/q/48007472
tags question: http://stackoverflow.com/q/47943242
tags question: http://stackoverflow.com/q/47963601
tags question: http://stackoverflow.com/q/47949159
tags question: http://stackoverflow.com/q/47874298
tags question: http://stackoverflow.com/q/47969422
tags question: http://stackoverflow.com/q/47984035
tags question: http://stackoverflow.com/q/47935421

http://stackoverflow.com/q/47946202
downvote count: 0
favorite count: 0
tagged with: python
tagged with: python-decorators
tagged with: atomic
has answer: http://stackoverflow.com/a/48007779
accepted answer: http://stackoverflow.com/a/48007779
tagged with: transactions
possible better answer: http://stackoverflow.com/a/47956907
type: Question
type: AnsweredQuestion
has body: I have a python app written in the Tornado Asynchronous framework. When an HTTP request comes in, this method gets called: @classmethod def my_method(cls, my_arg1): # Do some Database Transaction #1 x = get_val_from_db_table1(id=1, 'x') y = get_val_from_db_table2(id=7, 'y') x += x + (2 * y) # Do some Database Transaction #2 set_val_in_db_table1(id=1, 'x', x) return True The three database operations are interrelated. And this is a concurrent application so multiple such HTTP calls can be happening concurrently and hitting the same DB. For data-integrity purposes, its important that the three database operations in this method are all called without another processes reading or writing to those database rows in between. How can I make sure this method has database atomicity? Does Tornado have a decorator for this?
score: 4
tagged with: tornado
upvote count: 4
has title: How to make a tornado request atomic in the Database
answer count: 2
has answer: http://stackoverflow.com/a/47956907

http://stackoverflow.com/q/47955569
has title: How do I get pygame collisions to work
accepted answer: http://stackoverflow.com/a/47956243
has answer: http://stackoverflow.com/a/47956243
score: 0
upvote count: 1
answer count: 1
downvote count: 1
tagged with: pygame
favorite count: 0
has comment: http://stackoverflow.com/comment/82881883
has body: I am making a flappy bird replica and I can't get a collision mechanism. At the moment i'm trying to use .coliderect() but i'm not 100% sure how to. Here is the two classes. I'd like the program to do something, or just print('x') when the bird and the pipe collide, but when they collide at the moment the program does not do or output anything. import pygame vec = pygame.math.Vector2 BLACK = (0,0,0) WIDTH = 500 HEIGHT = 400 pygame.init() window = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Flappy Bird') clock = pygame.time.Clock() class Bird(): def __init__(self): self.skin = pygame.image.load('bird2.png') self.rect = self.skin.get_rect() self.rect.center = (WIDTH / 2, HEIGHT / 2) self.vx = 0 self.vy = 0 self.pos = vec(WIDTH / 2, HEIGHT / 2) self.vel = vec(0, 0) self.acc = vec(0, 0) def update(self): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() window.fill(BLACK) self.acc = vec(0, 0.7) #having 0.5 adds gravity self.vy = 0 keys = pygame.key.get_pressed() if keys[pygame.K_SPACE]: self.vel.y = -7 if keys[pygame.K_LEFT]: self.acc.x = -0.5 #change to y to add vertical motion if keys[pygame.K_RIGHT]: self.acc.x = 0.5 #change to y to add vertical motion #applys friction self.acc.x += self.vel.x * -0.08 #FRICTION #motion equations self.vel += self.acc self.pos += self.vel + 0.5 * self.acc self.rect.center = self.pos window.blit(self.skin, self.pos) class Pipe(): def __init__(self,x,y): self.image = pygame.Surface((50,60)) self.image.fill(RED) self.rect = self.image.get_rect() self.pos = vec(x,y) def blit_pipe(self): window.blit(self.image, self.pos) def border_check(): if (flappy.pos.y)+32 &gt; HEIGHT: #this is the very top of the flappy print("You are under\n") pygame.quit() quit() if flappy.pos.y &lt; 0: print("You are over\n") #this is the very top of the flappy pygame.quit() quit() pipey = Pipe(300,200) pipey.blit_pipe() pipey2 = Pipe(100,200) pipey2.blit_pipe() flappy = Bird() window.blit(flappy.skin, flap…
tagged with: python
type: AnsweredQuestion
type: Question

http://stackoverflow.com/q/47897401
downvote count: 0
has answer: http://stackoverflow.com/a/47897508
has comment: http://stackoverflow.com/comment/82763240
answer count: 2
tagged with: pandas
has body: I have a pandas DataFrame that looks like: ID | StateName | ZipCode ____________________________________ 0 MD 20814 1 90210 2 DC 20006 3 05777 4 12345 I have a function that will fill in StateName based on ZipCode value: def FindZip(x): search = ZipcodeSearchEngine() zipcode = search.by_zipcode(x) return zipcode['State'] I want to fill in the blanks in the column StateName - based on the value of the corresponding ZipCode. I've unsuccessfully tried this: test['StateName'] = test['StateName'].apply(lambda x: FindZip(test['Zip_To_Use']) if x == "" else x) Basically, I want to apply a function to a column different from the column I am trying to change. I would appreciate any help! Thanks!
has answer: http://stackoverflow.com/a/47909979
has title: Replace value of column based on value in separate column
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
tagged with: apply
type: Question

http://stackoverflow.com/comment/82841353
type: Comment
comment on: http://stackoverflow.com/a/47935755
type: AnswerComment
has text: The other question might help `df.groupby(pd.to_datetime(df['Index']).dt.weekday_name).size().to_frame('Count')`.
score: 0

http://stackoverflow.com/comment/82683717
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47859452
score: 0
has text: Did you try to run the code?

http://stackoverflow.com/q/47925182
tagged with: python
tagged with: curses
has comment: http://stackoverflow.com/comment/82849618
has comment: http://stackoverflow.com/comment/82821839
answer count: 0
has body: Is it possible to move item in a pythondialog menu or in a listbox with urwid? More precisely, I have to handle task priorities in a dialog box (that is why I thought about pythondialog, curses or urwid) and if I move up a task (a task name in fact), with the key-up keyboard (for example), it will be considered as more important than the task just below. It is like when one change a boot priority order in bios. It is the same idea. The tasks name are not editable, one can just reorder them.
type: Question
has comment: http://stackoverflow.com/comment/82819495
score: 0
has title: python: move menu item in pythondialog or urwid
linked to: http://stackoverflow.com/q/6807808
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82847567

http://stackoverflow.com/q/47973193
has body: I know I can implement in the base class some function to raise when subclass fails to override some method. def some_method( self ): raise NotImplementedError But how can I do the opposite, i.e. raise only when the subclass does override this method? Thanks! Edit: I'm trying to prevent people from overriding getitem/getattr so the namespace clash doesn't apply here. Edit: I already tried to check if the subclass method is base class method. This worked under CPython, but not PyPy. Is there any all-around solution?
linked to: http://stackoverflow.com/q/30543615
upvote count: 2
has comment: http://stackoverflow.com/comment/82916044
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82916023
downvote count: 1
has comment: http://stackoverflow.com/comment/82916070
has answer: http://stackoverflow.com/a/47973253
has title: Raise only when subclass overrides certain base class method?
type: Question
has comment: http://stackoverflow.com/comment/82915972
score: 1
tagged with: inheritance
has comment: http://stackoverflow.com/comment/82915982
has answer: http://stackoverflow.com/a/47973301
answer count: 3
has comment: http://stackoverflow.com/comment/82916054
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/47973290
has comment: http://stackoverflow.com/comment/82916013

http://stackoverflow.com/a/47877700
score: 13
downvote count: 0
has body: Using direct numpy broadcasting, you can do this: dist = np.sqrt(((a[:, None] - b[:, :, None]) ** 2).sum(0)) Alternatively, scipy has a routine that will compute this slightly more efficiently (particularly for large matrices) from scipy.spatial.distance import cdist dist = cdist(a, b) I would avoid solutions that depend on factoring-out matrix products (of the form A^2 + B^2 - 2AB), because they can be numerically unstable due to floating point roundoff errors.
upvote count: 13
answers question: http://stackoverflow.com/q/47877530
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47877530
type: Answer

http://stackoverflow.com/comment/82977690
has text: @phkr Added another example for clarification. Also, I'd encourage you to check it with different kernels and input tensor :)
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47992680
score: 0

http://stackoverflow.com/q/47869933
type: Question
tagged with: swig
score: 0
has comment: http://stackoverflow.com/comment/82704918
has body: If I have a C function like this: y = myfunc(x){ y = x + 2; } I know how to write the *.i file and make the above function callable in Python. But if I have a C function like this: void encode(int x[], int len, int y[]){ int i; for (i=0; i&lt;len; i++){ y[i] = x[i] * 2; } } I do not know how to write the *.i interface and failed to find over the internet. Anyone could give me some hint?
has comment: http://stackoverflow.com/comment/82705040
has comment: http://stackoverflow.com/comment/82705014
tagged with: python
has title: How to extend C void function to python using SWIG?
has comment: http://stackoverflow.com/comment/82951308
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/83268773
comment on: http://stackoverflow.com/a/47918901
type: Comment
score: 0
has text: of course you can. http://www.django-rest-framework.org/api-guide/throttling/#setting-the-throttling-policy tells you how to have specific throttling for one view.
type: AnswerComment

http://stackoverflow.com/q/47956261
tagged with: tensorflow
type: Question
downvote count: 0
tagged with: neural-network
tagged with: deep-learning
answer count: 1
tagged with: python
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has body: I'm training a neural network to recognize characters using the notMNIST dataset, but once I run it its accuracy stays relatively constant after each iteration. I've tried lower the learning rate but it wasn't any different. What might be the problem? I think the problem might be in the implementation of the tf.nn.relu() method, and how I calculate the predictions, since I'm fairly new at Tensor Flow and neural networks Here is a screenshot of my program running and you can see that the accuracy on the training set, validation set, and test set are all pretty bad num_steps=801 def accuracy(predictions, labels): return (100.0 * np.sum(np.argmax(predictions,1) == np.argmax(labels,1)) / predictions.shape[0]) with tf.Session(graph=graph) as session: #this is a one-time operation which ensure the parameters get initialized #we described in the graph: random weights for the matrix, zeros for the #biases. tf.global_variables_initializer().run() print("initialized") for step in range(num_steps): #run the computations. we tell .run() that we want to run the optimizer, #and get the loss value and the training predictions returned as numpy #arrays. _, l, predictions = session.run([optimizer,loss, train_prediction]) if (step % 100 ==0): print("loss at step %d: %f" % (step,l)) print("Training accuracy: %.1f%%" % accuracy( predictions, train_labels[:train_subset,:])) #calling .eval() on valid_prediction is basically like calling run(), but #just to get that one numpy array. Note that it recomputes all its graph #dependencies. print("Validation accuracy: %.1f%%" % accuracy( valid_prediction.eval(), valid_labels)) print("test accuracy: %.1f%%" % accuracy(test_prediction.eval(),test_labels)) batch_size = 128 hidden_nodes = 1024 graph = tf.Graph() with graph.as_default(): #input data. For the training data, we use a placeholder that will be fed #at run time with a training minibatch tf_train_dataset = tf.placeholder(tf.float32, shape=(batch_size, image_size*image_size), name="td") tf…
tagged with: machine-learning
has title: My neural network doesn't improve its accuracy
has answer: http://stackoverflow.com/a/47956452
score: 2

http://stackoverflow.com/q/47933019
has body: I am trying to learn how to sample truncated distributions. To begin with I decided to try a simple example I found here example I didn't really understand the division by the CDF, therefore I decided to tweak the algorithm a bit. Being sampled is an exponential distribution for values x&gt;0 Here is an example python code: # Sample exponential distribution for the case x&gt;0 import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm def pdf(x): return x*np.exp(-x) xvec=np.zeros(1000000) x=1. for i in range(1000000): a=x+np.random.normal() xs=x if a &gt; 0. : xs=a A=pdf(xs)/pdf(x) if np.random.uniform()&lt;A : x=xs xvec[i]=x x=np.linspace(0,15,1000) plt.plot(x,pdf(x)) plt.hist([x for x in xvec if x != 0],bins=150,normed=True) plt.show() Ant the output is: The code above seems to work fine only for when using the condition if a &gt; 0. :, i.e. positive x, choosing another condition (e.g. if a &gt; 0.5 :) produces wrong results. Since my final goal was to sample a 2D-Gaussian - pdf on a truncated interval I tried extending the simple example using the exponential distribution (see the code below). Unfortunately, since the simple case didn't work, I assume that the code given below would yield wrong results. I assume that all this can be done using the advanced tools of python. However, since my primary idea was to understand the principle behind, I would greatly appreciate your help to understand my mistake. Thank you for your help. EDIT: # code updated according to the answer of CrazyIvan from scipy.stats import multivariate_normal RANGE=100000 a=2.06072E-02 b=1.10011E+00 a_range=[0.001,0.5] b_range=[0.01, 2.5] cov=[[3.1313994E-05, 1.8013737E-03],[ 1.8013737E-03, 1.0421529E-01]] x=a y=b j=0 for i in range(RANGE): a_t,b_t=np.random.multivariate_normal([a,b],cov) # accept if within bounds - all that is neded to truncate if a_range[0]&lt;a_t and a_t&lt;a_range[1] and b_range[0]&lt;b_t and b_t&lt;b_range[1]: print(dx,dy) EDIT: I changed the code by …
tagged with: random
answer count: 3
has answer: http://stackoverflow.com/a/47935048
downvote count: 0
accepted answer: http://stackoverflow.com/a/47936094
favorite count: 0
has answer: http://stackoverflow.com/a/47936094
tagged with: python
has comment: http://stackoverflow.com/comment/82854316
has comment: http://stackoverflow.com/comment/82854122
tagged with: mcmc
score: 8
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/76641131
tagged with: probability
has title: How to properly sample truncated distributions?
has comment: http://stackoverflow.com/comment/82860361
upvote count: 8
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82860486
has comment: http://stackoverflow.com/comment/82839592
possible better answer: http://stackoverflow.com/a/47935048
has comment: http://stackoverflow.com/comment/82860617
has comment: http://stackoverflow.com/comment/82850951

http://stackoverflow.com/q/47938133
has comment: http://stackoverflow.com/comment/82845512
tagged with: python
has comment: http://stackoverflow.com/comment/82848440
tagged with: django
has answer: http://stackoverflow.com/a/49161153
tagged with: celery
possible better answer: http://stackoverflow.com/a/49117910
type: AnsweredQuestion
has title: Django Celery retry current task with failed data set only
has answer: http://stackoverflow.com/a/49117910
accepted answer: http://stackoverflow.com/a/49161153
tagged with: django-celery
has body: I have the following code from utils import SendSMS from celery.exceptions import * @celery.task(bind=True, max_retries=3) def send_sms(self,sms_list): failed_items = [] for sms_item in sms_list: status = SendSMS( **sms_item ) if status in ['Timeout','Error']: failed_items.append( sms_item ) if len(failed_items) &gt; 0: raise self.retry(failed_items) return "sms(s) send successfully." I want to retry the task but with different data set, with only failed items. I mean how can I achieve this line: raise self.retry(failed_items) ? Thanks in advance.
type: Question
answer count: 2
score: 0

http://stackoverflow.com/q/47978649
tagged with: dataframe
score: 6
has body: import statsmodels.api as sm xdat = rets['EUROSTOXX'] xdat = sm.add_constant(xdat) ydat = rets['VSTOXX'] model = sm.OLS(y=ydat,x=xdat).fit() I don't understand why there is an error popping up as stated on the topic. The following is the tail of the Dataframe of rets Out[105]: EUROSTOXX VSTOXX 2014-12-23 0.011835 -0.039307 2014-12-24 -0.002449 0.000000 2014-12-29 0.000160 0.121598 2014-12-30 -0.015574 0.048998 2014-12-31 0.003336 0.000000
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/47979324
tagged with: statsmodels
has title: Python OLS model: __init__() missing 1 required positional argument: 'endog'
type: Question
tagged with: charts

http://stackoverflow.com/q/47905076
type: Question
has comment: http://stackoverflow.com/comment/82777641
downvote count: 0
tagged with: permutation
favorite count: 0
tagged with: python
answer count: 0
has body: I am facing some issues in putting things together while implementing in python (Just a beginner). I want to create set of data array on permutation and combination based on another array vector which will only be based on three types of numbers -1, 0, 1. It can be in any order and in any number. It can be [-1 1 0 0 -1] or [-1 -1 0 0] or [-1 1] etc. Suppose I have data array of 4 values [a b c d] = [5 4 0 0] based on model chemical reaction a + b -&gt; c + d then according to this reaction changing array vector be created as v = [-1 -1 1 1], as a and b are producing c and d until a or b exhausted and reach 0. Now when we apply this array vector on [a b c d], we will get new array's like [4 3 1 1], [3 2 2 2], [2 1 3 3], [1 0 4 4]... now we cannot generate new array further as v cannot be applied on [1 0 4 4] because b is 0. This is a simple case. I have this simple code running to create next array but not in loops to create further array's :: [3 2 0 2], [2 1 0 3], [1 0 0 4]. class SumList(object): def __init__(self, this_list): self.mylist = this_list def __add__(self, other): new_list = [] zipped_list = zip(self.mylist, other.mylist) for item in zipped_list: new_list.append(item[0] + item[1]) return SumList(new_list) def __repr__(self): return str(self.mylist) list1 = SumList([5, 4, 0, 0]) list2 = SumList([-1, -1, 1, 1]) sum = list1 + list2 print(sum) This is what I want to achieve finally:: If I have multiple reactions and multiple vector array's, like a + b -&gt; c c -&gt; a + b c -&gt; b + d v1 = [-1 -1 1 0], v2 = [1 1 -1 0], v3 = [0 1 -1 1] Where, initial quantity of [a b c d] = [5 4 0 0] and want to apply v1, v2 and v3 on [a b c d] to create new data array's, like... When v1 is applied on [a b c d] it will give [4 3 1 0], [3 2 2 0], [2 1 3 0], [1 0 4 0] When v2 is applied on [a b c d] it will check that v2 cannot be applied on [5 4 0 0], as number of total molecules in the system is fixed (a=5, b=4) at max and cannot be increased to a=6, b=5 respectively, so i…
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/82777141
upvote count: 1
has comment: http://stackoverflow.com/comment/82874468
has title: How to create graph dictionary for traversal based on permutation and combination in python
tagged with: combinations
has comment: http://stackoverflow.com/comment/82873897

http://stackoverflow.com/a/47916493
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47913841
accepted answer of: http://stackoverflow.com/q/47913841
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82873943
has body: If you just want the histogram values, then just calculate them directly using something like numpy.histogram.

http://stackoverflow.com/comment/82803454
has text: @GarbageCollector Posted,
comment on: http://stackoverflow.com/q/47917731
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47975866
has title: pandas.read_excel parameter "sheet_name" not working
tagged with: pandas
has comment: http://stackoverflow.com/comment/82920780
has answer: http://stackoverflow.com/a/62111703
upvote count: 19
favorite count: 0
has answer: http://stackoverflow.com/a/74665382
has answer: http://stackoverflow.com/a/79230406
answer count: 9
possible better answer: http://stackoverflow.com/a/47975995
tagged with: python
has answer: http://stackoverflow.com/a/51312215
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/75938191
has answer: http://stackoverflow.com/a/73358216
has answer: http://stackoverflow.com/a/47975995
score: 19
tagged with: excel
type: Question
has answer: http://stackoverflow.com/a/49694269
has answer: http://stackoverflow.com/a/78833602
accepted answer: http://stackoverflow.com/a/49694269
has body: According to pandas doc for 0.21+, pandas.read_excel has a parameter sheet_name that allows specifying which sheet is read. But when I am trying to read the second sheet from an excel file, no matter how I set the parameter (sheet_name = 1, sheet_name = 'Sheet2'), the dataframe always shows the first sheet, and passing a list of indices (sheet_name = [0, 1]) does not return a dictionary of dataframes but still the first sheet. What might be the problem here?

http://stackoverflow.com/comment/83028052
comment on: http://stackoverflow.com/a/48010031
has text: XPath helps to extract specific data from the XML code but calculations are better on python side. You can mix @cpburnz answer and mine for example to get the day you are interested in as "d4 = tree.find('//D4/DAYPROFILE[@DATE="30-11-2017"]')". Then iterate all interval attributes as "for ip in d4.findall('IP/@INTERVAL')" and do your calculations. And so on. Hope that helps.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47902735
type: Answer
score: 1
upvote count: 1
has body: Use columns=[header] in your pd.Dataframe constructor i.e df0=pd.DataFrame(A,columns=['A']) df1=pd.DataFrame(B,columns=['B']) . . .
downvote count: 0
answers question: http://stackoverflow.com/q/47902580

http://stackoverflow.com/comment/121745552
has text: 3 years and 3 thousand views later, this question still doesn't have an answer?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47861490

http://stackoverflow.com/q/47922918
tagged with: python-2.7
score: 0
upvote count: 1
downvote count: 1
answer count: 1
favorite count: 0
has body: I am attempting to write a nested loop in order to compute a number of values for temperature (te) against time (t), each with a different timestep (dt) being used. dt_values = [0.05, 0.025, 0.1, 0.05, 0.001] for j in dt_values: t = np.arange(0,100,[j]) te = np.zeros(len(t)) te[0] = te_init dt = j def f(te): y = -r*(te - te_surr) # y is the derivative return y for i in range(1,len(t)): te[i] = te[i-1] + f(te[i-1])*[j] plt.plot(t, te) However I am receiving the following error message: t = np.arange(0,100,[j]) TypeError: unsupported operand type(s) for /: 'int' and 'list' So, it is not possible to use a list in the way I have done when creating the t array? I cannot use, for example for j in range ... As the values I have for dt are not separated evenly. So, I am wondering, is there another way of defining dt_values which is supported in np.arange?
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47922982
accepted answer: http://stackoverflow.com/a/47922982
type: Question
tagged with: matplotlib
has title: Unsupported operand type in array for a nested loop

http://stackoverflow.com/a/47979324
has body: According to the documentation of OLS, the function's parameters aren't called y and x, but endog and exog. You can simply change your function call to: model = sm.OLS(ydat, xdat).fit() or: model = sm.OLS(endog=ydat, exog=xdat).fit()
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47978649
score: 7
upvote count: 7

http://stackoverflow.com/comment/82753252
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47881296
has text: This is a great answer and np is really powerful, however, i'll pick Jezrael as best answer since it uses datafram's internal function. I appreciate it nonetheless.
type: AnswerComment

http://stackoverflow.com/a/48096611
upvote count: 9
type: Answer
has body: I have been tweaking a lot these days to solve this problem. Finally, I haven't solved the mystery of the memory size described in the question. I guess while computing the gradient tensoflow accumulate a lot of additional memory for computing gradient. I need to check the source of the tensorflow which seems very cumbersome at this time. You can check how much memory your model is using from terminal by the following command, nvidia-smi judging from this command you can guess how much additional memory you can use. But the solution to these type of problem lies on reducing the batch size, For my case reducing the size of the batch to 3 works. This may vary model to model. But what if you are using a model where the embedding matrix is much bigger that you cannot load them into memory? The solution is to write some painy code. You have to lookup on the embedding matrix and then load the embedding to the model. In short, for each batch, you have to give the lookup matrixes to the model(feed them by the feed_dict argument in the sess.run()). Next you will face a new problem, You cannot make the embeddings trainable in this way. The solution is to use the embedding in a placeholder and assign them to a Variable(say for example A). After each batch of training, the learning algorithm updates the variable A. Then compute the output of A vector by tensorflow and assign them to your embedding matrix which is outside of the model. (I said that the process is painy) Now your next question should be, what if you cannot feed the embedding lookup to the model because it's so big. This is a fundamental problem that you cannot avoid. That's why the NVIDIA GTX 1080, 1080ti and NVIDA TITAN Xp have so price difference though NVIDIA 1080ti and 1080 have the higher frequency to run an execution.
accepted answer of: http://stackoverflow.com/q/48007984
answers question: http://stackoverflow.com/q/48007984
downvote count: 0
has comment: http://stackoverflow.com/comment/83183131
score: 9
has comment: http://stackoverflow.com/comment/83182323
has comment: http://stackoverflow.com/comment/83267742
type: AcceptedAnswer

http://stackoverflow.com/comment/82690264
has text: Best way to debug something like this is to add lots of print statements so that you can "see" what the code is doing. As a start, add a print statement under every `if`and also in the corresponding `else`, adding the `else:` if it doesn't exist. (I would have done this myself, but I don't want to spam a website with hundreds or thousands of requests.)
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47862285
type: Comment

http://stackoverflow.com/comment/82729586
type: Comment
type: QuestionComment
has text: Please use Google and do it yourself.
comment on: http://stackoverflow.com/q/47881857
score: 0

http://stackoverflow.com/a/47922506
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82816638
type: Answer
answers question: http://stackoverflow.com/q/47922302
score: 2
downvote count: 0
has body: Use glob to get all files in the folder then use for loop and append the output to the variable. import glob text = '' for file in glob.glob('folder_name/*.docx'): text += docx2txt.process(file)
accepted answer of: http://stackoverflow.com/q/47922302
upvote count: 2

http://stackoverflow.com/a/47864737
upvote count: 30
has body: I believe you need first parameter parse_dates in read_csv for parse column to datetime and then groupby by weekday_name and aggregate: df_data = pd.read_csv('data.csv', parse_dates=['arrival_date']) week_df = df_data.groupby(df_data['arrival_date'].dt.weekday_name).mean() print (week_df) price_1 price_2 price_3 price_4 arrival_date Friday 71.952235 1130.106565 64.900476 25.779593 Monday 71.026544 1391.363442 67.362277 25.976418 Saturday 83.149556 1364.312304 76.538815 27.371489 Sunday 57.553097 1223.977557 51.952801 21.552876 Thursday 66.831764 1364.982781 63.940393 23.887128 Tuesday 79.006604 1241.603185 75.360606 28.250994 Wednesday 76.021324 1276.650570 72.485089 23.611288 For numeric index use weekday: week_df = df_data.groupby(df_data['arrival_date'].dt.weekday).mean() print (week_df) price_1 price_2 price_3 price_4 arrival_date 0 71.026544 1391.363442 67.362277 25.976418 1 79.006604 1241.603185 75.360606 28.250994 2 76.021324 1276.650570 72.485089 23.611288 3 66.831764 1364.982781 63.940393 23.887128 4 71.952235 1130.106565 64.900476 25.779593 5 83.149556 1364.312304 76.538815 27.371489 6 57.553097 1223.977557 51.952801 21.552876 EDIT: For correct ordering add reindex: days = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday', 'Sunday'] week_df = df_data.groupby(df_data['arrival_date'].dt.weekday_name).mean().reindex(days) print (week_df) price_1 price_2 price_3 price_4 arrival_date Monday 71.026544 1391.363442 67.362277 25.976418 Tuesday 79.006604 1241.603185 75.360606 28.250994 Wednesday 76.021324 1276.650570 72.485089 23.611288 Thursday 66.831764 1364.982781 63.940393 23.887128 Friday 71.952235 1130.106565 64.900476 25.779593 Saturday 83.149556 1364.312304 76.538815 27.371489 Sunday 57.553097 1223.977557 51.952801 21.552876
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47864691
has comment: http://stackoverflow.com/comment/105524748
accepted answer of: http://stackoverflow.com/q/47864691
type: Answer
has comment: http://stackoverflow.com/comment/82695541
score: 30
downvote count: 0
has comment: http://stackoverflow.com/comment/82695721
has comment: http://stackoverflow.com/comment/82695564

http://stackoverflow.com/comment/82828957
has text: So I think I figured out a bit of the issue. My form is wrapped up in a jinja loop that creates blocks of html based on the number of attribute id's sent into the page. This is making it so that each form has the same id. Not sure how to remedy this.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47899093

http://stackoverflow.com/q/47912899
score: 1
has answer: http://stackoverflow.com/a/47913247
has title: find alphabets count per date in python pandas
type: Question
tagged with: numpy
tagged with: dataframe
has comment: http://stackoverflow.com/comment/82793962
tagged with: pandas
upvote count: 1
has body: I've a list of dates and alphabets. I've to find count of alphabets occurring within a week. I'm trying to group by them by alphabets and re-sample it by '1w'. But i get some weird data frame which contains MultiIndex. How can i do all this and get the DataFrame with just three rows containing score, new re-sample date and count? PS: What i'm looking for is a week and count for occurrence of every alphabet in that week. something like that datetime alphabet count 2016-12-27 22:57:45.407246 a 1 2016-12-30 22:57:45.407246 a 2 2017-01-02 22:57:45.407246 a 0 2016-12-27 22:57:45.407246 b 0 2016-12-30 22:57:45.407246 b 1 2017-01-02 22:57:45.407246 b 4 2016-12-27 22:57:45.407246 c 7 2016-12-30 22:57:45.407246 c 0 2017-01-02 22:57:45.407246 c 0 Here is the code import random import pandas as pd import datetime def randchar(a, b): return chr(random.randint(ord(a), ord(b))) # Create a datetime variable for today base = datetime.datetime.today() # Create a list variable that creates 365 days of rows of datetime values date_list = [base - datetime.timedelta(days=x) for x in range(0, 365)] score_list =[randchar('a', 'h') for i in range(365)] df = pd.DataFrame() # Create a column from the datetime variable df['datetime'] = date_list # Convert that column into a datetime datatype df['datetime'] = pd.to_datetime(df['datetime']) # Set the datetime column as the index df.index = df['datetime'] # Create a column from the numeric score variable df['score'] = score_list df_s = tt = df.groupby('score').resample('1w').count()
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/47913247
tagged with: python
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/82793679

http://stackoverflow.com/a/52903853
type: Answer
downvote count: 0
upvote count: 4
score: 4
answers question: http://stackoverflow.com/q/47954901
has body: As an addition to EnergyNumbers' answer, you also have to make sure that you've actually quit chrome before launching your script. In my case I constantly got the error Chrome failed to start: exited abnormally (unknown error: DevToolsActivePort file doesn't exist) But that instantly disappeared when I quit chrome before launching the script. Apparantly, no 2 instances of the same profile can be opened at the same time.

django-forms
tags question: http://stackoverflow.com/q/47960839
tags question: http://stackoverflow.com/q/47952433
tags question: http://stackoverflow.com/q/47927356
tags question: http://stackoverflow.com/q/47875322
tags question: http://stackoverflow.com/q/47971410
tag name: django-forms
type: Tag
tags question: http://stackoverflow.com/q/47881660
tags question: http://stackoverflow.com/q/47898329
tags question: http://stackoverflow.com/q/47968668
tags question: http://stackoverflow.com/q/47866193
tags question: http://stackoverflow.com/q/47953973
tags question: http://stackoverflow.com/q/48004236
tags question: http://stackoverflow.com/q/47962592
tags question: http://stackoverflow.com/q/47884882
tags question: http://stackoverflow.com/q/47951133
tags question: http://stackoverflow.com/q/47913153
tags question: http://stackoverflow.com/q/47977415
tags question: http://stackoverflow.com/q/47937261
tags question: http://stackoverflow.com/q/47907506
tags question: http://stackoverflow.com/q/47954063
tags question: http://stackoverflow.com/q/47959104
tags question: http://stackoverflow.com/q/47982570
tags question: http://stackoverflow.com/q/47887158

http://stackoverflow.com/q/47981065
answer count: 1
has body: I've looked into the source code for some django model fields, in this case DateTimeField. In the tutorial for Django, we are taught to create a DateTimeField like this: from django.db import models field = models.DateTimeField() But looking in the source code, the file where DateTimeField is defined is django/db/models/fields. So, intuitively, if I were to import the field, I would write from django.db.models.fields import DateTimeField. Do you see the difference? In the tutorial, they import it from django/db/models, while it looks like from the location of the source code that it actually resides in django/db/models/fields. Why doesn't the tutorial way of importing DateTimeField crash?
favorite count: 0
tagged with: django
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47981156
has title: Where do Django model fields reside?
upvote count: 2
type: Question
accepted answer: http://stackoverflow.com/a/47981156
linked to: http://stackoverflow.com/q/448271
downvote count: 0

http://stackoverflow.com/q/47915356
has comment: http://stackoverflow.com/comment/82799092
has comment: http://stackoverflow.com/comment/82798986
type: Question
tagged with: contextmanager
has answer: http://stackoverflow.com/a/47917281
has body: Consider this threading.Thread class: class Sleeper(threading.Thread): def __init__(self, sleep=5.0): threading.Thread.__init__(self) self.event = threading.Event() self.sleep = sleep def run(self): while self.sleep &gt; 0 and not self.event.is_set(): self.event.wait(1.0) self.sleep -= 1 def stop(self): self.event.set() It sleeps for a certain amount of time and exits or is stopped before reaching that amount. I use it as: sleeper = Sleeper() try: sleeper.start() # do stuffs here except: # handle possible exceptions here finally: sleeper.stop() And I would much rather use it like a context manager: with Sleeper(): # do stuffs here and then the thread is stopped when exiting the with block. I have tried adding __enter__ and __exit__ methods and it seems to work but I'm not sure this is the way to go: def __enter__(self): self.start() return self and def __exit__(self, type, value, traceback): self.stop() But I'm really not sure what I'm doing here. How should it be done properly?
has comment: http://stackoverflow.com/comment/82798949
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/82799212
tagged with: python-multithreading
score: 6
tagged with: python
accepted answer: http://stackoverflow.com/a/47917281
upvote count: 6
has title: How to use a thread in a context manager?
type: AnsweredQuestion

http://stackoverflow.com/a/47908671
upvote count: 1
score: 1
has body: By using merge df1=pd.DataFrame({'word':word,'ink':ink}) df.merge(df1.assign(congruent=1),on=['word','ink'],how='left').fillna(0)
answers question: http://stackoverflow.com/q/47908340
downvote count: 0
type: Answer

http://stackoverflow.com/a/47918727
answers question: http://stackoverflow.com/q/47918219
has comment: http://stackoverflow.com/comment/82807379
upvote count: 1
has comment: http://stackoverflow.com/comment/82806875
has comment: http://stackoverflow.com/comment/82823773
has comment: http://stackoverflow.com/comment/82807386
has comment: http://stackoverflow.com/comment/82807390
has body: Using the standard formula for 95% CI: sample mean +/- 1.96 * std.err You can do everything in one go with apply: def stats(g): r2 = r2_score(g.Actual, g.Predicted) rmse = np.sqrt(mean_squared_error(g.Actual, g.Predicted)) ci95_hi = g.Predicted.mean() + g.Predicted.sem() * 1.96 ci95_lo = g.Predicted.mean() - g.Predicted.sem() * 1.96 return r2, rmse,(ci95_lo, ci95_hi) df.groupby("Type").apply(stats)
downvote count: 0
has comment: http://stackoverflow.com/comment/82807467
score: 1
has comment: http://stackoverflow.com/comment/82807191
type: Answer

http://stackoverflow.com/a/47962001
answers question: http://stackoverflow.com/q/47961638
type: Answer
upvote count: 5
score: 5
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47961638
has body: You need to define the Lambda execution role and assign the function the appropriate permissions. There should be a Role property of AWS::Serverless::Function Role: !GetAtt LambdaExecutionRole.Arn Then create the referenced role in your template: LambdaExecutionRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: {Service: [lambda.amazonaws.com]} Action: ['sts:AssumeRole'] Path: / ManagedPolicyArns: - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole - arn:aws:iam::aws:policy/service-role/AWSLambdaRole Policies: - PolicyName: SNSPolicy PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: - "SNS:ListTopic" Resource: ['*'] Tweak the permission in the Action section as needed.

http://stackoverflow.com/q/47932955
answer count: 1
has answer: http://stackoverflow.com/a/47933302
has body: Given two 3d points and another list of 3d points, I want to check which one is inside the cylinder defined as the 3d line between the two points with a radius of r. I've implemented a numeric solution for that, which isn't accurate and too slow: def point_in_cylinder(pt1, pt2, points, r, N=100): dist = np.linalg.norm(pt1 - pt2) ori = (pt2 - pt1) / dist line = np.array([pt1 + ori*t for t in np.linspace(0, dist, N)]) dists = np.min(cdist(line, points), 0) return np.where(dists &lt;= r)[0] I'm sure there is a better solution for that... ***** Edit ***** I speed up this function a little bit by replacing the listcomp (where the line is declared) with matrices multiplication: line = (pt1.reshape(3, 1) + elc_ori.reshape(3, 1) @ np.linspace(0, dist, N).reshape(1, N)).T
score: 7
has title: How to check if a 3D point is inside a cylinder
favorite count: 0
accepted answer: http://stackoverflow.com/a/47933302
tagged with: python
upvote count: 7
type: AnsweredQuestion
type: Question
tagged with: numpy
tagged with: 3d
downvote count: 0

http://stackoverflow.com/comment/82701362
score: 1
comment on: http://stackoverflow.com/q/47868174
type: QuestionComment
has text: no everything is correct, python provides different Interpreter. There are differents between version2 and 3. https://wiki.python.org/moin/Python2orPython3
type: Comment

http://stackoverflow.com/q/48000663
answer count: 2
downvote count: 1
has comment: http://stackoverflow.com/comment/82970874
favorite count: 0
has title: Step detection in one-dimensional data
has comment: http://stackoverflow.com/comment/82970957
accepted answer: http://stackoverflow.com/a/48001937
has comment: http://stackoverflow.com/comment/82971927
tagged with: python
has comment: http://stackoverflow.com/comment/123466533
has body: Is there an existing implementation in Python for detecting steps in one dimensional data? E.g. something that detects one step in this data: There are quite a few descriptions of algorithms out there but I am wondering if something suited for the job exists in Python? I'm not sure if/how I should provide that data but here it is: [ 594. 568.55555556 577.22222222 624.55555556 546.66666667 552.88888889 575.55555556 592.33333333 528.88888889 576.11111111 625. 574.22222222 556.33333333 567.66666667 576.66666667 591.66666667 566.33333333 567.33333333 547.44444444 631.11111111 555.66666667 548.66666667 579.44444444 546.88888889 597.55555556 519.88888889 582.33333333 618.88888889 574.55555556 547.44444444 593.11111111 565.66666667 544.66666667 562.66666667 554.11111111 543.88888889 602.33333333 609.77777778 550.55555556 561.88888889 719.33333333 784.44444444 711.22222222 843.66666667 691.33333333 690.11111111 684.33333333 749.11111111 759.11111111 653.33333333 817.11111111 705.22222222 689.44444444 712.33333333 659. 683.88888889 713. 740.44444444 692.22222222 677.33333333 681.44444444 640. 717.55555556 717.88888889 769.22222222 690.88888889 786. 774.66666667 799.44444444 743.44444444 789.88888889 673.66666667 685.66666667 709.88888889 645.55555556 846.11111111 792.77777778 702.22222222 749.44444444 678.55555556 707.55555556 665.77777778 643.55555556 671.44444444 795.66666667 627.22222222 684.55555556 708.44444444 829.66666667 719. ]
type: AnsweredQuestion
upvote count: 35
has answer: http://stackoverflow.com/a/48001937
linked to: http://stackoverflow.com/q/19714663
has comment: http://stackoverflow.com/comment/82970049
has comment: http://stackoverflow.com/comment/82971298
score: 34
tagged with: signal-processing
linked to: http://stackoverflow.com/q/47290732
has comment: http://stackoverflow.com/comment/119396537
type: Question
possible better answer: http://stackoverflow.com/a/69847429
has answer: http://stackoverflow.com/a/69847429
has comment: http://stackoverflow.com/comment/82970738
has comment: http://stackoverflow.com/comment/82970149

http://stackoverflow.com/q/47856288
tagged with: python
linked to: http://stackoverflow.com/q/6053541
tagged with: regex
has comment: http://stackoverflow.com/comment/82677467
has title: Regex: match any character zero or more times, except number "touching" the matching group
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/82677880
score: 4
has answer: http://stackoverflow.com/a/47856906
upvote count: 4
has body: I am having a hard time creating a regex (in Python 3.6) with which I could parse a datetime string, following these rules: Date is always in the form of YYYYMMDD, where YYYY is any year between 2000 and 2099 (inclusive), so that becomes 20yyMMDD Time is always in the form of HHMMSS Date is always before time, as YYYYMMDDHHMMSS Date and time can be separated with no character or any non-numeric character YYYYMMDDHHMMSS - Ok YYYYMMDD-HHMMSS - Ok YYYYMMDD HHMMSS - Ok YYYYMMDD1HHMMSS - Not accepted There can be any characters in front or at the end, except the character "touching" the date string must be non-numeric (YYYYMMDDHHMMSS) - Ok 123-YYYYMMDDHHMMSS)123 - Ok abc1YYYYMMDDHHMMSS - Not accepted I know basics of regex, read many SO answers (found Regex: match everything but, Regex, every non-alphanumeric character except white space or colon and others pretty useful), but just cannot figure out regex to pass all of my test cases. I need two groups for the actual date and time parsing, that is (20[\d]{6})([\d]{6}). Then I added support for the additional characters .*(20[\d]{6})[^\d]?([\d]{6}).* which works fine until there is a numeric character in the front, at the end or in the middle and it shall not match, but it matches. So I started adding different thing in the front or the back, as example (?&lt;![\d]), .*[^\d]?, [^\d]?.*,... but unfortunately my regex knowledge ends soon and the string becomes a mess which I do not understand nor does it work properly. I made some test strings (each with the desired results) and a simple test function: import datetime import re from typing import Tuple, List #my_regex = r"(?&lt;![\d])(20[\d]{6})[^\d]?([\d]{6})[^\d]?.*" my_regex = r"\b(20[\d]{6})[^\d]?([\d]{6})[^\d]?.*" dt = datetime.datetime(2017, 12, 17, 9, 10, 11) tests: List[Tuple[str, datetime.datetime]] = [ # Clean one. ("20171217091011", dt), # Character in between. ("20171217a091011", dt), ("20171217b091011", dt), ("20171217-091011", dt), ("20171217_091011", dt), ("2…
linked to: http://stackoverflow.com/q/1687620
has comment: http://stackoverflow.com/comment/82677552
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/82676667
has comment: http://stackoverflow.com/comment/82678049
has comment: http://stackoverflow.com/comment/82676775
accepted answer: http://stackoverflow.com/a/47856906

http://stackoverflow.com/comment/82940871
has text: @CeriseLimón I have tried it. I will post it. I know I can do it multiple iteration but got stuck trying to achieve it in a single iteration.
type: Comment
comment on: http://stackoverflow.com/q/47985855
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82936859
has text: @MaxGhenis you can treat the zip in python is list of list in R , in R we need `unlist` here is the example of R :-) (PS, I am 50% R user too :-) ) https://stackoverflow.com/questions/4227223/r-list-to-data-frame
type: AnswerComment
comment on: http://stackoverflow.com/a/47983582
type: Comment
score: 1

http://stackoverflow.com/q/47951352
has comment: http://stackoverflow.com/comment/82875176
answer count: 1
downvote count: 0
favorite count: 0
tagged with: jupyter-notebook
has title: Python multithreading - memory not released when ran using While statement
tagged with: multithreading
tagged with: memory-leaks
score: 6
tagged with: python
upvote count: 6
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82872535
has answer: http://stackoverflow.com/a/47958794
type: Question
has comment: http://stackoverflow.com/comment/82886453
has body: I built a scraper (worker) launched XX times through multithreading (via Jupyter Notebook, python 2.7, anaconda). Script is of the following format, as described on python.org: def worker(): while True: item = q.get() do_work(item) q.task_done() q = Queue() for i in range(num_worker_threads): t = Thread(target=worker) t.daemon = True t.start() for item in source(): q.put(item) q.join() # block until all tasks are done When I run the script as is, there are no issues. Memory is released after script finishes. However, I want to run the said script 20 times (batching of sort), so I turn the script mentioned into a function, and run the function using code below: def multithreaded_script(): my script #code from above x = 0 while x&lt;20: x +=1 multithredaded_script() memory builds up with each iteration, and eventually the system start writing it to disk. Is there a way to clear out the memory after each run? I tried: setting all the variables to None setting sleep(30) at end of each iteration (in case it takes time for ram to release) and nothing seems to help. Any ideas on what else I can try to get the memory to clear out after each run within the While statement? If not, is there a better way to execute my script XX times, that would not eat up the ram? Thank you in advance.
accepted answer: http://stackoverflow.com/a/47958794

http://stackoverflow.com/comment/82764295
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47895864
has text: Try it and see what happens
score: 0

http://stackoverflow.com/a/47989227
has comment: http://stackoverflow.com/comment/82983951
answers question: http://stackoverflow.com/q/47988936
upvote count: 1
has body: You can in the python docs to find the io https://docs.python.org/2/library/io.html io is a built-in module: The io module provides the Python interfaces to stream handling. Under Python 2.x, this is proposed as an alternative to the built-in file object, but in Python 3.x it is the default interface to access files and streams. You can not create .py file named the built-in modules, they will get repetition.
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/82916553
type: AnswerComment
type: Comment
has text: @ik_tech Or once you get the list3, you can do `['ID'+str(e) for e in list3]`. This will merge ID in front of each element in the list.
comment on: http://stackoverflow.com/a/47973393
score: 0

http://stackoverflow.com/comment/82809571
comment on: http://stackoverflow.com/a/47920610
score: 0
type: Comment
has text: I installed pytables of course. error still occures
type: AnswerComment

http://stackoverflow.com/comment/82860617
has text: This problem prevails even at 1E8 iterations.
comment on: http://stackoverflow.com/q/47933019
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83107483
type: Comment
type: QuestionComment
has text: 10.x.x.x is not an external address.
score: 0
comment on: http://stackoverflow.com/q/47955872

http://stackoverflow.com/comment/82932947
type: Comment
has text: If you don't mind re-creating your output, then see my answer.
type: QuestionComment
comment on: http://stackoverflow.com/q/47982042
score: 0

http://stackoverflow.com/comment/82968705
type: AnswerComment
comment on: http://stackoverflow.com/a/47999504
score: 0
type: Comment
has text: Fixed. Thanks for the hint.

http://stackoverflow.com/a/47948133
type: Answer
answers question: http://stackoverflow.com/q/47948003
has body: You should use loc when setting values. Essentially, there is no guarantee that the __setitem__ call will be executed on the original dataframe or a copy in memory. You should really read the section mentioned in the error method(indexing-view-versus-copy). The preferred method would be: s.loc[s.A.isnull(), 'A'] = 'P'
score: 0

http://stackoverflow.com/a/51628183
upvote count: 1
has body: You have to specify the route for index page as @app.route('/') If you give any other name to the template, you need to have to specify the name to the route. For eg, if the template name is "home", then you have to give it as: @app.route('/home')
answers question: http://stackoverflow.com/q/47953621
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/comment/82821737
has text: zezollo: Yes, that's what I meant. This is described in a little more detail in [this answer](https://stackoverflow.com/a/18561055/355230) of mine (to an unrelated question). If you want, I could post an answer showing how to do it to the `locale` module.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47910688

http://stackoverflow.com/comment/82936997
score: 0
type: Comment
type: QuestionComment
has text: @ShpielMeister True enough. I stand corrected.
comment on: http://stackoverflow.com/q/47983662

http://stackoverflow.com/q/47889559
accepted answer: http://stackoverflow.com/a/47889858
favorite count: 0
tagged with: python
has body: I am analyzing the TMDB dataset on Kaggle and the year present in the variable release_date on some entries are shifted by 40 years when compared with the variable release_year: # Change to pandas datetime tmdb_df['release_date'] = pd.to_datetime(tmdb_df['release_date']) tmdb_df.query('release_date &gt; datetime.date(2015,12,31)')'release_date', 'release_year'.head() ### #release_date release_year #9849 2062-10-04 1962 #9850 2062-12-10 1962 #9851 2062-06-13 1962 #9852 2062-12-25 1962 #9853 2062-10-24 1962 I've come up with a solution using apply: # Check for movies where the year on `release_date` are shifted # when compared with `release_yer` import datetime # Change to pandas datetime tmdb_df['release_date'] = pd.to_datetime(tmdb_df['release_date']) def aux_func(row): """Fix year""" if row['release_date'].year != row['release_year']: return row['release_date'].replace(year=row['release_year']) else: return row['release_date'] # Apply fix tmdb_df['release_date'] = tmdb_df'release_date', 'release_year'.apply(aux_func, axis=1) But I was wondering if it is possible to use Pandas' transform to solve this or if there is another approach.
type: AnsweredQuestion
has title: Implementing an alternative solution with Pandas `transform`
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/47889858
tagged with: dataframe
score: 0
tagged with: pandas
answer count: 1

http://stackoverflow.com/q/47870440
favorite count: 0
has body: To this question I am referring to this example: https://matplotlib.org/examples/user_interfaces/embedding_in_qt5.html I want to replace the sine plot to with a simple rectangle plot without coordinate system shown. To be exactly, I want to change this part of the original code: class MyStaticMplCanvas(MyMplCanvas): """Simple canvas with a sine plot.""" def compute_initial_figure(self): t = arange(0.0, 3.0, 0.01) s = sin(2*pi*t) self.axes.plot(t, s) I found the rectangle class in Matplotlib: https://matplotlib.org/devdocs/api/_as_gen/matplotlib.patches.Rectangle.html#examples-using-matplotlib-patches-rectangle This should be a simple task. But I tried a lot on my own without sucess. One of my many tries looks like: (But it does not work) class MyStaticMplCanvas(MyMplCanvas): """Simple canvas with a rectangle plot.""" def compute_initial_figure(self): x = 10 y = 20 width = 10 height = 20 fig,ax = plt.subplots(1) rect = mpatches.Rectangle((x, y), width, height) ax.add_patch(rect) self.axes.plot(rect) Could anyone please help me out? Any help will be highly appreciated!
tagged with: python
accepted answer: http://stackoverflow.com/a/47870986
type: AnsweredQuestion
upvote count: 1
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/13013781
tagged with: matplotlib
has title: Place rectangle in plot
duplicate of: http://stackoverflow.com/q/13013781
has answer: http://stackoverflow.com/a/47870986
score: 0
tagged with: pyqt
answer count: 1

http://stackoverflow.com/q/47934626
tagged with: command-line
has comment: http://stackoverflow.com/comment/82838768
accepted answer: http://stackoverflow.com/a/47934671
upvote count: 1
has comment: http://stackoverflow.com/comment/82838790
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47934713
score: 1
has body: I'm trying to make a custom command line to control a robotic arm. So I want to be able to run the program and type in servoMove(arg1,arg2) and have arg1 and arg2 get transferred into the function servoMove. servoPos = [0,1,2,3,4] def servoMove(servo,angle): servoPos[servo] = angle print(servoPos[servo]) def commands(cmd): if cmd == 'servoMove('+arg1+','+arg2+')': servoMove(arg1,arg2) else: print("[Error] - Unknown Command") commands(input("")) Clearly, the code below doesn't work for this. if cmd == 'servoMove('+arg1+','+arg2+')': servoMove(arg1,arg2) Does anybody know how I can do this?
tagged with: command-line-interface
type: Question
has answer: http://stackoverflow.com/a/47934846
tagged with: arrays
downvote count: 0
has answer: http://stackoverflow.com/a/47934671
possible better answer: http://stackoverflow.com/a/47934846
has title: How would I convert user input into function arguments?
answer count: 3
linked to: http://stackoverflow.com/q/4894069
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/82857731
type: Comment
comment on: http://stackoverflow.com/a/47943667
type: AnswerComment
score: 0
has text: you can create the Session object inside the spider (on `start_requests` for example) and still use it on the Pipeline.

http://stackoverflow.com/q/47879965
has title: Should Meta Classes in Models Inherit From Object
accepted answer: http://stackoverflow.com/a/47884122
score: 4
possible better answer: http://stackoverflow.com/a/47880084
answer count: 2
has answer: http://stackoverflow.com/a/47884122
favorite count: 0
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47880084
upvote count: 4
type: AnsweredQuestion
downvote count: 0
has body: It seems pretty conventional to write models something like this: from django.db import models class Foo(models.Model): name = models.CharField(max_length=100, null=False) class Meta: ordering = ("name") Is there any reason class Meta: is used, and not class Meta(object):? Is there any reason not to explicitly inherit from object?
type: Question

pygame
tags question: http://stackoverflow.com/q/47972613
tags question: http://stackoverflow.com/q/47918184
tags question: http://stackoverflow.com/q/47885897
tags question: http://stackoverflow.com/q/47963980
tags question: http://stackoverflow.com/q/47961345
tags question: http://stackoverflow.com/q/47856390
tags question: http://stackoverflow.com/q/47875231
tags question: http://stackoverflow.com/q/47921638
tags question: http://stackoverflow.com/q/47908812
tags question: http://stackoverflow.com/q/47981842
tags question: http://stackoverflow.com/q/47878264
tags question: http://stackoverflow.com/q/47955569
tags question: http://stackoverflow.com/q/47894415
tags question: http://stackoverflow.com/q/47967836
tags question: http://stackoverflow.com/q/47957700
tags question: http://stackoverflow.com/q/47925759
tags question: http://stackoverflow.com/q/47929265
tags question: http://stackoverflow.com/q/47926159
tags question: http://stackoverflow.com/q/47875878
tag name: pygame
tags question: http://stackoverflow.com/q/47984932
tags question: http://stackoverflow.com/q/48005171
tags question: http://stackoverflow.com/q/47935303
tags question: http://stackoverflow.com/q/47981151
tags question: http://stackoverflow.com/q/47857583
tags question: http://stackoverflow.com/q/47888545
tags question: http://stackoverflow.com/q/47972880
tags question: http://stackoverflow.com/q/47902535
tags question: http://stackoverflow.com/q/47875544
tags question: http://stackoverflow.com/q/47975482
tags question: http://stackoverflow.com/q/47984812
tags question: http://stackoverflow.com/q/47999608
type: Tag

http://stackoverflow.com/q/47946251
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I have two dataframes: df1 (index is date): a b 1900-01-01 1 2 1900-01-02 1 3 1900-01-03 3 3 df2 (index is int): c 0 3 1 1 after merge: a b d 1900-01-01 1 2 3 1900-01-02 1 3 1 1900-01-03 3 3 Which function should I use?
has title: Merging two dataframes with different indexes
upvote count: 3
has answer: http://stackoverflow.com/a/47946357
type: Question
score: 3
has comment: http://stackoverflow.com/comment/82862893

http://stackoverflow.com/q/47880019
tagged with: pyq
accepted answer: http://stackoverflow.com/a/47881016
has title: PyQ: How to enumerate symbol column on a splayed table?
answer count: 1
downvote count: 0
tagged with: kdb+
score: 1
favorite count: 0
has body: I'm trying to create a splayed table with a symbol column using pyq. In q I would set the table by enumerating the symbol column with .Q.en... :splay/ set .Q.en[`:splay;]([]a:`x`y`z; b:1 2 3) I tried a few variations of the following... q.set(':splay/', q('.Q.en')('!', ["Name", "Ask", "Bid", "Last", "Vol", "Time"], [K.symbol([]), K.float([]), K.float([]), K.float([]), K.float([]), K.timestamp([])]).flip) But it throws the following rank error: _k.error: rank. What is the proper syntax for this in pyq?
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47881016
upvote count: 1
type: Question

http://stackoverflow.com/q/47929049
score: 0
has title: Using pywinauto to read a value within a window and use in a function
answer count: 1
tagged with: pywinauto
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
has body: I am building an automation script with python using pywinauto, and I am stumped on this part. So far I'm able to start the app, or connect to it. I've toggled through the windows in the interface, and now it needs to somehow read the value and compare to the contents of a .csv file and continue with more functions. The app has multiple windows and one of them uses a spreadsheet type interface. There is not a find/replace feature, or else I could just use that. Now comes the challenge. It needs to "see" the string within a cell and I can easily do this using AccExplorer or Inspect.exe. This is the cell structure in the app, with the selected item "CAM 2". Cell example from the app AccExplorer window showing results of the cell And this is the result provided by AccExplorer. The red circle indicates the "value" I wish to find, and use for comparison. (I have found that searching for this topic on "value" results in answers that are too vague, rather than my literal need to find the value of "value" in this case.) By using this code in my script passing in the class of the window provided by the AccExpolorer tool (red arrow for the class) edit = wdow['WindowsForms10.Window.8.app.0.378734a'] props = edit.GetProperties() print(props) It does not return the "Value" field or its property in this case should be "Cam 2" {'class_name': 'WindowsForms10.Window.8.app.0.378734a', 'friendly_class_name': 'WindowsForms10.Window.8.app.0.378734a', 'texts': [''], 'control_id': 1639674, 'rectangle': &lt;RECT L0, T47, R1366, B746&gt;, 'is_visible': True, 'is_enabled': True, 'control_count': 76, 'style': 1442906112, 'exstyle': 65536, 'user_data': 0, 'context_help_id': 0, 'fonts': [&lt;LOGFONTW 'MS Shell Dlg' -11&gt;], 'client_rects': [&lt;RECT L0, T0, R1366, B699&gt;], 'is_unicode': True, 'menu_items': []} I am rather new to python (and programming in general) but I have been doing quite well at grasping all of this. I am aware of the backend, which I have not had luck with using UIA, an…
type: Question
has answer: http://stackoverflow.com/a/48223026
accepted answer: http://stackoverflow.com/a/48223026

http://stackoverflow.com/a/50577672
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/103816530
type: Answer
answers question: http://stackoverflow.com/q/47925688
has comment: http://stackoverflow.com/comment/103780675
has comment: http://stackoverflow.com/comment/103888595
upvote count: 3
has body: It was quite tricky to accomplish with reasonable performance, though. Check out the project: https://github.com/DanielTea/rage-analytics/blob/master/README.md The main file is realtime_Videostreamer.py in the engine folder. If you initialize this object it creates an ffmpeg subprocess and fills a queue with video frames in an extra thread. This architecture prevents the mainthread from blocking so depending on your networkspeed and cpu power a couple streams can be analyzed in parallel. This solution works with twitch streams very well. Didn’t try out other streaming sites. More info about this project.
has comment: http://stackoverflow.com/comment/103924100
score: 3
has comment: http://stackoverflow.com/comment/103923413
accepted answer of: http://stackoverflow.com/q/47925688

http://stackoverflow.com/q/47857583
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/58474204
linked to: http://stackoverflow.com/q/54595777
has body: import pygame import time pygame.init() display_width = (1000) display_height = (480) black = (255,50,0) white = (0,60,7) blue = (0,205,205) kled1_width = 30 kled1_height = 45 ground1_height = 300 screen = pygame.display.set_mode((display_width,display_height)) pygame.display.set_caption(" kled ") clock = pygame.time.Clock() gameDisplay = screen kled1IMG = pygame.image.load("IMG.png") def kled1(x,y): gameDisplay.blit(kled1IMG,(x,y)) def game_loop(): x = (1) y = (340) x_change = 0 y_change = 0 gameExit = False while not gameExit: for event in pygame.event.get(): if event.type == pygame.QUIT: gameExit = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: x_change = -5 elif event.key == pygame.K_RIGHT: x_change = 5 elif event.key == pygame.K_UP: y_change = -15 elif event.key == pygame.K_DOWN: y_change = 5 if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_LEFT and pygame.K_r or event.key == pygame.K_RIGHT and pygame.K_2: x_change = 0 if event.type == pygame.KEYUP: if event.key == pygame.K_UP or event.key == pygame.K_DOWN: y_change = 0 x += x_change y += y_change gameDisplay.fill(blue) pygame.draw.rect(gameDisplay, white, [1, 400, 1000,ground1_height]) kled1(x,y) #prevents from going into ground if y &gt; ground1_height: y_change = 0 pygame.display.update() clock.tick(30) game_loop() pygame.quit() quit() How would I make my code so that if I press ▲ once, the image moves up 15 spaces from the image's current position, and then goes down 15 spaces after about .5 seconds? Essentially, it is a jumping game like Mario that I will add platforms and other things to it. Also, I want to know how to make sure you can't double jump while in the air! Sorry that I am not a good programmer, I just need help for this game. I am using Python 2.7
type: Question
linked to: http://stackoverflow.com/q/48069508
score: -1
duplicate of: http://stackoverflow.com/q/62822322
has comment: http://stackoverflow.com/comment/82681389
upvote count: 2
tagged with: python-2.7
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47858300
duplicate of: http://stackoverflow.com/q/54595777
downvote count: 3
has title: How do I add jumping to my game
duplicate of: http://stackoverflow.com/q/64864966
tagged with: python
tagged with: pygame

http://stackoverflow.com/comment/82834426
comment on: http://stackoverflow.com/q/47932542
has text: note that doing `movie_lst = [str(x) for x in movie_lst]` wouldn't hurt for strings, and would convert anything else to string. Worth a try.
score: 0
type: Comment
type: QuestionComment

primary-key
tags question: http://stackoverflow.com/q/47951915
tag name: primary-key
type: Tag

http://stackoverflow.com/comment/82917286
has text: I changed the code like you instructed, its given below. `while True: print(analog_read()) #gainString = analog_read() gainString.append(analog_read()) x_axis = range(len(gainString)) #x_axis = x_axis + 1 #dataArray = gainString.split(',') #gain = float(dataArray[0]) #gainF.append(gain) makeFig() plt.pause(.000001) time.sleep(1)` It created an output of an array like below `90 [195, 189] range(0, 2) 91 [195, 189, 96] range(0, 3)` which keeps going, but the graph is still empty
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47937719

http://stackoverflow.com/q/47869484
has answer: http://stackoverflow.com/a/47869538
possible better answer: http://stackoverflow.com/a/47869636
upvote count: 4
has answer: http://stackoverflow.com/a/47869636
answer count: 3
score: 3
has answer: http://stackoverflow.com/a/47870566
has title: Merge two dictionaries in Python with the same keys
accepted answer: http://stackoverflow.com/a/47869538
favorite count: 0
tagged with: python
tagged with: merge
tagged with: dictionary
type: AnsweredQuestion
has body: I have two dictionaries with exaclty the same keys. The first dictionary is : { "key_1" : "AR" , "key_2":"BR" , "key_3" : "CR" } the second is : { "key_1" : "signinfication of AR" , "key_2":" signinfication of BR" , "key_3" : " signinfication of CR" } and I would like to obtain the dictionary below : {"key_1" : {"AR" : "signinfication of AR"} , "key_2" : {"BR" : "signinfication of BR"} , "key_3" : {"CR" : "signinfication of CR"} Thank you for your help !
downvote count: 1
type: Question

http://stackoverflow.com/comment/82947542
type: Comment
comment on: http://stackoverflow.com/a/47981416
has text: I understand better what you need. The correct way to do that is to create two modules, the main one, with your main functionality, and a secondary one which only adds the XML code to make invisible those fields (the code will be some simple lines like ` 1 `). This secondary module must depend (in the `__manifest__.py`) on your main module and the module which created the fields you're making invisible (the one which will be installed or not).
score: 0
type: AnswerComment

http://stackoverflow.com/q/47923381
linked to: http://stackoverflow.com/q/43146968
tagged with: numpy
has title: Compute sparse transitive closure of scipy sparse matrix
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/82829674
tagged with: sparse-matrix
has body: I want to compute the transitive closure of a sparse matrix in Python. Currently I am using scipy sparse matrices. The matrix power (**12 in my case) works well on very sparse matrices, no matter how large they are, but for directed not-so-sparse cases I would like to use a smarter algorithm. I have found the Floyd-Warshall algorithm (German page has better pseudocode) in scipy.sparse.csgraph, which does a bit more than it should: there is no function only for Warshall's algorithm - that is one thing. The main problem is that I can pass a sparse matrix to the function, but this is utterly senseless as the function will always return a dense matrix, because what should be 0 in the transitive closure is now a path of inf length and someone felt this needs to be stored explicitly. So my question is: Is there any python module that allows computing the transitive closure of a sparse matrix and keeps it sparse? I am not 100% sure that he works with the same matrices, but Gerald Penn shows impressive speed-ups in his comparison paper, which suggests that it is possible to solve the problem. EDIT: As there were a number of confusions, I will point out the theoretical background: I am looking for the transitive closure (not reflexive or symmetric). I will make sure that my relation encoded in a boolean matrix has the properties that are required, i.e. symmetry or reflexivity. I have two cases of the relation: reflexive reflexive and symmetric I want to apply the transitive closure on those two relations. This works perfectly well with matrix power (only that in certain cases it is too expensive): &gt;&gt;&gt; reflexive matrix([[ True, True, False, True], [False, True, True, False], [False, False, True, False], [False, False, False, True]]) &gt;&gt;&gt; reflexive**4 matrix([[ True, True, True, True], [False, True, True, False], [False, False, True, False], [False, False, False, True]]) &gt;&gt;&gt; reflexive_symmetric matrix([[ True, True, False, True], [ True, True, True, F…
favorite count: 0
upvote count: 5
has comment: http://stackoverflow.com/comment/82829642
tagged with: python
has answer: http://stackoverflow.com/a/47930658
accepted answer: http://stackoverflow.com/a/47930658
has comment: http://stackoverflow.com/comment/82829206
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/37674435
tagged with: floyd-warshall
tagged with: scipy
has comment: http://stackoverflow.com/comment/82829944
type: Question
score: 3
has comment: http://stackoverflow.com/comment/83320008

http://stackoverflow.com/q/47867479
has body: Making a QWERTY musical keyboard for school. This code isn't working. The bit where it's supposed to play a noise (20th Century Fanfare) It plays a windows noise instead... Any ideas? def playSound02(canvas, synchronous): async = winsound.SND_FILENAME | winsound.SND_ASYNC canvas.data["soundCounter"] += 1 sound02 = ["centuryfox.wav" ] sound02 = sound02[canvas.data["soundCounter"] % len(sound02)] winsound.PlaySound(sound02, async)
has title: Creating a musical QWERTY keyboard. Plays error sound instead of sound
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/47870637
tagged with: audio
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48262185
accepted answer: http://stackoverflow.com/a/48262185
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/47870637
score: 0

constraints
type: Tag
tags question: http://stackoverflow.com/q/47959028
tag name: constraints

http://stackoverflow.com/comment/82706427
score: 1
comment on: http://stackoverflow.com/q/47870531
type: Comment
has text: Your file may contains blank spaces. Oh and yes: which Python version are you using ?
type: QuestionComment

http://stackoverflow.com/a/47870986
answers question: http://stackoverflow.com/q/47870440
type: Answer
has body: You can add the Rectangle to self.axes with add_patch. This method does not automatically change the limits of the axis. Consider where you are trying to place the Rectangle patch. class MyStaticMplCanvas(MyMplCanvas): """Simple canvas with a rectangle plot.""" def compute_initial_figure(self): x = 10 y = 20 width = 10 height = 20 rect = mpatches.Rectangle((x, y), width, height) self.axes.add_patch(rect) # Change limits so we can see rect self.axes.set_xlim((0, 50)) self.axes.set_ylim((0, 50))
score: 2
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/47870440
upvote count: 3

http://stackoverflow.com/q/47958550
tagged with: python
has comment: http://stackoverflow.com/comment/82893817
has comment: http://stackoverflow.com/comment/82896811
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82896927
tagged with: subclassing
type: Question
tagged with: keystrokes
has comment: http://stackoverflow.com/comment/82888972
tagged with: inheritance
has comment: http://stackoverflow.com/comment/82886640
has title: Subclassing with fewer keystrokes
has body: How can I define a subclass using an instance of the superclass without typing a lot? See: class A(): def __init__(self,x,y): self.x=x self.y=y class B(A): def __init__(self,x,y,z): A.__init__(A,x,y) self.z=z class1=A(2,3) class2=B(class1.x,class1.y,5) # Is there something easier than this, where I don't have to type class1.x, class1.y and # I can just pass all the data members of class1 at once?
has comment: http://stackoverflow.com/comment/82888958
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/82886488
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82886449
has comment: http://stackoverflow.com/comment/82889009
has answer: http://stackoverflow.com/a/47963762

http://stackoverflow.com/comment/82832308
comment on: http://stackoverflow.com/q/47927361
score: 0
type: QuestionComment
has text: Thanks for all the answers, it was very helpful, obviously I was using wrong locator to find the button I wanted to click. As I see my knowledge for the project I want to finish are superficial. By now I am familiar with some python basics and read [Al Sweigart's "Automate the boring stuff with python"](https://automatetheboringstuff.com/) book. I am not familiar with HTML and CSS and currently planning to learn some basics of it. If anyone has any advice of topics I should've cover before starting to write automated bot able to navigate web pages I would appreciate it very much.
type: Comment

http://stackoverflow.com/a/47967781
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47967584
answers question: http://stackoverflow.com/q/47967584
type: Answer
has body: From a discussion in the comments, it was deduced that your column contained a mixture of strings and integers. For example, s = pd.Series(['0', 0, '0', '6', 6, '6', '3', '3']) s 0 0 1 0 2 0 3 6 4 6 5 6 6 3 7 3 dtype: object Now, calling pd.get_dummies would result in multiple such columns of the same feature. pd.get_dummies(s) 0 6 0 3 6 0 0 0 1 0 0 1 1 0 0 0 0 2 0 0 1 0 0 3 0 0 0 0 1 4 0 1 0 0 0 5 0 0 0 0 1 6 0 0 0 1 0 7 0 0 0 1 0 The fix is to ensure that all elements are of the same type. I'd recommend, for this case, converting to str. s.astype(str).str.get_dummies() 0 3 6 0 1 0 0 1 1 0 0 2 1 0 0 3 0 0 1 4 0 0 1 5 0 0 1 6 0 1 0 7 0 1 0
score: 2
downvote count: 0

http://stackoverflow.com/comment/83101528
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47950311
score: 0
has text: Hi, I tried this code and I have two problems: 1- this code `colors="red:sort=='1'"` doesn't work. it works with letters (a instead of 1). 2- I want to hide the sort field from the tree and form view. If I hide it. odoo doesn't compute that field and I have no sort. And this problem occurs in both codes. Yours and mine.

http://stackoverflow.com/comment/82830739
type: Comment
type: QuestionComment
has text: Because they don't write/change any entry. They are just setting flags which will make evaluation different when accessed. It's a view!
comment on: http://stackoverflow.com/q/47930428
score: 0

http://stackoverflow.com/q/47885998
downvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/82737555
type: Question
tagged with: split
has title: Split string by size(1024 bytes)
answer count: 1
has body: I have opened a picture file and saved on a variable. file_input = open(FILE_PATH, 'rb') file_doc = file_input.read() How can I split the variable to a list by size(each part of the list is the size of 1024 bytes)?
tagged with: python
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/47886365
type: UnansweredQuestion

function
tags question: http://stackoverflow.com/q/47878228
tags question: http://stackoverflow.com/q/47942094
tags question: http://stackoverflow.com/q/47952964
tags question: http://stackoverflow.com/q/47946317
tag name: function
tags question: http://stackoverflow.com/q/47910573
tags question: http://stackoverflow.com/q/47956743
tags question: http://stackoverflow.com/q/47861446
tags question: http://stackoverflow.com/q/47922274
tags question: http://stackoverflow.com/q/47856233
tags question: http://stackoverflow.com/q/47970531
tags question: http://stackoverflow.com/q/47875208
tags question: http://stackoverflow.com/q/47888009
tags question: http://stackoverflow.com/q/47950998
type: Tag
tags question: http://stackoverflow.com/q/47991833
tags question: http://stackoverflow.com/q/47977465
tags question: http://stackoverflow.com/q/47875531
tags question: http://stackoverflow.com/q/47990890
tags question: http://stackoverflow.com/q/47922441
tags question: http://stackoverflow.com/q/47978225
tags question: http://stackoverflow.com/q/47990103
tags question: http://stackoverflow.com/q/47890550
tags question: http://stackoverflow.com/q/47874585
tags question: http://stackoverflow.com/q/47964186
tags question: http://stackoverflow.com/q/47889609
tags question: http://stackoverflow.com/q/47907268
tags question: http://stackoverflow.com/q/47978149
tags question: http://stackoverflow.com/q/47865046
tags question: http://stackoverflow.com/q/47896006
tags question: http://stackoverflow.com/q/47922128

http://stackoverflow.com/comment/82990878
type: Comment
has text: I have two for each loops. In each of these loops I might find different `product`. I'm not sure that I understand correctly your proposal. Could you please post my code with your updates?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48011191

http://stackoverflow.com/q/47917135
tagged with: excel
type: Question
has comment: http://stackoverflow.com/comment/82805721
score: 2
has comment: http://stackoverflow.com/comment/82802304
has comment: http://stackoverflow.com/comment/125707450
upvote count: 2
downvote count: 0
answer count: 1
favorite count: 0
has body: I converted a few .csv files using python code to .xls but now when i try to open the files it gives me an error : "COUNT_DIST2.xls cannot be accessed. The file may be corrupt, located on a server that is not responding , or read only". I have created many other files in this projects which are both .csv and .xls but none of them are giving me this problem. I think in my code somewhere maybe i am doing something wrong. I am very sure this is not a network error or office error because i am able to open all the other documents. Attached is the code: import pandas as pd import numpy as np from xlrd import open_workbook from xlwt import Workbook from xlutils.copy import copy from openpyxl import load_workbook import matplotlib.pyplot as plt import xlwt import os path = ('C:\Users\PETERemote\PycharmProjects\untitled\distributions') data = [] count =1 count2 = 0 for files in os.listdir(path): if files.endswith("COUNT16_DISTRIBUTION" + str(count*1) + ".csv"): count += 1 count2 = count-2 print(count2) #print(count2 = count) count3=1 file_name = "COUNT16_DISTRIBUTION" + str(count3*1) + ".csv" while (count3&lt;=count2): with open(file_name) as f: for line in f: data.append([word for word in line.split(" ") if word]) wb = xlwt.Workbook() output_file = open("COUNT16_DIST" + str(count3 * 1) + ".xls", 'w') count3 += 1 sheet = wb.add_sheet("Sheet1") for row_index in range(len(data)): for col_index in range(len(data[row_index])): sheet.write(row_index, col_index, data[row_index][col_index]) wb.save(output_file) data = [] output_file.close()
has comment: http://stackoverflow.com/comment/82829137
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has title: Unable to open excel file created inthe python code
has comment: http://stackoverflow.com/comment/82806604
has answer: http://stackoverflow.com/a/47917167
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82834051

http://stackoverflow.com/a/47858235
has comment: http://stackoverflow.com/comment/82681524
answers question: http://stackoverflow.com/q/47858024
has comment: http://stackoverflow.com/comment/82681166
type: Answer
has comment: http://stackoverflow.com/comment/82681047
has body: Your function is doing what you want: 1 and 2 are of int type and '3' and '4' are of str type: def app(l): for i in l: print("{} is: {}".format(i, type(i))) l = [1,2,'3','4'] app(l) 1 is: &lt;class 'int'&gt; 2 is: &lt;class 'int'&gt; 3 is: &lt;class 'str'&gt; 4 is: &lt;class 'str'&gt; Edit: To get string representation of the list elements, like @Paul Panzer suggested in the comments, you could do print(repr(i)): def app(l): for i in l: print(repr(i), end=' ') # Print on the same line l = [1,2,'3','4'] app(l) 1 2 '3' '4' &gt;&gt;&gt; repr(object) says: Return a string containing a printable representation of an object.
upvote count: 1
type: AcceptedAnswer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/47858024

http://stackoverflow.com/comment/82964226
type: QuestionComment
has text: @Xema how do you know the `DOWNLOAD_DELAY` is not working? is it between `www.fitbit.com` and `api.fitbit.com` requests? are you doing requests to another domain apart from those 2?
score: 0
comment on: http://stackoverflow.com/q/47994646
type: Comment

http://stackoverflow.com/a/60204878
upvote count: 0
type: Answer
downvote count: 2
score: -2
answers question: http://stackoverflow.com/q/47931241
has body: Sometimes there may be another server is running under that port in your machine or Use python manage.py runserver 8000 Note: You can user any port

http://stackoverflow.com/comment/82749364
type: Comment
has text: PavelPerminov you don't guarantee original order with `list(set(source))`.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47885408

http://stackoverflow.com/a/48011695
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82992031
accepted answer of: http://stackoverflow.com/q/48011386
type: Answer
answers question: http://stackoverflow.com/q/48011386
upvote count: 1
has body: Python3 handles this automatically, you don't need to use encode. As for the list, you're creating a new one with each iteration, create it above the loop, and print it after iterating over the XML elements has finished. Working example (I've added the word abiétacée to an XML a bunch of times to reproduce your situation): my_list = [] for event, elem in ET.iterparse(file_path, events=("start", "end")): if elem.tag == 'orthography' and event =='start': data = elem.text if data is not None : for i in data.split('\n'): my_list.append(i) print (my_list) outputs ['abiétacée', 'abiétacée', 'abiétacée', 'abiétacée']

http://stackoverflow.com/comment/82823976
score: 0
comment on: http://stackoverflow.com/a/47867408
type: AnswerComment
type: Comment
has text: Thanks Foster! My only issue now is that it's giving me a status 400 error message. So I'm not sure whether this means I've implemented your suggestion wrong (most likely) or whether I need to add a sleep to this loop in order for IBM Watson not to freak out?

http://stackoverflow.com/comment/82910856
comment on: http://stackoverflow.com/q/47970707
score: 0
type: QuestionComment
has text: If you'll notice, the result you see is basically the output of the first partition operation, and nothing more. What you need to pass to the recursive calls are indices to operate on, `l` and `r`. Passing copies will not affect the original in any way.
type: Comment

http://stackoverflow.com/comment/82793835
comment on: http://stackoverflow.com/q/47913047
has text: You should prolly read up how `eval` works and/or try `red == red` as the first expression in your terminal.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47862840
accepted answer: http://stackoverflow.com/a/47862970
score: 2
has comment: http://stackoverflow.com/comment/82691114
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47863006
possible better answer: http://stackoverflow.com/a/47862885
has answer: http://stackoverflow.com/a/67858451
has comment: http://stackoverflow.com/comment/82690945
has answer: http://stackoverflow.com/a/47862885
type: Question
upvote count: 2
linked to: http://stackoverflow.com/q/44597662
favorite count: 0
answer count: 5
has comment: http://stackoverflow.com/comment/82690755
has answer: http://stackoverflow.com/a/47876773
has title: how to install package for python3 using pip? Now it always install for python2
tagged with: python
linked to: http://stackoverflow.com/q/6587507
has comment: http://stackoverflow.com/comment/82691055
has comment: http://stackoverflow.com/comment/82690829
downvote count: 0
has body: I've been puzzled for a while. I can't install/upgrade any package for my python35 now. I have python27 and python35(via anaconda) on mac. Whenever I want to install a python package via pip, the one paired with python2 was invoked. Go to anaconda folder(where my python35 installed): ls -al | grep pip I got the result: -rwxrwxr-x 1 xx staff 113 Jul 26 2016 conda-pipbuild -rwxr-xr-x 1 xx staff 230 Dec 17 21:40 pip -rwxr-xr-x 1 xx staff 230 Dec 17 21:40 pip3 -rwxr-xr-x 1 xx staff 230 Dec 17 21:40 pip3.5 In my .bashrc file, I defined: alias python2=/usr/bin/python2.7 alias python=~/anaconda/bin/python3.5 When I type python2: $ python2 Python 2.7.10 (default, Oct 23 2015, 19:19:21) [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; When I type python: $ python Python 3.5.2 |Anaconda custom (x86_64)| (default, Jul 2 2016, 17:52:12) [GCC 4.2.1 Compatible Apple LLVM 4.2 (clang-425.0.28)] on darwin Type "help", "copyright", "credits" or "license" for more information. When type: pip -V pip 9.0.1 from /Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg (python 2.7) When type pip3 -V -bash: pip3: command not found which pip /usr/local/bin/pip To reinstall pip3, I downloaded get-pip.py from https://pip.pypa.io/en/latest/installing/ From the doc it says, it will install the correct pip according to the version of Python runs the script. Therefore, I ran python get-pip.py Requirement already up-to-date: pip in /Users/xxx/anaconda/lib/python3.5/site-packages Below shows When I try to install a package with pip: pip install tushare --upgrade Collecting tushare Using cached tushare-1.0.7-py2-none-any.whl Requirement already up-to-date: lxml&gt;=3.8.0 in /Library/Python/2.7/site-packages (from tushare)
has comment: http://stackoverflow.com/comment/82690887
tagged with: pip
has answer: http://stackoverflow.com/a/47862970
has comment: http://stackoverflow.com/comment/82690924

http://stackoverflow.com/a/47984058
has comment: http://stackoverflow.com/comment/82937298
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47983412
type: Answer
answers question: http://stackoverflow.com/q/47983412
has body: You need to "post" your form-data to http://streamcloud.eu/. Additionally pass an additional parameter called op with the value login, to indicate, that you want to log in. All of this can be found out through a quick look at the html of the target website: Benutzername: Passwort: As you can see the form posts its information to http://streamcloud.eu/: Here you can see the hidden op parameter: Here is the updated code: import requests url = 'http://streamcloud.eu' headers = {'User-Agent': 'Mozilla/5.0'} payload = { 'op': 'login', 'login': 'my_login', 'password': 'my_password' } r = requests.session() r.get(url) login = r.post(url, data=payload, headers=headers) result = r.get('http://streamcloud.eu/?op=my_account') print(result.text)

http://stackoverflow.com/comment/96023400
has text: is there a way by which one can merge the columns into a numpy array. I mean here `type` of `df['combine'].iloc[0]` would be `list`, can one make sure it is `numpy.ndarray` while merging itself?
score: 3
comment on: http://stackoverflow.com/a/48011716
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47953705
type: AnsweredQuestion
has body: Support for the allow_tags attribute on ModelAdmin methods is removed.
possible better answer: http://stackoverflow.com/a/50989257
has answer: http://stackoverflow.com/a/50989257
type: Question
has answer: http://stackoverflow.com/a/65087335
has answer: http://stackoverflow.com/a/47953774
score: 48
has title: How do I use allow_tags in django 2.0 admin?
downvote count: 0
upvote count: 48
favorite count: 0
accepted answer: http://stackoverflow.com/a/47953774
has answer: http://stackoverflow.com/a/48734518
tagged with: django
tagged with: python
answer count: 4

http://stackoverflow.com/q/47976524
has comment: http://stackoverflow.com/comment/82922946
has comment: http://stackoverflow.com/comment/82922547
type: Question
has comment: http://stackoverflow.com/comment/82922587
has comment: http://stackoverflow.com/comment/82922853
has comment: http://stackoverflow.com/comment/82922557
has comment: http://stackoverflow.com/comment/82922510
has comment: http://stackoverflow.com/comment/82922732
has comment: http://stackoverflow.com/comment/82922820
has body: I'm new to python and have been trying to install jira 1.0.10.tar.gz packages with pip.I have installed python 3.6 on my system. My command line throws me this error though: Command "python setup.py egg_info" failed with error code 1 in C:\Users\manmohit .kaur\AppData\Local\Temp\pip-z0dmal3l-build\ Please find below the logs D:\cucumber\Drivers\Drivers&gt;pip3 install jira-1.0.10.tar.gz Processing d:\cucumber\drivers\drivers\jira-1.0.10.tar.gz Complete output from command python setup.py egg_info: Download error on https://pypi.python.org/simple/pytest-runner/: [Errno 1100 2] getaddrinfo failed -- Some packages may not be found! Couldn't find index page for 'pytest-runner' (maybe misspelled?) Download error on https://pypi.python.org/simple/: [Errno 11002] getaddrinfo failed -- Some packages may not be found! No local packages or working download links found for pytest-runner Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "C:\Users\manmohit.kaur\AppData\Local\Temp\pip-z0dmal3l-build\setup.p y", line 37, in &lt;module&gt; test_suite='tests') File "c:\program files (x86)\python36-32\lib\distutils\core.py", line 108, in setup _setup_distribution = dist = klass(attrs) File "c:\program files (x86)\python36-32\lib\site-packages\setuptools\dist .py", line 315, in __init__ self.fetch_build_eggs(attrs['setup_requires']) File "c:\program files (x86)\python36-32\lib\site-packages\setuptools\dist .py", line 361, in fetch_build_eggs replace_conflicting=True, File "c:\program files (x86)\python36-32\lib\site-packages\pkg_resources\_ _init__.py", line 850, in resolve dist = best[req.key] = env.best_match(req, ws, installer) File "c:\program files (x86)\python36-32\lib\site-packages\pkg_resources\_ _init__.py", line 1122, in best_match return self.obtain(req, installer) File "c:\program files (x86)\python36-32\lib\site-packages\pkg_resources\_ _init__.py", line 1134, in obtain return installer(requirement) File "c:\program files (x86)\pytho…
has comment: http://stackoverflow.com/comment/82922497
has title: Python pip install jira 1.0.10.tar.gz gives “Command ”python setup.py egg_info“ failed with error code 1”
has comment: http://stackoverflow.com/comment/82922869
answer count: 1
has comment: http://stackoverflow.com/comment/82922755
has comment: http://stackoverflow.com/comment/82922699
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82922979
has comment: http://stackoverflow.com/comment/82922261
tagged with: python
has answer: http://stackoverflow.com/a/47977073
has comment: http://stackoverflow.com/comment/82922678
score: 0
has comment: http://stackoverflow.com/comment/82922606
has comment: http://stackoverflow.com/comment/82922250

http://stackoverflow.com/comment/82885940
type: QuestionComment
type: Comment
score: 2
comment on: http://stackoverflow.com/q/47958318
has text: Whats wrong with concat. Its neat

http://stackoverflow.com/q/48007152
linked to: http://stackoverflow.com/q/46996782
has title: How to click unopened tabs where the numbers change
score: -1
has body: How do I click all the unopened tabs pages where the value changes when you click tabs? (see image below) Take the following script, based off of this question with the following approach: clickMe = wait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, path + '[%s]' % str(index - 1)))) Works great for the large majority of pages, however I cannot see how it can be used in this case. Any idea how you can get around this issue? The reason it does not work is because as soon as you click an unopened tab, the number values change. This means the job is trying to click elements that used to exist, but the number values changed when you opened a closed tab. This is better illustrated in the image below. Say you had //div[@class="KambiBC-collapsible-container KambiBC-mod-event-group-container"][1] In the picture below, you can see that the above selector will change based upon when the job itself clicks tabs and upon loading the webpage. The webpage has a habit of randomising opened and closed tabs. So this explains why it will click some elements and then completely break or if you add try except, click only some elements and finish. output: 1 2 3 4 #Stops working Desired 1 2 3 4 etc,, (Clicks all the pages) The above images are both: //div[@class="KambiBC-collapsible-container KambiBC-mod-event-group-container"][1]` You can see how this will cause issues later on. The image on the right would not be able to locate //div[@class="KambiBC-collapsible-container KambiBC-mod-event-group-container"][11] where a the one on the left could based on the order of tabs clicked. outerhtml
type: Question
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48007934
tagged with: python
upvote count: 0
type: UnansweredQuestion
tagged with: selenium
downvote count: 1

http://stackoverflow.com/comment/82793726
type: QuestionComment
has text: I added example of data. It's not quite np.outer since this generates an outer product of two vectors. I want to apply a custom operation (an inner product) to the outer join of two series. Thank you for your help!
score: 0
comment on: http://stackoverflow.com/q/47912611
type: Comment

http://stackoverflow.com/a/47986216
downvote count: 0
upvote count: 3
has comment: http://stackoverflow.com/comment/82941347
has comment: http://stackoverflow.com/comment/82941521
has comment: http://stackoverflow.com/comment/82941423
has body: Two levels deep = double comprehension! :) [[x + y for x, y in zip(sublst1, sublst2)] for sublst1, sublst2 in zip(lst1, lst2)] EDIT: or, shorter (thanks to Stefan Pochmann): [[x + y for x, y in zip(*sublists)] for sublists in zip(lst1, lst2)]
type: Answer
answers question: http://stackoverflow.com/q/47986166
score: 3

coreml
tags question: http://stackoverflow.com/q/47864505
type: Tag
tag name: coreml

http://stackoverflow.com/a/47866253
downvote count: 0
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/47866193
answers question: http://stackoverflow.com/q/47866193
has body: Since you are adding the URL to a model admin class, you need to include the admin namespace to reverse it. return redirect('admin:auth_user_password_change')
score: 2
type: AcceptedAnswer

lookup
tags question: http://stackoverflow.com/q/47941113
tags question: http://stackoverflow.com/q/47949628
tag name: lookup
type: Tag

http://stackoverflow.com/comment/82931806
has text: What are you trying to achieve?
comment on: http://stackoverflow.com/q/47981620
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47911968
has answer: http://stackoverflow.com/a/47912767
accepted answer: http://stackoverflow.com/a/47912767
has answer: http://stackoverflow.com/a/47912151
type: AnsweredQuestion
has title: Storing variables and functions in a dictionary , is this the right way to go?
has comment: http://stackoverflow.com/comment/82791656
has comment: http://stackoverflow.com/comment/82792247
type: Question
has comment: http://stackoverflow.com/comment/82791916
tagged with: database
has body: I'm new to Python and trying to get my head round creating a case statement equivalent which will store sql strings that I want to pull out of a dictionary and then execute. The problem is that the sql statements themselves will have variables/functions within them (effectively they are dynamic sql statements). I've read a myriad of comments about whether dict or if..else is the best way to implement what I'm trying to achieve in Python. Here's my starting code which doesn't return what I want it to def my_switch(action,user,role): switcher = { "CR": "CREATE USER user PASSWORD genpass()", "DR": "DROP USER user", "GR": "GRANT ROLE role TO user", "RV": "REVOKE ROLE role FROM user", "PW": "ALTER USER user PASSWORD genpass()" } logger.debug("Command passed was %s,user passed was %s, role passed was %s",action,user,role) print switcher.get(action, "Invalid command") my_switch(cmd,user,role) Output when passing CR, bloggsj, APP for example is CREATE USER user PASSWORD genpass() When I wanted it to come back with CREATE USER bloggsj PASSWORD somegeneratedpw How do I get it to recognise user as a variable and execute the genpass() function ?
has comment: http://stackoverflow.com/comment/82792143
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/82792076
possible better answer: http://stackoverflow.com/a/47912151
tagged with: python

http://stackoverflow.com/q/47860840
has comment: http://stackoverflow.com/comment/82687227
has body: I got a full code from github and everything was OK, server worked without any problems. But then I tried to do some changes, like adding a new class in the model.py and trying to import it to the admin.py I got such an error: ImportError: cannot import name TechnicalExamination. Of course, I did migrations before this, using python manage.py makemigrations and python manage.py migrate. Here is my class in models.py: class HealthExamination(models.Model): class Meta: verbose_name_plural = 'Health Examinations' doctor = models.CharField(max_length=70) person = models.ForeignKey(Person, on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() class TechnicalExamination(models.Model): class Meta: verbose_name_plural = 'Technical Examinations' technician = models.CharField(max_length=70) person = models.ForeignKey(Person, on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() def get_fields(self): pairs = [] for field in self._meta.fields: name = field.name try: pairs.append((name, getattr(self, "get_%s_display" % name)())) except AttributeError: pairs.append((name, getattr(self, name))) return pairs def __str__(self): return str(self.person) Here is my admin.py: from __future__ import unicode_literals from django.contrib import admin from .models import Person, Car, InsuranceCompany, Policy, HealthExamination, TechnicalExamination admin.site.register(Person) admin.site.register(Car) admin.site.register(InsuranceCompany) admin.site.register(Policy) admin.site.register(HealthExamination) admin.site.register(TechnicalExamination) And here is my root:
tagged with: python
has comment: http://stackoverflow.com/comment/82687217
tagged with: django
tagged with: import
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47863043
has comment: http://stackoverflow.com/comment/82687517
has comment: http://stackoverflow.com/comment/82689045
has comment: http://stackoverflow.com/comment/82698297
type: Question
score: 0
has title: ImportError: cannot import name and Cannot import class
accepted answer: http://stackoverflow.com/a/47863043
has comment: http://stackoverflow.com/comment/82687171
answer count: 1

http://stackoverflow.com/comment/82779532
type: Comment
comment on: http://stackoverflow.com/q/47894011
type: QuestionComment
has text: The error means (as printed) that the file ` filtered_reads/A_r1_q20p50_filtered.fasta- filtered_reads/A_r2_q20p50_filtered.fasta` is not there after execution of the job. I suggest to check whether your command really creates the files it is supposed to create.
score: 0

http://stackoverflow.com/q/47948586
tagged with: django
has body: I'm trying to put a django website live and after going through the deployment checklist and turning debug = False django gives out a 404 error and only static files are loaded no media files uploaded from users are displayed. However with debug=True all the images and files work properly. below are the configurations of the project with debug = True. The console logs show multiple missing files.can someone point to me what i'm doing wrong? settings.py urls.py console errors
score: 1
type: Question
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/82867455
upvote count: 1
answer count: 1
has title: Django shows 404 error on media files when debug = False in production
favorite count: 0
has answer: http://stackoverflow.com/a/47951792
tagged with: python
tagged with: sorl-thumbnail
tagged with: python-3.x
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/48078079
downvote count: 0
has body: At first, I use on_model_change to set the default value of the roles field. And then, I use form_args and query_factory to limit the choices of roles field. def filter_func(): return db.session.query(Role).filter_by(name="applicant") form_args = { "roles": { "query_factory": filter_func } }
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47981081
type: Answer
answers question: http://stackoverflow.com/q/47981081
score: 2

http://stackoverflow.com/comment/82948002
score: 0
type: Comment
type: QuestionComment
has text: @terra9 Did you not read my first comment? I said `i` is being redeclared inside the loop, so `key` always receives the same value, and the `while` loop condition never becomes True, so you iterate infinitely.
comment on: http://stackoverflow.com/q/47989670

http://stackoverflow.com/q/47874943
has comment: http://stackoverflow.com/comment/82715898
tagged with: python
has comment: http://stackoverflow.com/comment/82937709
answer count: 0
type: UnansweredQuestion
type: Question
has title: Creating txt file in python - pywin32
score: 0
has body: I'm trying to create a txt file using PythonWin and when I run it, nothing happens. import sys, os import wmi import math computer = wmi.WMI() computer_info = computer.Win32_ComputerSystem()[0] os_info = computer.Win32_OperatingSystem()[0] proc_info = computer.Win32_Processor()[0] gpu_info = computer.Win32_VideoController()[0] os_name = os_info.Name.encode('utf-8').split(b"|")[0] os_version = ' '.join([os_info.Version, os_info.BuildNumber]) system_ram = math.ceil(float(os_info.TotalVisibleMemorySize) / 1048576) processorInfo = (proc_info.Name.split(" CPU")[0]) processorInfo = processorInfo.replace("(R)", "") processorInfo = processorInfo.replace("(TM)", "") operatingSystem = (os_name.decode('utf8')) operatingVersion = (os_version.split(" ")[0]) memoryInfo = ('{0} GB'.format(system_ram)) graphicsCard = (gpu_info.Name) hardwareList = [operatingSystem, operatingVersion, processorInfo, graphicsCard, memoryInfo] f = open('user_specs.txt', 'w+') f.write(str(hardwareList)) f.close() As I run it all I get is "Script 'my file location' returned exit code 0", but no file was created anywhere.

http://stackoverflow.com/comment/82714298
type: QuestionComment
comment on: http://stackoverflow.com/q/47859929
has text: [GitHub issue](https://github.com/landscapeio/pylint-django/issues/108)
score: 0
type: Comment

http://stackoverflow.com/q/47881611
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47881744
type: Question
tagged with: line-count
has body: I need to write a python code that reads the contents of a text file(file.txt) and calculate the average number of words per sentence.(Assuming the file contains a number of sentences only one per line.) i did the coding and i need to know whether it can be more efficient in another way. Million thanks in advance. here is mine : # This program reads contents of a .txt file and calulate # the average number of words per sentence . line_count=0 # open the file.txt for reading content_file=open('file.txt','r') # calculate the word count of the file content=content_file.read() words= content.split() word_count=len(words) # calculate the line count for line in open('file.txt'): line_count+=1 content_file.close() # calculate the average words per line average_words=word_count/line_count # Display the result print('The average word count per sentence is', int(average_words))
possible better answer: http://stackoverflow.com/a/47881788
upvote count: 0
has answer: http://stackoverflow.com/a/47881788
has title: Efficient way of reading word count from a file and calculating average per sentence
answer count: 3
has answer: http://stackoverflow.com/a/47881744
tagged with: python
has answer: http://stackoverflow.com/a/47881841
favorite count: 0
score: -1
tagged with: word-count
tagged with: file
downvote count: 1

http://stackoverflow.com/a/53318223
type: Answer
has body: 0 and 1 are exit codes. exit code (0) means an exit without an errors or any issues, can be a compile time error or any dependency issue. exit code (1) means there was some issue which caused the program to exit. For example if your program is running on port :8080 and that port is currently in used or not closed, then you code ends up with exit code 1
downvote count: 0
answers question: http://stackoverflow.com/q/47970844
score: 10
upvote count: 10

http://stackoverflow.com/q/47890695
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47898378
tagged with: django
tagged with: python
tagged with: pyjwt
type: Question
has title: Is any needs to create a simple login view when using djangorestframework-jwt obtain_jwt_token views?
tagged with: django-rest-framework
has body: Basically I want to developed a system where user logged in using username and password using 'JSONWebTokenAuthentication'.That's way I am use 'django rest framework JWT'.Before i was create an accounts app where user can registration and login using there username and password. In account/urls.py urlpatterns = [ url('^login/$', UserLoginApiView.as_view(), name='login'), url('^register/$', UserCreateApiView.as_view(), name='register'), ] In mainproject/urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/auth/token/', obtain_jwt_token), url(r'^api/users/', include("account.urls", namespace='user_api')), ] When i was open 'api/auth/token/' This URL. it shows username field and password field in the browserable api it's ok coz it is built in view djangorestframework-jwt.If username &amp; password match in db that's provided a token. My question is when i use my own login view .If using 'djangorestframework-jwt' obtain_jwt_token views in api/auth/token/ Only registration is enough to create an user. Is any needs to create an extra login view if we use djangorestframework-jwt.
score: 0
answer count: 1
tagged with: django-rest-framework-jwt

http://stackoverflow.com/comment/82683582
score: 0
type: QuestionComment
type: Comment
has text: @MadPhysicist thanks for the comment. If I swap the mask and the or the mask with the image, I will have the value 255 at all the places outside the mask. I want the value -1 at all those other places outside the mask.
comment on: http://stackoverflow.com/q/47859327

http://stackoverflow.com/q/47884199
has comment: http://stackoverflow.com/comment/82734586
downvote count: 3
has comment: http://stackoverflow.com/comment/82747545
tagged with: mapreduce
has comment: http://stackoverflow.com/comment/82734442
linked to: http://stackoverflow.com/q/28239529
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82741303
has comment: http://stackoverflow.com/comment/82777864
has comment: http://stackoverflow.com/comment/82734144
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/82734371
favorite count: 0
tagged with: dask
has comment: http://stackoverflow.com/comment/82734361
type: Question
has comment: http://stackoverflow.com/comment/82734701
has comment: http://stackoverflow.com/comment/82734616
has comment: http://stackoverflow.com/comment/82743972
tagged with: python
has body: I have a huge .csv file (above 100 GB) in the form: | Column1 | Column2 | Column3 | Column4 | Column5 | |---------|---------|---------|---------|---------------------| | A | B | 35 | X | 2017-12-19 11:28:34 | | A | C | 22 | Z | 2017-12-19 11:27:24 | | A | B | 678 | Y | 2017-12-19 11:38:36 | | C | A | 93 | X | 2017-12-19 11:44:42 | And want to summarize it by the unique values in Column1 and Column2 with sum(Column3), max(Column5) the value of Column4, where Column5 was at its maximum. Therefore the above extract should become: | Column1 | Column2 | sum(Column3) | Column4 | max(Column5) | |---------|---------|--------------|---------|---------------------| | A | B | 702 | Y | 2017-12-19 11:38:36 | | A | C | 22 | Z | 2017-12-19 11:27:24 | | C | A | 93 | X | 2017-12-19 11:44:42 | With these additional considerations: The .csv is not sorted I have python under windows The solution should be on a standalone PC (Cloud instances are not acceptable) I have tried Dask and the .compute() step (should it ever complete) will take about a week. Anything faster than this would be a good solution. I am open to all kinds of solutions - splitting the file into chunks, multiprocessing... whatever would work Edit 1: I had not used multiprocessing in dask. Adding it improves the speed signifficantly (as suggested by one of the comments), but the 32G RAM is not enough for this approach to complete. Edit 2: Dask 0.16.0 is not a possible solution, as it is absolutely broken. After 5 hours of writing partitions to disk, it has written 8 out of 300 partitions and after reporting to have written 7, now it reports having written 4, instead of 8 (without throwing an error).
has comment: http://stackoverflow.com/comment/82768526
has title: Group a huge csv file in python
upvote count: 3
score: 0
has comment: http://stackoverflow.com/comment/82808507

frequency-distribution
tag name: frequency-distribution
type: Tag
tags question: http://stackoverflow.com/q/47998828

http://stackoverflow.com/a/48012291
has comment: http://stackoverflow.com/comment/82993141
has body: You could just reset index and output it? Note: I'm using to_dict here instead of to_json to use a simple print import pandas as pd df = pd.DataFrame({'2017-12-24': [1.5, 0.0, 1.5], '2017-12-31': [0.5, 1.5, 0.0]}, index=['a', 'b', 'c']) print(df.T.reset_index().rename(columns={'index':'datetime'}).to_dict('r')) [{'datetime': '2017-12-24', 'a': 1.5, 'b': 0.0, 'c': 1.5}, {'datetime': '2017-12-31', 'a': 0.5, 'b': 1.5, 'c': 0.0}]
upvote count: 2
has comment: http://stackoverflow.com/comment/82993165
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82993199
answers question: http://stackoverflow.com/q/48012197

http://stackoverflow.com/comment/82715113
has text: One opinion: your GUI will look very overloaded. :P
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47874864

http://stackoverflow.com/q/47896904
has answer: http://stackoverflow.com/a/47897567
score: 0
has title: Inverse of ProcessPoolExecutor in Python
has body: This is related to my earlier problem which I'm still working on solving. Essentially I need the inverse design of ProcessPoolExecutor, where I have many querying processes and one worker which calculates and sends back results in batches. Sending the work items is easy with one shared queue, but I still don't have a nice solution for sending all the results back to the right threads on the right processes.
tagged with: python
type: AnsweredQuestion
tagged with: multiprocessing
type: Question
accepted answer: http://stackoverflow.com/a/47897567
linked to: http://stackoverflow.com/q/47890254
answer count: 1

http://stackoverflow.com/comment/82881967
type: Comment
comment on: http://stackoverflow.com/q/47956236
score: 1
type: QuestionComment
has text: Not that I'm aware of, and I don't see how it would work; I think you'd have to write that yourself. For example, you could expose that function at a higher level in the module, using the `f = numba.jit(f)` form, then import the original, unwrapped version directly in your tests.

http://stackoverflow.com/comment/82965300
score: 0
type: QuestionComment
has text: well if you want JSON, than you do not want searlize() and searlizeArray()
type: Comment
comment on: http://stackoverflow.com/q/47998286

http://stackoverflow.com/q/48008855
score: 0
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
type: UnansweredQuestion
has body: So I'm currently working on a project which is using Java for it's GUI and a python script to perform the primary functions of the program. I was wondering if there is a way to run the python script from within the application directory, and then send its output to the GUI program for parsing. The output could be JSON/YAML/Plaintext etc (so this will be parsed by the GUI). Two options I thought of (which may or may not work) were: Running the Python program separately and having it output a file which is then read by the Java program (This is my least favourite) Using ProcessBuilder or Runtime.exec to run the Python program.. But then how would I get the output? If neither of my options I thought of are feasible or would work, then is there a way to do this much better? Thanks!
tagged with: python
has answer: http://stackoverflow.com/a/48008990
tagged with: java
has title: Using Java to run a Python application and then parse its output
type: Question
has comment: http://stackoverflow.com/comment/83047536

http://stackoverflow.com/q/47997164
has answer: http://stackoverflow.com/a/52730642
accepted answer: http://stackoverflow.com/a/52730642
has answer: http://stackoverflow.com/a/47997410
linked to: http://stackoverflow.com/q/18363022
has comment: http://stackoverflow.com/comment/82962629
type: Question
has body: I followed online instructions on how to install pip on macOS (for example this, this, and this). I all seems to simple, but it's not working for me. My python --version is 2.7.10. When I run sudo easy_install pip I get: $ sudo easy_install pip Password: Searching for pip Reading http://pypi.python.org/simple/pip/ Couldn't find index page for 'pip' (maybe misspelled?) Scanning index of all packages (this may take a while) Reading http://pypi.python.org/simple/ No local packages or download links found for pip error: Could not find suitable distribution for Requirement.parse('pip') Any idea how I can fix or work around this?
has answer: http://stackoverflow.com/a/55383585
has title: Installing pip on macOS does not work (anymore)
score: 12
answer count: 3
possible better answer: http://stackoverflow.com/a/47997410
tagged with: macos
tagged with: easy-install
favorite count: 0
upvote count: 12
has comment: http://stackoverflow.com/comment/82962728
tagged with: pip
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82963945
downvote count: 0

http://stackoverflow.com/q/47881280
has answer: http://stackoverflow.com/a/47887248
has title: Timeout for sftp.get in Paramiko
tagged with: sftp
type: AnsweredQuestion
downvote count: 0
score: 1
has body: I found this to be useful Setting timelimit for sftp.get() of Paramiko module but the callback function here also takes into account time for connection establishment. I need to restrict only the SFTP get file transfer time. I tried to modify the callback function as below but it doesn't work. Here's my code. class TimeLimitExceeded(Exception): pass def _timer(start_time, timelimit=5): elapsed_time = time.time()-start_time if elapsed_time &gt; timelimit: raise TimeLimitExceeded if __name__=="__main__": ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip, port, username, password) sftp = ssh.open_sftp() try: start_time=time.time() sftp.get(remote_path, local_path, _timer(start_time)) except TimeLimitExceeded: print ("The operation took too much time to complete") finally: sftp.close() ssh.close()
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/47887248
linked to: http://stackoverflow.com/q/40222684
upvote count: 1
answer count: 1
tagged with: paramiko
has comment: http://stackoverflow.com/comment/82736853

http://stackoverflow.com/q/47956410
has answer: http://stackoverflow.com/a/47956518
linked to: http://stackoverflow.com/q/476968
type: Question
favorite count: 0
upvote count: 2
tagged with: scala
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/82882275
has comment: http://stackoverflow.com/comment/82882437
has title: How to run Scala class in python?
has comment: http://stackoverflow.com/comment/82882451
linked to: http://stackoverflow.com/q/18484879
has body: There is Scala object object Test { def t1(): String = { "test" } } need execute its in Python Test.t1() need execute not in JVM interpretator or convert Scala code to Python
downvote count: 5
type: UnansweredQuestion
score: -3

http://stackoverflow.com/comment/82822914
score: 2
comment on: http://stackoverflow.com/q/47927371
has text: I don't understand. Where is your input? And what do you want the output to be? Do you want to remove the symbols? Do you want to evaluate the expressions? Do you want to extract the integers separately? What is it?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82695956
type: Comment
comment on: http://stackoverflow.com/q/47865418
has text: **ctrl+z ** can work but is there any other way such as to check main_thread alive.
score: 0
type: QuestionComment

directory
tags question: http://stackoverflow.com/q/47933487
tags question: http://stackoverflow.com/q/47951914
tags question: http://stackoverflow.com/q/47947889
tag name: directory
tags question: http://stackoverflow.com/q/47956567
tags question: http://stackoverflow.com/q/47871357
tags question: http://stackoverflow.com/q/47948907
type: Tag
tags question: http://stackoverflow.com/q/47977255
tags question: http://stackoverflow.com/q/47880491
tags question: http://stackoverflow.com/q/47915831
tags question: http://stackoverflow.com/q/47858950

http://stackoverflow.com/comment/82759879
has text: You are welcome. But I am not making your program, I am just illustrating a concept or two for you.
comment on: http://stackoverflow.com/a/47896398
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47996863
has body: Looking for help to loop through all tabs on a website to capture all relevant information. In the following site, there are a few tabs labelled 5x5, 5x10, 5x15, 10x10, etc. I'm not sure how to structure it so it will go through the tabs and write the loops in my script. Your help is appreciated. Below is the python script; from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup import csv urls = [ 'https://www.lifestorage.com/storage-units/florida/orlando/32810/610-near-lockhart/?size=5x5' ] filename = 'life_storage.csv' f = open(filename, 'a+') csv_writer = csv.writer(f) headers = ['unit_size', 'unit_type', 'description', 'online_price', 'reg_price', 'store_address', 'store_city', 'store_state', 'store_postalcode' ] ##unit_size = 5'x10' withouth the ' ##unit_type = climate controlled or not (this could be blank if non-climate) ##descirption = the level it's on and type of access. ##online_price = $##/mo text ##reg_price = the scratched off $## text csv_writer.writerow(headers) for my_url in urls: uClient = uReq(my_url) page_html = uClient.read() uClient.close() page_soup = soup(page_html, 'html.parser') store_locator = page_soup.findAll("div", {"itemprop": "address"}) containers = page_soup.findAll("ul", {"id": "spaceList"}) for container in containers: for store_location in store_locator: store_address1 = store_location.find("span", {"itemprop": "streetAddress"}) store_address = store_address1.text store_city1 = store_location.find("span", {"itemprop": "addressLocality"}) store_city = store_city1.text store_state1 = store_location.find("span", {"itemprop": "addressRegion"}) store_state = store_state1.text store_postalcode1 = store_location.find("span", {"itemprop": "postalCode"}) store_postalcode = store_postalcode1.text title_container = container.find("div", {"class": "storesRow"}) unit_size = title_container.text unit_container = container.find("div", {"class": "storesRow"}) unit_type = unit_container.strong.text description_container …
has comment: http://stackoverflow.com/comment/82964689
type: Question
has answer: http://stackoverflow.com/a/48001043
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/82967024
tagged with: http://stackoverflow.com/tag/html
tagged with: beautifulsoup
accepted answer: http://stackoverflow.com/a/48001043
has comment: http://stackoverflow.com/comment/82964457
tagged with: web-scraping
tagged with: python
type: AnsweredQuestion
has title: Python Web Scrape Cycle Tabs

http://stackoverflow.com/comment/82752972
comment on: http://stackoverflow.com/a/47892880
score: 0
type: AnswerComment
has text: @Oleh Kuzovkov: IMO this answer is better than mine—so you should accept it. Jared: Meta interesting!
type: Comment

http://stackoverflow.com/comment/82988606
type: QuestionComment
comment on: http://stackoverflow.com/q/48009926
has text: well check this out https://stackoverflow.com/questions/47986858/give-inputs-to-a-running-program-using-python/47990014#47990014 , but one thing to remember while using pipes that if one file has done executing then another file will automatically get the output through the pipe
score: 0
type: Comment

http://stackoverflow.com/comment/82860346
has text: could I email you to assist me with getting this together?
type: Comment
comment on: http://stackoverflow.com/a/47917792
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82778798
comment on: http://stackoverflow.com/a/47905857
type: AnswerComment
score: 0
has text: i saved it but it runs without any error and shows nothing.
type: Comment

http://stackoverflow.com/q/47979117
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/47979563
has comment: http://stackoverflow.com/comment/82926948
possible better answer: http://stackoverflow.com/a/47979572
tagged with: http://stackoverflow.com/tag/html
has body: When ever i summit my Django form from the template .I get the result bellow <a href="http://127.0.0.1:8000/Search_match_distributors/?csrfmiddlewaretoken=3rDq624irqw2L0WDQCvzFHM5pAux3ep9cXWTeKQ4WlNyd5JWJxQrHVfBOLAPMHI1&CompanyRegisteredName=unine&CompanyRegisteredState=weqeqqw&CompanyRegisteredAddress=qewq&CompanyRegisteredCity=qwqw&CompanyEmail=qweq%40yahoo.com&Country=Belize&RegisteredCompanyType=corperation&title=SeaFood&YouOwnBusiness=Yes&AreaCode=%2B375&WorkPhone=121212&TypeOfDistributorPrefered=IntensiveDistributors" rel="nofollow noreferrer">http://127.0.0.1:8000/Search_match_distributors/?csrfmiddlewaretoken=3rDq624irqw2L0WDQCvzFHM5pAux3ep9cXWTeKQ4WlNyd5JWJxQrHVfBOLAPMHI1&CompanyRegisteredName=unine&CompanyRegisteredState=weqeqqw&CompanyRegisteredAddress=qewq&CompanyRegisteredCity=qwqw&CompanyEmail=qweq%40yahoo.com&Country=Belize&RegisteredCompanyType=corperation&title=SeaFood&YouOwnBusiness=Yes&AreaCode=%2B375&WorkPhone=121212&TypeOfDistributorPrefered=IntensiveDistributors data to be save in the saver, is displayed on the browser instead.In the form of a url (url above) . Does someone has an idea why such happens. My code in views.py ,form.py and model.py and url.py has no error Template {% csrf_token %} {% for dis in distributor %} {{dis.errors }} {% endfor %} CompanyName {{distributor.CompanyRegisteredName}} StateOfRegistry {{distributor.CompanyRegisteredState}} AddressOfCompany {{distributor.CompanyRegisteredAddress}} CityOfRegistry {{distributor.CompanyRegisteredCity}} CompanyEmail {{distributor.CompanyEmail}} Country {{distributor.Country}} TypeOfCompany {{distributor.RegisteredCompanyType}} DistributorType {{distributor.title}} CompanyWebsite?If yes chosen,companyweblink ask in next {{distributor.YouOwnBusiness}} WorkPhone {{distributor.AreaCode}}{{distributor.WorkPhone}} Products You Distribute {% for checkbox in distributor.ManufacturerOfInterest %} {{checkbox.tag}} {{checkbox.choice_label}} {% endfor %} Create here is my view.py @transaction.atom…
has answer: http://stackoverflow.com/a/47979572
has title: Why will django form not summit data to dabase but instead displays result as a url on the broswer
has answer: http://stackoverflow.com/a/47979563
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82926934
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82927009
has comment: http://stackoverflow.com/comment/82926916

http://stackoverflow.com/comment/82995629
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48012711
has text: The data is stored as lists in one column, do something like `scaler.fit(np.array(df[0].values.tolist()))`

http://stackoverflow.com/q/47901307
has title: pandas dataframe count unique list
has comment: http://stackoverflow.com/comment/82769480
has body: If the type of a column in dataframe is int, float or string, we can get its unique values with columnName.unique(). But what if this column is a list, e.g. [1, 2, 3]. How could I get the unique of this column?
score: 3
tagged with: dataframe
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/47904311
has answer: http://stackoverflow.com/a/47901350
accepted answer: http://stackoverflow.com/a/47901350
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/82769210
tagged with: python
has comment: http://stackoverflow.com/comment/82769149
type: AnsweredQuestion
upvote count: 3
possible better answer: http://stackoverflow.com/a/47904311
type: Question

http://stackoverflow.com/a/47935301
accepted answer of: http://stackoverflow.com/q/47934894
score: 0
has body: Solved the edited portion by: firebase.patch('/test/' + fstr , {cstr: t.conf})
answers question: http://stackoverflow.com/q/47934894
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/82815259
comment on: http://stackoverflow.com/q/47923795
score: 0
type: Comment
has text: I want to have access to the CSV data and use the column data for a variety of functions, and then move to the next row of data
type: QuestionComment

http://stackoverflow.com/comment/82688510
has text: The former starts about here **[parallel-processing]** >>> https://stackoverflow.com/tags/parallel-processing/info The latter starts about here **[parallelism-amdahl]** >>> https://stackoverflow.com/revisions/18374629/3 Many projects, even countless examples here, on StackOverflow, finish with asking "Why's my parallel code so slower than the original?", so indeed worth to read twice before cut once. The costs of ( principally ) wrong approach are inadvertently lost and pain remains, after forgetting to first evaluate the re-formulated Amdahl's Law if there is any potential for speedup at all.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47861190
type: AnswerComment

http://stackoverflow.com/q/47863781
has comment: http://stackoverflow.com/comment/82693914
accepted answer: http://stackoverflow.com/a/47902813
tagged with: html-parsing
downvote count: 1
type: Question
score: 5
has title: How to use a custom parser with Python's Beautiful Soup?
has comment: http://stackoverflow.com/comment/82694353
answer count: 1
has answer: http://stackoverflow.com/a/47902813
has body: I am using Beautiful Soup 4 to parse and modify a set of HTML files. The HTML files are Angular templates, which means their markup is somehow different than the one in regular HTML documents (mixed case attributes, directives, input/output bindings, etc.). None of the parsers listed in Beautiful Soups documentation (html.parser, lxml, html5lib) totally fit my needs. The closest to it is Python’s built in html.parser, but I had to make a few adjustments to it. Is it possible to use a custom parser class with Beautiful Soup? If yes, how could this be implemented? Edit: Below is an example of how Beautiful Soup parses a template. The main issue is that all attributes from the result are lowercase (*ngIf -> *ngif) and the directives (appAutoFocus, appKeepFocusInside, etc.) get an empty string value (e.g. appautofocus=""). from bs4 import BeautifulSoup test_html = """ &lt;kendo-dialog *ngIf="dialogOpened" appAutoFocus appKeepFocusInside (close)="closeDialog()" width="1000"&gt; &lt;kendo-dialog-titlebar&gt;A title&lt;/kendo-dialog-titlebar&gt; &lt;div *ngIf="model.showValidationFailedMessage" class="alert alert-danger alert-dismissible"&gt; &lt;button type="button" class="close" aria-label="Close" (click)="model.closeValidationAlert()"&gt;&lt;span aria-hidden="true"&gt;&amp;amp;times;&lt;/span&gt;&lt;/button&gt; Validation failed &lt;/div&gt; &lt;kendo-tabstrip [keepTabContent]="true"&gt; &lt;kendo-tabstrip-tab title="Tab title 1" [selected]="true"&gt; &lt;ng-template kendoTabContent&gt; &lt;div&gt;Tab content&lt;/div&gt; &lt;/ng-template&gt; &lt;/kendo-tabstrip-tab&gt; &lt;/kendo-tabstrip&gt; &lt;/kendo-dialog&gt; """ document = BeautifulSoup(test_html, "html.parser") print(document.prettify()) Result: &lt;kendo-dialog (close)="closeDialog()" *ngif="dialogOpened" appautofocus="" appkeepfocusinside="" width="1000"&gt; &lt;kendo-dialog-titlebar&gt; A title &lt;/kendo-dialog-titlebar&gt; &lt;div *ngif="model.showValidationFailedMessage" class="alert alert-danger alert-dism…
favorite count: 0
tagged with: parsing
tagged with: beautifulsoup
tagged with: python-3.x
tagged with: python
upvote count: 6
type: AnsweredQuestion

http://stackoverflow.com/comment/82759369
type: QuestionComment
has text: Please focus your question on the specific technical problem you're asking about, not the application you're trying to create. If you haven't gotten to where you have a specific technical problem, you don't have a question suited for StackOverflow.
type: Comment
score: 2
comment on: http://stackoverflow.com/q/47896244

http://stackoverflow.com/comment/105930263
type: AnswerComment
has text: The scope can be any REST resource instance. For example, use '/subscriptions/{subscription-id}/' for a subscription, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for a resource group. So res_group_id is a valid scope
type: Comment
comment on: http://stackoverflow.com/a/47958873
score: 0

http://stackoverflow.com/a/47951526
has comment: http://stackoverflow.com/comment/82873730
has comment: http://stackoverflow.com/comment/82872757
has body: Using an XPath with elements by position is not ideal. Instead use a CSS selector to match the attributes for the targeted elements. Something like: all_Display = driver.find_elements_by_css_selector("#tiles li[onclick][data-item-id] a[title]") You can then click them in a loop if none of them is loading a new page: for element in all_Display: element.click()
type: Answer
answers question: http://stackoverflow.com/q/47948225
has comment: http://stackoverflow.com/comment/82872822
score: 0

http://stackoverflow.com/comment/114529255
score: 0
type: Comment
comment on: http://stackoverflow.com/a/58409912
type: AnswerComment
has text: I think you should edit `Cs, Ds = [], []` (1st row of `run_loopy`) to `v1s, v2s = [], []` or vice versa

http://stackoverflow.com/q/47863768
answer count: 2
has answer: http://stackoverflow.com/a/47865022
has body: How to use python (3.5) json standard library to print floats with trailing zeros? import json to_be_serialized = {'something': 0.020} print(json.dumps(to_be_serialized)) {"something": 0.02} # desired output: {"something": 0.020} I tried this but unfortunately without desired result.
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47883263
has title: python json float with leading zeros
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 3
tagged with: http://stackoverflow.com/tag/json
possible better answer: http://stackoverflow.com/a/47865022
linked to: http://stackoverflow.com/q/1447287
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/47883263

http://stackoverflow.com/a/47966693
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47966556
score: 1
answers question: http://stackoverflow.com/q/47966556
type: AcceptedAnswer
downvote count: 0
has body: Regexes can have groups. They are denoted by (). Groups can be used to extract a part of the match which might be useful. In the phone number regex for example, there are 9 groups: Group Subpattern 1 ((\d{3}|\(\d{3}\))?(\s|-|\.) (\d{3}) (\s|-|\.)(\d{4})(\s*(ext|x|ext.)\s*(\d{2,,5}))?) 2 (\d{3}|\(\d{3}\))? 3 (\s|-|\.) 4 (\d{3}) 5 (\s|-|\.) 6 (\d{4}) 7 (\s*(ext|x|ext.)\s*(\d{2,,5}))? 8 (ext|x|ext.) 9 (\d{2,,5}) Note how each group is enclosed in ()s. The groups[x] is just referring to the string matched by a particular group. groups[0] means the string matched by group 1, groups[1] means the string matched by group 2, etc.

http://stackoverflow.com/q/47933946
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47942848
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47942848
downvote count: 0
score: 1
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/47946167
tagged with: hierarchical-data
has answer: http://stackoverflow.com/a/47946167
has body: I have some hierarchical codes stored in an OrderedDict with keys corresponding to levels of the hierarchy and a list of codes for each level, each child level having relations to a code in the parent level: from collections import OrderedDict codes_ord_dict = OrderedDict([ (2, [11]), (3, [111, 112]), (4, [1111, 1112, 1113, 1114, 1119, 1121, 1122, 1123, 1124, 1125, 1129]) ]) I am trying to get from this form to one such as a nested dictionary or a tree representation of these codes, the former being something like: codes_dict = { 11: { 111: { 1111: { ... }, 1112: { ... }, 1113: { ... }, ... }, 112: { ... }, } } Mentally I am just not making the programming connection to traverse a level, follow a parent code by pushing onto the next level to build out the children before returning back the way I came and moving on to the next code, while maintaining some kind of record of what relations I have built out and which ones I have not, so there is no repeating. Not really looking for an answer handed to me, but just some strategies for how to approach this. It seems like a solution would involve recursion, but I also have to maintain some state to reference previous level(s) and next level(s). Any guidance would be appreciated.
upvote count: 1
tagged with: nested
has title: Hierarchical Data Traversal and Representation in Python

http://stackoverflow.com/q/47916856
linked to: http://stackoverflow.com/q/3020197
has body: While I was doing unit testing, I wrote some code that I knew wouldn't pass because of foreign constrainst... Except it did. This is an example : import os import sqlalchemy as sa from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base, declared_attr import logging logging.basicConfig() logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO) try: os.unlink('test.db') except: pass engine = create_engine('sqlite:///test.db') Base = declarative_base() class Test1(Base): __tablename__ = 'Test1' id = sa.Column(sa.Integer(), primary_key = True) class Test2(Base): __tablename__ = 'Test2' id = sa.Column(sa.Integer(), primary_key = True) link = sa.Column(sa.Integer(), sa.ForeignKey(Test1.id), index = True) Base.metadata.create_all(engine) Session = sessionmaker() session = Session(bind=engine) session.add(Test2(id=1, link=2)) # &lt;-- should raise an error because 2 not in Test1 session.commit() session.add(Test1(id=1)) session.commit() session.add(Test2(id=2, link=1)) #ok session.commit() session.add(Test2(id=3, link=42)) # &lt;-- should raise an error because 42 not in Test1 session.commit() I declare a simple database, a table Test1 with a PK id, and a second table Test2 with a PK id and a FK constrainst on Test2.link to reference Test1.id. Then, I insert some values that would break the FK. The FK seems to work because if I open a sqlite db browser, I can't put these same values... Why and how sqlalchemy bypasses the FK ? Note : I haven't tried on another db
has answer: http://stackoverflow.com/a/47916940
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/2614984
duplicate of: http://stackoverflow.com/q/2614984
tagged with: sqlalchemy
type: Question
accepted answer: http://stackoverflow.com/a/47916940
score: 0
tagged with: sqlite
has title: Why (and how ?) does sqlalchemy bypass FK constrainsts with sqlite?
answer count: 1

http://stackoverflow.com/q/47988765
score: -1
tagged with: flask
has comment: http://stackoverflow.com/comment/82949706
answer count: 2
has answer: http://stackoverflow.com/a/48361165
has body: I want to give flask a try. Using flask 0.12, python 3.4 I've created the project tree similar like in: https://damyanon.net/post/flask-series-structure/ controllers.py code: from flask import Blueprint import functools, operator main = Blueprint('main', __name__) @main.route('/') def index(): return "Main world" @main.route('/foo') def foo(): return "this is foo" when I run the app, I got 404 for /foo route but '/' is OK * Serving Flask app "run" * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) 127.0.0.1 - - [27/Dec/2017 15:19:21] "GET / HTTP/1.1" 200 - 127.0.0.1 - - [27/Dec/2017 15:19:25] "GET /foo HTTP/1.1" 404 - Any clue? Thanks. edit: As requested, here how I register blueprint in flask_app/localservice/init.py. Not sure about application factory. I'm still new with this. I substitute bookshelf with localservice and not use admin from flask import Flask from localservice.main.controllers import main app = Flask(__name__) app.register_blueprint(main, url_prefix='/')
upvote count: 0
favorite count: 0
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47990390
downvote count: 1
type: Question
has title: flask app gives 404 for non-root route

http://stackoverflow.com/q/47910192
tagged with: pyqt
answer count: 1
tagged with: pyqt4
downvote count: 0
tagged with: qlayout
upvote count: 8
tagged with: python
has answer: http://stackoverflow.com/a/47910493
favorite count: 0
has body: I am trying to create a layout looking like this: _________ | | | |1 | 2 | |__|______| | 3 | 4 | |____|____| Basically, I want cell number 1 the first row to be thinner that cell 2, but cells number 3 and 4 on the second row should have equal widths. Is it even possible to create a layout like this using QGridLayout in PyQt4?
tagged with: qgridlayout
linked to: http://stackoverflow.com/q/47681774
type: Question
has title: QGridLayout different column width
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47910493
score: 8

http://stackoverflow.com/a/47906434
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/82782394
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82781546
type: Answer
has comment: http://stackoverflow.com/comment/82779665
accepted answer of: http://stackoverflow.com/q/47906226
has body: We can use pivot table and concat i.e ndf = df.pivot_table(index=['ID'],columns=['Class'],aggfunc='count',fill_value=0)\ .xs('year_month_id', axis=1, drop_level=True) ndf['latest'] = df.sort_values('ID').groupby('ID')['Class'].tail(1).values Class A B D Other latest ID 1 1 1 0 0 B 2 0 0 1 0 D 3 0 1 0 0 B 4 0 0 0 1 Other 5 0 0 0 1 Other 6 0 0 0 1 Other 7 1 0 0 0 A 8 0 0 0 1 Other 9 1 0 0 0 A
answers question: http://stackoverflow.com/q/47906226

http://stackoverflow.com/q/47966081
has comment: http://stackoverflow.com/comment/82901864
tagged with: dataframe
type: Question
has body: I am trying use pandas DataFrame.combine to combine multiple data frames. However, I couldn't figure out how to fulfill the func parameter. The doc is not very clear to me. The documentation specifies: DataFrame.combine(other, func, fill_value=None, overwrite=True) other : DataFrame func : function. Function that takes two series as inputs and return a Series or a scalar fill_value : scalar value overwrite : boolean, default True. If True then overwrite values for common keys in the calling frame After some research, I found out that a similar command, DataFrame.combine_first can be used with reduce as below to combine multiple data frames (link): reduce(lambda left,right: pd.DataFrame.combine_first(left,right), [pd.read_csv(f) for f in files]) How can I use DataFrame.combine to combine multiple data frames?
has comment: http://stackoverflow.com/comment/82901848
downvote count: 0
tagged with: pandas
answer count: 1
favorite count: 0
has title: DataFrame.combine to Combine Multiple Frame
has comment: http://stackoverflow.com/comment/82901980
has comment: http://stackoverflow.com/comment/82901805
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47966143
has comment: http://stackoverflow.com/comment/82901808
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/44327999
has comment: http://stackoverflow.com/comment/82901912
score: 1

http://stackoverflow.com/q/47948512
has answer: http://stackoverflow.com/a/47949695
has comment: http://stackoverflow.com/comment/82867642
score: 1
linked to: http://stackoverflow.com/q/375427
tagged with: command-line-interface
has title: subprocess.Popen to interact with a CLI prompt
has comment: http://stackoverflow.com/comment/82867517
has comment: http://stackoverflow.com/comment/82867848
tagged with: bash
answer count: 2
linked to: http://stackoverflow.com/q/19880190
downvote count: 0
has comment: http://stackoverflow.com/comment/82867899
favorite count: 0
has body: I am trying to write and read from a CLI program using subprocess.Popen. So every time you issue a command to the CLI it prints something, and that something is what I want to read. I will try to explain what I want do to with a concrete example so everybody can try. Thus, instead of using my real program I will use ipython for which the problem holds: p = subprocess.Popen(['ipython'],stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate(input="5+5") If you use Popen.communicate(input=command) you get at stdout exactly all the text that ipython would print in the terminal if I would have executed it directly from the shell. What I want to do: Instead of using communicate. I want to be able to send individual commands and read the immediate output. For example I would like to do: p.stdin.write("5+5") out1 = p.stdout.read() p.stdin.write("5*10") out2 = p.stdout.read() So out1 should be 5 and out2 should be 50. Problem: You can not read the stdout until you close stdin. How do you do that ? I can't use read(n) or readline() since in my real application I do not know the length of the output.
linked to: http://stackoverflow.com/q/47947625
has comment: http://stackoverflow.com/comment/82868023
has comment: http://stackoverflow.com/comment/82867152
tagged with: python
has comment: http://stackoverflow.com/comment/82867888
tagged with: subprocess
has answer: http://stackoverflow.com/a/47948559
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/82867143
has comment: http://stackoverflow.com/comment/82867865
type: Question
tagged with: popen

http://stackoverflow.com/comment/82969368
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47972510
has text: You could also look at `help(p)` and search for `coeff` (type `/coeff`). This will help you find not only methods whose name mentions "coeff" but also methods whose docstring mentions it.

http://stackoverflow.com/q/47912149
has answer: http://stackoverflow.com/a/47912739
downvote count: 0
score: 1
favorite count: 0
tagged with: beautifulsoup
has body: from requests import get from bs4 import BeautifulSoup url = 'https://www.ceda.com.au/Events/Upcoming-events' response = get(url) events_container = html_soup.find_all('div', class_ = 'list-bx') event1name = events_container[0] print(event1name.a.text) Eventdate = html_soup.find('div', class_ = ' col-md-4 col-sm-4 side-box well side-boxTop') x = Eventdate.div.text print(x) I'm trying to print the second span class on the class " col-md-4 col-sm-4 side-box well side-boxTop" But I coud'nt able to print the second span class (Second P tag (Event Date) from the class as there is no unique span name for the each span class
possible better answer: http://stackoverflow.com/a/47912783
tagged with: python
has answer: http://stackoverflow.com/a/47912783
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47912739
tagged with: web-scraping
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/82792670
has title: Python: BeautifulSoup extract all the span clases from div section
answer count: 2

http://stackoverflow.com/comment/83014417
comment on: http://stackoverflow.com/a/47984501
type: AnswerComment
score: 0
type: Comment
has text: Python Extensions for Windows comes with the `makepy` tool, which generates static definitions in `c:\Program Files\Python36\Lib\site-packages\win32com\gen_py`.

http://stackoverflow.com/q/47915831
tagged with: directory
tagged with: regex
has comment: http://stackoverflow.com/comment/82799786
has answer: http://stackoverflow.com/a/47915994
type: UnansweredQuestion
has body: I have a list of directories named by date MMDDYYYY (11222013). I'm ultimately trying to delete all directories from the year 2013. I believe my regex should be looking for 6 digits [0-9]. I've tried breaking the code into multiple variables but have had no luck. I suspect I'm not escaping the regex correctly. I keep running into this error: FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:/U sers/USER/Desktop/test/\d{6}13' I've tried printing my output and I get this path: C:/Users/USER/Desktop/test/\d{6}13 My code: import os import shutil import re StrDir = 'C:/Users/USER/Desktop/test/' Regex = r"\d{6}" + '13' print (StrDir + Regex) shutil.rmtree (StrDir + Regex)
tagged with: python
tagged with: escaping
downvote count: 0
score: 1
has title: Python - Regex as part of directory path - escape
type: Question
upvote count: 1
linked to: http://stackoverflow.com/q/973473
has comment: http://stackoverflow.com/comment/82799917
favorite count: 0
answer count: 1

http://stackoverflow.com/comment/82906929
has text: @DipanshuJuneja I added example of using generator. Try to run it and see in which order it being executed. You will see how using generators you can run some function and execute some code "in the middle" of it, when function reaches 'yield' point and control returns to you.
comment on: http://stackoverflow.com/a/47962706
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47917595
answer count: 2
has body: I have an XML file like below, and I've parsed it with lxml into Tree. What I want to do is change xml declaration from xmlns="http://www.w3.org/TR/html4/" to xmlns="http://www.w3.org/TR/html5/". Apples Bananas But I failed to get the xmlns attribute or change it by set the tag property. Any help, thanks.
tagged with: lxml
possible better answer: http://stackoverflow.com/a/47918674
score: 3
downvote count: 0
has answer: http://stackoverflow.com/a/47918674
favorite count: 0
has title: How to change XML namespace with lxml in Python?
tagged with: python
tagged with: xml-namespaces
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47917650
upvote count: 3
type: Question
accepted answer: http://stackoverflow.com/a/47917650

http://stackoverflow.com/a/47918448
has comment: http://stackoverflow.com/comment/82805631
has comment: http://stackoverflow.com/comment/82804712
score: 1
has comment: http://stackoverflow.com/comment/82840690
answers question: http://stackoverflow.com/q/47918295
has comment: http://stackoverflow.com/comment/82804912
type: AcceptedAnswer
has body: from django.utils import timezone Business.objects.filter(created_at__gte=timezone.now()) i guess this will be better for you. and change your model created_at = models.DateTimeField(auto_now=True) then makemigrations, migrate and then add some data and try again
has comment: http://stackoverflow.com/comment/82804795
downvote count: 0
has comment: http://stackoverflow.com/comment/82804749
accepted answer of: http://stackoverflow.com/q/47918295
type: Answer
upvote count: 1

http://stackoverflow.com/a/47896365
has comment: http://stackoverflow.com/comment/100262546
has comment: http://stackoverflow.com/comment/82771225
has comment: http://stackoverflow.com/comment/99361965
has comment: http://stackoverflow.com/comment/100497671
has comment: http://stackoverflow.com/comment/121835633
has comment: http://stackoverflow.com/comment/100262593
downvote count: 1
has comment: http://stackoverflow.com/comment/82932886
upvote count: 37
has comment: http://stackoverflow.com/comment/100329813
has comment: http://stackoverflow.com/comment/100271065
score: 36
has body: Trying to run both event loops at the same time is a dubious proposition. However, since root.mainloop simply calls root.update repeatedly, one can simulate mainloop by calling update repeatedly as an asyncio task. Here is a test program that does so. I presume adding asyncio tasks to the tkinter tasks would work. I checked that it still runs with 3.7.0a2. """Proof of concept: integrate tkinter, asyncio and async iterator. Terry Jan Reedy, 2016 July 25 """ import asyncio from random import randrange as rr import tkinter as tk class App(tk.Tk): def __init__(self, loop, interval=1/120): super().__init__() self.loop = loop self.protocol("WM_DELETE_WINDOW", self.close) self.tasks = [] self.tasks.append(loop.create_task(self.rotator(1/60, 2))) self.tasks.append(loop.create_task(self.updater(interval))) async def rotator(self, interval, d_per_tick): canvas = tk.Canvas(self, height=600, width=600) canvas.pack() deg = 0 color = 'black' arc = canvas.create_arc(100, 100, 500, 500, style=tk.CHORD, start=0, extent=deg, fill=color) while await asyncio.sleep(interval, True): deg, color = deg_color(deg, d_per_tick, color) canvas.itemconfigure(arc, extent=deg, fill=color) async def updater(self, interval): while True: self.update() await asyncio.sleep(interval) def close(self): for task in self.tasks: task.cancel() self.loop.stop() self.destroy() def deg_color(deg, d_per_tick, color): deg += d_per_tick if 360 <= deg: deg %= 360 color = '#%02x%02x%02x' % (rr(0, 256), rr(0, 256), rr(0, 256)) return deg, color loop = asyncio.get_event_loop() app = App(loop) loop.run_forever() loop.close() Both the tk update overhead and time resolution increase as the interval is decreased. For gui updates, as opposed to animations, 20 per second may be enough. I recently succeeded in running async def coroutines containing tkinter calls and awaits with mainloop. The prototype uses asyncio Tasks and Futures, but I don't know if adding normal asyncio tasks would work. If one wants to run asyncio and tk…
answers question: http://stackoverflow.com/q/47895765
has comment: http://stackoverflow.com/comment/82760500
has comment: http://stackoverflow.com/comment/99362163
has comment: http://stackoverflow.com/comment/82764093
type: Answer
has comment: http://stackoverflow.com/comment/100225540
has comment: http://stackoverflow.com/comment/99676219
has comment: http://stackoverflow.com/comment/100172323
has comment: http://stackoverflow.com/comment/89573582

http://stackoverflow.com/q/47942623
tagged with: django
has comment: http://stackoverflow.com/comment/82903922
type: Question
score: 0
has comment: http://stackoverflow.com/comment/82860950
linked to: http://stackoverflow.com/q/47941623
has comment: http://stackoverflow.com/comment/82862067
tagged with: unicode
has comment: http://stackoverflow.com/comment/82903952
has body: I've got class for uploading my csv files with holidays to my fullcalendar. It looks like this: class UploadVacationsView(APIView): def put(self, request, *args, **kwargs): try: # check file type mime = MimeTypes() url = urllib.pathname2url(request.FILES['file']._name) mime_type = mime.guess_type(url) if 'text/csv' not in mime_type: raise APIException(code=400, detail='File type must be CSV') vacations_list =[] csv_file = StringIO(request.data.get('file', None).read().decode('utf-8')) user_tz = pytz.timezone(request.user.common_settings.time_zone) schedule_file = ScheduleFile.objects.create(user=request.user) instance_hebcal = HebcalService() events = instance_hebcal.process_csv(csv_file, user_tz) ... And in the other class, I've got a method that works with csv files: class HebcalService(...): def process_csv(self, csv_file, user_tz): events = [] csv_input = csv.reader(csv_file.readlines(), dialect=csv.excel) curr_row = 1 start_date = None end_date = None start_name = None holiday_name = '' last_event = {'subject': '', 'date': '', } for row in list(csv_input)[1:]: subject, date, time, _, _, _, _ = row[:7] curr_row += 1 row = [unicode(cell.strip(), 'utf-8') for cell in row] if 'lighting' in subject and not start_date: start_date = user_tz.localize(format_datetime(date, time)) if date == last_event['date']: start_name = last_event['subject'] Everything is ok when working with english holiday's names but when I encounter hebrew names it shots an error: Traceback (most recent call last): File "/home/stas/work/vacation/vmode/apps/marketplaces/base/api/views.py", line 47, in put events = instance_hebcal.process_csv(csv_file, user_tz) File "/home/stas/work/vacation/vmode/apps/marketplaces/base/services/hebcal.py", line 106, in process_csv for row in list(csv_input)[1:]: UnicodeEncodeError: 'ascii' codec can't encode characters in position 19-23: ordinal not in range(128) I've read about making all strings to unicode but don't understand where it gets that default ASCII en…
has comment: http://stackoverflow.com/comment/82912489
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/82862397
tagged with: python
has title: 'ascii' codec can't encode... while uploading csv file
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/82757722
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47895351
has text: @COLDSPEED it didnt work

http://stackoverflow.com/q/47947391
has title: How to find quantile from frequency data?
tagged with: quantile
tagged with: statistics
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/47948945
has comment: http://stackoverflow.com/comment/82864937
downvote count: 0
has body: Suppose I have a table of data where customers have purchased things as such: Customer|Price|Quantity Sold a | 200 | 3.3 b | 120 | 4.1 c | 040 | 12.0 d | 030 | 16.76 This is supposed to be a crude representation of a table of data, with customer, price, and quantity sold for the same product. I want to figure out how to calculate the median purchase price for this info. I'm getting a little confused on methodology because I get that getting a quantile in pandas is easy as data[row].quantile(x) but since each row really represents more than one observation, I'm unsure how get quantiles. edit: On top of that, the major problem is that quantity sold is not discreete. It's a continous variable. (We're like talking meters, kgs etc, so creating more rows isn't an option.)
has answer: http://stackoverflow.com/a/57313457
favorite count: 0
has comment: http://stackoverflow.com/comment/82868256
possible better answer: http://stackoverflow.com/a/47947720
has comment: http://stackoverflow.com/comment/82865608
has answer: http://stackoverflow.com/a/47947720
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47948945
score: 3
upvote count: 3
type: Question

selenium
tags question: http://stackoverflow.com/q/47861418
tags question: http://stackoverflow.com/q/47927361
tags question: http://stackoverflow.com/q/47948225
tags question: http://stackoverflow.com/q/47874994
tags question: http://stackoverflow.com/q/47920639
tags question: http://stackoverflow.com/q/47957207
tags question: http://stackoverflow.com/q/47980410
tags question: http://stackoverflow.com/q/47927599
tags question: http://stackoverflow.com/q/47891264
tags question: http://stackoverflow.com/q/47925116
tags question: http://stackoverflow.com/q/47898340
tags question: http://stackoverflow.com/q/47874307
tags question: http://stackoverflow.com/q/47894980
tags question: http://stackoverflow.com/q/47985495
tags question: http://stackoverflow.com/q/47916802
tags question: http://stackoverflow.com/q/47918306
tags question: http://stackoverflow.com/q/47956037
tags question: http://stackoverflow.com/q/47869382
tags question: http://stackoverflow.com/q/47925268
tags question: http://stackoverflow.com/q/47965879
tags question: http://stackoverflow.com/q/47863507
tags question: http://stackoverflow.com/q/48011212
tags question: http://stackoverflow.com/q/47922078
tags question: http://stackoverflow.com/q/47871513
tags question: http://stackoverflow.com/q/47999568
tags question: http://stackoverflow.com/q/47947400
tags question: http://stackoverflow.com/q/47957475
tags question: http://stackoverflow.com/q/48011403
tags question: http://stackoverflow.com/q/47906845
tags question: http://stackoverflow.com/q/47881249
tags question: http://stackoverflow.com/q/48006078
tags question: http://stackoverflow.com/q/47883572
tags question: http://stackoverflow.com/q/47957983
tags question: http://stackoverflow.com/q/47895888
tags question: http://stackoverflow.com/q/47900465
tags question: http://stackoverflow.com/q/47967774
tags question: http://stackoverflow.com/q/47879642
tags question: http://stackoverflow.com/q/48004453
tags question: http://stackoverflow.com/q/47879797
tag name: selenium
tags question: http://stackoverflow.com/q/47864772
tags question: http://stackoverflow.com/q/47872862
tags question: http://stackoverflow.com/q/48013774
tags question: http://stackoverflow.com/q/47957930
tags question: http://stackoverflow.com/q/48005687
tags question: http://stackoverflow.com/q/47901397
tags question: http://stackoverflow.com/q/48007699
tags question: http://stackoverflow.com/q/47936584
tags question: http://stackoverflow.com/q/47907620
tags question: http://stackoverflow.com/q/47972282
tags question: http://stackoverflow.com/q/47928440
tags question: http://stackoverflow.com/q/47899596
tags question: http://stackoverflow.com/q/47966982
tags question: http://stackoverflow.com/q/47923795
tags question: http://stackoverflow.com/q/47910355
tags question: http://stackoverflow.com/q/47964808
tags question: http://stackoverflow.com/q/47856783
tags question: http://stackoverflow.com/q/47888524
tags question: http://stackoverflow.com/q/47973352
tags question: http://stackoverflow.com/q/47893201
tags question: http://stackoverflow.com/q/47925340
tags question: http://stackoverflow.com/q/47931105
tags question: http://stackoverflow.com/q/47954604
tags question: http://stackoverflow.com/q/47857042
tags question: http://stackoverflow.com/q/47944401
tags question: http://stackoverflow.com/q/48014031
tags question: http://stackoverflow.com/q/47977346
tags question: http://stackoverflow.com/q/47971334
tags question: http://stackoverflow.com/q/47973741
tags question: http://stackoverflow.com/q/47880164
tags question: http://stackoverflow.com/q/47928120
tags question: http://stackoverflow.com/q/47892305
tags question: http://stackoverflow.com/q/47919975
tags question: http://stackoverflow.com/q/47965756
tags question: http://stackoverflow.com/q/47922167
tags question: http://stackoverflow.com/q/47911288
tags question: http://stackoverflow.com/q/47963284
tags question: http://stackoverflow.com/q/47896669
tags question: http://stackoverflow.com/q/47897434
tags question: http://stackoverflow.com/q/47858450

http://stackoverflow.com/comment/82996297
comment on: http://stackoverflow.com/a/47931477
score: 0
type: AnswerComment
has text: This actually just got the same result, I'm not sure why
type: Comment

http://stackoverflow.com/a/48096656
score: 1
has body: According to dlib reference: Using training images that don't look like the testing images This should be obvious, but needs to be pointed out. If there is some clear difference between your training and testing images then you have messed up. You need to show the training algorithm real images so it can learn what to do. If instead you only show it images that look obviously different from your testing images don't be surprised if, when you run the detector on the testing images, it doesn't work. As a rule of thumb, a human should not be able to tell if an image came from the training dataset or testing dataset. Here are some examples of bad datasets: A training dataset where objects always appear with some specific orientation but the testing images have a diverse set of orientations. A training dataset where objects are tightly cropped, but testing images that are uncropped. A training dataset where objects appear only on a perfectly white background with nothing else present, but testing images where objects appear in a normal environment like living rooms or in natural scenes. So, don't use that images, which is used in training. Use different images for testing.
upvote count: 2
type: Answer
downvote count: 1
answers question: http://stackoverflow.com/q/47975948
accepted answer of: http://stackoverflow.com/q/47975948
type: AcceptedAnswer

http://stackoverflow.com/a/52283085
upvote count: 270
has comment: http://stackoverflow.com/comment/113210149
has comment: http://stackoverflow.com/comment/115725453
has comment: http://stackoverflow.com/comment/123186297
type: Answer
has comment: http://stackoverflow.com/comment/113959178
has comment: http://stackoverflow.com/comment/137262423
has body: Overview The question has been addressed. However, this answer adds some practical examples to aid in the basic understanding of dataclasses. What exactly are python data classes and when is it best to use them? code generators: generate boilerplate code; you can choose to implement special methods in a regular class or have a dataclass implement them automatically. data containers: structures that hold data (e.g. tuples and dicts), often with dotted, attribute access such as classes, namedtuple and others. "mutable namedtuples with default[s]" Here is what the latter phrase means: mutable: by default, dataclass attributes can be reassigned. You can optionally make them immutable (see Examples below). namedtuple: you have dotted, attribute access like a namedtuple or a regular class. default: you can assign default values to attributes. Compared to common classes, you primarily save on typing boilerplate code. Features This is an overview of dataclass features (TL;DR? See the Summary Table in the next section). What you get Here are features you get by default from dataclasses. Attributes + Representation + Comparison import dataclasses @dataclasses.dataclass #@dataclasses.dataclass() # alternative class Color: r : int = 0 g : int = 0 b : int = 0 These defaults are provided by automatically setting the following keywords to True: @dataclasses.dataclass(init=True, repr=True, eq=True) What you can turn on Additional features are available if the appropriate keywords are set to True. Order @dataclasses.dataclass(order=True) class Color: r : int = 0 g : int = 0 b : int = 0 The ordering methods are now implemented (overloading operators: < > <= >=), similarly to functools.total_ordering with stronger equality tests. Hashable, Mutable @dataclasses.dataclass(unsafe_hash=True) # override base `__hash__` class Color: ... Although the object is potentially mutable (possibly undesired), a hash is implemented. Hashable, Immutable @dataclasses.dataclass(frozen=True) # `eq=True` …
has comment: http://stackoverflow.com/comment/115660683
score: 270
downvote count: 0
answers question: http://stackoverflow.com/q/47955263

http://stackoverflow.com/comment/82723424
score: 0
type: AnswerComment
has text: OK, so for a CNN autoencoder, the interpretation of the outputs is different, the output is pixel intensity, not probability. Not a problem, just means you have a different interpretation for the loss function.
type: Comment
comment on: http://stackoverflow.com/a/47877223

http://stackoverflow.com/comment/103156027
comment on: http://stackoverflow.com/a/48154139
type: Comment
score: 1
has text: @AshBerlin-Taylor This seems to be an issue still with 1.10.2.
type: AnswerComment

http://stackoverflow.com/a/48004080
answers question: http://stackoverflow.com/q/48003943
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/82977705
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/82977753
has comment: http://stackoverflow.com/comment/82977237
has body: This seems to work: class Negative: pass class PositiveMeta(type): def __neg__(self): return Negative class Positive(metaclass=PositiveMeta): pass print(-Positive is Negative) # prints True
has comment: http://stackoverflow.com/comment/82977669

http://stackoverflow.com/a/47946180
has comment: http://stackoverflow.com/comment/82875808
accepted answer of: http://stackoverflow.com/q/47938867
has comment: http://stackoverflow.com/comment/82868988
has body: Two things, firstly requests form-encodeds the POST data so you don't need to secondly you need to perform a GET before the POST to set up cookies etc. import requests from bs4 import BeautifulSoup s = requests.Session() url = 'https://services2.hdb.gov.sg/webapp/BB33RTIS/BB33SSearchWidget' data = {'USER_PROFILE': '2', 'FLAT_TYPE': '03', 'NME_NEWTOWN': 'AMK Ang Mo Kio', 'NME_STREET': '', 'NUM_BLK_FROM': '', 'NUM_BLK_TO': '', 'dteRange': '12', 'DTE_APPROVAL_FROM': 'Dec 2015', 'DTE_APPROVAL_TO': 'Dec 2017', 'AMT_RESALE_PRICE_FROM': '', 'AMT_RESALE_PRICE_TO': '', 'Process': 'continue', 'null': 'null' } userAgent = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0', 'Referer': 'https://services2.hdb.gov.sg/webapp/BB33RTIS/BB33PReslTrans.jsp'} s.get(url, headers=userAgent) page = s.post(url, data=data, headers=userAgent) # print(page.text) s.close() # just to check soup = BeautifulSoup(page.text, 'lxml') for tr in soup.find_all('tr', {'height': '30'}): print (tr.text) Outputs: 220 Ang Mo Kio Ave 1 10 to 12 67.00New Generation 1977 58 years $280,000.00 Dec 2017 225 Ang Mo Kio Ave 1 07 to 09 82.00New Generation 1978 59 years $350,000.00 Dec 2017 ...
answers question: http://stackoverflow.com/q/47938867
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/82786160
score: 2
has text: you have wrong parents in widgets - you have to put widgets in `self.window`. Or `Frame` has to use `self.window` as parent and use `pack()` to show frame in window.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47909342

http://stackoverflow.com/comment/82886892
type: QuestionComment
has text: aint that Playlist has many videos? it could be an M2M field for videos
comment on: http://stackoverflow.com/q/47958607
score: 0
type: Comment

http://stackoverflow.com/q/47911093
accepted answer: http://stackoverflow.com/a/47911383
score: 0
tagged with: deep-learning
answer count: 1
tagged with: keras
has body: I have an array of 35000 images of 256x256 grayscale images print(len(data)) &gt;&gt;&gt;35000 print(data[0].shape) &gt;&gt;&gt;(256, 256) My first layer is model.add(Conv2D(64, (3, 3), input_shape=(35000,), activation='relu')) and it gives me the error &gt;&gt;&gt;ValueError: Input 0 is incompatible with layer conv2d_1: expected ndim=4, found ndim=2 what I'm doing wrong? what is the proper way to define the input shape?
has comment: http://stackoverflow.com/comment/82790053
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47911383
has comment: http://stackoverflow.com/comment/82790243
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/82790504
has title: Proper way to define inputshape on the first layer on keras

http://stackoverflow.com/q/47919249
has title: Dynamically load classes and get a reference
accepted answer: http://stackoverflow.com/a/47919502
answer count: 2
downvote count: 0
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/47919502
type: AnsweredQuestion
has body: Python is doing my nut. I'd not imagine it can be so hard to load a few modules and instantiate the classes within dynamically. I've read several other questions on here but none of the offered solutions seem to work for me. My folder structure ./coin.py ./exchanges/ /bittrex.py (contains Bittrex class) /kraken.py (contains Kraken class) ... My goal To, in as little code and without any hacky means, import each of these modules dynamically and get a reference to the classes within so that I can instantiate them and get their attributes. My current code import glob, exchanges, dirfiles, isfile, inspect dirfiles = glob.glob(dirname(__file__) + "/exchanges/*.py") __all__ = [ basename(f)[:-3] for f in dirfiles if isfile(f) and not f.endswith('__init__.py')] class Indicator(object): def __init__(self): for exchange in __all__: class_name = exchange.capitalize() class_ = getattr(exchange, class_name) self.EXCHANGES.append({ 'code': exchange, 'name': class_name, 'instance': class_(self) }) However the above code and the many different permutations I've tried always end up with it interpreting my intended class references as strings.
score: 1
has answer: http://stackoverflow.com/a/47919384
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/82806076
possible better answer: http://stackoverflow.com/a/47919384

http://stackoverflow.com/q/47960157
type: Question
score: 5
has answer: http://stackoverflow.com/a/49536610
answer count: 6
has answer: http://stackoverflow.com/a/47960732
has answer: http://stackoverflow.com/a/48090498
has body: I am facing an issue. Kindly help me Here's the code: import pandas import quandl import time df = quandl.get('FINRA/FNSQ_GOOGL') print(df.head()) and the error which i am facing is: Traceback (most recent call last): File "C:\Users\Desktop\My Folder\test.py", line 5, in &lt;module&gt; df = quandl.get('FINRA/FNSQ_GOOGL') File "C:\Python27\lib\site-packages\quandl\get.py", line 48, in get data = Dataset(dataset_args['code']).data(params=kwargs, handle_column_not_found=True) File "C:\Python27\lib\site-packages\quandl\model\dataset.py", line 47, in data return Data.all(**updated_options) File "C:\Python27\lib\site-packages\quandl\operations\list.py", line 14, in all r = Connection.request('get', path, **options) File "C:\Python27\lib\site-packages\quandl\connection.py", line 36, in request return cls.execute_request(http_verb, abs_url, **options) File "C:\Python27\lib\site-packages\quandl\connection.py", line 50, in execute_request raise e SSLError: HTTPSConnectionPool(host='www.quandl.com', port=443): Max retries exceeded with url: /api/v3/datasets/FINRA/FNSQ_GOOGL/data?order=asc (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",),)) import pandas import quandl import time df='' while df=='': try: df = quandl.get('FINRA/FNSQ_GOOGL') except: time.sleep(5) print("try") continue print(df.head()) It would be grateful if somebody help me solve this issue. Thanks in advance!!
favorite count: 0
upvote count: 5
type: UnansweredQuestion
tagged with: python
tagged with: python-requests
has title: SSLError: HTTPSConnectionPool(host='www.quandl.com', port=443): Max retries exceeded
has answer: http://stackoverflow.com/a/54722664
has answer: http://stackoverflow.com/a/77469006
downvote count: 0
has answer: http://stackoverflow.com/a/55024152

http://stackoverflow.com/a/47904930
type: Answer
has comment: http://stackoverflow.com/comment/82780632
has comment: http://stackoverflow.com/comment/82781204
upvote count: 3
has comment: http://stackoverflow.com/comment/82809733
has comment: http://stackoverflow.com/comment/82780790
score: 3
has comment: http://stackoverflow.com/comment/82787044
has body: Your first example is correct. Sadly you have a small typo in your first line of code: hr = dict(name="Some Name, ...), The line ends with a comma ,. Now hr is becomes a tuple with a single element: the dict. Without the comma this works: {{ team.0.name }} {{ team.1.name }} With your updated answer you need to change context.team to team in your template: {% for person in team %} The context dictionary is 'unpacked' in the template.
answers question: http://stackoverflow.com/q/47904732
downvote count: 0
has comment: http://stackoverflow.com/comment/82818674

http://stackoverflow.com/comment/82883881
has text: You don't need that row array. You can can loop over the remaining lines of the file directly
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47957031

http://stackoverflow.com/q/47981839
downvote count: 1
type: Question
score: 0
has comment: http://stackoverflow.com/comment/82932113
has title: Why do I keep getting a 'string indices must be integers' error?
has comment: http://stackoverflow.com/comment/82932133
answer count: 1
has answer: http://stackoverflow.com/a/47982340
has body: I'm new to Python and I was trying to expand on a coding exercise from Codecademy. I want the program to take user input for the average of the selected student, but I keep getting a 'string indices must be integers' error. lloyd = { "name": "Lloyd", "homework": [90.0, 97.0, 75.0, 92.0], "quizzes": [88.0, 40.0, 94.0], "tests": [75.0, 90.0] } alice = { "name": "Alice", "homework": [100.0, 92.0, 98.0, 100.0], "quizzes": [82.0, 83.0, 91.0], "tests": [89.0, 97.0] } tyler = { "name": "Tyler", "homework": [0.0, 87.0, 75.0, 22.0], "quizzes": [0.0, 75.0, 78.0], "tests": [100.0, 100.0] } def average(numbers): total = sum(numbers) total = float(total)/len(numbers) return total #List of Students to choose from for get_average input() x = '1. Alice' y = '2. Tyler' z = '3. Lloyd' #get_average function def get_average(alice): homework = average(alice['homework']) quizzes = average(alice['quizzes']) tests = average(alice['tests']) student = input('Please type the number of the student who\'s weighted average you would like to see:' + '\n' + x + '\n' + y + '\n' + z) if student == '1': print( 0.1 * average(alice['homework']) + 0.3 * average(alice['quizzes']) + 0.6 * average(alice['tests']) ) get_average('student') I was going to use the code for Alice's average to create a function for Lloyd's and Tyler's average, but I just can't figure the first part out. Can someone help me? Thanks.
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82932351
upvote count: 1

http://stackoverflow.com/q/47879813
has comment: http://stackoverflow.com/comment/82726001
tagged with: dataframe
type: Question
accepted answer: http://stackoverflow.com/a/47879855
answer count: 1
duplicate of: http://stackoverflow.com/q/39862053
score: 0
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/47879855
linked to: http://stackoverflow.com/q/39862053
tagged with: python
has body: My code runs through XML files and parses certain data. I'm using pandas to organize, dataframe, and write to CSV which looks like: data = {"Name":inv_names, "Publication Date":date_pub, "Document Number":doc_num, "Patcit":name_citation, "Npatcit":data2, "Country":data3, "MainClass":data13} df = pd.concat([df, pd.DataFrame(data)]) with open("./output.csv", "a", encoding = 'utf-8') as f: df.to_csv(f, index = False) This prints to the CSV file like: Country Document Number MainClass Name Npatcit Patcit Publication Date All I really want to do is re-order this data like: Name Publication Date Document Number ..... (just like the order given by data above) Might be a simple case but I've tried things like df.sort_values() by different types but nothing seems to work.
type: AnsweredQuestion
has title: Ordering pandas dataframe columns by choice in Python

http://stackoverflow.com/comment/82844434
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47929498
type: AnswerComment
has text: I am using it like following :- credentials = ServicePrincipalCredentials(client_id=clientid,secret=clientsecret,tenant=tenantid) client = ResourceManagementClient(credentials,subscription_id) delete_async_operation = client.resourceoperations.delete_by_id(resource_id,api) delete_async_operation.wait() But getting error:- 'ResourceManagementClient' object has no attribute 'resourceoperations'

http://stackoverflow.com/comment/106069518
comment on: http://stackoverflow.com/a/47878515
has text: @Kristada673 There are other ways to encode categorical variables like BinaryEncoding. Check out the python package categorical encoders https://github.com/scikit-learn-contrib/categorical-encoding
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/82810425
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47921450
type: Comment
has text: Just wanted to add, that apply in general loops through the data and tends to be slow. Whenever possible, try to use vectorised solution, like the one provided by @jezrael,

http://stackoverflow.com/a/47948032
has body: See this: What is the use of "assert" in Python? assert is for asserting a condition, means verify that this condition has been met else trigger an action. For your use case, you want to catch an exception, so this is something you want. #!/usr/bin/env python import sys def get_value(x): lookup = {'one': 1} return lookup[x] try: get_value('two') except: # catch *all* exceptions e = sys.exc_info() print e This will catch the exception and print it. In this particular case it will print something like: (<type 'exceptions.KeyError'>, KeyError('two',), <traceback object at 0x102c71c20>)
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47947676
score: 1

http://stackoverflow.com/comment/82975032
type: AnswerComment
has text: I see. You can print individually each step as @sancho bellow suggested to avoid such problems in the future.
type: Comment
comment on: http://stackoverflow.com/a/48003404
score: 0

http://stackoverflow.com/comment/82829790
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47930411
has text: What does `console.log(data)` give you?? Try `data[0].id`
score: 0

http://stackoverflow.com/a/47905508
score: 1
upvote count: 1
has body: For starters, the first example doesn't make much sense. __init__ accepts arguments but doesn't do anything with them, and the values for the instance attributes are still hard-coded. A more sensible example would be: class Bubble: def __init__(self, pos, vel, color): self.pos = pos self.vel = vel self.color = color Now it makes sense to compare it to the second example you provided. In the example above Bubble will accept 3 arguments and assign them to the instance attributes. Nothing is hard-coded and the calling code has control over the created instance's attributes (Bubble(position_1, [1, 2], blue) or Bubble(position_2, [3, 3], yellow) etc). In the second example you provided the calling code has zero control over the values used to initialize the instance attributes since they are hard-coded in __init__'s code, and the way to create a Bubble object will be Bubble(). A common approach is to accommodate both use cases by using arguments with default values (just be careful not to use a mutable default argument): class Bubble: def __init__(self, pos=None, vel=None, color=None): if pos is None: self.pos = list(FIRING_POSITION) else: self.pos = pos if vel is None: self.vel = [0, 0] else: self.vel = vel if color is None: self.color = random.choice(COLOR_LIST) else: self.color = color This could be written more concisely as class Bubble: def __init__(self, pos=None, vel=None, color=None): self.pos = pos or list(FIRING_POSITION) self.vel = vel or [0, 0] self.color = color or random.choice(COLOR_LIST) This way offers granular control, and Bubble can be called with any combination of arguments (0, 1 or any combination of 2 and 3 arguments).
answers question: http://stackoverflow.com/q/47905426
has comment: http://stackoverflow.com/comment/82779055
type: Answer
downvote count: 0

http://stackoverflow.com/a/47978505
has body: I am not sure how sensible an idea this is, but you can achieve it using a "filesystem watcher" such as fswatch (the macOS equivalent of Linux's inotifywait). So, you can use homebrew to install fswatch like this: brew install fswatch Then, say you wanted to monitor all filesystem events under your HOME directory that pertain to Python files and involve file creation, you could run: fswatch -0 -E --event Created -e ".*" -i ".py$" $HOME | xargs -0 -n1 chmod +x You won't see anything, but as soon as you create a file ending in .py, it will run chmod +x on that file to make it executable.
type: AcceptedAnswer
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47973401
answers question: http://stackoverflow.com/q/47973401

http://stackoverflow.com/comment/82855446
type: QuestionComment
type: Comment
has text: @DanGittik looks like that is the issue. However, I'm a bit confused. I thought by workon the right venv python is using the right pip, isn't it?
score: 0
comment on: http://stackoverflow.com/q/47942901

http://stackoverflow.com/comment/82962218
type: QuestionComment
has text: well since you have not defined "best" this is definately a true statement from where we are sitting ...
comment on: http://stackoverflow.com/q/47996986
score: 0
type: Comment

http://stackoverflow.com/comment/82835298
score: 2
comment on: http://stackoverflow.com/q/47933048
type: Comment
type: QuestionComment
has text: Why not use [`os.walk`](https://docs.python.org/3/library/os.html#os.walk)?

http://stackoverflow.com/comment/82863698
comment on: http://stackoverflow.com/q/47936097
score: 0
type: Comment
type: QuestionComment
has text: @Partfait I added a screenshot of the table datatypes. I used longtext to specify the mouse_mgi_id column datatype.

http://stackoverflow.com/a/47883923
answers question: http://stackoverflow.com/q/47882315
downvote count: 0
upvote count: 2
has body: The interval of the animation is already set to 0, meaning in theory an infinite number of frames per second. In reality it means that the animation is drawn as fast as your computer allows it to. The limiting factor in the animation is that for each frame everything in the canvas is redrawn. This is a lot of overhead, since axes, ticks, labels etc. all stay the same during animation. A standard technique to overcome this limitation is blitting. This would only repaint the animated artist (the red ball) in each frame. def get_step(n,x,y,point): point.set_data(x[n],y[n]) return point, mymovie = animation.FuncAnimation(fig,get_step,frames= time, blit=True,\ fargs=(x[0,:],y[0,:],my_point), interval = 1) If this is not fast enough, you might consider skipping steps of your animation, e.g. showing only every second step, frames = time[::2]
type: Answer
score: 2

http://stackoverflow.com/q/47871806
score: -2
has comment: http://stackoverflow.com/comment/82710705
has comment: http://stackoverflow.com/comment/82709452
has comment: http://stackoverflow.com/comment/82710815
linked to: http://stackoverflow.com/q/3106689
has comment: http://stackoverflow.com/comment/82710341
downvote count: 2
accepted answer: http://stackoverflow.com/a/47872098
has comment: http://stackoverflow.com/comment/82709002
has answer: http://stackoverflow.com/a/47871866
favorite count: 0
has answer: http://stackoverflow.com/a/47871834
has answer: http://stackoverflow.com/a/47872098
answer count: 5
possible better answer: http://stackoverflow.com/a/47871866
tagged with: python
has comment: http://stackoverflow.com/comment/82709064
has answer: http://stackoverflow.com/a/47871931
type: AnsweredQuestion
upvote count: 0
has body: Here's my code : hp1 = 100 health1 = 'you have', hp1 hp1 = hp1 - 50 health1 print hp1 print health1 This is what it prints : 50 ('you have', 100) Why doesn't the hp1 change inside the health?
has answer: http://stackoverflow.com/a/47871956
type: Question
has title: How do I change a variable inside a variable?
has comment: http://stackoverflow.com/comment/82709582
has comment: http://stackoverflow.com/comment/82710997

http://stackoverflow.com/q/47968578
has comment: http://stackoverflow.com/comment/82909490
tagged with: python
tagged with: utf-8
accepted answer: http://stackoverflow.com/a/47972295
has answer: http://stackoverflow.com/a/47969478
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/2276200
has title: Python3 utf-8 decode issue
type: Question
score: 4
has answer: http://stackoverflow.com/a/47972295
upvote count: 4
answer count: 2
has body: The following code runs fine with Python3 on my Windows machine and prints the character 'é': data = b"\xc3\xa9" print(data.decode('utf-8')) However, running the same on an Ubuntu based docker container results in : UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 0: ordinal not in range(128) Is there anything that I have to install to enable utf-8 decoding ?
has comment: http://stackoverflow.com/comment/82908204
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: linux
linked to: http://stackoverflow.com/q/728891
tagged with: windows
has comment: http://stackoverflow.com/comment/82908286
possible better answer: http://stackoverflow.com/a/47969478

http://stackoverflow.com/q/47936526
tagged with: database
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82842435
has answer: http://stackoverflow.com/a/55120277
has title: Error Message: "No module named 'django.core.urlresolvers".Even though I've replaced the module
has comment: http://stackoverflow.com/comment/82842472
has comment: http://stackoverflow.com/comment/82842385
tagged with: python
has comment: http://stackoverflow.com/comment/85457412
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/82842489
type: Question
has body: I was trying to create tables in my database by executing the command on the django shell in the Windows CLI migrate.py syncdb It returned with the error message django.core.exceptions.ImproperlyConfigured: Error importing debug panel debug_toolbar.panels.request: "No module named 'django.core.urlresolvers'" After reading up to resolve my problem I discovered it is because the module django.core.urlresolvers is not available in versions of python higher than 1.9 and django.urls is the more suitable module. I replaced the former module in my code with the latter from django.urls import reverse and somehow still manage to get the same error. How do I resolve this? Thanks in advance.
has comment: http://stackoverflow.com/comment/82842581
has comment: http://stackoverflow.com/comment/82842430

http://stackoverflow.com/a/48029862
upvote count: 1
has comment: http://stackoverflow.com/comment/83033032
has comment: http://stackoverflow.com/comment/83123427
type: Answer
has body: This was only slightly faster than the list comprehension for me on my machine, but if you want unicode support this might be the fastest way of doing it. You'll need to apt-get install libunistring-dev or whatever is appropriate for your OS / package manager. In some C file, say, _lower.c, have #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;unistr.h&gt; #include &lt;unicase.h&gt; void _c_tolower(uint8_t **s, uint32_t total_len) { size_t lower_len, s_len; uint8_t *s_ptr = *s, *lowered; while(s_ptr - *s &lt; total_len) { s_len = u8_strlen(s_ptr); if (s_len == 0) { s_ptr += 1; continue; } lowered = u8_tolower(s_ptr, s_len, NULL, NULL, NULL, &amp;lower_len); memcpy(s_ptr, lowered, lower_len); free(lowered); s_ptr += s_len; } } Then, in lower.pxd you do cdef extern from "_lower.c": cdef void _c_tolower(unsigned char **s, unsigned int total_len) And finally, in lower.pyx: cpdef void lower(ndarray arr): cdef unsigned char * _arr _arr = &lt;unsigned char *&gt; arr.data _c_tolower(&amp;_arr, arr.shape[0] * arr.itemsize) On my laptop, I got 46ms for the list comprehension you had above and 37ms for this method (and 0.8ms for your lower_fast), so it's probably not worth it, but I figured I'd type it out in case you wanted an example of how to hook such a thing into Cython. There are a few points of improvement that I don't know will make much of a difference: arr.data is something like a square matrix I guess? (I don't know, I don't use numpy for anything), and pads the ends of the shorter strings with \x00s. I was too lazy to figure out how to get u8_tolower to look past the 0s, so I just manually fast-forward past them (that's what the if (s_len == 0) clause is doing). I suspect that one call to u8_tolower would be significantly faster than doing it thousands of times. I'm doing a lot of freeing/memcpying. You can probably avoid that if you're clever. I think it's the case that every lowercase unicode character is at most as wide as its uppercase variant, …
downvote count: 0
has comment: http://stackoverflow.com/comment/83110519
score: 1
answers question: http://stackoverflow.com/q/47998664
has comment: http://stackoverflow.com/comment/83033075
has comment: http://stackoverflow.com/comment/83033051

http://stackoverflow.com/q/47994573
has answer: http://stackoverflow.com/a/47996860
tagged with: text-files
accepted answer: http://stackoverflow.com/a/47996860
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82959729
has answer: http://stackoverflow.com/a/47998230
type: Question
has comment: http://stackoverflow.com/comment/82957580
score: 0
has title: remove BeautifulSoup tags from Text file
answer count: 2
possible better answer: http://stackoverflow.com/a/47998230
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/82964401
has comment: http://stackoverflow.com/comment/82957203
has comment: http://stackoverflow.com/comment/82964395
tagged with: python
has body: I have bs4 installed. How do you remove HTML tags from a textfile? In a nutshell, I have a script that writes ESRI metadata items to a textfile from that metadata's HTML page, and for a couple of these items the HTML format code is also written for some reason. How can I use BeautifulSoup to remove this code? It looks sloppy. The Description item of this attachment has the HTML: Textfile

http://stackoverflow.com/a/47931019
accepted answer of: http://stackoverflow.com/q/47918524
type: AcceptedAnswer
has body: Using python3 worked. Another thing to mention, it uses the core python in the system and does not recognise any other version installed.
answers question: http://stackoverflow.com/q/47918524
type: Answer
score: 0

http://stackoverflow.com/comment/82758877
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47895813
has text: Thanks for Posting the solution Max. I am getting the following error. Are you using any other packages other than pandas, nupy,os and glob ??? -> 3081 return object.__getattribute__(self, name) 3082 3083 def __setattr__(self, name, value): AttributeError: 'Series' object has no attribute 'assign'
score: 0

http://stackoverflow.com/a/50527075
type: Answer
score: 6
upvote count: 7
downvote count: 1
answers question: http://stackoverflow.com/q/47891332
has body: This should do it: sudo pip install path.py

jupyter
tags question: http://stackoverflow.com/q/48012811
tags question: http://stackoverflow.com/q/47978149
type: Tag
tags question: http://stackoverflow.com/q/47864235
tags question: http://stackoverflow.com/q/47861911
tags question: http://stackoverflow.com/q/47994333
tags question: http://stackoverflow.com/q/47954097
tags question: http://stackoverflow.com/q/47870022
tags question: http://stackoverflow.com/q/48002785
tags question: http://stackoverflow.com/q/48012813
tag name: jupyter
tags question: http://stackoverflow.com/q/47889919
tags question: http://stackoverflow.com/q/47878009
tags question: http://stackoverflow.com/q/47975904
tags question: http://stackoverflow.com/q/47969937
tags question: http://stackoverflow.com/q/47861490
tags question: http://stackoverflow.com/q/47889693
tags question: http://stackoverflow.com/q/47929811

http://stackoverflow.com/a/47903096
has body: The problem in your approach is that the shape of each element varies and hence you cannot have a fixed shape. However you can define each element as type object and achieve what you are trying to do. import numpy as np tf = np.empty((500, 4, 1), dtype= object) will produce array([[[None], [None], [None], [None]], [[None], [None], [None], [None]], [[None], [None], [None], [None]], ..., [[None], [None], [None], [None]], [[None], [None], [None], [None]], [[None], [None], [None], [None]]], dtype=object) Now add your constant initial element as a list to each of these array elements. You might be tempted to use fill() here, but that assigns a single object to each array element and modifying individual array elements will change the entire array. To initialize, you cannot avoid iterating through the entire array. for i,v in enumerate(tf): for j,w in enumerate(v): tf[i][j][0] = [[500.0,1.0]] will produce array([[[list([[500.0, 1.0]])], [list([[500.0, 1.0]])], [list([[500.0, 1.0]])], [list([[500.0, 1.0]])]], [[list([[500.0, 1.0]])], [list([[500.0, 1.0]])], [list([[500.0, 1.0]])], [list([[500.0, 1.0]])]], [[list([[500.0, 1.0]])], [list([[500.0, 1.0]])], [list([[500.0, 1.0]])], [list([[500.0, 1.0]])]], ..., [[list([[500.0, 1.0]])], [list([[500.0, 1.0]])], [list([[500.0, 1.0]])], [list([[500.0, 1.0]])]], [[list([[500.0, 1.0]])], [list([[500.0, 1.0]])], [list([[500.0, 1.0]])], [list([[500.0, 1.0]])]], [[list([[500.0, 1.0]])], [list([[500.0, 1.0]])], [list([[500.0, 1.0]])], [list([[500.0, 1.0]])]]], dtype=object) Now you can access each element separately. Use append or extend as you prefer. tf[0][0][0].append([100,0.33]) will give array([[[list([[500.0, 1.0], [100, 0.33]])], [list([[500.0, 1.0]])], [list([[500.0, 1.0]])], [list([[500.0, 1.0]])]], [[list([[500.0, 1.0]])], [list([[500.0, 1.0]])], [list([[500.0, 1.0]])], [list([[500.0, 1.0]])]], [[list([[500.0, 1.0]])], [list([[500.0, 1.0]])], [list([[500.0, 1.0]])], [list([[500.0, 1.0]])]], ..., [[list([[500.0, 1.0]])], [list([…
score: 2
has comment: http://stackoverflow.com/comment/82772952
has comment: http://stackoverflow.com/comment/82774859
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82773215
has comment: http://stackoverflow.com/comment/82775838
accepted answer of: http://stackoverflow.com/q/47902323
downvote count: 0
answers question: http://stackoverflow.com/q/47902323
upvote count: 2
has comment: http://stackoverflow.com/comment/82777989
type: Answer

http://stackoverflow.com/comment/82690984
type: Comment
has text: Add only NormalTextRun class to forloop for data in elem.find_all('span', class_="NormalTextRun"):
type: QuestionComment
comment on: http://stackoverflow.com/q/47863031
score: 1

http://stackoverflow.com/a/47896002
type: Answer
answers question: http://stackoverflow.com/q/47877848
score: 0
has body: I think I've found the best and simplest way: g = sns.FacetGrid(df, row="Car", hue="Combustible", size=12) g = g.map(plt.plot, "Date", "Cost")

http://stackoverflow.com/comment/83016381
type: QuestionComment
comment on: http://stackoverflow.com/q/48007009
has text: Ok, I'll give it a try now.
score: 0
type: Comment

python-module
tags question: http://stackoverflow.com/q/47858469
type: Tag
tag name: python-module
tags question: http://stackoverflow.com/q/47891419
tags question: http://stackoverflow.com/q/47944214
tags question: http://stackoverflow.com/q/47914388
tags question: http://stackoverflow.com/q/47890647
tags question: http://stackoverflow.com/q/47869521

http://stackoverflow.com/comment/126535405
has text: Thank you so much, I was searching for hours to get this to work and you sorted it... `cache = Cache() cache.memoize = mock.patch('flask_caching.Cache.memoize', mocked_memoize).start()` then I can just pass the cache object into the class which uses the decorator...
score: 1
comment on: http://stackoverflow.com/a/47926195
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/82996937
has text: @JohnLexus, ...also, if you're using the word "process" to refer to a chunk of code you want to call, rather than to refer to an OS process (which is the pertinent meaning in the context of discussing parallelism/threading), then the terminology is extremely confusing.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48013540
score: 0

http://stackoverflow.com/q/48006574
has answer: http://stackoverflow.com/a/48007433
type: Question
score: 3
has title: Using Keras with HDF5Matrix with labels only
tagged with: deep-learning
accepted answer: http://stackoverflow.com/a/48007433
downvote count: 0
answer count: 1
tagged with: keras
favorite count: 0
tagged with: h5py
tagged with: python
has body: I believe that this is my first question in Stack Overflow, so I apologize in advance if I don't follow all guidelines. I recently started to use Keras for deep learning, and since I work with HDF5 files using h5py to manage large datasets, I searched for a way to train models using keras on very large HDF5 files. I found out that the most common way would be to use HDF5Matrix found in keras.utils.io_utils. I modified one of Keras examples (mnist.cnn) as following: '''Trains a simple convnet on the MNIST dataset. Gets to 99.25% test accuracy after 12 epochs (there is still a lot of margin for parameter tuning). 16 seconds per epoch on a GRID K520 GPU. ''' from __future__ import print_function import keras from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D from keras import backend as K # My Imports from os.path import exists import h5py from keras.utils.io_utils import HDF5Matrix batch_size = 128 num_classes = 10 epochs = 12 # input image dimensions img_rows, img_cols = 28, 28 # the data, shuffled and split between train and test sets (x_train, y_train), (x_test, y_test) = mnist.load_data() if K.image_data_format() == 'channels_first': x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols) input_shape = (1, img_rows, img_cols) else: x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1) input_shape = (img_rows, img_cols, 1) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 print('x_train shape:', x_train.shape) print(x_train.shape[0], 'train samples') print(x_test.shape[0], 'test samples') # convert class vectors to binary class matrices y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) #-----…
type: AnsweredQuestion
upvote count: 3
tagged with: hdf5

http://stackoverflow.com/comment/82965208
score: 0
type: Comment
type: QuestionComment
has text: How do you install `jupyterhub`? If I install it via `pip install jupyterhub`, `pkg_resources.resource_filename('jupyterhub', 'jupyter/hub/templates/error.html')` returns a valid path as expected. Even if I cheat and build a source distribution of `jupyterhub` myself, and pass it as a dependency to the setup script, the resource is still found.
comment on: http://stackoverflow.com/q/47987611

http://stackoverflow.com/comment/82941687
has text: @BorrajaX Codes may not be necessarily? Just two process will add data to table and I try to ensure the data insert into table not be repeating? The logci now I know is, check exists or not,and insert or not.But may two process check and add at the same time?`update_or_create` is the check in django not in database.I try to explain it ,if something I explain bad,tell me please.
comment on: http://stackoverflow.com/q/47985369
score: 0
type: Comment
type: QuestionComment

javascript
tags question: http://stackoverflow.com/q/47983667
tags question: http://stackoverflow.com/q/47936150
tags question: http://stackoverflow.com/q/47985855
tags question: http://stackoverflow.com/q/47955736
tags question: http://stackoverflow.com/q/47857270
tags question: http://stackoverflow.com/q/47998286
tags question: http://stackoverflow.com/q/47898427
tags question: http://stackoverflow.com/q/47880389
tags question: http://stackoverflow.com/q/47867630
tags question: http://stackoverflow.com/q/47858877
tags question: http://stackoverflow.com/q/48011682
tags question: http://stackoverflow.com/q/47954185
tags question: http://stackoverflow.com/q/48011101
tags question: http://stackoverflow.com/q/47859999
tags question: http://stackoverflow.com/q/47955849
tags question: http://stackoverflow.com/q/48002644
tags question: http://stackoverflow.com/q/47881338
tag name: javascript
tags question: http://stackoverflow.com/q/47869088
tags question: http://stackoverflow.com/q/47997812
tags question: http://stackoverflow.com/q/47920020
tags question: http://stackoverflow.com/q/47945268
tags question: http://stackoverflow.com/q/47995681
tags question: http://stackoverflow.com/q/47907880
tags question: http://stackoverflow.com/q/48004264
tags question: http://stackoverflow.com/q/47983317
tags question: http://stackoverflow.com/q/48007982
type: Tag
tags question: http://stackoverflow.com/q/47964694
tags question: http://stackoverflow.com/q/47993617
tags question: http://stackoverflow.com/q/47931219
tags question: http://stackoverflow.com/q/47999442
tags question: http://stackoverflow.com/q/47956352
tags question: http://stackoverflow.com/q/47876617
tags question: http://stackoverflow.com/q/47970686
tags question: http://stackoverflow.com/q/47866503
tags question: http://stackoverflow.com/q/47993391
tags question: http://stackoverflow.com/q/47933748
tags question: http://stackoverflow.com/q/47870231
tags question: http://stackoverflow.com/q/47875815
tags question: http://stackoverflow.com/q/47888639
tags question: http://stackoverflow.com/q/47882829
tags question: http://stackoverflow.com/q/47858650
tags question: http://stackoverflow.com/q/47899093
tags question: http://stackoverflow.com/q/47984489
tags question: http://stackoverflow.com/q/47941250
tags question: http://stackoverflow.com/q/48012370
tags question: http://stackoverflow.com/q/47860912
tags question: http://stackoverflow.com/q/47921945
tags question: http://stackoverflow.com/q/47863507
tags question: http://stackoverflow.com/q/47893249
tags question: http://stackoverflow.com/q/47951097
tags question: http://stackoverflow.com/q/47969850
tags question: http://stackoverflow.com/q/47934319

http://stackoverflow.com/comment/82882338
comment on: http://stackoverflow.com/q/47956327
has text: @danihp is there any django documentation which suggests NOT to use static reference from server side? Or it is meant to be used ONLY form the client side? I'd appreciate any reference because I don't recall reading any. Thank you.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82799636
comment on: http://stackoverflow.com/q/47915713
type: QuestionComment
score: 1
has text: Thanks mypetlion that was the problem m8
type: Comment

http://stackoverflow.com/q/47951017
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82872756
type: Question
has comment: http://stackoverflow.com/comment/82879859
score: -2
has answer: http://stackoverflow.com/a/47955158
has title: How to print something from Entry in another window in Python 3?
downvote count: 4
has comment: http://stackoverflow.com/comment/82879556
has comment: http://stackoverflow.com/comment/82879552
answer count: 1
tagged with: tkinter-entry
has comment: http://stackoverflow.com/comment/82872793
favorite count: 0
has comment: http://stackoverflow.com/comment/82873215
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82873361
tagged with: tkinter
upvote count: 2
accepted answer: http://stackoverflow.com/a/47955158
tagged with: python
has body: Why it does not print the string values I have entered into the textbox in the newwindow? from tkinter import * def newwindow(): newwindow = Tk() newwindow.title('Sign Up') newwindow.geometry('200x400') def sign_done(): david = a.get() javed = b.get() lbee = Label(newwindow, text=david).pack() baeee = Label(newwindow, text=javed).pack() a = StringVar() b = StringVar() user = Entry(newwindow, textvariable=a).pack() pword = Entry(newwindow, textvariable=b).pack() done = Button(newwindow, text='done now', command=sign_done).pack() newwindow.mainloop() root = Tk() root.title('Gulmeena') root.geometry("500x200") button = Button(root, text='Go', command=newwindow).pack() root.mainloop() Please do not use Classes

http://stackoverflow.com/a/47906149
downvote count: 0
type: Answer
upvote count: 1
score: 1
has body: As per the Website if you want to click on the Next Page Button you have to induce WebDriverWait for the WebElement to be clickable following either of the code block as follows : nextpage = WebDriverWait(driver, 10).until(EC.element_to_be_clickable(By.XPATH,"//div[@id='ctl00_ContentPlaceHolder1_ASPxSplitter1_CallbackPaneldgd_dgd_DXPagerBottom']/a[@class='dxp-lead dxp-button dxp-bi']/img[@class='dxWeb_pPrev_Aqua']")) nextpage.click() Or nextpage = WebDriverWait(driver, 10).until(lambda x: x.find_element_by_xpath("//div[@id='ctl00_ContentPlaceHolder1_ASPxSplitter1_CallbackPaneldgd_dgd_DXPagerBottom']/a[@class='dxp-lead dxp-button dxp-bi']/img[@class='dxWeb_pPrev_Aqua']")) nextpage.click()
answers question: http://stackoverflow.com/q/47905232

http://stackoverflow.com/comment/83101003
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47931620
has text: Thanks @mattip I will reach out on IRC. The above screenshots is a real use case currently deployed in prod (w/o pypy). I can comeup with a slim down version of this use-case that can help troubleshoot the slowness

http://stackoverflow.com/q/47935733
has comment: http://stackoverflow.com/comment/82915571
tagged with: python
tagged with: opencv
upvote count: 2
score: 1
tagged with: hough-transform
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/82841987
has comment: http://stackoverflow.com/comment/82846012
has comment: http://stackoverflow.com/comment/82915509
has answer: http://stackoverflow.com/a/47940716
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82841395
type: UnansweredQuestion
has body: I'm trying to detect the the outline of the court, however it is not able to pick up the rectangular shape of the image. b,g,r = cv2.split(img) rgb_img = cv2.merge([r,g,b]) gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray,100,200,apertureSize = 3) lines = cv2.HoughLines(edges,1,np.pi/180,200) for rho,theta in lines[0]: a = np.cos(theta) b = np.sin(theta) x0 = a*rho y0 = b*rho x1 = int(x0 + 1000*(-b)) y1 = int(y0 + 1000*(a)) x2 = int(x0 - 1000*(-b)) y2 = int(y0 - 1000*(a)) cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2) Output image The detected line is in red which appears only on the right hand side of the image. *I have also tried HoughLinesP() but it picks up lines that are not required. Have also tried adjusting the threshold and min and max line length. **Input Image
has title: Python/OpenCV - Detect lines of basketball court from aerial image

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

http://stackoverflow.com/a/48000534
downvote count: 0
score: 1
type: Answer
has body: Try pandas.Series.cumsum(): Code: df['delta_cash'] = (df.Close * -df.pos_chg + df.cash).cumsum() Test Code: import pandas as pd import numpy as np df = pd.read_fwf(StringIO(u""" Date Close pos_chg cash 2000-01-04 81.9375 0.0 10000.00 2000-01-05 69.7500 0.0 0.00 2000-01-06 65.5625 0.0 0.00 2000-01-07 69.5625 0.0 0.00 2000-01-10 69.1875 100.0 0.00 2000-01-11 66.7500 0.0 0.00 2000-01-12 63.5625 -200.0 0.00 2000-01-13 65.9375 200.0 0.00 2000-01-14 64.2500 -200.0 0.00 2000-01-18 64.1250 0.0 0.00"""), skiprows=1) df['delta_cash'] = (df.Close * -df.pos_chg + df.cash).cumsum() print(df) Results: Date Close pos_chg cash delta_cash 0 2000-01-04 81.9375 0.0 10000.0 10000.00 1 2000-01-05 69.7500 0.0 0.0 10000.00 2 2000-01-06 65.5625 0.0 0.0 10000.00 3 2000-01-07 69.5625 0.0 0.0 10000.00 4 2000-01-10 69.1875 100.0 0.0 3081.25 5 2000-01-11 66.7500 0.0 0.0 3081.25 6 2000-01-12 63.5625 -200.0 0.0 15793.75 7 2000-01-13 65.9375 200.0 0.0 2606.25 8 2000-01-14 64.2500 -200.0 0.0 15456.25 9 2000-01-18 64.1250 0.0 0.0 15456.25
upvote count: 1
answers question: http://stackoverflow.com/q/48000395

http://stackoverflow.com/comment/82752936
has text: It is giving an empty list. As you can see in my sample input it is a list within a list.
comment on: http://stackoverflow.com/a/47892727
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/82680270
comment on: http://stackoverflow.com/q/47857835
has text: Saw that answer, just didn't put it together. Thanks!
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47864373
has title: Python Pandas format
score: 0
answer count: 3
tagged with: pandas
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/47865511
has answer: http://stackoverflow.com/a/47864708
has body: I was making a comparation using pandas and I found the next problem: I have 2 tables like this: DESCRIPTION EXTRAS ADDRESS AVAILABLE 1 House WiFi CP 432 1 2 Farm NONE CP 345 1 3 House Wifi CP 315 1 DESCRIPTION EXTRAS ADDRESS AVAILABLE 1 House WiFi CP 437 0 2 House Wifi CP 315 0 And I have the next output: ID DESCRIPTION EXTRAS ADDRESS AVAILABLE 1,1 House WiFi CP 432 1 2,2 Farm NONE CP 345 1 3,3 House Wifi CP 315 1 4,1 House WiFi CP 437 0 Is like pandas is mixing both ID´s. On the other hand in another CSV, I found that some lines looks great, but the others have all the information in the "ID" column. The strange thing is that before the merge of the two CSVs all the info is perfectly placed in the correct column. It looks like this: ID DESCRIPTION EXTRAS ADDRESS AVAILABLE 1 House WiFi CP 432 1 2;Farm NONE CP 345 1 3 House Wifi CP 315 1 1 House WiFi CP 437 0 The code that merged the 2 CSV´s in both situations is this: df1 = pd.read_csv(get_work_folder_path(args.processName) + "/" + args.processName +"EnAlquiler"+ ".csv" , error_bad_lines=False) df2 = pd.read_csv(get_work_folder_path(args.processName) + "/" + args.processName + ".csv" , error_bad_lines=False) frames = [df1, df2] result = pd.concat(frames) df5 = pd.DataFrame(result) df5.drop_duplicates( keep='first', inplace = True) df5.to_csv(get_work_folder_path(args.processName) + "/" + args.processName +"HomeAwayComparacion"+ ".csv") print(df5)
type: Question
has answer: http://stackoverflow.com/a/47864601

http://stackoverflow.com/q/47890756
answer count: 1
favorite count: 0
has title: Conditional replace value in pandas dataframe with calculated value
accepted answer: http://stackoverflow.com/a/47890812
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/47890812
type: Question
tagged with: dataframe
has body: I am struggling with the following. I have a dataframe which has concentration values, which can be below detection limit (in this example &lt;100 or &lt;200) df2 = DataFrame({"site":['site1','site2','site3','site4'], "concentration":[12000,2000,'&lt;100','&lt;200']}) In order to plot the values, I'd like to replace the values &lt;100 with 0.5 x the detection limit. So &lt;100 becomes 50; &lt;200 becomes . The code should then add a column TPH&lt; to indicate which sites are below the detection limit. Any help is much appreciated
tagged with: pandas
upvote count: 1

http://stackoverflow.com/q/47859327
has comment: http://stackoverflow.com/comment/82684523
tagged with: python
has comment: http://stackoverflow.com/comment/82684459
has comment: http://stackoverflow.com/comment/82684292
score: 1
has comment: http://stackoverflow.com/comment/82683582
tagged with: image-processing
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/82683382
upvote count: 2
has body: I have an image img. I also have a mask with value 255 at all the places where I want to retain the pixel values of img are 0 at all other places. I want to use these two images viz. the mask and img such that I create a matrix with original img values at places where the mask is 255, and the value -1 at all places where mask is 0. So, far, I have written this: maskedImg = cv2.bitwise_and(img, mask) but the maskedImg has 0 at all the places where the mask has 0. How can I get the value -1 instead of 0 at all the other places using a fast bitwise operation?
has title: How to set the binary mask in OpenCV python correctly?
answer count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47863380
type: UnansweredQuestion

http://stackoverflow.com/a/47936124
has comment: http://stackoverflow.com/comment/82841688
score: 4
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/82841750
upvote count: 4
accepted answer of: http://stackoverflow.com/q/47936065
downvote count: 0
answers question: http://stackoverflow.com/q/47936065
has comment: http://stackoverflow.com/comment/82975863
has body: When you use the result of a map call it is consumed: &gt;&gt;&gt; p = map(int, ['1', '2']) &gt;&gt;&gt; p &lt;map object at 0x02C878B0&gt; &gt;&gt;&gt; list(p) [1, 2] &gt;&gt;&gt; list(p) [] You should instead store the result of changing the map to a list: &gt;&gt;&gt; p = list(map(int, ['1', '2'])) &gt;&gt;&gt; p [1, 2] &gt;&gt;&gt; p = list(filter(lambda x: x == 1, p)) &gt;&gt;&gt; p [1] Note the same thing happens with filter hence I've assigned that changed to a list too.

http://stackoverflow.com/q/47981939
upvote count: 1
downvote count: 1
has body: When I am trying to send a .exe file using send_file() function of Flask (python 2.7) I get this error IOError: [Errno 22] invalid mode ('rb') or filename: 'C:\\Users\\Dell\\Desktop\\mom\x08uild\\s6\\s6.exe' where s6.exe is my file I want to send
type: Question
answer count: 1
tagged with: flask
linked to: http://stackoverflow.com/q/42012192
has answer: http://stackoverflow.com/a/47981983
favorite count: 0
score: 0
has title: Can't send an .exe file over flask
has comment: http://stackoverflow.com/comment/82932393
duplicate of: http://stackoverflow.com/q/42012192
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/q/47930827
accepted answer: http://stackoverflow.com/a/47930861
has comment: http://stackoverflow.com/comment/82830924
type: AnsweredQuestion
has body: Everyone! The API I'm using has a limit of 50 objects per request so I'm using their scroll api to get the next page, but when I navigate through the last page its X-Next-Page header parameter does not exist and it throws this error KeyError: 'x-next-page' The code I'm using: while request.headers['X-Next-Page'] is not None: url = "https://api-2445582011268.apicast.io%s" % request.headers['X-Next-Page'] request = requests.get(url, headers=self.headers) # break if api key hit usage limit if request.status_code == 403: print("API key reached its limit") break So how do I check if request.headers has X-Next-Page properly? Thank you
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/82830466
score: 0
answer count: 1
has title: Python Key Error exception when navigating api requests
has comment: http://stackoverflow.com/comment/82830556
favorite count: 0
has answer: http://stackoverflow.com/a/47930861
tagged with: python

http://stackoverflow.com/a/47915448
has body: The simplest and most readable answer here is: use current_thread(). You can use various weird ways to pass the thread as a parameter, but there's no good reason for that. Calling current_thread() is the standard approach which is shorter than all the alternatives and will not confuse other developers. Don't try to overthink/overengineer this: def runnable(): thread = threading.current_thread() Thread(target=runnable).start() If you want to hide it a bit and change for aesthetic reasons, you can try: def with_current_thread(f): return f(threading.current_thread()) @with_current_thread def runnable(thread): print(thread.name) Thread(target=runnable).start() If this is not good enough, you may get better answers by describing why you think the parameter passing is better / more correct for your use case.
has comment: http://stackoverflow.com/comment/82799361
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82799231
answers question: http://stackoverflow.com/q/47913963
downvote count: 0

http://stackoverflow.com/q/47885570
tagged with: dot-matrix
tagged with: python
has body: I need to print to a dot-matrix printer, with continuous-sheet paper. My program is written in Python 2.7 and runs in Windows. The printer is connected to a parallel port. I need to print text, not images, however I need to set font family and size, and the exact size of the paper. I absolutely don't want to use win32api and/or the Windows driver, because it has a number of issues (main one, it cannot correctly set the paper height). I guess I should send some escape sequence directly to the printer. How should I do? If it can be useful, this is the exact printer model: EPSON LX-300+ /II https://www.epson.it/products/printers/dot-matrix-printers/epson-lx-300ii
answer count: 0
score: 1
upvote count: 1
has title: Print from python to dot-matrix printer
type: Question
has comment: http://stackoverflow.com/comment/90896026
has comment: http://stackoverflow.com/comment/82736925
tagged with: printing
tagged with: printer-control-language
downvote count: 0
has comment: http://stackoverflow.com/comment/90948728
tagged with: parallel-port
favorite count: 0
has comment: http://stackoverflow.com/comment/82770331
type: UnansweredQuestion

http://stackoverflow.com/comment/82763023
type: AnswerComment
comment on: http://stackoverflow.com/a/47880037
has text: It works perfectly. Thank you very much for your help, I would probably not have figured that out alone.
type: Comment
score: 0

http://stackoverflow.com/comment/82750337
comment on: http://stackoverflow.com/q/47889565
score: 0
type: Comment
type: QuestionComment
has text: The problem I think is that reading json line by line wont work - why do you not just load the file via the json module? - and rename it to .json instead of txt first of all..

http://stackoverflow.com/comment/82702157
type: Comment
comment on: http://stackoverflow.com/a/47868589
type: AnswerComment
has text: Can you generalise this for multiple separators? Or not at all? This will fail for the latter case.
score: 0

http://stackoverflow.com/comment/82682620
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47858950
has text: @ScottHunter unless `newDirectory` is the current dir, it just cannot.

http://stackoverflow.com/q/47971142
favorite count: 0
tagged with: python
has title: TypeError: not enough arguments for format string?
has comment: http://stackoverflow.com/comment/82912102
has comment: http://stackoverflow.com/comment/82911866
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/47971250
has comment: http://stackoverflow.com/comment/82911996
upvote count: 1
has comment: http://stackoverflow.com/comment/82911861
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/47971250
score: 0
has comment: http://stackoverflow.com/comment/82911827
answer count: 1
has body: I have a list which I get from the form: hobby = request.form.getlist('hobby') The list is something like: hobby = [sports, music, coding] I would like to store this list in mysql server, so I have tried: cursor.executemany('INSERT into hobby(list,a_id) VALUES(%s,%s)', (hobby, current_user.id)) return '&lt;h1&gt; Inserted &lt;/h1&gt;'

http://stackoverflow.com/comment/82912706
score: 0
type: Comment
type: QuestionComment
has text: I just edited and added the code and script. Basically I'm using sublime test editor. Is there something problem in script editor?
comment on: http://stackoverflow.com/q/47971533

http://stackoverflow.com/a/47972962
score: 0
has comment: http://stackoverflow.com/comment/82947668
has body: You could use re.findall() to extract all the words from the sentences in description, and check if any of the words from my_list exist in it: import re def find_words(words, text): desc_words = re.findall(r'[^\s,.]+', "".join(text)) for word in words: if word in desc_words: return "found" return "Keywords not found" Which outputs: &gt;&gt;&gt; description = ['This is a random sentence. I like to travel and stuff','Hello world', 'Things on my bucket list, travel'] &gt;&gt;&gt; my_list = ['travel','fire'] &gt;&gt;&gt; find_words(my_list, description) found Or you could use this set() approach: def find_words(words, text): return "found" if set(words).intersection(re.findall(r'[^\s,.]+', "".join(text))) else "Keywords not found" Note: You will have to update your regular expression if you come across sentences with different punctuation other than ,..
answers question: http://stackoverflow.com/q/47972846
type: Answer
has comment: http://stackoverflow.com/comment/82947636
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82947589

http://stackoverflow.com/comment/82965977
score: 0
comment on: http://stackoverflow.com/q/47998664
type: QuestionComment
type: Comment
has text: @Craig Pandas and numpy are useless here, which is why I want to do this in Cython. I was able to lowercase ascii strings extremely fast by incrementing the bytes by 32 but this won't work for unicode strings.

http://stackoverflow.com/comment/82940701
type: AnswerComment
score: 0
type: Comment
has text: Answers like this win the late game as they are more generally applicable.
comment on: http://stackoverflow.com/a/47985809

http://stackoverflow.com/a/47879382
downvote count: 0
type: Answer
upvote count: 3
score: 3
has body: You can use argsort() and then index into columns: (df.apply(lambda x: (-x).argsort(), axis=1) # use -x for sort descending .apply(lambda x: df.columns[x], axis=1)) A B C D A B C A D B C A B D C D A C B D A D C B Note: If you don't want the index and columns in your final output, just add .values.
answers question: http://stackoverflow.com/q/47879262

http://stackoverflow.com/comment/82832110
comment on: http://stackoverflow.com/q/47931539
type: Comment
type: QuestionComment
score: 3
has text: you mean `df.loc[df['variable'] == -9999, 'variable'] = np.nan` ?

http://stackoverflow.com/q/47945819
accepted answer: http://stackoverflow.com/a/47945982
has answer: http://stackoverflow.com/a/47946945
has body: I have a C like source code, and I am trying to extract and save all the strings in this source code to a list, without including the strings that are in comments. a string in this source code can have any characters, white spaces, and even comments. Example: // this is an inline comment with the name "Alpha 1" string x = "Alpha 2"; /** this is a block comment with the string "Alpha 3" */ foo("Alpha 4"); string y = "Alpha /* */ 5 // with comments"; Output: ["Alpha 2", "Alpha 4", "Alpha /* */ 5 // with comments"] The problem that I can't use regex because I can have comments within a given string (which is valid), and of course I can have strings inside an inline comment or inside a block comment. I use this method to get all strings inside a code: re.findall(r'\"(.+?)\"', code) but It gives me also the strings that are inside comments. Any Help?
has answer: http://stackoverflow.com/a/47949735
downvote count: 0
has title: Finding all strings within source code that are not inside comments using Python
has comment: http://stackoverflow.com/comment/82861552
has comment: http://stackoverflow.com/comment/82861918
favorite count: 0
has comment: http://stackoverflow.com/comment/82861695
upvote count: 2
has answer: http://stackoverflow.com/a/47945982
tagged with: python
tagged with: regex
answer count: 4
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47946284
has answer: http://stackoverflow.com/a/47946284
type: Question

http://stackoverflow.com/q/47998640
has body: I'm looking to have a generator function that returns points along a line, given a minimum-distance k. This is simple enough, and can be done with numpy as follows: points = np.linspace(start, end, k) However, I would like to generate the points as a sort of "increasing resolution", so that on a line from 0 to 1, the generator would yield: 1/2, 1/4, 3/4, 1/8, 3/8, 5/8, ... Again, this is easy enough to do recursively (just accept the endpoints and call self on each half), but I'd like a generator that can achieve the same thing without having to fill an array with everything from the start, and without duplicate points. What would be the best way to do this?
type: Question
score: 1
tagged with: numpy
answer count: 2
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/47999417
has title: Back-and-Forth Linspace Generator
has answer: http://stackoverflow.com/a/47999417
has answer: http://stackoverflow.com/a/47998788
tagged with: python
type: AnsweredQuestion
tagged with: geometry
accepted answer: http://stackoverflow.com/a/47998788
has comment: http://stackoverflow.com/comment/82966041
has comment: http://stackoverflow.com/comment/82966081
upvote count: 1
has comment: http://stackoverflow.com/comment/82965829

http://stackoverflow.com/comment/82861533
type: Comment
has text: You can test the configuration and see exactly which files `nginx` is reading with: `nginx -T`
comment on: http://stackoverflow.com/q/47945783
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82776876
type: AnswerComment
has text: @StefanPochmann It's the nested `map`s where I - or rather my spinning head - draw the line.
type: Comment
comment on: http://stackoverflow.com/a/47904653
score: 0

http://stackoverflow.com/comment/82820765
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/47926341
has text: Possible duplicate of [What's the canonical way to check for type in Python?](https://stackoverflow.com/questions/152580/whats-the-canonical-way-to-check-for-type-in-python)

http://stackoverflow.com/comment/92843628
type: QuestionComment
comment on: http://stackoverflow.com/q/47969937
type: Comment
score: 4
has text: I have only found a workaround in this: http://deeplearning.lipingyang.org/2018/03/29/run-jupyter-notebook-from-terminal-with-tmux/ But it involves running the whole notebook from the terminal. I wish there could be a way to do what you're asking for.

bash
tags question: http://stackoverflow.com/q/47924373
tags question: http://stackoverflow.com/q/47879805
tags question: http://stackoverflow.com/q/47886113
tags question: http://stackoverflow.com/q/48004543
tags question: http://stackoverflow.com/q/48007548
tags question: http://stackoverflow.com/q/47905056
tags question: http://stackoverflow.com/q/47910810
tags question: http://stackoverflow.com/q/47982203
tags question: http://stackoverflow.com/q/47910189
tags question: http://stackoverflow.com/q/47994631
tags question: http://stackoverflow.com/q/47964675
tags question: http://stackoverflow.com/q/47945185
tags question: http://stackoverflow.com/q/47899453
tags question: http://stackoverflow.com/q/47979645
tags question: http://stackoverflow.com/q/47937446
tags question: http://stackoverflow.com/q/48005872
tags question: http://stackoverflow.com/q/47880153
tags question: http://stackoverflow.com/q/47999477
tags question: http://stackoverflow.com/q/47926929
tags question: http://stackoverflow.com/q/47882305
tags question: http://stackoverflow.com/q/47948120
tags question: http://stackoverflow.com/q/47890232
tags question: http://stackoverflow.com/q/47959383
tags question: http://stackoverflow.com/q/47879490
tags question: http://stackoverflow.com/q/47972000
tags question: http://stackoverflow.com/q/47947625
tags question: http://stackoverflow.com/q/47893138
type: Tag
tags question: http://stackoverflow.com/q/47871976
tags question: http://stackoverflow.com/q/47882916
tags question: http://stackoverflow.com/q/47948512
tags question: http://stackoverflow.com/q/47939713
tags question: http://stackoverflow.com/q/48003424
tags question: http://stackoverflow.com/q/47877985
tags question: http://stackoverflow.com/q/48014443
tag name: bash
tags question: http://stackoverflow.com/q/47895454
tags question: http://stackoverflow.com/q/48000154

http://stackoverflow.com/comment/82831406
type: AnswerComment
type: Comment
has text: Thanks a lot for your answer. `sym.solve(H_I(P) - H_II(P) , P)` returns `-6.32436145176552 + 0.e-19*I ` and the other 2 roots. However, `[x.evalf() for x in sol]` returns `-6.32436145176552 + 1.0842021724855e-19*I` What is `evalf()` doing on `0.e-19*I` so that it is converted to `1.0842021724855e-19*I` ?
comment on: http://stackoverflow.com/a/47927676
score: 1

http://stackoverflow.com/comment/82697017
comment on: http://stackoverflow.com/q/47865690
has text: Are you sure the duration is exactly 220 seconds? 9745238 at 44.1Khz would be 220.98 seconds.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47986874
type: Question
type: AnsweredQuestion
has body: As subject, I try to fetch the table using beautifulsoup. http://www.hkjc.com/english/racing/Horse.asp?HorseNo=T421 from selenium import webdriver from bs4 import BeautifulSoup import pandas as pd import numpy as np import lxml import xlrd HorseNo = ["T421"] driver = webdriver.PhantomJS(r'D:\Program Files\Python\Path\PhantomJS\bin\phantomjs.exe') #driver = webdriver.Chrome(r'D:\Program Files\Python\Path\chromedriver.exe') url = "http://www.hkjc.com/english/racing/horse.asp?HorseNo=" + str(HorseNo) driver.get(url) html = driver.page_source soup = BeautifulSoup(html, "lxml") table = soup.find("table", {"class" :"bigborder", "width":"970"}).findAll("tr") print(table) for row in table: cells = row.findAll("td") print(cells) Print(table) result is fine though print(cells) is not able to return every td in the table. Would somebody advise me further. Thanks.
has answer: http://stackoverflow.com/a/47987022
answer count: 1
tagged with: beautifulsoup
score: 0
tagged with: http://stackoverflow.com/tag/html
tagged with: python
accepted answer: http://stackoverflow.com/a/47987022
has title: Python beautifulsoup paring html table - td data missing

http://stackoverflow.com/a/47926275
answers question: http://stackoverflow.com/q/47926274
has comment: http://stackoverflow.com/comment/82940952
has comment: http://stackoverflow.com/comment/83166585
upvote count: 2
type: Answer
has body: Good news: Ranorex still works with .NET for Python. And this will still be in the future as long as C# or VB APIs are supported by ranorex and as long as dotnet for python is still supported (which it is, last commit is a few days ago at the time of this post). Now, it is a bit tricky to get Ranorex remote control running in Python. This setup was from pure trial-and-error and combining different pieces of information online: Install python for .net: pip3 install pythonnet Find out the DLL folder of ranorex. In my case it was C:\Program Files (x86)\Ranorex 8.0\Bin\x64\. In this folder you should see several DLLs (75 DLLs on my machine) including Ranorex.Core.dll Now Ranorex should be ready to be used in Python. Here is a small example (you'd need to replace the sys.path.extend() with the path you got from step 2. import sys import clr # make Ranorex module available, needs before the `import Ranorex` sys.path.append('C:\\Program Files (x86)\\Ranorex 8.0\\Bin\\x64\\') clr.AddReference('Ranorex.Core') import Ranorex Ranorex.Host.Local.RunApplication('C:\\path\\to\\my_app.exe') apps = [c for c in Ranorex.Host.Local.Children if "My App" in c.ToString()] if len(apps) != 1: print("starting of 'My App' somehow failed, quitting now") sys.exit(1) app = apps[0] app.PressKeys('{LMenu down}{Fkey}{LMenu up}') # presses Alt-F -&gt; e.g. opens the file menu To develop your python scripts you best set up the test in ranorex recorder and then generate the C# code over Export -> Generate C# Code (Ctrl-G). Then you'd need to translate the C# code to python but that's relatively easy.
score: 2
accepted answer of: http://stackoverflow.com/q/47926274
type: AcceptedAnswer
downvote count: 0

yield
tags question: http://stackoverflow.com/q/47906338
type: Tag
tags question: http://stackoverflow.com/q/47865046
tag name: yield

http://stackoverflow.com/q/47884228
downvote count: 0
has answer: http://stackoverflow.com/a/47899136
favorite count: 0
accepted answer: http://stackoverflow.com/a/47899136
tagged with: postgresql
has body: I'm running SQL Query using python-Django RAW Query..!! I'm using IN() function to pass my tuple in the query. My code looks like this... Here I am getting the list of dnc_domains and dnc_company from a json/function dnc_domain_names = list(map(lambda x: get_domain_name(x), dnc_websites)) dnc_company_names = list(map(lambda l: l.lower(), list(filter(None, list(map(lambda x: x['company_name'], dnc_info)))))) QUERY: select_query = """ select c.id from ( select id, lower(company_name) as c_name,substring(website from '(?:.*://)?(?:www\.)?([^/]*)') as website_domain, from contacts where campaign_id = %s ) c where c.c_name IN %s OR c.website_domain IN %s """ Executing Query: with connection.cursor() as cursor: cursor.execute(select_query, (campaign.id,tuple(dnc_company_names),tuple(dnc_domain_names)) matching_contact_ids = cursor.fetchall() But, there is a case when any dnc_company_names or dnc_domain_name is empty [] then my Query throws an Error otherwise if there at least 1 element in any of them then it works fine. SQL Error: syntax error at or near ")" LINE 5: WHERE id IN () ^ So, help me to tackle this error. SQL should handle both empty or non empty tuples.
tagged with: python
upvote count: 3
tagged with: django
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47884969
score: 3
has title: Syntax Error in SQL Query( select ) when an empty list is passed
type: Question
has answer: http://stackoverflow.com/a/47884969
answer count: 2
tagged with: sql

http://stackoverflow.com/comment/82813849
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47921571
has text: I have tried using unidecode for str_1 and str_2, it became the same but another issue appeared , the accent in text was be removed.

http://stackoverflow.com/a/47993692
answers question: http://stackoverflow.com/q/47993502
type: Answer
has body: i converted the entire list into a string and then found a substring of that string the list when converted to a string it becomes str(a)='[9,0,1,2,3,4,5,6,7,8]' which when when we strip the string becomes str(a).strip('[]')='9,0,1,2,3,4,5,6,7,8' Now the problem just converted to checking if there is a substring in the the string so we can us the in operator to check the substring The solution a=[9,0,1,2,3,4,5,6,7,8] b=[1,2,3,4,5,6] print(str(b).strip('[]') in str(a).strip('][')) testcase1 testcase2
score: 0

http://stackoverflow.com/comment/82894407
has text: Here we go. Move `grocery_item = {}` into the loop, or else you append the _same_ dictionary to the list _each time_. So, if you modify one, you modify them all _just the same_.
score: 1
comment on: http://stackoverflow.com/q/47962474
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47947991
favorite count: 0
possible better answer: http://stackoverflow.com/a/53240641
tagged with: labview
has answer: http://stackoverflow.com/a/53240641
upvote count: 1
tagged with: python
type: AnsweredQuestion
type: Question
tagged with: numpy
answer count: 2
downvote count: 0
has body: I'm using the npTDMS Python module for reading TDMS files, and I'm having trouble getting all the channel properties. I can open my TDMS file using Scout or DIAdem or even the built-in LabVIEW viewer, and I can see that each channel in the file (Time and Pressure) has four properties: NI_ArrayColumn, NI_ChannelLength, NI_DataType, and name. However, the following code only outputs OrderedDict([('NI_ArrayColumn', 1)]) The code is the following: from nptdms import TdmsFile tdms_file = TdmsFile("2017-10-16;12.37.05_Pressure (1).tdms") channel = tdms_file.object('Scan', 'Pressure') print(str(channel.properties)) Where are the other three properties?
has answer: http://stackoverflow.com/a/47998718
accepted answer: http://stackoverflow.com/a/47998718
score: 1
has title: npTDMS Python Module not getting all channel properties

http://stackoverflow.com/a/47949893
answers question: http://stackoverflow.com/q/47946026
has body: I suppose the error message clearly states the issue, keyword error on previous because the correct keyword is previousStepName not previous. Refer to 34.25 in scripting reference guide for more info.
upvote count: 1
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/82958092
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47985841
has text: I did matched your code and why I am seeing better results and the insert syntax works perfectly. Even spacing matches

http://stackoverflow.com/comment/82935494
comment on: http://stackoverflow.com/q/47983093
score: 0
type: QuestionComment
has text: @Wen This is a pretty good solution. In the above example, it would be ` df1.amount.gt(0).all()`
type: Comment

http://stackoverflow.com/comment/82720771
type: QuestionComment
has text: Yes, but how do I take the timezone into account?
score: 0
comment on: http://stackoverflow.com/q/47877346
type: Comment

http://stackoverflow.com/a/47891330
accepted answer of: http://stackoverflow.com/q/47891228
has comment: http://stackoverflow.com/comment/82749641
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82749479
has comment: http://stackoverflow.com/comment/82749351
has body: I'd do this with groupby + first, and then use np.where to decide where to apply the changes. i = df.groupby('Id').Name.transform('first') df['New Col'] = np.where(np.equal(df.Name, i), df.Name, df.Name + '-' + i) df Id Rank Name New Col 0 111 7 x x 1 111 5 y y-x 2 111 1 z z-x 3 222 1 x x 4 333 5 a a 5 333 1 b b-a 6 444 1 c c
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47891228

installation
tags question: http://stackoverflow.com/q/47982521
tags question: http://stackoverflow.com/q/47932607
tags question: http://stackoverflow.com/q/48000502
tags question: http://stackoverflow.com/q/47963083
tag name: installation
tags question: http://stackoverflow.com/q/47961041
tags question: http://stackoverflow.com/q/47963861
tags question: http://stackoverflow.com/q/47916730
tags question: http://stackoverflow.com/q/47856996
type: Tag
tags question: http://stackoverflow.com/q/48005872
tags question: http://stackoverflow.com/q/47955200
tags question: http://stackoverflow.com/q/47941418
tags question: http://stackoverflow.com/q/47999518
tags question: http://stackoverflow.com/q/47968124
tags question: http://stackoverflow.com/q/47922700
tags question: http://stackoverflow.com/q/47937133
tags question: http://stackoverflow.com/q/47962148

http://stackoverflow.com/q/47891517
has body: I am trying to read all the lines in a specific file, and it prints the number of the line as an index. What I am trying to do is to delete the line by inputting the number of the line by the user. As far as it is now, it prints all the lines with the number of that line, but when I enter the number of the line to be deleted, it's not deleted. This is the code of the delete function: def deleteorders (): index = 0 fh = open ('orders.txt', 'r') lines = fh.readlines() for line in lines: lines = fh.readlines() index = index+1 print (str(index) + ' ' + line) try: indexinp = int(input('Enter the number of the order to be deleted, or "B" to go back: ')) if indexinp == 'B': return else: del line[indexinp] print (line) fh = open ('orders.txt', 'w') fh.writelines(line) fh.close() except: print ('The entered number is not in the range') return
has comment: http://stackoverflow.com/comment/82749855
has title: reading and deleting lines in python
score: -1
type: Question
has answer: http://stackoverflow.com/a/47892409
answer count: 1
has comment: http://stackoverflow.com/comment/82749692
has comment: http://stackoverflow.com/comment/82751437
favorite count: 0
has comment: http://stackoverflow.com/comment/82749737
tagged with: python
type: UnansweredQuestion
downvote count: 2
upvote count: 1

http://stackoverflow.com/q/47900237
has answer: http://stackoverflow.com/a/47900380
possible better answer: http://stackoverflow.com/a/47900388
score: 12
has answer: http://stackoverflow.com/a/47900388
answer count: 2
upvote count: 21
has title: Why does (1 == 2 != 3) evaluate to False in Python?
has body: Why does (1 == 2 != 3) evaluate to False in Python, while both ((1 == 2) != 3) and (1 == (2 != 3)) evaluate to True? What operator precedence is used here?
downvote count: 9
accepted answer: http://stackoverflow.com/a/47900380
type: AnsweredQuestion
favorite count: 0
type: Question
tagged with: python
tagged with: operator-precedence

http://stackoverflow.com/comment/82884451
has text: You may use *the dictionary*, which you can know about, to store what is not yet known. `d = {}; d[input_key] = input_value`
score: 4
type: Comment
comment on: http://stackoverflow.com/q/47957566
type: QuestionComment

http://stackoverflow.com/q/47955175
accepted answer: http://stackoverflow.com/a/47955256
favorite count: 0
has title: What's 'comprehesion' mean in python 'list comprehension'
upvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82879760
score: -3
type: Question
downvote count: 4
answer count: 1
has body: I know what list comprehension is, just want to know the name origin It's hard to remember this widely used python concept without understanding the term.
has answer: http://stackoverflow.com/a/47955256
tagged with: python

http://stackoverflow.com/q/47883593
has comment: http://stackoverflow.com/comment/82734327
has comment: http://stackoverflow.com/comment/82733613
favorite count: 0
has comment: http://stackoverflow.com/comment/82734214
has comment: http://stackoverflow.com/comment/82734583
linked to: http://stackoverflow.com/q/32454589
tagged with: python
has comment: http://stackoverflow.com/comment/82733137
tagged with: windows-subsystem-for-linux
score: 2
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/82733715
has comment: http://stackoverflow.com/comment/82734748
has comment: http://stackoverflow.com/comment/82733305
type: Question
has answer: http://stackoverflow.com/a/51344899
accepted answer: http://stackoverflow.com/a/51344899
upvote count: 2
has body: After installing the WSL I have two python installations on my PC, the Windows one and the one in the WSL. The developers state here that you "can invoke Windows binaries directly from the WSL command line," however, when I try to invoke the python.exe file I get the following odd behavior: myprompt$ python.exe 1 2 print("test") print "test" File "&lt;stdin&gt;", line 4 print "test" ^ SyntaxError: Missing parentheses in call to 'print' myprompt$ Whereas if the interactive interpreter was running, I'd get: myprompt$ python.exe &gt;&gt;&gt;1 1 &gt;&gt;&gt;2 2 print("test") test print "test" File "&lt;stdin&gt;", line 1 print "test" ^ SyntaxError: Missing parentheses in call to 'print' myprompt$ Its like the interpreter is running, but its not giving me a prompt, and it exits at the first error. Interestingly, if I navigate to the same directory and run python.exe from a windows command prompt, everything works fine. P.S.: I found the location of the Windows Python install by running the sys.executable command in Python.
answer count: 1
has title: Strange Behavior Calling Windows Python from Within WSL (Bash on Windows)
has comment: http://stackoverflow.com/comment/82734718

http://stackoverflow.com/comment/82824761
has text: `//input[@class='btn icon-icon_bearbeiten status-expired'][@type='button']` doesnot identifies any `WebElement` on the `Web Page`. If you are looking to click on the **`Login`** button, that is within a ` ` tag and you must be using **`driver.find_element_by_xpath("//button[@class='btn btn-wh-primary' and @id='wh-login-btn']")`**
type: AnswerComment
comment on: http://stackoverflow.com/a/47925805
score: 0
type: Comment

http://stackoverflow.com/comment/82923786
has text: @Zohair sure, added an explanation; see updated answer!
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47977225
score: 2

http://stackoverflow.com/comment/82805783
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47918992
has text: `r"C:\mypath\......"`
score: 0

datetime
tags question: http://stackoverflow.com/q/48014586
tags question: http://stackoverflow.com/q/47984939
tags question: http://stackoverflow.com/q/47930029
tags question: http://stackoverflow.com/q/47873936
tags question: http://stackoverflow.com/q/47980464
tags question: http://stackoverflow.com/q/47865485
tags question: http://stackoverflow.com/q/47863742
tags question: http://stackoverflow.com/q/47863283
tags question: http://stackoverflow.com/q/47872522
tags question: http://stackoverflow.com/q/47985562
tags question: http://stackoverflow.com/q/47997596
tags question: http://stackoverflow.com/q/47952986
tags question: http://stackoverflow.com/q/47951637
tags question: http://stackoverflow.com/q/47981061
tags question: http://stackoverflow.com/q/47921648
tags question: http://stackoverflow.com/q/47900711
tags question: http://stackoverflow.com/q/47927043
tags question: http://stackoverflow.com/q/47907967
tags question: http://stackoverflow.com/q/48004171
tags question: http://stackoverflow.com/q/47919315
tags question: http://stackoverflow.com/q/47857971
tags question: http://stackoverflow.com/q/47938194
tags question: http://stackoverflow.com/q/47978380
tag name: datetime
tags question: http://stackoverflow.com/q/47879683
tags question: http://stackoverflow.com/q/47898473
tags question: http://stackoverflow.com/q/47995356
tags question: http://stackoverflow.com/q/47934307
tags question: http://stackoverflow.com/q/47996743
tags question: http://stackoverflow.com/q/47993763
type: Tag
tags question: http://stackoverflow.com/q/47890399
tags question: http://stackoverflow.com/q/48010283
tags question: http://stackoverflow.com/q/47869154
tags question: http://stackoverflow.com/q/47956313
tags question: http://stackoverflow.com/q/47904296
tags question: http://stackoverflow.com/q/48004752
tags question: http://stackoverflow.com/q/47899416
tags question: http://stackoverflow.com/q/47972604
tags question: http://stackoverflow.com/q/47919045
tags question: http://stackoverflow.com/q/47942306
tags question: http://stackoverflow.com/q/47947145
tags question: http://stackoverflow.com/q/47932455

http://stackoverflow.com/comment/82916752
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47973393
has text: @FatihAkici list(set(flatList)) is also an iterator my friend. so if you have one loop `for e in l:` and then `list(set(flatList))` and then `['ID'+str(e) for e in list3]` , Now you have three iterators.

http://stackoverflow.com/q/47877089
favorite count: 0
tagged with: linux
has comment: http://stackoverflow.com/comment/94959948
accepted answer: http://stackoverflow.com/a/48642328
tagged with: python
tagged with: jupyter-notebook
tagged with: jupyterhub
type: AnsweredQuestion
score: 2
has body: I'm struggling to fire up jupyterhub, running with limited sudo rights, without root privileges. If I understand correctly, this makes it possible to run notebook servers as real system users on a shared system without running the Hub itself as root. I followed the following steps, but for someone reason the following command keeps giving me the error that my new user (rhea) is required to give password: sudo -u rhea sudo -n -u $USER /usr/local/bin/sudospawner --help # sudo: a password is required I added the following lines to /etc/sudoers (edited using visudo): Cmnd_Alias JUPYTER_CMD = /usr/local/bin/sudospawner rhea ALL=(%jupyterhub) NOPASSWD:JUPYTER_CMD And added a new user to the group jupyterhub: adduser -G jupyterhub newuser I'm struggling to see why rhea is not allowed to run sudospawner. If I simply run sudo /usr/local/bin/sudospawner --help I do get the desired result. Running on Ubuntu 16.04 EC2. Help and advice on this is highly appreciated!
upvote count: 2
type: Question
has answer: http://stackoverflow.com/a/48642328
tagged with: ubuntu
answer count: 1
has title: Jupyterhub using sudo without root: can't run sudospawner without pw
downvote count: 0
has comment: http://stackoverflow.com/comment/82720116

http://stackoverflow.com/a/47906171
score: 1
has comment: http://stackoverflow.com/comment/82779354
answers question: http://stackoverflow.com/q/47906007
has body: Python makes no assumptions about the contents of your string. If you want to insert a datetime, you'd need to first call gmtime, get the result, and then insert it into a string with str.format. Here's a simple example - &gt;&gt;&gt; "C:\\path\\screenshots\\{}.png".format(strftime("%Y-%m-%d %H:%M:%S", gmtime())) 'C:\\path\\screenshots\\2017-12-20 12:37:29.png' What you've been doing thus far is inserting the expression as a substring. Like I mentioned, python does not make any assumptions about your string, and does not evaluate its contents in any way.
upvote count: 1
type: Answer
downvote count: 0

http://stackoverflow.com/comment/82914538
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47972362
score: 0
has text: poke, dawg: I'm not exactly sure what you mean, but in Terminal I use cd to change the directory to the folder containing the script, then I type "python doodles.py" where "doodles.py" is the name of the script, written in emacs. Everything works perfectly, except this issue with the grey line, and only on the first execution.

http://stackoverflow.com/comment/82715929
type: AnswerComment
comment on: http://stackoverflow.com/a/47874334
has text: for some reason I cant make it work this way but seems simplier !
score: 0
type: Comment

http://stackoverflow.com/comment/82690881
has text: @furas Yes, I tested the same URL with Postman, it gives proper response content in the response body.
score: 0
comment on: http://stackoverflow.com/q/47862948
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82711036
has text: @jezrael ummm, my real answer is `(df.groupby('item_category_id').total_sales.sum()).loc[lambda x : x==x.max()]`
type: AnswerComment
comment on: http://stackoverflow.com/a/47871239
type: Comment
score: 1

http://stackoverflow.com/comment/82736821
score: 0
has text: Since you need to have in API web interface and it is impossible, may be that has not been implemented to have that. But to overcome issue we have option of json / raw input.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47885340

http://stackoverflow.com/comment/82970215
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48000786
score: 0
has text: @Prune: Question looks like it meets those criteria to me...

http://stackoverflow.com/q/47859394
favorite count: 0
has answer: http://stackoverflow.com/a/47859555
downvote count: 5
tagged with: python
possible better answer: http://stackoverflow.com/a/47859544
has comment: http://stackoverflow.com/comment/82683541
type: AnsweredQuestion
upvote count: 0
score: -5
has body: https://www.urionlinejudge.com.br/judge/en/problems/view/1145 Write an program that reads two numbers X and Y (X &lt; Y). After this, show a sequence of 1 to y, passing to the next line to each X numbers. Input The input contains two integer numbers X (1 &lt; X &lt; 20) and Y (X &lt; Y &lt; 100000). Output Each sequence must be printed in one line, with a blank space between each number. My code is here: x,y = raw_input().split(" ") x = int(x) xr = x y = int(y) lis = [] for i in range(1, y+1): lis.append(i) j = 0 for i in range(1, y+1): while j &lt;= x: try: if j &lt; x: print str(lis[j]), j=j+1 else: if x == y: break else: print "" x = xr + x except IndexError: break Code's output is accurate. But the website is not accepting my code for some reason. Please help me find the bug?
has title: What's wrong with my Python 2 program?
type: Question
has answer: http://stackoverflow.com/a/47859544
tagged with: python-2.7
answer count: 2
accepted answer: http://stackoverflow.com/a/47859555

http://stackoverflow.com/q/47981775
accepted answer: http://stackoverflow.com/a/48042746
tagged with: python
answer count: 1
upvote count: 3
has body: I have a wierd situation in Keras and it really freaks me out. I am trying to train a CNN using pretrained Inception with additional convolution, global average pool and dense layers. I am using a ImageDataGenerator to load the data. The data generator is working fine, I have tested that. The model compiles well also. But when I run fit_generator, no output is printed, the CPU is at 100% and memory starts filling up slowly until it overflows. And although I have a GPU and have worked with it in tensorflow (which is the backend here) a number of times, it is completely ignored by Keras. Considering that maybe batch size could be a problem, I set it to 1 but it did not solve the issue. The images are of size 299x299, which is not that big anyway. I will post the code below as a reference though it seems to me that nothing is wrong with it: def get_datagen(): return ImageDataGenerator(rotation_range=30, width_shift_range=0.2, height_shift_range=0.2, horizontal_flip=True, fill_mode='nearest' ) # Setup and compile the model. model = InceptionV3(include_top=False, input_shape=(None, None, 3)) # Set the model layers to be untrainable for layer in model.layers: layer.trainable = False x = model.output x = Conv2D(120, 5, activation='relu')(x) x = GlobalAveragePooling2D()(x) predictions = Activation('softmax')(x) model_final = Model(inputs=model.inputs, outputs=predictions) model_final.compile(optimizer='adam', loss='categorical_crossentropy',metrics=['accuracy']) # Define the dataflow. train_gen = get_datagen() val_test_gen = get_datagen() train_data = train_gen.flow_from_directory(train_folder, target_size=(299, 299), batch_size=1) val_data = val_test_gen.flow_from_directory(validation_folder, target_size=(299, 299), batch_size=1) test_data = val_test_gen.flow_from_directory(test_folder, target_size=(299, 299), batch_size=1) train_size = train_data.n val_size = val_data.n test_size = test_data.n # Define callbacks. model_checkpoint = ModelCheckpoint('../models/dbc1/', monit…
has comment: http://stackoverflow.com/comment/83053141
has comment: http://stackoverflow.com/comment/83039415
downvote count: 0
has answer: http://stackoverflow.com/a/48042746
tagged with: keras
has title: Keras prints no output, high memory and CPU usage and GPU is not used when using tensorboard Callback
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/83041589
has comment: http://stackoverflow.com/comment/83044078
favorite count: 0
type: Question

http://stackoverflow.com/q/47958934
score: 0
has comment: http://stackoverflow.com/comment/82892682
tagged with: python
tagged with: kivy
tagged with: exe
has body: I'm trying to create an exec file from Kivy app(in python) through PyInstaller and I have python classes which I created that importing them gives an error: 'module' has no attribute 'A'(A is a python class which also have a kivy file). How I can import them through the spec file like importing python modules through 'hidden imports'(I have a problem with importing python modules and importing them through 'hidden imports solved the problem)?
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82977132
type: Question
has title: Create executable from a kivy file
has comment: http://stackoverflow.com/comment/82995159

http://stackoverflow.com/comment/82918961
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47974195
has text: You can have both as the index, and then slice accordingly. It isn't hard. With an example, I can write an answer and show you. Can you add some reproducible data example explaining what it is you want to do?

http://stackoverflow.com/q/47908045
answer count: 0
linked to: http://stackoverflow.com/q/30761152
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82783397
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/83449686
has comment: http://stackoverflow.com/comment/82783408
has comment: http://stackoverflow.com/comment/82783487
has title: Importing Pandas in python always gives an error
has comment: http://stackoverflow.com/comment/82783904
has body: I'm using python 3.6, windows 7, pyCharm IDE. I keep getting this message when trying to import pandas using import pandas. File "C:\Users\Seif\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas__init__.py", line 35, in "the C extensions first.".format(module)) ImportError: C extension: DLL load failed: The specified procedure could not be found. 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. I tried some solutions provided on google search but nothing works. 1) checking pip version using this command: pip -V pip 9.0.1 from c:\users\seif\appdata\local\programs\python\python36-32\lib\site- packages\pip-9.0.1-py3.6.egg (python 3.6) 2) installing pandas using this command: pip install pandas --upgrade Requirement already up-to-date: pandas in c:\users\seif\appdata\local\programs\p ython\python36-32\lib\site-packages Requirement already up-to-date: python-dateutil>=2 in c:\users\seif\appdata\loca l\programs\python\python36-32\lib\site-packages (from pandas) Requirement already up-to-date: numpy>=1.9.0 in c:\users\seif\appdata\local\prog rams\python\python36-32\lib\site-packages (from pandas) Requirement already up-to-date: pytz>=2011k in c:\users\seif\appdata\local\progr ams\python\python36-32\lib\site-packages (from pandas) Requirement already up-to-date: six>=1.5 in c:\users\seif\appdata\local\programs \python\python36-32\lib\site-packages (from python-dateutil>=2->pandas) when I run the suggested command python setup.py build_ext --inplace --force there is no file called setup.py. so what I missing?
score: 0
tagged with: pandas

http://stackoverflow.com/q/47895890
tagged with: python
has comment: http://stackoverflow.com/comment/82758615
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47895946
downvote count: 0
accepted answer: http://stackoverflow.com/a/47895946
score: 1
type: Question
tagged with: split
has comment: http://stackoverflow.com/comment/82758584
has body: def main(): print('Assignment #4-1, Ayub Hussein, ayub.hussein13@gmail.com') for line in fileinput.input(): words = line.split() for i in range(0,len(words)): sys.stdout.write(words[i]+', ') sys.stdout.write('\n') main() OUTPUT: hello, this, is\n hello, this, is\n hello, this, is\n
upvote count: 1
answer count: 1
tagged with: string
has comment: http://stackoverflow.com/comment/82758577
favorite count: 0
has comment: http://stackoverflow.com/comment/82759241
has title: Sentence prints too many times

http://stackoverflow.com/comment/82770552
type: QuestionComment
comment on: http://stackoverflow.com/q/47901931
has text: Can you add data samples and expected output?
score: 0
type: Comment

http://stackoverflow.com/a/47996106
upvote count: 2
answers question: http://stackoverflow.com/q/47995710
has body: row is a tuple with two elements, therefore you can unpack it during assignment: StatesPriority = {} for row in sheet.iter_rows(min_row=2, max_col=2, max_row=50) cell_a, cell_b = row StatesPriority[cell_a.value] = (tuple(cell_b.value.split(','))
has comment: http://stackoverflow.com/comment/82960394
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47995710
score: 2

http://stackoverflow.com/comment/92493249
type: Comment
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/48861231
has text: @erickfis I've updated the class with a proper example. Do note that the not every database will use the same driver and will thus raise an error when using this class. An example database that does not use this is PostgreSQL. I haven't found a fast way yet to insert data into PSQL. One way to still use this class like that is by explicitly turning the switch off by calling: `con._init_engine(SET_FAST_EXECUTEMANY_SWITCH=False)` After having initialized the class. Good luck.

http://stackoverflow.com/comment/82941521
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/47986216
has text: `[[x + y for x, y in zip(*sublists)] for sublists in zip(lst1, lst2)]`

http://stackoverflow.com/q/47871976
has comment: http://stackoverflow.com/comment/82713695
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/82709776
type: Question
tagged with: bash
score: 2
tagged with: signals
downvote count: 0
has body: I have a python program that plays a video (using OpenCV). This runs concurrently with a couple of other programs - and based on some conditions, I want to be able to send the python script running the video a signal that tells it to stop, play, pause, etc. I currently have something that listens to keystrokes, and if a certain key is pressed, it executes a certain action. But, I cannot have a user keep sending keystroke signals. I tried to think of some way to have the bash script I am running (that will, by the way, be the medium through which I send these signals to said python script) send the keystroke messages through a little hack using wmcntrl and xdotool, but it is really not working as intended. So, what is the Python way of having a bash script send a signal like "Pause", "Play", "Take Screenshot", etc? I am kinda lost... Thank you
favorite count: 0
type: UnansweredQuestion
has title: Sending a signal to a running Python Script
tagged with: python

http://stackoverflow.com/q/47991710
type: AnsweredQuestion
has title: how to stop python from "binding" variables that stand for lists
has comment: http://stackoverflow.com/comment/82951677
has comment: http://stackoverflow.com/comment/82951854
type: Question
has comment: http://stackoverflow.com/comment/82951826
has comment: http://stackoverflow.com/comment/82951829
has comment: http://stackoverflow.com/comment/82951709
has answer: http://stackoverflow.com/a/47992074
has comment: http://stackoverflow.com/comment/82951715
score: 0
linked to: http://stackoverflow.com/q/11222440
linked to: http://stackoverflow.com/q/2612802
answer count: 1
duplicate of: http://stackoverflow.com/q/11222440
duplicate of: http://stackoverflow.com/q/2612802
has comment: http://stackoverflow.com/comment/82951783
accepted answer: http://stackoverflow.com/a/47992074
has comment: http://stackoverflow.com/comment/82951693
has body: In python, the code x = 0 y = x y = 1 print x returns "0" while the code x = [0] y = x y[0] = 1 print x returns "[1]". Why does python treat lists so differently from integers and what can I do to force it to treat the bottom "x" as it does the top "x"? It seems like the '='s in the respective second lines mean different things - the top one only affects y while the bottom somehow binds x to y. So maybe I need to use a different symbol in the bottom code?
tagged with: python
has comment: http://stackoverflow.com/comment/82951665

http://stackoverflow.com/comment/82844036
comment on: http://stackoverflow.com/q/47937366
has text: print path variable to cross verify.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82699493
comment on: http://stackoverflow.com/q/47867135
has text: What have you tried that didn't work ? Hint : The "API call" part is totally irrelevant here - the question is "how do I apply a function working on a single item to a list (or any other iterable) of items"
type: QuestionComment
type: Comment
score: 2

http://stackoverflow.com/comment/82990057
type: AnswerComment
comment on: http://stackoverflow.com/a/48009970
score: 0
type: Comment
has text: I prefer my version. ;) At least, you should avoid calling `int(testNumber)` twice. Also, `math.floor` returns an `int` in Python 3, so you don't need to wrap it in a call to the `int` constructor.

http://stackoverflow.com/q/47977954
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82924915
has title: How to access variables from .yaml file to robot framework script?
downvote count: 1
type: Question
tagged with: robotframework
score: 3
has answer: http://stackoverflow.com/a/47978196
accepted answer: http://stackoverflow.com/a/47978196
has body: I have Myvariable.yaml file and sample.robot file, I wanted to use the variables from .yaml file to robot file Myvariable.yaml file: ACFC NEWS: Doc_Title: XPath=//div[@class='ng-scope'] Open_Selector: xpath=//button[@class='btn btn-default ng-binding] Sample.robot file ***Settings**** Variables Myvariable.yaml ***Keywords**** Choose Topic: Input Text ${Doc_Title} "Some text" Click Button ${Open_Selector} Error: Variable not found It would be great if any one can help me in solving this issue.
upvote count: 4
answer count: 1
favorite count: 0
tagged with: python

http://stackoverflow.com/a/47878375
answers question: http://stackoverflow.com/q/47878044
score: 0
type: Answer
has body: If you're looking for a a detailed algorithm with similarities to the "Bubble Sort": original = [a,b,c,d,e] order = [1,4,2,2,0] # Initialize list new = [None for x in range(len(original))] for i, item in enumerate(original): idx = order[i] if new[idx] is None: new[idx] = item else: while True: if new[idx] &lt; item: idx += 1 if new[idx] is None: new[idx] = item break else: temp = new[idx] new[idx] = item while True: idx += 1 if new[idx] is None: new[idx] = temp break else: temp2 = new[idx] new[idx] = temp temp = temp2

http://stackoverflow.com/q/47979490
score: 0
has body: I'm trying to send video captured by webcam from a client to a server which should display the video. Unfortunately, my server get the data (I think) but doesn't display it correctly and I don't unerstand why. I only get a small and grey window. The client: import numpy as np import cv2, time import speech_recognition as sr from threading import Thread import socket import pickle host = "localhost" port = 8888 connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connection.connect((host, port)) print("Connextion established on port {}".format(port)) cap = cv2.VideoCapture(0) # while(True): # Capture frame-by-frame while 1: ret, frame = cap.read() ret = str(ret).encode() connection.send(ret) frame = pickle.dumps(frame) connection.send(frame) # When everything done, release the capture cap.release() cv2.destroyAllWindows() And the server #cd C:\Users\Clement\Desktop\pychat\example import numpy as np import cv2 import socket host = '' port = 8888 connexion_principale = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connexion_principale.bind((host, port)) connexion_principale.listen(5) print("The server is listening on port {}".format(port)) connexion_avec_client, infos_connexion = connexion_principale.accept() cap = cv2.VideoCapture("localhost") #Maybe there is a problem here msg_recu = b"" error = 0 while 1: msg_recu1 = connexion_avec_client.recv(1024) msg_recu2 = connexion_avec_client.recv(1024) try: if msg_recu1 != b"": # Capture frame-by-frame ret, frame = bool(msg_recu1.decode()), np.frombuffer(msg_recu2) # Display the resulting frame cv2.imshow('frame',frame) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break except: error +=1 # When everything done, release the capture cap.release() cv2.destroyAllWindows() print("Connection is now closed") connexion_avec_client.close() connexion_principale.close()
has comment: http://stackoverflow.com/comment/82929625
has comment: http://stackoverflow.com/comment/82928674
has comment: http://stackoverflow.com/comment/82929550
type: UnansweredQuestion
tagged with: sockets
tagged with: python
has title: Video tchat with opencv via tcp
tagged with: opencv
tagged with: video
answer count: 0
linked to: http://stackoverflow.com/q/47977474
tagged with: tcp
type: Question
has comment: http://stackoverflow.com/comment/82931319

http://stackoverflow.com/q/47947412
tagged with: variables
has comment: http://stackoverflow.com/comment/82864658
favorite count: 0
type: UnansweredQuestion
score: -3
has answer: http://stackoverflow.com/a/47947448
has title: Variable not defined?
tagged with: python
has comment: http://stackoverflow.com/comment/82864717
has body: Im a very early beginner in python and need some help. The point of the game is to guess a number and if its not right numguesses adds 1. I know the code is not very efficient but i need it for a project. Heres the code: import random from datetime import datetime answer = random.randint(1, 2) guess = 0 now = datetime.now() play = 'y' print 'Welcome to Hi-Lo' print 'The current time is: ' '%s-%s-%s' % (now.year, now.month, now.day) while play != 'n': while guess != answer: guess = int(input('Pick a number inbewteen 1-100 to see if its higher or lower:')) if guess == answer: numguesses = numguesses + 1 print 'You are correct! The number was: ' + str(answer) print 'It took ' + str(numguesses) + ' guess(es)' elif guess &gt; answer: print 'Too high' else: print 'Too low' play = str(input('Play again? [y/n]?')) And the error that it produces is: Traceback (most recent call last): File "C:-----------------------------.py", line 17, in &lt;module&gt; numguesses = numguesses() + 1 NameError: name 'numguesses' is not defined so if somebody could provide a simple explanation for this, i would appreciate it. Thanks!
upvote count: 1
has comment: http://stackoverflow.com/comment/82864645
has answer: http://stackoverflow.com/a/47947453
type: Question
has answer: http://stackoverflow.com/a/47947710
downvote count: 4
answer count: 3
has comment: http://stackoverflow.com/comment/82864641

http://stackoverflow.com/q/47908930
score: 2
has comment: http://stackoverflow.com/comment/82785623
answer count: 0
has comment: http://stackoverflow.com/comment/82857936
downvote count: 0
type: Question
tagged with: multiprocessing
tagged with: infinite-loop
has body: I haven’t coded since college and I’m new to Python so I’m coming at this as a relative novice. My ultimate goal will be to have a gui program that will react based on commands people enter into twitch chat. I have a barebones gui created with tkinter and a bot that will monitor twitch chat. When I run these two components separately in their own .py files they work fine. When they are together in same program it locks up because I have two infinite loops running. I tried threading them but this also didn’t work. I tried using using multiprocess instead of threading, the code for which I’ve included below. I've looked at the other multiprocess and threading questions but I can't seem to figure this out. from tkinter import * # settings contains values for HOST, PORT, NICK, PASS, CHANNEL from settings import * import socket import multiprocessing class Gui: def __init__(self, master): self.master=master master.title("AftA_Bot beta") self.doodle = Canvas(master, width=720, height=576, bg="white") self.doodle.pack() self.out = Button(master, text="Quit", command=master.quit) self.out.pack() class createbot: def __init__(self, server, port, username, token, channel): self.s = socket.socket() self.s.connect((server, port)) self.channel = channel self.s.send(bytes("PASS " + token + "\r\n", "UTF-8")) self.s.send(bytes("NICK " + username + "\r\n", "UTF-8")) self.s.send(bytes("JOIN #" + channel + " \r\n", "UTF-8")) print("Connected to host") # Clear initial connection text while True: line = str(self.s.recv(1024)) if "End of /NAMES list" in line: break print("Initial login text cleared.") def read_chat(self): # Infinite Loop to monitor chat while True: for line in str(self.s.recv(1024)).split('\\r\\n'): parts = line.split(':') if len(parts) &lt; 3: continue message = parts[2][:len(parts[2])] usernamesplit = parts[1].split("!") username = usernamesplit[0] print(username + ": " + message) def send_message(self, msg): self.s.send(bytes("PRIVMSG #" + self.channel + " :" + msg + …
has comment: http://stackoverflow.com/comment/82822092
upvote count: 2
has comment: http://stackoverflow.com/comment/82799977
has comment: http://stackoverflow.com/comment/82860750
tagged with: user-interface
favorite count: 0
type: UnansweredQuestion
tagged with: irc
tagged with: python
has title: Why is my Python multiprocess crashing when I try to run infinite loop along with gui

http://stackoverflow.com/a/47867712
downvote count: 0
has body: You almost had it, $group is a good way to do this. Something like this should work. db.test1.aggregate([ {"$group": { "_id": "$reportId", "usr": {"$sum": "$users"}, "qty": {"$sum": "$quantity"} } }, {"$project": { "_id": 0, "reportId": "$_id", "total": {"$multiply": ["$usr", "$qty"]} }} ]) Firstly we combine all users and quantity and then multiply them. During the group stage you need to accumulate the desired metrics.
has comment: http://stackoverflow.com/comment/82701107
has comment: http://stackoverflow.com/comment/82701146
type: Answer
has comment: http://stackoverflow.com/comment/82701012
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/82701059
answers question: http://stackoverflow.com/q/47866730
has comment: http://stackoverflow.com/comment/82700814
has comment: http://stackoverflow.com/comment/82701004

http://stackoverflow.com/comment/82994661
type: Comment
type: QuestionComment
has text: How did you expect them to change if you don't change them?
comment on: http://stackoverflow.com/q/48012992
score: 0

http://stackoverflow.com/q/47996671
has answer: http://stackoverflow.com/a/47998027
downvote count: 0
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/82961521
has answer: http://stackoverflow.com/a/47996737
answer count: 3
has answer: http://stackoverflow.com/a/47996829
favorite count: 0
has title: How to check the condition of a list during list comprehension?
type: UnansweredQuestion
score: 5
has body: Say I have a list of three words and I want to generate a list containing the characters in the word. This can be achieved easily using for-loops or list-comprehension: wordList = ["one", "two", "three"] letterList = [] # Solution 1: for word in wordList: for letter in word: letterList.append(letter) # Solution 2: letterList = [letter for word in wordList for letter in word] print(letterList) # Prints: ['o', 'n', 'e', 't', 'w', 'o', 't', 'h', 'r', 'e', 'e'] However, when this problem is made more difficult, I am unable to find a solution using a list-comprehension. For example, assume I want to generate the previous list, but I also want any duplicate characters to be removed. I can do this using for-loops: wordList = ["one", "two", "three"] letterList = [] for word in wordList: for letter in word: if letter not in letterList: letterList.append(letter) print(letterList) # Prints: ['o', 'n', 'e', 't', 'w', 'h', 'r'] So, my question is: How do I check to see if an item is in the list being build during a list comprehension? Or put more simply: How do I do the above using list-comprehensions?
tagged with: python
upvote count: 5
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/82961982
type: Question

http://stackoverflow.com/comment/82794731
type: Comment
type: QuestionComment
has text: If the file object goes out of scope then python will close it. If I modify your first example to: jsonda = json.loads(open('./myConfig.cfg').read()) then the file object goes out of scope right away and there is nothing to call close() on.
score: 0
comment on: http://stackoverflow.com/q/47913291

http://stackoverflow.com/q/47970263
downvote count: 1
has answer: http://stackoverflow.com/a/47970332
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82909888
tagged with: python
upvote count: 0
type: Question
has comment: http://stackoverflow.com/comment/82909897
score: -1
has body: import os, sys, math, pygame, pygame.mixer from pygame.locals import * class Unit(): def __init__(self): self.last = pygame.time.get_ticks() self.cooldown = 3000 def wait(self): now = pygame.time.get_ticks() if now - self.last &gt;= self.cooldown: screen.fill(black) black = (0,0,0) red = (255,0,0) green = (0,255,0) blue = (0,0,255) white = (255,255,255) run_me = True stage1 = 1 stage2 = 1 stage3 = 1 stage4 = 1 st1 = True st2 = True st3 = True st4 = True screen_size = screen_width, screen_height = 600, 400 screen = pygame.display.set_mode(screen_size) pygame.display.set_caption('ha ha ha ha ha') clock = pygame.time.Clock() fps_limit = 60 while run_me: clock.tick(fps_limit) if stage1 == 1: screen.fill(red) wait(self) for event in pygame.event.get(): if event.type == pygame.QUIT: run_me = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: screen.fill(red) stage2 - 1 if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: screen.fill(black) stage1 - 1 if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: screen.fill(blue) stage1 - 1 if event.type == pygame.KEYDOWN: if event.key == pygame.K_DOWN: screen.fill(green) stage1 - 1 if stage1 == 0: run_me = False pygame.display.flip() pygame.quit() when I run this code it outputs "wait is not defined" how can I fix this and make the code make the screen red then black again. this should have a 3 second gap. I'm not good with functions and I would really like some help. also if you have enough time can you send me a guide for functions. I will be most greatful.
has title: When i try and use the function "wait", it doesn't work
answer count: 1

http://stackoverflow.com/q/48007535
tagged with: django
type: Question
has title: Trying to understand JSONField for django postgresql
type: AnsweredQuestion
score: 3
answer count: 2
has answer: http://stackoverflow.com/a/48010986
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/65145432
tagged with: python
has body: I'm reading the docs on JSONField, a special postgresql field type. Since I intend to create a custom field that subclasses JSONField, with the added features of being able to convert my Lifts class: class Lifts(object): def __init__(self, series): for serie in series: if type(serie) != LiftSerie: raise TypeError("List passed to constructor should only contain LiftSerie objects") self.series = series class AbstractSerie(object): def __init__(self, activity, amount): self.activity_name = activity.name self.amount = amount def pre_json(self): """A dict that can easily be turned into json.""" pre_json = { self.activity_name: self.amount } return pre_json def __str__(self): return str(self.pre_json()) class LiftSerie(AbstractSerie): def __init__(self, lift, setlist): """ lift should be an instance of LiftActivity. setList is a list containing reps for each set that has been performed. """ if not (isinstance(setlist, collections.Sequence) and not isinstance(setlist, str)): raise TypeError("setlist has to behave as a list and can not be a string.") super().__init__(lift, setlist) I've read here that to_python() and from_db_value() are two methods on the Field class that are involved in loading values from the database and deserializing them. Also, in the docstring of the to_python() method on the Field class, it says that it should be overridden by subclasses. So, I looked in JSONField. Guess what, it doesn't override it. Also, from_db_value() isn't even defined on Field (and not on JOSNField either). So what is going on here? This is making it very hard to understand how JSONField takes values and turns them into json and stores them in the database, and then the opposite when we query the database. A summary of my questions: Why isn't to_python() overridden in JSONField? Why isn't from_db_value() overridden in JSONField? Why isn't from_db_value() even defined on Field? How does JSONField go about taking a python dict for example, converting it to a JSON string, and stor…
accepted answer: http://stackoverflow.com/a/48010986
possible better answer: http://stackoverflow.com/a/65145432
upvote count: 3

http://stackoverflow.com/comment/82820232
score: 0
comment on: http://stackoverflow.com/a/47925802
type: AnswerComment
type: Comment
has text: Listen, I dont want to use copy every time, I want a copy made when I reference the object. can you just please tell me how to accomplish this if you know?

http://stackoverflow.com/a/47963850
answers question: http://stackoverflow.com/q/47955745
downvote count: 1
score: -1
upvote count: 0
has body: So I found the reason why I didn’t get the same output. Sklearn function does not standarize your data while R facanal() does. I had to scale my data in order to get similar outputs. Another question would be why this makes such a big difference when I am working with log returns and not prices.
type: Answer

http://stackoverflow.com/q/47960521
has answer: http://stackoverflow.com/a/52598142
favorite count: 0
score: 16
type: Question
has answer: http://stackoverflow.com/a/78567203
has answer: http://stackoverflow.com/a/73482822
tagged with: python
has answer: http://stackoverflow.com/a/71172664
upvote count: 16
has answer: http://stackoverflow.com/a/64031345
answer count: 11
has answer: http://stackoverflow.com/a/68187355
has answer: http://stackoverflow.com/a/49765709
tagged with: visual-studio-code
has title: Python unit tests not discovered in VSCode
has answer: http://stackoverflow.com/a/63241411
tagged with: python-unittest
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/68412798
has answer: http://stackoverflow.com/a/73247875
has answer: http://stackoverflow.com/a/63448215
downvote count: 0
has body: I've written a python test file called scraping_test.py, with a single test class, using unittest, called TestScrapingUtils """Tests for the scraping app""" import unittest from bs4 import BeautifulSoup as bs4 from mosque_scraper.management.commands import scraping_utils from mosque_scraper.selectors import MOSQUE_INFO_ROWS_SELECTOR class TestScrapingUtils(unittest.TestCase): """Test scraping_utils.py """ def setup(self): """Setup McSetupface.""" pass def test_get_keys_from_row(self): """ Test that we extract the correct keys from the supplied rows.""" test_page_name = "test_page.html" with open(test_page_name) as test_page_file: test_mosque = bs4(test_page_file, 'html.parser') rows = test_mosque.select(MOSQUE_INFO_ROWS_SELECTOR) field_dict = scraping_utils.get_fields_from_rows(rows) self.assertDictEqual(field_dict, {}) My settings for unit tests are: { "python.unitTest.unittestEnabled": true, "python.unitTest.unittestArgs": [ "-v", "-s", ".", "-p", "*test.py" ] } It looks like it should work, but when I click to run the tests in VSCode it says that no tests were discovered: No tests discovered, please check the configuration settings for the tests. How do I make it work?

http://stackoverflow.com/q/47963586
has answer: http://stackoverflow.com/a/47963607
favorite count: 0
tagged with: beautifulsoup
has title: IDLE text editor/Python2.7/Mac OS X/ "URLError: <urlopen error no host given>"
score: -2
type: UnansweredQuestion
downvote count: 2
tagged with: urlopen
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/82896567
has body: I put in this script to IDLE 2.7.14 import urllib2 from bs4 import BeautifulSoup quote_page = 'http:www.bloomberg.com/quote/SPX:IND' page = urllib2.urlopen(quote_page) Traceback: Traceback (most recent call last): "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py ", line 1126, in do_request_ raise URLError('no host given') URLError: &lt;urlopen error no host given&gt; &gt;&gt;&gt; Backstory: I installed and uninstalled BeautifulSoup, Pycharm, and downloaded Python 2x earlier...
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82896575

http://stackoverflow.com/q/47944860
tagged with: xml-rpc
accepted answer: http://stackoverflow.com/a/48060063
has title: Xmlrpc error from a client when using a string
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has body: My use case is : a client sends data via xmlrpc the xmlrpc server retrieves these data so the function is called with it as parameters The code as reproduced here gives the following error : Traceback (most recent call last): File "rpcclient.py", line 37, in &lt;module&gt; s.on(pinaddr) File "/usr/lib/python3.5/xmlrpc/client.py", line 1092, in __call__ return self.__send(self.__name, args) File "/usr/lib/python3.5/xmlrpc/client.py", line 1432, in __request verbose=self.__verbose File "/usr/lib/python3.5/xmlrpc/client.py", line 1134, in request return self.single_request(host, handler, request_body, verbose) File "/usr/lib/python3.5/xmlrpc/client.py", line 1150, in single_request return self.parse_response(resp) File "/usr/lib/python3.5/xmlrpc/client.py", line 1322, in parse_response return u.close() File "/usr/lib/python3.5/xmlrpc/client.py", line 655, in close raise Fault(**self._stack[0]) xmlrpc.client.Fault: &lt;Fault 1: "&lt;class 'SystemError'&gt;:&lt;built-in function setup&gt; returned NULL without setting an error"&gt; my tests and tries : from the server code below : print(type(pin_address)) returns class 'str' so this is fine. if I call the function hard coded server side : GPIO.setup("P8_45", GPIO.OUT) it's fine as well if I use print(s.on("P8_45")) : it's ok. It's left commented in the code if I force pinaddr = "p8_45" client side, it fails. It's left commented in the code The CLI line is : python3 rpcclient.py -s 192.168.1.2 on -p p8_45 the client code #!/usr/bin/env python3 # -*- coding: utf-8 -*- import xmlrpc.client import argparse import time RPC_PORT = 1234 RPC_HOSTNAME = "####" parser = argparse.ArgumentParser() parser.add_argument("-s", "--server", help="Specify ACME Hostname") parser.add_argument("-p", "--pinaddress", help="Specify which pin to use") parser.add_argument("command", help="ACME Command, use 'help' to get all commands") parser.add_argument("args", nargs='?', help="ACME Command Arguments") args = parser.parse_args() if args.server: s…
tagged with: python
has answer: http://stackoverflow.com/a/48060063
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/q/47856289
has body: My Mid-2014 Macbook Pro has a strange issue. It shuts off at seemingly random points, the issue is detailed here by another user. It seems to be an issue where the CPU core becomes unstable because the voltage drops too low. The only way that I have found that prevents the issue 100% of the time is the following script from time import sleep while True: sleep(0.00002) This works but it uses 15-20% CPU, not a big issue but I was wondering if there's a more efficient way to do it. I tried to doing a similar thing in Swift: DispatchQueue.global(qos: .background).async { while true { Thread.sleep(forTimeInterval: 0.00002) } } It uses less CPU (3-5%) and the system seems to run a little bit more stable but it still occasionally shuts off. Any ideas of other approaches I can try?
answer count: 0
has comment: http://stackoverflow.com/comment/82822636
type: UnansweredQuestion
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82813610
type: Question
tagged with: sleep
downvote count: 0
tagged with: macos
favorite count: 0
tagged with: xcode
tagged with: python
has title: Efficient way to prevent CPU from idling
tagged with: swift

http://stackoverflow.com/a/48104560
type: Answer
has body: The correct recipe to run the PUB/SUB pattern (regardless of language) is: Pub socket(zmq.PUB) bind("tcp://127.0.0.1:5555") encoding (usually just encode() for strings but you can also compress() or dumps() for objects or even both) encoded_topic = topic.encode() encoded_msg = msg.encode() send_multipart([encoded_topic, encoded_msg]) Sub socket(zmq.SUB) setsockopt(zmq.SUBSCRIBE, topic.encode()) connect("tcp://127.0.0.1:5555") answer = recv_multipart() decode the answer enc_topic, enc_msg = answer topic = enc_topic.decode() msg = enc_msg.decode() In general, steps Pub - 2 / Sub - 3 (ie bind/connect) and Pub - 3 / Sub - 5 (ie encode/decode or dumps/loads) need to be complementary to each other in order for things to work.
upvote count: 2
answers question: http://stackoverflow.com/q/47971907
score: 2
downvote count: 0

http://stackoverflow.com/a/47863877
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82714153
has body: Here's a quick and dirty solution using list-comprehensions, if you want to stick with functional constructs (comprehensions being favored in Python over map and filter): import operator as op x = [[1],[2],[3]] # Notice the dimensions! A = [[1,1,1], [2,2,2], [3,3,3]] def matrix_mult(A, X): return [ [sum(map(op.mul, row, col)) for col in zip(*X)] for row in A ] To see in action: In [17]: A Out[17]: [[1, 1, 1], [2, 2, 2], [3, 3, 3]] In [18]: x Out[18]: [[1], [2], [3]] In [19]: matrix_mult(A, x) Out[19]: [[6], [12], [18]]
has comment: http://stackoverflow.com/comment/82714318
has comment: http://stackoverflow.com/comment/82716337
type: Answer
has comment: http://stackoverflow.com/comment/82714432
downvote count: 0
has comment: http://stackoverflow.com/comment/82716594
score: 1
answers question: http://stackoverflow.com/q/47863243
has comment: http://stackoverflow.com/comment/82714528
has comment: http://stackoverflow.com/comment/82711748
accepted answer of: http://stackoverflow.com/q/47863243
has comment: http://stackoverflow.com/comment/82714122
has comment: http://stackoverflow.com/comment/82716380
has comment: http://stackoverflow.com/comment/82714473
has comment: http://stackoverflow.com/comment/82711046
has comment: http://stackoverflow.com/comment/82716622
upvote count: 1

http://stackoverflow.com/q/48011604
upvote count: 1
tagged with: python
tagged with: opencv
tagged with: tracking
score: 1
linked to: http://stackoverflow.com/q/36439902
type: Question
tagged with: video-streaming
has answer: http://stackoverflow.com/a/48012696
tagged with: raspberry-pi3
has title: Deep learning person detection with opencv
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/34871294
has body: so I'm really new here. Currently working on a public art project where I need a little help with the programming because I'm kind off lost between codes. First I'll give you a short description of the goal of the work and then state my problem. I'm putting a webcam in the shopwindow of a gallery that is facing out on a public street. This webcam is connected to a tv screen that is facing outwards on the street so people see themselves being filmed (like cctv). Then if people stand still long enough for the camera the webcam makes an automatic screenshot what will be emailed to a site which hold a script for automatic attachment printing and the people from the street instantly come in to my gallery, on paper. (and yes I have permission from the gallery to do this since it is slightly in the grey area of legality) I come from a art background with interest in programming so this was all very very new for me and made it already quite far I think. I have a raspberry pi running with open cv and put a script on it for deep learning object detection (https://www.pyimagesearch.com/2017/09/18/real-time-object-detection-with-deep-learning-and-opencv/) &lt; the link I used for that. I also come across loads of pedestrian tracking but did not find a suitable code yet for a real time video stream. So what I need from you guys, is a little help with how to make a timer in the script so that when people stand still long enough for the camera, it wil make the screenshot. It is a bit like reversed security cams script because they react on movement and I want it to react to no movement at all. The automatic attachment printing part I got covered I think because there are a lot of scripts already on the internet. If you have any tips or tricks.. please let me know. Help a girl out! Marije

http://stackoverflow.com/comment/82812170
comment on: http://stackoverflow.com/q/47922235
score: 0
type: QuestionComment
type: Comment
has text: You should at least be able to implement a straight forward solution using a dictionary and a `for` loop.

http://stackoverflow.com/a/47894920
answers question: http://stackoverflow.com/q/47894861
score: 5
has body: IIUC: df.assign(**df['Info'].str.split(',', expand=True).add_prefix('Info_')) Output: Name Info Info_0 Info_1 Info_2 Info_3 0 Mike a, b, c, d a b c d 1 Joe a, f, z a f z None Note: You can also use join instead of assign (Using @coldspeed \s* to elimate spaces): df.join(df['Info'].str.split('\s*,\s*', expand=True).add_prefix('Info_'))
upvote count: 5
type: Answer
downvote count: 0

http://stackoverflow.com/comment/82889628
comment on: http://stackoverflow.com/q/47959954
type: QuestionComment
has text: Somewhat related https://stackoverflow.com/questions/12935241/python-call-instance-method-using-func
score: 0
type: Comment

http://stackoverflow.com/q/47873019
upvote count: 8
type: Question
has title: Does the base for logarithmic calculations in Python influence the speed?
score: 7
has answer: http://stackoverflow.com/a/47874195
tagged with: logarithm
has comment: http://stackoverflow.com/comment/82712138
has body: I have to use a lot of logarithmic calculations in one program. In terms of the logarithmic base, the procedure is not specific. I was wondering, if any base n (2? 10? e?) is faster in the Python 3.5 math module than others, because maybe under the hood all other bases a are transformed into log_a(x) = log_n(x)/log_n(a). Or does the choice of the base not influence the speed of the calculation, because all bases are implemented in the same way using a C library?
has comment: http://stackoverflow.com/comment/82711975
answer count: 2
has comment: http://stackoverflow.com/comment/82711510
has comment: http://stackoverflow.com/comment/82712036
downvote count: 1
possible better answer: http://stackoverflow.com/a/47873516
favorite count: 0
has answer: http://stackoverflow.com/a/47873516
tagged with: python
linked to: http://stackoverflow.com/q/5476189
has comment: http://stackoverflow.com/comment/82711549
has comment: http://stackoverflow.com/comment/82711734
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82711444
has comment: http://stackoverflow.com/comment/82712345
has comment: http://stackoverflow.com/comment/82711612
accepted answer: http://stackoverflow.com/a/47874195

http://stackoverflow.com/q/47928839
has comment: http://stackoverflow.com/comment/82827358
upvote count: 3
tagged with: random
has comment: http://stackoverflow.com/comment/82826507
has comment: http://stackoverflow.com/comment/82826450
tagged with: string
has title: How to create a hill climbing algorithm
favorite count: 0
tagged with: hill-climbing
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82827585
tagged with: python
has body: I have been following a book for learning python, and the book has one of the following challenge: Self Check Here’s a self check that really covers everything so far. You may have heard of the infinite monkey theorem? The theorem states that a monkey hitting keys at random on a typewriter keyboard for an infinite amount of time will almost surely type a given text, such as the complete works of William Shakespeare. Well, suppose we replace a monkey with a Python function. How long do you think it would take for a Python function to generate just one sentence of Shakespeare? The sentence we’ll shoot for is: “methinks it is like a weasel” You’re not going to want to run this one in the browser, so fire up your favorite Python IDE. The way we’ll simulate this is to write a function that generates a string that is 28 characters long by choosing random letters from the 26 letters in the alphabet plus the space. We’ll write another function that will score each generated string by comparing the randomly generated string to the goal. A third function will repeatedly call generate and score, then if 100% of the letters are correct we are done. If the letters are not correct then we will generate a whole new string.To make it easier to follow your program’s progress this third function should print out the best string generated so far and its score every 1000 tries. I was able to implement this part of the challenge, with the following code: (I am new to python) import random target = 'methinks it is like a weasel' target_len = 28 def string_generate(strlen): alphabet = 'abcdefghijklmnopqrstuvwxyz ' #26 letters of the alphabet + space res = '' for i in range(strlen): res += alphabet[random.randrange(27)] return res def score_check(target,strlen): score = 0 res = string_generate(strlen) for i in range(strlen): if res[i] == target[i]: score += 1 return score, res def progress_check(): counter = 0 score = 0 res = '' while score != 28: score_temp, res_temp = score_check(target,…
score: 3
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/82827554
type: Question
has comment: http://stackoverflow.com/comment/82826543
tagged with: algorithm
has comment: http://stackoverflow.com/comment/82826294

http://stackoverflow.com/q/47890232
type: Question
score: 5
has title: Why are the parallel tasks always slow at the first time?
has comment: http://stackoverflow.com/comment/82746746
has body: I have some classifiers which I want to evaluate on the one sample. This task can be ran in parallel since they are independent of each other. This means that I want to parallelize it. I tried it with python and also as a bash script. The problem is that when I run it the program for the first time, it takes like 30s-40s to finish. When I run the program multiple times consecutively, it takes just 1s-3s to finish. Even If I fed classifiers with different input I got different result so it seems that there is no caching. When I run some other program and afterwards rerun the program then it again takes 40s to finish. I also observed in htop that CPUs are not that much utilized when the program is run for the first time but then when I rerun it again and again the CPUs are fully utilized. Can someone please explain me this strange behaviour? How can I avoid it so that even the first run of the program will be fast? Here is the python code: import time import os from fastText import load_model from joblib import delayed, Parallel, cpu_count import json os.system("taskset -p 0xff %d" % os.getpid()) def format_duration(start_time, end_time): m, s = divmod(end_time - start_time, 60) h, m = divmod(m, 60) return "%d:%02d:%02d" % (h, m, s) def classify(x, classifier_name, path): f = load_model(path + os.path.sep + classifier_name) labels, probabilities = f.predict(x, 2) if labels[0] == '__label__True': return classifier_name else: return None if __name__ == '__main__': with open('classifier_names.json') as json_data: classifiers = json.load(json_data) x = "input_text" Parallel(n_jobs=cpu_count(), verbose=100, backend='multiprocessing', pre_dispatch='all') \ (delayed(perform_binary_classification) (x, classifier, 'clfs/') for classifier in classifiers) end_time = time.time() print(format_duration(start_time, end_time)) Here is the bash code: #!/usr/bin/env bash N=4 START_TIME=$SECONDS open_sem(){ mkfifo pipe-$$ exec 3&lt;&gt;pipe-$$ rm pipe-$$ local i=$1 for((;i&gt;0;i--)); d…
has comment: http://stackoverflow.com/comment/82747585
tagged with: bash
has comment: http://stackoverflow.com/comment/82751583
has comment: http://stackoverflow.com/comment/82748850
has comment: http://stackoverflow.com/comment/82747215
answer count: 1
tagged with: joblib
has comment: http://stackoverflow.com/comment/82747358
favorite count: 0
has answer: http://stackoverflow.com/a/68940199
has comment: http://stackoverflow.com/comment/82810685
has comment: http://stackoverflow.com/comment/82748098
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82773762
tagged with: python
upvote count: 6
tagged with: parallel-processing
linked to: http://stackoverflow.com/q/32923451
downvote count: 1

http://stackoverflow.com/comment/82800027
type: Comment
comment on: http://stackoverflow.com/a/47915639
has text: Yup! That was it. I guess I just didn't realize i typed python and not python3 at the terminal. So I was in fact using 2 different versions. I know about //, just didn't know why I was seeing the discrepancy. Thanks all! -John
type: AnswerComment
score: 0

http://stackoverflow.com/comment/140031572
has text: I created a tiny Python package to speed up loading pandas to SQL Server, internally the package uses .Net's SqlBulkCopy to load data very quickly, even faster than using fast_executemany=True. See https://github.com/RusselWebber/arrowsqlbcpy
comment on: http://stackoverflow.com/a/48861231
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/47984780
has body: When you call a decorator with arguments, the function you call isn't actually working as a decorator itself. Rather, it's a decorator factory (a function or other callable that returns something that will act as the decorator). Usually you solve this by adding an extra level of nested functions. Since you're defining your decorator with a class, that's a bit awkward to do directly (though you probably could make it work). But there doesn't really seem to be any need for your decorator to be a class, as long as you handle self in the wrapper function (it will be the instance of MyClass now, rather than an instance of a Decorator class): class MyClass: def __init__(self): self.start = 0 def decorator_factory(msg): def decorator(f): def wrapper(self, test): # you might want to replace test with *args and **kwargs print(msg) print(self.start) return f(self, test) return wrapper return decorator @decorator_factory(msg='p1') def p1(self, sent): print(sent) @decorator_factory(msg='p2') def p2(self, sent): print(sent) I named the decorator factory the way I did to be explicit about the different levels of nested functions, but you should of course use something that's actually meaningful for your use case as the top level name. You might also want to move it out of the class namespace, since it will be available to call on all instances of MyClass (with possibly silly results, since it's not intended to be a method).
upvote count: 1
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/47984103
score: 1

http://stackoverflow.com/q/47969721
has answer: http://stackoverflow.com/a/47969823
linked to: http://stackoverflow.com/q/14692690
has body: I have this path that can change from time to time: '#/path/to/key' The parts of the path aren't defined, so this value is also fine '#/this/is/a/longer/path' I'm splitting this key at '/' so I get ['#', 'path', 'to', 'key'] and I need to get to the key in this path, let's say my dict is exp, so I need to get to here: exp['path']['to']['key'] how could I possibly know how to get to this key?
accepted answer: http://stackoverflow.com/a/47969823
answer count: 7
duplicate of: http://stackoverflow.com/q/14692690
upvote count: 6
favorite count: 0
has answer: http://stackoverflow.com/a/47969874
has answer: http://stackoverflow.com/a/47969764
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/56228938
type: AnsweredQuestion
has title: get dictionary key by path (string)
possible better answer: http://stackoverflow.com/a/56228938
has answer: http://stackoverflow.com/a/47969787
has answer: http://stackoverflow.com/a/65500038
downvote count: 1
has answer: http://stackoverflow.com/a/47969772
type: Question
score: 5

http://stackoverflow.com/comment/85444938
comment on: http://stackoverflow.com/a/48160523
type: Comment
score: 0
type: AnswerComment
has text: Perfect, that was a great help!

http://stackoverflow.com/comment/82903450
type: Comment
type: QuestionComment
score: 0
has text: I don't understand why you've written a custom backend here at all. It doesn't do anything different from the default one. You should remove it.
comment on: http://stackoverflow.com/q/47965313

http://stackoverflow.com/q/47911749
upvote count: 1
tagged with: python
tagged with: jinja2
accepted answer: http://stackoverflow.com/a/47911847
tagged with: google-cloud-datastore
has body: I am trying to output the results of a query into an HTML table and put a link next to it that deletes the entity. How do I retrieve the ID of each entity from the datastore so that the delete link knows which entity it needs to delete?. I am using Python/Webapp2/Jinja2. HTML: {{ result.email }} {{ result.date }} {{ result.title }} {{ result.content }} <a href="/delete/{{ ID GOES HERE }}" Python: class MyRequestsHandler(webapp2.RequestHandler): # Queries the datastore def get(self): user = users.get_current_user() userIdentity = users.get_current_user().user_id() #email = users.get_current_user().email() login_url = users.create_login_url(self.request.path) logout_url = users.create_logout_url(self.request.path) q = WorkRequest.query(WorkRequest.userId == userIdentity) results = q.fetch(10) template = template_env.get_template('myrequests.html') context = { 'user': user, 'login_url': login_url, 'logout_url': logout_url, 'results': results, } self.response.out.write(template.render(context))
downvote count: 0
answer count: 1
type: Question
type: AnsweredQuestion
has title: Retrieve ID from entity in datastore
has comment: http://stackoverflow.com/comment/82791138
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47911847
has comment: http://stackoverflow.com/comment/82791226
tagged with: google-app-engine

http://stackoverflow.com/comment/82914162
score: 0
type: AnswerComment
has text: The problem comes if you are no longer inside a function.
type: Comment
comment on: http://stackoverflow.com/a/47972153

http://stackoverflow.com/q/47982884
has comment: http://stackoverflow.com/comment/82934325
duplicate of: http://stackoverflow.com/q/240178
has title: Adding n different lists to list results same list repeating
tagged with: list
has body: When I add lists to my list the result is list of correct length, but all the lists are the same, last list I added code: cycle_points = [] for i in range(games_per_cycle): points = game.game_cycle() print(points) cycle_points.append(points) print(cycle_points) When changing cycle_points = [] to cycle_points = [[] for n in range(games_per_cycle)] as suggested here, has no effect. sample output: [26.0, 26.0, 2.0, 22.0, 12.0] [7.0, 23.0, 19.0, 1.0, 2.0] [21.0, 28.0, 2.0, 12.0, 2.0] [17.0, 26.0, 4.0, 25.0, 4.0] [1.0, 30.0, 22.0, 15.0, 20.0] [0.0, 19.0, 23.0, 6.0, 24.0] [17.0, 15.0, 24.0, 2.0, 35.0] [27.0, 5.0, 15.0, 17.0, 4.0] [2.0, 24.0, 6.0, 26.0, 14.0] [27.0, 11.0, 5.0, 12.0, 26.0] [[27.0, 11.0, 5.0, 12.0, 26.0], [27.0, 11.0, 5.0, 12.0, 26.0], [27.0, 11.0, 5.0, 12.0, 26.0], [27.0, 11.0, 5.0, 12.0, 26.0], [27.0, 11.0, 5.0, 12.0, 26.0], [27.0, 11.0, 5.0, 12.0, 26.0], [27.0, 11.0, 5.0, 12.0, 26.0], [27.0, 11.0, 5.0, 12.0, 26.0], [27.0, 11.0, 5.0, 12.0, 26.0], [27.0, 11.0, 5.0, 12.0, 26.0]] Full code here https://github.com/aoskarih/5wonders/blob/master/main.py if it helps.
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/82934484
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/82936355
linked to: http://stackoverflow.com/q/240178
favorite count: 0
duplicate of: http://stackoverflow.com/q/2612802
upvote count: 2
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/82804814
has text: it seems to be some memory issue or else. After restarting the machine and executing the code previously throwing error worked.
type: AnswerComment
comment on: http://stackoverflow.com/a/47906719
score: 0
type: Comment

http://stackoverflow.com/a/47874663
has body: By ImportanceOfBeingErnest's help in comments, I was able to solve the problem. I decided to share my code for others: import matplotlib # Make sure that we are using QT5 matplotlib.use('Qt5Agg') import matplotlib.pyplot as plt from PyQt5 import QtWidgets from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar class ScrollableWindow(QtWidgets.QMainWindow): def __init__(self, fig): self.qapp = QtWidgets.QApplication([]) QtWidgets.QMainWindow.__init__(self) self.widget = QtWidgets.QWidget() self.setCentralWidget(self.widget) self.widget.setLayout(QtWidgets.QVBoxLayout()) self.widget.layout().setContentsMargins(0,0,0,0) self.widget.layout().setSpacing(0) self.fig = fig self.canvas = FigureCanvas(self.fig) self.canvas.draw() self.scroll = QtWidgets.QScrollArea(self.widget) self.scroll.setWidget(self.canvas) self.nav = NavigationToolbar(self.canvas, self.widget) self.widget.layout().addWidget(self.nav) self.widget.layout().addWidget(self.scroll) self.show() exit(self.qapp.exec_()) import matplotlib.pyplot as plt import numpy as np import pandas from matplotlib.table import Table def main(): MY_List=[[1,2,5,56,6,7,7,7,7,5],[3,4,5,5,5,5,5,5,5,8],[4,5,6,6,7,7,4,3,4,2],[4,7,2,3,4,5,6,78,8,9],[3,4,5,5,6,6,6,7,77,7],[1,2,3,3,4,5,6,6,7,7], [3,4,4,5,5,5,4,4,4,4],[2,2,4,4,5,5,5,5,5,5],[2,2,3,3,4,4,3,2,3,3],[3,3,3,4,5,5,6,7,8,9],[1,1,2,3,4,5,6,6,7,8],[3,4,5,6,7,8,9,98,7,7]] data = pandas.DataFrame(MY_List) checkerboard_table(data) plt.show() def checkerboard_table(data, fmt='{:.2f}', bkg_colors=['C', 'white']): MY_List=[[1,2,5,56,6,7,7,7,7,5],[3,4,5,5,5,5,5,5,5,8],[4,5,6,6,7,7,4,3,4,2],[4,7,2,3,4,5,6,78,8,9],[3,4,5,5,6,6,6,7,77,7],[1,2,3,3,4,5,6,6,7,7], [3,4,4,5,5,5,4,4,4,4],[2,2,4,4,5,5,5,5,5,5],[2,2,3,3,4,4,3,2,3,3],[3,3,3,4,5,5,6,7,8,9],[1,1,2,3,4,5,6,6,7,8],[3,4,5,6,7,8,9,98,7,7]] # create a figure and some subplots fig, ax = plt.subplots(figsize=(len(MY_List[0])*0…
type: Answer
accepted answer of: http://stackoverflow.com/q/47872845
answers question: http://stackoverflow.com/q/47872845
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/82765250
has text: HIveContext is deprecated, you shouldn't rely on it. Sql function returns you a dataframe anyway. The advantage here is your dataframe is a lazy object of the whole table, not just the count of the rows.
score: 1
comment on: http://stackoverflow.com/a/47898455
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47973352
has title: Not clicking tabs TimeoutException(message, screen, stacktrace)
has comment: http://stackoverflow.com/comment/82921651
tagged with: python
tagged with: selenium-webdriver
score: 0
tagged with: selenium
has comment: http://stackoverflow.com/comment/82918298
type: Question
has comment: http://stackoverflow.com/comment/82918401
has comment: http://stackoverflow.com/comment/82918820
has body: I have a script below that clicks some buttons then it gives: line 41, in clickMe = wait(driver, 15).until(EC.element_to_be_clickable((By.XPATH,'(//*[@class="KambiBC-collapsible-container KambiBC-mod-event-group-container"])[%s]' % str(index + 1)))) line 80, in until raise TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message: I've tried changing the xpath to //*[@class="KambiBC-mod-event-group-header__event-count"] and increasing wait time. But it keeps giving this error message. Any idea how I can get around this so I can click all the tabs on that page? from random import shuffle from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait as wait driver = webdriver.Chrome() driver.set_window_size(1024, 600) driver.maximize_window() driver.get('https://www.unibet.com.au/betting#filter/football') options = driver.find_elements_by_xpath('//div[@class="KambiBC-collapsible-container KambiBC-mod-event-group-container"]') def page_counter(): for x in range(1000): yield x count = page_counter() clickMe = wait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, ('//div[@class="KambiBC-collapsible-container KambiBC-mod-event-group-container"]')))) #//*[@class="KambiBC-mod-event-group-header__event-count"] import collections coupon_lables = driver.find_elements_by_xpath('//div[@class="KambiBC-collapsible-container KambiBC-mod-event-group-container"]') coupon_lables = [index for index in range(len(coupon_lables))] shuffle(coupon_lables) links = dict((next(count) + 1, e) for e in coupon_lables) desc_links = collections.OrderedDict(sorted(links.items(), reverse=True)) for key, index in desc_links.items(): clickMe = wait(driver, 15).until(EC.element_to_be_clickable((By.XPATH,'(//*[@class="KambiBC-collapsible-container KambiBC-mod-event-group-container"])[%s]' % str(index + 1)))) driver.execute_sc…
has comment: http://stackoverflow.com/comment/82922185
tagged with: xpath
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82917938
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/82833085
comment on: http://stackoverflow.com/q/47930144
has text: If you set an index on `ID` before the OLS, you'll get back an indexed result after the `fit()` method. Try it, then when you add it back to the frame, it will implicitly align on your index.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47964186
has answer: http://stackoverflow.com/a/47964407
has answer: http://stackoverflow.com/a/47964494
linked to: http://stackoverflow.com/q/41957574
score: 1
tagged with: set
has body: Say you have a function f:integers -&gt; integers, one should be able to lift this function to act on sets of integers. I.e. f:sets of integers -&gt; sets of integers, by f({a,b,...}) = {f(a),f(b),...} How can one do this succinctly in python? That is, not involving iterables (loops), potentially something more native and order-independent. I would expect f({a,b,...}) to be the syntax, but it's not. Maybe something like act(f,{a,b,...})?
accepted answer: http://stackoverflow.com/a/47964272
type: Question
possible better answer: http://stackoverflow.com/a/47964407
has comment: http://stackoverflow.com/comment/82897946
tagged with: function
downvote count: 0
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/82898063
favorite count: 0
has comment: http://stackoverflow.com/comment/82898113
has title: lifting functions in python
has comment: http://stackoverflow.com/comment/82898569
answer count: 5
has comment: http://stackoverflow.com/comment/82898196
has answer: http://stackoverflow.com/a/47964272
has answer: http://stackoverflow.com/a/71924402
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47964438
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82897965

http://stackoverflow.com/a/48250488
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47975155
answers question: http://stackoverflow.com/q/47975155
has body: I think that you are on the right track using dask.delayed. However calling list on the series is probably not ideal. I would create a function that converts one of your series into a numpy array and then go through delayed with that. def convert_series_to_array(pandas_series): # make this as fast as you can ... return numpy_array L = dask_series.to_delayed() L = [delayed(convert_series_to_array)(x) for x in L] arrays = [da.from_delayed(x, shape=(np.nan, 300), dtype=...) for x in L] x = da.concatenate(arrays, axis=0) Also, regarding this line: da = delayed(dask.array.concatenate)(pt, axis=1) You should never call delayed on a dask function. They are already lazy.
type: AcceptedAnswer
downvote count: 0

jinja2
tags question: http://stackoverflow.com/q/48002297
tags question: http://stackoverflow.com/q/47983667
tags question: http://stackoverflow.com/q/47998764
tags question: http://stackoverflow.com/q/47994685
tags question: http://stackoverflow.com/q/47911749
tags question: http://stackoverflow.com/q/47952952
type: Tag
tags question: http://stackoverflow.com/q/47991528
tags question: http://stackoverflow.com/q/48009241
tag name: jinja2
tags question: http://stackoverflow.com/q/47913278
tags question: http://stackoverflow.com/q/47920845

http://stackoverflow.com/comment/82881884
comment on: http://stackoverflow.com/a/47956067
score: 0
type: Comment
has text: OK. I understand but that is essentially creating a new column how can I replace or rename?
type: AnswerComment

aws-lambda
tags question: http://stackoverflow.com/q/47961638
type: Tag
tags question: http://stackoverflow.com/q/47899753
tags question: http://stackoverflow.com/q/47907641
tags question: http://stackoverflow.com/q/48004640
tags question: http://stackoverflow.com/q/47928448
tags question: http://stackoverflow.com/q/47866945
tags question: http://stackoverflow.com/q/47984322
tags question: http://stackoverflow.com/q/48004350
tags question: http://stackoverflow.com/q/47990383
tag name: aws-lambda
tags question: http://stackoverflow.com/q/47933565
tags question: http://stackoverflow.com/q/47856186
tags question: http://stackoverflow.com/q/48014551
tags question: http://stackoverflow.com/q/47878893
tags question: http://stackoverflow.com/q/47923452
tags question: http://stackoverflow.com/q/47944567
tags question: http://stackoverflow.com/q/47909840

urllib3
tags question: http://stackoverflow.com/q/47862835
tags question: http://stackoverflow.com/q/47984230
type: Tag
tags question: http://stackoverflow.com/q/47896933
tag name: urllib3

fabric
tags question: http://stackoverflow.com/q/47913880
tag name: fabric
tags question: http://stackoverflow.com/q/47876879
type: Tag

http://stackoverflow.com/q/47947673
downvote count: 1
has answer: http://stackoverflow.com/a/48977895
type: Question
score: 178
tagged with: django-urls
answer count: 6
accepted answer: http://stackoverflow.com/a/47947947
has answer: http://stackoverflow.com/a/47947800
has title: Is it better to use path() or url() in urls.py for django 2.0?
possible better answer: http://stackoverflow.com/a/49932648
favorite count: 0
upvote count: 179
has answer: http://stackoverflow.com/a/49932648
has answer: http://stackoverflow.com/a/48359776
has answer: http://stackoverflow.com/a/52438409
tagged with: python
has comment: http://stackoverflow.com/comment/82865569
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47947947
tagged with: django
has body: In a django online course, the instructor has us use the url() function to call views and utilize regular expressions in the urlpatterns list. I've seen other examples on youtube of this. e.g. from django.contrib import admin from django.urls import include from django.conf.urls import url urlpatterns = [ path('admin/', admin.site.urls), url(r'^polls/', include('polls.urls')), ] #and in polls/urls.py urlpatterns = [ url(r'^$', views.index, name="index"), ] However, in going through the Django tutorial, they use path() instead e.g.: from django.urls import path from . import views urlpatterns = [ path('', views.index, name="index"), ] Furthermore regular expressions don't seem to work with the path() function as using a path(r'^$', views.index, name="index") won't find the mysite.com/polls/ view. Is using path() without regex matching the proper way going forward? Is url() more powerful but more complicated so they're using path() to start us out with? Or is it a case of different tools for different jobs?

http://stackoverflow.com/q/47897108
tagged with: matrix
tagged with: python
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/47899985
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/82761051
accepted answer: http://stackoverflow.com/a/47899985
possible better answer: http://stackoverflow.com/a/47897149
type: Question
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/47897149
has title: Compute distance matrix with numpy
tagged with: arrays
downvote count: 0
has body: I am trying to compute a "distance matrix" matrix to position using numpy. To put it more clearly, I have a matrix representing positions in a 2-D grid: array([[[0, 0], [1, 0], [2, 0], [3, 0]], [[0, 1], [1, 1], [2, 1], [3, 1]], [[0, 2], [1, 2], [2, 2], [3, 2]], [[0, 3], [1, 3], [2, 3], [3, 3]], [[0, 4], [1, 4], [2, 4], [3, 4]]]) I can loop over the position and compute the norm of the difference between the goal position and each position of the position matrix like this: pos_goal = np.array([1,2]) dist_matrix = np.zeros(l_arr.shape[:2]) for i, line in enumerate(l_arr): for j, pos in enumerate(line): dist_matrix[i,j] = np.linalg.norm(pos - pos_goal) dist_matrix Result: array([[ 2.23606798, 2. , 2.23606798, 2.82842712], [ 1.41421356, 1. , 1.41421356, 2.23606798], [ 1. , 0. , 1. , 2. ], [ 1.41421356, 1. , 1.41421356, 2.23606798], [ 2.23606798, 2. , 2.23606798, 2.82842712]]) Isn't there a better way to do this (without the 2 loops)?

http://stackoverflow.com/comment/82879446
score: 1
type: QuestionComment
has text: You can still use inheritance, but I see no reason to. All you've done is give a different value, not overwritten any class behavior. In other words, just use a different parameter value for the tropor
comment on: http://stackoverflow.com/q/47954904
type: Comment

http://stackoverflow.com/comment/82926081
has text: Hi bpbutti! Woah- how careless of me. Thanks for answering!!
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47978672

http://stackoverflow.com/comment/82813342
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/47922700
has text: Please don't post screenshots of errors. Copy and paste the text.

http://stackoverflow.com/a/51053010
answers question: http://stackoverflow.com/q/47986646
downvote count: 0
score: 1
upvote count: 1
type: Answer
has body: To summarize other answers: Issue: "ValueError: embedded null character" when using copy to clipboard (Kivy) Solution: pip install pyperclip pyperclip.copy('text that you want into clipboard')

http://stackoverflow.com/comment/82976770
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47937244
has text: @bluppfisk If that's true you should probably report it as a bug.

http://stackoverflow.com/q/47864096
has comment: http://stackoverflow.com/comment/82693295
duplicate of: http://stackoverflow.com/q/22736641
has comment: http://stackoverflow.com/comment/82693895
has comment: http://stackoverflow.com/comment/82693377
has body: I was going through how to sort and print the symmetric difference of two sets in python when I saw this line of code: ss=sorted(s1^s2) where s1 and s2 are the two integer sets. ss gives the perfect required result. However I can't understand how s1^s2 works. What function does '^' this perform? EDIT: Symmetric Difference, Suppose, s1={2,4,5,9} and s2={2,4,11,12} then ss={5,9,11,12}
has title: Sort Symmetric Difference of Two Sets in Python
type: Question
has comment: http://stackoverflow.com/comment/82693097
tagged with: python-2.7
score: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82693416
tagged with: python
has comment: http://stackoverflow.com/comment/82693109
answer count: 0
linked to: http://stackoverflow.com/q/22736641
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82732043

http://stackoverflow.com/comment/135827102
type: AnswerComment
comment on: http://stackoverflow.com/a/47864202
type: Comment
has text: Why do you use a[-1]?
score: 0

http://stackoverflow.com/comment/84444341
type: Comment
comment on: http://stackoverflow.com/a/47971435
score: 0
type: AnswerComment
has text: did you figure this out , I'm having the same issue

http://stackoverflow.com/a/48007353
has body: I used this method and it worked: def AnalyzeTwoExpr(expr1, expr2): #Case sensitive commonExpr = [] a = expr1.split(' ') #splits each expression into an array of words b = expr2.split(' ') #splits each expression into an array of words for word1 in a: for word2 in b: if(word1 == word2): commonExpr.append(word1) return commonExpr This method returns an array containing all the words that were included in both expressions. This method has 2 required arguments, 2 strings, which are the 2 expressions to analyze. Also, have a not case sensitive method: def AnalyzeTwoExpr(expr1, expr2): #Not case sensitive commonExpr = [] a = expr1.split(" ") b = expr2.split(" ") for word1 in a: for word2 in b: w1 = word1.lower() w2 = word2.lower() if(w1 == w2): commonExpr.append(w1) return commonExpr Hope this works for you.
answers question: http://stackoverflow.com/q/48006038
type: Answer
score: 0

xpath
tags question: http://stackoverflow.com/q/47898340
tags question: http://stackoverflow.com/q/47985495
tags question: http://stackoverflow.com/q/47915676
tags question: http://stackoverflow.com/q/48014262
tags question: http://stackoverflow.com/q/47931534
tag name: xpath
tags question: http://stackoverflow.com/q/48014000
tags question: http://stackoverflow.com/q/47963080
tags question: http://stackoverflow.com/q/47997725
tags question: http://stackoverflow.com/q/47957983
tags question: http://stackoverflow.com/q/47900465
tags question: http://stackoverflow.com/q/47957930
tags question: http://stackoverflow.com/q/48005687
tags question: http://stackoverflow.com/q/47907620
tags question: http://stackoverflow.com/q/47964808
tags question: http://stackoverflow.com/q/47973352
tags question: http://stackoverflow.com/q/47935982
tags question: http://stackoverflow.com/q/47977346
tags question: http://stackoverflow.com/q/47956242
tags question: http://stackoverflow.com/q/47922167
tags question: http://stackoverflow.com/q/47984636
tags question: http://stackoverflow.com/q/47897434
tags question: http://stackoverflow.com/q/47883630
tags question: http://stackoverflow.com/q/47957827
tags question: http://stackoverflow.com/q/47974320
tags question: http://stackoverflow.com/q/47978702
type: Tag
tags question: http://stackoverflow.com/q/47905232
tags question: http://stackoverflow.com/q/47990341
tags question: http://stackoverflow.com/q/47935006
tags question: http://stackoverflow.com/q/47948598
tags question: http://stackoverflow.com/q/47979845
tags question: http://stackoverflow.com/q/47999652
tags question: http://stackoverflow.com/q/47948225
tags question: http://stackoverflow.com/q/47927599

http://stackoverflow.com/q/47861837
has comment: http://stackoverflow.com/comment/82689518
upvote count: 2
has comment: http://stackoverflow.com/comment/82688758
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82688728
downvote count: 2
has comment: http://stackoverflow.com/comment/82688799
tagged with: python
linked to: http://stackoverflow.com/q/2739051
has answer: http://stackoverflow.com/a/47862108
has comment: http://stackoverflow.com/comment/82688798
has body: I am trying to find the two largest elements of a given list of numbers using list comprehension. This is what I have tried so far. I also tried to use the 'filter' function in place of this. def top_two(l): l1 = [lambda x,y:x &gt; y for x in l] return l1 I also tried something like this but it is not working either. def top_two(l): l1 = [l[x] for x in range(len(l)) for y in l[x:] if l[x] &gt; y] Any help would be appreciated! EDIT I had not thought of simply sorting it! I will sort it with list comprehensions and extract the max. Thanks!
type: Question
has answer: http://stackoverflow.com/a/47861920
has comment: http://stackoverflow.com/comment/82689231
has comment: http://stackoverflow.com/comment/82688781
has title: How to finding maximum values in list in python without using loops
tagged with: list-comprehension
score: 0
answer count: 2
tagged with: functional-programming
favorite count: 0
has comment: http://stackoverflow.com/comment/82689342
has comment: http://stackoverflow.com/comment/82688778

http://stackoverflow.com/comment/82723926
type: Comment
has text: There was a python3.4 compatibility module at `/usr/lib/python3.6/enum/__init__.py` that was interfering with the standard library module at `/usr/lib/python3.6/enum.py`. Manually deleted the directories `/usr/lib/python3.6/enum` and `/usr/lib/python3.6/enumenum34-1.1.6.dist-info` and now `enum.__file__` shows `/usr/lib/python3.6/enum.py` as it should and everything works. I love it when that happens.
score: 1
comment on: http://stackoverflow.com/a/47878910
type: AnswerComment

http://stackoverflow.com/comment/82677834
score: 0
comment on: http://stackoverflow.com/q/47856718
type: QuestionComment
has text: One concrete piece of advice I have for you though is not to have that giant set of `if` `elif` for the color selection. If you can't figure out a very simple function for mapping number to rgb, at least use a dictionary to store the mapping.
type: Comment

http://stackoverflow.com/a/47980259
type: Answer
accepted answer of: http://stackoverflow.com/q/47979647
answers question: http://stackoverflow.com/q/47979647
score: 0
type: AcceptedAnswer
has body: This one is the easiest one, views.py :- def get_queryset(self): param = self.kwargs.get('pk') param2 = self.kwargs.get('sk') param3 = self.kwargs.get('ek') return namelist.objects.filter(name=param, date__gte = param2, date__lte = param3) urls.py :- urlpatterns = { url('^namelist/(?P&lt;pk&gt;[\w\-\.]+)/(?P&lt;sk&gt;[\w\-\.]+)/(?P&lt;ek&gt;[\w\-\.]+)/$', ListViewParam.as_view()), }

http://stackoverflow.com/a/47992143
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/82959306
has comment: http://stackoverflow.com/comment/82959949
answers question: http://stackoverflow.com/q/47991509
downvote count: 0
score: 1
has body: SFTP and FTP are two completely unrelated protocols. You cannot connect with FTP protocol (ftplib) to SFTP server. pysftp/Paramiko should work. If it does not, post a new question specifically about pysftp/Paramiko, with more details.

http://stackoverflow.com/comment/82759051
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47896006
has text: I am not sure why my question was marked as a duplicate. My issue has nothing to do with the age question someone else posted a while ago. My code is not updating the values after the user fixes it and it doesn't finalize the computation. The input format is correct and requests float and integers as numbers.

http://stackoverflow.com/comment/82844525
type: Comment
score: 1
comment on: http://stackoverflow.com/q/47937697
has text: When you say "not scaleable", do you mean you would have a bunch of repetitive code? If so, use a loop: `for reference_word in reference_list:`
type: QuestionComment

http://stackoverflow.com/comment/122081868
type: AnswerComment
has text: I've always found this to be such a pain. Backend development for some reason you always need to try 'form-data', 'form-urlencoded', 'raw', etc to see which one works. And now not only it needs to be raw, but also has to set the language...
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47882232

http://stackoverflow.com/q/47898368
tagged with: web-scraping
type: Question
answer count: 1
linked to: http://stackoverflow.com/q/12876177
has comment: http://stackoverflow.com/comment/82763563
has comment: http://stackoverflow.com/comment/82763562
upvote count: 3
has comment: http://stackoverflow.com/comment/82763540
has title: requests.exceptions.MissingSchema: Invalid URL 'h': No schema supplied
downvote count: 1
has comment: http://stackoverflow.com/comment/82763579
favorite count: 0
has comment: http://stackoverflow.com/comment/82763782
has comment: http://stackoverflow.com/comment/82763590
accepted answer: http://stackoverflow.com/a/47898423
has body: I am working on a web scraping project and have run into the following error. requests.exceptions.MissingSchema: Invalid URL 'h': No schema supplied. Perhaps you meant http://h? Below is my code. I retrieve all of the links from the html table and they print out as expected. But when I try to loop through them (links) with request.get I get the error above. from bs4 import BeautifulSoup import requests import unicodedata from pandas import DataFrame page = requests.get("http://properties.kimcorealty.com/property/output/find/search4/view:list/") soup = BeautifulSoup(page.content, 'html.parser') table = soup.find('table') for ref in table.find_all('a', href=True): links = (ref['href']) print (links) for link in links: page = requests.get(link) soup = BeautifulSoup(page.content, 'html.parser') table = [] # Find all the divs we need in one go. divs = soup.find_all('div', {'id':['units_box_1', 'units_box_2', 'units_box_3']}) for div in divs: # find all the enclosing a tags. anchors = div.find_all('a') for anchor in anchors: # Now we have groups of 3 list items (li) tags lis = anchor.find_all('li') # we clean up the text from the group of 3 li tags and add them as a list to our table list. table.append([unicodedata.normalize("NFKD",lis[0].text).strip(), lis[1].text, lis[2].text.strip()]) # We have all the data so we add it to a DataFrame. headers = ['Number', 'Tenant', 'Square Footage'] df = DataFrame(table, columns=headers) print (df)
tagged with: python
tagged with: python-requests
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47898423

http://stackoverflow.com/comment/82910043
type: QuestionComment
comment on: http://stackoverflow.com/q/47970321
score: 0
type: Comment
has text: Perhaps you should connect to an UDP port?

http://stackoverflow.com/a/48034335
downvote count: 0
score: 18
type: Answer
answers question: http://stackoverflow.com/q/48013201
has body: As already pointed out in the comments, even though what you are asking for in itself is well-defined, the proper approach to its solution will depend on the properties of your model. Let's see why, let's see how far a generalist optimization approach gets you, and let's see how a bit of math may simplify the problem. A copy-pastable solution is included at the bottom. First of all, least squares fitting is "easier" than what you are trying to do in the sense that specialized algorithms apply; for example, SciPy's leastsq makes use of the Levenberg--Marquardt algorithm which assumes that your optimization objective is a sum of squares. Of course, in the special case of linear regression, the problem can also be solved analytically. Besides the practical advantages, least squares linear regression may also be justified theoretically: If the residuals of your observations are independent and normally distributed (which you may justify if you find that the central limit theorem applies in your model), then the maximum likelihood estimate of your model parameters will be those obtained through least squares. Similarly, the parameters minimizing a mean absolute error optimization objective will be the maximum likelihood estimates for Laplace distributed residuals. Now what you are trying to do will have an advantage over ordinary least squares if you know beforehand that your data is so dirty that assumptions on normality of residuals will fail, but even then, you may be able to justify other assumptions that will impact the choice of objective function, so I am curious how you have ended up in that situation? Using numerical methods With that out of the way, some general remarks apply. First of all, note that SciPy does come with a large selection of general purpose algorithms which you can apply directly in your case. As an example, let us see how to apply minimize in the univariate case. # Generate some data np.random.seed(0) n = 200 xs = np.arange(n) ys = 2*xs + 3 + …
upvote count: 18

http://stackoverflow.com/comment/82723145
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47878467
type: Comment
has text: It did not remove or add any data.

http://stackoverflow.com/comment/82880220
has text: @dawg: Very good point, though I'd even use `lst = [number for item in lst for number in [item.strip()] if number]` to have the items stripped in the resulting list. Have updated my answer below.
type: Comment
comment on: http://stackoverflow.com/q/47953523
type: QuestionComment
score: 0

http://stackoverflow.com/a/47870087
answers question: http://stackoverflow.com/q/47869967
has body: Your code: x = 1 size = 16 for i in range(size): print((' ' * (size - i)) + bin(x)[2:] .replace('0', ' ').replace('1', ' *')) x ^= x &lt;&lt; 1 More clear by introducing some variables: x = 1 size = 16 for i in range(size): spaces = (' ' * (size - i)) binary = bin(x)[2:] print(spaces + binary .replace('0', ' ').replace('1', ' *')) x ^= x &lt;&lt; 1 The reason that dot in the beginning of line is not an error is that you have an unclosed parenthesis and Python is looking for remaining parts on the next line.
score: 3
upvote count: 3
downvote count: 0
type: Answer

http://stackoverflow.com/comment/82739506
comment on: http://stackoverflow.com/q/47884566
type: QuestionComment
has text: FeatureUnion will supply the same input data to all its internal transformers. So what you are trying to do here is correct.
type: Comment
score: 1

http://stackoverflow.com/q/47892006
type: Question
answer count: 2
downvote count: 1
has body: I am new to python and odoo. I came across a scenario that i want to create a excel file first from my dynamic records and then want to save it to ir.attachment table. So that i can link that as an attachment in email. Here is what i tried, but its not writing into the file workbook = xlsxwriter.Workbook('demo.xlsx') worksheet = workbook.add_worksheet() worksheet.set_column('A:A', 20) bold = workbook.add_format({'bold': True}) worksheet.write('A1', 'Hello') worksheet.write('A2', 'World', bold) worksheet.write(2, 0, 123) worksheet.write(3, 0, 123.456) workbook.close() Update I am able to create the xlsx file, actullay it was my path issue. Now i just want to know that how to add that file in ir.attachment
favorite count: 0
tagged with: odoo-10
tagged with: python
score: 8
upvote count: 9
possible better answer: http://stackoverflow.com/a/47892498
has comment: http://stackoverflow.com/comment/83003030
has comment: http://stackoverflow.com/comment/82821885
has comment: http://stackoverflow.com/comment/82943915
has answer: http://stackoverflow.com/a/47892498
accepted answer: http://stackoverflow.com/a/48018846
has comment: http://stackoverflow.com/comment/82759072
tagged with: excel
has title: How to create and then write on a xlsx file
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48018846
tagged with: odoo
has comment: http://stackoverflow.com/comment/82752550
has comment: http://stackoverflow.com/comment/82751065

http://stackoverflow.com/a/75779627
score: 0
answers question: http://stackoverflow.com/q/47917460
type: Answer
has body: Alternative ways to get the scalar values of a single value Series are: val = df.loc[df['iata'] == 'PDX', 'name'].squeeze() val = df.loc[df['iata'] == 'PDX', 'name'].item() val = df.loc[df['iata'] == 'PDX', 'name'].iat[0] All of them return 'Portland Intl'.

http://stackoverflow.com/comment/82857464
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47943879
type: Comment
has text: Unfortunately, there is no general solution

http://stackoverflow.com/comment/82975556
score: 0
comment on: http://stackoverflow.com/q/48003638
type: Comment
type: QuestionComment
has text: So if I use `char.decode("cp1252")`, the result is `u'\xbf'`. If I `print(u"¿")`, the result is `¿`. I've tested on both Windows and Linux with the same result.

http://stackoverflow.com/a/48009970
has comment: http://stackoverflow.com/comment/82988739
has comment: http://stackoverflow.com/comment/82989789
has comment: http://stackoverflow.com/comment/82988671
upvote count: 3
has comment: http://stackoverflow.com/comment/82988686
has comment: http://stackoverflow.com/comment/82988624
has comment: http://stackoverflow.com/comment/82988605
has body: How about this where testNumber is your variable (testNumber - 1 &gt;&gt; 1 &lt;&lt; 1) | 1 # LESS THAN OR EQUAL TO (testNumber - 2 &gt;&gt; 1 &lt;&lt; 1) | 1 # LESS THAN
has comment: http://stackoverflow.com/comment/82988576
answers question: http://stackoverflow.com/q/48009830
type: Answer
has comment: http://stackoverflow.com/comment/82988459
has comment: http://stackoverflow.com/comment/82988375
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/82988730
has comment: http://stackoverflow.com/comment/82988391
has comment: http://stackoverflow.com/comment/82989663
has comment: http://stackoverflow.com/comment/82989134
has comment: http://stackoverflow.com/comment/82988541
has comment: http://stackoverflow.com/comment/82990057
has comment: http://stackoverflow.com/comment/82988774

http://stackoverflow.com/comment/82898864
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47964574
has text: Can you include the getData function, in your question, please? Also, are you trying to get data multiple times for an alexa intent call? If so, why can't you get data before the call? Just trying to understand a little better so I can help.
score: 0

http://stackoverflow.com/comment/83037430
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47977783
score: 0
has text: also [this answer](https://stackoverflow.com/a/37964206/9141316) for sniffing form large pcap files

http://stackoverflow.com/q/47965276
answer count: 1
has comment: http://stackoverflow.com/comment/82900437
tagged with: machine-learning
tagged with: python
accepted answer: http://stackoverflow.com/a/47965308
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47965308
type: Question
has title: Python - how to store time series into dataset
tagged with: neural-network
tagged with: dataset
has comment: http://stackoverflow.com/comment/82900450
has body: I build a parser which converts MIDI song into sequence of note - chord tuples. For each song, it returns list of tuples, where first item is note and second item is set of notes. So resulting data has shape [(note, {chords})], e.g. [(20, {21, 23}), (30, {22, 24, 26, 28})]. Notice that chord could be arbitrary long. I would like to build a dataset from many songs and later pass them into recurrent neural network. So my question is: What is simplest way to persist this data into file? I tried h5py library. Unfortunately, it only works with matrices. Though it would be possible to save each pair like that, it would probably be very inefficient, since length of chord is unlimited.
score: 0
tagged with: h5py

http://stackoverflow.com/a/47888419
answers question: http://stackoverflow.com/q/47887942
upvote count: 1
has body: Though not the most optimal way to do it, but one way could be to split your long string into list of words. Then for each word query the database using LIKE regex. Eg: SELECT * FROM table WHERE city LIKE '%word%'
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/q/47927940
favorite count: 0
tagged with: sockets
tagged with: python
has comment: http://stackoverflow.com/comment/82824817
has comment: http://stackoverflow.com/comment/106243689
has comment: http://stackoverflow.com/comment/106244911
type: UnansweredQuestion
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/58939739
has comment: http://stackoverflow.com/comment/82825151
answer count: 1
downvote count: 0
has title: How should I close and unregister socket registered to a selector
has body: In my code I am opening a socket which I register to an EpollSelector. The documentation for selectors/unregister() then says that: A file object shall be unregistered prior to being closed. How can I guarantee this with code looking like this: with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as a_socket: a_socket.bind(socket_addr) a_socket.listen(1) epoll = select.epoll() epoll.register(a_socket, select.EPOLLIN, select.EPOLLERR, select.EPOLLHUP) do_stuff() epoll.unregister(a_socket) If do_stuff raises an exception how can I make sure the unregister happens before the socket closes? What sort of problems can occur if I don't unregister before closing the socket?

http://stackoverflow.com/a/60462019
score: 0
type: Answer
has body: Since you are using Class based views; you can also do: self.assertEqual( found.func.view_class, views.HomePageView )
answers question: http://stackoverflow.com/q/47968535

http://stackoverflow.com/comment/82872275
type: AnswerComment
type: Comment
has text: thanks. But how to do it using urllib? I am new into it.
comment on: http://stackoverflow.com/a/47951354
score: 0

http://stackoverflow.com/a/47877774
score: -1
downvote count: 1
has comment: http://stackoverflow.com/comment/82722246
type: Answer
answers question: http://stackoverflow.com/q/47877712
upvote count: 0
has comment: http://stackoverflow.com/comment/82722306
has body: You can just iterate through rows from the oldest ones to the newest and at each step decide if it is to be removed or not, comparing it to the last row that was not removed (accepted_rows[-1]): all_rows = [...] accepted_rows = all_rows[0:1] # initially just first row for current_row in all_rows[1:]: if price_change_between(accepted_rows[-1], current_row) &lt;= 0.1: accepted_rows.append(current_row)

http://stackoverflow.com/comment/82955427
comment on: http://stackoverflow.com/a/47992330
score: 0
type: Comment
has text: @RoadRunner my first answer was written with the assumption that hbakan wanted to read all data into a single list. This one is about loading data into a list of lists.
type: AnswerComment

hdf5
tags question: http://stackoverflow.com/q/47979751
tags question: http://stackoverflow.com/q/48006574
tags question: http://stackoverflow.com/q/47980423
tags question: http://stackoverflow.com/q/47921953
tags question: http://stackoverflow.com/q/48000371
tags question: http://stackoverflow.com/q/47978664
type: Tag
tag name: hdf5

http://stackoverflow.com/comment/87631162
has text: Hey, did you have any luck in fixing this? I am having a similar issue. I run the visualization command, but not getting any graph
comment on: http://stackoverflow.com/q/47996444
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47881713
has body: Furas is quite right... The solution is as simple as the elide=True keyword arg passed to the tag_config() method. It's strange that the elide keyword is not documented in any Tkinter docs I can find. But, the simplest scenario is to create a tag config as follows: textWidget.tag_config('hidden', elide=True) # or elide=1 This will cause the tagged text to be "invisible" or "hidden" in the text widget. You will not be able to see the text in the Text widget, but it is still there. If you call textWidget.get('1.0', 'end - 1c'), you'll see the hidden characters in the text returned by the method. You can also delete the hidden characters from textWidget without needing to see them. As you're deleting the elided characters, you won't see the INSERT cursor move. It's a bit odd... Note that the tagged text can span multiple lines, so all lines are collapsed in the Text widget. The first thing I thought of while testing this was that, if I were implementing a source code editor and wanted to add the feature of "collapsing" part of the code (say, in an if block), elided text would be the feature I would want to be using to do that. Thanks, Furas!
type: Answer
answers question: http://stackoverflow.com/q/47879356
score: 2
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/82729258
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47879356

http://stackoverflow.com/a/47940826
has comment: http://stackoverflow.com/comment/82868037
answers question: http://stackoverflow.com/q/47931787
has body: Here's a somewhat simplified example of what you could do: In [42]: def queryParams(params): ...: params = urllib.parse.parse_qs(params) ...: for key, val in params.items(): ...: # Trust the implicit conversions: ...: # https://docs.oracle.com/en/database/oracle/oracle-database/12.2/sqlrf/Data-Type-Comparison-Rules.html#GUID-6DB331B5-0F34-4215-9A20-16AEA9D7FF4B ...: yield column(key) == val ...: Using column() handles quoting reserved words and mixed case, and escaping bad characters in column names, but you should still possibly whitelist though. The comparison produces a binary SQL expression object, with the bound parameter val. You can combine Core constructs with text fragments in order to generate your query: In [43]: params = 'asdf=1&amp;qwer=true&amp;foo=baz' In [44]: s = select([text(""" ...: a.cod_lim_judicial, a.desc_lim_judicial, a.dt_lim_judicial, ...: a.dt_validade, a.nr_mandado, a.tipo_liminar, a.folhas_incidencia, ...: a.num_folha, a.mes_ano_folha, p.mat_servidor, p.cod_depend, a.perc_pa""")]).\ ...: select_from( ...: outerjoin( ...: text("folha.fl_liminar a"), ...: text("folha.fl_pens_x_liminar p"), ...: text("a.cod_lim_judicial = p.cod_lim_judicial"))).\ ...: where(and_(*queryParams(params))) ...: In [45]: print(s) SELECT a.cod_lim_judicial, a.desc_lim_judicial, a.dt_lim_judicial, a.dt_validade, a.nr_mandado, a.tipo_liminar, a.folhas_incidencia, a.num_folha, a.mes_ano_folha, p.mat_servidor, p.cod_depend, a.perc_pa FROM folha.fl_liminar a LEFT OUTER JOIN folha.fl_pens_x_liminar p ON a.cod_lim_judicial = p.cod_lim_judicial WHERE asdf = :asdf_1 AND qwer = :qwer_1 AND foo = :foo_1
has comment: http://stackoverflow.com/comment/82871680
has comment: http://stackoverflow.com/comment/82858434
has comment: http://stackoverflow.com/comment/82894959
has comment: http://stackoverflow.com/comment/82895108
has comment: http://stackoverflow.com/comment/82860736
has comment: http://stackoverflow.com/comment/82870876
has comment: http://stackoverflow.com/comment/82861288
type: AcceptedAnswer
score: 0
has comment: http://stackoverflow.com/comment/82894925
accepted answer of: http://stackoverflow.com/q/47931787
type: Answer

http://stackoverflow.com/comment/82899955
has text: Yeah I'll definitely admit it's all a bit sloppy in it's current state and I'll try and clean that up now and see if it fixes things. However I'm not too optimistic it will to be honest, because I've tried using the index.html page, which I know for sure works, instead of laws.html or about.html and the error still occurs. It's looking like it must be some small detail somewhere though, so I'm going to go ahead and read through everything again while trying to clean some stuff up. Thanks for the suggestions.
score: 0
comment on: http://stackoverflow.com/q/47961481
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82836336
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47898455
has text: It defaults to false. But, you might want to post that as a new question including the error. https://github.com/apache/spark/blob/master/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala#L391
score: 0

http://stackoverflow.com/comment/82987259
type: Comment
score: 1
comment on: http://stackoverflow.com/a/48008874
has text: Well I didn't feel like asking two people about it, and yours was the higher-voted one (with one vote from me for the round-trip idea :-)
type: AnswerComment

pygobject
type: Tag
tags question: http://stackoverflow.com/q/47963727
tag name: pygobject

http://stackoverflow.com/a/47947703
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: Here is a pure numpy solution. It sorts the records by first column to easily find duplicate names. import numpy as np data = """ Jack 0.794938 0 Marc 0.05155265 0 Eliza 0.96454115 0 Louis 0.075102 0 Milo 0.951499 0 Marc 0.63319 0 Michael 0.719391 0 Louis 0.502843 0 Eliza 0.620387 0 """ data = (line.split() for line in data.strip().split('\n')) data = np.array([(x, float(y), float(z)) for x, y, z in data], dtype=object) res = data.copy() idx = np.argsort(res[:, 0], kind='mergesort') dupl = res[idx[:-1], 0] == res[idx[1:], 0] res[idx[:-1][dupl], 2] = res[idx[1:][dupl], 1] mask = np.ones(res.shape[:1], dtype=bool) mask[idx[1:][dupl]] = False res = res[mask] Result: # array([['Jack', 0.794938, 0.0], # ['Marc', 0.05155265, 0.63319], # ['Eliza', 0.96454115, 0.620387], # ['Louis', 0.075102, 0.502843], # ['Milo', 0.951499, 0.0], # ['Michael', 0.719391, 0.0]], dtype=object)
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/47947148
answers question: http://stackoverflow.com/q/47947148

http://stackoverflow.com/comment/82732791
has text: Please look at my updated graph. Only 0 appear on the scale. Do you know why? Guess not. So let me explain, if you use `np.linspace` you just shorten my scale. I have 266336 data, and you put a command to python to make a scale for it which contain only 300 records, that's why nothing except 0 appear after using your command. Is that clear? So that does not resolve my problem at all.
comment on: http://stackoverflow.com/a/47878227
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/47895078
favorite count: 0
has answer: http://stackoverflow.com/a/47895294
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82757194
upvote count: 0
type: Question
score: -2
has body: I'm trying to normalize numbers within multiple arrays. I have 10 arrays with 5 numbers each. I have been able to normalize my first array, but all other arrays take the parameters from the first array. my code norm func: normfeatures = (features - np.min (features)) / (np.max(features) - np.min(features)) how can I make it so that each array takes the min and max from their own array rather than the min and max from the first one?
downvote count: 2
answer count: 1
has title: How to normalise multiple arrays?

http://stackoverflow.com/q/47926159
accepted answer: http://stackoverflow.com/a/47926760
upvote count: 5
answer count: 1
downvote count: 0
has title: Pygame blit area parameter?
favorite count: 0
tagged with: area
has answer: http://stackoverflow.com/a/47926760
score: 5
tagged with: partial
tagged with: python
tagged with: pygame
tagged with: blit
has body: I am currently trying to blit a part of an already drawn image again. For this I read one can use the optional third area parameter when using blit. I do not know why but that parameter is acting weird for me. From what I understand the area parameter is (pos_x, pos_y, width, height). My screen is 1280x1024, so if I want to have the part I want to redraw start in the center I would pass something like (640, 512, 200, 200) and a 200x200 part of the image should be drawn starting from the center. However, for me the image is always drawn in the top left, and the first two numbers in the area parameter change the brightness of the part being drawn. My Code: image = pygame.image.load("image.jpg") image = pygame.transform.scale(image, (self.display.get_width(), self.display.get_height())) self.display.blit(image, (0,0)) # Drawing something here which has to be overwritten, but cannot redraw everything. self.display.blit(image, (0,0), (640,512,200,200)) The second blit just draws a 200x200 image at the top left of my screen, which is brighter than the first time the image is drawn. Kind regards
type: AnsweredQuestion
type: Question

http://stackoverflow.com/comment/100714633
comment on: http://stackoverflow.com/q/47990985
type: Comment
type: QuestionComment
has text: did you manage to figure this problem out?
score: 0

http://stackoverflow.com/comment/82894220
score: 0
type: Comment
type: QuestionComment
has text: I have newer or similar versions. I will update my question with the versions
comment on: http://stackoverflow.com/q/47947828

http://stackoverflow.com/q/47883841
score: 0
has answer: http://stackoverflow.com/a/47887825
tagged with: python
has body: I have written the following code to transfer a video from client to server and then to transfer a stream of ints from server to client. It works when I make the server and client in 2 different terminals on one computer. But I get the following error when i do the same on 2 different computers. grpc._channel._Rendezvous: &lt;_Rendezvous of RPC that terminated with (StatusCode.UNAVAILABLE, Connect Failed)&gt; I'm simply setting up all these files on 2 different computers. On one computer, I call python imageTest_client.py and on the other python imageTest_server.py What else has to be done to send messages from one computer to another? client.py import grpc ... def run(): channel = grpc.insecure_channel('localhost:50051') stub = imageTest_pb2_grpc.ImageTestStub(channel) for response in stub.Analyse( generateRequests() ): print(str(response.reply)) server.py import grpc class Greeter(imageTest_pb2_grpc.ImageTestServicer): def Analyse(self, request_iterator, context): for req in request_iterator: yield imageTest_pb2.MsgReply(reply = 1 ) def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) imageTest_pb2_grpc.add_ImageTestServicer_to_server(Greeter(), server) server.add_insecure_port('[::]:50051') server.start() try: while True: time.sleep(_ONE_DAY_IN_SECONDS) except KeyboardInterrupt: server.stop(0) .proto syntax = "proto3"; option java_multiple_files = true; option objc_class_prefix = "HLW"; // The greeting service definition. service ImageTest { // Sends a greeting rpc Analyse (stream MsgRequest) returns (stream MsgReply) {} } // The request message containing the image. message MsgRequest { bytes img = 1; } // The response message containing the reply message MsgReply { int32 reply = 1; }
type: UnansweredQuestion
type: Question
tagged with: grpc
has title: GRPC not working when I use 2 computers instead of 1
answer count: 1

state
tag name: state
tags question: http://stackoverflow.com/q/47878137
type: Tag

http://stackoverflow.com/a/48011330
score: 14
has body: With a CSS selector for an element with a title starting with "4G Signal quality": driver.find_element_by_css_selector("[title^='4G Signal quality']") , or containing "4G Signal quality": driver.find_element_by_css_selector("[title*='4G Signal quality']")
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 14
accepted answer of: http://stackoverflow.com/q/48011212
answers question: http://stackoverflow.com/q/48011212

http://stackoverflow.com/a/47878910
has comment: http://stackoverflow.com/comment/82723926
has body: You should check to see if there's another module named enum on your python path that is shadowing the stdlib enum module. To do that, you can do: import enum print(enum.__file__) If that doesn't match the python3 stdlib module path, you should try to remove it. Ideally, you should use whatever package manager your system uses to uninstall it, as it it might be a dependency of some other package. But if that isn't possible, you can just try removing it manually.
type: Answer
upvote count: 6
score: 6
has comment: http://stackoverflow.com/comment/93948239
answers question: http://stackoverflow.com/q/47878060
accepted answer of: http://stackoverflow.com/q/47878060
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/48020851
answers question: http://stackoverflow.com/q/47990383
has comment: http://stackoverflow.com/comment/131016804
type: Answer
upvote count: 4
has body: Upload your json with the secret key just as you're doing, then do this: #import GoogleCredentials from oauth2client.client import GoogleCredentials credentials = GoogleCredentials.get_application_default() service = discovery.build('people', 'v1', credentials=credentials,cache_discovery=False) On your lambda configuration set GOOGLE_APPLICATION_CREDENTIALS as environment variable key and your credentials json file name as value. It works on all my lambdas that use google api.
downvote count: 0
score: 4

http://stackoverflow.com/q/47902547
has comment: http://stackoverflow.com/comment/82772529
tagged with: python-2.7
duplicate of: http://stackoverflow.com/q/41127441
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/82772173
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82772101
tagged with: python
score: 2
answer count: 0
has title: Differences in 'for' syntax on Python 2 and Python 3
type: Question
has comment: http://stackoverflow.com/comment/82771934
has body: While porting my code from Python 2 to Python 3, the following function could not execute: from decimal import Decimal def func(x, y, z): x, y, z = [Decimal(arg) for arg in x, y, z] # function continues... In Python 3, I had to change it to x, y, z = [Decimal(arg) for arg in [x, y, z]]. Question #1: Is that piece of code even legal under Python 2 standard, or did my interpreter just happened to be "forgiving"? Question #2: Are there any similar ("list-related") differences that I should be aware of?
linked to: http://stackoverflow.com/q/41127441

http://stackoverflow.com/a/47864202
type: Answer
answers question: http://stackoverflow.com/q/47864028
score: 2
has comment: http://stackoverflow.com/comment/135838551
downvote count: 1
has comment: http://stackoverflow.com/comment/135837397
upvote count: 3
has comment: http://stackoverflow.com/comment/135827102
has comment: http://stackoverflow.com/comment/135834669
has body: append returns None, so you cannot get the list back into reduce like this. Just use the addition between the list and a list made of a single element, or just a list made of initial element if list is empty: from functools import reduce def my_cum_sum(arg): return reduce(lambda a, x: a + [a[-1]+x] if a else [x], arg, []) print (my_cum_sum([1, 1, 1, 1])) result: [1, 2, 3, 4] (note that if len(a)&gt;0 is better written if a as well)

http://stackoverflow.com/q/47875565
has answer: http://stackoverflow.com/a/47880446
score: 0
has title: How do I scrapy a particular webpage with a login form bearing only a nameless password field, and then submit values to ajax? with Selenium?
tagged with: web-scraping
tagged with: python
tagged with: scrapy
answer count: 1
has body: I'm new to Python Scrapy, have this so far: import scrapy class ExampleSpider(scrapy.Spider): name = 'example' allowed_domains = ['flashfurniture.com'] start_urls = ['http://flashfurniture.com/'] skus = ['LE-L-C-BLACK-GG', 'SZ-TUFT-SIL-GG'] zips = ['33122', '90210', '07501', '60007'] qtys = [1, 2, 12, 24, 50] def start_requests(self): for sku in self.skus: yield scrapy.Request(url='http://www.flashfurniture.com/'+sku.lower()+'.html', cookies=[{'name': 'password', 'value': 'fubar', 'domain': 'www.flashfurniture.com', 'path': '/'}], callback=self.parse) def parse(self, response): sku = response.css('#fobTable .product-code::text').extract_first() self.log(sku) for zip in self.zips: for qty in self.qtys: return scrapy.FormRequest(url=response.url, formdata={'vwquantity': str(qty), 'shippingAddressDS.shipping_ROW0_zip': zip}, callback=self.after_post) #self.log('LTL FDX') #pass #write to file def after_post(self, response): LTL = response.css('#calcBox .unique-shipment #rateRad0[value]::text').extract_first() FDX = response.css('#calcBox .unique-shipment #rateRad1[value]::text').extract_first() self.log('LTL $%s FDX $%s' % (LTL, FDX)) self.log(response.xpath('//div[@class="show-button"][@style]')) The above returns the SKUs (way to go right) and 2017-12-18 14:28:51 [example] DEBUG: LTL $None FDX $None 2017-12-18 14:28:51 [example] DEBUG: [] 2017-12-18 14:28:51 [example] DEBUG: LTL $None FDX $None 2017-12-18 14:28:51 [example] DEBUG: [] The very last line is supposed to be a login success test. Note that the password included in my above code is invalid; hopefully you can help me figure this out anyway. What I'm trying to achieve should be pretty clear: I need ultimately to write to CSV five rows per SKU/page parsed, to contain the following: SKU, Z0Q0L, Z0Q0F, Z1Q0L, Z1Q0F, Z2Q0L, Z2Q0F, Z3Q0L, Z3Q0F Q1, Z0Q1L, Z0Q1F, Z1Q1L, Z1Q1F, Z2Q1L, Z2Q1F, Z3Q1L, Z3Q1F Q2, Z0Q2L, Z0Q2F, Z1Q2L, Z1Q2F, Z2Q2L, Z2Q2F, Z3Q2L, Z3Q2F Q3, Z0Q3L, Z0Q3F, Z1Q3L, Z1Q3F, Z2Q3L, Z2Q3F, Z3Q3L, Z…
type: UnansweredQuestion
type: Question

http://stackoverflow.com/q/47956313
type: Question
has answer: http://stackoverflow.com/a/47956361
answer count: 1
score: 0
tagged with: datetime
tagged with: python
type: UnansweredQuestion
tagged with: datetimeindex
tagged with: weekday
has title: How can I make a table with a date range labeling weekdays and weekends (joinable by date) in python?
tagged with: date
has body: I've never worked with DataTimeIndex. It's giving me a headache as everything I normally would try is not working. I've tried converting to datetime and I'm still unable to just make a weekday column using date.weekday or .dayofweek. Can someone please assist? date_list = pd.date_range(trainset['date'].min(), trainset['date'].max(), freq='d', name='date_val') date_list['date_val'] = date_list['date_val'].dt.date date_list['Weekdays'] = date_list.date_val.dt.dayofweek()

http://stackoverflow.com/comment/82943905
has text: @Piinthesky i figured it is little complex if the initial block size itself is not of size threshold. I solved my problem with itertools.groupby.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47978863

http://stackoverflow.com/comment/82912489
type: QuestionComment
comment on: http://stackoverflow.com/q/47942623
has text: You mean you can do nothing about the Python version? Well, than I suggest (1) you use [unicodecsv](https://pypi.python.org/pypi/unicodecsv) (`pip install unicodecsv`), and (2) you make your code Unicode-aware, ie. use Unicode strings (`u"..."`) everywhere, otherwise you'll continue to have implicit coercion with potential encoding errors. To ease the pain with the `u"..."` strings, consider using `from __future__ import unicode_literals`.
type: Comment
score: 1

http://stackoverflow.com/q/47993740
upvote count: 1
has comment: http://stackoverflow.com/comment/82955745
has answer: http://stackoverflow.com/a/47994180
has comment: http://stackoverflow.com/comment/82956705
tagged with: permutation
favorite count: 0
possible better answer: http://stackoverflow.com/a/47996996
tagged with: python
has answer: http://stackoverflow.com/a/47996996
tagged with: list
has comment: http://stackoverflow.com/comment/82956253
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82955733
has body: Let's say I have a list or an array of the type: mylist = [1, 2, 3, 4] And I want to replace an item in this list. Normally I would use something like the following: mylist[2] = 7 That works well. However, can someone explain how to create all possible permutations of mylist when replacing one or more items in mylist. For example, I want to create the following: [7, 2, 3, 4] [7, 7, 3, 4] [7, 2, 7, 4] [7, 7, 7, 4] [7, 2, 3, 7] ...(and so on) I know I can use itertools to generate all possible permutations, but how can I specify that I want to substitute an item in all possible locations in the list before generating the permutations? Here is how I tried to use itertools: list(itertools.permutations([1,2,3,4,7], 4)) This doesn't work because it doesn't substitute 7 more than one time per permutation, and it also generates permutations that do not include the number 7.
accepted answer: http://stackoverflow.com/a/47994180
score: -1
has title: Replacing items in a list in all possible permutations
answer count: 2
downvote count: 2

http://stackoverflow.com/comment/82749366
comment on: http://stackoverflow.com/a/47891371
score: 0
type: AnswerComment
type: Comment
has text: @仲耀晖 I suspect there's a file named `path.py` which is reside in the same directory where you launch interactive shell (terminal). `path.py` is not a part of standard library.

http://stackoverflow.com/comment/82937902
type: QuestionComment
has text: You might be looking for the [``cell.variables`` property](https://www.tensorflow.org/api_docs/python/tf/contrib/rnn/BasicRNNCell#variables). [This](https://stackoverflow.com/questions/47640455/tensorboard-visualize-weights-of-lstm/47643427#47643427) answer might be useful. If that's not what you're looking for, could you link the source code? Or explain what ``W`` and ``U`` are?
comment on: http://stackoverflow.com/q/47965256
score: 0
type: Comment

http://stackoverflow.com/a/77374882
has comment: http://stackoverflow.com/comment/136410701
score: 0
has body: go to site_package directory and remove all cv and opencv packages. then run "pip install opencv-python".
type: Answer
answers question: http://stackoverflow.com/q/47857141

http://stackoverflow.com/q/47995002
has comment: http://stackoverflow.com/comment/82958211
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
has title: Panda export to csv
tagged with: python
has answer: http://stackoverflow.com/a/47997366
score: 2
upvote count: 2
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/82958410
has comment: http://stackoverflow.com/comment/82959818
has body: I have the code bellow: from xlsxwriter import Workbook import os,shutil import requests import pandas from bs4 import BeautifulSoup MAX_RETRIES = 20 base_url='https://pagellapolitica.it/politici/sfoggio/9/matteo-renzi?page=' for page in range(1,32,1): l=[] session = requests.Session() adapter = requests.adapters.HTTPAdapter(max_retries=MAX_RETRIES) session.mount('https://', adapter) session.mount('http://', adapter) site=(base_url+str(page)+".html") # print(site) c=session.get(site) r=c.content soup=BeautifulSoup(r,'html.parser') all=soup.find_all("div",{"class":"clearfix"}) for d in all: links=d.find_all("a") len(links) l=[] # workbook = Workbook('bbb.xlsx') # worksheet = workbook.add_worksheet() # row +=0 # worksheet.write(row,0,'Link') # worksheet.write(row,1,'Name ') # row+=1 for a in links[5:17]: d={} href=(a["href"]) basic_url=('https://pagellapolitica.it/') site =basic_url + href #print(site) c=requests.get(site) r=c.content soup=BeautifulSoup(r,'html.parser') Name=soup.find("h3",{"class":"pull-left"}).text Fact_checking=soup.find("label",{"class":"verdict-analisi"}).text quote=soup.find("div",{"class":"col-xs-12 col-sm-6 col-smm-6 col-md-5 col-lg-5"}).text all=soup.find_all("span",{"class":"item"}) Topic=all[0].text Date=all[2].text a=all[3].find("a",{"class":"" ""}) Link=a["href"] Text=soup.find("div",{"class":"col-xs-12 col-md-12 col-lg-12"}).text d["Name"]=Name d["Fact_checking"]=Fact_checking d["Quote"]=quote d["Economic_topic"]=Topic d["Date"]=Date d["Link"]=Link d["Text"]=Text l.append(d) df=pandas.DataFrame(l) df.to_csv("outing.csv") The problem that when I export the data in csv I only get 6 rows of results.When I do print(df) and print(l) it prints all the data that I havein the list,however when i check len(l) I only get a lenght of 6. Any ideas why this is happening?? Thank you in advance!
tagged with: pandas
answer count: 1
downvote count: 0

http://stackoverflow.com/q/48005152
tagged with: python
has body: I need to work with an array to make some computations. I have the following data: x = [[81, 68, 71, 71, 67, -72], [79, 77, 88, 88, 59, -71], [67, 71, 68, 68, 85, -66]] and I would need to play with the data and extract from each column the number of positive and negative values so the output should be like: positive_value = [3,3,3,3,0] negative_vaue = [0,0,0,0,3] I gave it a try using a for loop with no success and with Numpy as well, but I do not really know how to use it. What is the best way to get that result?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48005309
tagged with: list
has answer: http://stackoverflow.com/a/52734109
has comment: http://stackoverflow.com/comment/82979273
has comment: http://stackoverflow.com/comment/82978585
has comment: http://stackoverflow.com/comment/82979007
downvote count: 3
has comment: http://stackoverflow.com/comment/82978795
has comment: http://stackoverflow.com/comment/82979199
has comment: http://stackoverflow.com/comment/82978740
has comment: http://stackoverflow.com/comment/106979013
type: Question
has answer: http://stackoverflow.com/a/60470495
has comment: http://stackoverflow.com/comment/82979823
has comment: http://stackoverflow.com/comment/82978906
has answer: http://stackoverflow.com/a/60471844
has comment: http://stackoverflow.com/comment/82978637
answer count: 6
has title: Extract the count of positive and negative values from an array
has comment: http://stackoverflow.com/comment/82979525
has answer: http://stackoverflow.com/a/48005309
has comment: http://stackoverflow.com/comment/82979244
score: 8
upvote count: 11
favorite count: 0
possible better answer: http://stackoverflow.com/a/48005552
has comment: http://stackoverflow.com/comment/82979424
has answer: http://stackoverflow.com/a/48005552
has answer: http://stackoverflow.com/a/48005328
tagged with: count

http://stackoverflow.com/q/47902750
has comment: http://stackoverflow.com/comment/82772290
duplicate of: http://stackoverflow.com/q/27616778
has answer: http://stackoverflow.com/a/47902886
score: 8
has comment: http://stackoverflow.com/comment/82772314
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/47902886
favorite count: 0
upvote count: 8
type: Question
tagged with: argparse
tagged with: python
linked to: http://stackoverflow.com/q/27616778
has title: How to accept `choices` in Python argparse irrespective of case?
has body: I have a flag in a Python program which can only be certain strings, rock, paper, or scissors. Python argparse has a great way to implement this, using choices, container of the allowable values for the argument. Here's an example from the documentation: import argparse ... parser = argparse.ArgumentParser(prog='game.py') parser.add_argument('move', choices=['rock', 'paper', 'scissors']) parser.parse_args(['rock']) ### Namespace(move='rock') parser.parse_args(['fire']) ### usage: game.py [-h] {rock,paper,scissors} ### game.py: error: argument move: invalid choice: 'fire' (choose from 'rock','paper', 'scissors') I would like to implement choices such that the choices are not case-sensitive, i.e. users could input RoCK and it would still be valid. What is the standard way to do this?
answer count: 1

http://stackoverflow.com/comment/82931108
has text: `mysql` isn't part of the standard library, so you have to install it yourself if you want to use it. Download it from https://pypi.python.org/pypi/MySQL-python.
comment on: http://stackoverflow.com/q/47980601
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48010814
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48010748
type: Answer
accepted answer of: http://stackoverflow.com/q/48010748
score: 41
downvote count: 0
upvote count: 41
has body: OS is python's standard library. So no need to download it.

http://stackoverflow.com/comment/82850860
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47940731
type: QuestionComment
has text: @Divakar works, can you make it to pandas dataframe

http://stackoverflow.com/q/47986121
has comment: http://stackoverflow.com/comment/82941163
type: Question
has comment: http://stackoverflow.com/comment/82941220
has title: Week number of the month
has comment: http://stackoverflow.com/comment/82941271
score: 0
linked to: http://stackoverflow.com/q/3806473
tagged with: pandas
answer count: 1
tagged with: series
has answer: http://stackoverflow.com/a/47986732
type: UnansweredQuestion
tagged with: python
has body: Does pandas (python) offer a way to easily get the current week of the month (1:4) from a date series? data = {'date': ['2014-05-01', '2014-05-01', '2014-05-02', '2014-05-02', '2014-05-02', '2014-05-02', '2014-05-03', '2014-05-03', '2014-05-04', '2014-05-04']} df = pd.DataFrame(data, columns = ['date']) df['date']=pd.to_datetime(df['date']) def week_of_month(dt): """ Returns the week of the month for the specified date. """ first_day = dt.replace(day=1) dom = dt.day adjusted_dom = dom + first_day.weekday() return int(ceil(adjusted_dom/7.0)) df ['week']=np.nan for i in range(len(df)): df ['week'][i] = week_of_month(df.date.iloc[i]) with a short data set it works but with a large data set takes to much resources

http://stackoverflow.com/comment/82859639
comment on: http://stackoverflow.com/a/47930033
score: 0
type: AnswerComment
type: Comment
has text: @Parfait: yes, I have tested `to_sql` and it takes little more than 7 mins to insert 26646 rows. I want to compare other methods but for that, I have to get other methods working.

http://stackoverflow.com/q/47945512
has title: How to reshape input for keras LSTM?
tagged with: lstm
tagged with: numpy
has comment: http://stackoverflow.com/comment/82861005
tagged with: neural-network
type: UnansweredQuestion
tagged with: keras
has body: I have a numpy array of some 5000 rows and 4 columns (temp, pressure, speed, cost). So this is of the shape (5000, 4). Each row is an observation at a regular interval this is the first time i'm doing time series prediction and I'm stuck on input shape. I'm trying to predict a value 1 timestep from the last data point. How do I reshape it into the 3D form for LSTM model in keras? Also It will be much more helpful if a small sample program is written. There doesn't seem to be any example/tutorial where the input has more than one feature (and also not NLP).
has comment: http://stackoverflow.com/comment/82861504
linked to: http://stackoverflow.com/q/45764629
tagged with: python
favorite count: 0
type: Question
score: 0
upvote count: 1
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82862191
has answer: http://stackoverflow.com/a/47946295

http://stackoverflow.com/comment/82762987
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47897974
has text: Variable have the search result sir.It shows in the picture.are you want in string format?

http://stackoverflow.com/comment/82976561
type: AnswerComment
has text: That works, thanks! However, is there a way I can sort the final dataframe so that the matching rows are bunched together?
type: Comment
comment on: http://stackoverflow.com/a/48004204
score: 0

http://stackoverflow.com/q/48000502
type: Question
answer count: 2
upvote count: 5
score: 4
has answer: http://stackoverflow.com/a/54917357
tagged with: module
favorite count: 0
tagged with: installation
type: UnansweredQuestion
has title: ImportError: cannot import name '_BACKCOMPAT_MAGIC_NUMBER'
tagged with: pip
tagged with: python
downvote count: 1
has body: Trying to use pip to install just installed another version of python (3.4) get error ImportError: cannot import name '_BACKCOMPAT_MAGIC_NUMBER'
has answer: http://stackoverflow.com/a/50115085

http://stackoverflow.com/a/47888539
type: Answer
answers question: http://stackoverflow.com/q/47888054
score: 2
accepted answer of: http://stackoverflow.com/q/47888054
has body: You may want to look into python's list comprehension. arr = [int(arr_temp) for arr_temp in input().strip().split(' ')] Let me answer this with an example, suppose you input : 1 3 4 29 12 -2 0 the input function reads this as a string The strip function eliminates whitespace from both ends of the string, The split function splits the string into smaller strings with a delimiter: (that is a literal space) In the list comprehension you can read it as : for arr_temp in input().strip().split(' ') : int(arr_temp) We get a list of integers stored in the variable arr (arr = [1, 3, 4, 29, 12, -2, 0]). This is not an actual replacement code for the list comprehension but it might give you a better understanding of what it is trying to do. Extra note : Apart from lists, Python also has comprehension expressions for sets, dictionaries and generators.
downvote count: 0
type: AcceptedAnswer
upvote count: 2

http://stackoverflow.com/q/47858956
has answer: http://stackoverflow.com/a/47860660
accepted answer: http://stackoverflow.com/a/47860660
has answer: http://stackoverflow.com/a/47860104
tagged with: python
linked to: http://stackoverflow.com/q/23930274
has title: How to convert Tkinter line object to list of points
type: AnsweredQuestion
tagged with: tkinter
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/82683230
has comment: http://stackoverflow.com/comment/82682965
possible better answer: http://stackoverflow.com/a/47860104
has comment: http://stackoverflow.com/comment/82682585
answer count: 2
downvote count: 0
has body: I'm creating a GUI that uses the Tkinter Canvas widget to allow a user to draw a line over an image. I would like to convert that line object to a list of points that make up that line. I'm able to get the coordinates and bounding box and other things described under the documentation, but I wasn't able to find the answer to this. As an example, if I had a line that started at point (0,0) and ended at (3,3), I would like a list that includes points [(0,0), (1,1), (2,2), (3,3)] Any help is greatly appreciated.
has comment: http://stackoverflow.com/comment/82682703
favorite count: 0

http://stackoverflow.com/comment/82898525
type: QuestionComment
has text: @chris what means an array of arrays? can you give me a detailed example?
comment on: http://stackoverflow.com/q/47964378
score: 0
type: Comment

http://stackoverflow.com/q/47972832
favorite count: 0
has comment: http://stackoverflow.com/comment/82915523
linked to: http://stackoverflow.com/q/36819739
tagged with: python
has comment: http://stackoverflow.com/comment/82915561
has comment: http://stackoverflow.com/comment/82915573
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47972873
upvote count: 2
has body: When trying to calculate the eigenvalues of a particular matrix using scipy's eigh function, I am getting negative eigenvalues where I do not expect them. My code is as follows: import numpy as np from scipy import linalg def get_symmetrized_eigens(array): a = np.dot(array.transpose(), array) # Compute square matrix from the input evals, evecs = linalg.eigh(a) # Compute eigenvalues, eigenvectors # Output to test for negative eigenvalues print('{0} eigenvalues computed'.format(evals.size)) for x in evals: if x &lt; 0: print(x) return evals, evecs The code is supposed to take an arbitrarily-sized matrix (in ndarray format), generate a square matrix from it by left-multiplying its transpose, and calculate the eigenvalues and eigenvectors of the generated square matrix. Mathematically, the eigenvalues of a square matrix generated in this way must be greater than or equal to zero (given an m by n real-valued matrix A, let T be the tranpose of A. Then TA is a symmetric matrix that has real, non-negative eigenvalues). But when I input the following 35 by 40 matrix: 127 127 127 127 127 127 127 127 127 127 127 125 127 128 126 118 116 128 236 253 254 254 254 253 253 254 254 254 254 254 254 254 253 253 253 253 253 253 253 254 127 127 127 127 127 127 127 127 127 127 127 126 129 121 140 116 116 116 241 255 254 254 254 253 253 253 254 254 254 254 255 254 254 254 253 253 253 253 253 254 127 127 127 127 126 125 126 128 127 123 126 125 135 191 204 116 116 116 208 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 127 127 127 126 123 127 129 125 124 129 126 169 233 252 173 116 116 116 173 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 127 127 127 127 128 129 121 130 127 141 218 254 254 252 136 116 116 116 136 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 127 127 127 124 125 124 131 125 174 243 252 253 252 237 116 116 116 116 116 239 255 255 255 255 255 255 255 255 255 255 255 2…
tagged with: scipy
type: Question
linked to: http://stackoverflow.com/q/28469682
accepted answer: http://stackoverflow.com/a/47972873
tagged with: numpy
has title: Why is scipy's eigh returning unexpected negative eigenvalues?
tagged with: matrix
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82915633
tagged with: eigenvalue

http://stackoverflow.com/comment/82916627
type: AnswerComment
score: 0
type: Comment
has text: @AyodhyankitPaul isn't it less complex to flatten out in one loop, and then append 'ID's in a separate loop, rather than calling the checker function in a loop, which contains another loop, therefore a nested loop?
comment on: http://stackoverflow.com/a/47973393

http://stackoverflow.com/q/47866996
has comment: http://stackoverflow.com/comment/82703503
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47867350
has body: I have a plot with several data points that I would like to keep as it is. One of the data point is 'better', because it does not only come with a value but also a probability assigned to it. I would like to show that probability by plotting the normal data points, and for the one with the measured PDF show a violinplot. So far I've done this with a scatter plot over plotted which looks somewhat like this (in an MWE): import numpy as np import matplotlib.pyplot as plt def plot(): x = np.linspace(0,20,20) data = x + np.random.rand(len(x)) y = 2*x histo = np.array([1,2,3,10,20,10,3,1]) y_better = np.array([9.5,9.8,10,11.5,12,13,15,16]) ax = plt.subplot() ax.plot(x,data,'o') ax.scatter(np.ones_like(histo)*x[10],y_better,c=histo,norm=matplotlib.colors.LogNorm(),s=100) plt.show() plot() which looks like this: While this works, and transports the message - but doesn't look too cool. Following the suggestion by @￼jadsq, I discovered violinplots, which look exactly like what I want! I now have the problem that the violinplot function assumes data and then conveniently draws the PDF. In my case I already have a measured PDF (which is what I want to plot). How could I make a plot that looks like the violin plot, but with my PDF (so without the estimation)?
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/47867350
tagged with: matplotlib
score: -1
upvote count: 0
answer count: 1
favorite count: 0
has title: violinplot style histogram in plot
tagged with: python

http://stackoverflow.com/a/48006709
has comment: http://stackoverflow.com/comment/120145959
has comment: http://stackoverflow.com/comment/82989621
upvote count: 9
has body: It is true, sklearn works only with 2D data. What you can try to do: Just use np.reshape on the training data to convert it to shape (3240, 20*5255). It will preserve all the original information. But sklearn will not be able to exploit the implicit structure in this data (e.g. that features 1, 21, 41, etc. are different versions of the same variable). Build a convolutional neural network on your original data (e.g. with tensorflow+Keras stack). CNNs were designed specially to handle such multidimensional data and exploit its structure. But they have lots of hyperparameters to tune. Use dimensionality reduction (e.g. PCA) on the data reshaped to (3240, 20*5255). It fill try to preserve as much information as possible, while still keeping number of features low. Use manual feature engineering to extract specific information from the data structure (e.g. descriptive statistics along each dimension), and train your model on such features. If you had more data (e.g. 100K examples), the first approach might work best. In your case (3K examples and 10K features) you need to regularize your model heavily to avoid overfitting.
accepted answer of: http://stackoverflow.com/q/48003185
has comment: http://stackoverflow.com/comment/120163677
has comment: http://stackoverflow.com/comment/82989474
answers question: http://stackoverflow.com/q/48003185
score: 9
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/82989722
has comment: http://stackoverflow.com/comment/120172946

duplicates
tags question: http://stackoverflow.com/q/48004089
tags question: http://stackoverflow.com/q/47959798
tags question: http://stackoverflow.com/q/47998672
tags question: http://stackoverflow.com/q/47948519
type: Tag
tag name: duplicates

http://stackoverflow.com/comment/82993937
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48012388
type: Comment
has text: so this was a simplified example. `second_route` is used to push data to a database. `message` is used to return the success of that data and reloading the page will requery a bunch of stuff from the database, so the `done` function with the div tag (while works in this example) will not work in my application. if I used `window.location.href` then I wouldn't have access to the message. Sorry my simple example oversimplifies things.

http://stackoverflow.com/comment/82924048
type: QuestionComment
comment on: http://stackoverflow.com/q/47976853
score: 0
has text: Strange, are you shuffling the data before modelling?
type: Comment

http://stackoverflow.com/q/47972000
has answer: http://stackoverflow.com/a/47972373
tagged with: bash
answer count: 3
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47972038
has title: How to run a bash file with no extension in Python
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47972036
type: Question
accepted answer: http://stackoverflow.com/a/47972038
has body: I was wondering how I could use the script from this page in Python: http://www.fmwconcepts.com/imagemagick/textcleaner/index.php When downloading it, there is no extension. I tried renaming it to "textcleaner.sh" and run the following: import subprocess subprocess.check_call(['textcleaner.sh', '-g', '-e', 'normalize', 'input_image.jpg', 'output_image.jpg']) But I get this error when doing so: Traceback (most recent call last): File "C:/Users/ikdem/PycharmProjects/McAffeeeeeee/bash test.py", line 11, in &lt;module&gt; subprocess.check_call(['textcleaner.sh', '-g', '-e', 'normalize', 'opl-small-1.jpg', 'output.jpg']) File "C:\Users\ikdem\AppData\Local\Programs\Python\Python35\lib\subprocess.py", line 579, in check_call retcode = call(*popenargs, **kwargs) File "C:\Users\ikdem\AppData\Local\Programs\Python\Python35\lib\subprocess.py", line 560, in call with Popen(*popenargs, **kwargs) as p: File "C:\Users\ikdem\AppData\Local\Programs\Python\Python35\lib\subprocess.py", line 950, in __init__ restore_signals, start_new_session) File "C:\Users\ikdem\AppData\Local\Programs\Python\Python35\lib\subprocess.py", line 1220, in _execute_child startupinfo) OSError: [WinError 193] %1 is not a valid Win32 application
possible better answer: http://stackoverflow.com/a/47972036

http://stackoverflow.com/a/47969621
type: Answer
upvote count: 4
downvote count: 0
score: 4
has body: Use enumerate and insert: x = [['A','B','C','D'],['E','F','G','H']] y = [] for index, li in enumerate(x): li_copy = li[:] li_copy.insert(0, index) y.append(li_copy) print(y) # [[0, 'A', 'B', 'C', 'D'], [1, 'E', 'F', 'G', 'H']] Or if you don't mind overwriting x: x = [['A','B','C','D'],['E','F','G','H']] for index, li in enumerate(x): li.insert(0, index) print(x) # [[0, 'A', 'B', 'C', 'D'], [1, 'E', 'F', 'G', 'H']]
answers question: http://stackoverflow.com/q/47969616
has comment: http://stackoverflow.com/comment/82908810
has comment: http://stackoverflow.com/comment/82908701

http://stackoverflow.com/q/47996814
has body: I'm relatively new in python/django thing. Having 3 models with some fields for example: class Card(models.Model): id = models.AutoField(primary_key=True) cardtype_id = models.CharField(max_length=10) holder_name = models.CharField(max_length=100) card_number = models.IntegerField(default=0) email = models.EmailField(blank=True) birthday = models.DateField(blank=True, default=None) created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(default=timezone.now) strip = models.CharField(max_length=20, default="strip") def __str__(self): return self.holder_name class Transaction(models.Model): id = models.AutoField(primary_key=True) description = models.CharField(max_length=100) class CardTransactions(models.Model): card = models.ForeignKey(Card, on_delete=models.CASCADE) transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE) value = models.DecimalField(max_digits=7, decimal_places=2, blank=True) value_date = models.DateTimeField(default=timezone.now) created = models.DateTimeField(default=timezone.now) description = models.CharField(max_length=200, blank=True) table_value = models.DecimalField(max_digits=7, decimal_places=2, blank=True) discount = models.DecimalField(max_digits=7, decimal_places=2, blank=True) net_value = models.DecimalField(max_digits=7, decimal_places=2, blank=True) doc_number = models.CharField(max_length=20, blank=True) How can I ask the user to input, for example, the "card_number" and print out the "description" on a HTML page?
tagged with: http://stackoverflow.com/tag/html
favorite count: 0
type: UnansweredQuestion
score: -3
tagged with: django
tagged with: python
has title: How do I make a input from the user to search for something in django/python?
has comment: http://stackoverflow.com/comment/82961880
upvote count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47996937
has answer: http://stackoverflow.com/a/47996948
downvote count: 3

http://stackoverflow.com/comment/82733123
type: Comment
has text: note that I was on numpy v1.12.1, and had to upgrade to v1.13.3 for this to work.
comment on: http://stackoverflow.com/a/47882531
score: 0
type: AnswerComment

http://stackoverflow.com/q/47876999
score: 4
answer count: 2
has body: I'm recently struggling with using sklearn for my project. I wanted to build a classifier and classify my data into six groups. the total sample size was 88 then I split the data into train(66) and test(22) I did exactly as sklearn documentation showed, here is my code from sklearn.multiclass import OneVsRestClassifier from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis as QDA clf = OneVsRestClassifier(QDA()) QDA_score = clf.fit(train,label).decision_function(test) from sklearn.metrics import roc_curve, auc from sklearn.metrics import roc_curve fpr = dict() tpr = dict() roc_auc = dict() for i in range(3): fpr[i], tpr[i], _ = roc_curve(label_test[:, i], QDA_score[:, i]) roc_auc[i] = auc(fpr[i], tpr[i]) from itertools import cycle import matplotlib.pyplot as plt plt.figure() lw = 2 colors = cycle(['aqua', 'darkorange', 'cornflowerblue']) for i, color,n in zip(range(3), colors,['_000','_15_30_45','60']): plt.plot(fpr[i], tpr[i], color=color, lw=lw, label='ROC curve of {0} (area = {1:0.2f})' ''.format(n , roc_auc[i])) plt.plot([0, 1], [0, 1], 'k--', lw=lw) plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('ROC for multi-classes') plt.legend(loc="lower right") plt.show() the link is my result. however every time I run the code the result changes. I'm wondering if there is anyway that I can combine this with Cross validation and compute average and stable ROC for each class Thanks!
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/47877367
favorite count: 0
tagged with: roc
has comment: http://stackoverflow.com/comment/83224811
has answer: http://stackoverflow.com/a/51425049
tagged with: python
upvote count: 4
downvote count: 0
type: UnansweredQuestion
tagged with: machine-learning
type: Question
has title: how to compute average ROC for cross validated for multiclass
has comment: http://stackoverflow.com/comment/89821116
tagged with: cross-validation

http://stackoverflow.com/comment/82708147
has text: Way to few information about your input data. According to your two very simple examples you could just use `split()[0]`.
type: Comment
type: QuestionComment
score: 7
comment on: http://stackoverflow.com/q/47871354

http://stackoverflow.com/comment/82742764
comment on: http://stackoverflow.com/q/47888396
score: 0
type: QuestionComment
has text: What function does `count` have? You initialize, increase it but what is it for? When would this `while` loop actually break, looks infinite at first glance?
type: Comment

http://stackoverflow.com/a/47921600
has comment: http://stackoverflow.com/comment/82815965
has body: I was not able to comment so I had to post an answer. Only immutable data types can be used as keys, i.e. no lists or dictionaries can be used If you use a mutable data type as a key, you get an error message.Tuple as keys are okay. With what i can tell is the problem is in your view code: This context = {team:[hr,js]} should be this: context = {"team":[hr,js]} or context = dict(team=[hr,js])
type: Answer
has comment: http://stackoverflow.com/comment/82811099
has comment: http://stackoverflow.com/comment/82816974
score: 0
has comment: http://stackoverflow.com/comment/82811446
answers question: http://stackoverflow.com/q/47904732

http://stackoverflow.com/q/47884709
has answer: http://stackoverflow.com/a/47921369
downvote count: 0
answer count: 1
score: 8
favorite count: 0
has comment: http://stackoverflow.com/comment/82735403
tagged with: python
type: AnsweredQuestion
tagged with: pytest
has comment: http://stackoverflow.com/comment/82735276
tagged with: pytest-cov
upvote count: 8
type: Question
has comment: http://stackoverflow.com/comment/82735138
has body: I am getting ImportError: No module named _pluggy error when running tests using pytest. Then I tried installing pluggy using pip install pluggy. It installs pluggy==0.6.0 successfully, but is still giving the error. Versions List (From running pip freeze | grep pytest) pytest==3.3.1 pytest-cov==2.5.1 pytest-metadata==1.5.0 pytest-runner==3.0 pluggy==0.6.0 Python 2.7.12 Shown below is the stack trace Tests run successfully when run in a virtualenv. What are the possible causes which can cause this error in a non-virtualenv environment?
accepted answer: http://stackoverflow.com/a/47921369
tagged with: python-2.7
has title: Python: ImportError: No module named _pluggy

http://stackoverflow.com/q/47972386
tagged with: python
has body: So far I have this code: When it's executed, you'll see two windows main and another one called Figure 1, when the csv data is readed, and the plot button pressed, The graph is shown in another window (Figure 2) How can I fix this issues? Many, many thanks in advance for your time! import sys import pandas as pd import matplotlib matplotlib.use('QT5Agg') from PyQt5 import QtWidgets from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayout from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar import matplotlib.pyplot as plt from matplotlib import style style.use('ggplot') class Window(QtWidgets.QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): self.setGeometry(600,300, 1000, 600) self.center() grid = QtWidgets.QGridLayout() widget = QtWidgets.QWidget(self) self.setCentralWidget(widget) widget.setLayout(grid) #Import CSV Button btn1 = QtWidgets.QPushButton('Import CSV', self) btn1.resize(btn1.sizeHint()) btn1.clicked.connect(self.getCSV) grid.addWidget(btn1, 1, 0) self.figure = plt.figure(figsize=(15,5)) self.canvas = FigureCanvas(self.figure) grid.addWidget(self.canvas, 2,0,1,2) btn2 = QtWidgets.QPushButton('Plot', self) btn2.resize(btn2.sizeHint()) btn2.clicked.connect(self.plot) grid.addWidget(btn2, 1, 1) self.show() def plot(self): self.df.plot(x='col1',y='col2') self.canvas.draw() def getCSV(self): filePath, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Open file', '/home') if filePath != "": print ("Dirección",filePath) self.df = pd.read_csv(str(filePath)) def center(self): qr = self.frameGeometry() cp = QtWidgets.QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) def main(): app = QtWidgets.QApplication(sys.argv) w = Window() sys.exit(app.exec_()) if __name__ == '__main__': main()
type: AnsweredQuestion
tagged with: pyqt5
type: Question
accepted answer: http://stackoverflow.com/a/47972681
tagged with: matplotlib
score: 0
tagged with: pandas
tagged with: pyqt
answer count: 1
has answer: http://stackoverflow.com/a/47972681
has title: How can I have the matplotlib graph with pandas.plot() in the widget?

http://stackoverflow.com/a/47950273
has comment: http://stackoverflow.com/comment/82870393
type: Answer
upvote count: 1
has body: You want to set up a related_name on your foreign key so that you can fetch all your subsections corresponding to the section. class Section(models.Model): section_title = models.CharField(primary_key = True, unique = True, max_length = 50) class Subsection(models.Model): subsection_title = models.CharField(max_length = 50) subsection_section = models.ForeignKey( 'Section', related_name = 'subsections', on_delete = models.CASCADE, ) And then you can change your template code to loop over your subsections as follows: {% for section in sections %} &lt;div class="sectionHeader"&gt; {{ section.section_title }} &lt;/div&gt; &lt;div class="forumSection"&gt; &lt;div&gt; {% for subsection in section.subsections.all %} {{ subsection.subsection_title }} {% endfor %} &lt;/div&gt; &lt;/div&gt; {% endfor %} See https://docs.djangoproject.com/en/1.11/topics/db/queries/#related-objects for more information.
has comment: http://stackoverflow.com/comment/82870144
has comment: http://stackoverflow.com/comment/82870154
accepted answer of: http://stackoverflow.com/q/47950107
has comment: http://stackoverflow.com/comment/82870248
score: 1
has comment: http://stackoverflow.com/comment/82870150
answers question: http://stackoverflow.com/q/47950107
has comment: http://stackoverflow.com/comment/82870157
has comment: http://stackoverflow.com/comment/82870354
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82870347
has comment: http://stackoverflow.com/comment/82870373
has comment: http://stackoverflow.com/comment/82870298

http://stackoverflow.com/comment/82952285
has text: @Sanket see comment by AmosEgel - it's not an ideal approach, and is brittle.
score: 0
comment on: http://stackoverflow.com/q/47991909
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82721793
score: 0
comment on: http://stackoverflow.com/q/47877858
type: QuestionComment
type: Comment
has text: Could it be the input_series?? inputs_series = tf.split(1, truncated_backprop_length, batchX_placeholder) labels_series = tf.unstack(batchY_placeholder, axis=1)

http://stackoverflow.com/q/47904813
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47904842
score: 3
downvote count: 0
tagged with: pivot
has title: Pandas Pivot repeat index row
type: Question
upvote count: 3
tagged with: pandas
answer count: 1
has body: If I export a Pandas Pivot Table to CSV table I get first second bar one A 0.721555 B -0.706771 two A -1.039575 B 0.271860 baz one A -0.424972 B 0.567020 two A 0.276232 B -1.087401 because I am working with this data in excel, I would have all rows repeated, for example first second bar one A 0.721555 bar one B -0.706771 bar two A -1.039575 bar two B 0.271860 baz one A -0.424972 baz one B 0.567020 baz two A 0.276232 baz two B -1.087401 Do you know how is that possible?
favorite count: 0

dictionary
tags question: http://stackoverflow.com/q/48003385
tags question: http://stackoverflow.com/q/47922235
tags question: http://stackoverflow.com/q/47960190
tags question: http://stackoverflow.com/q/47972274
tags question: http://stackoverflow.com/q/47899477
tags question: http://stackoverflow.com/q/47947082
tags question: http://stackoverflow.com/q/47916762
tags question: http://stackoverflow.com/q/47987584
tags question: http://stackoverflow.com/q/47959908
tags question: http://stackoverflow.com/q/47908310
tags question: http://stackoverflow.com/q/47981828
tags question: http://stackoverflow.com/q/47891699
tags question: http://stackoverflow.com/q/47856949
tags question: http://stackoverflow.com/q/47910532
tags question: http://stackoverflow.com/q/47991296
tags question: http://stackoverflow.com/q/47893854
tags question: http://stackoverflow.com/q/47870210
tags question: http://stackoverflow.com/q/47983699
tags question: http://stackoverflow.com/q/47887071
tags question: http://stackoverflow.com/q/47950212
tags question: http://stackoverflow.com/q/47935850
tags question: http://stackoverflow.com/q/47872781
tags question: http://stackoverflow.com/q/47905378
tags question: http://stackoverflow.com/q/47973024
tags question: http://stackoverflow.com/q/47961192
tags question: http://stackoverflow.com/q/47896329
tags question: http://stackoverflow.com/q/47920845
tags question: http://stackoverflow.com/q/48000143
tags question: http://stackoverflow.com/q/47869308
tags question: http://stackoverflow.com/q/47984091
tags question: http://stackoverflow.com/q/48002267
tags question: http://stackoverflow.com/q/47865048
tags question: http://stackoverflow.com/q/47879762
tags question: http://stackoverflow.com/q/47984836
tags question: http://stackoverflow.com/q/47934409
tags question: http://stackoverflow.com/q/47946407
tags question: http://stackoverflow.com/q/47998184
tags question: http://stackoverflow.com/q/47994685
tags question: http://stackoverflow.com/q/47933089
tags question: http://stackoverflow.com/q/47893774
tags question: http://stackoverflow.com/q/47858802
tags question: http://stackoverflow.com/q/47930052
tag name: dictionary
tags question: http://stackoverflow.com/q/47933978
tags question: http://stackoverflow.com/q/47869316
tags question: http://stackoverflow.com/q/47949810
tags question: http://stackoverflow.com/q/47961922
tags question: http://stackoverflow.com/q/47957134
tags question: http://stackoverflow.com/q/48000274
tags question: http://stackoverflow.com/q/47911607
tags question: http://stackoverflow.com/q/47907655
tags question: http://stackoverflow.com/q/47867468
tags question: http://stackoverflow.com/q/47910907
tags question: http://stackoverflow.com/q/47929256
tags question: http://stackoverflow.com/q/48004089
tags question: http://stackoverflow.com/q/47856298
tags question: http://stackoverflow.com/q/47984583
tags question: http://stackoverflow.com/q/47981693
tags question: http://stackoverflow.com/q/47879938
tags question: http://stackoverflow.com/q/47942735
tags question: http://stackoverflow.com/q/47957841
tags question: http://stackoverflow.com/q/47894090
tags question: http://stackoverflow.com/q/47962601
tags question: http://stackoverflow.com/q/47913215
tags question: http://stackoverflow.com/q/47914610
tags question: http://stackoverflow.com/q/48011526
tags question: http://stackoverflow.com/q/47890929
tags question: http://stackoverflow.com/q/47972195
tags question: http://stackoverflow.com/q/47927096
tags question: http://stackoverflow.com/q/47960757
tags question: http://stackoverflow.com/q/47879585
tags question: http://stackoverflow.com/q/47930394
tags question: http://stackoverflow.com/q/47873034
tags question: http://stackoverflow.com/q/47891623
tags question: http://stackoverflow.com/q/47889916
tags question: http://stackoverflow.com/q/47979374
tags question: http://stackoverflow.com/q/47948519
tags question: http://stackoverflow.com/q/47941253
tags question: http://stackoverflow.com/q/48006742
tags question: http://stackoverflow.com/q/48004577

http://stackoverflow.com/a/47922282
has comment: http://stackoverflow.com/comment/82812263
has comment: http://stackoverflow.com/comment/82812206
answers question: http://stackoverflow.com/q/47922128
score: 0
has body: i would recommend, to add a for-loop. To get the same results do for i in range(n): A[i] = radom.choice(foo) n is the length of your Array and to count add a variable berfore the loop, like countZeros = 0 countOnes = 0 and in the loop add if a == 0: countZeros++ else: countOnes++
type: Answer

http://stackoverflow.com/comment/82745982
has text: You're skipping `__init__` method for your objects. As they are, they are just containers for methods.
comment on: http://stackoverflow.com/q/47888559
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82759362
type: Comment
has text: what is happen if you run code without `os.remove()` ? Do you need it ?
type: QuestionComment
comment on: http://stackoverflow.com/q/47888545
score: 0

http://stackoverflow.com/comment/82863897
type: Comment
type: QuestionComment
has text: And to answer in a comment, `°` is treated as a literal character. I presume the input language uses it as a bullet marking the items.
score: 1
comment on: http://stackoverflow.com/q/47946897

http://stackoverflow.com/q/47970891
tagged with: pandas
tagged with: python
linked to: http://stackoverflow.com/q/46944650
score: 7
answer count: 4
has answer: http://stackoverflow.com/a/47970920
has answer: http://stackoverflow.com/a/47971055
has answer: http://stackoverflow.com/a/47970923
upvote count: 7
possible better answer: http://stackoverflow.com/a/47970920
type: AnsweredQuestion
has body: I have a pandas dataFrame in which I would like to check if one column is contained in another. Suppose: df = DataFrame({'A': ['some text here', 'another text', 'and this'], 'B': ['some', 'somethin', 'this']}) I would like to check if df.B[0] is in df.A[0], df.B[1] is in df.A[1] etc. Current approach I have the following apply function implementation df.apply(lambda x: x[1] in x[0], axis=1) result is a Series of [True, False, True] which is fine, but for my dataFrame shape (it is in the millions) it takes quite long. Is there a better (i.e. faster) implamentation? Unsuccesfull approach I tried the pandas.Series.str.contains approach, but it can only take a string for the pattern. df['A'].str.contains(df['B'], regex=False)
has title: Faster implementation of pandas apply function
has answer: http://stackoverflow.com/a/47971054
tagged with: apply
type: Question
accepted answer: http://stackoverflow.com/a/47970923
downvote count: 0
tagged with: string
favorite count: 0

http://stackoverflow.com/q/47871639
type: Question
has comment: http://stackoverflow.com/comment/82716007
tagged with: python
has comment: http://stackoverflow.com/comment/82713282
has comment: http://stackoverflow.com/comment/82810327
has answer: http://stackoverflow.com/a/47872577
has answer: http://stackoverflow.com/a/47876278
score: 0
upvote count: 1
downvote count: 1
has body: I am new to Python but I have been using Perl for some time. In Perl, in order to limit search of an file to specific block of text, I would write something like below: if (/start_line/ ... /end_line/) { do something here } The condition /start_line/ ... /end_line/ starts being true once the /start_line/ regex matches and then continues being true until after the /end_line/ regex matches. In a loop that reads input line by line, this would execute the if-block for all lines between the start line and the end line, inclusive. How can I express the same condition in Python?
has answer: http://stackoverflow.com/a/47874334
has comment: http://stackoverflow.com/comment/82715931
possible better answer: http://stackoverflow.com/a/47871858
tagged with: perl
has comment: http://stackoverflow.com/comment/82730785
has answer: http://stackoverflow.com/a/47871858
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82794884
accepted answer: http://stackoverflow.com/a/47874334
has title: Python - repetitive blocks of text
has comment: http://stackoverflow.com/comment/82709055
favorite count: 0

http://stackoverflow.com/a/47950044
type: Answer
has comment: http://stackoverflow.com/comment/82870676
has comment: http://stackoverflow.com/comment/82870481
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47936640
score: 0
has comment: http://stackoverflow.com/comment/82871572
answers question: http://stackoverflow.com/q/47936640
has body: question = request.json['data'][0]['question'] will work.

http://stackoverflow.com/a/47939903
answers question: http://stackoverflow.com/q/47935421
score: 1
downvote count: 0
type: Answer
upvote count: 1
has body: You could make use of the slicing operator. op = sum len_a, len_b = len(ListA), len(ListB) min_len, max_len = min(len_a,len_b), max(len_a,len_b) ListC = list(map(op,zip(ListA[:min_len],ListB[:min_len]))) + ListA[min_len:max_len] + ListB[min_len:max_len] The last line will concatenate the remainder of the two lists. If they are the same length then it won't do anything. If they are not the same length then the ListSmaller[min_len:max_len] will be an empty list: []

http://stackoverflow.com/q/47889252
answer count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 1
tagged with: celery
score: 1
tagged with: multiprocessing
type: Question
tagged with: flask
favorite count: 0
has body: Let's say I'm creating the following service: @app.route('/train_model' , methods = ['GET' , 'POST']) Suppose multiple people want to train the model(using different datasets) using the above service. So, I need to incorporate parallelism now. So the following things has to be added Note: The following is not the complete code def make_celery(app): celery = Celery(app.import_name, broker = 'redis://localhost:6379',#amqp://localhost//, backend = 'redis://localhost:6379') celery.conf.update(app.config) TaskBase = celery.Task class ContextTask(TaskBase): abstract = True def __call__(self, *args, **kwargs): with app.app_context(): return TaskBase.__call__(self, *args, **kwargs) celery.Task = ContextTask return celery app = Flask(__name__) celery = make_celery(app) @app.route('/train_qna_service' , methods = ['GET' , 'POST']) def uploadfile(): train_model.delay() @celery.task(name='main.train_model') def train_model(): # do appropriate task to train the model pass But if I use train_model.delay(), I won't get the result. If I'll use train_model.wait(), other people can not hit the service. If I use multiprocessing module, still other people can not hit the service. What is the best way to support multiple training request using flask service ?
tagged with: python
has title: Parallelize the training of deep learning model using Flask

http://stackoverflow.com/comment/82930732
comment on: http://stackoverflow.com/q/47981061
has text: (dt, '%b %d, %Y %-I:%M:%S %p %Z')
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47925020
tagged with: python
has comment: http://stackoverflow.com/comment/82817619
accepted answer: http://stackoverflow.com/a/47925074
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82817848
type: Question
has title: ModuleNotFoundError: No moudle name <name> in docker python
has answer: http://stackoverflow.com/a/47925074
has body: I have two python files my_script.py test.py with below content. my_script.py #!/usr/bin/python3 import os import sys sys.path.append("/home/user/test") import test as count data = count.function() print(data) test.py #!/usr/bin/python3 import time def function(): print("This is function") return "test" When I execute my_script.py, I get the following result: This is function test I created docker image of my_script.py using Dockerfile: FROM python:3 ADD my_script.py / CMD [ "python3", "./my_script.py" ] But when I am running its container, I am getting an error: Traceback (most recent call last): File "./my_script.py", line 13, in &lt;module&gt; import test as count ModuleNotFoundError: No module named 'test' Initially I thought the container will look for test.py automatically and will perform its function but its not. How can I resolve this issue.
tagged with: containers
tagged with: docker
score: 5
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82818715
upvote count: 5
has comment: http://stackoverflow.com/comment/82817871

http://stackoverflow.com/comment/124964869
comment on: http://stackoverflow.com/a/48145639
has text: Hi, could you add in the setting of rvecs?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/47858935
type: UnansweredQuestion
type: Question
tagged with: financial
score: 0
tagged with: data-analysis
has title: How to merge two data frame to calculate effective spread in bond market in python
tagged with: python
has comment: http://stackoverflow.com/comment/82684345
has body: I want to compute Effective spread on bond market.(It is a little bit complex) I have 2 data frame first is Trade and the Second is quote: Trade(Transaction) is look like this: Id Date Index Time Volume Price 0 56033738624803469 2017-05-21 1 10:32:28 1 935049.7 1 56033738624803469 2017-05-21 1 11:54:41 10 919410.0 2 56033738624803469 2017-05-21 2 12:25:46 1 919410.0 3 56033738624803469 2017-05-21 1 11:48:08 5 954999.0 4 56033738624803469 2017-05-21 2 11:48:43 6 954999.0 5 56033738624803469 2017-05-21 1 10:00:49 50000 959900.0 and quote(Limit Order Book) is like this: BuyCount BuyPrice BuyTime BuyVol Date SID row SellTime SellPrice SellVol SellCount row.1 Quote-Spread MidQuote 1 930100 10:30:05 100 2017-05-21 56033738624803469 1 10:32:27 939999 5700 2 1 0.010643 935049.5 1 930000 10:30:05 260 2017-05-21 56033738624803469 2 06:12:52 940000 2817 1 2 0.010753 935000.0 1 928000 10:30:05 2892 2017-05-21 56033738624803469 3 06:12:52 946800 458 1 3 0.020259 937400.0 2 900000 10:30:05 35000 2017-05-21 56033738624803469 4 06:12:52 946980 6000 1 4 0.052200 923490.0 1 874001 10:30:05 100 2017-05-21 56033738624803469 5 06:12:52 946999 6000 1 5 0.083522 910500.0 Effective Spread is calculated like this: market order: 2×|pt−mt| (absolute differention) Where pt is the price for the transaction at time t , and mt is the mid quote at time t−ε (just before the trade). I should first merge this two data by time and then calculate the Effective Spread; for example: for data that been traded(First data frame) at time 10:32:28 this formula should be like this: Effective Spread = 2*(935049.7-935049.5).abs() Note 1: the mid quote of row == 1 is considered and other quotes should be neglected.because markets actual trade(best buy and best sell price is in row 1) My question is how can i merge this two data then i could calculate this formula. Edit: I have found this link but i my data is a little bit different. http://www.vincentgregoire.com/introduction-to-empirical-market-microstructure-in…
has comment: http://stackoverflow.com/comment/82683712
answer count: 0

http://stackoverflow.com/a/47969331
upvote count: 1
answers question: http://stackoverflow.com/q/47969262
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82908477
has comment: http://stackoverflow.com/comment/82908485
type: Answer
downvote count: 0
score: 1
has body: Try this: df[(df&gt;1).sum(1).gt(1)] Demo: import string In [118]: df = pd.DataFrame(np.random.rand(10,10)*1.2, columns=list(string.ascii_letters[:10])) In [119]: df Out[119]: a b c d e f g h i j 0 0.934290 0.426050 0.165846 1.114521 1.101023 0.924071 0.241893 0.890354 1.168406 0.506547 1 0.576869 1.091996 0.272124 0.834070 0.229545 0.585501 1.114688 0.957817 1.151957 0.761277 2 0.016659 1.138262 0.481773 0.186753 0.176585 0.497437 0.321805 0.664140 0.738851 0.177179 3 0.192605 0.395377 0.950169 0.678960 0.525349 0.050877 0.181615 0.105080 0.385672 0.401810 4 1.184054 1.097378 0.197706 0.453395 0.258631 1.088337 0.139201 0.217262 0.369734 1.054716 5 0.246081 0.234748 0.879371 0.198397 0.288288 0.534848 0.561080 0.732490 0.156947 0.662194 6 0.660215 0.221513 0.224576 0.049425 0.339101 0.441393 1.122385 0.057968 1.094025 1.130691 7 0.022977 0.681718 0.314200 0.622263 0.692124 0.803743 0.783381 0.715494 0.434911 0.247724 8 0.815742 0.419933 0.019704 0.764557 0.074530 0.990639 0.801125 0.403838 0.680618 1.043551 9 1.061915 0.229453 0.446562 0.324415 0.121421 0.270542 0.884124 0.926168 0.282650 0.267467 In [120]: df[(df&gt;1).sum(1).gt(1)] Out[120]: a b c d e f g h i j 0 0.934290 0.426050 0.165846 1.114521 1.101023 0.924071 0.241893 0.890354 1.168406 0.506547 1 0.576869 1.091996 0.272124 0.834070 0.229545 0.585501 1.114688 0.957817 1.151957 0.761277 4 1.184054 1.097378 0.197706 0.453395 0.258631 1.088337 0.139201 0.217262 0.369734 1.054716 6 0.660215 0.221513 0.224576 0.049425 0.339101 0.441393 1.122385 0.057968 1.094025 1.130691
accepted answer of: http://stackoverflow.com/q/47969262

http://stackoverflow.com/a/47977728
score: 1
answers question: http://stackoverflow.com/q/47977609
has body: There are several options depending on your environment and visualization libraries. Check this good answer
upvote count: 1
type: Answer
downvote count: 0

http://stackoverflow.com/q/47865277
has comment: http://stackoverflow.com/comment/82705413
has comment: http://stackoverflow.com/comment/82706271
has comment: http://stackoverflow.com/comment/82716812
has title: AttributeError: class Prolog has no attribute 'dynamic'
type: Question
has comment: http://stackoverflow.com/comment/82696090
has comment: http://stackoverflow.com/comment/82697466
score: 0
has comment: http://stackoverflow.com/comment/82696235
tagged with: swi-prolog
has body: I've installed pyswip on ubuntu and I followed the official documentation to do so. However, I'm still getting some issues, I found some workarounds for a couple of them and I'm still fighting with more. Here is the code and error I'm currently getting: &gt;&gt;&gt; from pyswip import Prolog, registerForeign, Variable, Functor &gt;&gt;&gt; registerForeign(ask_question,name='ask', arity=1) 1 &gt;&gt;&gt; hypothesize = Functor("hypothesize",1) &gt;&gt;&gt; Test = Variable() &gt;&gt;&gt; assertz = Functor('assertz',1) &gt;&gt;&gt; Prolog.dynamic("yes/1, no/1") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: class Prolog has no attribute 'dynamic' Any thoughts? Thanks!
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82703652
has comment: http://stackoverflow.com/comment/82696493
has comment: http://stackoverflow.com/comment/82706494
tagged with: python
has comment: http://stackoverflow.com/comment/82716027
has comment: http://stackoverflow.com/comment/82697507
has comment: http://stackoverflow.com/comment/82731067
answer count: 0

http://stackoverflow.com/a/47920260
has body: This is the simplest and cleanest way of doing it (universal across Python 2 and 3): print('\n'.join(a + ["===================="] + a)) This is the Python-3-only version: print(*(a + ["===================="] + a), sep='\n')
answers question: http://stackoverflow.com/q/47919179
type: Answer
score: 0

http://stackoverflow.com/a/47924971
accepted answer of: http://stackoverflow.com/q/47924825
has body: You have spaces in the column name. i.e. 'First Name' instead of 'FirstName', removing the spaces will solve your problem. If you want to preserve the spaces, use backticks '`' to wrap the string Sample code: columns = [ ('Last Name', 'First Name', 'Job', 'Country') ] #list of tuples for p in columns: q = """ CREATE TABLE IF NOT EXISTS stud_data (`{col1}` VARCHAR(250),`{col2}` VARCHAR(250),`{col3}` VARCHAR(250),`{col4}` VARCHAR(250)); """ sql_command = q.format(col1=p[0], col2=p[1], col3=p[2], col4 = p[3]) &gt;&gt;&gt; sql_command ' CREATE TABLE IF NOT EXISTS stud_data (`Last Name` VARCHAR(250),`First Name` VARCHAR(250),`Job` VARCHAR(250),`Country` VARCHAR(250)); '
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47924825

http://stackoverflow.com/comment/82992089
type: QuestionComment
comment on: http://stackoverflow.com/q/48011010
has text: @cᴏʟᴅsᴘᴇᴇᴅ done, thanks.
score: 0
type: Comment

http://stackoverflow.com/q/47864013
possible better answer: http://stackoverflow.com/a/47864274
has answer: http://stackoverflow.com/a/47864274
type: Question
has answer: http://stackoverflow.com/a/47864100
score: 3
has body: I want to binarize python list based on previous value, output should be 1 if previous value is lower, and 0 if higher. Example: [18985.0, 20491.0, 18554.0, 14241.0, 13390.0, 14965.0,] should become: [0, 1, 0, 0, 0, 1] Is there any elegant way to do this? Thanks in advance!
tagged with: algorithm
accepted answer: http://stackoverflow.com/a/47864100
has answer: http://stackoverflow.com/a/47864343
downvote count: 0
favorite count: 0
has title: Binarize a python list based on previous value
tagged with: python
has answer: http://stackoverflow.com/a/47864429
answer count: 4
type: AnsweredQuestion
tagged with: list
upvote count: 3

http://stackoverflow.com/comment/82892469
comment on: http://stackoverflow.com/q/47961641
type: Comment
type: QuestionComment
score: 1
has text: Did you try adding a timeout?

http://stackoverflow.com/q/47913700
tagged with: python
has comment: http://stackoverflow.com/comment/82795107
accepted answer: http://stackoverflow.com/a/47929306
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82795386
type: Question
score: 0
has answer: http://stackoverflow.com/a/47929306
has title: How to combine rows and put into single row in dataframe by sql or python
tagged with: sql
tagged with: hiveql
has body: I'd like to aggregate rows in certain column base on the relationship with other column and create certain column which contain aggregated data in json format. This is the example. Original data table Child Name Child Age Father Name Father Age Peter 5 Richard 40 James 15 Doug 45 Liz 2 Doug 45 Paul 6 Richard 40 Shirly 11 Charles 33 Eva 9 Chris 29 Converted Data table will be either Father Name Father Age Children Richard 40 {"Peter":"5", "Paul":"6"} Doug 45 {"James":"15","Liz":"2"} Charles 33 {"Shirly" : "11"} Chris 29 {"Eva" : "9"} Or Father Name Father Age Children Name Children Age Richard 40 {"Peter", "Paul"} {"5","6"} Doug 45 {"James", "Liz"} {"15","2"} Charles 33 {"Shirly"} {"11"} Chris 29 {"Eva"} {"9"} My code is import pandas as pd df = pd.DataFrame({ "Child Name" : ["Peter","James","Liz","Paul","Shirly","Eva"], "Child Age" : ["5","15","2","6","11","9"], "Father Name" : ["Richard","Doug","Doug","Richard","Charles","Chris"], "Father Age" : ["40","45","45","40","33","29"] }) print df g1 = df.groupby(["Father Name"])["Child Name"].apply(", ".join).reset_index() g1.columns = ['Father Name','Children Name'] print g1 and the output will be Father Name Children Name 0 Charles Shirly 1 Chris Eva 2 Doug James, Liz 3 Richard Peter, Paul I can't figure out how to add "Father Age" and "Children Age" in the columns. how can I convert this in dataframe in most efficient way? I'd like to avoid loop via python as it will take long to process. thanks,
answer count: 1

http://stackoverflow.com/comment/83021901
type: AnswerComment
comment on: http://stackoverflow.com/a/48016497
score: 0
has text: When trying this, I am receiving a ValueError: Cannot convert non-finite values (NA or inf) to integer
type: Comment

http://stackoverflow.com/a/47945232
has body: Thanks to @Elez-Shenhar answer I get the following working code: OneHot=housing_cat_1hot.toarray() OneHot= pd.DataFrame(OneHot) result = housing.join(OneHot) result.shape (20640, 15)
has comment: http://stackoverflow.com/comment/104336491
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47942861

http://stackoverflow.com/comment/82882562
type: AnswerComment
score: 0
type: Comment
has text: this flag will disable JIT at the process level, right?
comment on: http://stackoverflow.com/a/47956479

http://stackoverflow.com/comment/82801037
comment on: http://stackoverflow.com/a/47916429
type: AnswerComment
score: 0
has text: In Pandas the fastest solution usually involves using the built in vectorized functions. Your first code is a more natural way of sorting each row but apply is slow :/
type: Comment

http://stackoverflow.com/comment/82913164
score: 0
type: Comment
has text: @DenGor Updated the answer here, now it should be working.
comment on: http://stackoverflow.com/a/47970449
type: AnswerComment

http://stackoverflow.com/q/47865181
tagged with: multidimensional-array
downvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/82695727
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82695286
type: Question
has comment: http://stackoverflow.com/comment/82695491
has comment: http://stackoverflow.com/comment/82695282
tagged with: algorithm
score: -2
has answer: http://stackoverflow.com/a/47865645
accepted answer: http://stackoverflow.com/a/47865645
upvote count: 3
has body: I have started to play around with Project Euler, however i hit a roadblock at problem 11 What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?` There probably is a bug in my logic somewhere but even after multiple breaks and new approaches, i still have had no success. The correct output should be 70600674 but i get 51267216. This is more of an educational question, I would like to at least know where i messed up. input.txt: 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 Main.py: in_file = 'input.txt' m = list(map(lambda line_str: list(map(int, line_str.split(' '))), open(in_file, 'r').read().split('\n'))) for line in m: print(' '.join(map(lambda num: str(num).rjust(2), line))) print() vertical_max = horizontal_max = main_diag_max = second_diag_max = 0 for…
has comment: http://stackoverflow.com/comment/82695259
has comment: http://stackoverflow.com/comment/82695710
has comment: http://stackoverflow.com/comment/82695347
tagged with: arrays
answer count: 1
favorite count: 0
has title: Project Euler #11 logic
tagged with: python-3.x

http://stackoverflow.com/q/47976874
tagged with: subtraction
has answer: http://stackoverflow.com/a/47976986
score: 2
type: AnsweredQuestion
tagged with: list
upvote count: 2
type: Question
has title: How can I subtract 2 string or list in python?
has body: I have very large strings in my codes. I would like to detect different characters between the strings. Here is an example what I mean: a='ababaab' b='abaaaaa' a=a-b print(a) I expect kind of like these; 'bb' or '000b00b' I know sounds weird but I really need this.
possible better answer: http://stackoverflow.com/a/47976930
has answer: http://stackoverflow.com/a/47976930
answer count: 6
accepted answer: http://stackoverflow.com/a/47976986
has answer: http://stackoverflow.com/a/47977139
has comment: http://stackoverflow.com/comment/82922756
has answer: http://stackoverflow.com/a/47977160
tagged with: difference
has answer: http://stackoverflow.com/a/47977026
downvote count: 0
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/47977196
tagged with: python

http://stackoverflow.com/q/47884976
has comment: http://stackoverflow.com/comment/82735959
type: Question
has answer: http://stackoverflow.com/a/47895474
has comment: http://stackoverflow.com/comment/82743355
tagged with: python
score: 21
tagged with: http://stackoverflow.com/tag/png
has comment: http://stackoverflow.com/comment/82736971
has title: Am I creating lossless PNG images?
has comment: http://stackoverflow.com/comment/82743004
answer count: 2
has comment: http://stackoverflow.com/comment/82743906
has body: I am doing image processing in a scientific context. Whenever I need to save an image to the hard drive, I want to be able to reopen it at a later time and get exactly the data that I had before saving it. I exclusively use the PNG format, having always been under the impression that it is a lossless format. Is this always correct, provided I am not using the wrong bit-depth? Should encoder and decoder play no role at all? Specifically, the images I save are present as 2D numpy arrays have integer values from 0 to 255 are encoded with the OpenCV imwrite() function, e.g. cv2.imwrite("image.png", array)
upvote count: 21
accepted answer: http://stackoverflow.com/a/47895474
tagged with: opencv
has comment: http://stackoverflow.com/comment/82742624
has comment: http://stackoverflow.com/comment/90963056
has comment: http://stackoverflow.com/comment/82736522
has comment: http://stackoverflow.com/comment/90963207
has comment: http://stackoverflow.com/comment/82736886
tagged with: numpy
possible better answer: http://stackoverflow.com/a/59921563
has comment: http://stackoverflow.com/comment/90957214
has comment: http://stackoverflow.com/comment/90963507
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/12216333
has answer: http://stackoverflow.com/a/59921563
has comment: http://stackoverflow.com/comment/90965943
downvote count: 0
favorite count: 0
tagged with: image-compression
has comment: http://stackoverflow.com/comment/82744284

http://stackoverflow.com/comment/82831656
has text: @MadPhysicist Ah thanks, sorry, I misread the question then.
comment on: http://stackoverflow.com/q/47931356
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82690315
comment on: http://stackoverflow.com/q/47862285
score: 0
has text: @JohnGordon Indeed. And when it does encounter a bad-link/404 I want it to be stored in the `not_found` `set` in the `CrawlerClient` class.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47953132
has title: Kivy sizing label inside RecycleView
score: 1
upvote count: 1
type: Question
has body: I would like my label to have exactly the height it needs to display its text. It is inside a RecycleView. I think my code should work outside an RecycleView. How can I make the Label big enough so that its content can easily be read? In the same way as it already works for CodeInput and TextInput. from kivy.base import runTouchApp from kivy.lang import Builder from kivy.uix.recycleview import RecycleView from kivy.uix.label import Label from kivy.uix.recycleboxlayout import RecycleBoxLayout from kivy.uix.behaviors import FocusBehavior from kivy.uix.boxlayout import BoxLayout from kivy.lang import Builder from kivy.properties import StringProperty Builder.load_string(''' &lt;RV&gt;: viewclass: 'SnippetView' RecycleBoxLayout: default_size: None, dp(56) default_size_hint: 1, None size_hint_y: None height: self.minimum_height orientation: 'vertical' spacing: 10 &lt;SnippetView&gt;: canvas.before: Color: rgb: (255,0,0) Rectangle: pos: self.pos size: self.size orientation: 'vertical' Label: text: root.heading text_size: root.width, None size: self.texture_size TextInput: text: root.dscrpt size_hint_y: None height: self.minimum_height CodeInput: text: root.code size_hint_y: None height: self.minimum_height ''') class SnippetView(BoxLayout): heading = StringProperty() dscrpt = StringProperty() code = StringProperty() class RV(RecycleView): def __init__(self, **kwargs): super(RV, self).__init__(**kwargs) self.data = [{'heading': str(x),'dscrpt': str(x),'code': str(x)} for x in range(100)] rv = RV() runTouchApp(rv) I am also thankful for any comments regarding RecycleView in general since I am using it for the first time.
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: kivy-language
tagged with: python
tagged with: kivy
has answer: http://stackoverflow.com/a/47955479
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47955479

http://stackoverflow.com/q/47879645
tagged with: matplotlib
tagged with: ubuntu-16.04
has body: I'm using matlab.engine(MATLAB R2016b) in python(3.5.2) on ubuntu16.04, following the official instructions "MATLAB API for Python". I've got confused in face of this weird problem. It works well when I import matlab.engine after importing matplotlib: import matplotlib import matlab.engine eng = matlab.engine.start_matlab() #... However, without matplotlib being imported first, error occurs as the following in jupyter-notebook: --------------------------------------------------------------------- ImportError Traceback (most recent call last) ~/workspace/python/vp3.5_64/lib/python3.5/site-packages/matlab/engine /__init__.py in &lt;module&gt;() 41 try: ---&gt; 42 pythonengine = importlib.import_module("matlabengineforpython"+_PYTHONVERSION) 43 except: ~/workspace/python/vp3.5_64/lib/python3.5/importlib/__init__.py in import_module(name, package) 125 level += 1 --&gt; 126 return _bootstrap._gcd_import(name[level:], package, level) 127 ~/workspace/python/vp3.5_64/lib/python3.5/importlib/_bootstrap.py in _gcd_import(name, package, level) ~/workspace/python/vp3.5_64/lib/python3.5/importlib/_bootstrap.py in _find_and_load(name, import_) ~/workspace/python/vp3.5_64/lib/python3.5/importlib/_bootstrap.py in _find_and_load_unlocked(name, import_) ImportError: No module named 'matlabengineforpython3_5' During handling of the above exception, another exception occurred: ImportError Traceback (most recent call last) ~/workspace/python/vp3.5_64/lib/python3.5/site-packages/matlab/engine /__init__.py in &lt;module&gt;() 57 os.environ[_envs[_arch]] = _bin_dir ---&gt; 58 pythonengine = importlib.import_module("matlabengineforpython"+_PYTHONVERSION) 59 except Exception as e: ~/workspace/python/vp3.5_64/lib/python3.5/importlib/__init__.py in import_module(name, package) 125 level += 1 --&gt; 126 return _bootstrap._gcd_import(name[level:], package, level) 127 ~/workspace/python/vp3.5_64/lib/python3.5/importlib/_bootstrap.py in _gcd_import(name, package, level) ~/workspace/python/vp3.5_64…
upvote count: 3
favorite count: 0
has title: Error occurs when importing matlab.engine without importing matplotlib in python3.5.2 on ubuntu16.04. Why?
tagged with: python
tagged with: jupyter-notebook
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: matlab
type: Question
score: 3

http://stackoverflow.com/a/47873873
type: Answer
has body: The % character has special meaning inside batch files, so you need to "escape" them by using double %%: @echo off assoc .py=PythonFile ftype PythonFile="H:\profile\programs\Python34\python.exe" "%%1" "%%*"
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82713595
has comment: http://stackoverflow.com/comment/82713512
has comment: http://stackoverflow.com/comment/82713777
has comment: http://stackoverflow.com/comment/82713443
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82716664
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47873361
answers question: http://stackoverflow.com/q/47873361

http://stackoverflow.com/a/47942534
score: 5
answers question: http://stackoverflow.com/q/47942273
has comment: http://stackoverflow.com/comment/82855324
has comment: http://stackoverflow.com/comment/82854842
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82858886
has comment: http://stackoverflow.com/comment/82855296
has comment: http://stackoverflow.com/comment/82855896
type: Answer
has body: Consider a pd.Series - s Index Monday 2 Tuesday 4 Wednesday 5 Thursday 2 Friday 1 Saturday 6 Sunday 3 Name: counts, dtype: int64 Now, call pd.Series.plot.pie on counts column - s.plot.pie(y=df.index, shadow=False, colors=colors, explode=(0, 0, 0, 0, 0.15, 0, 0), # exploding 'Friday' startangle=90, autopct='%1.1f%%') plt.axis('equal') plt.tight_layout() plt.show() Don't call plot()! Call pie on plot. If you need your index sorted by weekday, make sure to convert it to pd.Categorical - cat = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday', 'Sunday'] df.index = pd.Categorical(df.index, categories=cat, ordered=True) df = df.sort_index() And then, you can plot as shown above.
has comment: http://stackoverflow.com/comment/82855205
has comment: http://stackoverflow.com/comment/82854865
upvote count: 5
accepted answer of: http://stackoverflow.com/q/47942273

http://stackoverflow.com/q/47915414
tagged with: pyqt
answer count: 1
favorite count: 0
tagged with: python
tagged with: python-3.x
upvote count: 2
has answer: http://stackoverflow.com/a/47915581
tagged with: pyqt5
has body: Here's my code. I'm trying to make it such that as you change the dropdown box, it will dynamically show more or less QLineEdits for input. This is just the latest iteration of testing import sys from PyQt5.QtWidgets import (QWidget, QPushButton, QLineEdit, QInputDialog, QApplication, QComboBox, QFrame) import numpy as np class GUI(QWidget): def __init__(self): super().__init__() self.initgui() def initgui(self): # # Set up GUI # self.setGeometry(100, 100, 400, 400) self.move(300, 300) combobox = QComboBox(self) for i in range(1, 10, 1): combobox.addItem(str(i + 1)) combobox.activated[str].connect(self.comboboxchanged) self.setWindowTitle("Testing Easy Setup") self.show() def comboboxchanged(self, text): frame = QWidget(self) frame.hide() for num in range(0, int(text), 1): QLineEdit(frame).move(60, num * 19) frame.show() if __name__ == '__main__': app = QApplication(sys.argv) gui = GUI() sys.exit(app.exec_())
downvote count: 1
type: AnsweredQuestion
score: 1
type: Question
has title: How can I dynamically add/remove elements in an element?
accepted answer: http://stackoverflow.com/a/47915581

http://stackoverflow.com/comment/82835379
score: 0
has text: @Galen I don't understand how does it work very well
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47933048

sqlalchemy
tags question: http://stackoverflow.com/q/47986098
tags question: http://stackoverflow.com/q/47912520
tags question: http://stackoverflow.com/q/47928048
tags question: http://stackoverflow.com/q/47943534
tags question: http://stackoverflow.com/q/48004485
tags question: http://stackoverflow.com/q/47871887
tags question: http://stackoverflow.com/q/48006551
tags question: http://stackoverflow.com/q/48006740
tags question: http://stackoverflow.com/q/47931287
tags question: http://stackoverflow.com/q/47909457
tags question: http://stackoverflow.com/q/47953854
tags question: http://stackoverflow.com/q/47896555
tags question: http://stackoverflow.com/q/47915364
tags question: http://stackoverflow.com/q/47931787
tags question: http://stackoverflow.com/q/47865981
tag name: sqlalchemy
tags question: http://stackoverflow.com/q/47856198
tags question: http://stackoverflow.com/q/47869558
tags question: http://stackoverflow.com/q/47882616
tags question: http://stackoverflow.com/q/47934743
tags question: http://stackoverflow.com/q/47967328
tags question: http://stackoverflow.com/q/47917385
tags question: http://stackoverflow.com/q/48002965
tags question: http://stackoverflow.com/q/47917101
tags question: http://stackoverflow.com/q/48004925
tags question: http://stackoverflow.com/q/47983152
tags question: http://stackoverflow.com/q/47916856
tags question: http://stackoverflow.com/q/47981246
tags question: http://stackoverflow.com/q/47995784
tags question: http://stackoverflow.com/q/47864389
tags question: http://stackoverflow.com/q/47941948
tags question: http://stackoverflow.com/q/47998500
tags question: http://stackoverflow.com/q/47945447
tags question: http://stackoverflow.com/q/47884649
tags question: http://stackoverflow.com/q/47988811
tags question: http://stackoverflow.com/q/47918946
tags question: http://stackoverflow.com/q/47904931
tags question: http://stackoverflow.com/q/47948274
tags question: http://stackoverflow.com/q/47873275
tags question: http://stackoverflow.com/q/47979390
type: Tag
tags question: http://stackoverflow.com/q/47991373

http://stackoverflow.com/comment/82948872
type: Comment
has text: @darrrn How is your code not even erroring out? Both `each` and `reflist[i]` are lists, and you are applying a string method of `split(",")` on them. Can it be that your code is not running at all, and therefore you are getting the initial value of `count = 0`?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47988583

http://stackoverflow.com/a/55191893
downvote count: 0
score: 1
upvote count: 1
type: Answer
has body: check your database structure. sha256 may require upto 70 values. Increase the password field to about 100 values.
answers question: http://stackoverflow.com/q/47867216

http://stackoverflow.com/comment/82952125
has text: @Sanket. won't work. python does not provide for manufacturing variable names, at least not directly.
comment on: http://stackoverflow.com/q/47991909
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82851135
comment on: http://stackoverflow.com/a/47940883
score: 0
type: AnswerComment
has text: Thank you, added to answer.
type: Comment

http://stackoverflow.com/q/47983317
tagged with: javascript
has body: How can I do this in JavaScript? It should print 'Found' when it hits words in big_list big_list = ['this', 'is', 'a', 'long', 'list', 'of' 'words'] needle = ['words', 'to', 'find'] for i in big_list: if i in needle: print('Found') else: print('Not Found') I know the general if/else structure but am unsure the syntax: if (big_list in needle) { console.log('print some stuff') } else { console.log('print some other stuff') }
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/47983342
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47983378
has title: Translate python conditional to javascript -- control flow
tagged with: list
possible better answer: http://stackoverflow.com/a/47983378
accepted answer: http://stackoverflow.com/a/47983342
type: AnsweredQuestion
tagged with: arrays

http://stackoverflow.com/comment/82738080
type: AnswerComment
comment on: http://stackoverflow.com/a/47871742
score: 0
type: Comment
has text: I saved the file in UTF-8. The result now is `The input file is 23 bytes long` which is really close to the original. I guess my question was a little basic or pointless, I mean, 23 bytes or 42 bytes in such a simple file... But thanks to all your answers guys I learned something new about the Encoding format and that's great.

http://stackoverflow.com/comment/82898667
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47964427
has text: Ah. Could you replace commas with periods, then use the tokenizer?
score: 0

http://stackoverflow.com/q/47884862
accepted answer: http://stackoverflow.com/a/47885932
tagged with: keras
has comment: http://stackoverflow.com/comment/82839975
favorite count: 0
tagged with: python
has title: Keras: Big one-hot-encoding: binary_crossentropy or categorical_crossentropy
tagged with: machine-learning
downvote count: 1
has answer: http://stackoverflow.com/a/47885932
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82837709
upvote count: 5
score: 4
type: Question
tagged with: deep-learning
answer count: 1
has body: I'm training a text classification model where the input data consists of 4096 term frequency–inverse document frequencies. My output are 416 possible categories. Each piece of data has 3 categories, so there are 3 ones in an array of 413 zeros (one-hot-encodings) My model looks like this: model = Sequential() model.add(Dense(2048, activation="relu", input_dim=X.shape[1])) model.add(Dense(512, activation="relu")) model.add(Dense(416, activation="sigmoid")) When I train it with the binary_crossentropy loss, it has a loss of 0.185 and an accuracy of 96% after one epoch. After 5 epochs, the loss is at 0.037 and the accuracy at 99.3%. I guess this is wrong, since there are a lot of 0s in my labels, which it classifies correctly. When I train it with the categorical_crossentropy loss, it has a loss of 15.0 and an accuracy of below 5% in the first few epochs, before it gets stuck at a loss of 5.0 and an accuracy of 12% after several (over 50) epochs. Which one of those would be right for my situation (large one-hot-encodings with multiple 1s)? What do these scores tell me? EDIT: These are the model.compile() statement: model.compile(loss='categorical_crossentropy', optimizer=keras.optimizers.Adam(), metrics=['accuracy']) and model.compile(loss='binary_crossentropy', optimizer=keras.optimizers.Adam(), metrics=['accuracy'])
tagged with: neural-network

http://stackoverflow.com/comment/82722124
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47877903
has text: Needs google cloud tag

comtypes
tags question: http://stackoverflow.com/q/47985956
type: Tag
tag name: comtypes

http://stackoverflow.com/comment/82845095
score: 0
type: AnswerComment
type: Comment
has text: Thanks. May I know where do I add the class? view.py?
comment on: http://stackoverflow.com/a/47937738

http://stackoverflow.com/comment/82727165
comment on: http://stackoverflow.com/q/47880600
type: Comment
type: QuestionComment
score: 0
has text: No it is a string until it is explictly converted (in python 3)

http://stackoverflow.com/a/48126778
has comment: http://stackoverflow.com/comment/88199761
has comment: http://stackoverflow.com/comment/86222715
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/85319817
score: 62
has comment: http://stackoverflow.com/comment/84819350
answers question: http://stackoverflow.com/q/47955397
has comment: http://stackoverflow.com/comment/86379195
has comment: http://stackoverflow.com/comment/85792737
has body: I met the same issue with python 3.5.2 and pip3 (9.0.1). And I fixed it by following this workaround: https://github.com/pypa/setuptools/issues/885#issuecomment-307696027 More specifically, I edited line #2121~2122 of this file: "sudo vim /usr/local/lib/python3.5/dist-packages/pip/_vendor/pkg_resources/__init__.py" #orig_path.sort(key=position_in_sys_path) #module.__path__[:] = [_normalize_cached(p) for p in orig_path] orig_path_t = list(orig_path) orig_path_t.sort(key=position_in_sys_path) module.__path__[:] = [_normalize_cached(p) for p in orig_path_t]
upvote count: 62

http://stackoverflow.com/comment/82829105
comment on: http://stackoverflow.com/a/47908432
score: 0
type: AnswerComment
has text: Yes indeed, I'm trying to like it and yours however I'm not able to because I'm a new user...
type: Comment

http://stackoverflow.com/a/47873349
accepted answer of: http://stackoverflow.com/q/47873270
answers question: http://stackoverflow.com/q/47873270
type: Answer
score: 4
has body: Use a negative lookahead like this: Washington(?!\s*DC) It will check if washington is followed by any number of spaces and "DC"
has comment: http://stackoverflow.com/comment/82713773
upvote count: 4
has comment: http://stackoverflow.com/comment/82714400
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82714658

http://stackoverflow.com/q/47878296
linked to: http://stackoverflow.com/q/43770118
tagged with: django-models
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/47890026
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
has answer: http://stackoverflow.com/a/47890026
tagged with: django
has body: I have two models 'ModelParent' and 'ModelChild', where 'ModelParent' has many 'ModelChild', here is my models structure: class ModelParent(models.Model): ... some params ... class ModelChild(models.Model): TYPES = ( (1, 'First'), (2, 'Second'), ) parent = models.ForeignKey(ModelParent, on_delete=models.CASCADE, related_name='childs') type = models.SmallIntegerField(choices=TYPES, default=0) Currently, there's only one 'ModelChild' in the database who belongs to the only 'ModelParent' currently in the database, the 'type' value of the 'ModelChild' is equal to '1', I'm getting the 'ModelParent' object and I need to aggregate to it the count of his 'childs' where type is '1' and also the count of his 'childs' where type is '2', this is the way I'm trying to do so: queryset = ModelParent.objects \ .annotate(first_count=Count('childs', filter=Q(childs__type=1))) \ .annotate(second_count=Count('childs', filter=Q(childs__type=2))).get(pk=1) The query doesn't throw any errors but when looking at the response, the values for both annotations are '1', when it should be '1' only for 'first_count' and '0' for 'second_count'. I have also noticed that no matter what value I set to 'childs__type' within the filter "filter=Q(childs__type=1)", the result is always the same, I can set it like this for example: 'childs__type=10' and still the count is equal to '1'.. it is like the entire 'filter' param is being ignored.
type: Question
has title: Django Count filter annotation not working

http://stackoverflow.com/q/47955611
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82880936
has title: About the built-in __iter__
type: Question
accepted answer: http://stackoverflow.com/a/47955793
has comment: http://stackoverflow.com/comment/82880941
score: 0
has comment: http://stackoverflow.com/comment/82881516
tagged with: built-in
answer count: 1
has comment: http://stackoverflow.com/comment/82881454
has answer: http://stackoverflow.com/a/47955793
tagged with: python
has body: I'm learning python and reading fluent python book! While following some class implementation, I stopped by this snippet of code: def __iter__(self): return iter(self._components) with components being an array of floats, my question is: why calling the iter() method on components although it's already an iterable?.

http://stackoverflow.com/q/47967328
type: UnansweredQuestion
has body: How to determine if the transaction is committed or rolled-back in the after_transaction_end event listener? I looked into _state, but it's always CLOSED.
score: 3
upvote count: 3
tagged with: sqlalchemy
type: Question
downvote count: 0
has title: sqlalchemy: How to determine if transaction is committed in after_transaction_end event
tagged with: python
favorite count: 0
answer count: 0

http://stackoverflow.com/comment/82837675
type: Comment
has text: @guillermochamorro Edited my post, views are tied to urls, I literally just need to find one integer for a user (it's for a button).
comment on: http://stackoverflow.com/q/47933718
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82902830
type: Comment
type: QuestionComment
has text: you should to use implicit/explicit wait as needed and before click check staleness
comment on: http://stackoverflow.com/q/47966568
score: 0

http://stackoverflow.com/comment/82749626
comment on: http://stackoverflow.com/a/47891500
type: AnswerComment
score: 0
type: Comment
has text: Why range and not xrange?

http://stackoverflow.com/comment/82798402
score: 0
type: Comment
has text: Thanks for the fast help! This is what i needed.
comment on: http://stackoverflow.com/a/47915013
type: AnswerComment

http://stackoverflow.com/a/47924096
downvote count: 0
has comment: http://stackoverflow.com/comment/125822887
type: Answer
accepted answer of: http://stackoverflow.com/q/47923952
has body: in your template {% for message in messages %} × {{ message }} {% endfor %} in view from django.contrib import messages def login(request): if request.method == 'POST': form = AuthenticationForm(request.POST) username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: auth_login(request, user) return redirect('index') else: messages.error(request,'username or password not correct') return redirect('login') else: form = AuthenticationForm() return render(request, 'todo/login.html', {'form': form})
answers question: http://stackoverflow.com/q/47923952
score: 22
has comment: http://stackoverflow.com/comment/115803372
upvote count: 22
type: AcceptedAnswer

http://stackoverflow.com/a/47867577
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/47867468
has comment: http://stackoverflow.com/comment/82700581
has comment: http://stackoverflow.com/comment/82700707
has comment: http://stackoverflow.com/comment/82700658
has comment: http://stackoverflow.com/comment/82700811
has comment: http://stackoverflow.com/comment/82701128
has body: Here's an assumption that should make sense - there are no keys that only differ by case sensitivity (otherwise, your question would no longer make sense). What you'd do is create a new dictionary with all lowercase keys. Correspondingly, when you are querying, lowercase the query key and index the dictionary. Here's how you'd do this. In [63]: n_dict = {k.lower() : v for k, v in dct.items()} In [64]: n_dict Out[64]: {'age': 7, 'class': 'First', 'name': 'Zara'} In [65]: key = 'NaMe' In [66]: n_dict.get(key.lower()) Out[66]: 'Zara' As a side note, don't use dict to name your variables, because dict is the name of a builtin, which you'd end up shadowing.
upvote count: 1
has comment: http://stackoverflow.com/comment/82700562
has comment: http://stackoverflow.com/comment/82701495
has comment: http://stackoverflow.com/comment/82701458
type: Answer
has comment: http://stackoverflow.com/comment/82701159

twilio
tag name: twilio
tags question: http://stackoverflow.com/q/47928852
tags question: http://stackoverflow.com/q/47888472
type: Tag

http://stackoverflow.com/a/47890388
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82747125
score: 0
has body: Here you go class Entity(models.Model): name = models.CharField(max_length=255) class EntityProp(models.Model): entity = models.ForeignKey('Entity') key = models.CharField(max_length=255) value = models.CharField(max_length=255, blank=True, default='') class Meta: unique_together = ('key', 'entity') Source: https://docs.djangoproject.com/en/dev/ref/models/options/#unique-together
answers question: http://stackoverflow.com/q/47890241
type: Answer

http://stackoverflow.com/comment/82825944
type: QuestionComment
has text: Here is the link to the [Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/).
type: Comment
comment on: http://stackoverflow.com/q/47928659
score: 0

http://stackoverflow.com/comment/82832757
type: QuestionComment
comment on: http://stackoverflow.com/q/47929533
type: Comment
has text: I have read through the question now 3 times and can't understand it. Can you rephrase it? e.g. what is your is your program doing, why do you use multiprocessing (and why did you choose it over multithreading), what are these resources, would you use them concurrently (e.g. all processes can potentially use all resources at the same time) are all processes reading/writing to these resources or is it reading only etc.
score: 0

http://stackoverflow.com/comment/82821869
has text: It's fixed, I waiting more time for random elements
type: Comment
comment on: http://stackoverflow.com/a/47920046
type: AnswerComment
score: 0

http://stackoverflow.com/q/47886482
downvote count: 2
tagged with: python-click
has body: I'm trying to execute a Python 3 script via the command line with the Click library but it seems that it isn't working as it should. @click.option('--criteria', default='', type=click.STRING, envvar="CRITERIA") That is the given line which throws the TypeError: 'str' object is not callable. Should I be doing something else or is it a matter of syntax? UPDATE Having changed the placement of the criteria option few places above, now I see that the error mentioned before is given in the last placed option, no matter the type. This is my method signature and the places where the parameters are used. @click.command('my_command', 'Initialize my_command') @click.option('--s1', type=click.STRING, envvar='S_1', help='s1') @click.option('--s2', type=click.STRING, envvar='S_2', help='s2') @click.option('--i', type=click.STRING, envvar="I") @click.option('--c', type=click.STRING, envvar="C") @click.option('--l', default='[]', type=click.STRING, envvar="L") @click.option('--st', default='[]', type=click.STRING, envvar="ST") @click.option('--s', default='[]', type=click.STRING, envvar="S") def my_command(s1, s2, i, c, l, st, s): ... Traceback Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/runpy.py", line 85, in _run_code exec(code, run_globals) File "/project_root/__main__.py", line 27, in &lt;module&gt; @click.command('my_command', 'Initialize my_command') File "/project_root/venv/lib/python3.6/site-packages/click/decorators.py", line 115, in decorator cmd = _make_command(f, name, attrs, cls) File "/project_root/venv/lib/python3.6/site-packages/click/decorators.py", line 89, in _make_command callback=f, params=params, **attrs) TypeError: 'str' object is not callable
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82738733
has comment: http://stackoverflow.com/comment/82738647
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83006598
tagged with: python
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/83006801
has answer: http://stackoverflow.com/a/48019020
accepted answer: http://stackoverflow.com/a/48019020
has title: TypeError: 'str' object is not callable using Python Click library
type: Question
tagged with: command-line-interface
upvote count: 3

http://stackoverflow.com/comment/82720004
comment on: http://stackoverflow.com/q/47877068
has text: What about https://docs.opencv.org/2.4/modules/stitching/doc/high_level.html ?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47985052
type: Question
has comment: http://stackoverflow.com/comment/82939594
has title: Bag of Words - Add feature manually
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/47985085
score: 0
has comment: http://stackoverflow.com/comment/82947659
answer count: 1
tagged with: nlp
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82939402
tagged with: python
has body: I am trying to improve my model on text classification. text = df['text'] count_vect = CountVectorizer(min_df=1,ngram_range=(1, 2), stop_words="english", max_features=200) count_vect.fit(text) counts = count_vect.transform(text) Here is the sample output: [(u'spring', 386), (u'https', 341), (u'com', 317), (u'pr', 313), (u'for the', 285), (u'the pr', 208), (u'need', 196), (u'session', 164), (u'jp', 158), (u'png', 156), (u'updated', 154), (u'please', 152), (u'see', 145)] I want to add word/frequencies manually which I thought could be a good indicator. Any help on this?

memoization
type: Tag
tag name: memoization
tags question: http://stackoverflow.com/q/47858382

http://stackoverflow.com/comment/82795539
score: 0
type: Comment
has text: Wouldn't it be better to store the data as a set from the beginning so you don't have to remove the duplicates later?
type: AnswerComment
comment on: http://stackoverflow.com/a/47912114

http://stackoverflow.com/q/47917385
upvote count: 2
type: UnansweredQuestion
tagged with: python
has body: I have a project with articles having different prices depending on their location. The Article and ArticlePrice models are as follow: from flask_sqlalchemy import SQLAlchemy from sqlalchemy.orm import relationship db = SQLAlchemy() class Article(db.Model): __tablename__ = 'article' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(255), nullable=False) description = db.Column(db.Text) prices = relationship("ArticlePrice") class ArticlePrice(db.Model): __tablename__ = 'article_prices' id = db.Column(db.Integer, primary_key=True) article_id = db.Column(db.Integer, db.ForeignKey("article.id"), nullable=False) location_id = db.Column(db.Integer, db.ForeignKey("location.id"), nullable=False) price = db.Column(db.Integer, nullable=False) location = relationship('Location') I don't want to return all the prices of an article to the client but just his location price. Such as he receives a JSON like: { id: '', title: '', description: '', price: 0 } So my schema looks like this now: article = namespace.model('Article', { 'id': fields.Integer(required=True), 'title': fields.String(required=True), 'description': fields.String(required=True), 'price': fields.Integer(attribute=lambda x: x.prices[0].price), # This one works }) This is working fine with a lambda expression, but in the documentation (flask-restful and flask-restplus) they talk about another way, but I can't make it work as follow: 'price': fields.Integer(attribute='prices[0].price') # This one doesn't work What am I missing? Why is the last syntax not working? Did I misunderstand this syntax use?
score: 2
tagged with: flask-restful
has title: How to marshal nested attribute up to the schema?
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/82812387
has answer: http://stackoverflow.com/a/51357246
downvote count: 0
answer count: 1
tagged with: flask
favorite count: 0
has comment: http://stackoverflow.com/comment/82810983
tagged with: flask-restplus
has comment: http://stackoverflow.com/comment/107457883

http://stackoverflow.com/a/47908432
answers question: http://stackoverflow.com/q/47908310
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47908310
has comment: http://stackoverflow.com/comment/82784483
upvote count: 2
type: Answer
score: 2
has body: Set a dictionnary right before your for loop, then update it during your loop such as : import collections from Bio import Seq from itertools import product def ListMW(file_name): seq_records = SeqIO.parse(file_name, 'fasta',alphabet=generic_dna) retDict = {} for record in seq_records: dictionary = Seq.IUPAC.IUPACData.ambiguous_dna_values result = [] for i in product(*[dictionary[j] for j in record]): result.append("".join(i)) molw = [] for sequence in result: molw.append(SeqUtils.molecular_weight(sequence)) tuple= (min(molw),max(molw)) if min(molw)==max(molw): retDict[record.id] = molw else: retDict[record.id] = (min(molw), max(molw))} # instead of printing now, print in the end of your function / script # print(dict) Right now, you're setting a new dict at each turn of your loop, and print it. It is just a normal behaviour of your code to print lots and lots of dict.
has comment: http://stackoverflow.com/comment/82784662
has comment: http://stackoverflow.com/comment/82829105
downvote count: 0

http://stackoverflow.com/q/47942306
tagged with: raspberry-pi
has answer: http://stackoverflow.com/a/47942393
has body: I am using python-docx for this task and am currently having difficulties in trying to insert a variable (i.e. month) into a heading of my python-docx generated word doc. Running the script successfully generates a word doc, but the heading is printed as current month instead of the desired 12(i.e. Dec). My python script is as shown below: import datetime import urllib from docx import Document from docx.shared import Inches now = datetime.datetime.now() currentmonth=now.month print (currentmonth) document = Document() document.add_picture('placeholder.jpg', width=Inches(1.25)) document.add_heading('currentmonth', 0) p = document.add_paragraph('A plain paragraph having some') p.add_run('bold').bold = True p.add_run(' and some ') p.add_run('italic.').italic = True document.add_heading('Heading, level 1', level=1) document.add_paragraph('Intense quote', style='Intense Quote') document.add_paragraph( 'first item in unordered list', style='ListBullet' ) document.add_paragraph( 'first item in ordered list', style='ListNumber' ) recordset = [ { "id" : 1, "qty": 2, "desc": "New item" }, { "id" : 2, "qty": 2, "desc": "New item" }, { "id" : 3, "qty": 2, "desc": "New item" }, ] table = document.add_table(rows=1, cols=3) hdr_cells = table.rows[0].cells hdr_cells[0].text = 'Qty' hdr_cells[1].text = 'Id' hdr_cells[2].text = 'Desc' for item in recordset: row_cells = table.add_row().cells row_cells[0].text = str(item["qty"]) row_cells[1].text = str(item["id"]) row_cells[2].text = item["desc"] document.add_page_break() document.save('demo.docx') The difficulty arise at **document.add_heading('currentmonth', 0)**. When I remove the quotation marks to get document.add_heading(currentmont', 0), terminal shows me an error when I run the script. The error is shown below: pi@raspberrypi:~/user $ python demo_script_v01.py 12 Traceback (most recent call last): File "demo_script_v01.py", line 14, in &lt;module&gt; document.add_heading(currentmonth, 0) File "/usr/local/lib/python2.7/dist-pac…
answer count: 1
has title: Inserting a variable into a heading of a python-docx generated word doc
tagged with: variables
tagged with: python-docx
tagged with: datetime
tagged with: python
accepted answer: http://stackoverflow.com/a/47942393
type: AnsweredQuestion
score: 0
type: Question

http://stackoverflow.com/a/47901200
accepted answer of: http://stackoverflow.com/q/47901099
answers question: http://stackoverflow.com/q/47901099
has comment: http://stackoverflow.com/comment/82769553
has comment: http://stackoverflow.com/comment/82769202
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82768949
has comment: http://stackoverflow.com/comment/82769024
type: Answer
has body: socketserver, struct and threading are all Python standard library modules, so since you're running a Debian based distro there is no need to install any external packages to get them. However, socketserver is a Python 3 module, hence not available in Python 2. Maybe this is the issue you're facing? Which Python version are you using to run the script? Pasting error message would be helpful.
upvote count: 2
has comment: http://stackoverflow.com/comment/82769138
score: 2

http://stackoverflow.com/a/47881510
has body: Look up time in a list is O(N) and look up time in set is O(1). To check if an element is contained in a list every element of a list has to be checked until either an element is found or not. This gives look up time proportional to size of the list or O(N). set is implemented as a hashtable which much more efficient, and look up time is on average O(1), or look up time does not increase much as size of set increases.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47881433

http://stackoverflow.com/q/47952517
has title: pandas dataframe - add new row if new index, if existing then supplement the index with column data
favorite count: 0
has comment: http://stackoverflow.com/comment/82874759
has body: I have an array with 170 dataframes, each including: gender - year name M/F count so example: Gender 2015 William M 12321 George M 19000 .... ... .... Each dataframe in the array is for a different year. What i want to do is combine all dataframes to a single dataframe. With different years some names appear and others disappear, so not all dataframes have the same structure (different row count). tldr what i want (source: https://pandas.pydata.org/pandas-docs/stable/merging.html): But using this method i get the error: ValueError: Shape of passed values is (274, 96313), indices imply (274, 96174) Which is because my dataframes (unlike the example) have different row counts (I think). Here is my full code: from zipfile import ZipFile import pandas as pd zip_file = ZipFile('names.zip') df = pd.DataFrame() dfs = [] with zip_file as f: for name in f.namelist(): df1 = pd.read_csv(zip_file.open(name), sep=',',names=['Gender',name]) #Name = year df.append(df1) print(newDf) dfs.append(df1) result = pd.concat(dfs,axis=1) print(result.head()) Ive tried both append,merge and concat but none of them seem to do what I'm searching for. the solutions I've found to this error aren't directly applicable to my case as I'm dealing with a long array of dataframes, and I haven't been able to get them to work with my code.
tagged with: python
has comment: http://stackoverflow.com/comment/82875020
tagged with: merge
type: AnsweredQuestion
score: 1
type: Question
accepted answer: http://stackoverflow.com/a/47953205
tagged with: dataframe
linked to: http://stackoverflow.com/q/43499216
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/47953205
answer count: 1
downvote count: 0

http://stackoverflow.com/a/47943216
downvote count: 0
score: 1
has body: Yes, since import is a reserved word in Python, the Google python library will append a "_" to the API method name. Use: service.users().messages().import_(....) The documentation is currently (as of late 2017) incorrect and there's an open issue to fix it. See: https://github.com/google/google-api-python-client/issues/408
upvote count: 1
has comment: http://stackoverflow.com/comment/82870007
type: Answer
answers question: http://stackoverflow.com/q/47939137

http://stackoverflow.com/a/47934356
has comment: http://stackoverflow.com/comment/82838256
answers question: http://stackoverflow.com/q/47934340
has comment: http://stackoverflow.com/comment/82838301
type: Answer
accepted answer of: http://stackoverflow.com/q/47934340
has body: 2**10000000 This doesn’t take 2.5 minutes to execute. It takes 2.5 minutes to convert to a decimal string, which is how integers are printed by default. Try (2**10000000) % 10000000 or len(hex(2**10000000)).
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/115161271
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/47887198
type: Comment
has text: Not sure if this is the case when using `gevent`

http://stackoverflow.com/q/47903791
type: Question
tagged with: python-multiprocessing
has title: How to terminate a multiprocess in python when a given condition is met?
has comment: http://stackoverflow.com/comment/82774462
has body: Let's say I have the function: def f(): while True: x = generate_something() if x == condition: return x if __name__ == '__main__': p=Pool(4) I want to run this function in a multiprocess and when one of the processes meets my function's condition, I want all other processes to stop.
score: 2
answer count: 1
linked to: http://stackoverflow.com/q/36962462
downvote count: 0
has answer: http://stackoverflow.com/a/47905112
favorite count: 0
duplicate of: http://stackoverflow.com/q/36962462
upvote count: 2
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47905112
has comment: http://stackoverflow.com/comment/82776526
linked to: http://stackoverflow.com/q/33447055

http://stackoverflow.com/q/47910547
score: 4
has comment: http://stackoverflow.com/comment/82788711
tagged with: http://stackoverflow.com/tag/json
has title: Python requests.post() returns None
has comment: http://stackoverflow.com/comment/82788671
tagged with: post
upvote count: 4
answer count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47911432
downvote count: 0
favorite count: 0
tagged with: rest
type: Question
has answer: http://stackoverflow.com/a/47926586
has body: I know that this issue was discussed earlier but I am unable to find a working solution that fits my use case. We have an internal server (sorry, no external address available) that returns data. Invoking a POST Method on the Endpoint returns a JSON. I tried the post with the Postman tool to check a valid response is received. When using a Postman I receive the response as expected. An authentication is not necessary. However, Python Client fails to return data and an empty response is received. code snippet : import json import requests URL_PATH = "https://our.internal.server.rest.address" HEADERS = { 'Content-Type': 'application/json' } DATA = '''{ "method" : "object.read", "params" : "", "id" : 142 }''' S = requests.session() R = S.post(URL_PATH, headers=HEADERS, json=DATA) if R.ok: print("Type: ", R.headers["Content-Type"]) print("Text: ", str(R.text)) print("JSON: ", R.json()) print("Content", R.content) else: R.raise_for_status() S.close() The output is: Type: application/json Text: null JSON: None Content b'null' Any idea what I'm doing wrong with my Python code and why there is no data returned, but is when using a separate tool? I also tried to use data= in the post(): S.post(URL_PATH, headers=HEADERS, data=json.dumps(DATA)) or skip the Session() by directly using requests.post().
has answer: http://stackoverflow.com/a/55625260
has comment: http://stackoverflow.com/comment/82814852
possible better answer: http://stackoverflow.com/a/47911485
tagged with: python
tagged with: python-requests
has answer: http://stackoverflow.com/a/47911432
has answer: http://stackoverflow.com/a/47911485

http://stackoverflow.com/q/47983239
has comment: http://stackoverflow.com/comment/82935197
has comment: http://stackoverflow.com/comment/82935204
has title: How to extract a word from the line which is next to particular keyword
has answer: http://stackoverflow.com/a/47983272
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47983400
has answer: http://stackoverflow.com/a/47983315
has body: I want to extract a word which is next to the keyword in the line. Note: The keyword exists twice in the line and I want to print both words next to the keyword. Example: This is my first Python language and I like this language to the most. Desired Output:(need words next to language in below format) and to
has comment: http://stackoverflow.com/comment/82935134
type: Question
has comment: http://stackoverflow.com/comment/82935155
has comment: http://stackoverflow.com/comment/82935177
linked to: http://stackoverflow.com/q/22171558
score: 0
answer count: 3

http://stackoverflow.com/comment/82704679
score: 1
comment on: http://stackoverflow.com/a/47866951
type: AnswerComment
has text: So I would like to do it in my `BaseEndpoint` class, after dispatch_request. I think a better solution is to rollback here instead of commit? So I keep only transactions that were committed explicitly during a request, all the others will be rollbacked. What do you think?
type: Comment

http://stackoverflow.com/q/47943183
downvote count: 0
has comment: http://stackoverflow.com/comment/82856373
score: 1
has comment: http://stackoverflow.com/comment/82856764
has comment: http://stackoverflow.com/comment/82856595
type: Question
possible better answer: http://stackoverflow.com/a/47944346
has comment: http://stackoverflow.com/comment/82856937
answer count: 2
tagged with: pandas
upvote count: 1
has title: Scikit learn - output average probability of right choice
has answer: http://stackoverflow.com/a/47944424
accepted answer: http://stackoverflow.com/a/47944424
tagged with: scikit-learn
favorite count: 0
has body: So I'm messing around with a three outcome dataframe with Scikit-Learn. I'm more interested in predicting accurate probability rather than predicting the right outcome. Thus I use predict_proba rather than predict, and I can then output all the probabilities for each test instance being a, b or c, which is smooth! Is there any way to do a "probability score" the same way the accuracy_score(y_predictions, y_test) works? So that I get the average probability it has attributed each correct outcome? I can do this manually by copying it over to Excel or similar but it takes a lot of time.. Thanks! EDIT - this is what predict_proba outputs: A B C 1 [ 0.6 0.3 0.1] 2 [ 0.4 0.1 0.5] 3 [ 0.4 0.3 0.3] 4 [ 0.3 0.1 0.6] ... Now, assuming the outcomes of instance 1 and 2 is A, the outcome for instance 3 is C, and the outcome of instance 4 is B, that would give my model an "average probability of correct outcome" of (0.6 + 0.4 + 0.3 + 0.1) / number of instances (in this case 4) which is 0,35 or 35 %. I have the accurate results stored in y_test (of course) so I want to quickly be able to get this average probability of correct outcome for around the ~500 instances in my test set.
has answer: http://stackoverflow.com/a/47944346
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/47980199
type: UnansweredQuestion
score: -3
tagged with: python
has body: I am rather new to python and am trying to run a written script that starts with import numpy as np When I run the script, it says it can't find the module numpy. How do I find and install new modules such as numpy?
linked to: http://stackoverflow.com/q/21222114
downvote count: 3
type: Question
has answer: http://stackoverflow.com/a/52332160
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/82929240
has title: How do I add a new module in python?
favorite count: 0
has answer: http://stackoverflow.com/a/47980266

http://stackoverflow.com/q/47910558
downvote count: 0
favorite count: 0
has body: I am trying to read wikitables from this wikipedia page: https://en.wikipedia.org/wiki/Timeline_of_Apple_Inc._products I am using the following: import pandas as pd page = 'https://en.wikipedia.org/wiki/Timeline_of_Apple_Inc._products' wikitables = pd.read_html(page, attrs={"class":"wikitable"}) table1 = wikitables[0] Since the cell sizes are not equal (e.g. the year '1979' spans multiple models of Apple), this skews some cells to fill up the 'blank' cell and introduces NaNs in the wrong cells (e.g. values from the column 'model' end up in the column 'year'). here is a screenshot of the dataframe with skewed values Is there a way of fixing this while reading the html? Or another way of consistently filling those empty spaces in the cell so the values don't get skewed? Thanks in advance!
tagged with: python
answer count: 0
type: UnansweredQuestion
score: 1
tagged with: wikipedia
upvote count: 1
type: Question
tagged with: pandas
has title: Reading wikitables with unequal cell sizes in Pandas

http://stackoverflow.com/comment/82821033
score: 1
type: AnswerComment
type: Comment
has text: Stuck at wait again with that change. There is something strange going on with headless Chrome and this page.
comment on: http://stackoverflow.com/a/47925369

http://stackoverflow.com/q/47868134
has body: I have some data of soil's moisture content (Theta) in the form of 3D-domain points (CSV file of the columns x, y, z, Theta). I want to take cross sections from the 3D domain in some specific positions (section ABCD in the figure). I want to calculate the value of Theta in a 5*5 grid in the cross-section, but the points around each node of the grid are not coplanar with the unknown point. I did this before for 2D domains in python, but the 3D domains seem more complicated for me. I found that plotly can make something like that in its virtual environment but I want this to output a numpy array or pandas DataFrame to draw it as a contour in the jupyter notebook. I know that finding the grid involves finding the value of each point like P0 in the figure by interpolation or gridding from its neighbors, then to draw the cross section using matplotlib, but I don' know how to do it. Related question, Is slicing 2D grids from 3D grids available in matplotlib or similar libraries? Thanks for all help.
tagged with: scipy
tagged with: plotly
tagged with: matplotlib
has answer: http://stackoverflow.com/a/47870607
has title: How to slice 2D grid from 3D irrigular data?
type: Question
upvote count: 2
answer count: 2
tagged with: 3d
has answer: http://stackoverflow.com/a/47868572
favorite count: 0
linked to: http://stackoverflow.com/q/15748767
tagged with: python
score: 2
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/82723176
type: Comment
has text: This just looks like a plainly terrible idea.
score: 8
comment on: http://stackoverflow.com/q/47878597
type: QuestionComment

http://stackoverflow.com/a/47942523
has comment: http://stackoverflow.com/comment/82855342
answers question: http://stackoverflow.com/q/47941954
downvote count: 0
has body: The problem there is that the static page brought up by Google does not actually contain any image-search results. If you fetch the images contained in the result you are getting, you will find Google logo, and some structural images - maybe the tags they use to suggest search refining. The actual images are loaded lazily by Javascript code, and it is very though to get those using requests - it will imply you checking which requests the client code of the page is doing to the server, by using your browser's tools, and mimicking those instead. This may or not be feasible, as it would be easy for Google to insert some tokens and pre-calculation to the lazy-requests that would be very hard to reverse-engineer from the Javascript on the page. Also, it most likely violates the terms of use of Google's image search. You could try switching to Selenium to do the web search, instead of requests. As that uses a real browser, it will run the Javascript and make the actual lazy requests. It will work - but you will still be infringing the terms of use of the site, and it might not be long before you start getting captchas in your results. So, the correct way to do this sort of thing is check if the service provider - Google Image Search in this case - have a public API you can make use of to perform your searches. On searching for that, you will find out that Google Image Search API is a deprecated thing, and it is now possible to use Google Search API to look for images. Currently they allow 100 free searches per day, and the service is charged after that. Here is their link for understanding the API, and probably signing-up https://developers.google.com/custom-search/json-api/v1/overview?csw=1 After you are done understanding and getting an API Key, there is a Python wrapper for the API which can spare you a lot of headache and likely deliver you the URLs for the images: https://pypi.python.org/pypi/Google-Search-API
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/q/47999678
score: 0
answer count: 0
type: UnansweredQuestion
tagged with: python
has title: VSCode Requires Carriage Return for Python Print
has comment: http://stackoverflow.com/comment/82969433
type: Question
tagged with: visual-studio-code
has comment: http://stackoverflow.com/comment/82967897
tagged with: powershell
has body: I'm running the following statement in VSCode by opening up the test.ps1 file and hitting F5. The problem is that it won't print "hi mom" in the VSCode Terminal window until I focus in the Terminal window and hit carriage return. it will hang there forever. I don't have this problem in the normal PowerShell ISE, it prints immediately. Any ideas? Test.ps1 python d:\RepoStats\Python\Test.py Test.py print("hi mom!")

http://stackoverflow.com/q/47915698
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82799457
upvote count: 1
tagged with: python
downvote count: 1
has body: It's my first time here and I'm kinda panicking. I have an assignment to code Rock, Paper, Scissors in Python. (I use Python 3.1) and for some reason the function is not running...? Here's the code: hscore = 0 cscore = 0 tries = 0 #computer choice rock = ("rock") paper = ("paper") scissors = ("scissors") rps = (rock, paper, scissors) cchoice = random.choice(rps) choice = input("\nWhat do you choose? &lt;rock, paper, scissors&gt;: ") tries +=1 def humanfunction(): if choice == "rock": if cchoice == scissors: print("Human wins this round.") hscore +=1 if choice == "scissors": if cchoice == paper: print("Human wins this round.") hscore +=1 if choice == "paper": if cchoice == rock: print("Human wins this round.") hscore +=1 if cchoice == choice: print("Tie.") def compfunction(): if cchoice == scissors: if choice == "paper": print("Computer wins this round.") cscore +=1 if cchoice == rock: if choice == "scissors": print("Computer wins this round.") cscore +=1 if cchoice == paper: if choice == "rock": print("Computer wins this rounud.") cscore +=1 if cchoice == choice: print("Tie.") def choose(): tries = 0 while 0 == 0: choice = input("\nWhat do you choose? &lt;rock, paper, scissors&gt;: ") tries +=1 print("\nHuman choice: ", choice) print("Computer choice: ", cchoice) print("Finished game number", tries) if tries == 10: print("Limit reached!") break humanfunction() compfunction() choose() I've been trying to solve this for days now and for some reason, when I run the code, it doesn't show up who won. Help would be appreciated &lt;3 EDIT: here's what i get when i run the code: output the program is actually supposed to show this: output2
type: Question
has comment: http://stackoverflow.com/comment/82799711
has comment: http://stackoverflow.com/comment/82799717
has answer: http://stackoverflow.com/a/47915885
score: 0
has title: Python Function not running?
has comment: http://stackoverflow.com/comment/82799497
answer count: 1

http://stackoverflow.com/a/57657074
has body: Its very easy... This method working perfectly with google. Also try with any other if you know the url prams import dryscrape as d d.start_xvfb() br = d.Session() import urllib.parse query = urllib.parse.quote("فارسی") print(query) #it prints : '%D9%81%D8%A7%D8%B1%D8%B3%DB%8C' Url = "http://google.com/search?q="+query br.visit(Url) print(br.xpath('//title')[0].text()) #it prints : Google Search - فارسی #You can also check it with br.render("url_screenshot.png")
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47900129

http://stackoverflow.com/a/48918516
has body: I hope this helps: @tfabiant, To run this code, in the terminal type: python script.py fastafile.fasta def unambiguous(sequences): nucleotide_weights = {'A':331.2218, 'T':322.2085, 'C':307.1971, 'G':347.2212} for seq in sequences: seqname = seq sequence = sequences[seq] weight = 0 for nucleotide in sequence: if nucleotide not in nucleotide_weights: weight = "AMBIGUOUS" break else: weight+=nucleotide_weights[nucleotide] if weight != "AMBIGUOUS": print "%s\t\tWEIGHT %s"%(seqname, weight) def readfasta(): ##########I. Load Fasta File file = open(sys.argv[1]) rfile = file.readline() seqs = {} ##########II. To Make fasta dictionary with the sequences tnv = ""#temporal name value while rfile != "": if "&gt;" in rfile: tnv = string.strip(rfile) seqs[tnv] = "" else: seqs[tnv] += (string.strip(rfile)).upper() rfile = file.readline() return(seqs) #To run this code, in the terminal: python readDNA.py fastafile.fasta # OR insert this function in your code import string, sys sequences = readfasta() unambiguous(sequences)
score: 0
answers question: http://stackoverflow.com/q/47942453
type: Answer

http://stackoverflow.com/q/47977255
tagged with: python
tagged with: directory
tagged with: merge
has comment: http://stackoverflow.com/comment/82925738
type: UnansweredQuestion
tagged with: path
tagged with: file
has comment: http://stackoverflow.com/comment/82924137
score: 2
downvote count: 0
has title: How to merge content from files with same name but in different folders by Python?
has answer: http://stackoverflow.com/a/47977702
type: Question
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/82923463
has answer: http://stackoverflow.com/a/47977601
has comment: http://stackoverflow.com/comment/82923953
has comment: http://stackoverflow.com/comment/82925746
favorite count: 0
has body: I'm trying to merge content from different TXT files by using Python, but the challenge is I need to only merge content from the same file names coming from different folders. Here's a screenshot for your reference: So far, I can print out all the file names with their full paths: import os for root, dirs, files in os.walk(".", topdown=False): for file in files: if file.endswith(".txt"): filepath = os.path.join(root, file) print (filepath) However, how could I use Python to only merge files with the same name...still researching. Let me know if you know the answer, or point me a way to research more. Thank you very much and happy holidays!

perforce
tags question: http://stackoverflow.com/q/47899386
type: Tag
tag name: perforce

http://stackoverflow.com/comment/82829240
type: Comment
type: QuestionComment
has text: C and C++ do not support multiple assignment the way Python does. In C and C++, the statement `A, B = B, A + B` is parsed as `(A), (B = B), (A + B)` and evaluated as "evaluate `A` and discard the result, then assign `B` to `B`, then evaluate `A + B` and discard the result." To do what you want in C, you'd have to use two separate assignment statements - `A = B; B = A + B;`
comment on: http://stackoverflow.com/q/47926650
score: 0

http://stackoverflow.com/q/47916452
has title: Link Errors Installing Python Blosc
has comment: http://stackoverflow.com/comment/82804706
has comment: http://stackoverflow.com/comment/82801765
tagged with: bcolz
type: UnansweredQuestion
tagged with: python
has body: I installed C-Blosc library no problem, but when I try to install python-blosc and get to python setup.py build_ext --inplace --blosc="C:\\Program Files (x86)\\blosc" I get link errors. What's going on? I have Windows 7 and am trying to install Python Blosc in MSVC 2015 from here https://github.com/Blosc. running build_ext building 'blosc.blosc_extension' extension C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD "-IC:\Program Files (x86)\blosc\include" -IC:\Users\adam.hendry\AppData\Local\Programs\Python\Python35\include -IC:\Users\adam.hendry\AppData\Local\Programs\Python\Python35\include "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.16299.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.16299.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.16299.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.16299.0\winrt" /Tcblosc/blosc_extension.c /Fobuild\temp.win-amd64-3.5\Release\blosc/blosc_extension.obj blosc_extension.c C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\link.exe /nologo /INCREMENTAL:NO /LTCG /DLL /MANIFEST:EMBED,ID=2 /MANIFESTUAC:NO "/LIBPATH:C:\Program Files (x86)\blosc\lib" /LIBPATH:C:\Users\adam.hendry\AppData\Local\Programs\Python\Python35\libs /LIBPATH:C:\Users\adam.hendry\AppData\Local\Programs\Python\Python35\PCbuild\amd64 "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\LIB\amd64" "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\LIB\amd64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.16299.0\ucrt\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\lib\um\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.16299.0\um\x64" blosc.lib /EXPO…
has comment: http://stackoverflow.com/comment/82803246
has comment: http://stackoverflow.com/comment/82803287
has answer: http://stackoverflow.com/a/54608096
tagged with: linker-errors
type: Question
has comment: http://stackoverflow.com/comment/82801649
has comment: http://stackoverflow.com/comment/82801424
has comment: http://stackoverflow.com/comment/82801673
has comment: http://stackoverflow.com/comment/82803192
score: 0
answer count: 1

http://stackoverflow.com/q/47866365
has comment: http://stackoverflow.com/comment/82700767
type: Question
score: 0
has body: What are the different modules/ways to copy file from a windows computer to a linux server available in python I tried using ftplib api to connect to the windows server but i m unable to do with the error - socket.error: [Errno 111] Connection refused What are the other modules that i can connect to a windows computer to copy or list the files under a directory
has answer: http://stackoverflow.com/a/47869378
has comment: http://stackoverflow.com/comment/82701986
upvote count: 1
answer count: 1
downvote count: 1
has title: Copy File from Windows Host to Linux [Python]
favorite count: 0
tagged with: ftplib
has comment: http://stackoverflow.com/comment/82702037
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82703579

http://stackoverflow.com/q/47857410
type: UnansweredQuestion
type: Question
linked to: http://stackoverflow.com/q/39579727
has answer: http://stackoverflow.com/a/47858891
tagged with: usb
has title: usb automatic detection in python for linux env
score: 0
answer count: 3
tagged with: pyserial
has comment: http://stackoverflow.com/comment/82679295
has comment: http://stackoverflow.com/comment/84938324
has answer: http://stackoverflow.com/a/47857595
tagged with: linux
has body: I'm using polling command(glob('/dev/tty[A-Za-z]*')) in python to detect usb devices connected to my linux pc in regular interval for my application. Is there any way to detect usb devices connected automatically?
tagged with: serial-port
tagged with: python
has answer: http://stackoverflow.com/a/47857560

http://stackoverflow.com/comment/116817687
has text: To make it work in Spacy V. 3.0 matcher.add("Verb phrase", [pattern])
type: AnswerComment
comment on: http://stackoverflow.com/a/62038950
type: Comment
score: 3

http://stackoverflow.com/comment/82945305
type: QuestionComment
type: Comment
has text: You should not declare the input list inside your function, the way you did it, it is not even callable from the outside (so `print(top_three(input_list))` will give error).
score: 0
comment on: http://stackoverflow.com/q/47988324

http://stackoverflow.com/comment/82726494
score: 0
has text: I habe also tried finding them by id and got the same result. I have witnessed the firs part of the code executing amd filling in the username and password, it seems to specifically be happening when I try to submit or identify the click button element and use the click method. How will increasing the performance of the test execution preventing this error from occurring?
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47879839

http://stackoverflow.com/q/47992133
score: 0
tagged with: python
favorite count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/47992299
downvote count: 1
has title: Add www after http/https using urlparse in python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47992299
type: Question
has body: I want to add www after HTTP/https in particular URL. Here is my code: import urllib from urllib.parse import urlunsplit def addhttps(url): replaced=urllib.parse.urlsplit(url) if replaced.scheme=='http' or replaced.scheme=='https' or replaced.scheme=='': replaced = replaced._replace(scheme="https") return replaced.geturl() def addWWW(url): replaced=urllib.parse.urlsplit(url) if replaced.netloc=='': replaced = replaced._replace(netloc="www") return replaced.geturl() s="example.com" c=addhttps(s) d=addWWW(c) print(c) print(d) I am getting output which i don't want: https:///example.com https://www/example.com I am expecting output like this: https://example.com https://www.example.com Thanks in advance :)
answer count: 1

http://stackoverflow.com/a/57806388
has comment: http://stackoverflow.com/comment/106256054
downvote count: 0
answers question: http://stackoverflow.com/q/47892039
type: Answer
score: 2
upvote count: 2
has body: It is not officially supported feature. But take a look at this. You can modify ~/.spyder-py3/spyder.ini and ColorSchemeName.ini and save them.

http://stackoverflow.com/q/47926966
has answer: http://stackoverflow.com/a/47927008
accepted answer: http://stackoverflow.com/a/47927008
tagged with: python
has title: PySpark - Calling a function within a UDF
upvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82822116
score: 1
tagged with: pyspark
tagged with: dataframe
has comment: http://stackoverflow.com/comment/82844905
type: Question
has body: I have created a UDF however I need to call a function within a UDF. It currently returns nulls. Could someone please explain why I am getting this error. a= spark.createDataFrame([("A", 20), ("B", 30), ("D", 80)],["Letter", "distances"]) def get_number(num): return range(num) from pyspark.sql.functions import udf def cate(label): if label == 20: counting_list = get_number(4) return counting_list else: return [0] udf_score=udf(cate, ArrayType(FloatType())) a.withColumn("category_list", udf_score(a["distances"])).show(10) out: +------+---------+--------------------+ |Letter|distances| category_list| +------+---------+--------------------+ | A| 20|[null, null, null...| | B| 30| [null]| | D| 80| [null]| +------+---------+--------------------+
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/82821212
comment on: http://stackoverflow.com/a/47926677
type: Comment
type: AnswerComment
has text: ah...the x_0 coefficient. Definitely. Thanks a lot
score: 1

enthought
tags question: http://stackoverflow.com/q/47945894
type: Tag
tag name: enthought

http://stackoverflow.com/comment/82714703
score: 0
has text: Please, check out some of the recommendations I have provided in my answer and give some feedback on whether they were helpful.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47874461

http://stackoverflow.com/a/47946650
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47946448
answers question: http://stackoverflow.com/q/47946448
type: Answer
has body: How tkinter works: create_rectangle adds a rectangle, but doesn't draw it it returns an id (the number), so you can modify it later when you call mainloop everything displays this will get you a rectangle from tkinter import Tk, Canvas, mainloop c = Canvas(Tk(), width=200, height=100) c.pack() c.create_rectangle(50, 25, 150, 75, fill="red", outline="red") mainloop() If you want to use tkinter from the command line, there's discussion here about how to configure it but it looks complicated.

http://stackoverflow.com/comment/82732677
type: QuestionComment
has text: I would add the tags `math` and `algorithm` and ask a similar question about algorithms on [SE mathematics](https://math.stackexchange.com/).
score: 0
comment on: http://stackoverflow.com/q/47883034
type: Comment

http://stackoverflow.com/q/47995944
score: 0
type: UnansweredQuestion
type: Question
linked to: http://stackoverflow.com/q/35991403
has title: Raspberry Pi Cannot Download Packages Using Pip
has comment: http://stackoverflow.com/comment/82978967
has body: I am having an issue downloading packages on my Raspberry Pi 2 using pip. When running sudo pip install packageName, the following is outputted: Command python setup.py egg_info failed with error code 1 in /home/pi/build/jsonschema Storing complete log in /root/.pip/pip.log Has the package installed successfully, or was there an error? The packages that I am trying to install are piui and plotly.
tagged with: raspberry-pi2
tagged with: python
has comment: http://stackoverflow.com/comment/82960058
answer count: 0
has comment: http://stackoverflow.com/comment/82959976

http://stackoverflow.com/comment/82741129
score: 0
comment on: http://stackoverflow.com/q/47887454
type: Comment
type: QuestionComment
has text: I want to check if the first player always wins (given that he plays correctly)

http://stackoverflow.com/comment/82719049
has text: @umerselmani because of the first part of my comment. Printing the value of a subtraction does not inherently change the values themselves. `health1` will always be the same value, you're just visualising the result of subtracting some number from it.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47876558
score: 0

http://stackoverflow.com/q/47985787
tagged with: python
answer count: 1
has title: How to use numpy fillna() with numpy.where() for a column in a pandas DataFrame?
has comment: http://stackoverflow.com/comment/82940593
has answer: http://stackoverflow.com/a/47985922
tagged with: numpy
has body: Here is an example pandas DataFrame: import pandas as pd import numpy as np dict1 = {'file': ['filename2', 'filename2', 'filename3', 'filename4', 'filename4', 'filename3'], 'amount': [3, 4, 5, 1, 2, 1], 'front': [21889611, 36357723, 196312, 11, 42, 1992], 'back':[21973805, 36403870, 277500, 19, 120, 3210], 'type':['A', 'A', 'A', 'B', 'B', 'C']} df1 = pd.DataFrame(dict1) print(df1) file amount front back type 0 filename2 3 21889611 21973805 A 1 filename2 4 36357723 36403870 A 2 filename3 5 196312 277500 A 3 filename4 1 11 19 B 4 filename4 2 42 120 B 5 filename3 1 1992 3210 C I'm defining a new column end using numpy.where(): df1['end'] = np.where(df1['type']=='B', df1['front'], df1['front'] + df1['back']) print(df1) amount back file front type end 0 3 21973805 filename2 21889611 A 43863416 1 4 36403870 filename2 36357723 A 72761593 2 5 277500 filename3 196312 A 473812 3 1 19 filename4 11 B 11 4 2 120 filename4 42 B 42 5 1 3210 filename3 1992 C 5202 I would like to use the same approach to fill in NaN values, if the end column partially exists, e.g. here is a DataFrame where a end does exist as a column, but with many NaN values. (EDIT: these values that are not NA may be entirely unique): new_df amount back file front type end 0 3 21973805 filename2 21889611 A NaN 1 4 36403870 filename2 36357723 A NaN 2 5 277500 filename3 196312 A 12 3 1 19 filename4 11 B NaN 4 2 120 filename4 42 B 49 5 1 3210 filename3 1992 C NaN I would think one could do this with pandas.DataFrame.fillna(), but this throws an error: df1['end'].fillna(np.where(df1['type']=='B', df1['front'], df1['front'] + df1['back']), inplace=True) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python3.6/site-packages/pandas/core/series.py", line 2434, in fillna **kwargs) File "/usr/local/lib/python3.6/site-packages/pandas/core/generic.py", line 3631, in fillna type(value)) ValueError: invalid fill value with a &lt;class 'numpy.ndarray'&gt; Question: how do…
downvote count: 0
tagged with: dataframe
has comment: http://stackoverflow.com/comment/82940740
has comment: http://stackoverflow.com/comment/82940822
has comment: http://stackoverflow.com/comment/82940783
tagged with: fillna
tagged with: pandas
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47985922
favorite count: 0
has comment: http://stackoverflow.com/comment/82940801
type: Question
upvote count: 2

http://stackoverflow.com/a/47999676
answers question: http://stackoverflow.com/q/47999555
score: 2
has body: Standard way of doing this is to store it in a dictionary that has the user's desired key as in: def save(self): global df df = pd.DataFrame({'AAA' : [1., 2., 3., 4.], 'BBB' : [4., 3., 2., 1.]}) should simply be replaced with: def save(self): global df user_spec = self.pythonVar.get() df[user_spec] = pd.DataFrame({'AAA' : [1., 2., 3., 4.], 'BBB' : [4., 3., 2., 1.]}) while also declaring df as a dictionary in the global scope, for example in 'main': if __name__ == "__main__": df = dict() PyDataTest().mainloop() A dangerous, and error-prone way would be to use exec or eval built-in method, like in here.
has comment: http://stackoverflow.com/comment/82990827
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/comment/82914854
comment on: http://stackoverflow.com/q/47972602
type: QuestionComment
type: Comment
has text: What do you mean without a getter? That *is* the getter. The decorator is used to make it attribute access `self._constructor` rather than a method call `self._constructor()`.
score: 4

http://stackoverflow.com/q/47933184
has answer: http://stackoverflow.com/a/47933279
has answer: http://stackoverflow.com/a/47933305
tagged with: python
accepted answer: http://stackoverflow.com/a/47933279
type: AnsweredQuestion
tagged with: 2d
tagged with: list
tagged with: delete-row
type: Question
answer count: 2
has body: I have two 2D lists that look like this: list1 = [[26, "k", 5.78], [26, "M", 5.89], [26, "J", 7.89], ......... [290, "O", 9.9]] len(list1) = 4978 list2 = [[26, "k", 0.99], [26, "M", 0.88], [26, "J", 9.77], ....... [290, "O", 7.88]] len(list2) =4765 I want to iterate through list1 and if one row's first index and second index is not in list2, I want to delete this row. Essentially, it's something like this: for i in list1: if i[0]+i[1] not in any rows of list2, delete this row from list1. for example, if list1 has a row like this: [57, "k", 9.8] but in list2, there is no row that contains 57, and "k", then I need to delete this row from list1. the third column in both list1 and list2 is not involved in this comparison. And also, it's guaranteed that for every row in list2, there is another row in list1 that contains corresponding first element and second element, meaning that, if list2 has a row like: [58, "J", 0.9] Then, list1 definitely has a row starting with 58, and "J"
score: 0
has title: compare 2 2D lists and delete items from one list based on another
possible better answer: http://stackoverflow.com/a/47933305

http://stackoverflow.com/q/47934144
linked to: http://stackoverflow.com/q/47895765
tagged with: python-multithreading
has title: Update data in a Tkinter-GUI with data from a second Thread
has body: The question is if my solution is a save and pythonic way to update a Tkinter-GUI with data from another thread? Are Locks required? Or how could a Queue help here? This example is working fine but the original application has much more complex data to deal with. Please focus on AsyncioThread.create_dummy_data() in the minimal working example. The example has two threads. One run the Tkinter-mainloop and the second thread run a asyncio-loop. The asyncio-loop simulates getting some data and refreshing some tkinter.Label with this data. #!/usr/bin/env python3 # -*- coding: utf-8 -*- # restrict to Python3.5 or higher because of asyncio syntax # based on &lt;https://stackoverflow.com/a/47920128/4865723&gt; from tkinter import * import asyncio import threading import random class AsyncioThread(threading.Thread): def __init__(self, asyncio_loop, theWindow): self.asyncio_loop = asyncio_loop self.theWindow = theWindow self.maxData = len(theWindow.varData) threading.Thread.__init__(self) def run(self): self.asyncio_loop.run_until_complete(self.do_data()) async def do_data(self): """ Creating and starting 'maxData' asyncio-tasks. """ tasks = [ self.create_dummy_data(number) for number in range(self.maxData) ] completed, pending = await asyncio.wait(tasks) results = [task.result() for task in completed] print('\n'.join(results)) async def create_dummy_data(self, number): """ One task. """ sec = random.randint(1, 3) data = '{}:{}'.format(number, random.random()) await asyncio.sleep(sec) # IS THIS SAVE? self.theWindow.varData[number].set(data) print('Thread-ID: {}\tsec: {}\n\t{}' \ .format(threading.get_ident(), sec, data)) return data class TheWindow: def __init__(self, maxData): # asyncio loop will run in an extra Thread self.asyncio_loop = asyncio.get_event_loop() # the GUI main object self.root = Tk() # create the data variable self.varData = [] for i in range(maxData): self.varData.append(StringVar()) self.varData[i].set('&lt;default&gt;') # Button to start the asyncio task…
has comment: http://stackoverflow.com/comment/82848374
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/67452689
has comment: http://stackoverflow.com/comment/82850429
score: 1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/67452689
upvote count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/17847869
favorite count: 0
has comment: http://stackoverflow.com/comment/82849968
tagged with: python-asyncio
has answer: http://stackoverflow.com/a/47947223
tagged with: python
accepted answer: http://stackoverflow.com/a/47947223
tagged with: asynchronous
tagged with: tkinter

http://stackoverflow.com/a/47984209
score: 4
has body: From your reply to my comment, I think I understand what you want to do. With dictionnary = {'keyid': ['foo', '1', 'bar', '2', '(FancyStrininParathesis)']} you can iterate through the values with dictionnary.items(): for key, value in dictionnary.items(): ... Now because here value is a list, we can iterate through it and create our own output string: for key, value in dictionnary.items(): output = "" for item in value: output += item + " - " output = output[:-3] # Remove the last three characters print(output) A more pythonic way would be to use str.join: for key, value in dictionnary.items(): output = str.join(" - ", value) print(output)
type: Answer
accepted answer of: http://stackoverflow.com/q/47984091
has comment: http://stackoverflow.com/comment/82937513
has comment: http://stackoverflow.com/comment/82937538
upvote count: 4
answers question: http://stackoverflow.com/q/47984091
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/47941287
type: Answer
has body: fillna replaces the Nan values with what you write so if you write '', it will be an empty string. just write: dataset.fillna(0) if you need to distinguish between 0 and Nan, you can try replace it with -1, that's what we do.
answers question: http://stackoverflow.com/q/47941232
score: 0
has comment: http://stackoverflow.com/comment/82852501
has comment: http://stackoverflow.com/comment/82854261
has comment: http://stackoverflow.com/comment/82852805
has comment: http://stackoverflow.com/comment/82852714

http://stackoverflow.com/q/47967663
answer count: 1
has comment: http://stackoverflow.com/comment/82904827
has comment: http://stackoverflow.com/comment/82905221
favorite count: 0
has comment: http://stackoverflow.com/comment/82905079
tagged with: python
has comment: http://stackoverflow.com/comment/82905113
has comment: http://stackoverflow.com/comment/82904783
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82905335
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/82904853
has title: Need to sum a,b,c, unless they equal 13,14,17,18,19
has comment: http://stackoverflow.com/comment/82904817
accepted answer: http://stackoverflow.com/a/47968003
type: Question
has body: Here is my assignment: Given 3 int values, a b c, return their sum. However, if any of the values is a teen -- in the range 13..19 inclusive -- then that value counts as 0, except 15 and 16 do not count as a teens. Write a separate helper "def fix_teen(n):"that takes in an int value and returns that value fixed for the teen rule. In this way, you avoid repeating the teen code 3 times (i.e. "decomposition"). Define the helper below and at the same indent level as the main no_teen_sum(). Here is the only solution I could come up with: excep = [13,14,17,18,19] def no_teen_sum(a, b, c): if a in excep and b in excep and c in excep: return 0 elif a in excep and b in excep and c not in excep: return c elif b in excep and c in excep and a not in excep: return a elif a in excep and c in excep and b not in excep: return b elif a in excep and b not in excep and c not in excep: return b+c elif b in excep and a not in excep and c not in excep: return a+c elif c in excep and a not in excep and b not in excep: return a+b else: return a+b+c
has comment: http://stackoverflow.com/comment/82904892
has comment: http://stackoverflow.com/comment/82904883
has answer: http://stackoverflow.com/a/47968003
upvote count: 1

http://stackoverflow.com/a/47935939
score: 3
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: If you return True from an __exit__ clause, it will stop any errors from going through. For example: class Foo(): def __enter__(self): print("enter") def __exit__(self, type, value, tb): print("exit with", repr(value)) return True with Foo(): print("inside") raise ValueError() will output enter inside exit with ValueError() but not raise anything because __exit__() returned True. In the example case, if the error raised is a TypeError, the statement: return isinstance(value, TypeError) Will return True and the TypeError will be "swallowed".
accepted answer of: http://stackoverflow.com/q/47935881
answers question: http://stackoverflow.com/q/47935881
upvote count: 3

http://stackoverflow.com/q/47969587
linked to: http://stackoverflow.com/q/18682830
has title: Opencv Python open dng format
tagged with: python
tagged with: opencv
type: AnsweredQuestion
has body: I can't figure out how to open a dng file in opencv. The file was created when using the pro options of the Samsung Galaxy S7. The images that are created when using those options are a dng file as well as a jpg of size 3024 x 4032 (I believe that is the dimensions of the dng file as well). I tried using the answer from here (except with 3 colors instead of grayscale) like so: import numpy as np fd = open("image.dng", 'rb') rows = 4032 cols = 3024 colors = 3 f = np.fromfile(fd, dtype=np.uint8,count=rows*cols*colors) im = f.reshape((rows, cols,colors)) #notice row, column format fd.close() However, i got the following error: cannot reshape array of size 24411648 into shape (4032,3024,3) Any help would be appreciated
score: 7
upvote count: 7
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/70603556
has answer: http://stackoverflow.com/a/70603556
has answer: http://stackoverflow.com/a/47969969
tagged with: image
tagged with: type-conversion
answer count: 2
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/47969969

http://stackoverflow.com/comment/82743873
score: 0
type: AnswerComment
type: Comment
has text: Or you can create class ResourceManager which will load image/sound/etc. when you will need it first time and later it will keep it in memory ("caching") to get it from memory next time, it can also generate rotated images when you ask for it first time and later it can keep it in memory so it doesn't have to rotate it again.
comment on: http://stackoverflow.com/a/47876915

http://stackoverflow.com/q/47977379
tagged with: inheritance
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82925090
has comment: http://stackoverflow.com/comment/82924785
has body: I had a base class A with a old_name() method. Subclasses used to inherit from A and override old_name() by first calling A.old_name(): class A(): '''Old A class''' def old_name(self): print('foo') class B(A): '''Old Subclass.''' def old_name(self): A.old_name(self) print('bar') b = B() b.old_name() # must print 'foo bar', prints 'foo bar' Now, I want to change old_name into new_name. However, I don't want to break my API so I still want old subclasses like B to support both calls to new_name() and old_name(). I also want new subclasses (like C) to support both methods. By that, I mean that it must print foo bar whether new_name() was called or old_name() was called. I cannot modify class B: the only one I can change is class A. Here is what I came up with. Unfortunately, B does not support a direct call to new_name() because it bypasses b.old_name(). class A(): '''New A class. Now A has to support new_name AND old_name.''' def old_name(self): self.new_name() def new_name(self): print('foo') class B(A): '''Old Subclass, still using old_name''' def old_name(self): A.old_name(self) print('bar') class C(A): '''New Subclass, now using new_name''' def new_name(self): A.new_name(self) print('bar') b = B() b.new_name() # must print 'foo bar', only prints 'foo'. Bad. b.old_name() # must print 'foo bar', prints 'foo bar'. OK. c = C() c.new_name() # must print 'foo bar', prints 'foo bar'. OK. c.old_name() # must print 'foo bar', prints 'foo bar'. OK. Any help would be greatly appriciated!
has comment: http://stackoverflow.com/comment/82925056
tagged with: python
has comment: http://stackoverflow.com/comment/82923668
has answer: http://stackoverflow.com/a/47977573
type: UnansweredQuestion
score: 0
upvote count: 1
downvote count: 1
type: Question
has title: Python: renaming a method while keeping backward compatibility
tagged with: rename

http://stackoverflow.com/comment/82744883
has text: there is no sense to use `GetFilePath1()` if you can get `fileListA` directly - `file1 = fileListA`. Python is not Java which likes getter/setter methods (`GetSomethig()` , `SetSomething()`)
comment on: http://stackoverflow.com/q/47889011
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48009064
tagged with: python
tagged with: alphanumeric
has body: Searching a large syslog repo and need to get a specific word to match with a certain condition. I'm using regex to compile a search for this word. I've read the python docs on regex characters and I understand how to specify each criteria separately but somehow missing how to concatenate all together for my specific search. This is what I have so far but not working... p = re.compile("^'[A-Z]\w+'$") match = re.search(p, syslogline, ) the word is a username that can be alphanum, always beginning with an uppercase character (preceded by blank space), can contain chars or nums, is 3-12 in length and ends with single quote. an example would be: Epresley01' or J98473'
has comment: http://stackoverflow.com/comment/82986915
has answer: http://stackoverflow.com/a/48009329
has comment: http://stackoverflow.com/comment/82986425
has answer: http://stackoverflow.com/a/48009337
type: Question
answer count: 2
tagged with: string
score: 0
tagged with: regex
has comment: http://stackoverflow.com/comment/82986327
has comment: http://stackoverflow.com/comment/82986347
has title: Python regex specific word with singe quote at end
has comment: http://stackoverflow.com/comment/82987873
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82986668

http://stackoverflow.com/q/47955588
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82881480
type: Question
score: 2
tagged with: interpreter
has comment: http://stackoverflow.com/comment/82881072
upvote count: 2
has answer: http://stackoverflow.com/a/48130563
answer count: 2
has comment: http://stackoverflow.com/comment/82881459
has comment: http://stackoverflow.com/comment/82881645
has title: Python interactive shell / interpreter in the Atom editor
tagged with: atom-editor
has comment: http://stackoverflow.com/comment/82881672
tagged with: python
has answer: http://stackoverflow.com/a/47955633
tagged with: shell
favorite count: 0
has body: I am programming in Python 3 and I recently found Atom editor. It looks amazing and has a great functionality. I want to ask, if there is a package or any way of having an interactive python shell in the Atom editor. And no, I am not looking for simple script executing package such as the script package or the Hydrogen package. I need this: (shell.jpg) Thanks.
tagged with: python-3.x

countvectorizer
type: Tag
tags question: http://stackoverflow.com/q/47887247
tag name: countvectorizer

http://stackoverflow.com/comment/82914599
type: Comment
has text: Amazing! I have no clue how it works (still learning about the details), but it works like a charm. Many thanks!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47972457

http://stackoverflow.com/q/47891056
has comment: http://stackoverflow.com/comment/82750312
has comment: http://stackoverflow.com/comment/82751302
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/82751386
upvote count: 1
has comment: http://stackoverflow.com/comment/82751439
tagged with: python-requests
tagged with: scrapy
type: Question
has comment: http://stackoverflow.com/comment/82751590
has body: I'm working on an ocr project using scrapy using the ocr api at https://ocr.space/ocrapi . I have some code that works successfully using requests: file_string = ctypes.string_at(image_data_pointer, length.value) payload_filename = 'my_hires_image.jpg' # Post payload as multipart encoded image file with filename. # requests.post(THE_URL, files={'file': (payload_filename, payload)}) payload = {'isOverlayRequired': overlay, 'apikey': api_key, 'language': language, r = requests.post('https://api.ocr.space/parse/image', files={payload_filename: file_string}, data=payload, ) return r.content.decode() I'm now trying to turn this into a scrapy post request. I have: payload_filename = 'my_hires_image.jpg' # Post payload as multipart encoded image file with filename. # requests.post(THE_URL, files={'file': (payload_filename, payload)}) body = {'file': file_string, 'isOverlayRequired': True, 'apikey': 'mykey', 'language': 'eng', } files = {payload_filename: file_string} yield FormRequest(url='https://api.ocr.space/parse/image', headers=headers2, formdata=body, callback=self.ocr_space, meta={'row': row, 'cookiejar': i}, dont_filter=True) please note that file_string is a byte string. You can see it in screenshot above. The code is giving me: File "/\lib\site-packages\scrapy\utils\defer.py", line 102, in iter_errback yield next(it) File "/\lib\site-packages\scrapy\spidermiddlewares\offsite.py", line 29, in process_spider_output for x in result: File "/\lib\site-packages\scrapy\spidermiddlewares\referer.py", line 339, in &lt;genexpr&gt; return (_set_referer(r) for r in result or ()) File "/\lib\site-packages\scrapy\spidermiddlewares\urllength.py", line 37, in &lt;genexpr&gt; return (r for r in result or () if _filter(r)) File "/\lib\site-packages\scrapy\spidermiddlewares\depth.py", line 58, in &lt;genexpr&gt; return (r for r in result or () if _filter(r)) File "Emy_PROject/spiders\ocr_spider.py", line 148, in get_PDF yield FormRequest(url='https://api.ocr.space/parse/image', hea…
has comment: http://stackoverflow.com/comment/82752726
downvote count: 0
has comment: http://stackoverflow.com/comment/82751341
favorite count: 0
has comment: http://stackoverflow.com/comment/82751377
linked to: http://stackoverflow.com/q/39303851
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82750412
has title: Translating Requests request to Scrapy request

http://stackoverflow.com/a/47916032
upvote count: 1
has comment: http://stackoverflow.com/comment/82823466
has comment: http://stackoverflow.com/comment/82827291
has comment: http://stackoverflow.com/comment/82827277
downvote count: 0
has comment: http://stackoverflow.com/comment/82823683
has comment: http://stackoverflow.com/comment/82822155
has comment: http://stackoverflow.com/comment/82826958
type: Answer
has body: Convert your dictionaries to a data structure i.e. a real class. For this class, overload the __cmp__ method for each object, if you want to be able to sort them. Overload __eq__ if you want to be able to tell if two objects are equal. class ApiDto(object): def __cmp__ (self, other): pass def __eq__ (self, other): pass class Address(object): def __cmp__ (self, other): pass def __eq__ (self, other): pass class Id(object): def __cmp__ (self, other): pass def __eq__ (self, other): pass Change the dicts to now use the above classes. Now you can sort and compare as you like without having to deal with handling all the attributes at once. In case it's not obvious at this point, the dict you have will now be an ApiDto which has a name field, an addresses field which is a list of Address, an ids field which is a list of Id, and finally a dob field. When you overload __cmp__ and __eq__ methods for ApiDto, you will do the same for all the classes, and this will allow you to sort the objects and finally compare them to each other. Also if you ever need to convert the objects back to a dict, you can call the __dict__ attribute to give you this
answers question: http://stackoverflow.com/q/47914234
score: 1

http://stackoverflow.com/q/47891291
downvote count: 5
type: UnansweredQuestion
score: -4
tagged with: openpyxl
tagged with: python
tagged with: excel
tagged with: combinations
type: Question
has comment: http://stackoverflow.com/comment/82749063
has comment: http://stackoverflow.com/comment/82748995
has comment: http://stackoverflow.com/comment/82749109
upvote count: 1
has body: Need to find all combinations written to an excel sheet. A = ['x', 'y', 'z'] B = ['T', 'F'] C = ['GT', 'LT'] I want combination like follows written to excel sheet x T GT y T GT z T GT x F GT y F GT z F GT x T LT y T LT z T LT x F LT y F LT z F LT
answer count: 1
favorite count: 0
has title: All combination of list elements printed to excel using python
has comment: http://stackoverflow.com/comment/82749132
has answer: http://stackoverflow.com/a/47891538

http://stackoverflow.com/q/47904042
score: 0
has title: How to put many fields of django-tables2 into one?
has comment: http://stackoverflow.com/comment/82782663
tagged with: django-tables2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82781478
has comment: http://stackoverflow.com/comment/83989872
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82809059
answer count: 0
type: Question
has body: I have a django table declared as follow : class BookTable(tables.Table): user= tables.TemplateColumn("""{% include 'books/user.html' with user=record.created_by %}""") books= tables.TemplateColumn( """ {% if record.g_books.count %} &lt;div class="panel-body"&gt; {% include 'books/details/detail.html' with book=record %} &lt;/div&gt; {% else %} No New Books {% endif %} &lt;div&gt; &lt;/div&gt; """) actions = tables.TemplateColumn("""{% include 'books/action.html' with book=record %}""") I want to make changes on the order and some styles of fields and I want to render only one field that groups user, books and actions fields . Is that possible with django-tables2 or it's a bad way to do so ? New with django-tables2 , any advice is welcome Thanks.
has comment: http://stackoverflow.com/comment/82810596
has comment: http://stackoverflow.com/comment/83914310

http://stackoverflow.com/a/47880071
answers question: http://stackoverflow.com/q/47880010
score: 0
has body: If you want to forgo all good practice and not use defaultdict(list), you can use setdefault and call it every single time you choose to add a value. This is inefficient and not idiomatic, but it will work. In [1]: from collections import defaultdict In [2]: a = defaultdict(list) In [3]: b = {} In [4]: a[1].append(1) In [5]: b.setdefault(1, []).append(1) In [6]: a Out[6]: defaultdict(list, {1: [1]}) In [7]: b Out[7]: {1: [1]} In [8]:
type: Answer

http://stackoverflow.com/comment/83179262
type: AnswerComment
score: 0
type: Comment
has text: Sorry about that. I've edited the code in the question.
comment on: http://stackoverflow.com/a/47896769

http://stackoverflow.com/q/47903962
favorite count: 0
type: Question
tagged with: qvariant
accepted answer: http://stackoverflow.com/a/47904079
tagged with: python
has body: Based on the SO example here and the below output: from PyQt4.QtCore import QVariant data = {'key1': 123, 'key2': 456} v = QVariant((data,)) v.toPyObject()[0] &gt;&gt;&gt; {'key2': 456, 'key1': 123}` I try to accomplish this for pyqt5 but with partial success. import sys from PyQt5 import QtCore from PyQt5.QtCore import QVariant data = {'key1': 123, 'key2': 456} v = QtCore.QVariant((data,)) v.value()[0] print v The output is: &lt;PyQt5.QtCore.QVariant object at 0x0000000006778748&gt; and not the expected: {'key1': 123, 'key2': 456} or {'key2': 456, 'key1': 123} As the implementation of QVariant changed toPyObject() was removed and received value() instead in pyqt5. Any help on how to get the value instead of object location?
upvote count: 3
downvote count: 2
tagged with: pyqt5
answer count: 1
has comment: http://stackoverflow.com/comment/82790266
has comment: http://stackoverflow.com/comment/82793167
linked to: http://stackoverflow.com/q/9257422
tagged with: pyqt4
has answer: http://stackoverflow.com/a/47904079
type: AnsweredQuestion
score: 1
has title: PyQt5 - QVariant.value() returns object instead of python value (pyqt4 .toPyObject())

http://stackoverflow.com/q/47930283
has title: How do I get '\\\\host\\printer' out of a string var of '\\host\printer' in python 2.7.5?
type: UnansweredQuestion
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/82829439
has comment: http://stackoverflow.com/comment/82855222
has comment: http://stackoverflow.com/comment/82829481
has comment: http://stackoverflow.com/comment/82848785
has comment: http://stackoverflow.com/comment/82830563
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/82837132
score: -1
tagged with: python-2.7
has answer: http://stackoverflow.com/a/47930908
answer count: 1
has body: How do I get '\\\\host\\printer' out of a string var of '\\host\printer' in python 2.7.5? My program takes in a string argument, "\\host\printer", and I need to convert it to "\\\\host\\printer" in order to submit it as a JSON doc to a web endpoint. Seems simple enough, but python won't let me. Here's what happens: &gt;&gt;&gt; data = '\\host\printer' &gt;&gt;&gt; print data.replace('\\','\\\\') \\host\\printer Now, if this data var was assigned a raw string, it'd work fine: &gt;&gt;&gt; data = r'\\host\printer' &gt;&gt;&gt; print data.replace('\\','\\\\') \\\\host\\printer However, since data is an input argument, I can't make it a raw string. I've tried several tricks found on SO to convert it to a raw string, but no luck with the final result, as shown below. encode() doesn't help: &gt;&gt;&gt; data = '\\host\printer' &gt;&gt;&gt; data = data.encode('string-escape') &gt;&gt;&gt; print data.replace('\\','\\\\') \\\\host\\\\printer nor does repr(): &gt;&gt;&gt; data = '\\host\printer' &gt;&gt;&gt; data = repr(data) &gt;&gt;&gt; print data.replace('\\','\\\\') '\\\\host\\\\printer' nor does re.escape(): &gt;&gt;&gt; import re &gt;&gt;&gt; data = '\\host\printer' &gt;&gt;&gt; data = re.escape(data) &gt;&gt;&gt; print data.replace('\\','\\\\') \\\\host\\\\printer
favorite count: 0

python-2.7
tags question: http://stackoverflow.com/q/47951097
tags question: http://stackoverflow.com/q/47945785
tags question: http://stackoverflow.com/q/47923772
tags question: http://stackoverflow.com/q/47864806
tags question: http://stackoverflow.com/q/47881857
tags question: http://stackoverflow.com/q/47869308
tags question: http://stackoverflow.com/q/47958700
tags question: http://stackoverflow.com/q/47970238
tags question: http://stackoverflow.com/q/47939588
tags question: http://stackoverflow.com/q/47950571
tags question: http://stackoverflow.com/q/47930046
tags question: http://stackoverflow.com/q/47893594
tags question: http://stackoverflow.com/q/47859316
tags question: http://stackoverflow.com/q/48003973
tags question: http://stackoverflow.com/q/47874292
tags question: http://stackoverflow.com/q/47878228
tags question: http://stackoverflow.com/q/47965487
tags question: http://stackoverflow.com/q/47972217
tags question: http://stackoverflow.com/q/47899678
tags question: http://stackoverflow.com/q/47883487
tags question: http://stackoverflow.com/q/47878070
tags question: http://stackoverflow.com/q/47992427
tags question: http://stackoverflow.com/q/47980278
tags question: http://stackoverflow.com/q/47985562
tags question: http://stackoverflow.com/q/47910632
tags question: http://stackoverflow.com/q/47948821
tags question: http://stackoverflow.com/q/47918949
tags question: http://stackoverflow.com/q/47951178
tags question: http://stackoverflow.com/q/47948947
tags question: http://stackoverflow.com/q/48013074
tags question: http://stackoverflow.com/q/47978625
tags question: http://stackoverflow.com/q/47946616
tags question: http://stackoverflow.com/q/47934222
tags question: http://stackoverflow.com/q/47944013
tags question: http://stackoverflow.com/q/47856198
tags question: http://stackoverflow.com/q/47979158
tags question: http://stackoverflow.com/q/47970321
tags question: http://stackoverflow.com/q/47916762
tags question: http://stackoverflow.com/q/47893915
tags question: http://stackoverflow.com/q/47914870
tags question: http://stackoverflow.com/q/47882616
tags question: http://stackoverflow.com/q/47963234
tags question: http://stackoverflow.com/q/47919975
tags question: http://stackoverflow.com/q/47983017
tags question: http://stackoverflow.com/q/47983576
tags question: http://stackoverflow.com/q/48010571
tags question: http://stackoverflow.com/q/48003723
tags question: http://stackoverflow.com/q/47929477
tags question: http://stackoverflow.com/q/48001754
tags question: http://stackoverflow.com/q/47963763
tags question: http://stackoverflow.com/q/48001691
tags question: http://stackoverflow.com/q/47984978
tags question: http://stackoverflow.com/q/47955736
tags question: http://stackoverflow.com/q/47934184
tags question: http://stackoverflow.com/q/47922536
tags question: http://stackoverflow.com/q/47930029
tags question: http://stackoverflow.com/q/47907032
tags question: http://stackoverflow.com/q/47907967
tags question: http://stackoverflow.com/q/48001033
tags question: http://stackoverflow.com/q/47877068
tags question: http://stackoverflow.com/q/47863881
tags question: http://stackoverflow.com/q/47900991
tags question: http://stackoverflow.com/q/47933073
tags question: http://stackoverflow.com/q/48005748
tags question: http://stackoverflow.com/q/47922918
tags question: http://stackoverflow.com/q/47956327
tags question: http://stackoverflow.com/q/47947639
tags question: http://stackoverflow.com/q/47861392
tags question: http://stackoverflow.com/q/47865586
tags question: http://stackoverflow.com/q/47995349
tags question: http://stackoverflow.com/q/47883445
tags question: http://stackoverflow.com/q/47878173
tags question: http://stackoverflow.com/q/47935421
tags question: http://stackoverflow.com/q/47879994
tags question: http://stackoverflow.com/q/47857950
tags question: http://stackoverflow.com/q/47916009
tags question: http://stackoverflow.com/q/48011682
tags question: http://stackoverflow.com/q/47943101
tags question: http://stackoverflow.com/q/47943562
tags question: http://stackoverflow.com/q/47884709

http://stackoverflow.com/comment/82882029
has text: I cannot reproduce this problem. I suspect that you are defining the paths/filenames with literal strings (maybe for testing) and did not escape the backslashes, which would mean that `\6` is not a backslash followed by a 6, but the single character with ASCII code 6.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47956169
score: 1

http://stackoverflow.com/a/48000898
type: Answer
has comment: http://stackoverflow.com/comment/83041375
answers question: http://stackoverflow.com/q/48000610
has body: With descriptive variable names... reduce(lambda xorSoFar, nextIndexAndValue: xorSoFar ^ nextIndexAndValue[0] ^ nextIndexAndValue[1], enumerate(values), 0)
score: 0
accepted answer of: http://stackoverflow.com/q/48000610
upvote count: 1
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/82984974

http://stackoverflow.com/q/47972057
tagged with: arrays
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/82913808
score: 1
has answer: http://stackoverflow.com/a/47972096
favorite count: 0
has title: AttributeError: 'list' object has no attribute 'reshape'
has comment: http://stackoverflow.com/comment/82913774
has comment: http://stackoverflow.com/comment/82913788
has body: I have the following Python script portion: X_to_text_file = np.savetxt('x.txt', X.reshape(np.shape(X)), fmt='%5f') for which I'm getting this error: AttributeError: 'list' object has no attribute 'reshape' Provided that X is a Numpy array, which I obtained as follows: for img in range(len(names)): for name in names: img = np.array(Image.open(name)) X.append(img) Any ideas why I'm getting this error and how I can solve it? Thanks.
upvote count: 3
downvote count: 2
has comment: http://stackoverflow.com/comment/82913773
tagged with: reshape
answer count: 1
has comment: http://stackoverflow.com/comment/82913818
has comment: http://stackoverflow.com/comment/82913759
tagged with: list
type: UnansweredQuestion
tagged with: numpy
has comment: http://stackoverflow.com/comment/82913858
has comment: http://stackoverflow.com/comment/82913842
linked to: http://stackoverflow.com/q/9775297

pandas-datareader
tags question: http://stackoverflow.com/q/47952901
tags question: http://stackoverflow.com/q/47931695
tag name: pandas-datareader
type: Tag

http://stackoverflow.com/q/47967813
tagged with: python
has answer: http://stackoverflow.com/a/47967927
has title: class attributes not being initialized by parent in constructor python
type: AnsweredQuestion
has body: When I call the project_task.fromid() and try to access the project_task.(id/name/type) why does Python tell me that this class doesn't have any of these attributes? class project_task(task): def __init__(self, project_id, name, duration, deadline, done, id = None): if not id: task.__init__(name, 0) else: task.fromid(id) self.project_id = project_id self.duration = duration self.deadline = deadline self.done = done @classmethod def fromid(cls, id): db.cursor.execute('''SELECT * FROM project_task WHERE id=?''', [id]) try: result = db.cursor.fetchone() return cls(result[1], None, result[2], result[3], result[4], id) except: return None class task: def __init__(self, name, type, id = None): self.name = name self.type = type self.id = id @classmethod def fromid(cls, id): db.cursor.execute(''' SELECT * FROM task WHERE id = ? ''', [id]) try: result = db.cursor.fetchone() return cls(result[1], result[2], id) except: return None
type: Question
accepted answer: http://stackoverflow.com/a/47967927
score: 0
tagged with: class-method
answer count: 1
has comment: http://stackoverflow.com/comment/82905123

http://stackoverflow.com/a/47949851
type: Answer
has comment: http://stackoverflow.com/comment/82869481
has body: In your models.py address1 = models.CharField( max_length=38, blank=False, null=False, ) address2 = models.CharField( max_length=38, blank=True, null=True, ) city = models.CharField( max_length=15, blank=False, null=False, ) state = models.CharField( max_length=2, blank=False, null=False, ) zip5 = models.CharField( max_length=5, blank=False, null=False, ) zip4 = models.CharField( max_length=4, blank=True, null=True, I think it should be lowercase. forms.py has all lowercase like address1, address2, city, state, zip5 and zip4.
accepted answer of: http://stackoverflow.com/q/47949757
has comment: http://stackoverflow.com/comment/82869580
answers question: http://stackoverflow.com/q/47949757
score: 2
type: AcceptedAnswer
downvote count: 0
upvote count: 2

http://stackoverflow.com/a/51077098
downvote count: 0
has body: TZInfo objects can be created in the CPython API from version 3.7 using PyTimeZone_FromOffsetAndName and PyTimeZone_FromOffset
score: 1
has comment: http://stackoverflow.com/comment/89154573
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47904296

http://stackoverflow.com/comment/82935440
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47983212
has text: Please provide more detail, what you've tried so far, where you are having trouble, and what your desired output is. But first read this: [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask)
score: 0

http://stackoverflow.com/comment/82900762
has text: @jonrsharpe A single expression can run several statements: https://ideone.com/w6nIS3 :-P
type: QuestionComment
comment on: http://stackoverflow.com/q/47964796
type: Comment
score: 0

http://stackoverflow.com/a/47961510
downvote count: 0
has comment: http://stackoverflow.com/comment/82892396
score: 1
answers question: http://stackoverflow.com/q/47961437
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/82892281
has body: You're using logging.exception, which delegates to the root logger, instead of using logger.exception, which would use yours (and write to error.log).

http://stackoverflow.com/comment/82756007
comment on: http://stackoverflow.com/q/47893594
score: 0
type: Comment
type: QuestionComment
has text: @user2357112 thanks for that link it appears that python essentially cannot support this design properly, which is a pity because it would be the proper way to design the solution. I guess the only clean way to deal with this is to move the factory method to its own module.

http://stackoverflow.com/q/47941991
tagged with: python
tagged with: css
linked to: http://stackoverflow.com/q/23215581
type: AnsweredQuestion
score: 3
downvote count: 0
possible better answer: http://stackoverflow.com/a/47942082
type: Question
has answer: http://stackoverflow.com/a/47942082
has answer: http://stackoverflow.com/a/47942431
accepted answer: http://stackoverflow.com/a/47942431
has comment: http://stackoverflow.com/comment/82855388
upvote count: 3
answer count: 3
tagged with: django-staticfiles
favorite count: 0
has answer: http://stackoverflow.com/a/65742971
has body: I'm pretty new to Django. I started an app, made template and static directories, add them to the project settings and ran the server by following this tutorial. Then I wanted to change some settings in my CSS file so I modified some lines. But when I ran the python manage.py runserver again(I ran on Windows), the changes did not take effect. The initial code of CSS is: body { position: relative; padding-bottom: 10px; min-height: 100%; background: #f7f7f7; } I changed the padding resulting like this: body { position: relative; padding-bottom: 50px; min-height: 100%; background: #f7f7f7; } When I ran the django server again, the new code was not taking effect. I checked the code with Chrome Dev Tools and found out the padding value was still 10px. I've been running the server again and again but with no change. Is there something I am missing with the settings?
has title: Django server not making changes to CSS
has comment: http://stackoverflow.com/comment/82853453
tagged with: django

http://stackoverflow.com/a/47867195
answers question: http://stackoverflow.com/q/47867145
has body: list(x) is not in place. It converts x to a new list and returns a reference to it, so it should be assigned back to x (or to anything else): x = list(x) Compare x = set() list(x) print(x) # set() to x = set() x = list(x) print(x) # []
upvote count: 7
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82737433
type: Answer
downvote count: 0
score: 7
accepted answer of: http://stackoverflow.com/q/47867145

http://stackoverflow.com/a/48003404
downvote count: 0
has comment: http://stackoverflow.com/comment/82974958
type: Answer
score: 3
has comment: http://stackoverflow.com/comment/82995472
accepted answer of: http://stackoverflow.com/q/48003270
upvote count: 3
has comment: http://stackoverflow.com/comment/82975032
has body: You need to parse the JSON object. add json.loads() as: import requests import json print json.loads(requests.get('https://rbx.rocks/apis/item?id=1285307').json())['stats']
answers question: http://stackoverflow.com/q/48003270
type: AcceptedAnswer

http://stackoverflow.com/comment/120904846
type: Comment
score: 1
has text: what would happen if there is no match? how would you handle that?
comment on: http://stackoverflow.com/a/47867513
type: AnswerComment

http://stackoverflow.com/a/47863123
has comment: http://stackoverflow.com/comment/82692916
has comment: http://stackoverflow.com/comment/82692884
has body: You can use: #convert to numeric, NaNs for non numeric df1 = df.apply(pd.to_numeric, errors='coerce') #count consecutive values with reset a = df1 == 0 b = a.cumsum(axis=1) c = b-b.where(~a, axis=1).ffill(axis=1).fillna(0).astype(int) print (c) 2017-04-03 2017-04-04 2017-04-05 2017-04-06 id 0 1 0 1 2 1 1 0 1 0 2 1 2 3 4 #replace by mask df = df.mask(c != 0, 'inactive_' + c.astype(str)) print (df) 2017-04-03 2017-04-04 2017-04-05 2017-04-06 id 0 inactive_1 active inactive_1 inactive_2 1 inactive_1 active inactive_1 active 2 inactive_1 inactive_2 inactive_3 inactive_4 Timings: np.random.seed(425) df = pd.DataFrame(np.random.choice([0, 'active'], size=(100000, 300))) In [4]: %timeit (jez(df)) 1 loop, best of 3: 1min 40s per loop In [5]: %timeit col(df) 1 loop, best of 3: 5min 54s per loop def jez(df): df1 = df.apply(pd.to_numeric, errors='coerce') #count consecutive values a = df1 == 0 b = a.cumsum(axis=1) c = b-b.where(~a, axis=1).ffill(axis=1).fillna(0).astype(int) #replace by mask return df.mask(c != 0, 'inactive_' + c.astype(str)) def f(x): return x.groupby(x.ne(x.shift()).cumsum()).cumcount() + 1 def col(df): i = df.apply(pd.to_numeric, errors='coerce') j = 'inactive_' + i.apply(f, axis=1).astype(str) df[:] = np.where(i.ne(0), df.values, j) return(df) Caveat: Performance really depend on the data.
score: 1
has comment: http://stackoverflow.com/comment/82692853
downvote count: 0
has comment: http://stackoverflow.com/comment/82693417
has comment: http://stackoverflow.com/comment/82693342
answers question: http://stackoverflow.com/q/47862796
has comment: http://stackoverflow.com/comment/82693461
upvote count: 1
type: Answer

pycharm
tags question: http://stackoverflow.com/q/47911183
tags question: http://stackoverflow.com/q/47862363
tags question: http://stackoverflow.com/q/47946187
tags question: http://stackoverflow.com/q/47966943
tags question: http://stackoverflow.com/q/47928724
tags question: http://stackoverflow.com/q/47900611
tag name: pycharm
tags question: http://stackoverflow.com/q/47964128
tags question: http://stackoverflow.com/q/47976339
tags question: http://stackoverflow.com/q/47953245
tags question: http://stackoverflow.com/q/47945766
tags question: http://stackoverflow.com/q/47996058
tags question: http://stackoverflow.com/q/47988810
tags question: http://stackoverflow.com/q/47961041
tags question: http://stackoverflow.com/q/47901163
tags question: http://stackoverflow.com/q/47936144
tags question: http://stackoverflow.com/q/47960795
tags question: http://stackoverflow.com/q/47984045
tags question: http://stackoverflow.com/q/47969091
tags question: http://stackoverflow.com/q/47995958
tags question: http://stackoverflow.com/q/47878919
tags question: http://stackoverflow.com/q/47897462
tags question: http://stackoverflow.com/q/47988936
type: Tag
tags question: http://stackoverflow.com/q/47897070
tags question: http://stackoverflow.com/q/48005301
tags question: http://stackoverflow.com/q/47877726
tags question: http://stackoverflow.com/q/48009814
tags question: http://stackoverflow.com/q/47978893

http://stackoverflow.com/comment/82802742
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47917234
score: 0
has text: `while 0 == 0:` What's wrong with `while True:`?

http://stackoverflow.com/a/47910255
answers question: http://stackoverflow.com/q/47908429
has body: The scatter plot is a PathCollection, which subclasses ScalarMappable. A ScalarMappable has a method to_rgba. This can be used to get the color corresponding to the colorvalues. In this case sc.to_rgba(c[idx]) Note that the arrays used in the question are 2D arrays, which is normally undesired. So a complete example would look like import matplotlib.pyplot as plt import numpy as np x = 100*np.random.rand(5) y = 100*np.random.rand(5) c = np.random.rand(5) fig, ax = plt.subplots() sc = plt.scatter(x, y, c=c, cmap='viridis') # I want to annotate the third point (idx=2) idx = 2 ax.annotate("hello", xy=(x[idx],y[idx]), color=sc.to_rgba(c[idx]), xytext=(5,5), textcoords="offset points") plt.show()
type: AcceptedAnswer
downvote count: 1
upvote count: 12
type: Answer
accepted answer of: http://stackoverflow.com/q/47908429
score: 11

http://stackoverflow.com/q/47948762
tagged with: timeit
has comment: http://stackoverflow.com/comment/82867541
has comment: http://stackoverflow.com/comment/82867613
score: 2
type: AnsweredQuestion
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/47948789
has title: infinite loop, unknown reason
tagged with: python-3.6
answer count: 1
has comment: http://stackoverflow.com/comment/82867609
favorite count: 0
has body: For some reason this code seems to enter an infinite loop and I have no clue why import timeit t = timeit.Timer(stmt="for num in num_list: print(num)", setup="num_list = [digit for digit in range(1, 101)]") print(t.timeit()) I have python version 3.6.2 installed via Anaconda. I've tried running it in the Spyder IDE and in command prompt, both have the same results. If I change the setup to be generator instead of list comprehension everything works fine, the same can be said about running identical code out of timeit. I've even tried restarting my computer because ya know, I have to try turning it off and on again, it works for most things.
upvote count: 2
accepted answer: http://stackoverflow.com/a/47948789
tagged with: python

http://stackoverflow.com/comment/84614240
has text: @Phoenix probably you would want to train a classifier on the Location predicting 3 classes 'source', 'destination' and 'other'. There are multiple ways to define such a classifier, one popular approach would be with recurrent neural networks and attention. Also an extension is dynamic memory networks for questions answering. Have a look at: https://www.youtube.com/watch?v=T3octNTE7Is
comment on: http://stackoverflow.com/q/48003074
score: 0
type: Comment
type: QuestionComment

file
tags question: http://stackoverflow.com/q/47938945
type: Tag
tags question: http://stackoverflow.com/q/47936155
tags question: http://stackoverflow.com/q/47992385
tags question: http://stackoverflow.com/q/47923755
tags question: http://stackoverflow.com/q/47954216
tags question: http://stackoverflow.com/q/47912051
tag name: file
tags question: http://stackoverflow.com/q/47981828
tags question: http://stackoverflow.com/q/47936547
tags question: http://stackoverflow.com/q/47869368
tags question: http://stackoverflow.com/q/47947472
tags question: http://stackoverflow.com/q/47858219
tags question: http://stackoverflow.com/q/47884034
tags question: http://stackoverflow.com/q/47977255
tags question: http://stackoverflow.com/q/47937366
tags question: http://stackoverflow.com/q/47961922
tags question: http://stackoverflow.com/q/47881611
tags question: http://stackoverflow.com/q/47995991

http://stackoverflow.com/q/47879356
answer count: 2
has body: According to http://www.tkdocs.com/tutorial/text.html#more, in Tk/Tcl it is possible to embed "elided" text in a Text widget, text that is not displayed. This sounds useful. Is this functionality available in Python? If so, what is the API?
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/47881713
tagged with: python
linked to: http://stackoverflow.com/q/43416330
type: AnsweredQuestion
has title: Elided or "Hidden" Text in a Python Tkinter Text Widget
tagged with: tkinter
possible better answer: http://stackoverflow.com/a/47880181
has comment: http://stackoverflow.com/comment/82725182
has answer: http://stackoverflow.com/a/47880181
tagged with: tk-toolkit
upvote count: 1
accepted answer: http://stackoverflow.com/a/47881713
type: Question
score: 1
has comment: http://stackoverflow.com/comment/82726182

http://stackoverflow.com/q/47951758
tagged with: python-3.x
downvote count: 0
has comment: http://stackoverflow.com/comment/82872991
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82873049
has comment: http://stackoverflow.com/comment/82873265
tagged with: python
has comment: http://stackoverflow.com/comment/82876372
score: 1
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47953877
has body: I have a sequence definition xn+1 = f(xn , xn-1) Where xn is x evaluated at time tn. Any value in the sequence is defined by some function of the previous two values (and the time step, but for now that's constant). I would like to generate the first N values in this sequence, given x0 & x1. What's the most pythonic way to do this? My current approach is just to loop. I create a numpy.ones array of the correct size, then loop through it by index. If index = 0 or 1 then I change the value from 1 to x0 / x1 respectively. For greater indices I lookup the previous values in the array and apply the function. But I feel like this doesn't seem to be making use of the numpy array methods, so I wonder if there's a better approach? Code In my code I have a createSequence function, which takes in a definition of xn+1 as well as boundary conditions and timestep, and outputs a sequence following those rules. NB, I'm very new to Python so any general advice would also be appreciated! import numpy as np def x_next(x_current,x_previous,dt): """Function to return the next value in the sequence x_current and x_previous are the values at tn and tn-1 respectively dt is the time step """ return (x_current - x_previous)/dt #as an example def createSequence(x_next,x0,x1,start,stop,dt): """ Function to create sequence based on x_next function, and boundary conditions""" num = (stop-start)/dt x_array = np.ones(int(num)) x_array[0] = x0 x_array[1] = x1 for index in range(len(x_array)): if index == 0: x_array[index] = x0 elif index == 1: x_array[index] = x1 else: x_current = x_array[index - 1] x_previous = x_array[index - 2] x_array[index] = x_next(x_current,x_previous,dt) return x_array print(createSequence(x_next=x_next,x0=0.1,x1=0.2,start=0,stop=20,dt=0.1))
answer count: 2
has comment: http://stackoverflow.com/comment/82873398
tagged with: arrays
has comment: http://stackoverflow.com/comment/82872860
favorite count: 0
has title: Pythonic way to generate sequence from linear difference
has comment: http://stackoverflow.com/comment/82873146
has answer: http://stackoverflow.com/a/47951901
upvote count: 1
tagged with: sequence

http://stackoverflow.com/a/47946357
downvote count: 0
type: Answer
upvote count: 3
has body: Adding values and using at df1.at[:len(df2),'d']=df2.c.values df1 Out[1200]: a b d 1900-01-01 1 2 3.0 1900-01-02 1 3 1.0 1900-01-03 3 3 NaN
score: 3
answers question: http://stackoverflow.com/q/47946251

http://stackoverflow.com/q/47870264
downvote count: 0
has answer: http://stackoverflow.com/a/50827583
has comment: http://stackoverflow.com/comment/82706010
favorite count: 0
linked to: http://stackoverflow.com/q/39868762
answer count: 1
tagged with: python
type: UnansweredQuestion
tagged with: integer-programming
upvote count: 1
tagged with: julia
score: 1
has comment: http://stackoverflow.com/comment/82706723
has comment: http://stackoverflow.com/comment/82706447
has title: Solving integer programs in Python with PuLP
has body: I am working on a Python package for computing several NP-Hard graph invariants. The current version of the package uses brute force for nearly all of the algorithms, but I am very interested in using integer programming to help speed up the computations for larger graphs. For example, a simple integer program for solving the independence number of an n-vertex graph is to maximize given the constraints , where . How do I solve this using PuLP? Is PuLP my best option, or would it be beneficial to use solvers in another language, like Julia, and interface may package with those?
type: Question

http://stackoverflow.com/comment/82967996
type: AnswerComment
has text: Pandas reads CSVs directly, this answer doesn't require the `csv` module.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47998569

automated-refactoring
tags question: http://stackoverflow.com/q/47978893
type: Tag
tag name: automated-refactoring

http://stackoverflow.com/q/47876712
has comment: http://stackoverflow.com/comment/82719361
upvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82719240
linked to: http://stackoverflow.com/q/37928815
tagged with: python
has comment: http://stackoverflow.com/comment/82720097
has comment: http://stackoverflow.com/comment/82719354
linked to: http://stackoverflow.com/q/30380678
has body: I have two timestamp strings. I want to find the difference between them in seconds. I've tried: from time import gmtime, strptime a = "Mon 11 Dec 2017 13:54:36 -0700" b = "Mon 11 Dec 2017 13:54:36 -0000" time1 = strptime(a, "%a %d %b %Y %H:%M:%S %z") time2 = strptime(b, "%a %d %b %Y %H:%M:%S %z") time1-time2 Getting an error: TypeError: unsupported operand type(s) for -: 'time.struct_time' and 'time.struct_time' So, how do I calculate the difference using package time? I was successful using package datetime - in the code below, but I think I read that datetime ignores seconds in leap years, or something to that effect. Thus, I am trying to use 'time': from datetime import datetime time1 = datetime.strptime(a, "%a %d %b %Y %H:%M:%S %z") time2 = datetime.strptime(b, "%a %d %b %Y %H:%M:%S %z") dif = time1 - time2 print(int(dif.total_seconds())) Thank you very much!
tagged with: time
type: UnansweredQuestion
downvote count: 1
has title: Python 3 time: difference in seconds between two timestamps
tagged with: timestamp
type: Question
score: -1
has comment: http://stackoverflow.com/comment/82719699
has comment: http://stackoverflow.com/comment/82719567
has answer: http://stackoverflow.com/a/47876882

http://stackoverflow.com/comment/82914758
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47972525
type: Comment
has text: what is your Pandas version? `df > 'A'` works just fine for me (Pandas 0.21.1)

http://stackoverflow.com/q/47963234
answer count: 2
tagged with: ocr
has title: Captcha Break or Text reader from Image: OCR-Python
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I have a typical captcha image which contain only digits. Ex. i want to extract 78614 from this image. I tried few library &amp; code using OCR-Python. But its returning 0. Sample Code-1 from captcha_solver import CaptchaSolver solver = CaptchaSolver('browser') with open('captcha.png', 'rb') as inp: raw_data = inp.read() print(solver.solve_captcha(raw_data)) Sample Code-2 from PIL import Image def p(img, letter): A = img.load() B = letter.load() mx = 1000000 max_x = 0 x = 0 for x in range(img.size[0] - letter.size[0]): _sum = 0 for i in range(letter.size[0]): for j in range(letter.size[1]): _sum = _sum + abs(A[x+i, j][0] - B[i, j][0]) if _sum &lt; mx : mx = _sum max_x = x return mx, max_x def ocr(im, threshold=200, alphabet="0123456789abcdef"): img = Image.open(im) img = img.convert("RGB") box = (8, 8, 58, 18) img = img.crop(box) pixdata = img.load() letters = Image.open(im) ledata = letters.load() # Clean the background noise, if color != white, then set to black. for y in range(img.size[1]): for x in range(img.size[0]): if (pixdata[x, y][0] &gt; threshold) \ and (pixdata[x, y][1] &gt; threshold) \ and (pixdata[x, y][2] &gt; threshold): pixdata[x, y] = (255, 255, 255, 255) else: pixdata[x, y] = (0, 0, 0, 255) counter = 0; old_x = -1; letterlist = [] for x in range(letters.size[0]): black = True for y in range(letters.size[1]): if ledata[x, y][0] &lt;&gt; 0 : black = False break if black : if True : box = (old_x + 1, 0, x, 10) letter = letters.crop(box) t = p(img, letter); print counter, x, t letterlist.append((t[0], alphabet[counter], t[1])) old_x = x counter += 1 box = (old_x + 1, 0, 140, 10) letter = letters.crop(box) t = p(img, letter) letterlist.append((t[0], alphabet[counter], t[1])) t = sorted(letterlist) t = t[0:5] # 5-letter captcha final = sorted(t, key=lambda e: e[2]) answer = "" for l in final: answer = answer + l[1] return answer print(ocr('captcha.png')) Has anyone had the opportunity to get/extract text from such typical captcha?
has answer: http://stackoverflow.com/a/47963794
has answer: http://stackoverflow.com/a/76564500
upvote count: 2
score: 1
downvote count: 1
type: Question
tagged with: opencv
tagged with: captcha
tagged with: python-2.7

http://stackoverflow.com/comment/82895395
type: Comment
type: QuestionComment
has text: @jonrsharpe i did the trial.name change . Still False.
comment on: http://stackoverflow.com/q/47963008
score: 0

http://stackoverflow.com/q/47857982
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
linked to: http://stackoverflow.com/q/17098654
has answer: http://stackoverflow.com/a/52369556
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/47858808
has body: I am trying to save a pandas dataframe as .csv file. Currently my code looks like this: with open('File.csv', 'a') as f: df.to_csv(f, header=False) The saving works but the problem is that the lists in my dataframe are just compressed to [first,second,...,last] and all the entries in the middle are discarded. If I just look at the original dataframe all entries are there. Is there any way how I can convert the list to a string which contains all the elements (str(df) also discards the middle elements) or how I can save a full numpy array in a cell of a csv table? Thank you for your help, Viviane
type: AnsweredQuestion
has title: Save Pandas df containing long list as csv file
has answer: http://stackoverflow.com/a/71302958
has comment: http://stackoverflow.com/comment/82680492
score: 10
has comment: http://stackoverflow.com/comment/82682116
possible better answer: http://stackoverflow.com/a/52369556
upvote count: 10
has comment: http://stackoverflow.com/comment/82681910
type: Question
accepted answer: http://stackoverflow.com/a/47858104
has comment: http://stackoverflow.com/comment/82682558
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/47858104

django-rest-framework
tags question: http://stackoverflow.com/q/47856476
tags question: http://stackoverflow.com/q/47961651
tags question: http://stackoverflow.com/q/47940530
tags question: http://stackoverflow.com/q/47884601
tags question: http://stackoverflow.com/q/47986739
tags question: http://stackoverflow.com/q/47874008
tags question: http://stackoverflow.com/q/47974094
tags question: http://stackoverflow.com/q/47976274
tags question: http://stackoverflow.com/q/47867746
tags question: http://stackoverflow.com/q/47878367
tags question: http://stackoverflow.com/q/47902913
tags question: http://stackoverflow.com/q/47971506
type: Tag
tags question: http://stackoverflow.com/q/47937256
tags question: http://stackoverflow.com/q/47964694
tags question: http://stackoverflow.com/q/47903042
tags question: http://stackoverflow.com/q/47898868
tags question: http://stackoverflow.com/q/47858295
tags question: http://stackoverflow.com/q/47974935
tags question: http://stackoverflow.com/q/47890695
tags question: http://stackoverflow.com/q/47929991
tags question: http://stackoverflow.com/q/47948051
tags question: http://stackoverflow.com/q/47973701
tags question: http://stackoverflow.com/q/47885340
tags question: http://stackoverflow.com/q/47895678
tags question: http://stackoverflow.com/q/47988239
tags question: http://stackoverflow.com/q/47935318
tags question: http://stackoverflow.com/q/48007965
tags question: http://stackoverflow.com/q/47938729
tags question: http://stackoverflow.com/q/47998392
tags question: http://stackoverflow.com/q/47913326
tags question: http://stackoverflow.com/q/47880666
tags question: http://stackoverflow.com/q/47986522
tags question: http://stackoverflow.com/q/48012329
tags question: http://stackoverflow.com/q/47985717
tags question: http://stackoverflow.com/q/47898731
tag name: django-rest-framework
tags question: http://stackoverflow.com/q/47936083
tags question: http://stackoverflow.com/q/47945978
tags question: http://stackoverflow.com/q/47885274
tags question: http://stackoverflow.com/q/48001418
tags question: http://stackoverflow.com/q/48014173
tags question: http://stackoverflow.com/q/48009349
tags question: http://stackoverflow.com/q/47999097
tags question: http://stackoverflow.com/q/47874233
tags question: http://stackoverflow.com/q/47868653
tags question: http://stackoverflow.com/q/47986088
tags question: http://stackoverflow.com/q/47873707
tags question: http://stackoverflow.com/q/47967084
tags question: http://stackoverflow.com/q/47958607

http://stackoverflow.com/comment/82721150
type: Comment
comment on: http://stackoverflow.com/a/47877085
score: 0
type: AnswerComment
has text: this is what I did: `df.set_index(['date','customer','product','type']).amt.unstack(-4).\ reindex(columns=pd.date_range(df['date'].min(), df['date'].max()),fill_value=0).\ stack(dropna=False).unstack().stack(dropna=False).\ unstack('customer').stack(dropna=False).reset_index().\ unstack('product').stack(dropna=False).reset_index().\ fillna(0).sort_values(['level_1','customer','product','type'])` but I got a stacking error. Is there anything else I need to add?

http://stackoverflow.com/a/47981376
has body: I wonder if this is a good idea (using regular expressions, that is) but here you go: \[szur[^][]*\].*?&lt;\w+&gt; Use the DOTALL modifier and see a demo on regex101.com. In Python: import re string = """[szur formatter] line 1&lt;?xml version="1.0"?&gt;&lt;star&gt;[szur parser] line 2&lt;?xml version="1.0"?&gt;&lt;Planet&gt;""" rx = re.compile(r'(\[szur[^][]*\].*?&lt;\w+&gt;)') matches = rx.findall(string) # matches = rx.findall(string, re.DOTALL) print(matches)
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47980835

http://stackoverflow.com/comment/82726595
score: 1
comment on: http://stackoverflow.com/a/47871704
type: AnswerComment
type: Comment
has text: Thanks for the solution !

http://stackoverflow.com/comment/82997081
comment on: http://stackoverflow.com/q/48014080
has text: The first thing to mention is that there is no point using LIKE without a wildcard, just use equals. Or add a wildcard(s) as appropriate.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82752869
score: 0
type: AnswerComment
has text: Are you sure `\de[+-]?\d` isn't enough to verify a valid exponential? You don't really care about catching **all** of it, just skip the `e`.
type: Comment
comment on: http://stackoverflow.com/a/47892778

http://stackoverflow.com/q/47919309
has comment: http://stackoverflow.com/comment/82829415
has title: How can I initialize variables with Bernoulli distribution in TensorFlow?
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47926241
favorite count: 0
type: UnansweredQuestion
has body: How can I initialize variables in TensorFlow? I want to associate each weight with a Bernoulli distribution: with probability of p to get some value x1, and with probability of 1-p to get some value x2. How should I initialize this matrix? I wrote this code: logits_y = tf.get_variable("logits", [n_input*n_hidden,2], initializer=tf.constant_initializer(1.)) The 2 in [n_input*n_hidden, 2] means [p, 1-p].
tagged with: python
has comment: http://stackoverflow.com/comment/82813337
score: 1
tagged with: probability
upvote count: 1
tagged with: tensorflow
type: Question
tagged with: bernoulli-probability

http://stackoverflow.com/comment/82923400
type: Comment
comment on: http://stackoverflow.com/a/47976802
type: AnswerComment
has text: make your input tensor to `x = tf.placeholder(tf.float32, (272, 272))` and use PIL to read image in gray scale `gray_image = Image.open('image.png').convert('LA')` and then feed the tensor `x` the `gray_image` your input neurons depends on the shape of tensor `x`
score: 0

http://stackoverflow.com/comment/83891983
score: 0
type: Comment
has text: I'm having the same problem any fixes yet?
type: AnswerComment
comment on: http://stackoverflow.com/a/48154139

http://stackoverflow.com/q/47995054
type: Question
accepted answer: http://stackoverflow.com/a/47995155
has body: I've been making a scorekeeper and i can't figure out how to assign the amount of player's variables to 0. For example, if there are 3 players, then i need to assign 3 different variables the value of 0. Is this possible? If so, how? If not, how else could i do this? while True: try: numPlayers = int(input("How many people are playing?")) if numPlayers == 0 or numPlayers == 1 or numPlayers &gt; 23: print("You cannot play with less than 2 people or more than 23 people.") else: break except ValueError: print("Please enter an integer value.") for numTimes in range(0, numPlayers): #what should i do?
tagged with: variables
score: -1
has comment: http://stackoverflow.com/comment/82958245
upvote count: 0
answer count: 1
tagged with: variable-assignment
favorite count: 0
has title: Python scorekeeping
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47995155
tagged with: python
has comment: http://stackoverflow.com/comment/82992372
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82958221
downvote count: 1

http://stackoverflow.com/q/48000993
favorite count: 0
tagged with: python
tagged with: regex
has title: Which regular expression algorithm does Python use?
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/48001051
type: Question
tagged with: algorithm
has comment: http://stackoverflow.com/comment/83006158
score: -1
downvote count: 4
has body: I wonder which regular expression algorithm does Python's re module use~
linked to: http://stackoverflow.com/q/12022443
answer count: 1
accepted answer: http://stackoverflow.com/a/48001051
has comment: http://stackoverflow.com/comment/82970511

http://stackoverflow.com/comment/82688492
score: 0
comment on: http://stackoverflow.com/q/47861749
type: QuestionComment
has text: Please refer to the answer to ["How to read numbers from file in Python?"](https://stackoverflow.com/questions/6583573/how-to-read-numbers-from-file-in-python)
type: Comment

http://stackoverflow.com/comment/82940808
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47985922
type: Comment
has text: Thanks for the help. Please see my edit above for `new_df`. I think my first try at this question was somewhat confusing

http://stackoverflow.com/comment/83989868
score: 0
type: Comment
has text: Yes, it is possible with modbus_tk.modbus.Slave.get_values
comment on: http://stackoverflow.com/a/48457449
type: AnswerComment

clr
type: Tag
tag name: clr
tags question: http://stackoverflow.com/q/47913079

http://stackoverflow.com/comment/82897841
has text: Can you clarify what you mean by not seeing the random number? In the Python prompt, on Python 2.7, doing `random.random()` just prints out a random number [0.0, 1.0).
score: 0
comment on: http://stackoverflow.com/q/47964128
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47902528
has title: Finding the line number of the element's ending tag in lxml
upvote count: 5
has body: While parsing an XML document with lxml I want to find the starting and ending line numbers of a particular tag. I am able to find the starting tag's position by using the sourceline property on lxml.etree.Element, however I am struggling at finding the closing tag's line number. A trivial example of my attempt: import lxml.etree as ET xml_sample = b'''<?xml version="1.0" encoding="utf-8"?> foo bar ''' for el in ET.fromstring(xml_sample).getroottree().findall('//value'): print('Found value "{el.text}" starting on line {el.sourceline} ' 'and ending on line ???.'.format(el=el)) Is it possible to get the closing tag line numbers of the value elements in the above example?
tagged with: python
type: AnsweredQuestion
type: Question
score: 5
downvote count: 0
accepted answer: http://stackoverflow.com/a/47903639
tagged with: lxml
answer count: 1
has answer: http://stackoverflow.com/a/47903639
favorite count: 0

http://stackoverflow.com/comment/82751302
type: QuestionComment
has text: I tried your suggestion , but it gives: File scrapy\http\request\form.py", line 65, in <listcomp> values = [(to_bytes(k, enc), to_bytes(v, enc)) ValueError: not enough values to unpack (expected 2, got 1). Also according to the Formrequest docs you can pass a dic as formdata.
comment on: http://stackoverflow.com/q/47891056
score: 0
type: Comment

http://stackoverflow.com/q/47945670
tagged with: python
score: 4
answer count: 0
has title: How to leverage CNN for Portrait Image Segmentation in Python?
tagged with: tensorflow
type: Question
has body: I will be needing a step-by-step process for Image Segmentation or If you can break down the problem into comprehensible and programmatically implementable modules that would also be a great help. Below Image is a snapshot of what needs to be done. Here are some research papers that can help understand results I want. Automatic Portrait Segmentation for Image Stylization Automatically Remove Backgrounds From Images New Deep Learning Method Enhances Your Selfies I have trained a tensor-flow model for custom object detection (apart from the 90 classes pre-trained COCO dataset model) but the problem is: TensorFlow does return the co-ordinates (bounding box) of the detected object, but we need the contour (outline) of the object. ^Considering that I know how to train CNN models with tensorflow, can you educate me how can I replicate the above research papers programatically? Like I know they collected a dataset of 1800 images and then transmuted that into 19000 images by augmentation but HOW can I prepare a dataset for training? what tool can I use to annotate images? Please help me implement the above research papers. All I want is to extract a person from a photo - Portrait segmentation. Thanks a lot!
upvote count: 4
tagged with: image-segmentation
downvote count: 0
tagged with: cudnn
favorite count: 0
type: UnansweredQuestion
tagged with: convolution

http://stackoverflow.com/a/47977860
answers question: http://stackoverflow.com/q/47977615
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47977615
has body: Apart from wrong indentation, in conditional statements you need to replace assignment operators with comparison operators. Also, a : is missing from an if statement. def register(): print("Register") login = input("Enter login") passwd = input("Enter password") passwdacc = input("Accept password") if passwdacc == passwd: print("You have registered, now please sign up") else: print("Try again, passwords don't match") login2 = input("Enter login") password = input("Enter password") if password == passwd and login2 == login: print("Accepted") else: print("Try again")

http://stackoverflow.com/q/47898620
type: AnsweredQuestion
tagged with: scipy
accepted answer: http://stackoverflow.com/a/47899518
tagged with: tensorflow
type: Question
tagged with: minimize
score: 0
has body: I am using tf scipy interface, to use scipy minimize over a custom function that I define in tensorflow. I need to debug it and I want to use a callback function to print some info. However, the callback function is called only once, despite the number of iterations / function evaluations / gradient evaluations are more than one. Why? I am getting the same problem using just scipy (without tensorflow). Here is a MWE with the Rosenbrock function (it should say that the minimizer does 23 iterations, 53 function evaluation, 23 gradient evaluations, but CALLBACK! is printed only twice, once for step_callback and once for loss_callback). import tensorflow as tf import numpy as np class Solver: def __init__(self, session, y, x): self.session = session self.y = y self.x = x self.optimizer = tf.contrib.opt.ScipyOptimizerInterface(self.y, options={'maxiter': 100, 'disp': True}, method='SLSQP', var_list=[self.x], var_to_bounds={self.x: (1e-8, np.infty)}) def optimize(self): self.optimizer.minimize(self.session, step_callback=self.callback(), loss_callback=self.callback()) def callback(self): print('CALLBACK!') def main(): seed = 0 np.random.seed(seed) tf.set_random_seed(seed) session = tf.Session() x_size = 10 x = tf.Variable(np.random.rand(x_size), dtype=tf.float32) y = 0. for i in range(x_size-1): y += 100. * (x[i+1] - x[i]*x[i])**2 + (x[i] - 1)**2 solver = Solver(session, y, x) session.run(tf.global_variables_initializer()) solver.optimize() if __name__ == '__main__': main()
answer count: 1
tagged with: callback
has comment: http://stackoverflow.com/comment/82765356
has answer: http://stackoverflow.com/a/47899518
tagged with: python
has title: Scipy callback is called only once
has comment: http://stackoverflow.com/comment/82765467

http://stackoverflow.com/comment/82807078
score: 0
type: AnswerComment
has text: i'm getting an "AttributeError: 'DatetimeProperties' object has no attribute 'round'"
type: Comment
comment on: http://stackoverflow.com/a/47919506

http://stackoverflow.com/comment/82721702
type: Comment
has text: but for the arguments in shp = python1.shape(w,x,y,z) I had to use self.w,self.x,self.y,self.z and it gives me an error : self not defined
comment on: http://stackoverflow.com/a/47877695
type: AnswerComment
score: 0

http://stackoverflow.com/q/48004925
tagged with: python
has title: How to get the old value stored in database in an uncommitted SQLAlchemy Session?
has comment: http://stackoverflow.com/comment/82993940
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82994093
linked to: http://stackoverflow.com/q/3645802
has body: Query a user from database: user1 = db.session.query(User).filter_by(id=1).first() Update the user1, such as: user1.username = 'a' Query the user again: user2 = db.session.query(User).filter_by(id=1).first() Now user2.username equals user1.username, the new value. So after step 2 how can I get the old username stored in database?
has comment: http://stackoverflow.com/comment/82982505
has comment: http://stackoverflow.com/comment/82982983
has comment: http://stackoverflow.com/comment/82983612
has comment: http://stackoverflow.com/comment/82994294
tagged with: sqlalchemy
type: Question
score: 0

drf-queryset
type: Tag
tag name: drf-queryset
tags question: http://stackoverflow.com/q/47935318

http://stackoverflow.com/comment/82758900
comment on: http://stackoverflow.com/a/47895864
type: Comment
score: 1
has text: That's right, I am just suggesting you to be explicit in your answer, for those unaware of this, as might be the OP case.
type: AnswerComment

http://stackoverflow.com/q/48004562
type: UnansweredQuestion
has body: I'm building a web app in Python with Django and I want the users to authenticate with pam, in order to use their system credentials. I'm developing on Windows now, so I installed pam module through pip with pip install python-pam and it worked perfectly Collecting python-pam Downloading python-pam-1.8.2.tar.gz Installing collected packages: python-pam Running setup.py install for python-pam ... done Successfully installed python-pam-1.8.2 But then, when I try to import it in Python env with a simple import I get this error: &gt;&gt;&gt; import pam Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Program Files\Python36\lib\site-packages\pam.py", line 70, in &lt;module&gt; libc = CDLL(find_library("c")) File "C:\Program Files\Python36\lib\ctypes\__init__.py", line 348, in __init__ self._handle = _dlopen(self._name, mode) TypeError: LoadLibrary() argument 1 must be str, not None &gt;&gt;&gt; Am I missing something during installation or what? Thanks everybody in advance guys. UPDATE #1 Ok, the problem slightly move on: i skipped using python_pam directly when found django_pan, so i installed it from my virtual environment (everything ok), and following this guide i've been able to call the default login page. The problem now arise when i try to log in using the default form: after have inserted my credential and clicked the login button i got the django debug error page, the one woth the yellow header, the stack trace, etc.. The problem is still the same: File "c:\program files\python36\Lib\ctypes\__init__.py", line 348, in __init__ self._handle = _dlopen(self._name, mode) TypeError: LoadLibrary() argument 1 must be str, not None I tried upgrading django_pam with pip3 but nothing new: (django_test) X:\RnD\smanetti\Python\Django\django_test\mysite&gt;pip3 install django-pam Requirement already satisfied: django-pam in x:\rnd\smanetti\python\django\django_test\lib\site-packages Requirement already satisfied: python-pam in x:\rn…
tagged with: authentication
has comment: http://stackoverflow.com/comment/82977633
tagged with: import
has comment: http://stackoverflow.com/comment/88175910
type: Question
has comment: http://stackoverflow.com/comment/82980661
has title: Python importing pam module error
downvote count: 0
favorite count: 0
tagged with: pam
tagged with: python
tagged with: module
has comment: http://stackoverflow.com/comment/82986053
score: 2
answer count: 0
upvote count: 2

http://stackoverflow.com/comment/82704985
has text: If you are trying to parse the output of `pip freeze`, you can do that programmatically though python.
comment on: http://stackoverflow.com/q/47869800
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47999339
has comment: http://stackoverflow.com/comment/82988419
has comment: http://stackoverflow.com/comment/83130700
has body: There could be many ways to "normalize scores", and the best one would be highly dependent on what exactly you're trying to achieve (which isn't clear from the question). However, having said that, I'd like to suggest a simple, practical approach. Starting with the utopian case: say you had lots of data, all of it perfectly linear - i.e., showing a neat linear relation between load and MPG per vehicle type. In that case, you would have a strong prediction regarding the expected MPG per vehicle type, given some load. You could compare the actual MPG to the expected value, and "score" based on the ratio, e.g. actual MPG / expected MPG. Practically, however, data is never perfect. So you could build a model based on the available data, get a prediction, but instead of using a point-estimate as a basis for scoring, you could use a confidence interval. For instance: the expected MPG given a model and some load is between 9-11 MPG with 95% confidence. In some cases (where more data is available, or it's more linear) the confidence interval may be narrow; in others, it'll be wider. Then you could take an action (e.g. "punish" as you put it), say, only if MPG is out of the expected range. EDIT: an illustration (code in R): #df contains the data above. #generate a linear model (note that 'Vehicle' is not numerical) md &lt;- lm(data=df, Miles.per.Gal ~ Load + Vehicle) #generate predictions based on the model; for this illustration, plotting only for 'Tundra' newx &lt;- seq(min(df$Load), max(df$Load), length.out=100) preds_df &lt;- as.data.frame(predict(md, newdata = data.frame(Load=newx, model="Tundra")) #plot # fit + confidence plt &lt;- ggplot(data=preds_df) + geom_line(aes(x=x, y=fit)) + geom_ribbon(aes(x = x, ymin=lwr, ymax=upr), alpha=0.3) # points for illustration plt + geom_point(aes(x=1100, y=7.8), color="red", size=4) +geom_point(aes(x=1300, y=4), color="blue", size=4) + geom_point(aes(x=1400, y=9), color="green", size=4) So based on this data, the red driver's fuel …
has comment: http://stackoverflow.com/comment/82984576
accepted answer of: http://stackoverflow.com/q/47942707
has comment: http://stackoverflow.com/comment/83132029
has comment: http://stackoverflow.com/comment/82991816
upvote count: 4
answers question: http://stackoverflow.com/q/47942707
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83130702
score: 4
has comment: http://stackoverflow.com/comment/83052061
type: Answer

http://stackoverflow.com/q/47888548
score: 0
has title: genfromtxt from numpy only returning ints from a csv file full of floats
answer count: 2
has answer: http://stackoverflow.com/a/47902603
tagged with: variables
has comment: http://stackoverflow.com/comment/82743602
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/82743140
tagged with: python
has comment: http://stackoverflow.com/comment/82743660
tagged with: list
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47902725
has body: I currently have this project that I'm working on for my physics class involving taking data from a csv file and running some code to analyze the force of air resistance on a wiffle ball. My data (from the csv file) is all floats with no strings in it, but I've had a problem with my code. When I added the line for genfromtxt from numpy in my code, at first I thought the numbers in my csv file were added as strings, so I printed out the list it creates with it, and it showed that all my data was stored as integers. This is the line that I used to import the file: x = genfromtxt('Xpos.csv', delimiter=',') These are the first 10 numbers that are in my csv file: 0.659732735 0.746132896 0.806970832 0.881848293 0.966085435 1.017563689 1.101800832 1.190717816 1.256235594 1.317073531 These numbers show up in the printed list with the decimal places removed, so just 0, 0, 0, 0, 0, 1, 1, 1, 1, 1
type: Question
has comment: http://stackoverflow.com/comment/82743326
tagged with: numpy

http://stackoverflow.com/a/47926760
accepted answer of: http://stackoverflow.com/q/47926159
answers question: http://stackoverflow.com/q/47926159
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has body: You're passing (0, 0) as the blit destination (the second argument), so your surface appears in the top left corner of the display. If you want to draw it elsewhere, for example at (200, 300) you have to pass these coords as the second argument: self.display.blit(image, (200, 300), (640,512,200,200))
type: Answer

http://stackoverflow.com/comment/82782413
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47898271
has text: @Tim Biegeleisen I have seen the criticism to the layout of the question, will spend a while now editing. Thanks for feedback

http://stackoverflow.com/q/47999119
has comment: http://stackoverflow.com/comment/82967174
has comment: http://stackoverflow.com/comment/82966874
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82967228
has comment: http://stackoverflow.com/comment/83029579
has comment: http://stackoverflow.com/comment/82967158
has body: What will be the best way to make reading the files more efficient? Using this with open(fname, 'r') as myf: for myline in myf: or for glob.glob('*.txt'): I performed a cprofile stats and this is what I got for a few sorted lines: ncalls tottime percall cumtime percall filename:lineno(function) 4/1 0.000 0.000 1895.428 1895.428 {built-in method builtins.exec} 1 157.201 157.201 1895.428 1895.428 runmyfiles.py:2(&lt;module&gt;) 5 1365.371 273.074 1554.015 310.803 runmyfiles.py:9(readFile) 52727 184.205 0.003 184.205 0.003 {method 'write' of '_io.TextIOWrapper' objects} 194515 0.300 0.000 74.091 0.000 /usr/lib/python3.6/re.py:214(findall) 194515 72.479 0.000 72.479 0.000 {method 'findall' of '_sre.SRE_Pattern' objects} I know I should optimize the file reading process but not sure how to go about it. I may need to open all the files at once and compare each line in each file with similar lines in the other files then write the output for the line containing the max value of bb. Is this logical considering the stats generated?
has title: How to optimize reading and comparing lines between multiple files?
has comment: http://stackoverflow.com/comment/82992299
type: Question
score: 0
has comment: http://stackoverflow.com/comment/82966829
has comment: http://stackoverflow.com/comment/82966966

http://stackoverflow.com/q/47876084
has comment: http://stackoverflow.com/comment/82838042
has title: Can't call a decorator within the imported sub-class of a cherrpy application (site tree)
tagged with: class
has body: I am using cherrypy as a web server, and I want to check a user's logged-in status before returning the page. This works on methods in the main Application class (in site.py) but gives an error when I call the same decorated function on method in a class that is one layer deeper in the webpage tree (in a separate file). validate_user() is the function used as a decorator. It either passes a user to the page or sends them to a 401 restricted page, as a cherrypy.Tool, like this: from user import validate_user cherrypy.tools.validate_user = cherrypy.Tool('before_handler', validate_user) I attach different sections of the site to the main site.py file's Application class by assigning instances of the sub-classes as variables accordingly: from user import UserAuthentication class Root: user = UserAuthentication() # maps user/login, user/register, user/logout, etc admin = Admin() api = Api() @cherrypy.expose @cherrypy.tools.validate_user() def how_to(self, **kw): from other_stuff import how_to_page return how_to_page(kw) This, however, does not work when I try to use the validate_user() inside the Admin or Api or Analysis sections. These are in separate files. import cherrypy class Analyze: @cherrypy.expose @cherrypy.tools.validate_user() #### THIS LINE GIVES ERROR #### def explore(self, *args, **kw): # @addkw(fetch=['uid']) import explore kw['uid'] = cherrypy.session.get('uid',-1) return explore.explorer(args, kw) The error is that cherrypy.tools doesn't have a validate_user function or method. But other things I assign in site.py do appear in cherrypy here. What's the reason why I can't use this tool in a separate file that is part of my overall site map? If this is relevant, the validate_user() function simply looks at the cherrypy.request.cookie, finds the 'session_token' value, and compares it to our database and passes it along if the ID matches. Sorry I don't know if the Analyze() and Api() and User() pages are subclasses, or nested classes, or extended methods, or…
has comment: http://stackoverflow.com/comment/82717602
linked to: http://stackoverflow.com/q/47840006
score: 0
has answer: http://stackoverflow.com/a/47931272
answer count: 1
tagged with: cherrypy
accepted answer: http://stackoverflow.com/a/47931272
has comment: http://stackoverflow.com/comment/82860520
linked to: http://stackoverflow.com/q/6552025
tagged with: python
tagged with: python-decorators
type: AnsweredQuestion
type: Question

qwidget
tag name: qwidget
tags question: http://stackoverflow.com/q/47965618
type: Tag

http://stackoverflow.com/comment/82876309
type: AnswerComment
comment on: http://stackoverflow.com/a/47953424
score: 0
type: Comment
has text: `from bs4 import BeautifulSoup`, I got error `ImportError: No module named bs4`

http://stackoverflow.com/a/47956376
answers question: http://stackoverflow.com/q/47956327
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47956327
type: Answer
has body: When you create a new project on 1.8 setting BASE_DIR var is created: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) Use this var as base for your file path: &gt;&gt;&gt; from django.conf import settings &gt;&gt;&gt; import os &gt;&gt;&gt; f=os.path.join( settings.BASE_DIR, 'myApp/static/myApp/myData.json' ) &gt;&gt;&gt; f '/home/dani/tmp/ppdpd/p/myApp/myData.json' &gt;&gt;&gt; json_data = open(f) Notice than static is intended to get path to out of the box clients, from navigator side, remotely, from Internet. And not from your server side django app. Notice may be you invoke collectstatic when you deploy your app, then the right path will be settings.STATIC_ROOT something like: &gt;&gt;&gt; f=os.path.join( settings.STATIC_ROOT, 'myApp/myData.json' )
score: 5
upvote count: 5

http://stackoverflow.com/a/48198814
score: 0
has body: You can learn more about this feature here, it's just another repl with the convenience of being within Visual Studio. There's also some interesting connections to the editor that you can send selected code lines to the interactive window. I'm not sure how variable scoping works between the two but sometimes you just want to experiment in the repl before integrating it into a working python file. I mostly put the Immediate Window to use for some interactive exploratory coding when I develop in Visual Studio. This is scoped to where the current breakpoint is set which is good for manipulating things on the fly and getting feedback about my variables and what not.
type: Answer
answers question: http://stackoverflow.com/q/47992578

http://stackoverflow.com/comment/82852609
has text: I know, but in terms of memory, creating a new dictionary isn't as efficient as modifying the original... Nevertheless, in this case, I would go for this solution as it is more compact so +1 **:)**
type: AnswerComment
comment on: http://stackoverflow.com/a/47941455
score: 0
type: Comment

http://stackoverflow.com/a/47957535
downvote count: 0
has comment: http://stackoverflow.com/comment/82884364
answers question: http://stackoverflow.com/q/47957520
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47957520
has comment: http://stackoverflow.com/comment/82884490
score: 2
has comment: http://stackoverflow.com/comment/82884579
has body: You can using iloc with groupby df.groupby('Fruit').Amount.apply(lambda x: x/x.iloc[-1]) Out[38]: 0 1.500000 1 1.333333 2 0.166667 3 2.500000 4 1.250000 5 0.333333 6 1.000000 7 1.875000 8 0.625000 9 1.000000 Name: Amount, dtype: float64 After assign it back df['New']=df.groupby('Fruit').Amount.apply(lambda x: x/x.iloc[-1]) df Out[40]: Fruit Amount New 0 Orange 90 1.500000 1 Orange 80 1.333333 2 Orange 10 0.166667 3 Apple 100 2.500000 4 Apple 50 1.250000 5 Orange 20 0.333333 6 Orange 60 1.000000 7 Apple 75 1.875000 8 Apple 25 0.625000 9 Apple 40 1.000000 Without using lambda df.Amount/df.groupby('Fruit',sort=False).Amount.transform('last') Out[46]: 0 1.500000 1 1.333333 2 0.166667 3 2.500000 4 1.250000 5 0.333333 6 1.000000 7 1.875000 8 0.625000 9 1.000000 Name: Amount, dtype: float64
has comment: http://stackoverflow.com/comment/82884433
type: AcceptedAnswer

http://stackoverflow.com/comment/82836703
score: 0
comment on: http://stackoverflow.com/q/47933705
type: QuestionComment
type: Comment
has text: try with 's3a://' instead of 's3://' in the path

http://stackoverflow.com/q/47933194
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47933394
has body: This is the code I am trying to run... scoreCount = int(input("How many scores do you want to record?")) recordedValues = 0 averageScore = totalScore/scoreCount highestScore = 0 totalScore = 0 This is where I believe the code stops working... while recordedValues <= scoreCount: score = int(input("\n\nEnter Score,:") if type(score)== int: totalScore == totalScore + score recordedValues == recordedValues + 1 if score >= highestScore: highestScore = score else: print("\n\nThe scores are not integer values") quit() How can I get the while loop to end and have the average score/highest score/recorded values displayed? Edit: Thanks for the help, I have solved the problem.
has title: Why doesn't the while loop end?
has answer: http://stackoverflow.com/a/47933240
type: Question
score: 0
answer count: 2
tagged with: while-loop
has comment: http://stackoverflow.com/comment/82835536
has comment: http://stackoverflow.com/comment/82835643
has comment: http://stackoverflow.com/comment/82835571

http://stackoverflow.com/comment/82709927
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47872237
has text: yes, that is correct. This is the entire contents of the file: 13 34 14 53 56 76
score: 0

http://stackoverflow.com/comment/82974762
comment on: http://stackoverflow.com/q/48003270
score: 0
type: Comment
has text: print the result of `requests.get('https://rbx.rocks/apis/item?id=1285307').json()[0]`
type: QuestionComment

http://stackoverflow.com/q/48000522
has answer: http://stackoverflow.com/a/48000858
tagged with: threshold
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48000725
possible better answer: http://stackoverflow.com/a/48000858
has title: How to apply a threshold to a pandas DataFrame column and output a row outside of the threshold?
tagged with: python
accepted answer: http://stackoverflow.com/a/48000725
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48000778
type: Question
has body: I have a large dataset of product families. I'm trying to catch any weird data entries where a price is too high/low than the other members of the family. For example, I have a this pandas.DataFrame: df = Prices Product Family 0 1.99 Yoplait 1 1.89 Yoplait 2 1.59 Yoplait 3 1.99 Yoplait 4 7.99 Yoplait 5 12.99 Hunts 6 12.99 Hunts 7 2.99 Hunts 8 12.49 Hunts I want to write a for loop, that iterates through each Product Family, sets some kind of threshold which identifies which products are questionable (row 4 and row 7), and spits out that row. How can I do this? So far I have this: families = df['Product Family'].unique() for i in families: if df['Prices] .....(set threshold) then.....(spit out that row that is questionable) And then I would ideally finish off that if statement in the for loop, for each product family. Does anyone have an idea (or a better one) on how to set this threshold and finish off the code?
tagged with: dataframe
score: 4
upvote count: 4
answer count: 3
tagged with: for-loop
tagged with: pandas

http://stackoverflow.com/a/47968354
answers question: http://stackoverflow.com/q/47968210
type: Answer
score: 0
has body: I suppose you are trying to make something like this:- Inst1 Inst2 REPEAT 5 Now you are trying to repeat previous instructions whatever the "number" you have specified with Repeat. You can sure just covert it to int, e.g. int(currenct_inst[1]), but that's really ambigous. According to the zen of python i advise you to be more explicit, perhaps if current_instruction[0] = repeat: # strip here removes the leading and trailing whitespace times_repeat = int(current_instrucitons[1].strip()) If you would like to handle a instruction like REPEAT (::), then you should take a look at exception handling. If you're interested, take a look at:- https://www.programiz.com/python-programming/exception-handling

http://stackoverflow.com/q/47874994
has comment: http://stackoverflow.com/comment/82715962
score: -1
has title: How to start Selenium (Chrome Driver) on a profile, with cookies etc inherited, on Python?
has comment: http://stackoverflow.com/comment/82716219
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/47875746
accepted answer: http://stackoverflow.com/a/47875746
tagged with: python
type: AnsweredQuestion
downvote count: 3
tagged with: selenium
has body: Experimenting with things on Python, and want Selenium to fill out a form that is only available after adding something to a cart. I'm not sure how to set it up to have cookies/a profile on it beforehand. How would I do it?
type: Question
answer count: 1

http://stackoverflow.com/comment/115003301
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47933504
has text: that is true..but if they are writing to hdfs without spark their is no other very good option.

http://stackoverflow.com/comment/82907961
has text: I'm doing a project for vehicle counting. For this I'm using blob detection. My video is getting stored in python directory but I'm not able to open it
score: 0
comment on: http://stackoverflow.com/q/47967582
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47929324
has answer: http://stackoverflow.com/a/47929488
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47929457
tagged with: python
tagged with: regex
type: AnsweredQuestion
has title: Python - Read Tokens from a String
possible better answer: http://stackoverflow.com/a/47929457
accepted answer: http://stackoverflow.com/a/47929439
type: Question
has answer: http://stackoverflow.com/a/47929439
score: 0
has body: I am reading all tokens (operators, int, str, etc.) from a string My current code: import re expression = "($mat.name == 'sign') AND ($most == 100.0)" tokens = re.findall("\$+[a-zA-Z]*\.[a-zA-Z]+|[a-zA-Z]+|Not|not|NOT|[=]+|[+/*()-]|[0-9]*\.[0-9]+|[0-9]+", expression) The current result: ['(', '$mat.name', '==', 'sign', ')', 'AND', '(', 'most', '==', '100.0', ')'] The problem is that, while the regex is correctly matching $mat.name, it matches most instead of $most. Can you please help me fix the regular expression?
answer count: 3

http://stackoverflow.com/q/48001329
score: 1
favorite count: 0
tagged with: pattern-matching
has body: I have two sets of protein sequence data. As you can see, these 2 sequences look the same but actually they have 1 different amino acid (letter) between them. For example: File 1: TV*TV*TV*TISTI*VWGKIGIRIE*PWIVSISEVESVACNSKNSNNNSE*K**FSEHFDLNYEN*K File 2: TV*TV*TV*TISTI*VWGKIGIRIE*PWIVSISVVESVACNSKNSNNNSE*K**FSEHFDLNYEN*K Desired output: File 1: E File 2: V I'm aware that we can print different pattern from two sets of data using command of grep, comm, diff; the search is based on line. But in this situation, how do I print the letter different between these two patterns? Thanks.
accepted answer: http://stackoverflow.com/a/48001426
tagged with: letter
tagged with: python
upvote count: 2
has title: How to print unmatched letter from a pattern
downvote count: 1
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48001604
tagged with: http://stackoverflow.com/tag/r
answer count: 3
possible better answer: http://stackoverflow.com/a/48001604
has answer: http://stackoverflow.com/a/48001426
tagged with: perl
has answer: http://stackoverflow.com/a/48002635

http://stackoverflow.com/q/47887093
has comment: http://stackoverflow.com/comment/82741014
upvote count: 2
tagged with: python
tagged with: merge
has answer: http://stackoverflow.com/a/47888369
score: 2
has comment: http://stackoverflow.com/comment/82739789
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82739762
has title: How to combine multiple rows of same category to one in pandas?
type: Question
possible better answer: http://stackoverflow.com/a/47888674
accepted answer: http://stackoverflow.com/a/47888369
has answer: http://stackoverflow.com/a/47888674
tagged with: dataframe
has body: I'm trying to get from table 1 to table 2 from the image but I can't seem to get it right. I tried pivot table to change col A - D from rows to cols. Then I try groupby but it doesn't give me one row but messes up my dataframe instead.
has comment: http://stackoverflow.com/comment/82741135
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/82893538
has text: You're missing parenthesis after ``lower`` (i.e. ``lower()``), so you're essentially comparing the ``lower`` method to the string ``'clear'``, and since they're not equal the statement is never true.
score: 6
type: Comment
comment on: http://stackoverflow.com/q/47962161
type: QuestionComment

http://stackoverflow.com/comment/83023144
type: Comment
comment on: http://stackoverflow.com/a/48013309
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/162183/discussion-between-simon-and-momo-6aye3).
type: AnswerComment
score: 0

http://stackoverflow.com/a/47939136
has comment: http://stackoverflow.com/comment/82852343
has comment: http://stackoverflow.com/comment/82852079
has comment: http://stackoverflow.com/comment/82852158
has comment: http://stackoverflow.com/comment/82852313
has comment: http://stackoverflow.com/comment/82847498
upvote count: 2
has comment: http://stackoverflow.com/comment/82852450
type: AcceptedAnswer
downvote count: 0
has body: If you want to go with alphanumeric order instead of lexicographical, you have to "get" the integers out of the strings and sort based on them. One way to do it would be the following: import os path = [r'\path\to\directory\with\files\I\want\file_2457621_specific_string.txt', r'\path\to\directory\with\files\I\want\file_2457632_specific_string.txt', r'\path\to\directory\with\files\I\want\file_2457622_specific_string.txt'] path.sort(key=lambda x: int(os.path.basename(x).split('_')[1])) Just FYI, if my regex skills were any good I would do it with regex though. As the comments say, in your example, there is no difference, but for instance, these two: path = [r'\path\file_22_specific_string.txt', r'\path\file_200_specific_string.txt'] would produce different results depending on whether the numeric characters are treated as strings or numbers.
has comment: http://stackoverflow.com/comment/82847535
accepted answer of: http://stackoverflow.com/q/47938945
has comment: http://stackoverflow.com/comment/82852201
answers question: http://stackoverflow.com/q/47938945
type: Answer
has comment: http://stackoverflow.com/comment/82849471
has comment: http://stackoverflow.com/comment/82852420
score: 2
has comment: http://stackoverflow.com/comment/82852330
has comment: http://stackoverflow.com/comment/82852433

http://stackoverflow.com/q/47875221
tagged with: exception
type: UnansweredQuestion
tagged with: python
has body: class Translator(object): def __init__(self, tracking_col='tracking_id', coding_col='coding', qualifying_code_col='qualifying_code', translation_col='translation'): self._results = [] self.tracking_col = tracking_col self.data_col = coding_col self.definition_col = qualifying_code_col self.translation_col = translation_col self.__validate_parameters(self.__dict__) def __validate_parameters(self, variable_values): class_values = {} for key, value in variable_values.items(): if type(value) is str: class_values.setdefault(value, set()).add(key) for key, values in class_values.items(): # If there is more than one value, there is a duplicate if len(values) &gt; 1: raise Exception('Duplicate column names exist in parameters. \'{}\' are set to \'{}\'. ' 'Do not use duplicate column names.'.format(values, key)) This class cannot have the duplicate values for any of the 'col' variables. If duplicate values exist, logic further in the class may not crash but will create unpredictable results. Upon instantiation my function __validate_parameters will detect duplicate values and raise an Exception. The problem is I am dumping all the values out to a dictionary, iterating to create another dictionary, and finally manually raising an exception (which from what I've been told is the wrong thing to do in any situation). It's also rather verbose. Is there a shorter and more concise way to validate for duplicates while propogating an error up without the complexity above?
tagged with: reflection
has answer: http://stackoverflow.com/a/47875360
upvote count: 1
has answer: http://stackoverflow.com/a/47875377
type: Question
has title: Detecting Duplicates in Class Instance's Variable Values
tagged with: class
answer count: 2
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82716173

http://stackoverflow.com/a/48044879
has body: Apparently, the documentation does not match reality. unchecked and checked were the documented way to do what I wanted, but after experimenting with off and on which were equally ineffective, I tried closed and open, which, as I understand from the documentation, is only supposed to apply to QPushButtons with menus attached. Nonetheless, that worked. (It doesn't seem to be doing the outset and inset but it's getting the colors right.) I also switched to PyQt5 to see if there would be a change, but it behaved the same as PySide. #!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import os from PySide.QtCore import * from PySide.QtGui import * class UI(QDialog): def __init__(self, *args, **kwargs): super(UI, self).__init__(**kwargs) outerBox = QGroupBox(self) outerBox.setGeometry(50, 50, 200, 150) outerBox.setObjectName("outerBox") brokenCss = "QPushButton:closed {" brokenCss += " background-color: #ce9a9a;" # red-ish brokenCss += " border: 1px outset #000000;" brokenCss += " border-radius: 6px;" brokenCss += "}" brokenCss += "QPushButton:open {" brokenCss += " background-color: #12f785;" # green-ish brokenCss += " border: 1px inset #000000;" brokenCss += " border-radius: 6px;" brokenCss += "}" broken = [] for i in range(2): broken.append(QPushButton(outerBox)) broken[i].setObjectName("broken{0}".format(i)) broken[i].setGeometry(15, (35 * (i + 1)), 100, 20) broken[i].setText("Broken CSS {0}".format(i)) broken[i].setCheckable(True) broken[i].setChecked(False) broken[i].setStyleSheet(brokenCss) if __name__ == '__main__': app = QApplication(sys.argv) ui = UI() ui.showFullScreen() sys.exit(app.exec_())
type: AcceptedAnswer
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47998315
accepted answer of: http://stackoverflow.com/q/47998315

http://stackoverflow.com/comment/82863476
type: Comment
has text: any recommendation how to remove the letter 'b' from the result i get? It says its byte type.
type: AnswerComment
comment on: http://stackoverflow.com/a/47946747
score: 0

http://stackoverflow.com/comment/82916219
type: Comment
type: QuestionComment
has text: @OliverFrost is the `if guess == number:` comparison inside or outside the `def the_start():`?
comment on: http://stackoverflow.com/q/47973173
score: 0

http://stackoverflow.com/comment/82950074
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47990722
has text: @pranjalkumar: there is none.

http://stackoverflow.com/comment/82827978
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47929477
score: 0
has text: Please provide a MCVE. See [**How to create a Minimal, Complete, and Verifiable Example**](https://stackoverflow.com/help/mcve).

http://stackoverflow.com/comment/82839968
type: Comment
type: QuestionComment
has text: haha why wont the folder new be made...do I need to make it beforehand to move the images
score: 0
comment on: http://stackoverflow.com/q/47935107

http://stackoverflow.com/q/47912530
downvote count: 0
accepted answer: http://stackoverflow.com/a/47913544
favorite count: 0
tagged with: sql-server
tagged with: python
has answer: http://stackoverflow.com/a/47913544
tagged with: model
has title: Django getting "first_name" is invalid keyword argument for this function" TypeError when creating an instance of my model class
tagged with: django
upvote count: 1
type: AnsweredQuestion
score: 1
has body: Using Django 1.11 and django-pyodbc-azure latest version if it is relevant. I am new to Django and have been following along the 1.11 tutorial without any issues until this, and I am incredibly confused. Here is my models.py: from django.db import models # Create your models here. class Player(models.Model): first_name = models.CharField(max_length=20, name='First Name') last_name = models.CharField(max_length=20, name='Last Name') def __str__(self): return '{}, {} ({})'.format(self.last_name, self.first_name, self.id) class Game(models.Model): players = models.ManyToManyField(Player, name='Players') def __str__(self): return ' vs. '.join(self.players) class Round(models.Model): GIN = 'GI' UNDERCUT = 'UN' KNOCK = 'KN' ENDING_ACITONS = ( (GIN, 'Gin'), (UNDERCUT, 'Undercut'), (KNOCK, 'Knock'), ) game = models.ForeignKey(Game, on_delete=models.CASCADE, name='Parent Game') winner = models.ForeignKey(Player, on_delete=models.CASCADE, name='Winning Player') points = models.IntegerField(name='Points Awarded') end = models.CharField(max_length=2, choices=ENDING_ACITONS) def __str__(self): return '{} awarded {} points via {}'.format(self.winner, self.points, self.end.name) Now when I run manage.py shell and type: from game.models import * bobby = Player(first_name='Bobby', last_name='Fisher') I am met with this error: Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; File "C:\Users\mteper\PycharmProjects\GinRummy\venv\lib\site-packages\django\db\models\base.py", line 571, in __init__ raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0]) TypeError: 'first_name' is an invalid keyword argument for this function Any insight would be greatly appreciated, as, like I said earlier, I am new to Django and Python in general.
type: Question
answer count: 1

http://stackoverflow.com/q/47948749
has comment: http://stackoverflow.com/comment/82867521
has body: How can a turn this code into a shorthand line of code? is it possible at all? I would like the same purpose of the code, but with the least amount of lines possible inpt = input('Age: ') age = int(inpt) if age &lt;= 10: print('Kid') elif age &gt; 10 &lt;= 20: print('Teen') elif age &gt; 20: print('Adult')
favorite count: 0
has answer: http://stackoverflow.com/a/47948771
tagged with: python
answer count: 4
tagged with: python-3.x
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47948787
type: Question
score: 2
has title: In python, how to make a conditional of multiple statements into a shorthand line like a ternary operator?
has answer: http://stackoverflow.com/a/47948785
upvote count: 2
has answer: http://stackoverflow.com/a/47948770

http://stackoverflow.com/comment/82916436
has text: Thank you SteveB but that thread's answer still asks you to run chmod +x command where as I want to find a way so that MacOS automatically assigns the +x bit to any *.py file right from creation.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47973401

http://stackoverflow.com/comment/82916327
comment on: http://stackoverflow.com/a/47973260
has text: Well your `lines` list seems to contain just one line : (414, 23) - (416, 23). This isn't going to trigger your `if` conditions, resulting in empty lists, ultimately resulting in the exception. So I'm afraid you basically have some faulty reasoning going on, which is a completely different question.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/47935421
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/47935443
favorite count: 0
type: Question
tagged with: python
has title: How do I add all integers in one list to integers on another list with different length in the same order in Python?
answer count: 6
has answer: http://stackoverflow.com/a/47935485
upvote count: 3
possible better answer: http://stackoverflow.com/a/47935466
has answer: http://stackoverflow.com/a/47939903
has answer: http://stackoverflow.com/a/47935466
downvote count: 1
has answer: http://stackoverflow.com/a/47936028
has answer: http://stackoverflow.com/a/47935513
has answer: http://stackoverflow.com/a/47935443
has body: Given: ListA = [1,2,3,4,5] ListB = [10,20,30,40,50,60,70] How do I make it such that ListC = [11,22,33,44,55,60,70], where C[0] = B[0] + A[0]... C[5] = nil + B[5] and so on? I can't simply use a for loop in this case as there will be an IndexError as ListB has two more entries as compared to ListA?
tagged with: numpy
tagged with: python-2.7

http://stackoverflow.com/comment/82842435
has text: The command manage.py migrate basically executes the same thing but yeah it returns the same error. Thanks though.
comment on: http://stackoverflow.com/q/47936526
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82977148
type: AnswerComment
type: Comment
has text: I hope you don't mind, I updated my answer using your suggestion for completeness. Thanks for pointing it out.
comment on: http://stackoverflow.com/a/48001538
score: 0

http://stackoverflow.com/comment/82940490
comment on: http://stackoverflow.com/q/47985788
score: 0
has text: `for x in n: x[0] = 1`
type: QuestionComment
type: Comment

gmail
type: Tag
tags question: http://stackoverflow.com/q/47905873
tag name: gmail

http://stackoverflow.com/q/47930615
has answer: http://stackoverflow.com/a/53060860
type: Question
tagged with: graph-tool
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83417132
answer count: 1
downvote count: 0
has title: Graph-tool installed but can't be imported
favorite count: 0
has body: I installed Graph-tool via homebrew $ brew --prefix graph-tool /usr/local/opt/graph-tool But I still get error when trying to import it. I have read related posts How to let python3 import graph-tool installed by Homebrew? and tried all the solutions provided there, but none of them fixed it. Adding the path in python doesn't work, re-run homebrew as below doesn't either. $ brew install graph-tool --with-python2.7 Warning: homebrew/science/graph-tool 2.26_1 is already installed I usually use python via anaconda, but I also tried importing it from python console and it didn't work.
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/43521774
score: 2
upvote count: 2
tagged with: homebrew

http://stackoverflow.com/comment/82964260
has text: make sure to check the content of both `line` and `prev_line` json (also if your `add ...` is having such reference of "transactions")
score: 2
comment on: http://stackoverflow.com/q/47997953
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82881238
type: Comment
comment on: http://stackoverflow.com/a/47955357
has text: Thanks for the answer! I am not 100% sure what the function win_wait_for_parent() does exactly and, thus, how to include it in my program. Does it simply return True if there is no parent anymore?
type: AnswerComment
score: 0

http://stackoverflow.com/a/47958509
answers question: http://stackoverflow.com/q/47957207
type: Answer
has body: You have to pass the absolute path of the ChromeDriver along with the Attribute Key as follows : from selenium import webdriver driver = webdriver.Chrome(executable_path='/usr/local/bin/chromedriver') driver.get('http://www.google.com');
score: 0

http://stackoverflow.com/a/47881203
upvote count: 2
type: Answer
score: 2
downvote count: 0
has body: Here is one another variation of implementation. from collections import defaultdict import operator input= [ ["Pakistan", 23], ["Pakistan", 127], ["India", 3], ["India", 71], ["Australia", 31], ["India", 22], ["Pakistan", 81] ] cv_dict=defaultdict(list) for key, score in input: cv_dict[key].append(score) for k,v in cv_dict.items(): cv_dict[k]=sum(v)/len(v) max(cv_dict, key=cv_dict.get) Hope it helps !
answers question: http://stackoverflow.com/q/47880551

http://stackoverflow.com/a/47935326
score: 1
has comment: http://stackoverflow.com/comment/82869726
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/82860036
has body: sample data item very low, one for each freq, add small noise and use more data, normalize output data -1 to 1 range then try again
answers question: http://stackoverflow.com/q/47932589
upvote count: 1

http://stackoverflow.com/q/47896109
has comment: http://stackoverflow.com/comment/82759234
has body: I'm trying to build a toplevel window within python that has a single label within it called "text". It's textvariable is called "v". As you can see, there are 3 function calls within dialogueBox(). What I want the program to do is have the label "text" display the phrase "Event one", wait one second, display the phrase "Event two", wait one second, and then display the phrase "Event three". Instead of doing this, the top level window is opened displaying only "Event three". I suspect that this is a lambda issue but I'm still not sure how to use it in Tkinter. from tkinter import* import time def event1(): v.set("Event one") def event2(): v.set("Event two") def event3(): v.set("Event three") def dialogueBox(): top = Toplevel() global v top.minsize(400,0) top.maxsize(700,300) top.title("Toplevel test") v = StringVar() text = Label(top,textvariable = v) text.pack() event1() time.sleep(1) event2() time.sleep(1) event3() root = Tk() email = StringVar() password = StringVar() title = Label(root,text="Root window",font = 11) title.pack() label1 = Label(root,text = "Username") label1.pack() field1 = Entry(root,textvariable = email) field1.pack() label2 = Label(root,text = "Password") label2.pack() field2 = Entry(root,show = "*",textvariable = password) field2.pack() button = Button(root,text = "Get data",command = dialogueBox) button.pack() root.mainloop()
tagged with: python
tagged with: lambda
has comment: http://stackoverflow.com/comment/82759134
tagged with: tkinter
has comment: http://stackoverflow.com/comment/82759466
has answer: http://stackoverflow.com/a/47896350
has comment: http://stackoverflow.com/comment/82759247
type: Question
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/47839120
score: 0
accepted answer: http://stackoverflow.com/a/47896350
answer count: 3
has title: How do I get a label to update after function calls within a TopLevel window?
possible better answer: http://stackoverflow.com/a/47896362
has answer: http://stackoverflow.com/a/47896398
has answer: http://stackoverflow.com/a/47896362

http://stackoverflow.com/q/47985981
has answer: http://stackoverflow.com/a/47986022
type: Question
tagged with: keyvaluepair
has comment: http://stackoverflow.com/comment/82941012
has body: I am using and image scanning API to look for specific images i.e. cat or dog this API tells you the probability of a result in your image. For example an image of a dog would return {u'dog': 0.99628395, u'cat': 0.87454434} I want my end result only to take the highest returned value AND only if its above .89 AND below 1. Code I have so far: import operator #define lists tags = [u'dog', u'cat'] tags_value= [0.99628395, 0.87454434] #merge key and value pairs keywords = dict(zip(tags, tags_value)) #check the result print (keywords) which gives me {u'dog': 0.99628395, u'cat': 0.87454434} I am looking for an end result of [u'dog'] (notice how the end result is in [] and not {}) Note: if the end result is {u'dog': 0.88628395, u'cat': 0.87454434} then I don't want to return anything because the value is less than .89
has answer: http://stackoverflow.com/a/47986015
has title: Return highest key value pair in-between certain number
favorite count: 0
has answer: http://stackoverflow.com/a/47986131
answer count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/82940983
score: -1
accepted answer: http://stackoverflow.com/a/47986015
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47986095
has answer: http://stackoverflow.com/a/47986138
downvote count: 2
possible better answer: http://stackoverflow.com/a/47986022
upvote count: 1

http://stackoverflow.com/a/47924845
score: 2
answers question: http://stackoverflow.com/q/47924370
downvote count: 0
upvote count: 2
type: Answer
has body: There are many ways to achieve this. Overriding the default UserCreationForm() class MyForm(UserCreationForm): email = forms.EmailField(required=True) email.help_text = '' ... In the view template instead of using {{ form.as_p }} render the form manually &lt;form action="" method="post"&gt;{% csrf_token %} {{ form.username.label }} {{ form.username }} ... &lt;/form&gt; Design your custom template and map the field name to the form field name. Hope it helps !
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47924370

http://stackoverflow.com/a/48037093
has comment: http://stackoverflow.com/comment/83203572
upvote count: 10
downvote count: 0
answers question: http://stackoverflow.com/q/48012287
has body: I agree with your assessment - the weights aren't changing very much across the minibatches. It does appear they are changing somewhat. As I'm sure you're aware, you are doing fine tuning with very large models. As such, backprop can sometimes take a while. But, you're running many training iterations. I don't really think this is the problem. If I'm not mistaken, both of these were originally trained on ImageNet. If your images are in a totally different domain than something in ImageNet, that could explain the problem. The backprop equations do make it easier for biases to change with certain activation ranges. ReLU can be one if the model is highly sparse (i.e. if many layers have activation values of 0, then weights will struggle to adjust but biases will not). Also, if activations are in the range [0, 1], the gradient with respect to a weight will be higher than the gradient with respect to a bias. (This is why sigmoid is a bad activation function). It could also be related to your readout layer - specifically the activation function. How are you calculating error? Is this a classification or regression problem? If at all possible, I recommend using something other than sigmoid as your final activation function. tanh could be marginally better. Linear readout sometimes speeds up training, too (all the gradients have to "pass through" the readout layer. If the derivative of the readout layer is always 1 - linear - you're "letting more gradient through" to adjust the weights further down the model). Lastly I notice your weights histograms are pushing towards negative weights. Sometimes, especially with models that have a lot of ReLU activation, that can be an indicator of the model learning sparsity. Or an indicator of the dead neuron problem. Or both - the two are somewhat linked. Ultimately, I think your model is just struggling to learn. I've encountered very similar histograms retraining Inception. I was using a dataset of about 2000 images, and I was struggl…
type: Answer
has comment: http://stackoverflow.com/comment/83061067
score: 10

http://stackoverflow.com/comment/139381282
type: AnswerComment
has text: As long as the package is importable in Python (which can be done by adding them to the docker image or passing via --py-files as Python/egg/wheel files) then it should work.
type: Comment
comment on: http://stackoverflow.com/a/52066867
score: 0

http://stackoverflow.com/a/48014139
has comment: http://stackoverflow.com/comment/82997343
has comment: http://stackoverflow.com/comment/82998489
has body: You have an issue with quoting - try this: df = pd.read_sql_query("SELECT Department, count(*) as cnt FROM MyTable WHERE CompletedTraining = 'Incomplete' GROUP BY Department", con) You can also use the following technique: qry = """ SELECT department, count(*) as cnt FROM MyTable WHERE CompletedTraining = 'Incomplete' GROUP BY department """ df = pd.read_sql_query(qry, con)
upvote count: 4
has comment: http://stackoverflow.com/comment/82999263
has comment: http://stackoverflow.com/comment/82998534
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/48014080
has comment: http://stackoverflow.com/comment/82997193
type: Answer
has comment: http://stackoverflow.com/comment/82997403
has comment: http://stackoverflow.com/comment/82997615
has comment: http://stackoverflow.com/comment/82998101
has comment: http://stackoverflow.com/comment/82997523
has comment: http://stackoverflow.com/comment/82998090
has comment: http://stackoverflow.com/comment/82998153

http://stackoverflow.com/comment/83002516
has text: and I think `['[' + x for x in s[1:].split("[")]` is more easy to understand than `map lambda ` way
type: AnswerComment
comment on: http://stackoverflow.com/a/48010066
type: Comment
score: 1

http://stackoverflow.com/comment/82702304
comment on: http://stackoverflow.com/a/47868589
type: Comment
score: 1
type: AnswerComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ code can be repeated while separatot is present in b string. Does it a problem?

http://stackoverflow.com/comment/82937088
has text: Thanks, Now able to print the all the required infromation
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47983995
type: AnswerComment

http://stackoverflow.com/comment/82751503
type: Comment
comment on: http://stackoverflow.com/q/47892471
score: 0
has text: another way is to save it in the session, read up here https://stackoverflow.com/a/31707946/8150371
type: QuestionComment

http://stackoverflow.com/comment/82892611
type: Comment
comment on: http://stackoverflow.com/a/47961362
has text: Thanks Andersson in helping me understand, This solved my problem
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82972792
comment on: http://stackoverflow.com/a/48002038
score: 0
type: AnswerComment
type: Comment
has text: @user8817674 for example? what if statement do you want?

arrays
tags question: http://stackoverflow.com/q/47974841
tags question: http://stackoverflow.com/q/47913709
tags question: http://stackoverflow.com/q/47972693
tags question: http://stackoverflow.com/q/47979861
tags question: http://stackoverflow.com/q/47936662
tags question: http://stackoverflow.com/q/47985387
tags question: http://stackoverflow.com/q/47861349
tags question: http://stackoverflow.com/q/47905529
tags question: http://stackoverflow.com/q/47869673
tags question: http://stackoverflow.com/q/47919869
type: Tag
tags question: http://stackoverflow.com/q/47962044
tags question: http://stackoverflow.com/q/47998930
tags question: http://stackoverflow.com/q/48009477
tags question: http://stackoverflow.com/q/47892689
tags question: http://stackoverflow.com/q/47891130
tags question: http://stackoverflow.com/q/47957961
tags question: http://stackoverflow.com/q/47934473
tags question: http://stackoverflow.com/q/47878223
tags question: http://stackoverflow.com/q/47986878
tags question: http://stackoverflow.com/q/47866503
tags question: http://stackoverflow.com/q/47982894
tags question: http://stackoverflow.com/q/47914515
tags question: http://stackoverflow.com/q/47856160
tags question: http://stackoverflow.com/q/47906305
tags question: http://stackoverflow.com/q/47954398
tags question: http://stackoverflow.com/q/47982091
tags question: http://stackoverflow.com/q/47957305
tags question: http://stackoverflow.com/q/47951758
tags question: http://stackoverflow.com/q/47858996
tags question: http://stackoverflow.com/q/47881815
tags question: http://stackoverflow.com/q/47921101
tags question: http://stackoverflow.com/q/47957598
tags question: http://stackoverflow.com/q/47891168
tags question: http://stackoverflow.com/q/47948067
tags question: http://stackoverflow.com/q/47954529
tags question: http://stackoverflow.com/q/47968293
tags question: http://stackoverflow.com/q/47939235
tags question: http://stackoverflow.com/q/47876828
tags question: http://stackoverflow.com/q/47994661
tags question: http://stackoverflow.com/q/47992019
tags question: http://stackoverflow.com/q/47923020
tags question: http://stackoverflow.com/q/48008287
tags question: http://stackoverflow.com/q/47933073
tags question: http://stackoverflow.com/q/47932922
tags question: http://stackoverflow.com/q/47893884
tags question: http://stackoverflow.com/q/47997953
tags question: http://stackoverflow.com/q/47953069
tags question: http://stackoverflow.com/q/47905790
tags question: http://stackoverflow.com/q/47977238
tags question: http://stackoverflow.com/q/47860592
tags question: http://stackoverflow.com/q/48002267
tag name: arrays
tags question: http://stackoverflow.com/q/47934894
tags question: http://stackoverflow.com/q/47902323
tags question: http://stackoverflow.com/q/48012765
tags question: http://stackoverflow.com/q/47857372
tags question: http://stackoverflow.com/q/47904407
tags question: http://stackoverflow.com/q/47909107
tags question: http://stackoverflow.com/q/47925377
tags question: http://stackoverflow.com/q/47865181
tags question: http://stackoverflow.com/q/47867440
tags question: http://stackoverflow.com/q/47944089
tags question: http://stackoverflow.com/q/47983467
tags question: http://stackoverflow.com/q/48007472
tags question: http://stackoverflow.com/q/47899683
tags question: http://stackoverflow.com/q/47861749
tags question: http://stackoverflow.com/q/47874298
tags question: http://stackoverflow.com/q/47872453
tags question: http://stackoverflow.com/q/47859753
tags question: http://stackoverflow.com/q/47915264
tags question: http://stackoverflow.com/q/47972057
tags question: http://stackoverflow.com/q/47879556
tags question: http://stackoverflow.com/q/47934626
tags question: http://stackoverflow.com/q/48006202
tags question: http://stackoverflow.com/q/47945163
tags question: http://stackoverflow.com/q/47986166
tags question: http://stackoverflow.com/q/47881799
tags question: http://stackoverflow.com/q/47888054
tags question: http://stackoverflow.com/q/47865730

http://stackoverflow.com/q/47915560
answer count: 2
has comment: http://stackoverflow.com/comment/82799216
has title: simple math not adding up in python For loop
score: 0
has comment: http://stackoverflow.com/comment/82799208
has answer: http://stackoverflow.com/a/47915639
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82799217
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82799187
has body: Here's my code: x = 20 for i in range(1,7): y = x/i print(i) # These lines are just to show what print(y) # the code is doing. I know it's not elegant. print(i*y) # And is not my final solution print('\n') Here's my output: 1 20.0 20.0 2 10.0 20.0 3 6.666666666666667 20.0 4 5.0 20.0 5 4.0 20.0 6 3.3333333333333335 20.0 So why is every answer to the equation the same (20)? When i clearly changes? Say for the third iteration, when i=3, going to the interpreter and performing 3*(20/3) yields 18 correctly and not 20. So I'm not sure what's going on. This is answered below. The difference between floats in python2.7 and python3
linked to: http://stackoverflow.com/q/2986150
has answer: http://stackoverflow.com/a/47915744
downvote count: 1
type: Question

http://stackoverflow.com/comment/82826219
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47910688
has text: @martineau Excellent! This may already be a good work around: let the user set the locale "correctly" (i.e. using `fr`, or `fra_fra`) and then, when getting the locale (as `fr_FR`) "parse" it to use only the first part (`fr`) to set it back. In order to ensure the codepage is taken into account too, a kind of conversion table between the value returned by `getlocale()` and the one to really use (`fr` or `fra_fra` like suggested by @eryksun) would be useful (hence find a list of legacy 3 letters codes). A monkey patch looks even better though (would not depend on such a conversion table).

http://stackoverflow.com/comment/82791570
comment on: http://stackoverflow.com/a/47911768
type: AnswerComment
type: Comment
has text: Thanks for your help and gentle suggestion ;-)
score: 0

http://stackoverflow.com/comment/82693641
type: AnswerComment
has text: Hey! Thanks! I was able to run it this time around. However, I could not monitor it on tensorboard. https://drive.google.com/open?id=1nHJtl5VrUEgBGkb40DJ_FFQYxC7-tbYX and https://drive.google.com/open?id=193pH6Nr9IRjhMBiI72zlc5565oBWjXUn
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47862418

http://stackoverflow.com/comment/82750325
comment on: http://stackoverflow.com/q/47891649
type: Comment
type: QuestionComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ No aggregations are needed, just this tricky transformation ! thanks
score: 1

pywinauto
tags question: http://stackoverflow.com/q/48009887
tags question: http://stackoverflow.com/q/47929049
tag name: pywinauto
tags question: http://stackoverflow.com/q/47895500
type: Tag

http://stackoverflow.com/a/47890083
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
has body: You need to index into the list to get the year. Also, convert it to int so that it compares as number: &gt;&gt;&gt; sorted(sample, key=lambda x: (int(x[0][2:4]), codes.get(x[0][:2]))) [['AP14', 7], ['NO15', 27], ['JU17', 45], ['JA18', 97], ['FE18', -4]]
type: Answer
accepted answer of: http://stackoverflow.com/q/47889916
answers question: http://stackoverflow.com/q/47889916

http://stackoverflow.com/a/47963868
has comment: http://stackoverflow.com/comment/82909400
has comment: http://stackoverflow.com/comment/82900118
has comment: http://stackoverflow.com/comment/82900559
has comment: http://stackoverflow.com/comment/82901054
has comment: http://stackoverflow.com/comment/82900523
has comment: http://stackoverflow.com/comment/82900990
has comment: http://stackoverflow.com/comment/82900320
has body: Do not assign an object to the execute() call but simply iterate the assigned cursor object: cur = mariadb_connection.cursor() cur.execute("SELECT time, voltage FROM sensortable") data = [] xTickMarks = [] for row in cur.fetchall(): data.append(int(row[1])) xTickMarks.append(str(row[0]))
has comment: http://stackoverflow.com/comment/82900564
has comment: http://stackoverflow.com/comment/82899846
type: Answer
has comment: http://stackoverflow.com/comment/82909954
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82900372
has comment: http://stackoverflow.com/comment/82900304
has comment: http://stackoverflow.com/comment/82900533
has comment: http://stackoverflow.com/comment/82908765
answers question: http://stackoverflow.com/q/47959891
has comment: http://stackoverflow.com/comment/82900434
upvote count: 2

http://stackoverflow.com/q/47899952
type: AnsweredQuestion
tagged with: networkx
type: Question
tagged with: edges
has title: I use networkx.add_edge(),but nothing of edges added? why?
score: 0
answer count: 1
has body: import networkx as net def get_Children(g, df): for i in range(0, (df.iloc[:,0].size)-1): f1 = df.iloc[i]['firm1'] f2 = df.iloc[i]['firm2'] if f1 != f2: if df.iloc[i]['children'] == 1.0: g.add_edge(f1, f2) else: continue return g g = net.Graph() g.add_nodes_from(index) get_Children(g, df) data like this: firm1 firm2 children firm1 firm2 children 1 2 0 1 3 1 1 4 0 2 3 1 2 1 0 2 4 1 3 1 0 3 2 0 3 4 0 4 1 0 4 2 0 4 3 0 if firm1 is the children of firm2 then get 1 otherwise 0. but i use the function above add nothing of edges. In [177]: g.edges() Out[177]: EdgeView([])
tagged with: python
has answer: http://stackoverflow.com/a/47900874
accepted answer: http://stackoverflow.com/a/47900874

greatest-n-per-group
tag name: greatest-n-per-group
tags question: http://stackoverflow.com/q/47983152
type: Tag

http://stackoverflow.com/q/47932646
has title: Solve C*M = N (C,M and N are matrices) where M is known and the structure of N is given in SymPy
tagged with: python
tagged with: linear-equation
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47933233
upvote count: 1
tagged with: matrix-multiplication
type: Question
tagged with: sympy
tagged with: linear-algebra
has body: I have come across this matrix multiplication problem where M is some non-singular 3x3 matrix with known values (i.e M = sympy.Matrix([[1, 0, 0],[0, 2, 0],[0, 0, 3]])) C is a 3x3 matrix to be determined and N is of the following form: 1. The 1st and 3rdrow of N are the same as C (e.g N.row(0)[i] = C.row(0)[i] for 0&lt;=i&lt;=2) 2. The elements in the 2nd row of N are the sum of the corresponding column in M (e.g N.row(1)[1] = sum(M.col(1))) After searching the web for a way to express this problem as a system of equations I've found nothing. I've been trying to solve this using symbolic matrices and by or by solving three different systems of the form Ax=b each one made of a row from C multiplied by M with b as a column from N such that A = M.T, x = (C.row(i)).T and b = N. Solving it symbolically resulted in a ridiculous expression that cannot be even be comprehended and I was unable to get a numeric solution from it. My latest attempt follow: import sympy as sp def func(mat=matrix([[1, 1, 1], [0, 2, 2], [1, 4, 5]])): c11, c12, c13, c21, c22, c23, c31, c32, c33 = sp.symbols('c11, c12, c13, c21, c22, c23, c31, c32, c33') M = mat.T b1 = sp.Matrix(x, y, z).T b2 = sp.Matrix(sum(M.col(0)), sum(M.col(1)), sum(M.col(2))).T b3 = sp.Matrix(a, b, c).T M1 = M.col_insert(3, b1) M2 = M.col_insert(3, b2) M3 = M.col_insert(3, b3) C1 = sp.linsolve(M1, (x, y, z)) C2 = sp.linsolve(M2, (x, y, z)) C3 = sp.linsolve(M3, (a, b, c)) return C1, C2, C3 Calling this yields the following: &gt;&gt;&gt; func() ({(x + y - z, -x/2 + 2*y - 3*z/2, -y + z)}, {(-3, -17/2, 6)}, {(a + b - c, -a/2 + 2*b - 3*c/2, -b + c)})
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47933233
score: 1
favorite count: 0

http://stackoverflow.com/comment/82761093
has text: 'schedule': crontab(minute=0, hour=13) # real working time That time is not exactly exactly the same, probably 12 or 13 o'clock.
score: 0
comment on: http://stackoverflow.com/q/47897121
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47899966
accepted answer: http://stackoverflow.com/a/47900662
upvote count: 1
tagged with: python
tagged with: opencv
type: AnsweredQuestion
has body: I want to drawn a red circle around the centroid of some objects in a image (the objects in the image are some insects, so the circles would help to a human being to visually detect the insects); I already have the centroids (bellow), but don't know how to do this in python/opencv; array([[ 265., 751.], [ 383., 681.], [ 386., 889.], [ 434., 490.], [ 446., 444.], [ 450., 451.], [ 539., 1365.], [ 571., 1365.], [ 630., 645.], [ 721., 1365.], [ 767., 70.], [ 767., 82.], [ 767., 636.]]) Does anyone knows how to do what I want?
downvote count: 3
tagged with: image-processing
type: Question
possible better answer: http://stackoverflow.com/a/47900755
answer count: 2
has answer: http://stackoverflow.com/a/47900755
score: -2
tagged with: image
has answer: http://stackoverflow.com/a/47900662
has title: Drawn a circle around the centroid of a image in opencv-python
favorite count: 0

http://stackoverflow.com/a/47979382
type: Answer
upvote count: 3
accepted answer of: http://stackoverflow.com/q/47979049
has body: The first bit of the solution is similar to jezrael's answer to your previous question, using concat + set_index + stack + unstack + sort_index. df = pd.concat([df1, df2])\ .set_index(['Cliente', 'Fecha'])\ .stack()\ .unstack(-2)\ .sort_index(ascending=[True, False]) Now comes the challenging part, we have to incorporate the Names in the 0th level, into the 1st level, and then reset the index. I use np.insert to insert names above the revenue entry in the index. i, j = df.index.get_level_values(0), df.index.get_level_values(1) k = np.insert(j.values, np.flatnonzero(j == 'Revenue'), i.unique()) Now, I create a new MultiIndex which I then use to reindex df - idx = pd.MultiIndex.from_arrays([i.unique().repeat(len(df.index.levels[1]) + 1), k]) df = df.reindex(idx).fillna('') Now, drop the extra level - df.index = df.index.droplevel() df Fecha 20/12/17 21/12/17 Esteban Revenue $1 $7,890 Impresiones2 1235 99 Impresiones 667 235 Jose Revenue $12 $2 Impresiones2 35 5 Impresiones 1312 25 Martin Revenue $146 $123 Impresiones2 56 523 Impresiones 12 6347 Pedro Revenue $1,256 $22 Impresiones2 124 898 Impresiones 5443 2368
score: 3
answers question: http://stackoverflow.com/q/47979049
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/82984363
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48007059
type: Comment
has text: @user32185, this will produce a list of __tuples__, where first element is a group name and a second one - a dataframe

http://stackoverflow.com/comment/82943073
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47987086
has text: you don't have to check odd numbers because they are not divided by `2`
score: 0

http://stackoverflow.com/comment/82867923
has text: It didn't work. I have two objects with two hits each, but when I do Item.objects.all().order_by('-hit_count_generic__hits')[:10] they are not in the result (all my other objects have just one views each)
comment on: http://stackoverflow.com/a/47868673
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/82999799
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48013768
has text: And how are you updating `A`?

http://stackoverflow.com/q/47898329
linked to: http://stackoverflow.com/q/6557407
accepted answer: http://stackoverflow.com/a/47900978
tagged with: inheritance
linked to: http://stackoverflow.com/q/877723
answer count: 1
tagged with: python
has body: I am trying to add validation to my Django forms. I want to require at least one child model for my inlineformset. I am using the following as a reference: Inline Form Validation in Django I am still getting an error line 454, in formset_factory return type(form.name + str('FormSet'), (formset,), attrs) TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases from django.forms import inlineformset_factory from .models import * from django.forms.models import BaseInlineFormSet from django import forms class PropertyForm(forms.ModelForm): class Meta: model = Property exclude = () class UnitForm(forms.ModelForm): class Meta: model = Unit exclude = () class CustomUnitFormset(BaseInlineFormSet): def is_valid(self): return super(CustomUnitFormset, self).is_valid() and \ not any([bool(e) for e in self.errors]) def clean(self): # get forms that actually have valid data count = 0 for form in self.forms: try: if form.cleaned_data and not form.cleaned_data.get('DELETE', False): count += 1 except AttributeError: pass if count &lt; 1: raise forms.ValidationError('You must have at least one unit') UnitFormSet = inlineformset_factory(Property, Unit, form=PropertyForm, formset='CustomUnitFormset', extra=0, min_num=1, validate_min=True, validate_max=True, max_num=10, ) view.py class PropertyUnitCreate(LoginRequiredMixin, CreateView): model = Property fields = ['address'] success_url = reverse_lazy('property-list') def get_context_data(self, **kwargs): data = super(PropertyUnitCreate, self).get_context_data(**kwargs) if self.request.POST: data['units'] = UnitFormSet(self.request.POST) else: data['units'] = UnitFormSet() return data def form_valid(self, form): context = self.get_context_data() units = context['units'] form.instance.user = self.request.user with transaction.atomic(): self.object = form.save() if units.is_valid(): units.instance = self.object units.save() return super(PropertyUnitCreate, self).fo…
type: AnsweredQuestion
has title: Adding Validation to Django Inlineformset Causing Metaclass Conflict
score: 0
has answer: http://stackoverflow.com/a/47900978
tagged with: django
tagged with: django-forms
type: Question

http://stackoverflow.com/comment/82752527
comment on: http://stackoverflow.com/q/47880164
score: 0
type: Comment
type: QuestionComment
has text: @DebanjanB I'm trying to drag one element into another. The elements cannot be the same.

http://stackoverflow.com/a/47951817
score: 1
answers question: http://stackoverflow.com/q/47948423
downvote count: 0
type: Answer
has body: What about a simple recursive approach : data = 'ezcbobobegghakl' words=list(data) string_s=list(map(chr,range(97,123))) final_=[] def ok(list_1,list_2): if not list_1: return 0 else: first = list_1[0] chunks = list_2[list_2.index(first):] track = [] for j, i in enumerate(list_1): if i in chunks: track.append(i) chunks=list_2[list_2.index(i):] else: final_.append(track) return ok(list_1[j:],list_2) final_.append(track) print(ok(words,string_s)) print(max(final_,key=lambda x:len(x))) output: ['b', 'e', 'g', 'g', 'h']
upvote count: 1

http://stackoverflow.com/q/48013561
tagged with: python-typing
favorite count: 0
has answer: http://stackoverflow.com/a/48013719
linked to: http://stackoverflow.com/q/44225788
tagged with: python
has comment: http://stackoverflow.com/comment/103010886
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48013719
type: Question
tagged with: mypy
possible better answer: http://stackoverflow.com/a/48048085
has answer: http://stackoverflow.com/a/48048085
upvote count: 20
has comment: http://stackoverflow.com/comment/82996070
has comment: http://stackoverflow.com/comment/82996015
has body: Trying to use static types in Python code, so mypy can help me with some hidden errors. It's quite simple to use with single variables real_hour: int = lower_hour + hour_iterator Harder to use it with lists and dictionaries, need to import additional typing library: from typing import Dict, List hour_dict: Dict[str, str] = {"test_key": "test_value"} But the main problem - how to use it with Dicts with different value types, like: hour_dict = {"test_key": "test_value", "test_keywords": ["test_1","test_2"]} If I don't use static typing for such dictionaries - mypy shows me errors, like: len(hour_dict['test_keywords']) - Argument 1 to "len" has incompatible type So, my question: how to add static types to such dictionaries? :)
score: 20
answer count: 2
has title: How to use static type checking using Dict with different value types in Python 3.6?
has comment: http://stackoverflow.com/comment/82996064
downvote count: 0

http://stackoverflow.com/q/47994661
type: Question
upvote count: 2
tagged with: arrays
answer count: 1
downvote count: 0
has title: Python: Matching Strings from an Array with Substrings from Texts in another Array
has body: Currently I am crawling a Webpage for newspaper articles using Pythons BeautifulSoup Library. These articles are stored in the object "details". Then I have a couple of names of various streets that are stored in the object "lines". Now I want to search the articles for the street names that are contained in "lines". If one of the street names is part of one of the articles, I want to safe the name of the street in an array. If there is no match for an article (the selected article does not contain any of the street names), then there should be an empty element in the array. So for example, let's assume the object "lines" would consist of ("Abbey Road", "St-John's Bridge", "West Lane", "Sunpoint", "East End"). The object "details" consists of 4 articles, of which 2 contain "Abbey Road" and "West Lane" (e.g. as in "Car accident on Abbey Road, three people hurt"). The other 2 articles don't contain any of names from "lines". Then after matching the result should be an array like this: []["Abbey Road"][]["West Lane"] I was also told to use Vectorization for this, as my original data sample is quite big. However I'm not familiar with using vectorization for String operations. Has anyone worked with this already? My Code currently looks like this, however this only returns "-1" as elements of my resulting array: from bs4 import BeautifulSoup import requests import io import re import string import numpy as np my_list = [] for y in range (0, 2): y *= 27 i = str(y) my_list.append('http://www.presseportal.de/blaulicht/suche.htx?q=' + 'einbruch' + '&amp;start=' + i) for link in my_list: # print (link) r = requests.get(link) r.encoding = 'utf-8' soup = BeautifulSoup(r.content, 'html.parser') with open('a4.txt', encoding='utf8') as f: lines = f.readlines() lines = [w.replace('\n', '') for w in lines] details = soup.find_all(class_='news-bodycopy') for class_element in details: details = class_element.get_text() sdetails = ''.join(details) slines = ''.join(lines) i = str.find(s…
has answer: http://stackoverflow.com/a/47996711
accepted answer: http://stackoverflow.com/a/47996711
has comment: http://stackoverflow.com/comment/82958071
favorite count: 0
tagged with: data-extraction
tagged with: python
tagged with: vectorization
has comment: http://stackoverflow.com/comment/82961461
tagged with: string-matching
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/47996247
tagged with: conda
tagged with: version
downvote count: 0
favorite count: 0
has body: The error log: Traceback (most recent call last): File "C:\Anaconda3\lib\site-packages\conda\exceptions.py", line 724, in __call__ return func(*args, **kwargs) File "C:\Anaconda3\lib\site-packages\conda\cli\main.py", line 78, in _main exit_code = do_call(args, p) File "C:\Anaconda3\lib\site-packages\conda\cli\conda_argparse.py", line 75, in do_call exit_code = getattr(module, func_name)(args, parser) File "C:\Anaconda3\lib\site-packages\conda\cli\main_info.py", line 313, in execute info_dict = get_info_dict(args.system) File "C:\Anaconda3\lib\site-packages\conda\cli\main_info.py", line 143, in get_info_dict conda_build_version = conda_build.__version__ AttributeError: module 'conda_build' has no attribute '__version__' I'm not sure what's happening, but I suspect it might have something to do with the fact that I cancelled creation of a virtualenv using ctrl-C in the CLI, because I accidentally initiated creation of one and didn't want to wait for it to execute fully. I never activated the environment though, and deleted the few files that had been set up in its folder. Any ideas on what might be the cause? Conda and all other packages are fully updated (conda v. 4.4.4, which I can see running the conda -V command). So far it is only the info command that throws this error, and I want to use it to check if there are other virtualenvs I need to clean up.
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: conda info throws version error
score: 1
has comment: http://stackoverflow.com/comment/82962039
has comment: http://stackoverflow.com/comment/82961900
type: Question
tagged with: info

http://stackoverflow.com/comment/82972860
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48002240
has text: Welcome to Stackoverflow. First see https://stackoverflow.com/help/how-to-ask. Then try `[float(thing.strip('$')) for thing in price]`

http://stackoverflow.com/comment/82806000
score: 0
type: AnswerComment
has text: try updating python first
comment on: http://stackoverflow.com/a/47918819
type: Comment

http://stackoverflow.com/q/48013391
has comment: http://stackoverflow.com/comment/82996067
downvote count: 0
has answer: http://stackoverflow.com/a/48028861
tagged with: db2
accepted answer: http://stackoverflow.com/a/48028861
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/82996269
has body: I am currently using a Windows 10 machine and Python 3.6.3 and have downloaded and installed the requirements listed here: https://www.ibm.com/support/knowledgecenter/en/SSSNY3_10.1.0/com.ibm.swg.im.dbclient.python.doc/doc/t0054367.html from the following link: https://www.ibm.com/support/knowledgecenter/en/SSSNY3_10.1.0/com.ibm.swg.im.dbclient.python.doc/doc/r0054697.html I have installed the ODBC driver (IBM DB2 ODBC Driver) and configured it in my ODBC Data Source Administrator interface on the Windows 10 machine. I have also done this for a SQL Server connection using the appropriate set up for that. The issue I have is that I am receiving the following error: Traceback (most recent call last): File "C:\Users\&lt;Username&gt;\Python\Test IBM Connection.py", line 6, in &lt;module&gt; ibm_db.connect("&lt;DSN&gt;","&lt;Username&gt;","&lt;Password&gt;") Exception: [IBM][CLI Driver] SQL1531N The connection failed because the name specified with the DSN connection string keyword could not be found in either the db2dsdriver.cfg configuration file or the db2cli.ini configuration file. Data source name specified in the connection string: "&lt;DSN&gt;". SQLCODE=-1531 I, of course have googled this issue to no avail. I am new to IBM_DB and it requirements and need help configuring the DSN to work properly. I have also attempted to run the db2dsdcfgfill - but have been unsuccessful, see here: https://www.ibm.com/support/knowledgecenter/en/SSEPGG_9.5.0/com.ibm.swg.im.dbclient.config.doc/doc/r0054557.html I am unsure what information needs to be in these files, and where they need to be and how to register them so the system is seeing them. I have been able to connect and query an SQL Server, but have not been able to connect to the IBM iSeries AS400 system. I have researched the many parts of the issue I am having but have not found any solutions for my issue. As requested I have added the following information: Connection String: ibm.connect("&lt;DSN&gt;", "&lt;Username&gt;…
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83026799
has comment: http://stackoverflow.com/comment/82995572
has comment: http://stackoverflow.com/comment/83015944
tagged with: python
type: AnsweredQuestion
has title: Python 3 and IBM_DB Setup Issues
score: 1
type: Question

http://stackoverflow.com/comment/82989375
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48009814
score: 0
has text: I do not have an opinion on this. The official Tensorflow repository uses 2 spaces as convention instead of 4 (I'm sure they did it for a reason) and I happen to be using PyCharm IDE (and PEP8 inspection tool). For this scenario I would rather just follow the Tensorflow convention and remove corresponding warnings in IDE - it's fit for purpose for now.

http://stackoverflow.com/q/47943081
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47960518
has body: Guys I am new to python and deeplearning world I tried to install pytorch using conda I get this Error... (base) C:\WINDOWS\system32&gt;conda install pytorch `Solving environment: failed PackagesNotFoundError: The following packages are not available from current channels: pytorch Current channels: https://repo.continuum.io/pkgs/main/win-64 https://repo.continuum.io/pkgs/main/noarch https://repo.continuum.io/pkgs/free/win-64 Couldnt post all the channels due to reputation issue on stackoverflow... Trying Pip for installing Pytorch It just opens pytorch site after this error: (base) C:\WINDOWS\system32>pip install pytorch Collecting pytorch Using cached pytorch-0.1.2.tar.gz Building wheels for collected packages: pytorch Running setup.py bdist_wheel for pytorch ... error Complete output from command C:\ProgramData\Anaconda3\python.exe -u -c "import setuptools, tokenize;file='C:\Users\micha\AppData\Local\Temp\pip-build-t86penrg\pytorch\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 C:\Users\micha\AppData\Local\Temp\tmpqmo4j08upip-wheel- --python-tag cp36: Traceback (most recent call last): File "", line 1, in File "C:\Users\micha\AppData\Local\Temp\pip-build-t86penrg\pytorch\setup.py", line 17, in raise Exception(message) Exception: You should install pytorch from http://pytorch.org Failed building wheel for pytorch Running setup.py clean for pytorch Failed to build pytorch Installing collected packages: pytorch Running setup.py install for pytorch ... error Complete output from command C:\ProgramData\Anaconda3\python.exe -u -c "import setuptools, tokenize;file='C:\Users\micha\AppData\Local\Temp\pip-build-t86penrg\pytorch\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record C:\Users\micha\AppData\Local\Temp\pip-vms7q49e-record\install-record.txt --single-version-externally-mana…
favorite count: 0
tagged with: python
type: AnsweredQuestion
tagged with: pytorch
accepted answer: http://stackoverflow.com/a/47960518
upvote count: 2
tagged with: pip
type: Question
tagged with: conda
has title: pytorch PIP and CONDA error?
tagged with: deep-learning
score: 2

http://stackoverflow.com/comment/82703620
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/47869308
has text: If two paths have the same directory, the second one will overwrite the first one. Furthermore it is advicable not do path processing yourself.

http://stackoverflow.com/q/47856004
tagged with: pyqt
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/47857802
tagged with: macos
has body: Problem When running the following PyQt5 code on MacOS (Sierra 10.12.6) self.tray_icon = QtWidgets.QSystemTrayIcon(QtGui.QIcon("icon/path"), self) self.tray_icon.activated.connect(self.on_systray_activated) [...] def on_systray_activated(self, i_reason): logging.debug("entered on_systray_activated. i_reason = " + str(i_reason)) we get the activation reason QSystemTrayIcon::Trigger even when right clicking On other systems (for example XFCE) we get QSystemTrayIcon::Context when the user right clicks Question How can we distinguish between left and right click on the systray icon on MacOS?
type: UnansweredQuestion
upvote count: 1
tagged with: qsystemtrayicon
tagged with: qt
has title: How to distinguish between left and right click with QSystemTrayIcon
type: Question

http://stackoverflow.com/q/47873707
possible better answer: http://stackoverflow.com/a/47873798
has answer: http://stackoverflow.com/a/47873798
type: Question
upvote count: 2
answer count: 2
has title: Django REST Framework - Filtering against the URL
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/47873794
accepted answer: http://stackoverflow.com/a/47873794
favorite count: 0
has body: I am using the Django REST Framework toolkit with Django 1.11 and I am trying to filter the results against the url. Here is my setup: models.py: from django.db import models class Package(models.Model): name = models.CharField(max_length=255, unique=True) def __str__(self): return self.name serializers.py: from rest_framework import serializers from .models import Package class PackageSerializer(serializers.ModelSerializer): class Meta: model = Package fields = ('name',) views.py: from rest_framework import viewsets from .models import Package from .serializers import PackageSerializer class PackageViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = PackageSerializer queryset = Package.objects.all() urls.py from django.conf.urls import url, include from django.contrib import admin from rest_framework import routers router = routers.DefaultRouter() router.register(r'package', views.PackageViewSet) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/v1/', include(router.urls)), ] Currently when I use this I can filter the results by the id field: http://127.0.0.1:8000/api/v1/package/1/ I am hoping to filter the results by the name field of my package model instead by using this: http://127.0.0.1:8000/api/v1/package/basic/ How would I be able to accomplish this?
tagged with: python
downvote count: 0
tagged with: django
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/82727669
type: Comment
type: QuestionComment
has text: @furas When I run only one script, it works perfectly. So I guess the problem focusing on what's wrong when two crawlers run simultaneously.
comment on: http://stackoverflow.com/q/47880624
score: 0

coinbase-api
tags question: http://stackoverflow.com/q/47873006
type: Tag
tags question: http://stackoverflow.com/q/47999982
tag name: coinbase-api

http://stackoverflow.com/q/47958859
has comment: http://stackoverflow.com/comment/82886920
answer count: 0
type: Question
has title: MemoryError , Create Pandas.DataFrame
tagged with: dataframe
score: 0
has comment: http://stackoverflow.com/comment/82886971
tagged with: pandas
has comment: http://stackoverflow.com/comment/82886897
has comment: http://stackoverflow.com/comment/82888319
has comment: http://stackoverflow.com/comment/82886916
tagged with: python-3.x
type: UnansweredQuestion
has body: my code is this : pd.DataFrame(testMatrix, index = [0 for x in range(25000)], columns = testFeatureNames) by running this code this error is display: MemoryError testMatrix has 25000 rows and 56000 columns! how can i fix this?
has comment: http://stackoverflow.com/comment/82889074
tagged with: python

http://stackoverflow.com/q/47892384
has comment: http://stackoverflow.com/comment/82759250
score: 3
has comment: http://stackoverflow.com/comment/92387139
tagged with: http://stackoverflow.com/tag/r
has comment: http://stackoverflow.com/comment/82790062
has body: I am trying to change the hovertext for histogram plots created by plotly. By default, it creates (bin - bin, frequency) on hover. I would like to annotate it so it's something like the following: Bins: bin - bin Frequency: frequency I currently cannot figure out how to target the histogram variables so I can change the text attribute. The following is example code: library(plotly) test &lt;- data.frame(x = rnorm(50)) plot_ly(test, x = ~x, type = "histogram", mode = "text", text = paste("Bins:", "&lt;/br&gt;Frequency:"))
downvote count: 0
favorite count: 0
tagged with: python
has title: Changing hover text in histogram bins plotly
has comment: http://stackoverflow.com/comment/92860305
answer count: 0
upvote count: 3
type: UnansweredQuestion
tagged with: plotly
type: Question

http://stackoverflow.com/q/47876828
has comment: http://stackoverflow.com/comment/82719456
possible better answer: http://stackoverflow.com/a/47876904
has answer: http://stackoverflow.com/a/47876904
type: Question
tagged with: numpy
tagged with: arrays
score: 10
answer count: 3
upvote count: 10
linked to: http://stackoverflow.com/q/41325427
has title: How to optimize a nested for loop in Python
favorite count: 0
accepted answer: http://stackoverflow.com/a/47876994
has body: So I am trying to write a python function to return a metric called the Mielke-Berry R value. The metric is calculated like so: The current code I have written works, but because of the sum of sums in the equation, the only thing I could think of to solve it was to use a nested for loop in Python, which is very slow... Below is my code: def mb_r(forecasted_array, observed_array): """Returns the Mielke-Berry R value.""" assert len(observed_array) == len(forecasted_array) y = forecasted_array.tolist() x = observed_array.tolist() total = 0 for i in range(len(y)): for j in range(len(y)): total = total + abs(y[j] - x[i]) total = np.array([total]) return 1 - (mae(forecasted_array, observed_array) * forecasted_array.size ** 2 / total[0]) The reason I converted the input arrays to lists is because I have heard (haven't yet tested) that indexing a numpy array using a python for loop is very slow. I feel like there may be some sort of numpy function to solve this much faster, anyone know of anything?
has comment: http://stackoverflow.com/comment/82719576
has comment: http://stackoverflow.com/comment/82719478
tagged with: python
has answer: http://stackoverflow.com/a/47876994
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48062216
downvote count: 0

http://stackoverflow.com/a/47945850
score: 0
has comment: http://stackoverflow.com/comment/82861444
type: Answer
answers question: http://stackoverflow.com/q/47945761
has body: You can try this: s = [len(i) for a, b in fourier_dict.items() for i in b]

http://stackoverflow.com/comment/82917073
has text: busy now,will update later.This should override get_paginated_response method
comment on: http://stackoverflow.com/a/47973755
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/a/47905654
accepted answer of: http://stackoverflow.com/q/47905378
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82798414
type: Answer
has body: When you print a collection with Python 2, for instance a dict or a list, Python uses the repr() function to print the items of the collections. In the case of a string (unicode string) you get escaped characters… To do what you want, using Python 2, you need to print the dictionary yourself, like this: &gt;&gt;&gt; d = {"key": [u"äüö"]} &gt;&gt;&gt; for k, v in d.iteritems(): ... print(u"{k}: [{v}]".format(k=k, v=u", ".join(u"'{0}'".format(i) for i in v))) You get: key: ['äüö']
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47905378

http://stackoverflow.com/comment/82844550
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47937240
score: 0
has text: Let me get this straight. You want a class for Cars. You want a class for nodes that basically connect two cars. You want a class LinkedList whose object contains information about **all** cars ordered in price. True or something wrong here?

http://stackoverflow.com/comment/82849618
score: 0
type: Comment
type: QuestionComment
has text: I found that [post](https://stackoverflow.com/questions/6807808/highlighting-and-selecting-text-with-python-curses) which helped me a lot.
comment on: http://stackoverflow.com/q/47925182

http://stackoverflow.com/comment/82763052
type: Comment
score: 0
has text: Which python did your pycharm show? In `Preferences -> Project -> Project intepreter`
comment on: http://stackoverflow.com/q/47897462
type: QuestionComment

http://stackoverflow.com/q/47920639
tagged with: jenkins
tagged with: selenium
upvote count: 21
has title: How to fix "WebDriverException: Message: connection refused"?
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/83145148
possible better answer: http://stackoverflow.com/a/48088969
has answer: http://stackoverflow.com/a/60426112
tagged with: firefox
has answer: http://stackoverflow.com/a/48088969
has answer: http://stackoverflow.com/a/47921529
score: 20
linked to: http://stackoverflow.com/q/46088442
has comment: http://stackoverflow.com/comment/83180617
has body: I am using a very complex setup to test various non-public webpages. I use jenkins to run the python-selenium tests within a dockerimage. That way, I am completly independent of the jenkins environment and can create my own environment. In this environment I have the following software installed: Firefox: 57.0.1 geckodriver: 0.18.0 nosetests: 1.3.7 selenium: 3.8.0 The selenium tests create the WebDriver the following way: profile = webdriver.FirefoxProfile() profile.set_preference("browser.download.dir", self.downloadpath) profile.set_preference("browser.download.folderList", 2) profile.set_preference("browser.download.useDownloadDir", True) profile.set_preference("browser.download.manager.showWhenStarting", False) profile.set_preference("pdfjs.disabled", True) profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/force-download, image/png, text/html, text/plain, " "image/tiff, text/csv, application/zip, application/octet-stream") profile.set_preference("browser.download.manager.alertOnEXEOpen", False) profile.set_preference("browser.download.manager.focusWhenStarting", False) profile.set_preference("browser.helperApps.alwaysAsk.force", False) profile.set_preference("browser.download.manager.alertOnEXEOpen", False) profile.set_preference("browser.download.manager.closeWhenDone", True) profile.set_preference("browser.download.manager.showAlertOnComplete", False) profile.set_preference("browser.download.manager.useWindow", False) profile.set_preference("services.sync.prefs.sync.browser.download.manager.showWhenStarting", False) self.driver = webdriver.Firefox(profile, log_path = logfile) where logfile and self.downloadpath are two valid paths in the docker setup. The whole test suite consists of 6 independant test cases, each with the same setup as above. They normally run fine and complete without problems. But without any change to the tests or the general setup, a test sometimes fails with the following error message: File "/root/tests/bsp_u…
favorite count: 0
has answer: http://stackoverflow.com/a/55093287
linked to: http://stackoverflow.com/q/39547598
accepted answer: http://stackoverflow.com/a/47921529
tagged with: geckodriver
tagged with: python
answer count: 4
linked to: http://stackoverflow.com/q/48045663
type: AnsweredQuestion

http://stackoverflow.com/comment/83263177
score: 0
type: Comment
type: QuestionComment
has text: Hello Symmetric, thank you for your help. I have edit my question with the HTTP response and the request headers. Is there any other way to get more info about the 400 response?
comment on: http://stackoverflow.com/q/47964694

http://stackoverflow.com/comment/82993918
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48012549
has text: I might also suspect you have a typo: `SELECT username, password FROM accounts...` you've named table `account`
score: 0

http://stackoverflow.com/comment/82703787
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47869283
has text: @MayurMahajan So, that means it worked... unless you have some other problem? To my knowledge, there isn't any difference.

http://stackoverflow.com/comment/82748999
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47887790
has text: IMHO you are chasing the wrong rabbit here. Maybe you could find a way to keep an open channel, but it will certainly be harder that what you seem to expect, because you will have to ready to suffer output buffering from the remote. My advice is to strip down the profile to only what is required for your commands. It should be much simpler... Of course, your interactiver profile will be much longer, but it could source the non-interactive one to avoid duplication. Not what you asked for, so only a comment, but you really should think about that way.

http://stackoverflow.com/q/47923327
accepted answer: http://stackoverflow.com/a/47923761
has title: Applying re.search function to column in Python
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/82814373
has answer: http://stackoverflow.com/a/47923761
type: AnsweredQuestion
downvote count: 0
type: Question
score: 3
has comment: http://stackoverflow.com/comment/82816472
has comment: http://stackoverflow.com/comment/82814269
has comment: http://stackoverflow.com/comment/82814430
has body: I have the following Python code (I want the first match of a specific number in a text field): import numpy as np import pandas data = {'A': [1, 2, 3], 'B': ['bla 4044 bla', 'bla 5022 bla', 'bla 6045 bla']} df = pandas.DataFrame(data) def fun_subjectnr(column): column = str(column) subjectnr = re.search(r"(\b[4][0-1][0-9][0-9]\b)",column) subjectnr1 = re.search(r"(\b[2-3|6-8][0-9][0-9][0-5]\b)",column) subjectnr = np.where(subjectnr == "" and subjectnr1 != "", subjectnr1, subjectnr) return subjectnr1 df['C'] = df['B'].apply(fun_subjectnr) Wanted output: A B C 1 bla 4044 bla 4044 2 bla 5022 bla None 3 bla 6045 bla 6045 It doesn't seem to work. When I add a [0] to the regex code, it gives an error...(subjectnr = re.search(r"(\b[4][0-1][0-9][0-9]\b)",column)[0]) Who knows what to do? Thanks in advance!
upvote count: 3
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/82814522
favorite count: 0

http://stackoverflow.com/a/47858283
has body: In Python, usually calculations in the integer world are done with arbitrary size. So it means that if you calculate 2**1000000000, it will not do this with a 32-bit integer, or a 64-bit integer, but it uses a long in Python-2.x, or an int in Python-3.x (but an int in Python-3.x) has arbitrry size. 2**1000000000 is however a huge number. It would require 1'000'000'000 bits, or 125'000'000 bytes at least. It also will calculate the power using an algorithm and has to represent the intermediate results as well. In CPython, it requires 133 MB of memory to store the value. But that is not the end of it. Now you want to convert that to a string. The string will take approximately 301'029'995 digits. Each digits takes at least one byte. So this will take an extra 301 MB of memory, furthermore it will require a lot of work to calculate the decimal representation: each iteration, we have to perform a modulo 10 check, and furthermore we need to devide the number by 10, so it works (at least) quadratic in the number of digits of the number. Since the number of digits is huge (~300 million), it thus requires a huge amount of work. The len(..) operation is not very expensive, but the above steps are expensive in both memory (and somwhat in CPU time, especially the conversion to a string). Memory might seem like a factor we can ignore, but in case we consume huge amounts of memory, the system can slow down, or even freeze. Usually if the system runs out of RAM memory, it will start using swap memory: it will swap out parts of RAM memory to the hard disk drive, which is very slow (compared to RAM memory). The above sketched way to obtain the number of digits is definitely not a good one. It will for instance not work with negative numbers as well. There is a mathematical concept called logarithms, and if you take the log10 of a number, you get the number of digits minus one. There are some extra problems here: the log10 of negative numbers is not define; and nor is the log10 of z…
type: Answer
answers question: http://stackoverflow.com/q/47858187
upvote count: 4
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/82681152
has comment: http://stackoverflow.com/comment/82681042

http://stackoverflow.com/q/47906005
has body: I'm relatively new to python, and wondering if I'm doing something that may cause trouble down the line (or have gone about this in completely the wrong way); setting a class attribute of a common inherited bases classes from within a parent __bases__ attribute ... To explain: I have half a dozen derived classes (A, B, C...) all inheriting a base class called LevelMixin. class A(LevelMixin): .... class B(LevelMixin): .... class C(LevelMixin): .... class LevelMixin(object): """Contains all schema meta-info for a particular level""" _unpickleable = False def __getstate__(self): if LevelMixin._unpickleable: # modify state to hide private instance attributes else: state = self.__dict__.copy() The derived classes are instantiated in a nested structure, such that properties on A are instances of B and so on: a=A(b=B(c=C(d=D()))) When it's time to pickle an instance of A, I want all the classes that subclass LevelMixin to have access to the same "unpickleable" attribute (so i can set it once rather than pass it down through the code as each class is instantiated). e.g, a._unpickleable=True, a.b._unpickleable=True, a.b.c._unpickleable=True To this end, I've accessed the LevelMixin class attribute dynamically by: if unpickleable: # override the Level class attribute A.__bases__[0]._unpickleable = True else: A.__bases__[0]._unpickleable = False schema.append( A( b=B( ...) ) ) but this feels hacky. A similar approach has been suggested for the accepted answer here, but is this the right way to go? Many thanks in advance!
has comment: http://stackoverflow.com/comment/82815526
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82814554
has comment: http://stackoverflow.com/comment/82781508
has comment: http://stackoverflow.com/comment/82814358
has title: Setting a baseclass class attribute dynamically from within parent class __bases__ attribute
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/82803679
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82815072
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/82803343
has comment: http://stackoverflow.com/comment/82805499
linked to: http://stackoverflow.com/q/9760595
upvote count: 1

http://stackoverflow.com/q/47985177
accepted answer: http://stackoverflow.com/a/47985262
type: Question
linked to: http://stackoverflow.com/q/34304044
has comment: http://stackoverflow.com/comment/82950086
possible better answer: http://stackoverflow.com/a/47985331
score: 0
has comment: http://stackoverflow.com/comment/82939416
answer count: 3
tagged with: sqlite
has title: Hidden .db files using Python and SQLite3
has comment: http://stackoverflow.com/comment/82939508
has comment: http://stackoverflow.com/comment/82940299
has comment: http://stackoverflow.com/comment/82939460
tagged with: python
has answer: http://stackoverflow.com/a/47985331
has comment: http://stackoverflow.com/comment/82939465
has comment: http://stackoverflow.com/comment/82939587
type: AnsweredQuestion
has body: I am using sqlite3 and python for a new website I am creating. The problem is, the "files_storage.db" file I am trying to create will not appear in any Windows 10 Folder Window, PyCharm's Directory View, nor will it appear via the command line interface. The catch to this is, if I execute my python script multiple times, I get an error that states the database file already exists... So this file is somewhere, I guess it is a game of cat and mouse to find it. I have ran into this problem before, but I have ALWAYS been able to find the file via the command line. Usually, I wouldn't both yall with such a question but, this is really irking me and I am going to run into serious issues when it comes time to put this baby on a server. :( thanks in advance, and here's some screenshots I suppose.
has comment: http://stackoverflow.com/comment/82961936
has answer: http://stackoverflow.com/a/65982389
has answer: http://stackoverflow.com/a/47985262

http://stackoverflow.com/comment/82901493
has text: I just tried with echo 'export PATH=$PATH:/Applications/anaconda/pkgs/geckodriver (no extra space) but no dice. :(
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47965756
score: 0

http://stackoverflow.com/a/47870890
score: -2
upvote count: 0
has body: Just run your code, read the error, and deduct something from it. When you run it, here is the error message : Traceback (most recent call last): File "C:\Users\Kilian\Desktop\Code\Garbage\tmp.py", line 7, in &lt;module&gt; from temp2 import prnt File "C:\Users\Kilian\Desktop\Code\Garbage\temp2.py", line 1, in &lt;module&gt; from tmp import a File "C:\Users\Kilian\Desktop\Code\Garbage\tmp.py", line 7, in &lt;module&gt; from temp2 import prnt ImportError: cannot import name prnt Your script is trying to import something it already has tried to import earlier on. Python is probably deducing that it can't import it. :)
has comment: http://stackoverflow.com/comment/82707431
type: Answer
downvote count: 2
has comment: http://stackoverflow.com/comment/82707023
answers question: http://stackoverflow.com/q/47870681

http://stackoverflow.com/comment/82865616
score: 1
has text: Assertions are mostly for checking program errors, those that imply program code changes to fix (that is bugs in the code, things that should neve happen, that's why `assert` only works if `__debug__` is True), not runtime errors or conditions that may or may not arise, or other special events. For those (think `Exceptions`) use a `try` block
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47947676

http://stackoverflow.com/q/47880624
tagged with: python
tagged with: python-requests
has title: IndexError: list index out of range, When I run two python scripts at the same time
has comment: http://stackoverflow.com/comment/82727817
tagged with: web-crawler
type: Question
has comment: http://stackoverflow.com/comment/82727972
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/82727689
has body: I want to crawl data from a website, which is sorted by different province. To be faster, I try to run two or more python scripts to crawl each province at the same time. The only difference between two scripts is they crawl different url sets. Every time they worked well at the first 30 seconds or 1 minute. But later I got the below error in each script, and they arised simultaneously every time: Traceback (most recent call last): File "EOLGrades-A.py", line 157, in &lt;module&gt; dealEachCollege(url_2,tableName2,cNameList[i]) File "EOLGrades-A.py", line 58, in dealEachCollege insertData(getData(sp),tableName,collegeName) File "EOLGrades-A.py", line 33, in getData if FAtd[x+j].text == '--' or FAtd[x+j].text ==' ': IndexError: list index out of range Traceback (most recent call last): File "EOLGrades-B.py", line 157, in &lt;module&gt; dealEachCollege(url_2,tableName2,cNameList[i]) File "EOLGrades-B.py", line 58, in dealEachCollege insertData(getData(sp),tableName,collegeName) File "EOLGrades-B.py", line 33, in getData if FAtd[x+j].text == '--' or FAtd[x+j].text ==' ': IndexError: list index out of range My getData Method: def getData(soup,count): FAtr = soup.find_all(name='tr') FAtd = soup.find_all(name='td') m = [([0] * 6) for i in range(count)] x = 0 if(len(FAtd)&lt;=1): print("no data") return ['0'] else: for i in range(count): for j in range(6): if FAtd[x+j].text == '--' or FAtd[x+j].text ==' ': m[i][j] = None else: content = FAtd[x+j].text.strip() m[i][j] = content x= x+6 return m count is from getCount Method: def getCount(soup): FAtr = soup.find_all(name='tr') count = len(FAtr) - 1 return count dealEachCollege Method: def dealEachCollege(URL,tableName,collegeName): page = s.get(URL,headers=headers) page.encoding='utf-8' sp = BeautifulSoup(page.text,"html.parser") count = getCount(sp) insertData(getData(sp,count),tableName,collegeName,count) page.close() insertData Method: def insertData(dataList,tableName,collegeName,count): try: m=dataList if m[0]=='0': retu…
score: 0
has comment: http://stackoverflow.com/comment/82727669
has comment: http://stackoverflow.com/comment/82727447
answer count: 0
has comment: http://stackoverflow.com/comment/82727372
type: UnansweredQuestion

http://stackoverflow.com/comment/82723476
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47878386
has text: Can you try printing `str(narticle)` and see what it says? This may be the interpreter calling `__repr__` on your object instead of `__str__`. Also is the `def __str__` method actually a part of the Narticle model? It's missing from the source in your Narticle model.

http://stackoverflow.com/comment/82752090
comment on: http://stackoverflow.com/q/47892431
score: 0
has text: `EmiCtry` is calculated from other data and is an `numpy.array()` with `float` type values.
type: Comment
type: QuestionComment

computer-vision
tags question: http://stackoverflow.com/q/47911104
tags question: http://stackoverflow.com/q/47909321
tags question: http://stackoverflow.com/q/47952249
tags question: http://stackoverflow.com/q/47967070
tags question: http://stackoverflow.com/q/48003535
tags question: http://stackoverflow.com/q/47990350
type: Tag
tag name: computer-vision
tags question: http://stackoverflow.com/q/47984976
tags question: http://stackoverflow.com/q/47949828

http://stackoverflow.com/q/47972638
upvote count: 11
has answer: http://stackoverflow.com/a/70542315
has answer: http://stackoverflow.com/a/58323807
answer count: 3
has answer: http://stackoverflow.com/a/47984810
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has body: I have code like this: import click @click.group() def entry_point(): pass entry_point.add_command(lidtk.data.download_documents.main) entry_point.add_command(lidtk.data.create_ml_dataset.main) entry_point.add_command(lidtk.classifiers.text_cat.textcat_ngram.cli) which gives the help text: lidtk --help Usage: lidtk [OPTIONS] COMMAND [ARGS]... Options: --help Show this message and exit. Commands: create-dataset Create sharable dataset from downloaded... download Download 1000 documents of each language. textcat which is over all pretty close to what I want. But I would like to change the order to: Commands: download Download 1000 documents of each language. create-dataset Create sharable dataset from downloaded... textcat How can this be done using click?
tagged with: python
score: 11
tagged with: command-line-interface
type: Question
tagged with: python-click
has title: How can I define the order of click sub-commands in "--help"
downvote count: 0

sensors
type: Tag
tags question: http://stackoverflow.com/q/48002940
tag name: sensors

http://stackoverflow.com/comment/82862970
has text: @TylerNG happy coding and happy holiday :-)
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47945997

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/47882514
tags question: http://stackoverflow.com/q/47952473
tags question: http://stackoverflow.com/q/47926302
type: Tag

http://stackoverflow.com/a/47886771
type: Answer
score: 2
downvote count: 0
has body: You can specify the same log file from different python files: logzero.logfile("logfile.log", maxBytes=1000000, backupCount=3) It is mentioned in the documentation (Features section): Multiple loggers can write to the same logfile (also across multiple Python files).
accepted answer of: http://stackoverflow.com/q/47886582
upvote count: 2
answers question: http://stackoverflow.com/q/47886582
type: AcceptedAnswer

http://stackoverflow.com/q/47959076
score: 0
has answer: http://stackoverflow.com/a/47962158
tagged with: tcltk
has comment: http://stackoverflow.com/comment/82887725
tagged with: tkinter
has title: Trouble with failing to build _tkinter after installing binary tcltk
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82887678
tagged with: python
has comment: http://stackoverflow.com/comment/82887429
has body: I am running linux and python 2.7.14 I have successfully installed the binary version of tcltk. I installed it into the same directory as python27 such that the following directories were all added in the same folders, namely: include, lib, etc. The bits were not all found when I configured python again so when I checked the setup.py file it mentioned I could do the following, which I did: make clean ./configure --with-tcltk-includes="-I/home2/bishopk2/python27/include" -- with-tcltk-libs="-L/home2/bishopk2/python27/lib/tcllib1.18 -ltclm.n -L/ home2/bishopk2/python27/lib/tklib0.6 -ltkm.n" make TCLTK_INCLUDES="/home2/bishopk2/python27/include" TCLTK_LIBS="/home2/bishopk2/python27/lib" I have tried all permutations of this (i.e., with and without the tcllib1.18, ltclm.n, etc., etc.) I am not sure the best way to share a config.log on stack overflow but here is a link: https://www.pharmacoengineering.com/share-a-file/ (I made the pdf downloadable) I had to save it as a pdf file so that it would upload to wordpress. When I looked at it, I am not sure why the tcl.h file could not be found because when I: find . -name "tcl.h" It says that it is in my /home2/bishopk2/python27/include folder. All of the libraries are there and it should be able to connect Tkinter with my tcl and tk libraries. Any help would be greatly appreciated. Best wishes, Corey
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/82887468

http://stackoverflow.com/comment/82814778
type: QuestionComment
comment on: http://stackoverflow.com/q/47922948
has text: explain me what exactly you are trying to perform?
score: 0
type: Comment

http://stackoverflow.com/comment/83373634
comment on: http://stackoverflow.com/a/47964139
type: Comment
has text: I'm not an expert, but according to [this](https://bokeh.pydata.org/en/latest/docs/user_guide/server.html#deployment-scenarios), and [this](https://bokeh.pydata.org/en/latest/docs/user_guide/server.html#load-balancing-with-nginx) or [this](https://bokeh.pydata.org/en/latest/docs/user_guide/server.html#scaling-the-server), I think bokeh is useable for "wide scale". There is probably other solutions as well, but I don't know any. The only limit I found with bokeh is slow/laggy user experience with very large dataset (>300k). But there are [solutions](https://github.com/bokeh/datashader)
score: 0
type: AnswerComment

http://stackoverflow.com/a/48004138
accepted answer of: http://stackoverflow.com/q/48003559
downvote count: 0
score: 1
has body: Use matplotlib.pylab.cm to colorize the image. #!/usr/bin/python3 # 2017.12.28 16:26:26 CST import matplotlib.pyplot as plt from matplotlib.pylab import cm import numpy as np import cv2 ## use matplot jet for opencv def colorize(img): gray = None if img.ndim == 2: gray = img.copy() if len(img.shape) == 3: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) canvas = np.uint8(cm.jet(gray)*255) canvas = cv2.cvtColor(canvas, cv2.COLOR_RGBA2BGR) return canvas ## process img = cv2.imread("test.png") res = colorize(img) cv2.imwrite("res.png", res) Example 1: Generate the colorized the image (as the preview code). Example 2: Colorize the same data in Matplotlib (in jet) and OpenCV(using my function colorize).
upvote count: 1
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/48003559

http://stackoverflow.com/a/56869423
upvote count: 6
has body: You can now do this using pytest-cases: from pytest_cases import fixture @fixture(unpack_into="foo,bar") def foobar(): return "blah", "whatever" def test_stuff(foo, bar): assert foo == "blah" and bar == "whatever" See the documentation for more details (I'm the author by the way)
has comment: http://stackoverflow.com/comment/100336077
answers question: http://stackoverflow.com/q/47988664
score: 6
type: Answer
has comment: http://stackoverflow.com/comment/100344525
downvote count: 0

http://stackoverflow.com/a/47903980
type: Answer
score: 2
downvote count: 0
has body: This would be one approach I think ? import pandas as pd games = pd.DataFrame(data = {"home" : ["A", "B", "A", "A", "B"], "away" : ["B", "C", "C", "B", "A"], "homescore" : [0, 1, 4, 3, 0], "awayscore" : [1, 2, 2, 1, 1]}) games["homewin"] = games.apply(lambda row: 1 if row.homescore &gt; row.awayscore else 0, axis=1) g = games.groupby(by=["home", "homewin"]).size().reset_index(name="games") g["homewin"] = g.apply(lambda row: row.homewin*row.games, axis=1) g = g.groupby(by=["home"]).sum() g["homewinratio"] = g["homewin"]/g["games"] g Out[105]: homewin games homewinratio home A 2 3 0.666667 B 0 2 0.000000 Although I'm sure there are much better ones - I'm curious too
upvote count: 2
has comment: http://stackoverflow.com/comment/82775800
answers question: http://stackoverflow.com/q/47903414

machine-learning
tags question: http://stackoverflow.com/q/47880161
tags question: http://stackoverflow.com/q/47912045
tags question: http://stackoverflow.com/q/47988983
tags question: http://stackoverflow.com/q/47903504
tags question: http://stackoverflow.com/q/47891655
tags question: http://stackoverflow.com/q/47934170
tags question: http://stackoverflow.com/q/47955463
tags question: http://stackoverflow.com/q/47856092
tags question: http://stackoverflow.com/q/47932396
tags question: http://stackoverflow.com/q/47926343
tags question: http://stackoverflow.com/q/47946488
tags question: http://stackoverflow.com/q/47899463
tags question: http://stackoverflow.com/q/48004171
tags question: http://stackoverflow.com/q/48010445
tags question: http://stackoverflow.com/q/47951486
tags question: http://stackoverflow.com/q/47906412
tags question: http://stackoverflow.com/q/47965783
tags question: http://stackoverflow.com/q/47942707
tags question: http://stackoverflow.com/q/47953338
tags question: http://stackoverflow.com/q/47891429
tags question: http://stackoverflow.com/q/47947049
tags question: http://stackoverflow.com/q/47918681
tags question: http://stackoverflow.com/q/48003535
tags question: http://stackoverflow.com/q/47946413
tags question: http://stackoverflow.com/q/47954405
tags question: http://stackoverflow.com/q/47965149
tag name: machine-learning
tags question: http://stackoverflow.com/q/47909588
tags question: http://stackoverflow.com/q/47877278
tags question: http://stackoverflow.com/q/47925346
tags question: http://stackoverflow.com/q/48011874
tags question: http://stackoverflow.com/q/47941232
tags question: http://stackoverflow.com/q/47966665
tags question: http://stackoverflow.com/q/47968975
tags question: http://stackoverflow.com/q/47980936
tags question: http://stackoverflow.com/q/48002981
tags question: http://stackoverflow.com/q/47991379
tags question: http://stackoverflow.com/q/47964765
tags question: http://stackoverflow.com/q/48003185
tags question: http://stackoverflow.com/q/47965276
tags question: http://stackoverflow.com/q/47928554
type: Tag
tags question: http://stackoverflow.com/q/47902168
tags question: http://stackoverflow.com/q/47970688
tags question: http://stackoverflow.com/q/48001383
tags question: http://stackoverflow.com/q/47941891
tags question: http://stackoverflow.com/q/47878901
tags question: http://stackoverflow.com/q/47986662
tags question: http://stackoverflow.com/q/47968153
tags question: http://stackoverflow.com/q/47864509
tags question: http://stackoverflow.com/q/47940731
tags question: http://stackoverflow.com/q/47876999
tags question: http://stackoverflow.com/q/48001211
tags question: http://stackoverflow.com/q/47873366
tags question: http://stackoverflow.com/q/47984835
tags question: http://stackoverflow.com/q/47884788
tags question: http://stackoverflow.com/q/47945785
tags question: http://stackoverflow.com/q/47945556
tags question: http://stackoverflow.com/q/47946942
tags question: http://stackoverflow.com/q/47884862
tags question: http://stackoverflow.com/q/47911104
tags question: http://stackoverflow.com/q/47945077
tags question: http://stackoverflow.com/q/47898326
tags question: http://stackoverflow.com/q/47919853
tags question: http://stackoverflow.com/q/47961811
tags question: http://stackoverflow.com/q/47916335
tags question: http://stackoverflow.com/q/47902118
tags question: http://stackoverflow.com/q/47970716
tags question: http://stackoverflow.com/q/47968453
tags question: http://stackoverflow.com/q/47889999
tags question: http://stackoverflow.com/q/47934622
tags question: http://stackoverflow.com/q/47999271
tags question: http://stackoverflow.com/q/47957151
tags question: http://stackoverflow.com/q/47956261
tags question: http://stackoverflow.com/q/47892066
tags question: http://stackoverflow.com/q/47945139
tags question: http://stackoverflow.com/q/47948384
tags question: http://stackoverflow.com/q/47992091
tags question: http://stackoverflow.com/q/47952249
tags question: http://stackoverflow.com/q/48003074

http://stackoverflow.com/q/47966558
accepted answer: http://stackoverflow.com/a/47967156
type: Question
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/47967156
has body: I need to groupby dataframe df = pd.DataFrame({'id': [111, 111, 111, 111, 111, 222, 222], 'domain': ['vk.com', 'facebook.com', 'facebook.com', 'twitter.com', 'vk.com', 'facebook.com', 'twitter.com'], 'time': ['2017-01-12', '2017-01-12', '2017-01-12', '2017-01-13', '2017-01-12', '2017-01-14', '2017-01-14'], 'duration': [10, 20, 5, 12, 34, 12, 4]}) I use df.groupby([df.id, df.domain]).agg({'duration':'sum', 'time': 'first'}).reset_index().reindex(columns=df.columns) And get domain duration id time 0 facebook.com 25 111 2017-01-12 1 twitter.com 12 111 2017-01-13 2 vk.com 44 111 2017-01-12 3 facebook.com 12 222 2017-01-14 4 twitter.com 4 222 2017-01-14 But desire output is: domain duration id time vk.com 10 111 2017-01-12 facebook.com 25 111 2017-01-12 vk.com 34 111 2017-01-12 twitter.com 12 111 2017-01-13 facebook.com 12 222 2017-01-14 twitter.com 4 222 2017-01-14 How can I fix that?
tagged with: python
has answer: http://stackoverflow.com/a/47966687
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82902708
score: 1
has comment: http://stackoverflow.com/comment/82902665
possible better answer: http://stackoverflow.com/a/47966687
upvote count: 1
has title: Pandas: groupby neighboring identical elements

http://stackoverflow.com/comment/82706010
type: QuestionComment
has text: i.e. you are looking for the python equivalent of JuMP.jl
score: 2
comment on: http://stackoverflow.com/q/47870264
type: Comment

traitsui
tag name: traitsui
tags question: http://stackoverflow.com/q/47932680
type: Tag

http://stackoverflow.com/comment/82693048
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47863280
has text: Another problem could be antialiasing. I've extended my post.
score: 0

http://stackoverflow.com/a/48000705
upvote count: 16
type: Answer
has body: There are bunch of ways that you could do this, and you seem to have stumbled on the only way that doesn't work. These all work for me: df["one"].agg("mean") df.agg({"one": "mean"}) df["one"].agg(np.mean) df.agg({"one": np.mean}) Looking at the source code, it appears that when you use average it's casting the DataFrame to be a numpy array, and then mean is taking the row-wise averages by default. Because in the base case (no weights) average actually calls mean. See def mean(a, axis=None, dtype=None, out=None, keepdims=np._NoValue): kwargs = {} if keepdims is not np._NoValue: kwargs['keepdims'] = keepdims if type(a) is not mu.ndarray: try: mean = a.mean except AttributeError: pass else: return mean(axis=axis, dtype=dtype, out=out, **kwargs) return _methods._mean(a, axis=axis, dtype=dtype, out=out, **kwargs) and def average(a, axis=None, weights=None, returned=False): if (type(a) not in (np.ndarray, np.matrix) and issubclass(type(a), np.ndarray)): warnings.warn("np.average currently does not preserve subclasses, but " "will do so in the future to match the behavior of most " "other numpy functions such as np.mean. In particular, " "this means calls which returned a scalar may return a " "0-d subclass object instead.", FutureWarning, stacklevel=2) if not isinstance(a, np.matrix): a = np.asarray(a) if weights is None: avg = a.mean(axis) scl = avg.dtype.type(a.size/avg.size) else: ...
downvote count: 0
score: 16
answers question: http://stackoverflow.com/q/48000487

http://stackoverflow.com/comment/82974557
type: Comment
comment on: http://stackoverflow.com/q/48002970
score: 0
has text: In web-version `Dining table` but not `Dining` is `Noun`. Because it was updated and learnt that `Dining table` is a proper noun. That is similar like `Stanford University` won't be treated as `Stanford` and `University`.
type: QuestionComment

http://stackoverflow.com/a/47981766
answers question: http://stackoverflow.com/q/47981370
score: 0
has comment: http://stackoverflow.com/comment/82932288
type: Answer
has body: I think your question needs refinement. From what I can tell, your python program is doing what one would expect. $ cat 0.py #!/usr/bin/python import sys print sys.argv[0] print sys.argv[1] $ chmod 755 0.py $ python 0.py foo 0.py foo $ ./0.py foo bar ./0.py foo So, if your python program is prining 'new.py' as you wrote the question, I think that's expected behavior. Why you're passing unsanitized user input to a system call is another question. Why you're using a system call at all (why not set up a webservice with your python program?) is yet a further question. I hope this helps.
has comment: http://stackoverflow.com/comment/82932054

http://stackoverflow.com/a/47917763
score: 4
answers question: http://stackoverflow.com/q/47910177
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/47910177
downvote count: 0
has body: I believe the pandas Python package would come in handy for preparing your data for plotting. It's useful for manipulating table-like data structures. Here is how I went about your problem: from pandas import DataFrame from bokeh.io import show from bokeh.plotting import figure from bokeh.models import ColumnDataSource from bokeh.palettes import Viridis5 # Your sample data df = DataFrame({'id': [1, 2, 3, 4, 5, 6, 7, 8, 9, 1], 'year_month_id': [201612, 201612, 201612, 201612, 201612, 201612, 201612, 201612, 201612, 201701], 'class': ['A', 'D', 'B', 'other', 'other', 'other', 'A', 'other', 'A', 'B'] }) # Get counts of groups of 'class' and fill in 'year_month_id' column df2 = DataFrame({'count': df.groupby(["year_month_id", "class"]).size()}).reset_index() df2 now looks like this: # Create new column to make plotting easier df2['class-date'] = df2['class'] + "-" + df2['year_month_id'].map(str) # x and y axes class_date = df2['class-date'].tolist() count = df2['count'].tolist() # Bokeh's mapping of column names and data lists source = ColumnDataSource(data=dict(class_date=class_date, count=count, color=Viridis5)) # Bokeh's convenience function for creating a Figure object p = figure(x_range=class_date, y_range=(0, 5), plot_height=350, title="Counts", toolbar_location=None, tools="") # Render and show the vbar plot p.vbar(x='class_date', top='count', width=0.9, color='color', source=source) show(p) So the Bokeh plot looks like this: Of course you can alter it to suit your needs. The first thing I thought of was making the top of the y_range variable so it could accommodate data better, though I have not tried it myself.
has comment: http://stackoverflow.com/comment/82804963
type: AcceptedAnswer

http://stackoverflow.com/comment/115478395
type: Comment
score: 1
comment on: http://stackoverflow.com/a/50583153
type: AnswerComment
has text: Thanks! I had to do this additional step too!

http://stackoverflow.com/a/47881491
score: 0
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/47881454
has body: You can do sth along the following lines which constitute an oft-seen pattern. Make the default parameter None and set it to the dependent value if appropriate inside the function: def foo(bar, potato=None): if potato is None: potato = bar * bar if bar == 0: return potato potato -= bar return foo(bar-1, potato) And if you are greedy with lines you can use the ternary if-else operator: def foo(bar, potato=None): potato = bar * bar if potato is None else potato return potato if bar == 0 else foo(bar - 1, potato - bar)
accepted answer of: http://stackoverflow.com/q/47881454

http://stackoverflow.com/a/69887293
answers question: http://stackoverflow.com/q/47867954
type: Answer
has body: so you need to use a super function and inherit from the showBase class from direct.showbase.ShowBase import ShowBase class Window(ShowBase): def __init__(self): super().__init__() app = Window() app.run() try that
score: 0

http://stackoverflow.com/q/47993203
type: AnsweredQuestion
tagged with: metaclass
downvote count: 0
tagged with: python-descriptors
type: Question
has title: How do the __slot__ descriptors work in python?
score: 4
has answer: http://stackoverflow.com/a/47995309
accepted answer: http://stackoverflow.com/a/47995309
answer count: 1
has body: I know what __slots__ does and what it's supposed to be used for. However I have not found a comprehensive answer as to how the underlaying mechanisms of the member descriptor created using __slots__ works. Where are the object-level values actually stored? Is there a way to change these values without direct attribute access to the descriptors? (ex. when class C has __dict__ you can do C.__dict__['key'] instead of C.key) Can one "extend" the immutability of an object defining __slots__ by creating similar class-level descriptors? And as further elaboration of this; can one build an immutable object using metaclasses but not defining __slots__ explicitly by creating said descriptors manually?
tagged with: slots
favorite count: 0
tagged with: immutability
tagged with: python
upvote count: 4

http://stackoverflow.com/comment/82705513
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47870231
has text: Where are the CORS headers in the .py file?

http://stackoverflow.com/comment/82708978
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47871691
has text: @user7490953 If you have a TSV, I think (inferring from DSM's interjection), that `sep='\t'` would be better than `delim_whitespace`. As for the left being shifted, could it be that you have leading spaces?

http://stackoverflow.com/q/47909129
upvote count: 0
has answer: http://stackoverflow.com/a/48307049
has comment: http://stackoverflow.com/comment/82787505
type: Question
has comment: http://stackoverflow.com/comment/82786086
has title: why can't I write just meter instead of "meter' in python 2.7.14?
has body: I use python 2.7.14..... I wrote this code in python andriod Qpython3 version....but when I used it in python 2.7.14 the programme accepts strings with these " " or ' ' .......in Qpython3 I just had to to write meter....here I have to write "meter" ..... any suggestion how to solve it? here is the code: import time print("This is a converter.Here, you have to spell the whole name of a unit otherwise it wont work") print(' ') def converter(): a=float(input("Enter a number:" )) print(" ") x=input("from:" ) print(" ") y=input("to:" ) print(" ") if x=="meter" and y=="kilometer" or x=="gram" and y=="kilogram": print(a/1000) elif x=="kilometer" and y=="meter" or x=="kilogram" and y=="gram": print(a*1000) #just keep adding more convertions starting with elifs inside the define function #and keep the else statement at the end of all elifs... #and that converter() function call it at the all end just once... #infact dont do anything escept adding elif statements....good luck #dont change that float it accepts both integer and float else : print("wrong") print(" ") print('To continue type "next",Thank you.') print(" ") print('To exit type "quit",Thank you.') print(" ") s=input() if s=="next": print(" ") converter() elif s=="quit": time.sleep(1) else: print("I Can't understand your command") converter()
downvote count: 6
has comment: http://stackoverflow.com/comment/82785918
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82787732
score: -6
favorite count: 0
has comment: http://stackoverflow.com/comment/82785874
type: UnansweredQuestion

http://stackoverflow.com/a/47956652
type: Answer
has comment: http://stackoverflow.com/comment/108686653
has comment: http://stackoverflow.com/comment/82883237
has body: There's a large array of techniques that internet service providers use to detect and combat bots and scrapers. At the core of all of them is to build heuristics and statistical models that can identify non-human-like behavior. Things such as: Total number of requests from a certain IP per specific time frame, for example, anything more than 50 requests per second, or 500 per minute, or 5000 per day may seem suspicious or even malicious. Counting number of requests per IP per unit of time is a very common, and arguably effective, technique. Regularity of incoming requests rate, for example, a sustained flow of 10 requests per second may seem like a robot programmed to make a request, wait a little, make the next request, and so on. HTTP Headers. Browsers send predictable User-Agent headers with each request that helps the server identify their vendor, version, and other information. In combination with other headers, a server might be able to figure out that requests are coming from an unknown or otherwise exploitative source. A stateful combination of authentication tokens, cookies, encryption keys, and other ephemeral pieces of information that require subsequent requests to be formed and submitted in a special manner. For example, the server may send down a certain key (via cookies, headers, in the response body, etc) and expect that your browser include or otherwise use that key for the subsequent request it makes to the server. If too many requests fail to satisfy that condition, it's a telltale sign they might be coming from a bot. Mouse and keyboard tracking techniques: if the server knows that a certain API can only be called when the user clicks a certain button, they can write front-end code to ensure that the proper mouse-activity is detected (i.e. the user did actually click on the button) before the API request is made. And many many more techniques. Imagine you are the person trying to detect and block bot activity. What approaches would you take to en…
upvote count: 22
answers question: http://stackoverflow.com/q/47956527
type: AcceptedAnswer
downvote count: 0
score: 22
accepted answer of: http://stackoverflow.com/q/47956527

http://stackoverflow.com/q/47929131
has title: Failed to run sudo killall python from php script in raspberry pi 2 ver B
has answer: http://stackoverflow.com/a/47939909
score: 0
has comment: http://stackoverflow.com/comment/82827907
answer count: 1
has comment: http://stackoverflow.com/comment/82828404
has comment: http://stackoverflow.com/comment/82826935
type: UnansweredQuestion
tagged with: raspberry-pi2
tagged with: python
tagged with: php
has comment: http://stackoverflow.com/comment/82827573
type: Question
tagged with: raspbian
has body: i run script python from php in my raspberry pi and i wanna stop the program. when i run program with php is running perfectly but when i run another file php to stop the program i failed. this my code to run file python using php &lt;?php shell_exec("/usr/bin/python /home/pi/Documents/python_project/multiple.py"); this my code to stop program &lt;?php shell_exec("usr/bin/sudo killall python"); echo "kill executed" thanks
tagged with: raspberry-pi

http://stackoverflow.com/q/47974637
has comment: http://stackoverflow.com/comment/82918622
tagged with: pandas
possible better answer: http://stackoverflow.com/a/47976383
accepted answer: http://stackoverflow.com/a/47974802
downvote count: 0
linked to: http://stackoverflow.com/q/41190852
favorite count: 0
has body: I have the following time series dataframe. I would like to fill the missing values with the previous value. However i would only want to fill the missing values between the first_valid_index and the last_valid index. So the columns i wanna fill will be different for each row. How can i do this? So, given this dataframe. import numpy as np import pandas as pd df = pd.DataFrame([[1, 2 ,3,np.nan,5], [1, 3 , np.nan , 4 , np.nan], [4, np.nan , 7 , np.nan,np.nan]], columns=[2007,2008,2009,2010,2011]) Input dataframe: 2007 2008 2009 2010 2011 1 2 3 NaN 5 1 3 NaN 4 NaN 4 Nan 7 NaN NaN Output dataframe: 2007 2008 2009 2010 2011 1 2 3 3 5 1 3 3 4 NaN 4 4 7 NaN NaN I thought of creating new columns for first_valid_index and last_valid_index and then using .apply() but how can i fill different columns per row? def fillMissing(x): first_valid = int(x["first_valid"]) last_valid = int(x["last_valid"]) for i in range(first_valid,last_valid + 1): missing.append(i) #What should i do here since the following is not valid #x[missing] = x[missing].fillna(method='ffill', axis=1) df.apply(fillMissing , axis=1)
tagged with: python
type: AnsweredQuestion
score: 3
has title: Remove the nulls between 2 specific columns in pandas
upvote count: 3
has answer: http://stackoverflow.com/a/47974802
type: Question
has comment: http://stackoverflow.com/comment/82918702
has answer: http://stackoverflow.com/a/47976383
answer count: 2

http://stackoverflow.com/q/47884921
tagged with: hierarchical-clustering
tagged with: scipy
type: Question
has body: I have a large data matrix X and I use SciPy implementation of Ward's hierarchical clustering like so: Z = ward(X.todense()) fig = plt.figure(figsize=(25, 10)) dn = dendrogram(Z) I now wish to see which classes X[i] belongs to. How can I do this?
answer count: 1
linked to: http://stackoverflow.com/q/7664826
accepted answer: http://stackoverflow.com/a/47886568
downvote count: 1
tagged with: python
has title: Which cluster does X[i] belong to?
has answer: http://stackoverflow.com/a/47886568
favorite count: 0
type: AnsweredQuestion
upvote count: 0
score: -1

http://stackoverflow.com/a/47910852
type: Answer
has comment: http://stackoverflow.com/comment/82803549
has body: I tried code and I see it sends 404 and 301 to parse(), not to parse_item() but I don't have page with broken links so it doesn't start LinkExtractor I used portal httpbin.org to generate pages with different status. Maybe if I have page with broken urls then LinkExtractor could run and I could get different results. #!/usr/bin/env python3 import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.selector import Selector from scrapy.spiders import Rule, CrawlSpider #from scrapy.commands.view import open_in_browser class MySpider(CrawlSpider): name = 'MySpider' handle_httpstatus_list = [404, 301, 302, 303] all_responses_log = './responses_all.log' ok_responses_log = './responses_ok.log' bad_responses_log = './responses_bad.log' redirects_responses_log = './responses_redirect.log' start_urls = [ 'http://httpbin.org/status/301', 'http://httpbin.org/status/302', 'http://httpbin.org/status/303', 'http://httpbin.org/status/404', 'http://httpbin.org/status/200', ] # This spider has one rule: extract all (unique and canonicalized) links, follow them and parse them using the parse_items method rules = [ Rule( LinkExtractor( canonicalize=True, unique=True ), follow=True, callback="parse_item" ) ] def parse(self, response): print('parse url:', response.url) self.test_status('parse()', response) def parse_item(self, response): print('parse item url:', response.url) self.test_status('parse_item()', response) # The list of items that are found on the particular page items = [] res = Selector(response) self.append(self.resp_log_file, str(response)) # Only extract canonicalized and unique links (with respect to the current page) links = LinkExtractor(canonicalize=True, unique=True).extract_links(response) def test_status(self, text, response): try: if response.status == 404: log = self.bad_responses_log elif response.status == 200: log = self.ok_responses_log #elif 299 &lt; response.status &lt; 400: elif response.status in (301, 302, 303, 307): log = self.redirects_…
answers question: http://stackoverflow.com/q/47908075
score: 0
has comment: http://stackoverflow.com/comment/82830849

http://stackoverflow.com/comment/82965173
has text: Is it worth asking this at https://dsp.stackexchange.com/ ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47998371
score: 0

http://stackoverflow.com/comment/83257119
type: AnswerComment
comment on: http://stackoverflow.com/a/48089563
type: Comment
score: 0
has text: This is really good, thanks. I like that you used a function instead of class to do the regex matching.

http://stackoverflow.com/a/47968352
has comment: http://stackoverflow.com/comment/82909750
has comment: http://stackoverflow.com/comment/82913645
has body: There are a lot of possibilities out there... You can think about User Groups - so a User can be part of the group Alaska and California. (This options makes only sense because the states are not dynamically). Another option (more likely) is to have a model for the states and a model for the selected states for a single User. from django.db import models from django.contrib.auth.models import User class States(models.Model): name = models.TextField() class UserStates(models.Model): user = models.ForeignKey(User) state = models.ForeignKey(States) available_since = models.DateField(null=True)
has comment: http://stackoverflow.com/comment/82913678
downvote count: 0
has comment: http://stackoverflow.com/comment/82906673
answers question: http://stackoverflow.com/q/47968310
has comment: http://stackoverflow.com/comment/82906812
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/82880887
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47955699
has text: Just posting the code with a __*very*__ brief explanation of the problem you are facing is not a valid question here.
type: Comment

http://stackoverflow.com/q/47862895
tagged with: matplotlib
has answer: http://stackoverflow.com/a/71798615
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82706410
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47863280
tagged with: python
score: 2
has body: The following code draws two red rectangles. The red rectangles should be next to each other, with no space between. In the python plot, this is OK. In the exported pdf, there is a thin but noticeable white space between the rectangles. Is there some way of fixing this? import matplotlib.pyplot as plt import matplotlib import matplotlib.patches as patches fig1 = plt.figure(); ax = fig1.add_subplot(111, aspect='equal'); ax.set_xticks([]); ax.set_yticks([]); #add first patch dx=1.0; loc=(0.0,0.0); ax.add_patch(patches.Rectangle((loc[0]-dx/2.0,loc[1]-dx/2.0),dx,dx,facecolor='red',edgecolor='none',linewidth=0)); #add second patch dx=1.0; loc=(1.0,0.0); ax.add_patch(patches.Rectangle((loc[0]-dx/2.0,loc[1]-dx/2.0),dx,dx,facecolor='red',edgecolor='none',linewidth=0)); ax.set_xlim([-1,3]); ax.set_ylim([-1,2]); fig1.show(); plt.savefig('spaceTest.pdf'); All is OK in the python plot: But there is white space in the pdf:
upvote count: 2
has title: Undesired space between Rectangle patches in matplotlib
linked to: http://stackoverflow.com/q/71595779
type: Question

http://stackoverflow.com/q/48010631
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48010810
downvote count: 4
tagged with: for-loop
has comment: http://stackoverflow.com/comment/82993228
upvote count: 0
tagged with: nested-loops
answer count: 2
has title: Avoid nested for with numpy arrays
has comment: http://stackoverflow.com/comment/82989910
favorite count: 0
type: UnansweredQuestion
score: -4
has comment: http://stackoverflow.com/comment/82989797
tagged with: python
has body: I need to implement a generic operation on the elements of some np 2D arrays (A,B,C). In pseudo-code for i in A.height: for j in A.width: A[i,j] = f(B[i,j],C[i,j]) where f() is concatenating the bits of the two variables by means of struct.pack(), struct.unpack() x = struct.pack('2B', B[i, j], C[i, j]) y = struct.unpack('H', x) This code takes a really long time to execute (0.25 secs for 640*480 matrices ... maybe is normal yet I could use something faster ), so I was wondering if anybody could suggest me some pythonic way of achieving the same result which could also improve the performance
has answer: http://stackoverflow.com/a/48012467
has comment: http://stackoverflow.com/comment/82989786

http://stackoverflow.com/comment/82829329
type: Comment
has text: I think that warning also suggests using loc. Did you try that?
type: QuestionComment
comment on: http://stackoverflow.com/q/47930345
score: 1

http://stackoverflow.com/a/47895342
upvote count: 6
has body: Good spot! This is a bug in scipy. The source code can be found here. Line 3031 to 3051: def pmf(self, x, n, p): return np.exp(self.logpmf(x, n, p)) Line 2997 to 3017: def logpmf(self, x, n, p): n, p, npcond = self._process_parameters(n, p) Line 2939 to 2958: def _process_parameters(self, n, p): p = np.array(p, dtype=np.float64, copy=True) p[...,-1] = 1. - p[...,:-1].sum(axis=-1) # true for bad p pcond = np.any(p &lt;= 0, axis=-1) # &lt;- Here is why!!! pcond |= np.any(p &gt; 1, axis=-1) n = np.array(n, dtype=np.int, copy=True) # true for bad n ncond = n &lt;= 0 return n, p, ncond | pcond The line pcond = np.any(p &lt;= 0, axis=-1) results in pcond being true if any value of p is &lt;= 0. Then in logpmf line 3029: return self._checkresult(result, npcond_, np.NAN) results in logpmf and pmf returning nan! Note that the actual result is calculated properly (line 3020, 2994-2995): result = self._logpmf(x, n, p) def _logpmf(self, x, n, p): return gammaln(n+1) + np.sum(xlogy(x, p) - gammaln(x+1), axis=-1) With your values: import numpy as np from scipy.special import xlogy, gammaln x = np.array([3, 3, 0]) n = 6 p = np.array([2/3.0, 1/3.0, 0]) result = np.exp(gammaln(n+1) + np.sum(xlogy(x, p) - gammaln(x+1), axis=-1)) print(result) &gt;&gt;&gt;0.219478737997
score: 6
has comment: http://stackoverflow.com/comment/82757530
answers question: http://stackoverflow.com/q/47894446
downvote count: 0
type: Answer

http://stackoverflow.com/comment/82967666
has text: @JohnY See the edit. Your comment would serve as an answer to how I intended the question.
comment on: http://stackoverflow.com/q/47999145
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82823967
comment on: http://stackoverflow.com/q/47927755
type: Comment
type: QuestionComment
has text: This is an option, but may be there's an easier way?
score: 0

http://stackoverflow.com/q/47954926
tagged with: distributed-computing
favorite count: 0
has answer: http://stackoverflow.com/a/47966580
has body: I am trying to train a slim model using 3 GPUs. I specifically telling TF to use the second GPU to allocate the model: with tf.device('device:GPU:1'): logits, end_points = inception_v3(inputs) However, I'm getting an OOM error on that GPU everytime I run my code. I've tried to reduce the batch_size so the model fits in memory, but the net is ruinned. I own 3 GPUS so, is there a way to tell TF to use my third GPU when second is full? I've tried not telling TF to use any GPU and allowing soft placemente, but it is not working either.
tagged with: python
tagged with: multi-gpu
type: AnsweredQuestion
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/47966580
tagged with: tensorflow
type: Question
has title: Use multiple GPUs for inception_v3 model in TF slim
tagged with: deep-learning
answer count: 1
downvote count: 0

mfcc
type: Tag
tags question: http://stackoverflow.com/q/48001383
tag name: mfcc

http://stackoverflow.com/comment/82686229
comment on: http://stackoverflow.com/q/47860592
has text: Use read(1) instead of readline. Check for whatever your record boundary marker is.
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/82861753
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47945899
has text: Possible duplicate of [Basic text editor in command prompt?](https://stackoverflow.com/questions/19497399/basic-text-editor-in-command-prompt)
score: 0

http://stackoverflow.com/q/47859213
score: 0
tagged with: for-loop
answer count: 1
has answer: http://stackoverflow.com/a/47859267
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47859267
type: Question
tagged with: python-os
has body: I'm writing a script that walks through a directory and looks for files with the typical Windows installer extensions and deletes them. When I run this with a list (vs say checking for .msi or .exe), it breaks when going through the nested loop again. It seems as if it runs though my list, deletes one type of extension then runs through the loop again and attemtps to find the same extension then throws an exception. Here is the output when I simply print, but not remove a file: &gt; C:\Users\User\Documents\Python Scripts&gt;python test.py &lt; test_run.txt &gt; Found directory: . Found directory: .\test_files &gt; Deleting test.cub &gt; Deleting test.idt &gt; Deleting test.idt &gt; Deleting test.msi &gt; Deleting test.msm &gt; Deleting test.msp &gt; Deleting test.mst &gt; Deleting test.pcp &gt; Deleting test1.exe When I attempt to run it with os.remove it gives the following: Found directory: . Found directory: .\test_files Deleting test.cub Traceback (most recent call last): File "test.py", line 13, in &lt;module&gt; os.remove(fileName) FileNotFoundError: [WinError 2] The system cannot find the file specified: 'test.cub' I read up on os walk and that seems to be working properly, I can't seem to figure out where this script is going wrong. The code is below: import os myList = [".msi", ".msm", ".msp", ".mst", ".idt", ".idt", ".cub", ".pcp", ".exe"] rootDir = '.' for dirName, subdrList, fileList in os.walk(rootDir): print('Found directory: %s' %dirName) for fileName in fileList: for extName in myList: if(fileName.endswith(extName)): print('\t Deleting %s' % fileName) os.remove(fileName)
has title: For loop throwing exception on file already deleted during os walk

http://stackoverflow.com/comment/82915523
type: Comment
has text: That's quite unlikely. Probably you had a problem while entering the array
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47972832

http://stackoverflow.com/a/47980738
has body: for argument of to (email) isn't filled as a single email, but it used for list of email/s. You should change: msg = EmailMultiAlternatives(subject, text_content, to=to, from_email=from_email) to msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) See this docs for more..
downvote count: 1
score: -1
upvote count: 0
answers question: http://stackoverflow.com/q/47980660
type: Answer

http://stackoverflow.com/comment/82892748
comment on: http://stackoverflow.com/a/47961587
score: 0
type: AnswerComment
has text: Nope, it's working. You sure you haven't called it on ``8437221`` or ``8437216`` by mistake (note that it works left to right)?
type: Comment

http://stackoverflow.com/comment/82784756
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47880153
has text: How do I "put your results as an answer for all to see" and accept it?

http://stackoverflow.com/comment/82958765
has text: ah timedelta is smart. Good.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47995074
type: Comment

http://stackoverflow.com/comment/82681843
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47858529
has text: Lose the readlines... Just use `for line in l:`. Also both loops should be combined

http://stackoverflow.com/q/47978863
tagged with: python
has comment: http://stackoverflow.com/comment/82943905
upvote count: 2
has comment: http://stackoverflow.com/comment/82927525
answer count: 1
downvote count: 1
has body: How do I remove consecutive duplicates of block size less than some threshold (say 4 here) from a list like this in python? L = [0,0,0,0,0,1,1,1,1,1,0,0,0,1,1,1,1,1,0,0,0,0,0,1,1,0,0,0,0,0,1,1,0,0,0,0] I want the result to be like this: O = [0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] The new list should also replace the consecutive duplicates of block size less than threshold (here 4) with neighbor values (like filling with neighbors). I was thinking of some king of smoothing filter but couldn't find. Also, i was thinking of writing raw code for this but not able to think of logic. Assume that it is binary list.
has answer: http://stackoverflow.com/a/47979439
has title: Replace duplicates of block size less than Threshold - Python
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/82926352
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47979439

http://stackoverflow.com/comment/82746813
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47889919
score: 0
has text: @kazemakase "No module named 'numpy' "

http://stackoverflow.com/q/47905855
has answer: http://stackoverflow.com/a/47961125
upvote count: 2
tagged with: python
answer count: 1
tagged with: botocore
accepted answer: http://stackoverflow.com/a/47961125
has body: I am writing a small python application that uploads archives to AWS Glacier. During the upload process, I call the following methods: client.initiate_multipart_upload() client.upload_multipart_part() client.complete_multipart_upload() All of these have the potential to raise many different exceptions if the connection is lost or the request takes too long. I was using: except (botocore.exceptions.EndpointConnectionError, client.exceptions.RequestTimeoutException): to try and catch them, retry after a set period of time, and give up after a set number of attempts, but I still sometimes get other exceptions that go uncaught. Right now I have switched to using a blanket except: statement, which I am not very happy about. My application checks the AWS account credentials, vault name and connection to AWS at another stage, so these do not need to be considered. Is there a way I can catch all boto3 and botocore exceptions that might occur while carrying out these three methods?
score: 2
type: AnsweredQuestion
has title: How can I be sure to catch all possible exceptions when uploading to Glacier with boto3 (AWS)
downvote count: 0
tagged with: boto3
tagged with: amazon-web-services
favorite count: 0
type: Question

http://stackoverflow.com/comment/82741623
score: 0
comment on: http://stackoverflow.com/q/47882616
type: Comment
type: QuestionComment
has text: Now I have (non) working example and simpler explanation.

http://stackoverflow.com/comment/82915535
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47972846
has text: Possible duplicate of [Check if list item contains items from another list](https://stackoverflow.com/q/11328940)

http://stackoverflow.com/comment/82702353
score: 0
comment on: http://stackoverflow.com/q/47864617
has text: are you intending to use the same 1- base indexing as the fortran? (if you go that way you will not be able to use any python list operations). Your code is wrong either way..
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47949148
upvote count: 3
has comment: http://stackoverflow.com/comment/121372826
type: Answer
downvote count: 0
has body: Function round does accept negative values for cases in which you want to specify precision to the left of the decimal point: dataframe.columnName.round(-3) Example: &gt;&gt;&gt; pd.Series([1, 500, 500.1, 999, 1500, 1501, 946546]).round(-3) 0 0.0 1 0.0 2 1000.0 3 1000.0 4 2000.0 5 2000.0 6 947000.0 dtype: float64
score: 3
answers question: http://stackoverflow.com/q/47949053

http://stackoverflow.com/q/47922737
tagged with: graph-theory
has comment: http://stackoverflow.com/comment/82831608
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has title: Barabasi-Albert model, wrong degree exponent
has body: I'm trying to generate a scale-free network using the Barabasi-Albert model. The model predicts a degree distribution that follows p(k) ~ k^-3 but mine shows k^-2. The algorithm was taken from Barabasi's book at this URL: http://barabasi.com/networksciencebook, here is the relevant paragraph: Barabasi's algorithm Here is my code, could someone please help me figure out what is wrong? import numpy as np import matplotlib.pyplot as plt from collections import Counter plt.rcParams["figure.figsize"] = (15,6) #initialize values N = 10000 k = 2 m = int(k / 2) #initialize matrices adjacency = np.zeros((N,N)) degrees = np.zeros(N) #add links for i in range(N): degrees[i] = m for c in range(m): # choose a node with probability proportional to it's degree j = np.random.choice(N, p = degrees / (2 * m * i + m + c)) degrees[j] += 1 adjacency[i][j] += 1 adjacency[j][i] += 1 def get_binned_data(labels, values, num): min_label, max_label = min(labels), max(labels) base = (max_label / min_label) ** (1 / num) bins = [base**i for i in range(int(np.log(max_label) / np.log(base)) + 1)] binned_values, binned_labels = [], [] counter = 0 for b in bins: bin_size = 0 bin_sum = 0 while counter &lt; len(labels) and labels[counter] &lt;= b: bin_size += values[counter] bin_sum += values[counter] * labels[counter] counter += 1 if(bin_size): binned_values.append(bin_size) binned_labels.append(bin_sum / bin_size) return binned_labels, binned_values labels, values = zip(*sorted(Counter(degrees).items(), key = lambda pair: pair[0])) binned_labels, binned_values = get_binned_data(labels, values, 15) fig, (ax1, ax2) = plt.subplots(ncols = 2, nrows = 1) fig.suptitle('Barabasi-Albert Model',fontsize = 25) ax1.loglog(binned_labels, binned_values, basex = 10, basey = 10, linestyle = 'None', marker = 'o', color = 'red') ax1.set(xlabel = 'degree', ylabel = '# of nodes') ax1.set_title('log-log scale (log-binned)',{'fontsize':'15'}) ax2.plot(labels, values, 'ro') ax2.set(xlabel = 'degree', ylabel = '# of nodes…
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/82813920
has answer: http://stackoverflow.com/a/47924450
type: Question

http://stackoverflow.com/a/47973659
score: 1
answers question: http://stackoverflow.com/q/47973609
upvote count: 1
downvote count: 0
type: Answer
has body: You can check first that digit is float or int then convert according to its type(): def flat(lst): result=[] for i in lst: if isinstance(i,str): for item in i.split(','): if '.' in item: result.append(float(item)) else: result.append(int(item)) return result print(flat(['2,2.4,3'])) output: [2, 2.4, 3] if you want in all in float then: def flat(lst): result=[] for i in lst: if isinstance(i,str): for item in i.split(','): result.append(float(item)) return result print(flat(['2,2.4,3'])) output: [2.0, 2.4, 3.0]

http://stackoverflow.com/comment/82793098
type: Comment
comment on: http://stackoverflow.com/a/47911949
type: AnswerComment
has text: In Python, the equivalent function to convert something to float is 'float'. In this case, you will have to parse all of the data to find the min and the max values since you can't be sure you've found the smallest or the largest value unless you've looked at everything. You can also try finding the min/max/avg in your MongoDB query using the [$group] (https://docs.mongodb.com/manual/reference/operator/aggregation/group/#pipe._S_group) operator so you won't have to do any of that work in Python.
score: 0

http://stackoverflow.com/comment/82930226
type: AnswerComment
comment on: http://stackoverflow.com/a/47973658
type: Comment
score: 0
has text: @piRSquared ... I somehow impressed a pandas guru? No doubt I was just first to answer. Happy holidays!

multi-gpu
type: Tag
tags question: http://stackoverflow.com/q/47954926
tag name: multi-gpu

http://stackoverflow.com/q/48009091
score: 1
tagged with: snakemake
has title: Can't import python module using a conda environment in Snakemake rule
type: Question
tagged with: conda
has answer: http://stackoverflow.com/a/48014023
accepted answer: http://stackoverflow.com/a/48014023
upvote count: 1
answer count: 1
favorite count: 0
has body: I created a Conda environment with python 3.5, in order to run Snakemake workflows. I'm using separate Conda environments in Snakemake rules. I would like to run one of them using python2 libs, however here I can't seem to import a specific module. This is my rule's environment: channels: - conda-forge dependencies: - zeep My rule is calling a python script using python2: python2 my_script.py And the python script contains this import: from zeep import Client When I run the workflow I get this error: ImportError: No module named zeep Could this be an issue related to python versions?
tagged with: python
type: AnsweredQuestion
tagged with: anaconda
downvote count: 0

http://stackoverflow.com/comment/82998289
type: Comment
score: 0
has text: Yes, I've tried it. All test runners import the module under test, which will trigger the "can import" block. If a module has C extensions, then there may be a large number of references to it created by importing (for numba, there are 57). If you try to "hide" the module you want to cause an `ImportError` in this case, you will find it is very difficult to do so. The only solution that _may_ work as you describe is to have an entirely separate test suite that only tests ImportError catching blocks where you monkeypatch the module you want to fail to Import. But there must be a better way
type: AnswerComment
comment on: http://stackoverflow.com/a/47997308

http://stackoverflow.com/comment/82936862
has text: This question almost surely is dupe, but I can't seem to find it.
comment on: http://stackoverflow.com/q/47983782
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82973629
comment on: http://stackoverflow.com/a/47999180
type: AnswerComment
score: 0
type: Comment
has text: I also encountered this post but i want a inbuilt functionality of endpoints (If any) to set headers for my request. instead of some patching

http://stackoverflow.com/comment/82764392
type: Comment
has text: Documentation can be found at https://docs.djangoproject.com/en/dev/faq/models/#how-can-i-see-the-raw-sql-queries-django-is-running
score: 3
type: AnswerComment
comment on: http://stackoverflow.com/a/47898843

http://stackoverflow.com/q/47961670
tagged with: django
has answer: http://stackoverflow.com/a/47965885
has comment: http://stackoverflow.com/comment/82893336
has comment: http://stackoverflow.com/comment/82892835
has comment: http://stackoverflow.com/comment/82894422
has comment: http://stackoverflow.com/comment/82892637
has answer: http://stackoverflow.com/a/47963304
type: Question
has comment: http://stackoverflow.com/comment/82892761
answer count: 2
has comment: http://stackoverflow.com/comment/82894886
has comment: http://stackoverflow.com/comment/82892673
score: 0
has title: Adding Unique Slug in Django
tagged with: python
has comment: http://stackoverflow.com/comment/82892788
has body: I'm trying to add a slug field in my school project, Here's what I tried in my model, def pre_save_receiver(sender, instance, *args, **kwargs): slug = slugify(instance.title) exists = Data.objects.filter(slug=slug).exists() if exists: instance.slug = "%s-%s" % (slug, instance.id) else: instance.slug = slug pre_save.connect(pre_save_receiver, sender=Data) Everything is working fine but the problem is that it's adding ID in slug field behind even if it's Unique. How can I fix that?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82892722

http://stackoverflow.com/comment/100280283
type: AnswerComment
type: Comment
has text: TypeError: __init__() got an unexpected keyword argument 'dsn'
score: 0
comment on: http://stackoverflow.com/a/47972023

http://stackoverflow.com/comment/82712138
comment on: http://stackoverflow.com/q/47873019
score: 0
type: Comment
type: QuestionComment
has text: @pycoder Platform dependent, but base independent? Platform meaning the interpreter, I guess? Well, if that's the case, write it as an answer and I will accept it.

http://stackoverflow.com/comment/82821313
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47926650
has text: `antigo, novo = novo, antigo + novo;` in C does not do what you think it does. Here's what happens: 1: evaluate `antigo` and discard the result. 2: assign `novo` to `novo`. 3: evaluate `antigo+novo` and return it (but since you're not assigning the value it is still discarded).
score: 0

http://stackoverflow.com/q/47857372
tagged with: python
has comment: http://stackoverflow.com/comment/82679256
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47859567
type: Question
tagged with: indexing
has comment: http://stackoverflow.com/comment/82706150
has comment: http://stackoverflow.com/comment/82679602
has body: Is there an efficient way to add the same number (int/float) to all cells adjacent to any given [i,j] or [i,j,k] index in a Numpy array without inefficient looping? Just can't seem to find the right slice command. import numpy as np arr = np.zeros((5,5)) arr[0,0] = 2 arr[2,2] = 1 arr Returns Out [1]: array([[ 2., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.], [ 0., 0., 1., 0., 0.], [ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.]]) Looking to accomplish the effect shown below (manually coded to show desired output), but without directly knowing the cell contents or index numbers, other than they are non-zero, and without having to loop over every element in the array. # Add 2 around [0,0] arr[0:2, 0:2] += 2 arr[0,0] -= 2 # Add 1 around [2,2] arr[1:4,1:4] += 1 arr[2,2] -= 1 arr Out [2]: array([[ 2., 2., 0., 0., 0.], [ 2., 3., 1., 1., 0.], [ 0., 1., 1., 1., 0.], [ 0., 1., 1., 1., 0.], [ 0., 0., 0., 0., 0.]])
tagged with: slice
accepted answer: http://stackoverflow.com/a/47859567
tagged with: numpy
score: 0
answer count: 1
tagged with: arrays
linked to: http://stackoverflow.com/q/47648106
has title: Fast way to add a number to all cells adjacent a row/column index in a N-dim sparse Numpy Array?
has comment: http://stackoverflow.com/comment/82680453

http://stackoverflow.com/q/47882213
has title: How to correctly connect to mongodb in Celery worker?
score: 6
tagged with: celery
type: AnsweredQuestion
tagged with: pymongo
type: Question
tagged with: mongodb
answer count: 1
upvote count: 6
has body: Learning Celery, read Celery Best Practices, and have quite a simple question about database usage with Celery. Deni Bertovic says: You shouldn't pass Database objects (for instance your User model) to a background task because the serialized object might contain stale data. So, if I want to connect to the database in a worker, what is the right choice: @app.task def add(x, y, collection): client = MongoClient('mongodb://localhost:27017/') db = client.wakawaka db[collection].insert_one({'sum':x+y}) return True or: client = MongoClient('mongodb://localhost:27017/') db = client.wakawaka @app.task def add(x, y, collection): db[collection].insert_one({'sum':x+y}) return True ? UPD: I can close() my mongodb connection at the end of every task, so every time I need something, task will connect to fresh DB, and no resources wasted. Still, do I need to open/close database connection so many times? Or I can connect once and somehow refresh connection to retrieve fresh version of DB?
has answer: http://stackoverflow.com/a/47887198
accepted answer: http://stackoverflow.com/a/47887198
tagged with: celery-task
tagged with: python
favorite count: 0
downvote count: 0

http://stackoverflow.com/comment/82701506
type: AnswerComment
has text: Ok, thanks. I will give it a try it. By the way, edit your post a bit because I am not understanding the part "Just saying". Is that I must use either `s3 = session.resource('s3')` or `s3 = boto3.client('s3') s3 = boto3.resource('s3')`? It is not very clear in the way you write it.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47868159

http://stackoverflow.com/q/47955389
linked to: http://stackoverflow.com/q/11479816
has body: I have a variable var which could contain any number from 1-5. I want to run an if statement on each possibility. i.e. if var == 1: num = "a" if var == 2: num = "b" ... Is there an easier way to do this?
possible better answer: http://stackoverflow.com/a/47955401
has answer: http://stackoverflow.com/a/47955407
type: Question
has answer: http://stackoverflow.com/a/47955688
tagged with: python
has title: How to create bulk if statements
accepted answer: http://stackoverflow.com/a/47955688
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/47955401
type: AnsweredQuestion

http://stackoverflow.com/comment/82763644
has text: That doesn't really make any sense to me without seeing an example :-). Unit tests run tests. Each test should be isolated. It really doesn't matter how many there are (other than more tests take longer to run I suppose)...
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47880705

http://stackoverflow.com/q/47898811
answer count: 0
linked to: http://stackoverflow.com/q/16307307
type: Question
has body: I'm facing an issue when deploying a django app in other machine. In my local machine is working fine, but in a linux machine is not showing the (Currently) current value of ImageField. Both environments have django 1.11. The model: class Company(models.Model): class Meta: verbose_name = ("Empresa") name = models.CharField(max_length=500, verbose_name="nombre") nit = models.CharField(max_length=50, verbose_name="nit") address = models.CharField(max_length=500, verbose_name="dirección", blank=True, null=True) telephone = models.CharField(max_length=15, verbose_name="teléfono", blank=True, null=True) cellphone = models.CharField(max_length=15, verbose_name="celular", blank=True, null=True) legal_representative = models.CharField(max_length=500, verbose_name="representante legal", blank=True, null=True) photo = models.ImageField(upload_to='company/img', verbose_name="imagen", blank=True, null=True) photo_thumbnail1 = models.ImageField(upload_to='company/img', verbose_name="imagen 250x250", blank=True, null=True) def __str__(self): return self.name def __unicode__(self): return self.name The admin: class CompanyAdmin(admin.ModelAdmin): exclude = ('photo_thumbnail1',) list_display = ('id','name', 'nit', 'address','telephone','cellphone','legal_representative',) def render_change_form(self, request, context, *args, **kwargs): # Just to show the photo url while rendering print('rendering') print(vars(kwargs['obj'])) if kwargs['obj'].photo: print(kwargs['obj'].photo.url) if kwargs['obj'].photo_thumbnail1: print(kwargs['obj'].photo_thumbnail1.url) return super(CompanyAdmin, self).render_change_form(request, context, args, kwargs) In my local machine, I can see the the current value for Photo when I previously saved: In linux machine, it is not showing the current value as if there is no image saved for this field. But I made sure it is getting the value when rendering by printing in console the urls: Please, if you have any idea what can i do, it would be deeply appreciated.
score: 0
has title: Why is django admin not showing "currently" value of ImageField?
has comment: http://stackoverflow.com/comment/82764842
has comment: http://stackoverflow.com/comment/82857573
tagged with: linux
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/q/47897235
downvote count: 0
favorite count: 0
tagged with: string-formatting
accepted answer: http://stackoverflow.com/a/47897328
tagged with: ternary-operator
tagged with: python
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/82762033
upvote count: 1
has body: Is it possible to use placeholders in string formatting? An example will probably show what I mean: "some {plural?'people':'person'}".format(plural=True) Should be "some people". Basically, can I switch between two options in a format string, rather than directly provide all the values e.g.: "some {plural}".format(plural="people") This may sound a bit useless, but the use case is many strings with several words that could be plural, and this would drastically simplify the code.
has comment: http://stackoverflow.com/comment/82761309
type: Question
has title: String formatting with placeholders
possible better answer: http://stackoverflow.com/a/47897323
has answer: http://stackoverflow.com/a/47897323
has answer: http://stackoverflow.com/a/47897328
has comment: http://stackoverflow.com/comment/82761351
answer count: 2

importerror
tags question: http://stackoverflow.com/q/47911544
tags question: http://stackoverflow.com/q/47935707
tags question: http://stackoverflow.com/q/47867595
type: Tag
tags question: http://stackoverflow.com/q/47909851
tag name: importerror
tags question: http://stackoverflow.com/q/47895059

http://stackoverflow.com/comment/93808335
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48065082
has text: Hey! Sorry, I might not be the person to help as I'm a casual user of SQL-related libraries... What version of pyodbc are you using? I've found some discussions on the topic here https://github.com/mkleehammer/pyodbc/issues/371 and here https://stackoverflow.com/questions/49887717/why-would-i-get-a-memory-error-with-fast-executemany-on-a-tiny-df
score: 0

http://stackoverflow.com/q/47945004
has answer: http://stackoverflow.com/a/47945503
tagged with: python
has comment: http://stackoverflow.com/comment/82860436
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/47945174
has body: How can I validate for NaT in python while at the same time working for timestamps. E.g. the variable _date can be either NaT or Timestamp('2017-12-02 00:00:00') If I use this: np.isnat(np.datetime64(_date)), it works for Timestamp('2017-12-02 00:00:00') but not NaT
type: Question
tagged with: numpy
answer count: 2
has title: Checking for both NaT or pandas timestamp
downvote count: 0
possible better answer: http://stackoverflow.com/a/47945503
tagged with: pandas
favorite count: 0
upvote count: 2
accepted answer: http://stackoverflow.com/a/47945174
has comment: http://stackoverflow.com/comment/82860458

http://stackoverflow.com/comment/82924915
comment on: http://stackoverflow.com/q/47977954
score: 0
type: Comment
type: QuestionComment
has text: your code is not properly formatted, always paste code with proper formatting

http://stackoverflow.com/a/47996647
has comment: http://stackoverflow.com/comment/82961549
type: Answer
has body: You swap l[0][1] with l[1][0]... and then when you get to l[1][0], you swap l[1][0] with l[0][1]. Every pair of elements gets swapped twice, except for the diagonal elements, but those get swapped with themselves anyway. Everything ends up back where it started. If you want to perform a transpose by element swaps, you need to avoid swapping pairs twice: for i in range(len(a)): for j in range(i+1, len(a)): a[i][j], a[j][i] = a[j][i], a[i][j] Also, your transpose implicitly assumes square input. If you get a 3x5 input, you can't swap a[2][4] with a[4][2], because there is no a[4][2].
answers question: http://stackoverflow.com/q/47996516
has comment: http://stackoverflow.com/comment/82961489
accepted answer of: http://stackoverflow.com/q/47996516
score: 11
has comment: http://stackoverflow.com/comment/82961780
upvote count: 11
has comment: http://stackoverflow.com/comment/82961341
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48003074
tagged with: algorithm
score: 1
has comment: http://stackoverflow.com/comment/84608867
type: Question
has answer: http://stackoverflow.com/a/48805904
downvote count: 0
answer count: 1
tagged with: text-mining
has comment: http://stackoverflow.com/comment/82976047
favorite count: 0
has comment: http://stackoverflow.com/comment/84614149
has body: For a text (say): "I am leaving India today. I am headed to USA for a week." "I am travelling from India to USA" I need to train the machine to label USA as "Destination" and India as "Source" I am using SpaCy's NER to extract the locations. How should I proceed to create a training set and train it. What would be my feature vector and label vector?
tagged with: python
tagged with: nlp
has title: How to train a machine to label individual words in a text
type: UnansweredQuestion
tagged with: machine-learning
upvote count: 1
has comment: http://stackoverflow.com/comment/82974387
has comment: http://stackoverflow.com/comment/84614240

http://stackoverflow.com/comment/82835136
score: 1
comment on: http://stackoverflow.com/q/47932922
type: Comment
type: QuestionComment
has text: Stupid question, but are the numbers consistent? Can you reproduce this 25x every time? Or maybe the first needed some time to evict pages from RAM to allocate the required space?

http://stackoverflow.com/a/48003438
upvote count: 2
has comment: http://stackoverflow.com/comment/82975163
type: Answer
has comment: http://stackoverflow.com/comment/82976493
accepted answer of: http://stackoverflow.com/q/48003394
score: 2
answers question: http://stackoverflow.com/q/48003394
has body: I think the issue arises from below line \--trained_checkpoint_prefix training\model.ckpt-29809 \--output_directory crop_graph1 this training\model.ckpt-29809 should have a double quote like "training\model.ckpt-29809" I assume python is treating that extra "-" between ckpt and 29809 Or maybe remove the backslash as it meant for continuous command. The command should be in one line without "\" python export_inference_graph.py --input_type image_tensor --pipeline_config_path samples/configs/ssd_mobilenet_v1_pets --trained_checkpoint_prefix "training\model.ckpt-29809" --output_directory crop_graph1
has comment: http://stackoverflow.com/comment/82976650
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/82831600
comment on: http://stackoverflow.com/q/47930176
has text: What's the output to your terminal? Can you give us some examples?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47917288
tagged with: tensorflow
has body: I want to build a project that requests will be put to a python Queue at any arbitrary time, and a set of tensorflow models consume those requests from the queue, and return their results immediately. The models are in different threads, different tf.Graph, but the structure and weight values are the same. Every model use tf.data.Dataset.from_generator to encapsule a python iterator which fetch request from the queue. The problem is, when there is more than one models, request might be blocked until future request come. From testing results, it seems the python iterator indeed got the request just at the time it was put in the queue, but no result came from the model. Moreover, there seems no request was discarded, but blocked by maybe the tf Dataset iterator. Here is my test code: # -*- coding: utf-8 -*- import tensorflow as tf import numpy as np import sys import random import time from queue import Queue from concurrent.futures import ThreadPoolExecutor thread_count=int(sys.argv[1]) request_queue=Queue(128) def data_iter(): while True: yield request_queue.get() def task(): with tf.Graph().as_default(): ds=tf.data.Dataset.from_generator(data_iter, (tf.int32), output_shapes=([1, 8])) sample=ds.make_one_shot_iterator().get_next() with tf.Session() as sess: coord=tf.train.Coordinator() threads=tf.train.start_queue_runners(sess=sess, coord=coord) while not coord.should_stop(): try: result=sess.run(sample) print(result) except: coord.request_stop() coord.join(threads) executor=ThreadPoolExecutor(thread_count) try: for i in range(thread_count): executor.submit(task) rand=random.Random() for i in range(100): request_queue.put(np.full((1, 8), i, 'int32')) time.sleep(1e-3)#to let the model get request from the request_queue t=rand.randint(5,10) print('round {}, request_queue size is about {}, sleeping {} secs...'.format(i, request_queue.qsize(), t)) time.sleep(t) finally: for i in range(thread_count): request_queue.put(None) executor.shutdown() Environment: python 3.5.3, t…
type: Question
has title: Tensorflow Dataset.from_generator blocks input?
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/47948786
tagged with: python
type: UnansweredQuestion
tagged with: multithreading

http://stackoverflow.com/a/48000333
score: 8
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48000274
answers question: http://stackoverflow.com/q/48000274
upvote count: 8
type: AcceptedAnswer
has body: Reverse your list (or better range object). Take the last (now first) element as start value and create a new dict in each iteration through the rest of the reversed list: &gt;&gt;&gt; r = reversed(range(1, 11)) ... d = next(r) ... for x in r: ... d = {x: d} ... d ... {1: {2: {3: {4: {5: {6: {7: {8: {9: 10}}}}}}}}}
type: Answer

http://stackoverflow.com/comment/82892034
score: 0
comment on: http://stackoverflow.com/q/47959028
type: Comment
type: QuestionComment
has text: Adding to above comment: while potentially introducing numerical-trouble, this is imho the only approach you can take here and it's also done in [NLopt](https://nlopt.readthedocs.io/en/latest/NLopt_Algorithms/#cobyla-constrained-optimization-by-linear-approximations).

http://stackoverflow.com/q/47857973
type: AnsweredQuestion
tagged with: list
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/47858033
accepted answer: http://stackoverflow.com/a/47858033
type: Question
has comment: http://stackoverflow.com/comment/82682375
upvote count: 1
answer count: 1
has body: I create a list with numbers from 0 to 131072: x = [i for i in range(131072)] Then all pairs, except for pairs of the same numbers: pairs = [] append_pairs = pairs.append for i in range(len(x)): for j in range(len(x)): if x[i]!=x[j]: x2 = [x[i], x[j]] append_pairs(x2) which gives: pairs = [[0, 1], [0, 2], [0, 3], ... [131071, 131070]] But in this syntax it takes a very very long time. Can it be done faster?
favorite count: 0
tagged with: python-3.x
tagged with: python
has title: How to quickly generating a list of all pairs from a large set of numbers?
tagged with: combinations

http://stackoverflow.com/a/47872569
type: Answer
has comment: http://stackoverflow.com/comment/82713233
has comment: http://stackoverflow.com/comment/82715184
accepted answer of: http://stackoverflow.com/q/47872305
upvote count: 3
has comment: http://stackoverflow.com/comment/82755855
has comment: http://stackoverflow.com/comment/82710998
answers question: http://stackoverflow.com/q/47872305
score: 3
has body: I believe you can replace the negative values with NaN using a boolean array like df[df > 0]. According to the docs, NaN will be correctly handled by pandas' methods: https://pandas.pydata.org/pandas-docs/stable/missing_data.html Input (pandas_data.csv): date,id,diff 2017-01-01,123,5 2017-01-02,123,-3 2017-01-03,123,4 2017-01-04,123,6 2017-01-05,123,3 2017-01-01,124,7 2017-01-02,124,1 2017-01-03,124,-4 2017-01-04,124,6 2017-01-05,124,2 Code: import pandas as pd df = pd.read_csv('pandas_data.csv', header=0) df['mov_avg_diff'] = ( df[df &gt; 0] .groupby(['id'], as_index=False)['diff'] .rolling(3, min_periods=1) .mean() .fillna(0) .reset_index(0, drop=True)).transpose() Result: df date id diff mov_avg_diff 0 2017-01-01 123 5 5.000000 1 2017-01-02 123 -3 5.000000 2 2017-01-03 123 4 4.500000 3 2017-01-04 123 6 5.000000 4 2017-01-05 123 3 4.333333 5 2017-01-01 124 7 7.000000 6 2017-01-02 124 1 4.000000 7 2017-01-03 124 -4 4.000000 8 2017-01-04 124 6 3.500000 9 2017-01-05 124 2 4.000000
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82717683

http://stackoverflow.com/q/47988942
tagged with: cx-freeze
has comment: http://stackoverflow.com/comment/82953765
type: UnansweredQuestion
tagged with: python
tagged with: exe
has comment: http://stackoverflow.com/comment/82946833
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48013309
tagged with: vpython
has comment: http://stackoverflow.com/comment/82947289
has body: I have coded a VPython simulation but I can't compress it into an exe using cx_Freeze. I think it is because of VPython module since cx_Freeze works when I compress other programs that don't use VPython. Detailed steps: This is my test simulation program: from vpython import * ### Simulation ### def run_simulation(r): ball = sphere(radius=r) run_simulation(5) Here is my setup file: from cx_Freeze import setup, Executable setup(name='Test', version='0.1', description='Parse stuff', executables=[Executable('Test.py')]) I go to the folder which these two are in, hold shift and right click, then press on Windows PowerShell. In the shell I type: python setup.py build The supposed outcome is a new folder called 'build' (that has the executable) is created in the already existing folder, but instead I get this error on the PowerShell: KeyError: 'TCL_LIBRARY' For Simon's answer: Here is a picture of the error I get when I try to run it, along with my new code in my set up file. Error: from cx_Freeze import setup, Executable import os os.environ['TCL_LIBRARY'] = C:\Users\mohamed-tayeh\AppData\Local\Programs\Python\Python36-32\tcl\tcl8.6 setup(name='Test', version='0.1', description='Parse stuff', executables=[Executable('Test.py')])
has title: Converting a VPython program to an exe using cx_Freeze
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82965009
favorite count: 0

http://stackoverflow.com/q/47878009
type: Question
tagged with: matplotlib
has answer: http://stackoverflow.com/a/47878725
linked to: http://stackoverflow.com/q/41928387
answer count: 1
has title: Jupyter: How to update plot on button click (ipywidgets)
downvote count: 0
tagged with: jupyter
score: 7
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: ipywidgets
has comment: http://stackoverflow.com/comment/82722898
has body: I am using Jupyter and trying to make my plots interactive. So I have a plot. I have a ipywidgets button. On button click I need to update plot, like interact do with sliders. But I can't. It works only if matplotlib uses 'notebook' backend, but it looks terrible. At same time interact works with any kind of plots. Are there any way to reproduce this, not using interact? #this works fine! But toolbar near the graph is terible #%matplotlib notebook #this does not work %matplotlib inline from matplotlib.pyplot import * button = ipywidgets.Button(description="Button") def on_button_clicked(b): ax.plot([1,2],[2,1]) button.on_click(on_button_clicked) display(button) ax = gca() ax.plot([1,2],[1,2]) show()
upvote count: 7
has comment: http://stackoverflow.com/comment/82723193

http://stackoverflow.com/a/48159688
has comment: http://stackoverflow.com/comment/83532615
has body: I too had this issue and ended up here. Googling lead me to believe that this might be because third party root certificates on the windows host might have somehow been borked. Was it a bad update? Was it a dangerous user? Who knows! Who cares! I did the following, and it resolved my connection issues: 1) Delete HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\SystemCertificates\AuthRoot\Certificates 2) Reboot No more SSL wrong version error
answers question: http://stackoverflow.com/q/47993255
has comment: http://stackoverflow.com/comment/83299614
has comment: http://stackoverflow.com/comment/83454469
score: 0
has comment: http://stackoverflow.com/comment/83559281
type: Answer

http://stackoverflow.com/comment/130311576
type: AnswerComment
comment on: http://stackoverflow.com/a/48005958
type: Comment
score: 1
has text: Note that the force=True addition was made with python 3.8, so make sure you update to that if you want/need to use it.

http://stackoverflow.com/q/47892254
type: Question
has answer: http://stackoverflow.com/a/47901993
tagged with: python-2.7
has body: I am attempting to use an application in my buildroot target which uses PyDrive. I am receiving the following errors: # python driveapp.py ERROR:root:code for hash md5 was not found. Traceback (most recent call last): File "usr/lib/python2.7/hashlib.py", line 147, in &lt;module&gt; File "usr/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor ValueError: unsupported hash type md5 ERROR:root:code for hash sha1 was not found. Traceback (most recent call last): File "usr/lib/python2.7/hashlib.py", line 147, in &lt;module&gt; File "usr/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor ValueError: unsupported hash type sha1 ERROR:root:code for hash sha224 was not found. Traceback (most recent call last): File "usr/lib/python2.7/hashlib.py", line 147, in &lt;module&gt; File "usr/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor ValueError: unsupported hash type sha224 ERROR:root:code for hash sha256 was not found. Traceback (most recent call last): File "usr/lib/python2.7/hashlib.py", line 147, in &lt;module&gt; File "usr/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor ValueError: unsupported hash type sha256 ERROR:root:code for hash sha384 was not found. Traceback (most recent call last): File "usr/lib/python2.7/hashlib.py", line 147, in &lt;module&gt; File "usr/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor ValueError: unsupported hash type sha384 ERROR:root:code for hash sha512 was not found. Traceback (most recent call last): File "usr/lib/python2.7/hashlib.py", line 147, in &lt;module&gt; File "usr/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor ValueError: unsupported hash type sha512 Traceback (most recent call last): File "driveapp.py", line 1, in &lt;module&gt; from pydrive.auth import GoogleAuth File "usr/lib/python2.7/site-packages/pydrive/auth.py", line 3, in &lt;module&gt; File "usr/lib/python2.7/site-packages/httplib2/__init__.py", line 51, in &lt;module&gt; File "…
answer count: 1
downvote count: 0
favorite count: 0
tagged with: linux
tagged with: pydrive
type: UnansweredQuestion
has title: Python in Buildroot - PyDrive errors
tagged with: python
tagged with: buildroot
score: 3
upvote count: 3

http://stackoverflow.com/q/47972513
has title: Python store list as array in postgres database
has comment: http://stackoverflow.com/comment/82914695
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47972603
type: Question
has body: I'm trying to store data from my json file in postgres database. I've got problem storing arrays. When I've decoded my json file one of my fields look like this: [{u'wartosc': u'0', u'tytul': u'Global'}, {u'wartosc': u'150', u'tytul': u'Poland'}] When I'm trying to insert this in my database column (with text[] format) I'm getting error. The only accepted format is this: {{Global,0},{Poland,150}} And I've no idea how to do this. I've tried with for loop, but It gives me values 0 then Global but I need first Global then 0. And it should work for all arrays like this, not only with keys 'wartosc' and 'tytul' Schema of my table: I'm trying to store my data in similar_web
tagged with: postgresql
has comment: http://stackoverflow.com/comment/82914678
score: 0
answer count: 1

http://stackoverflow.com/a/47910036
score: 3
has comment: http://stackoverflow.com/comment/82788498
downvote count: 0
has comment: http://stackoverflow.com/comment/82787618
has body: Since daH is a mathematical function and always produces the same output for a given input, you can cache the values and use them. Sample output $ time python use_cache.py 4 5 5 6 15 real 0m0.194s user 0m0.144s sys 0m0.047s $ Caching decorator $ cat use_cache.py def use_cache_when_possible(func): cache = {} def foo(*args): if args not in cache: cache[args] = func(*args) return cache[args] return foo @use_cache_when_possible def daH(m): if m == 1: return int(1) else: if m &lt;= .5 * (daH(m-1) * (daH(m-1) +1)): return int(daH(m-1)) else: return int(daH(m-1) + 1) print(daH(10)) print(daH(11)) print(daH(15)) print(daH(16)) print(daH(106)) $
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/47909793

http://stackoverflow.com/comment/82853570
has text: You don't need `students.keys()` to iterate over a `dict` - that's already the defaut, so all you need is `for key in students: ....`
type: Comment
comment on: http://stackoverflow.com/a/47941349
type: AnswerComment
score: 0

http://stackoverflow.com/q/48007548
tagged with: bash
tagged with: lxml
answer count: 1
type: UnansweredQuestion
tagged with: python
has title: Speeding up merging multiple XML files in Python
linked to: http://stackoverflow.com/q/47376663
has body: I am using xsl file to merge multiple xml files. The number of files is around 100 and each file has 4000 nodes. The example xml and xsl are available here in this SO question My xmlmerge.py is as follows: import lxml.etree as ET import argparse import os ap = argparse.ArgumentParser() ap.add_argument("-x", "--xmlreffile", required=True, help="Path to list of xmls") ap.add_argument("-s", "--xslfile", required=True, help="Path to the xslfile") args = vars(ap.parse_args()) dom = ET.parse(args["xmlreffile"]) xslt = ET.parse(args["xslfile"]) transform = ET.XSLT(xslt) newdom = transform(dom) print(ET.tostring(newdom, pretty_print=True)) I am writing the output of the python to a xmlfile...so my code to run the python script is as follows: python xmlmerge.py --xmlreffile ~/Documents/listofxmls.xml --xslfile ~/Documents/xslfile.xsl For 100 files when I print the output on a console, it takes around 120 minutes however, if I try to save the same output in a xml file python xmlmerge.py --xmlreffile ~/Documents/listofxmls.xml --xslfile ~/Documents/xslfile.xsl &gt;&gt; ~/Documents/mergedxml.xml This takes around 3 days but yet the merge is not over. I was not sure if the machine is hung and hence tried with just 8 files on a different machine, and it had taken more than 4 hours but still the merge is not complete. I don't know why it takes so much of time when I write to the file but not when I am printing on to the console. Can someone guide me? I am using Ubuntu 14.04, python 2.7.
tagged with: xslt
type: Question
has answer: http://stackoverflow.com/a/48008265
score: 0
tagged with: linux

http://stackoverflow.com/comment/82834293
has text: @mypetlion, that's far from nitpicking! It's a vital piece of information I failed to mention. I'll edit the answer to reflect that. Thank you!
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47915329

http://stackoverflow.com/q/48010276
type: Question
has title: How to estimate eps using knn distance plot in DBSCAN
answer count: 2
tagged with: python
upvote count: 6
tagged with: knn
has answer: http://stackoverflow.com/a/48011796
has answer: http://stackoverflow.com/a/48594371
tagged with: image-processing
tagged with: dbscan
type: UnansweredQuestion
score: 6
downvote count: 0
tagged with: cluster-analysis
favorite count: 0
has body: I have the following code to estimate the eps for DBSCAN. If the code is fine then I have obtained the knn distance plot. The code is : ns = 4 nbrs = NearestNeighbors(n_neighbors=ns).fit(data) distances, indices = nbrs.kneighbors(data) distanceDec = sorted(distances[:,ns-1], reverse=True) plt.plot(indices[:,0], distanceDec) Where data is the array of pixel locations (rows and columns). I have obtained a plot but I am not getting how do I determine the eps. According to DBSCAN paper, the threshold point is the first point in the first valley of the sorted k-dist graph I dont know how do I implement it in the code. Moreover, is ns = 4 is my minPts or is there any way to estimate minPts from eps?

http://stackoverflow.com/a/47996033
answers question: http://stackoverflow.com/q/47995833
score: 1
type: AcceptedAnswer
downvote count: 0
has body: Open the data set with a text editor, and delete the blank lines at the end of the document. Then run your code
accepted answer of: http://stackoverflow.com/q/47995833
type: Answer
has comment: http://stackoverflow.com/comment/82960765
upvote count: 1

http://stackoverflow.com/q/47996058
score: 0
linked to: http://stackoverflow.com/q/38215059
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82960988
tagged with: pycharm
has answer: http://stackoverflow.com/a/47997546
has body: (short version of code) class Animal: __name = "" __gender = "unknown" __height = 0 __weight = 0 __hungry = False def __init__(self, name, gender, height, weight): self.__name, self.__gender, self.__height, self.__weight = name, gender, height, weight def toString(self): return f'{self.__name} is a {self.__gender}, {self.__height} m tall and weights {self.__weight} kg.' PyCharm warns me: Unresolved attribute reference '__name' for class 'Animal' The code is still working as intended. Why does this warning pop up? f-strings seem a cleaner version of str.format for me and they are also faster. PS. As I'm a newbie to Python, please feel free to bring out all the stylish errors or what could and should be done better :) Python version: 3.6.4 PyCharm Community version: 2017.3.1 Picture of the code and the error
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82960217
has comment: http://stackoverflow.com/comment/82962214
type: Question
has title: PyCharm f-string usage in a class displays warning (Unresolved attribute reference '__name' for class...)
has comment: http://stackoverflow.com/comment/82960334

http://stackoverflow.com/q/47888003
has body: I have a custom Django mixin which should be imported/added to a view class only if some app is installed, e.g. class MyView(LoginRequiredMixin, CustomMixin, View): # ^ # this is an optional mixin pass How to achieve this in Django?
tagged with: class
type: AnsweredQuestion
tagged with: python-3.x
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/47888191
has answer: http://stackoverflow.com/a/47888869
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47888191
has title: How can I dynamically define the list of base classes for a Python class?
score: 0
linked to: http://stackoverflow.com/q/28204130
accepted answer: http://stackoverflow.com/a/47888869
tagged with: inheritance

http://stackoverflow.com/a/73368380
score: 1
upvote count: 1
has body: I have encountered this myself. I download on a regular basis about 10 files daily from S3. I noticed that if the file is too large (~8MB), I get the SignatureDoesNotMatch error only for that file, but not the other files which are small in size. I then tried to use the shell "aws s3 cp" CLI command and got the same result. My co-worker suggested using "aws s3api get-object", which now works 100% of the time. However, I can't find the equivalent python script, so I'm stuck running the shell script. (s3.download_file or s3.download_fileobj don't work either.)
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47994825

http://stackoverflow.com/q/47994063
tagged with: python-3.x
has body: I have a tensor that looks like this: arr = tf.convert_to_tensor([[3, 1], [6, 2], [1, 1], [3, 0], [5, 1], [1, 0], [4, 2]]) And I need to compute the average of the first elements of each cell only when the second element is equal to 1. So in this example I would select the cells [3, 1], [1, 1], [5, 1] and calculate average(3, 1, 5)=3. Then, I need to repeat this operation for the cells ending with 0 and then 2, and sum up all the averages. I am writing this as a component for a loss function in a Neural Network, so I need to do this operation using only TensorFlow functions. I have solved this problem in Numpy, and it looks like this: means_sum = sum([np.mean(np.extract(arr.transpose()[1] == rank, arr.transpose()[0])) for rank in [0, 1, 2]]) But I can't find a way to do it in TensorFlow. Any ideas?
has answer: http://stackoverflow.com/a/47995094
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47995094
score: 0
tagged with: tensorflow
type: Question
has title: How do you divide a tensor based on its content?
answer count: 1

http://stackoverflow.com/comment/82935437
type: QuestionComment
comment on: http://stackoverflow.com/q/47983240
has text: @ozan see the question I linked to. Your question is a duplicate.
score: 0
type: Comment

http://stackoverflow.com/q/47858632
has answer: http://stackoverflow.com/a/47858692
possible better answer: http://stackoverflow.com/a/47858659
has answer: http://stackoverflow.com/a/47858659
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47858692
type: Question
has title: Adding a second plot to an existing matplotlib chart
tagged with: matplotlib
tagged with: python-2.7
score: 0
has body: I would like to have a function that adds plots to an existing chart when called. Right now my empty plot shows, but called the function never seems to happen as it waits until I close the chart window. The program then ends without reopening the chart window. import numpy as np import matplotlib.pyplot as plt import time fig, ax = plt.subplots() plt.show() def plotting(slope, intercept): x_vals = np.array(ax.get_xlim()) y_vals = intercept + slope * x_vals ax.plot(x_vals, y_vals, '-') plt.show() plotting(10,39) time.sleep(1) plotting(5,39)
answer count: 2

http://stackoverflow.com/comment/82755262
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47893496
has text: No, my point is that with postgres you can use the third model, not mentioned in the post - store json in `data` field instead of pickle
score: 0

http://stackoverflow.com/comment/82936085
score: 1
has text: you can shuffle a file without reading it _entirely_ into memory. Of course you have to read some parts into memory.
comment on: http://stackoverflow.com/q/47983576
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47963421
has answer: http://stackoverflow.com/a/47963823
type: Question
tagged with: numpy
score: 2
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/47963823
tagged with: python
has body: Not entirely sure how I should title this question. But how can I get a section of a numpy array that will have some of the values outside the boundary? See my simple example code below: def get_section(a, center, square_radius): return a[center[0] - square_radius:center[0] + square_radius + 1, \ center[1] - square_radius:center[1] + square_radius + 1] array = [ [1, 2, 3, 4, 5, 6, 7, 8, 9], [2, 3, 4, 5, 6, 7, 8, 9, 1], [3, 4, 5, 0, 7, 8, 9, 1, 2], [4, 5, 6, 7, 8, 9, 1, 2, 3], [5, 0, 7, 8, 9, 4, 5, 6, 7], [6, 7, 8, 9, 1, 2, 3, 4, 5] ] a = np.asarray(array) square_radius = 2 center = [2,3] print(get_section(a, center, square_radius)) center = [4,1] print(get_section(a, center, square_radius)) Say I have an array, but I would like to get a small section of it, by specifying the center and the radius of the section I'd like. The first one will print out: [[2 3 4 5 6] [3 4 5 6 7] [4 5 0 7 8] [5 6 7 8 9] [0 7 8 9 4]] Which is exactly what I wanted. For simplicity, I placed '0' on the center of the 2 examples identified. But the second one will print out [] For the second one I'd like to fill in the outside values with -1. Thus I'd like it to return: [[-1 3 4 5 0] [-1 4 5 6 7] [-1 5 0 7 8] [-1 6 7 8 9] [-1 -1 -1 -1 -1]] How can I do this in numpy?
favorite count: 0
has title: Fill in a section out of bounds in a numpy array
upvote count: 2
tagged with: indexing
type: AnsweredQuestion

http://stackoverflow.com/q/47925877
tagged with: mean-shift
tagged with: python
tagged with: opencv
tagged with: image-processing
has comment: http://stackoverflow.com/comment/82820008
has title: AttributeError: 'builtin_function_or_method' object has no attribute 'segment'
type: Question
tagged with: image-segmentation
upvote count: 0
has comment: http://stackoverflow.com/comment/82819839
has answer: http://stackoverflow.com/a/47930535
answer count: 1
score: -2
has body: Facing error in image segmentation using meanshift algorithm in following line: import cv2 (segmented_image, labels_image, number_regions) = cv2.meanShift.segment(im, spatial_radius=6, range_radius=4.5, min_density=50) complete traceback is: Traceback (most recent call last): File "image_processing.py", line 16, in &lt;module&gt; (segmented_image, labels_image, number_regions) = cv2.meanShift.segment(im, spatial_radius=6, AttributeError: 'builtin_function_or_method' object has no attribute 'segment'
favorite count: 0
type: UnansweredQuestion
downvote count: 2

http://stackoverflow.com/comment/82689359
comment on: http://stackoverflow.com/q/47862070
has text: first try to print the values and see if you are getting those values properly , after check type() of value and try something '4.74036126519e-07'=='value' and see if it give 'True' or 'False' ?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47928816
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/83374176
type: UnansweredQuestion
tagged with: django
upvote count: 1
type: Question
score: 1
has body: I'm using Google Calendar API library with django. creating or updating an event with the request parameter "sendNotification" set to True, the guests included in the event do not receive any notification via email. This is the code : created_event = service.events().update(calendarId=calendar_id,sendNotifications=True, eventId=event_id, body=modified_event).execute() the Notification setting in the calendars are correct ( enabled , and Email type is selected ) I'm using a service account for authentication, I do not know if it can affect thanks for the support
downvote count: 0
favorite count: 0
has title: Using the google calendar api libraries with django The sendNotification parameter does not send notification mails to an event's guests
tagged with: notifications
tagged with: google-calendar-api

http://stackoverflow.com/q/47932809
tagged with: python
has body: so i have this pymysql dictionary. basically an entire table. with many rows. thanks to: conn.cursor(pymysql.cursors.DictCursor) when i print one row/line it looks like this {u'key1': 10, u'key2': 20} so i assume the entire dictionary looks like this: {{u'key1': 10, u'key2': 20}, {u'key1': 11, u'key2': 21}, {u'key1': 12, u'key2': 22}} how can i append a row/line?? dict.append({u'key1': 13, u'key2': 23}) also.. why cant i use dict[0] to access a row of the dictionary? i have to use a for loop just to get 1 row?
has comment: http://stackoverflow.com/comment/82834790
has comment: http://stackoverflow.com/comment/82834854
has comment: http://stackoverflow.com/comment/82834884
accepted answer: http://stackoverflow.com/a/47933002
has comment: http://stackoverflow.com/comment/82835117
score: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82834787
type: Question
has title: how to append a row/line to a multi row/line dictionary
has comment: http://stackoverflow.com/comment/82834971
has answer: http://stackoverflow.com/a/47933002
answer count: 1
has comment: http://stackoverflow.com/comment/82835036

http://stackoverflow.com/comment/82807507
comment on: http://stackoverflow.com/a/47919891
has text: cnts = cv.findContours(thresh.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) print("cnts is ",cnts) like the above: output is following: cnts is (array([[255, 255, 255, ..., 255, 255, 255], [255, 255, 255, ..., 255, 255, 255], [255, 255, 255, ..., 255, 255, 255], ..., [255, 255, 255, ..., 255, 255, 255], [255, 255, 255, ..., 255, 255, 255]], dtype=uint8), [array([[[ 0, 0]], [[ 0, 131]], [[199, 131]], [[199, 0]]], dtype=int32)], array([[[-1, -1, -1, -1]]], dtype=int32))
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47947999
has title: Error on terminal while installing django taggit via pip install on ubuntu gnome
tagged with: django-taggit
tagged with: python
tagged with: web
answer count: 0
has comment: http://stackoverflow.com/comment/82866110
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82866019
tagged with: django
tagged with: tags
type: Question
has comment: http://stackoverflow.com/comment/82866094
has body: I am getting the error on installing django-taggit module... what might be the problem? Please help I have tried everythin and it̀s still bringing the same error even tried updating my setup tools :~$ pip install django-taggit Collecting django-taggit Using cached django_taggit-0.22.1-py2.py3-none-any.whl Installing collected packages: django-taggit Exception: Traceback (most recent call last): File "/home/krafty-coder/.local/lib/python3.5/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/home/krafty-coder/.local/lib/python3.5/site-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/home/krafty-coder/.local/lib/python3.5/site-packages/pip/req/req_set.py", line 784, in install **kwargs File "/home/krafty-coder/.local/lib/python3.5/site-packages/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/home/krafty-coder/.local/lib/python3.5/site-packages/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/home/krafty-coder/.local/lib/python3.5/site-packages/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/home/krafty-coder/.local/lib/python3.5/site-packages/pip/wheel.py", line 316, in clobber ensure_dir(destdir) File "/home/krafty-coder/.local/lib/python3.5/site-packages/pip/utils/__init__.py", line 83, in ensure_dir os.makedirs(path) File "/usr/lib/python3.5/os.py", line 241, in makedirs mkdir(name, mode) PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.5/dist-packages/taggit'
linked to: http://stackoverflow.com/q/34146065
score: 0

http://stackoverflow.com/q/48000029
has comment: http://stackoverflow.com/comment/82968683
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82968621
type: UnansweredQuestion
tagged with: python
has body: Working on a codefights problem. Got stuck on the solution, or rather, solving the way codefights wanted me too. Here is the solution def listBeautifier(a): res = a[:] while res and res[0] != res[-1]: a, *res, d = res return res* I did some printing of the result to try and understand what's going on and some experimentation to see how it works. From what I gathered, printing out various tests, the first item of res get's assigned to a and the last to d (which remain unused). Then, res is unpacked and each element of res is reassigned as the remaining bit of the list. I tried the following code def listBeautifier(a): res = a[:] while res and res[0] != res[-1]: a,c, *res, d = res return res* which threw an error so I gather this must be done symmetrically. What is python doing exactly? I see what's happening but not how.
answer count: 0
type: Question
tagged with: iterable-unpacking
has title: List slicing and unpacking
score: 0
tagged with: argument-unpacking

http://stackoverflow.com/comment/82713777
type: AnswerComment
comment on: http://stackoverflow.com/a/47873873
score: 0
type: Comment
has text: sorry, I fixed the problem. I just had to put quotes between `"%%1"` so that any spaces in the files are OK. it was just a coincidence that they were more complicated files :) thanks for all your help!

http://stackoverflow.com/a/47948771
has body: It's possible to shorten it to: age = int(input('Age: ')) print('Kid' if age &lt;= 10 else 'Teen' if age &lt;= 20 else 'Adult') That said, unless you're doing one-liners for fun, I'd stick to your original code, after fixing the test for Teen and just making the Adult case a plain else (no need to retest &gt; 20 since the previous cases eliminated the other possibilities).
upvote count: 1
answers question: http://stackoverflow.com/q/47948749
score: 1
downvote count: 0
type: Answer

http://stackoverflow.com/q/47941087
has body: How do I perform the below write-to-file task in an easier or one-liner way? >>> log="/tmp/test_write.log" >>> file = open(log, "a") >>> file.write("x" * 10) >>> file.write("\n") >>> file.close() Is there some like this (bash/shell) in Python? log="/tmp/test_write.log" printf "`printf 'x%0.s' {1..10}`\n" >> $log
has title: Single-liner to write to file in Python
has answer: http://stackoverflow.com/a/47941116
favorite count: 0
has answer: http://stackoverflow.com/a/66989016
upvote count: 3
has answer: http://stackoverflow.com/a/47941239
has answer: http://stackoverflow.com/a/47941131
accepted answer: http://stackoverflow.com/a/47941131
tagged with: python
possible better answer: http://stackoverflow.com/a/66989016
answer count: 4
type: AnsweredQuestion
downvote count: 0
type: Question
score: 3

http://stackoverflow.com/comment/82757412
type: QuestionComment
has text: Please run your code using `pdb` like this: `python -m pdb <filename of your python file>`. Then enter `step`. For each `step` command entered, the Python debugger proceeds one program line. At any point you can print variable values using `print(<varname>)`. This way you should be able to find out what is happening.
type: Comment
comment on: http://stackoverflow.com/q/47895255
score: 0

http://stackoverflow.com/q/47967778
has title: How to create a time-series graph from a number I get from API request?
score: 0
has comment: http://stackoverflow.com/comment/82906017
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has body: Lets assume that I run a simple loop that requests a number from an API and prints it every 30 seconds: import requests from time import sleep while True: # Get difficulty number: stats = requests.get('http://moneroblocks.info/api/get_stats/').json() diff = stats['difficulty'] # Print difficulty number: print(diff) # Pause for 30 seconds: sleep(30) What is the easiest way to get updated time-series graph every 30 seconds, instead of just a number?
answer count: 0
has comment: http://stackoverflow.com/comment/82906561
tagged with: timeserieschart
type: Question
tagged with: graph

http://stackoverflow.com/comment/93131468
type: Comment
comment on: http://stackoverflow.com/a/47870318
type: AnswerComment
has text: All those methods have been moved starting from pip version > 10. I provided another answer below.
score: 0

http://stackoverflow.com/comment/88219019
type: AnswerComment
type: Comment
has text: @vanilla double backslashes are still important when working on windows though.
comment on: http://stackoverflow.com/a/47906558
score: 0

vertica
tag name: vertica
tags question: http://stackoverflow.com/q/47992358
type: Tag

http://stackoverflow.com/comment/82979022
has text: Yes there are duplicate IDs. Assuming that there are no duplicate IDs, will it be simpler?
score: 0
comment on: http://stackoverflow.com/q/48005341
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47984773
answers question: http://stackoverflow.com/q/47984705
downvote count: 0
type: Answer
has body: If we look inside the QT documentation, we can read the following for the QMessageBox.question method's return value: Returns the identity of the standard button that was clicked. The identity for every standard button is an integer number, which is also specified by the documentation: QMessageBox::Yes 0x00004000 QMessageBox::No 0x00010000 If we convert this hex values to decimals, we get 16384 and 65536. why not True or False? Because there are a lot more options here, there are a lot more standard buttons (ex. Ok, Open, Save, Cancel, etc.) For more information you should read the documentation for QT: http://doc.qt.io/qt-5/qmessagebox.html (yes, it's for C++ but it is also applicable for the python wrapper)
score: 1
upvote count: 1

http://stackoverflow.com/a/47902476
has comment: http://stackoverflow.com/comment/119924779
has comment: http://stackoverflow.com/comment/82800384
score: 34
has comment: http://stackoverflow.com/comment/120776799
has body: You can use a simple breadth first search for this. Basically, each cell in your grid corresponds to a node in the graph, with edges between adjacent cells. Start at the starting position, and keep expanding passable cells until you find a goal cell. def bfs(grid, start): queue = collections.deque(start) seen = set([start]) while queue: path = queue.popleft() x, y = path[-1] if grid[y][x] == goal: return path for x2, y2 in ((x+1,y), (x-1,y), (x,y+1), (x,y-1)): if 0 &lt;= x2 &lt; width and 0 &lt;= y2 &lt; height and grid[y2][x2] != wall and (x2, y2) not in seen: queue.append(path + [(x2, y2)]) seen.add((x2, y2)) Grid setup and results: (Note that I'm using symbols instead of numbers, simply for the reason that it's easier to visually parse the grid this way and to verify the solution.) wall, clear, goal = "#", ".", "*" width, height = 10, 5 grid = ["..........", "..*#...##.", "..##...#*.", ".....###..", "......*..."] path = bfs(grid, (5, 2)) # [(5, 2), (4, 2), (4, 3), (4, 4), (5, 4), (6, 4)]
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82799308
has comment: http://stackoverflow.com/comment/119920169
answers question: http://stackoverflow.com/q/47896461
accepted answer of: http://stackoverflow.com/q/47896461
type: Answer
upvote count: 34
has comment: http://stackoverflow.com/comment/128594111
has comment: http://stackoverflow.com/comment/82810182
has comment: http://stackoverflow.com/comment/82799562
has comment: http://stackoverflow.com/comment/82804496

http://stackoverflow.com/a/47996882
accepted answer of: http://stackoverflow.com/q/47996792
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47996792
upvote count: 2
has comment: http://stackoverflow.com/comment/82961964
has body: Using groupby + value_counts + head - df.groupby('id')\ .number.value_counts()\ .groupby(level=0)\ .head(1)\ .reset_index(name='count')\ .drop('count', 1) id number 0 1 3 1 3 4 2 4 5
has comment: http://stackoverflow.com/comment/82962028

http://stackoverflow.com/comment/82782174
score: 0
type: Comment
type: QuestionComment
has text: try `plt.clf()` (clears figure) or `plt.cla()` (clears axis) after saving the figure! Let me know if that helps
comment on: http://stackoverflow.com/q/47907427

http://stackoverflow.com/q/47963548
tagged with: dataframe
type: UnansweredQuestion
has body: I have dataframes df1 and df2 both with columns ["Ticker", "Adj.Factor", "Date"]. I want to add to df2 the complete row from df1 if the value of "Adj.Factor" in that row in df1 equals to 0. I have the following code. for x in range(tot_len): if df1.iloc[x]['Adj.Factor'] == 0: df2.append(df1.iloc[x]) --&gt; not working. ` I have tried printing the values and it shows the correct output. But the values are not appended to df2.
downvote count: 0
has title: How to append a row to another dataframe
has answer: http://stackoverflow.com/a/47963574
type: Question
score: 14
tagged with: pandas
tagged with: python
tagged with: append
favorite count: 0
upvote count: 14
answer count: 2
has answer: http://stackoverflow.com/a/61090187
has comment: http://stackoverflow.com/comment/82896518

http://stackoverflow.com/q/47966602
has body: First I used: train['source']='train' test['source']='test' data = pd.concat([train,test],ignore_index=True) 2. Performed data exploration,cleaning on fulldata and now I wanted to split them back into train and test datsets. I used the following code : #Divide into test and train: train = data.loc[data['source']=="train"] test = data.loc[data['source']=="test"] But after doing so train and test datasets are empty dataframes giving just column names. What am I doing wrong??
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82903552
tagged with: python
has comment: http://stackoverflow.com/comment/82903142
type: Question
has comment: http://stackoverflow.com/comment/82903209
has comment: http://stackoverflow.com/comment/82903032
has comment: http://stackoverflow.com/comment/82903060
has comment: http://stackoverflow.com/comment/82902996
has title: Getting an empty dataframe after splitting my dataset back into train and test datasets
has comment: http://stackoverflow.com/comment/82903108
score: 0
tagged with: pandas

http://stackoverflow.com/comment/82781001
comment on: http://stackoverflow.com/a/47891761
has text: Inserting duplicates? `defaultdict` differs from `dict` insofar that it prepares a default value for each key which is read before being written. It has nothing to do with duplicates. Duplicates are handled likewise in `dict` as in `defaultdict` (i. e. just one entry is kept per key).
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/47886200
tagged with: sys
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47891728
has body: I'm trying to add something to my teardown method so that in the event of an exception it takes a screenshot before closing the browser instance. So far I have: - def tearDown(self): if sys.exc_info()[0]: test_method_name = self._testMethodName screenshot_name = common_functions.create_unique_id() + test_method_name + ".png" common_functions.take_screenshot(self.driver, screenshot_name) self.driver.close() As it is the screenshot is never taken and if I change the if statement to if sys.exc_info(): then it always takes a screenshot regardless of whether an exception is raised. When I query what is returned by sys.exc_info I get None, None, None. I was hoping that the first element should contain the exception name at least.
type: AnsweredQuestion
score: 1
tagged with: python-unittest
tagged with: chrome-web-driver
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/82739859
accepted answer: http://stackoverflow.com/a/47891728
answer count: 1
has comment: http://stackoverflow.com/comment/82741774
favorite count: 0
tagged with: screenshot
has title: Cannot react to exception in teardown

http://stackoverflow.com/comment/82965767
score: 0
comment on: http://stackoverflow.com/q/47998664
type: Comment
type: QuestionComment
has text: What's `arr`? You defined `alist`, `arr_unicode`, and `arr_object`, but then referred to some unknown `arr`.

string
tags question: http://stackoverflow.com/q/47959971
tags question: http://stackoverflow.com/q/47957216
tags question: http://stackoverflow.com/q/47928839
tags question: http://stackoverflow.com/q/47856796
tags question: http://stackoverflow.com/q/47913047
tags question: http://stackoverflow.com/q/47862783
tags question: http://stackoverflow.com/q/47903820
tags question: http://stackoverflow.com/q/47918611
tags question: http://stackoverflow.com/q/47948120
tags question: http://stackoverflow.com/q/47999233
tags question: http://stackoverflow.com/q/47931380
tags question: http://stackoverflow.com/q/47959029
tags question: http://stackoverflow.com/q/48009064
tags question: http://stackoverflow.com/q/47930650
tags question: http://stackoverflow.com/q/47957020
tags question: http://stackoverflow.com/q/47922675
tags question: http://stackoverflow.com/q/47983212
tags question: http://stackoverflow.com/q/47953966
tags question: http://stackoverflow.com/q/47926096
tags question: http://stackoverflow.com/q/47888317
tags question: http://stackoverflow.com/q/47908050
tags question: http://stackoverflow.com/q/47895890
tags question: http://stackoverflow.com/q/47901771
tags question: http://stackoverflow.com/q/48000877
tags question: http://stackoverflow.com/q/47881070
tags question: http://stackoverflow.com/q/47987878
tags question: http://stackoverflow.com/q/47887252
tags question: http://stackoverflow.com/q/47956457
tag name: string
tags question: http://stackoverflow.com/q/47976142
tags question: http://stackoverflow.com/q/47982331
tags question: http://stackoverflow.com/q/47905783
tags question: http://stackoverflow.com/q/47897166
tags question: http://stackoverflow.com/q/47955464
tags question: http://stackoverflow.com/q/47907585
tags question: http://stackoverflow.com/q/47901728
tags question: http://stackoverflow.com/q/47966093
tags question: http://stackoverflow.com/q/47898526
tags question: http://stackoverflow.com/q/47873305
tags question: http://stackoverflow.com/q/47857863
type: Tag
tags question: http://stackoverflow.com/q/47959532
tags question: http://stackoverflow.com/q/47995099
tags question: http://stackoverflow.com/q/47903700
tags question: http://stackoverflow.com/q/47908767
tags question: http://stackoverflow.com/q/47928702
tags question: http://stackoverflow.com/q/47879758
tags question: http://stackoverflow.com/q/47899565
tags question: http://stackoverflow.com/q/47861912
tags question: http://stackoverflow.com/q/47970561
tags question: http://stackoverflow.com/q/47985869
tags question: http://stackoverflow.com/q/47967809
tags question: http://stackoverflow.com/q/48014244
tags question: http://stackoverflow.com/q/47937697
tags question: http://stackoverflow.com/q/47992947
tags question: http://stackoverflow.com/q/47920965
tags question: http://stackoverflow.com/q/47956930
tags question: http://stackoverflow.com/q/47872522
tags question: http://stackoverflow.com/q/48006240
tags question: http://stackoverflow.com/q/47956169
tags question: http://stackoverflow.com/q/47977474
tags question: http://stackoverflow.com/q/47972377
tags question: http://stackoverflow.com/q/48013457
tags question: http://stackoverflow.com/q/47954300
tags question: http://stackoverflow.com/q/47883436
tags question: http://stackoverflow.com/q/47946317
tags question: http://stackoverflow.com/q/47973663
tags question: http://stackoverflow.com/q/47908741
tags question: http://stackoverflow.com/q/47936547
tags question: http://stackoverflow.com/q/47861704
tags question: http://stackoverflow.com/q/47974814
tags question: http://stackoverflow.com/q/47920064
tags question: http://stackoverflow.com/q/47875765
tags question: http://stackoverflow.com/q/47962817
tags question: http://stackoverflow.com/q/47992019
tags question: http://stackoverflow.com/q/47862083
tags question: http://stackoverflow.com/q/47970891
tags question: http://stackoverflow.com/q/47976874
tags question: http://stackoverflow.com/q/47858219
tags question: http://stackoverflow.com/q/47861976

http://stackoverflow.com/comment/82823802
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47919165
has text: @mootmoot that's a fake key not a valid one :-). I post that snippet only because, it might be helpful for someone.
score: 1

http://stackoverflow.com/comment/82831680
comment on: http://stackoverflow.com/a/47931440
score: 0
type: Comment
has text: You could stick your constants into a separate module and use that.
type: AnswerComment

http://stackoverflow.com/a/47885529
answers question: http://stackoverflow.com/q/47885300
type: Answer
upvote count: 4
downvote count: 0
has body: Have you consider using shift? import pandas as pd import numpy as np df = pd.DataFrame({"GDP": np.random.normal(3,1,51), "Pop":np.random.randint(1,10,51)}, index=np.arange(1950,2001)) df["res"] = df.GDP.shift(1)/df.Pop
score: 4

http://stackoverflow.com/a/47930429
answers question: http://stackoverflow.com/q/47930428
downvote count: 1
has body: Assuming out is an initialized copy of array, M and N their rows and columns numbers, and we are using a language indexing arrays from 0 to (M-1) and (N-1) : In Python : def rotate_180(array, M, N, out): for i in range(M): for j in range(N): out[i, N-1-j] = array[M-1-i, j] This takes 5.82 s on a 4000×3000 array. In parallelized Cython + OpenMP using Memviews : cdef void rotate_180(float[:, :] array, int M, int N, float[:, :] out) nogil: cdef size_t i, j with parallel(num_threads=8): for i in prange(M): for j in range(N): out[i, N-1-j] = array[M-1-i, j] This takes 5.45 s on a 4000×3000 array. In comparison, numpy with np.rot90(array, 2) takes 8.58 µs. Edit : to avoid know-it-all comments out of the point, here is what it does : a = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) rotate_180(a, 3, 3, b) b = array([[9, 8, 7], [6, 5, 4], [3, 2, 1]]) Using 2 successive 90° rotations with numpy built-in function, we get : np.rot90(a, 2) out = array([[9, 8, 7], [6, 5, 4], [3, 2, 1]]) So this rotate_180() is indeed a 180° rotation. Now : np.flip(a, 0) out = array([[7, 8, 9], [4, 5, 6], [1, 2, 3]]) is not a rotation but a symmetry along the last line. If we compose 2 symmetries along each direction : np.flip(np.flip(a, 1), 0) out = array([[9, 8, 7], [6, 5, 4], [3, 2, 1]]) we also get a 180° rotation. So, yes, thank you, my code does what it says.
type: AcceptedAnswer
type: Answer
score: 13
accepted answer of: http://stackoverflow.com/q/47930428
upvote count: 14

http://stackoverflow.com/comment/82833110
score: 0
has text: Have you tried: https://pypi.python.org/pypi/tensorflow-gpu ?
comment on: http://stackoverflow.com/q/47932029
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47963491
type: AcceptedAnswer
downvote count: 0
has body: I cannot try it out but here are my thoughts: The bins argument can also be a sequence of bin edges. Therefore you can take the minimum and maximum of durations and create a sequence with a step size of 5 (here using the numpy library): import numpy as np sequence = np.arange(min(dat['duration']), max(dat['duration']), 5) (Maybe you want to floor/ceil the minimum and maximum values to integers.) Here the code relies on the fact that I read the data using the pandas library. It can easily be filtered using pandas as well: import pandas as pd dat = pd.read_csv('YOURFILE.csv') dat_filtered = dat[dat['duration'] &lt; 75] Happy Holidays.
type: Answer
score: 1
answers question: http://stackoverflow.com/q/47963339
accepted answer of: http://stackoverflow.com/q/47963339
upvote count: 1

http://stackoverflow.com/q/47906119
has comment: http://stackoverflow.com/comment/82782100
type: AnsweredQuestion
score: 2
tagged with: colorbar
upvote count: 2
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/82813737
has answer: http://stackoverflow.com/a/47910725
has comment: http://stackoverflow.com/comment/82781856
type: Question
has title: matplotlib colorbar minor ticks color and number of minor ticks
accepted answer: http://stackoverflow.com/a/47910725
has comment: http://stackoverflow.com/comment/82789257
answer count: 1
downvote count: 0
has body: I have a matplotlib (v2.1.1) plot that includes a colorbar. When plotted on a figure with a white background, I get a colorbar as shown in one of the attached images. That is fine (though I'd love to know how to set the number of minor ticks). However when I set the background to black using fig.patch.set_facecolor(back_color) with back_color = 'black' I get a color bar which lacks the minor ticks and the multiplier at the top. I've already changed the color of the y tick labels manually, but can't find out how to change the minor tick or multiplier colors. [Edit] OK, here is a code which illustrates the problem. I solved the minor tick color problem, that leaves me with (in order of priority) the multiplier color &amp; the number of minor ticks. The code is below, change the background variable to 1 from 0 to see the multiplier. import matplotlib.pyplot as plt background = 0 if background == 0: back_color='black' fore_color='white' else: back_color='white' fore_color='black' fig, ax = plt.subplots() fig.patch.set_facecolor(back_color) im = ax.imshow([[1e5,2e5],[0.1e5,1e5]]) ax.axis( 'off' ) # don't show the axes ticks/lines/etc. associated with the image cb = plt.colorbar(im) cb.formatter.set_scientific(True) cb.formatter.set_powerlimits((0,0)) cbytick_obj = plt.getp(cb.ax, 'yticklabels' ) #Set y tick label color plt.setp(cbytick_obj, color=fore_color) cb.ax.tick_params(which = 'minor', length = 2, color = fore_color ) cb.ax.tick_params(which = 'major', length = 4, color = fore_color ) cb.ax.minorticks_on() cb.update_ticks() plt.show()
favorite count: 0
has comment: http://stackoverflow.com/comment/82780296
tagged with: python

http://stackoverflow.com/comment/82875234
score: 1
comment on: http://stackoverflow.com/q/47952911
has text: The easiest option would be to rename them in your dataframe.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82832142
comment on: http://stackoverflow.com/a/47930911
score: 0
has text: not sure why this give me the error: operands could not be broadcast together with shapes (4,10) (4,9)
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47947625
has body: I would like to open a bash session in python and keep interacting with it as if it was a terminal. This is what I have so far: import subprocess as s class Session: proc = None def execute(self, cmd): if self.proc is None: self.proc = s.Popen("/bin/bash", shell=True, stdin=s.PIPE, stdout=s.PIPE, stderr=s.STDOUT) cmd = cmd + ' ; echo EOF\n' self.proc.stdin.write(cmd.encode()) output = '' while not output.endswith("EOF"): output += self.proc.stdout.read(1).decode() return output sess = Session() sess.execute("export MY_VAR=HELLO") sess.execute("git clone https://github.com/internetsadboy/crapi.git") However, during git clone I get this output, and it fails Cloning into 'crapi'... EOF
linked to: http://stackoverflow.com/q/19880190
answer count: 1
has comment: http://stackoverflow.com/comment/82865415
upvote count: 1
has answer: http://stackoverflow.com/a/47947680
tagged with: python
favorite count: 0
tagged with: subprocess
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82865454
has title: How to open a bash session with Python and keep communicating with it?
score: 1
has comment: http://stackoverflow.com/comment/82865120
type: Question
tagged with: bash

http://stackoverflow.com/a/47959088
accepted answer of: http://stackoverflow.com/q/47959029
has body: The "null" value for all slice parts is None. slice(-4, None)
answers question: http://stackoverflow.com/q/47959029
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 3
score: 3

http://stackoverflow.com/q/47879660
type: Question
has title: How to use Python Dbus bindings in Anaconda
has body: I am trying to install dbus on Anaconda python environment and I am struggling. Here is the error message I am getting: e@gateway:~$ python Python 3.5.4 |Anaconda custom (64-bit)| (default, Oct 13 2017, 11:22:58) [GCC 7.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import dbus Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/e/anaconda3/lib/python3.5/site-packages/dbus/__init__.py", line 77, in &lt;module&gt; import dbus.types as types File "/home/e/anaconda3/lib/python3.5/site-packages/dbus/types.py", line 6, in &lt;module&gt; from _dbus_bindings import ( ImportError: /home/e/anaconda3/lib/python3.5/site-packages/_dbus_bindings.so: undefined symbol: _Py_ZeroStruct &gt;&gt;&gt; Here are some of the outputs I think may be asked: e@gateway:~$ conda install dbus Fetching package metadata ........... Solving package specifications: . # All requested packages already installed. # packages in environment at /home/e/anaconda3: # dbus 1.10.22 h3b5a359_0 e@gateway:~$ sudo apt-get install libdbus-glib-1-dev libdbus-1-dev Reading package lists... Done Building dependency tree Reading state information... Done libdbus-glib-1-dev is already the newest version (0.106-1). libdbus-1-dev is already the newest version (1.10.6-1ubuntu3.3). 0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded. e@gateway:~$ sudo apt-get install dbus Reading package lists... Done Building dependency tree Reading state information... Done dbus is already the newest version (1.10.6-1ubuntu3.3). 0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded. e@gateway:~$ which python /home/e/anaconda3/bin/python e@gateway:~$ conda --version conda 4.3.31 e@gateway:~$ sudo /home/e/anaconda3/bin/python -m pip install dbus-python The directory '/home/e/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that dir…
tagged with: ubuntu
tagged with: dbus
answer count: 2
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 3
tagged with: anaconda
upvote count: 3
has answer: http://stackoverflow.com/a/48160569
has answer: http://stackoverflow.com/a/48159244

http://stackoverflow.com/comment/82861233
has text: axis 0 is row direction. axis 1 is column direction *of the result* (!) not the arguments.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47945669
type: QuestionComment

http://stackoverflow.com/comment/82962820
comment on: http://stackoverflow.com/q/47996637
score: 1
has text: Actually after you run `python test.py`, the Python process is still running and hasn't returned, so the current terminal window can't receive any other inputs.
type: Comment
type: QuestionComment

rest
tags question: http://stackoverflow.com/q/47887547
tags question: http://stackoverflow.com/q/48011256
tags question: http://stackoverflow.com/q/47941234
tags question: http://stackoverflow.com/q/47863300
tags question: http://stackoverflow.com/q/47874233
tags question: http://stackoverflow.com/q/47910547
tags question: http://stackoverflow.com/q/47981691
tags question: http://stackoverflow.com/q/47861874
tags question: http://stackoverflow.com/q/47977485
type: Tag
tags question: http://stackoverflow.com/q/47903042
tags question: http://stackoverflow.com/q/47930324
tags question: http://stackoverflow.com/q/47957499
tags question: http://stackoverflow.com/q/47948051
tag name: rest
tags question: http://stackoverflow.com/q/47893309
tags question: http://stackoverflow.com/q/48006800

http://stackoverflow.com/comment/82696784
type: QuestionComment
comment on: http://stackoverflow.com/q/47856476
score: 1
has text: For daisy-chaining you can use Hyperlinked Serializers: http://www.django-rest-framework.org/api-guide/serializers/#hyperlinkedmodelserializer
type: Comment

http://stackoverflow.com/q/47865002
tagged with: oop
linked to: http://stackoverflow.com/q/42228895
type: Question
score: 5
has title: Global variable in pytest
answer count: 1
has body: In Pytest I'm trying to do following thing, where I need to save previous result and compare current/present result with previous for multiple iterations. I've done as following ways: @pytest.mark.parametrize("iterations",[1,2,3,4,5]) ------&gt; for 5 iterations @pytest.mark.parametrize("clsObj",[(1,2,3)],indirect = True) ---&gt; here clsObj is the instance. (clsObj.currentVal, here clsObj gets instantiated for every iteration and it is instance of **class func1**) presentVal = 0 assert clsObj.currentVal &gt; presrntVal clsObj.currentVal = presentVal When I do as above every time I loop presentVal get's assign to 0 (expected since it is local variable). Instead above I tried to declare presentVal as global like,global presentVal and also I intialized presentVal above my test case but didn't turn well. class func1(): def __init__(self): pass def currentVal(self): cval = measure() ---------&gt; function from where I get current values return cval Can someone suggest how declare global variable in pytest or other best way Thanks in advance!
favorite count: 0
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/47885205
tagged with: pytest
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82705348
downvote count: 1

http://stackoverflow.com/a/48043246
accepted answer of: http://stackoverflow.com/q/47954901
type: AcceptedAnswer
has body: Remove the Default/ from the end of your path options.add_argument("user-data-dir=/Users/alexiseggermont/Library/Application Support/Google/Chrome/") On a PC, it would typically be something like: options.add_argument('user-data-dir=C:/Users/{USERNAME}/AppData/Local/Google/Chrome/User Data') You'll need to check you've got compatible versions of chromedriver and chrome - the easiest way to do that, is to check that both are up to date. If it crashes immediately on opening, check the chromedriver help page. Maybe try disabling all extensions, to see if that helps.
answers question: http://stackoverflow.com/q/47954901
has comment: http://stackoverflow.com/comment/98266951
has comment: http://stackoverflow.com/comment/112839868
upvote count: 10
type: Answer
has comment: http://stackoverflow.com/comment/83098906
downvote count: 0
score: 10
has comment: http://stackoverflow.com/comment/83098255
has comment: http://stackoverflow.com/comment/119962319

http://stackoverflow.com/a/47966490
type: Answer
answers question: http://stackoverflow.com/q/47955449
has body: Without having the whole picture, my guess is that you are giving LabeledPoint the wrong type of arguments. More specifically, your y_train and y_test get values from the following: ... y_train.map(lambda line: line.split(",")) y_test.map(lambda line: line.split(",")) Each return a list, which is not compatible with the LabeledPoint label argument. So: training = LabeledPoint(y_train, X_train) --> training = LabeledPoint([some, values], [some, other, values]) But, taken from the docs/source, LabeledPoint expects the first argument, the label, to be something that can be casted to float. class LabeledPoint(object): """ Class that represents the features and labels of a data point. :param label: Label for this data point. :param features: Vector of features for this point (NumPy array, list, pyspark.mllib.linalg.SparseVector, or scipy.sparse column matrix). .. note:: 'label' and 'features' are accessible as class attributes. .. versionadded:: 1.0.0 """ def __init__(self, label, features): self.label = float(label) self.features = _convert_to_vector(features) Thus, depending on what your line looks like, maybe change your code to something like the following: ... y_train.map(lambda line: line.split(",")[0]) ... y_test.map(lambda line: line.split(",")[0]) Hope that helps, good luck!
score: 0

http://stackoverflow.com/q/47868375
has title: Rpy2 works only from console
tagged with: python
score: 2
answer count: 0
upvote count: 2
type: Question
tagged with: rpy2
has body: I've installed rpy2 via conda install -c r rpy2. After this, I tried to execute import rpy2.robjects as robjects in my jupyter notebook and kernel died and restarted. But when i run this import from console, it works well, without any errors. How to fix this?
tagged with: http://stackoverflow.com/tag/r
downvote count: 0
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/47954487
type: Answer
score: 2
upvote count: 2
has body: They are lists because random.choices returns "a k sized list of elements". Since there is only one element in the list, and this is what you are trying to return, you just want to write return star[0].
answers question: http://stackoverflow.com/q/47954431
accepted answer of: http://stackoverflow.com/q/47954431
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82878380

http://stackoverflow.com/comment/82746806
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47890055
has text: Python version?
score: 0

http://stackoverflow.com/comment/83585296
score: 0
type: AnswerComment
has text: @EvyatarMeged I just want the code to be more maintainable in the near future, avoiding one file for everything. So,need some guide to start with project structure.
type: Comment
comment on: http://stackoverflow.com/a/47990390

http://stackoverflow.com/comment/82756368
type: Comment
comment on: http://stackoverflow.com/a/47894681
type: AnswerComment
has text: But it's going to be different templates. So, I don't want to hardcode a single 'PATH/TEMPLATE.html'. Is there a way to do it? Or the only way is to create a View for every page that loads the navbar with the form?
score: 0

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/47943101
tags question: http://stackoverflow.com/q/47991804
tags question: http://stackoverflow.com/q/47953132
tags question: http://stackoverflow.com/q/47887837
tags question: http://stackoverflow.com/q/48013683
tags question: http://stackoverflow.com/q/48008771
tags question: http://stackoverflow.com/q/47959120
tag name: kivy-language
tags question: http://stackoverflow.com/q/47921413

http://stackoverflow.com/a/47930408
downvote count: 0
has body: You could create a second DataFrame from example_dict and then merge the two Dataframes d2 = pd.DataFrame(example_dict.keys(),columns= ['category']).assign(category_data=example_dict.values()) df.merge(d2,on='category',how='left') category ids category_data 0 category1 0 {u'filed2': 5.0, u'field1': 0.0} 1 category2 1 {u'field2': 8.0, u'field1': 5.0} 2 category1 2 {u'filed2': 5.0, u'field1': 0.0} 3 category2 3 {u'field2': 8.0, u'field1': 5.0} 4 category1 4 {u'filed2': 5.0, u'field1': 0.0} 5 category2 5 {u'field2': 8.0, u'field1': 5.0} 6 category1 6 {u'filed2': 5.0, u'field1': 0.0} 7 category2 7 {u'field2': 8.0, u'field1': 5.0} 8 category1 8 {u'filed2': 5.0, u'field1': 0.0} 9 category2 9 {u'field2': 8.0, u'field1': 5.0} Separating Dictionary values to columns d2 = pd.DataFrame(example_dict).T df.merge(d2,how='left',left_on='category',right_index=True) category ids field1 field2 filed2 0 category1 0 0.0 NaN 5.0 1 category2 1 5.0 8.0 NaN 2 category1 2 0.0 NaN 5.0 3 category2 3 5.0 8.0 NaN 4 category1 4 0.0 NaN 5.0 5 category2 5 5.0 8.0 NaN 6 category1 6 0.0 NaN 5.0 7 category2 7 5.0 8.0 NaN 8 category1 8 0.0 NaN 5.0 9 category2 9 5.0 8.0 NaN
answers question: http://stackoverflow.com/q/47930052
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/q/47871398
has comment: http://stackoverflow.com/comment/82715564
downvote count: 0
tagged with: datasource
has comment: http://stackoverflow.com/comment/82709077
tagged with: bokeh
has comment: http://stackoverflow.com/comment/82708525
has comment: http://stackoverflow.com/comment/82708626
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/82716249
has comment: http://stackoverflow.com/comment/82708866
answer count: 1
has body: I am using Bokeh and Python 2.7 Im trying to update the Data Source to change the plot based on Select Box. But I am not able to update the plot. what am I doing wrong? or is there a better way? Code: from bokeh.models import ColumnDataSource from bokeh.plotting import figure, output_file, show, output_notebook from bokeh.models.widgets import Select from bokeh.io import curdoc from bokeh.layouts import column, row from bokeh.io import output_file, show from bokeh import models import pandas as pd d1 = dict(x= [10,4,6,4], y = [6,2,8,10]) d2 = dict(x= [23,12,50,30], y = [5,10,23,18,12]) source = ColumnDataSource(data=d1) p = figure() select = Select(title="Select d", options=['d1', 'd2']) def update_plot(attrname, old, new): if new == 'd1': newSource = d1 if new == 'd2': newSource = d2 source.data = newSource p.line(x='x', y='y',source = source) select.on_change('value', update_plot) layout = column(row(select, width=400), p) curdoc().add_root(layout) show(layout)
has comment: http://stackoverflow.com/comment/82708211
has answer: http://stackoverflow.com/a/47872267
favorite count: 0
has comment: http://stackoverflow.com/comment/82708408
has comment: http://stackoverflow.com/comment/82708974
has title: how to change data source from select bokeh
has comment: http://stackoverflow.com/comment/82709538
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82715597
tagged with: python
tagged with: plot
has comment: http://stackoverflow.com/comment/82708985
score: 2

http://stackoverflow.com/comment/82981354
type: QuestionComment
has text: What does `where python` say?
comment on: http://stackoverflow.com/q/48000496
score: 0
type: Comment

http://stackoverflow.com/comment/82939936
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47980410
has text: Yes, it is just what i code.

http://stackoverflow.com/comment/82711074
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47872315
has text: Thanks, do you know how to check if a local branch exists?

http://stackoverflow.com/a/47989859
answers question: http://stackoverflow.com/q/47987412
score: 0
type: Answer
has body: You need to understand the big Oh notation in order to understand how efficient your algorithm is in terms of usage of computational resources independent of computer architecture or clock rate. It basically helps you analyze the worst case running time or memory usage of your algorithm as the size of the input increases. In summary, the running time of your algorithm will fall into one of these categories (from fastest to slowest); O(1): Constant time. Pronounced (Oh of 1). The fastest time. O(lg n): Logarithmic time. Pronounced (Oh of log n). Faster than linear time. Traditionally, it is the fastest time bound for search. O(n): Linear time. Pronounced (Oh of n, n is the size of your input e.g size of an array). Usually something when you need to examine every single bit of your input. O(nlgn): The fastest time we can currently achieve when performing a sort on a list of elements. O(n**2): Oh of n squared. Quadratic time. Often this is the bound when we have nested loops. O(2**n): Really, REALLY big! A number raised to the power of n is slower than n raised to any power. In your case, you are using nested loops which is O(n2). The code i have written uses a single while loop and has a growth complexity of O(n) which is faster than O(n2). I haven't really tried it on a very large array but in your case it seems to work. Try it and let me know if it works as expected. k = [7, 0, 3, 4, -1] n = len(k) i = 0 count = 0 while count &lt; n**2: # assuming we wouldn't go through the loop more than n squared times if i == n - 1: i = 0 count += 1 swapped = False elif k[i] &gt; k[i+1]: temp = k[i] k[i] = k[i+1] k[i+1] = temp i+=1 swapped = True elif swapped == False: i += 1 elif swapped == True and i &lt; n - 1: i += 1 Note: In the example list (k), we only need to loop through the list three times in order for it to be sorted in ascending order. So if you change the while loop to this line of code while count &lt; 4:, it would still work.

http://stackoverflow.com/a/47992561
downvote count: 0
has body: The main idea of stacked ensemble (and the thing that differentiates it from other types of ensemble, such as random forest, GBMs, simple averaging of confidences) is that it uses another machine learning model to determine how to weight the base learners. (This other model is the meta-learner.) For your second question, you currently cannot specify any parameters, but there is a ticket for it, so there is a fair chance it will be available in the next few months. In the meantime, I would say paying attention to over-fitting in the base models, is more important than regularization in the meta-learner.
has comment: http://stackoverflow.com/comment/99723317
type: Answer
answers question: http://stackoverflow.com/q/47983519
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/99687144
accepted answer of: http://stackoverflow.com/q/47983519
has comment: http://stackoverflow.com/comment/99723272
has comment: http://stackoverflow.com/comment/99692209
type: AcceptedAnswer

bokeh
tags question: http://stackoverflow.com/q/47959758
tags question: http://stackoverflow.com/q/47891531
tags question: http://stackoverflow.com/q/47968706
type: Tag
tags question: http://stackoverflow.com/q/47871398
tags question: http://stackoverflow.com/q/47965447
tags question: http://stackoverflow.com/q/47973900
tags question: http://stackoverflow.com/q/47910177
tags question: http://stackoverflow.com/q/47874323
tags question: http://stackoverflow.com/q/47989704
tags question: http://stackoverflow.com/q/47857971
tag name: bokeh
tags question: http://stackoverflow.com/q/47911355

http://stackoverflow.com/comment/82912652
type: AnswerComment
has text: @user1179317 I've added an explanation.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47963823

http://stackoverflow.com/comment/82752808
has text: Now I understand your problem! The `struct.unpack` does return a negative number, so it does indeed treat the first bit as sign. The `bin`, however, can't do that because as @Anis has explained at some length Python ints are arbitrary size, so in that sense there is no first bit. And `bin` can't know which particulat bit length you have in mind. A work-around is just doing `bin(1<<your_bit_length + your_number)` which will give you the complement representation for the given bit length.
comment on: http://stackoverflow.com/q/47885067
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47908650
type: Question
has title: currentItemchanged and listwidget.clear() is overlap and the window is close with" Process finished with exit code 1" - PyQt5 - python
tagged with: pyqt4
has comment: http://stackoverflow.com/comment/82799839
has comment: http://stackoverflow.com/comment/82800521
tagged with: user-interface
has comment: http://stackoverflow.com/comment/82792562
has comment: http://stackoverflow.com/comment/82799907
tagged with: click
has comment: http://stackoverflow.com/comment/82800416
has body: Firstly, it is my first sharing. I hope it doesn't have any serious problem. As you see, it is a GUI application. There are three button(BTC, ETH, USD) and a listWidget. When any button click, listWidget update data that json data from stock site. First, I run the code, and click buttons one by one. each time I see list that belong to the button. "ETH, DOCA, REN..." everything is perfect. but after that again I run the code, and click BTC button. After that I select a coin name where listWidget to plot BTC-x coin graph. After that I click ETH button. and the program is closed. and writing there is "Process finished with exit code 1" I hope I could understand my problem. import sys import requests from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayout,QHBoxLayout, QListView, QListWidget, QLineEdit, QLabel from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar import matplotlib.pyplot as plt global button_id class Window(QDialog): def __init__(self, parent=None): super(Window, self).__init__(parent) self.setWindowTitle('Market Currency') self.listWidget = QListWidget() self.listWidget.currentItemChanged.connect(self.touchme) self.button = QPushButton('Plot') self.button.clicked.connect(self.plot) self.button2 = QPushButton('BTC') self.button2.clicked.connect(lambda: self.buttonsee(1)) self.button3 = QPushButton('ETH') self.button3.clicked.connect(lambda: self.buttonsee(2)) self.button4 = QPushButton('USD') self.button4.clicked.connect(lambda: self.buttonsee(3)) self.figure = plt.figure() self.canvas = FigureCanvas(self.figure) self.toolbar = NavigationToolbar(self.canvas, self) self.textbox = QLineEdit('Ara beni') self.textbox.move(20, 20) self.textbox.resize(280, 40) self.x=self.textbox.text() print(self.x) self.aramam=QLabel() self.aramam.setText("""or Write here""") h_box = QHBoxLayout() h_box.addWidget(self.button2) h_box.addWidge…
linked to: http://stackoverflow.com/q/34363552
tagged with: python
answer count: 0
type: UnansweredQuestion
score: 0
tagged with: pyqt5

http://stackoverflow.com/comment/82986351
has text: @Markus, i'm using your example... ;-)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48008864
type: AnswerComment

http://stackoverflow.com/q/47904293
tagged with: subprocess
upvote count: 3
has title: Prohibit reading from /dev/tty
has comment: http://stackoverflow.com/comment/82776375
has comment: http://stackoverflow.com/comment/82783552
has comment: http://stackoverflow.com/comment/82775246
type: Question
has answer: http://stackoverflow.com/a/47905064
has comment: http://stackoverflow.com/comment/82776616
has comment: http://stackoverflow.com/comment/82776740
answer count: 1
has comment: http://stackoverflow.com/comment/82783707
downvote count: 0
favorite count: 0
tagged with: terminal
tagged with: linux
has comment: http://stackoverflow.com/comment/82776283
has body: Tools like sudo read from /dev/tty to read a password. I would like to avoid this. The subprocess should not be able to read /dev/tty. The subprocess should fail immediately instead of waiting for input for ever. I am using the subprocess module of Python. The subprocess should fail if it tries to read from /dev/tty. Remember: The tool sudo is just an example. A fancy command line argument to sudo does not solve my problem. This should work for all linux command line tools. Question: How to make any tool fail as soon as it wants to read from /dev/tty (called via the subprocess module of Python)? Background: This is a normal linux user process, not root.
has comment: http://stackoverflow.com/comment/82781883
tagged with: python
accepted answer: http://stackoverflow.com/a/47905064
type: AnsweredQuestion
score: 3

http://stackoverflow.com/comment/82842215
score: 1
has text: what does `cursor.fetchall()` show you?
comment on: http://stackoverflow.com/q/47936431
type: Comment
type: QuestionComment

http://stackoverflow.com/a/62033916
type: Answer
has body: Please try with below solution import psycopg2 as db conn = db.connect(host='localhost', dbname='randomname', user='candidate', password='abc')
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47928883

http://stackoverflow.com/comment/90273367
has text: Unfortunately formatting_info=True only works on .xls but not on .xlsx files :-( A good hint anyway - thnks!
type: Comment
type: AnswerComment
score: 3
comment on: http://stackoverflow.com/a/47857310

http://stackoverflow.com/comment/82799599
score: 0
type: Comment
type: QuestionComment
has text: Just realised and edited that
comment on: http://stackoverflow.com/q/47915713

http://stackoverflow.com/comment/82758902
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47895930
has text: Can you provide some examples of the text inside the files and what you expect the output to contain?

http://stackoverflow.com/comment/131842883
type: AnswerComment
comment on: http://stackoverflow.com/a/74664998
type: Comment
has text: As I commented in response to your comment on my answer, the character class `[-a-zA-Z0-9_]` in the url pattern only matches _ASCII_ strings. If you want to matches non-ASCII characters consider at least `[-\w0-9_]`, or even `[-\w\d_]` to match non-ASCII digits as well.
score: 0

http://stackoverflow.com/a/47888293
has comment: http://stackoverflow.com/comment/82953724
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/47883630
upvote count: 4
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47883630
type: Answer
has comment: http://stackoverflow.com/comment/82953836
has comment: http://stackoverflow.com/comment/82954534
has comment: http://stackoverflow.com/comment/82744391
has body: You have to use zip() to group price with seller and then yield every pair separately def parse(self, response): all_prices = response.xpath('(//td[@class="cell-price"] /a/span/span/span[@class="value"]/text())[position() &lt;= 10]').extract() all_sellers = response.xpath('(//tr/td/div/ul/li/a[@class="js_product-offer-link"]/text())[position()&lt;=10]').extract() for price, seller in zip(all_prices, all_sellers): yield {'price': price.strip(), 'seller': seller.strip()}

http://stackoverflow.com/comment/82977639
has text: @DanD. The `PYTHONPATH` I've mentioned is the same as I get from `which python` .
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48004264

http://stackoverflow.com/comment/110478996
score: 0
type: Comment
has text: I suggest you not to mess up and manage the LDAP from other tool, maybe Keycloak or similar if possible, and use the django-ldap just for querying.
comment on: http://stackoverflow.com/a/52270893
type: AnswerComment

http://stackoverflow.com/q/47984035
tagged with: numpy
downvote count: 0
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82937562
has answer: http://stackoverflow.com/a/47984649
has comment: http://stackoverflow.com/comment/82937274
tagged with: pickle
tagged with: python
has title: how to create a pickle file correctly?
has comment: http://stackoverflow.com/comment/82937946
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/82937128
has comment: http://stackoverflow.com/comment/82937420
tagged with: contextmanager
type: UnansweredQuestion
has body: I am trying to create a pickle file. I have used the following piece of code to do it: def pickler(input_nparray): with open('/Users/username/Desktop/pklfilename.pkl', 'wb+') as f: pickle.dump(input_nparray, f) This method works perfectly. What this does is it takes in the numpy array and stores the contents into the pklfilename.pkl. But the problem here is I have to specify the filename. This I tried to do in the following way, but failed. def pickler(input_nparray, pklfilename): with open('/Users/swaghccc/Desktop/' + pklfilename, 'wb+') as f: pickle.dump(input_nparray, f) pickler(input_nparray, 'file1.pkl') Can someone tell me the correct alternative?

http://stackoverflow.com/q/47954439
tagged with: tkinter
has comment: http://stackoverflow.com/comment/82878594
upvote count: 3
has answer: http://stackoverflow.com/a/47955560
tagged with: calendar
has comment: http://stackoverflow.com/comment/82879773
type: Question
linked to: http://stackoverflow.com/q/4443786
answer count: 1
favorite count: 0
has body: So what I'm trying to do is to make a calendar frame, just like the view of google calendar or any other calendar program really, where I can select a day and see the events I have to do on that day and it's time using python tkinter. Currently on my database I have events with date, starting time and ending time. Note that I am using python 3. Can anyone please give me a clue for how to do it or even send a link to a website where it says how to do it. But please, I'm not searching for a date picker just a calendar showing me what thing I should do when. Thank you ;)
has comment: http://stackoverflow.com/comment/82879970
has comment: http://stackoverflow.com/comment/82880086
type: UnansweredQuestion
downvote count: 8
has title: Make a calendar view for events in python tkinter
tagged with: python
score: -5

http://stackoverflow.com/a/47973260
type: Answer
answers question: http://stackoverflow.com/q/47973238
has comment: http://stackoverflow.com/comment/82916247
has body: Well the cause of the error is that the length is 0 of either y0_list or y1_list (or both). Since you initialize them in this for loop : for x0,y0,x1,y1 in lines: if x0 == 0: y0_list.append(y0) if x1 == im_wb.shape[1]: y1_list.append(y1) You can narrow your error down to either lines not having the expected values or your 2 if statements being faulty. I believe the problem is caused by the latter but the easiest check you can do is print out lines and check manually if your if statements would be triggered.
score: 0
has comment: http://stackoverflow.com/comment/82916146
has comment: http://stackoverflow.com/comment/82916327

http://stackoverflow.com/a/48007394
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/82983619
downvote count: 0
has body: groupby from itertools is your friend: &gt;&gt;&gt; l=[(7751, 0.9407466053962708), (6631, 0.03942129), (7751, 0.1235432)] &gt;&gt;&gt; #importing libs: &gt;&gt;&gt; from itertools import groupby &gt;&gt;&gt; from statistics import mean #(only python &gt;= 3.4) &gt;&gt;&gt; # mean=lambda l: sum(l) / float(len(l)) #(for python &lt; 3.4) (*1) &gt;&gt;&gt; #set the key to group and sort and sorting &gt;&gt;&gt; k=lambda x: x[0] &gt;&gt;&gt; data = sorted(l, key=k) &gt;&gt;&gt; #here it is, pythonic way: &gt;&gt;&gt; [ (k, mean([m[1] for m in g ])) for k, g in groupby(data, k) ] Results: [(6631, 0.03942129), (7751, 0.5321449026981354)] EDITED (*1) Thanks Elmex80s to refer me to mean.
answers question: http://stackoverflow.com/q/48007236
type: Answer
has comment: http://stackoverflow.com/comment/82983781
has comment: http://stackoverflow.com/comment/82983544

http://stackoverflow.com/q/47955661
has comment: http://stackoverflow.com/comment/82880762
has answer: http://stackoverflow.com/a/47955702
type: Question
score: -2
downvote count: 2
has comment: http://stackoverflow.com/comment/82880726
answer count: 1
has title: Regex to account for any dollar amount entry, including just decimal values without grouping
tagged with: regex
favorite count: 0
tagged with: python-3.x
upvote count: 0
has body: I'm trying to account for the possibility of any USD denomination and I came up with this: \$\d+\.?\,?\d+\.?\d+ This works for entries like $10,500.23, $1,050.23, $105.23, $105, $10, $1 But won't work for things like $.23 I tried using \d+? instead of just \d? but that doesn't seem to work either (maybe there is a special way of handling this that I'm unaware of?)
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/354044

http://stackoverflow.com/comment/83073538
comment on: http://stackoverflow.com/a/48017625
type: AnswerComment
has text: Yours is good enough! It looks like my problem is a PyInstaller issue rather than the GUI or threading. I'll post another question / answer once I get it figured out.
type: Comment
score: 0

http://stackoverflow.com/a/47939034
downvote count: 0
type: AcceptedAnswer
upvote count: 3
has body: Your Dockerfile may look like this: FROM python:2 RUN apt-get install libxxx ADD requirememts.txt / RUN pip install -r /requirements.txt ADD main.py /usr/src/app WORKDIR /usr/src/app RUN pip install -r /usr/src/app/requirements.txt CMD ["python", "main.py"] You can simply run docker build -t some_tag .. Only lines below ADD main.py /usr/src/app will be re-installed / upgraded, and lines above are installed only once when you build the image for the first time.
type: Answer
accepted answer of: http://stackoverflow.com/q/47938864
score: 3
answers question: http://stackoverflow.com/q/47938864

http://stackoverflow.com/comment/82961665
type: Comment
type: QuestionComment
has text: Everything is fine. The `print` function tries to make things 'look' friendly. And doesn't in this case. `print(bytes.fromhex('4d65727279204368726973746d6173'))`
score: 4
comment on: http://stackoverflow.com/q/47996767

http://stackoverflow.com/q/47892689
tagged with: list
has body: I need to retrieve only those words from a file whose pos tags are:'NN'or 'NNP' or 'NNS' or 'NNPS'. My sample input is: [['For,IN', ',,,', 'We,PRP', 'the,DT', 'divine,NN', 'caused,VBD', 'apostle,NN', 'We,PRP', 'vouchsafed,VBD', 'unto,JJ', 'Jesus,NNP', 'the,DT', 'son,NN', 'of,IN', 'Mary,NNP', 'all,DT', 'evidence,NN', 'of,IN', 'the,DT', 'truth,NN', ',,,', 'and,CC', 'strengthened,VBD', 'him,PRP', 'with,IN', 'holy,JJ'], [ 'be,VB', 'nor,CC', 'ransom,NN', 'taken,VBN', 'from,IN', 'them,PRP', 'and,CC', 'none,NN', '\n']] My expected output is: [ 'divine', 'apostle','Jesus', 'son','Mary', 'evidence', 'truth', 'ransom', 'none']
has answer: http://stackoverflow.com/a/47893239
score: -1
tagged with: pos-tagger
type: Question
has answer: http://stackoverflow.com/a/47898656
tagged with: arrays
possible better answer: http://stackoverflow.com/a/47892727
answer count: 3
has title: How to retrieve words with noun tags only from a file?
has answer: http://stackoverflow.com/a/47892727
downvote count: 1
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/47893239
type: AnsweredQuestion
upvote count: 0

http://stackoverflow.com/q/47859452
favorite count: 0
has title: Opening multiple files in Python before closing previous?
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47859523
has comment: http://stackoverflow.com/comment/82683717
score: 1
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/47859606
answer count: 3
has comment: http://stackoverflow.com/comment/82683810
has comment: http://stackoverflow.com/comment/82685386
has answer: http://stackoverflow.com/a/47860299
downvote count: 1
has body: I have a noob python question... so bear with me. Can I open multiple files before closing the previos. So... can I run import os files=[] for file in os.listdir(os.curdir): files.append(open(file,'w')) Then edit each file as I want and finish with for file in files: file.close() Thanks in advance

http://stackoverflow.com/q/47965265
favorite count: 0
has comment: http://stackoverflow.com/comment/82900432
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/48004110
has comment: http://stackoverflow.com/comment/82900583
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has body: I'm trying to get some hotels info from booking.com using Beautiful Soup. I need to get certain info from all the accomodations in Spain. This is the search url: <a href="https://www.booking.com/searchresults.html?aid=304142&amp;label=gen173nr-1DCAEoggJCAlhYSDNYBGigAYgBAZgBMbgBB8gBDNgBA-gBAfgBApICAXmoAgM&amp;sid=1677838e3fc7c26577ea908d40ad5faf&amp;class_interval=1&amp;dest_id=197&amp;dest_type=country&amp;dtdisc=0&amp;from_sf=1&amp;group_adults=2&amp;group_children=0&amp;inac=0&amp;index_postcard=0&amp;label_click=undef&amp;no_rooms=1&amp;oos_flag=0&amp;postcard=0&amp;raw_dest_type=country&amp;room1=A%2CA&amp;sb_price_type=total&amp;search_selected=1&amp;src_elem=sb&amp;ss=Spain&amp;ss_all=0&amp;ss_raw=spain&amp;ssb=empty&amp;sshis=0&amp;order=popularity" rel="nofollow noreferrer">https://www.booking.com/searchresults.html?aid=304142&amp;label=gen173nr-1DCAEoggJCAlhYSDNYBGigAYgBAZgBMbgBB8gBDNgBA-gBAfgBApICAXmoAgM&amp;sid=1677838e3fc7c26577ea908d40ad5faf&amp;class_interval=1&amp;dest_id=197&amp;dest_type=country&amp;dtdisc=0&amp;from_sf=1&amp;group_adults=2&amp;group_children=0&amp;inac=0&amp;index_postcard=0&amp;label_click=undef&amp;no_rooms=1&amp;oos_flag=0&amp;postcard=0&amp;raw_dest_type=country&amp;room1=A%2CA&amp;sb_price_type=total&amp;search_selected=1&amp;src_elem=sb&amp;ss=Spain&amp;ss_all=0&amp;ss_raw=spain&amp;ssb=empty&amp;sshis=0&amp;order=popularity When I inspect an accomodation in the result page using the developer tools it says that this is the tag to search: &lt;a class="hotel_name_link url" href="&amp;#10;/hotel/es/aran-la-abuela.html?label=gen173nr-1DCAEoggJCAlhYSDNYBGigAYgBAZgBMbgBB8gBDNgBA-gBAfgBApICAXmoAgM;sid=1677838e3fc7c26577ea908d40ad5faf;ucfs=1;srpvid=b4980e34f6e50017;srepoch=1514167274;room1=A%2CA;hpos=1;hapos=1;dest_type=country;dest_id=197;srfid=198499756e07f93263596e1640823813c2ee4fe1X1;from=searchresults&amp;#10;;highlight_room=#hotelTmpl" target="_blank" rel="noopener"&gt; &lt;span class="sr-hotel__name " data-et-click=" customGo…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82900579
has title: Extracting HTML content from a search page using Beautiful Soup with Python
tagged with: web-scraping
upvote count: 1
accepted answer: http://stackoverflow.com/a/48004110
type: Question
has comment: http://stackoverflow.com/comment/82900453
has comment: http://stackoverflow.com/comment/82900375
has comment: http://stackoverflow.com/comment/82900684
has comment: http://stackoverflow.com/comment/82901073
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82935690
score: 1

http://stackoverflow.com/q/47917832
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82803701
has body: Given a list of X elements I need to generate a sequence of k-length. if list= [1,2,3] and k=2 the result would be: ('1', '1') ('1', '2') ('1', '3') ('2', '1') ('2', '2') ('2', '3') ('3', '1') ('3', '2') ('3', '3') The itertools.product(list,repeat=k-length) would work wonderfully but I'm not allowed to use it. I've seen the source code and while it works quite well for small sequences, for longer sequences too much memory is used. Quite normal since we are creating len(list)**k-length combinations. My question is, is it possible to create an iterable generator that doesn't create the intermediate 'result' list? I've been fiddling with this function and thinking about a recursive solution but couldn't come up with anything that solved my problem. Code for reference: def product(*args, **kwds): pools = map(tuple, args) * kwds.get('repeat', 1) result = [[]] for pool in pools: result = [x+[y] for x in result for y in pool] for prod in result: yield tuple(prod) Another approach: def possible_combinations(sequence): for a in sequence: for b in sequence: yield(a,b) for combo in possible_combinations('123'): print(combo) With this code I'd have 3**2=9 results, where 3 is the length of the '123' string and 2 the k. This approach would also work if k were equal to 2, however given that k dynamically changes , I'd need to have k 'for loops' and not only 2 'for loops'. if k=3: def possible_combinations(sequence): for a in sequence: for b in sequence: for c in sequence: yield(a,b,c) for combo in possible_combinations('123'): print(combo) And now I'd have 3**k = 27 results. If k were 4 another for loop would need to be added, like so: def possible_combinations(sequence): for a in sequence: for b in sequence: for c in sequence: for d in sequence: yield(a,b,c,d) for combo in possible_combinations('123'): print(combo) And now I'd have 3**4=81 results
type: Question
tagged with: python-itertools
score: 1
has comment: http://stackoverflow.com/comment/82828336
upvote count: 1
answer count: 1
downvote count: 0
favorite count: 0
has title: Itertools product without intermediate results
tagged with: product
has answer: http://stackoverflow.com/a/47918260
accepted answer: http://stackoverflow.com/a/47918260
tagged with: python
has comment: http://stackoverflow.com/comment/82831561

http://stackoverflow.com/q/47994326
has body: I'm trying to set up my python script in a new server i'm migrating to but whenever i'm trying to connect to the DB with the script i get the following error dbHost = 'xxxxxx' dbPort = xxxx dbServiceName = 'xxx.xxxx.com' dbUser = 'xxxx' dbPass = 'xxxx' dnsTns = cx_Oracle.makedsn(dbHost, dbPort, dbServiceName).replace('SID','SERVICE_NAME') dbCon = cx_Oracle.connect(dbUser, dbPass, dnsTns) &gt;&gt;&gt; dbCon = cx_Oracle.connect(dbUser, dbPass, dnsTns) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; cx_Oracle.InterfaceError: Unable to acquire Oracle environment handle I can use sqlplus from command line using the same TNS user and pass with no problems but can't get it to work on the script My path variable has the oracle client folder set up like the previous server (C:\oracle\bin). TNS_ADMIN variable is set to "C:\oracle\NETWORK\ADMIN" tried using ORACLE_HOME to C:\oracle too Oracle client is 10 same as server windows version 64bit cx_Oracle module 5.1.3 installed using pip python is 2.7
type: Question
score: 0
answer count: 1
tagged with: cx-oracle
has title: oracle10 windows cx_Oracle Unable to acquire Oracle environment handle
tagged with: oracle-database
tagged with: windows
tagged with: python
has answer: http://stackoverflow.com/a/48067922
type: UnansweredQuestion

http://stackoverflow.com/a/47973658
has comment: http://stackoverflow.com/comment/82930238
has body: Consider a Dataframe.apply: new_tmp = tmp.filter(regex="ZW").apply(lambda col: col.shift(125 - col.idxmax())) print(new_tmp.equals(_)) # True
answers question: http://stackoverflow.com/q/47973209
has comment: http://stackoverflow.com/comment/82930226
type: Answer
accepted answer of: http://stackoverflow.com/q/47973209
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/82919015
has comment: http://stackoverflow.com/comment/82918857
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/82884433
type: Comment
comment on: http://stackoverflow.com/a/47957535
has text: @JodyK let me provide
type: AnswerComment
score: 0

google-chrome
tags question: http://stackoverflow.com/q/47995981
tags question: http://stackoverflow.com/q/47882829
tags question: http://stackoverflow.com/q/47967774
tags question: http://stackoverflow.com/q/47928440
tags question: http://stackoverflow.com/q/47925340
type: Tag
tag name: google-chrome
tags question: http://stackoverflow.com/q/47954901
tags question: http://stackoverflow.com/q/47927215

http://stackoverflow.com/q/47913278
favorite count: 0
has comment: http://stackoverflow.com/comment/82794444
has answer: http://stackoverflow.com/a/47913619
has comment: http://stackoverflow.com/comment/82794595
accepted answer: http://stackoverflow.com/a/47913619
has comment: http://stackoverflow.com/comment/82794568
has comment: http://stackoverflow.com/comment/82794740
has body: Sorry if this is a noob question I am still learning. I have passed a variable from python code to a jinja2 HTML template to set up a URL, like this: Delete When this link is pressed it should run a query that deletes the entity with that ID. But when the link is pressed it goes to /delete/1827424298 for example, which results in a 404 error as the request handler doesn't exist. I need to pass that ID back into my python code so it can run a method to delete the entity with that same ID. How do I go about doing this? Using webapp2 if that is important. class DeleteRequestHandler(webapp2.RequestHandler): def get(): template = template_env.get_template('myrequests.html') context = { 'results': results.key.id() } self.response.out.write(template.render(context)) EDIT: I've added my delete handler - it is incomplete as I have yet to add the query to delete the entity. My thinking behind it so far is I can grab the results.key.id() from the jinja2 template and put it into results but I am not sure if this would work.
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: jinja2
has comment: http://stackoverflow.com/comment/82794616
type: Question
tagged with: webapp2
has title: Pass variable from jinja2 template to python
has comment: http://stackoverflow.com/comment/82794653
has comment: http://stackoverflow.com/comment/82794916
upvote count: 1
answer count: 1

http://stackoverflow.com/a/47948569
has comment: http://stackoverflow.com/comment/82867234
accepted answer of: http://stackoverflow.com/q/47948550
score: 5
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82868970
answers question: http://stackoverflow.com/q/47948550
has body: You can convert the Counter objects to frozensets, which are hashable and can be put in a set themselves for linear savings on the in check: from collections import Counter counters = set() no_duplicates = [] for sub_list in all_subsets: c = frozenset(Counter(sub_list).items()) if c not in counters: counters.add(c) no_duplicates.append(list(sub_list)) Doing this with a dict comprehension also looks cool: no_duplicates = list( {frozenset(Counter(l).items()): l for l in all_subsets}.values())
type: Answer
upvote count: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/82867359

http://stackoverflow.com/q/47947606
score: 0
has answer: http://stackoverflow.com/a/47947686
linked to: http://stackoverflow.com/q/14524322
answer count: 1
duplicate of: http://stackoverflow.com/q/2265357
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has title: How to fix this strftime() error?
has body: I would like to only print '%d/%m/%Y, %H:%M', but when I say: print(loan_due.strftime('%d/%m/%Y, %H:%M')) I'm getting an error saying AttributeError: 'str' object has no attribute 'strftime'. I tried many ways but it's still not working for me. loan_due I have in my json file and this how it looks: {"customer": [{"loan_due": "22/12/2017, 19:02:39:4536"}]}
tagged with: python
duplicate of: http://stackoverflow.com/q/14524322
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/82865098
has comment: http://stackoverflow.com/comment/82865153
linked to: http://stackoverflow.com/q/2265357

http://stackoverflow.com/a/47868159
downvote count: 0
has comment: http://stackoverflow.com/comment/82703266
has body: You can use session first. Eg. session = boto3.Session( aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY, aws_session_token=SESSION_TOKEN, ) and then get your resource s3 = session.resource('s3') Note that aws_session_token is optional and will be used if you use STS to get temp sessions. Just saying s3 = boto3.client('s3') s3 = boto3.resource('s3') will use default creds in ~/.aws/credentials file. So it cannot be used in your case. It would be good if you can directly use - s3 = boto3.client( 's3', # Hard coded strings as credentials, not recommended. aws_access_key_id='xx', aws_secret_access_key='yy' ) For more details refer - boto3 configuration documentation
has comment: http://stackoverflow.com/comment/82701506
has comment: http://stackoverflow.com/comment/82703963
has comment: http://stackoverflow.com/comment/82701317
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82701293
answers question: http://stackoverflow.com/q/47867995
has comment: http://stackoverflow.com/comment/82706386

http://stackoverflow.com/comment/82980796
comment on: http://stackoverflow.com/q/48006240
score: 0
type: Comment
type: QuestionComment
has text: See https://stackoverflow.com/questions/1473577/writing-unicode-strings-via-sys-stdout-in-python

http://stackoverflow.com/comment/82875938
score: 0
type: Comment
has text: You should attempt to detect when a new line is required in a sentence, using a similar approach.
comment on: http://stackoverflow.com/a/47942101
type: AnswerComment

http://stackoverflow.com/comment/83189238
comment on: http://stackoverflow.com/q/47917621
score: 0
has text: Thank you for the help. I'm just starting and I'm following along with a book. I had the names like this. ['alice, 'david, 'caroline] Instead of this. ['alice', 'david', 'carloine'] pycharm is fine. I goofed up. Case closed. Thanks again for helping.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82748594
score: 0
type: Comment
has text: Can you show your expected output, so we can know we understood you correctly?
type: QuestionComment
comment on: http://stackoverflow.com/q/47890915

http://stackoverflow.com/q/47883284
has comment: http://stackoverflow.com/comment/82732222
answer count: 0
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82762774
has comment: http://stackoverflow.com/comment/82732485
score: 1
has comment: http://stackoverflow.com/comment/82762700
linked to: http://stackoverflow.com/q/26717120
type: Question
has comment: http://stackoverflow.com/comment/82732411
tagged with: python-multiprocessing
has comment: http://stackoverflow.com/comment/82732830
has comment: http://stackoverflow.com/comment/82732241
tagged with: apache
downvote count: 0
has comment: http://stackoverflow.com/comment/82732274
has title: OSError: [Errno 12] Cannot allocate memory
has body: I have implemented below code for multiprocessing that can handle multiple request concurrently but I'm getting below error. For that i use producer and consumer concept where producing putting process in queue and consumer consume that process and do some JOB. Traceback (most recent call last): p.start() File "/usr/lib/python2.7/multiprocessing/process.py", line 130, in start self._popen = Popen(self) File "/usr/lib/python2.7/multiprocessing/forking.py", line 121, in __init__ self.pid = os.fork() OSError: [Errno 12] Cannot allocate memory queue = Queue() lock = Lock() producers = [] consumers = [] for frame in frames: `enter code here`producers.extend([Process(target=self.producer, args=(queue, lock, frame)) for i in xrange(cpu_count())]) for i in range(50): p = Process(target=self.consumer, args=(queue, lock)) p.daemon = True consumers.append(p) for p in producers: #time.sleep(random.randint(0, 5)) p.start() for c in consumers: #time.sleep(random.randint(0, 5)) c.start() # Like threading, we have a join() method that synchronizes our program for p in producers: p.join() u_end = time.time() print u_start, u_end print('Parent process exiting...')
has comment: http://stackoverflow.com/comment/82733371
favorite count: 0

http://stackoverflow.com/a/47872692
type: AcceptedAnswer
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/47872453
answers question: http://stackoverflow.com/q/47872453
downvote count: 0
upvote count: 2
has body: The line shape_array=np.shape(a) creates a shape tuple, which is the expected input to np.empty. The expression [shape_array,] is that tuple, wrapped in a list, which seems superfluous. Use shape_array directly: d = np.empty(shape_array) On a related note, you can use the function np.empty_like to get an array of the same shape and type as the original more effectively: d = np.empty_like(a) If you want to use just the shape and size, there is really no need to store them in separate variables after calling np.size and np.shape. It is more idiomatic to use the corresponding properties of np.ndarray directly: d = np.empty(a.shape)

http://stackoverflow.com/q/47965487
has comment: http://stackoverflow.com/comment/82914337
type: Question
has comment: http://stackoverflow.com/comment/82901322
has answer: http://stackoverflow.com/a/47965956
has comment: http://stackoverflow.com/comment/82908337
has title: providing user input tkinter
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/82907140
has comment: http://stackoverflow.com/comment/82908674
answer count: 1
has body: I have a scenario where I am uploading a text file then providing a user input and then according to the user input processing further. Sample file : DOWN 07.11.2016 08:21:33 - 07.11.2016 08:22:33 UP 07.11.2016 09:41:07 - 09.11.2016 09:20:33 DOWN 09.11.2016 08:26:33 - 09.11.2016 08:35:33 UP 09.11.2016 08:23:33 - 09.11.2016 08:25:33 DOWN 09.11.2016 08:36:33 - 09.11.2016 08:38:33 DOWN 10.11.2016 08:36:33 - 10.11.2016 08:38:33 code : try: import Tkinter as Tk import tkFileDialog as fileDialog except ImportError: import tkinter as Tk fileDialog = Tk.filedialog import datetime def user_input(): current_date = my_entry.get() def processText(lines): total = 0 start = None for k, line in enumerate(lines): direction, date1, time1, _, date2, time2 = line.split() if direction != "Down": continue if start==None: start = date1 + ' ' + time1 # 1 D1, M1, Y1 = date1.split('.') h1, m1, s1 = time1.split(':') # 2 D2, M2, Y2 = date2.split('.') h2, m2, s2 = time2.split(':') # Timestamps t1 = datetime.datetime(*map(int, [Y1, M1, D1, h1, m1, s1])).timestamp() t2 = datetime.datetime(*map(int, [Y2, M2, D2, h2, m2, s2])).timestamp() total += (t2-t1) return total, start def openFile(): filename = fileDialog.askopenfilename() fileHandle = open(filename, 'r') down, start = processText(fileHandle.readlines()) txt = "Total Downtime is {0} min from {1}".format(down//60, start) textVar.set(txt) fileHandle.close() root = Tk.Tk() button = Tk.Button(root, text="Open", command=openFile) button.grid(column=1, row=1) textVar = Tk.StringVar(root) label = Tk.Label(root, textvariable=textVar) label.grid(column=1, row=2) root.mainloop() Above gives me output as Total Downtime is 12 min from 07.11.2016 08:21:33 but here I am trying to introduce the user input for DATE and for example if I want to get the downtime from 09.11.2016 then it should prompt me for selecting a date and output(total downtime) should be from the selected date. Any help would be great!! EDIT 1 (Added o/p): traceback : Exception in Tkint…
tagged with: tkinter-entry
accepted answer: http://stackoverflow.com/a/47965956
tagged with: python-3.x
tagged with: tkinter
has comment: http://stackoverflow.com/comment/82901243
has comment: http://stackoverflow.com/comment/82909344
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/48309354
type: Answer
has body: It's quite simple. Just do this. import pandas as pd xls = pd.ExcelFile('C:/users/path_to_your_excel_file/Analysis.xlsx') df1 = pd.read_excel(xls, 'Sheet1') print(df1) # etc. df2 = pd.read_excel(xls, 'Sheet2') print(df2)
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/47922946
score: 0

http://stackoverflow.com/q/48014040
score: 1
type: Question
tagged with: sympy
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82997088
has comment: http://stackoverflow.com/comment/82997302
has answer: http://stackoverflow.com/a/48014497
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/82997330
favorite count: 0
has comment: http://stackoverflow.com/comment/82997164
type: UnansweredQuestion
upvote count: 1
has title: Replacing part of the sympy expression
has body: Suppose I have a sympy expression like this: x = ( 1+ r70f * C2H4 *H+ r71* O) where r70f, C2H4, H , r71, O are sympy variables. I want it to change it to the following expression: x = ( 1+ k(r70f) * c(sC2H4) *c(sH)+ k(r71)* c(sO)) Basically replace r_SomeNumber_f to k(r_SomeNumber_f) and replace C2H4 or H or O to c(sC2H4) or c(sH) or c(sO) respectively. I am trying to use regular expressions but re.sub need str, but they are all sympy objects and that is making things complicated!!!

http://stackoverflow.com/comment/82818461
type: AnswerComment
has text: This is a nice solution, I am sure that this can be used, although in a slightly different context. Perhaps in queries where only one result is displayed. Thanks for the contribution.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47898518

http://stackoverflow.com/a/47978930
upvote count: 1
has body: Use new Dataset API(released as part of TF 1.4 version) to Speed up entire process Step for reading from CSV Files: 1) Read the CSV file name 2) Create TextLineDataset by providing the CSV file name 3) Create the Parse function for decoding and do any preprocessing work in input data 4) Create batching, repeat(no of epoch) and shuffling using dataset created in previous steps 5) Create the Iterator to fetch required inputs as a batch(i.e. mini-batch) Eg code: from matplotlib.image import imread def input_model_function(): csv_filename =['images.txt'] dataset = tf.data.TextLineDataset(csv_filename) dataset = dataset.map(_parse_function) dataset = dataset.batch(20)# you can use any number of batching iterator = dataset.make_one_shot_iterator() sess = tf.Session() batch_images, batch_labels = sess.run(iterator.get_next()) return {'x':batch_images}, batch_labels def _parse_function(line): image, labels= tf.decode_csv(line,record_defaults=[[""], [0]]) # Decode the raw bytes so it becomes a tensor with type. image = imread(image)# give full path name of image return image, labels Finally input batched Dataset into Model(created using any Pre-Made Estimator or Custom Estimator API)
downvote count: 0
answers question: http://stackoverflow.com/q/47978137
type: Answer
score: 1

http://stackoverflow.com/comment/82765160
comment on: http://stackoverflow.com/q/47899122
type: Comment
type: QuestionComment
has text: @Banana `Cases` is both a pattern matching function and a destructuring function. The easiest thing to do will be to approach the problem in a pythonic way, rather than trying to port Mathematica code over. Alternately, since it seems you're willing to use `subprocess` to get the job done, look into [Wolfram Script](http://reference.wolfram.com/language/ref/program/wolframscript.html). Then dump the lines you find into a more python-readable format on the Mathematica side.
score: 0

http://stackoverflow.com/a/47944083
has comment: http://stackoverflow.com/comment/82865733
has comment: http://stackoverflow.com/comment/82866609
has comment: http://stackoverflow.com/comment/82870902
has comment: http://stackoverflow.com/comment/82861592
type: Answer
has comment: http://stackoverflow.com/comment/82866534
has comment: http://stackoverflow.com/comment/82861722
has comment: http://stackoverflow.com/comment/82861610
has body: The usual procedure is to set v=x' so that then x' = v v' = ( y(t) - d*v - k*x) / m or def derivs(u,t): x,v = u return [ v, ( y(t) - d*v - k*x) / m ] def y(t): return Y*np.sin(w*t) t_0, t_1, n = 0, 1, 501 t=np.linspace(t_0,t_1, n) x0, v0 = 0.0, 0.0 u0 = [ x0, v0 ] u = odeint(derivs, u0, t) plt.subplot(2,1,1); plt.title("x(t)"); plt.plot(t, u[:,0]) plt.subplot(2,1,2); plt.title("x'(t)"); plt.plot(t, u[:,1]) plt.show() with the result
has comment: http://stackoverflow.com/comment/82860537
answers question: http://stackoverflow.com/q/47943973
has comment: http://stackoverflow.com/comment/82866374
has comment: http://stackoverflow.com/comment/82862619
has comment: http://stackoverflow.com/comment/82862084
has comment: http://stackoverflow.com/comment/82861156
score: 0
has comment: http://stackoverflow.com/comment/82860887
has comment: http://stackoverflow.com/comment/82860388

http://stackoverflow.com/q/47901618
has answer: http://stackoverflow.com/a/47903823
has body: Say I have two buttons, in a horizontal layout, that I need to add to a QMainWindow (basically, an app with a menu bar and two buttons in the main area). I tried implementing it this way class Example(QMainWindow): def __init__(self): super().__init__() # Menus exitAct = QAction(QIcon('exit.png'), '&amp;Exit', self) exitAct.setShortcut('Ctrl+Q') exitAct.setStatusTip('Exit application') exitAct.triggered.connect(qApp.quit) self.statusBar() menubar = self.menuBar() fileMenu = menubar.addMenu('&amp;File') fileMenu.addAction(exitAct) # central widget firstButton = QPushButton("first") secondButton = QPushButton("second") hbox = QHBoxLayout() hbox.addWidget(firstButton) hbox.addWidget(secondButton) # Not working because TypeError: setCentralWidget(self, QWidget): argument 1 has unexpected type 'QHBoxLayout' # self.setCentralWidget(hbox) # Not working because centralWidget is not set, therefore is null # self.centralWidget().setLayout(hbox) # Not working because this is a QMainWindow, and the top-level widget already has a layout containing the menu bar for instance self.setLayout(hbox) self.setGeometry(300, 300, 300, 190) self.setWindowTitle('Points') self.show() I have defined my two buttons, created an horizontal layout and added the buttons to the layout. Now I need to tell my window to use this layout. However, I cannot manage to add the layout to the QMainWindow, because QMainWindow already has a top level layout (for the menu bar among other things). As a result, my buttons are not displayed. How can I achieve this ?
tagged with: pyqt5
type: Question
accepted answer: http://stackoverflow.com/a/47903823
score: 2
downvote count: 0
answer count: 1
favorite count: 0
upvote count: 2
tagged with: python
has title: How to make a layout the main widget of a QMainWindow
type: AnsweredQuestion

http://stackoverflow.com/comment/82988956
comment on: http://stackoverflow.com/a/48009907
score: 1
has text: You could also just do `def greatest_odd_number_below(n): return n//2 * 2 - 1`
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47875208
has comment: http://stackoverflow.com/comment/82715918
tagged with: pandas
has answer: http://stackoverflow.com/a/47875305
answer count: 1
downvote count: 0
has body: I have two python data frames. I want to make all the values in one column of both data frames uppercase. The following code works: df_ERA4['reqmnt'] = df_ERA4['reqmnt'].str.upper() df_ERA5['reqmnt'] = df_ERA5['reqmnt'].str.upper() But when I want to do the same thing in a function it doesn't work: def uppercase(df): df['reqmnt'] = df['reqmnt'].str.upper() df_ERA4 = uppercase(df_ERA4) df_ERA5 = uppercase(df_ERA5) df_ERA4.head() Specifically, when I run the above code it gives me the following error: AttributeError: 'NoneType' object has no attribute 'head'
has comment: http://stackoverflow.com/comment/82715852
favorite count: 0
tagged with: python
has title: Python Dataframe: Create function that makes all values in one column uppercase
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47875305
score: 1
has comment: http://stackoverflow.com/comment/82715837
upvote count: 1
type: Question
tagged with: function

http://stackoverflow.com/comment/82749793
type: Comment
has text: how could I use the same one? I run the script like {python3 script.py}
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47891371

http://stackoverflow.com/a/47859653
has comment: http://stackoverflow.com/comment/82713808
has comment: http://stackoverflow.com/comment/82717068
downvote count: 0
answers question: http://stackoverflow.com/q/47859521
type: Answer
has body: Simplest solution: don't ask for the £ char ;-) A solution that work with your requirement is to change the line if len(minpay) or len(maxpay) &gt; maxSalary : with something like if int(minpay[1:]) &gt; int(maxSalary[1:]) or int(maxpay[1:]) &gt; int(maxSalary[1:]) : which check the numeric value of the strings (your condition seems wrong anyway to me)
upvote count: 2
score: 2

http://stackoverflow.com/q/47876663
tagged with: python
score: 14
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47876761
possible better answer: http://stackoverflow.com/a/47876770
upvote count: 14
has answer: http://stackoverflow.com/a/47876770
has title: pandas divide two multi index series
type: Question
has body: I have a multi-index series that looks like value foo bar baz 1 A C 6 D 2 B D 6 F 4 2 B C 5 F 7 I would like to sum on foo and bar, to get the sum of values for each foo, bar, regardless of baz, which I can achieve with df.groupby(level=[0, 1]).sum(). This series looks like: sum_value foo bar 1 A 8 B 10 2 B 12 However, I would then like to divide the original value by the new sum_value, to get the percentage of baz, given foo and bar. value foo bar baz 1 A C 6/8=.75 D 2/8=.25 B D 6/10=.6 F 4/10=.5 2 B C 5/12=.42 F 7/12=.58 I have tried df.div(df.groupby(level=[0, 1]).sum()), but get a Not Implemented error. Thanks!
tagged with: group-by
downvote count: 0
answer count: 3
has answer: http://stackoverflow.com/a/47876777
tagged with: pandas
has answer: http://stackoverflow.com/a/47876761
favorite count: 0

http://stackoverflow.com/a/47967038
has body: I can think of two options: 1) You use a simple "while true" and "wait" in python, so the script is running constantly. import time while True: # Code time.sleep(5) # goes to sleep for 5 seconds You can also do this in shell script (infinite loop+sleep) and then run the program when you want. 2) You can use cronjobs to run the pytho script. You basically have the script the will scrap the website and it will be launched every X seconds/minutes/hours. You can read more about how to use cronjobs in Google
score: 0
answers question: http://stackoverflow.com/q/47967004
type: Answer
has comment: http://stackoverflow.com/comment/82903614
has comment: http://stackoverflow.com/comment/82903960

http://stackoverflow.com/comment/82846604
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47938436
has text: I want to patch DataFrame in pandas but I can’t. I was told it is precompiled and can’t be monkey patched on runtime. So I will patch the functions using DataFrama. But since I apply the same patch to many functions I want to do this in a loop. See also my initial question: https://stackoverflow.com/questions/47922816/override-module-method-to-extend-functionality-then-import-the-updated-module-fr

http://stackoverflow.com/comment/90963507
score: 0
type: Comment
type: QuestionComment
has text: @jtlz2 Ah, I see :) I think it's good for comparing two files that should be identical, like an original and a copy, say a download from the web, but when compressing an image file, the checksum changes of course. I guess decompressing the new file and comparing the SSD between pixel values, similar to what was proposed in the second comment, could be seen as a kind of check sum in this context though.
comment on: http://stackoverflow.com/q/47884976

http://stackoverflow.com/a/60283571
answers question: http://stackoverflow.com/q/47861084
upvote count: 37
type: Answer
downvote count: 0
has body: The function _floats_feature described in the Tensorflow-Guide expects a scalar (either float32 or float64) as input. def _float_feature(value): """Returns a float_list from a float / double.""" return tf.train.Feature(float_list=tf.train.FloatList(value=[value])) As you can see the inputted scalar is written into a list (value=[value]) which is subsequently given to tf.train.FloatList as input. tf.train.FloatList expects an iterator that outputs a float in each iteration (as the list does). If your feature is not a scalar but a vectur, _float_feature can be rewritten to pass the iterator directly to tf.train.FloatList (instead of putting it into a list first). def _float_array_feature(value): return tf.train.Feature(float_list=tf.train.FloatList(value=value)) However if your feature has two or more dimensions this solution does not work anymore. Like @mmry described in his answer in this case flattening your feature or splitting it into several one-dimensional features would be a solution. The disadvantage of these two approaches is that the information about the actual shape of the feature is lost if no further effort is invested. Another possibility to write an example message for a higher dimensional array is to convert the array into a byte string and then use the _bytes_feature function described in the Tensorflow-Guide to write the example message for it. The example message is then serialized and written into a TFRecord file. import tensorflow as tf import numpy as np def _bytes_feature(value): """Returns a bytes_list from a string / byte.""" if isinstance(value, type(tf.constant(0))): # if value ist tensor value = value.numpy() # get value of tensor return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) def serialize_array(array): array = tf.io.serialize_tensor(array) return array #---------------------------------------------------------------------------------- # Create example data array_blueprint = np.arange(4, dtype='float64').reshape(2,…
score: 37

http://stackoverflow.com/q/47971907
tagged with: zeromq
tagged with: tcp
has title: C++ and Python ZeroMQ 4.x PUB/SUB example does not work
type: Question
downvote count: 0
has body: I can only find old C++ source examples. Anyways, I did mine, based on them. Here's my publisher in python: import zmq context = zmq.Context() socket = context.socket(zmq.PUB) socket.bind("tcp://*:5563") while True: msg = "hello" socket.send_string(msg) print("sent "+ msg) sleep(5) And here's the subscriber in C++: void * ctx = zmq_ctx_new(); void * subscriber = zmq_socket(ctx, ZMQ_SUB); // zmq_connect(subscriber, "tcp://*:5563"); zmq_connect(subscriber, "tcp://localhost:5563"); // zmq_setsockopt(subscriber, ZMQ_SUBSCRIBE, "", sizeof("")); while (true) { zmq_msg_t msg; int rc; rc = zmq_msg_init( &amp; msg); assert(rc == 0); std::cout &lt;&lt; "waiting for message..." &lt;&lt; std::endl; rc = zmq_msg_recv( &amp; msg, subscriber, 0); assert(rc == 1); std::cout &lt;&lt; "received: " &lt;&lt; (char * ) zmq_msg_data( &amp; msg) &lt;&lt; std::endl; zmq_msg_close( &amp; msg); } Initially, I tried zmq_setsockopt( subscriber, ZMQ_SUBSCRIBE, "", sizeof("") ); but I guess I should receive everything if I don't set this, right? So I commented it. When I run the code, I see "waiting for message..." forever. I tried to listen to TCP traffic using tcpdump. Turns out that when the publisher is turned on, I see a lot of garbage on the 5563 port, and when I turn the publisher off, they stop. When I tried a PUSH/PULL scheme, I could see the plaintext message in tcpdump. (I tried pushing with nodejs and pulling with c++ and it worked). What could I be doing wrong? I tried different combinations of .bind(), .connect(), localhost, 127.0.0.1, but they won't work either. UPDATE: I've just read that I must subscribe to something, so I did zmq_setsockopt( subscriber, ZMQ_SUBSCRIBE, NULL, 0 ); to subscribe to everything but I still receive nothing PyZMQ is in version 17.0.0.b3 and has ZeroMQ 4.2.3 C++ has ZeroMQ 4.2.2 UPDATE 2: Updates both to 4.2.3, won't work either.
accepted answer: http://stackoverflow.com/a/48196391
score: 11
tagged with: pyzmq
has answer: http://stackoverflow.com/a/48022156
answer count: 4
upvote count: 11
favorite count: 0
possible better answer: http://stackoverflow.com/a/48022156
has answer: http://stackoverflow.com/a/48104560
tagged with: python
tagged with: c++
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48196391
has answer: http://stackoverflow.com/a/48016421

http://stackoverflow.com/comment/82680058
comment on: http://stackoverflow.com/q/47857632
has text: As a last-ditch guess, do you possibly have multiple active connections that have been overlooked during your effort to strip the code back?
score: 0
type: Comment
type: QuestionComment

google-oauth
type: Tag
tag name: google-oauth
tags question: http://stackoverflow.com/q/47893474

http://stackoverflow.com/comment/82750636
comment on: http://stackoverflow.com/a/47890694
score: 0
type: Comment
has text: Its a string value that I can't seem to change. Sorry, I don't use classes that often so I may be missing something simple.
type: AnswerComment

http://stackoverflow.com/comment/82944844
score: 0
has text: First of all, you should use Dot Source in the second powershell to call the first PS1's function. Secondly, if all are functions then you should use psm1(module). Third, In python if you want to do,then change the working directory to the one where ps1 is located. I wont say bad question, but poorly researched. Welcome to SO. Go through [HOW TO ASK GOOD QUESTION](https://stackoverflow.com/help/how-to-ask)
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47988038

http://stackoverflow.com/a/47966202
accepted answer of: http://stackoverflow.com/q/47966110
answers question: http://stackoverflow.com/q/47966110
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: I see the form posts credentials to "https://scsctennis.gametime.net/auth/json-index" and get the json in response. Can you post into this endpoint instead of the one you posted? Posting fake credentials to this endpoint: curl "https://scsctennis.gametime.net/auth/json-index" -H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8" -H "Cookie: gametime=ba3725642c5b55fe1123dec46e45e3a7" --data "username=test&amp;passwo rd=test" returns error like {"code":505,"msg":"The username or password was not recognized. Please check the spelling and try again."}
has comment: http://stackoverflow.com/comment/82902576
score: 1
upvote count: 1

encoder-decoder
type: Tag
tags question: http://stackoverflow.com/q/47925287
tag name: encoder-decoder

jquery
tags question: http://stackoverflow.com/q/47998286
tags question: http://stackoverflow.com/q/47955849
tags question: http://stackoverflow.com/q/48002644
tags question: http://stackoverflow.com/q/47930411
type: Tag
tags question: http://stackoverflow.com/q/47919757
tags question: http://stackoverflow.com/q/47899093
tags question: http://stackoverflow.com/q/47993391
tags question: http://stackoverflow.com/q/47888639
tag name: jquery
tags question: http://stackoverflow.com/q/47936150
tags question: http://stackoverflow.com/q/47954185
tags question: http://stackoverflow.com/q/47908596

http://stackoverflow.com/comment/82686733
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47860867
score: 1
has text: perfect answer. Well explained, I learned a lot, and it solved my issue. Thanks very much @Stephen Rauch

http://stackoverflow.com/comment/82741284
comment on: http://stackoverflow.com/a/47886143
type: Comment
score: 1
type: AnswerComment
has text: "_I am unsure whether 127.0.0.2 is localhost, too._" @guettli see the answer to [this question](https://networkengineering.stackexchange.com/q/44635/8499).

http://stackoverflow.com/a/47919532
type: Answer
score: 2
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/47919440
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47919440
has body: The for loop should be modified as below, for i, teams in enumerate(data): HomeTeam = teams['Properties']['HomeTeam'] print (HomeTeam) This will output Columbus Blue Jackets Philadelphia Flyers Calgary Flames You don't need the inner loop since teams['Properties'] is a dictionary, not a list. Edit: Also, since you are not using the counter, you don't need to enumerate data,which is already a list for teams in data: HomeTeam = teams['Properties']['HomeTeam'] print (HomeTeam)

http://stackoverflow.com/comment/82993038
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48011969
has text: Thanks for you answer, but it didn't work. It throws syntax error at all lines. I'm using python 3.6 BTW.
type: Comment

http://stackoverflow.com/q/47946008
tagged with: macos
favorite count: 0
has title: Properly compile Zim wiki for Mac OS
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/65097052
has answer: http://stackoverflow.com/a/65097052
has answer: http://stackoverflow.com/a/58723397
type: Question
tagged with: compilation
has body: Does anyone know how to compile Zim wiki for Mac so that it functions just like any other app. I currently have it setup using Platypus as described here. However that gives you two icons in the dock and the app window doesn't look very nice. I was wondering if there perhaps was a better solution.
tagged with: wiki
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/58723397

http://stackoverflow.com/q/48012287
has comment: http://stackoverflow.com/comment/83047961
score: 15
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48037093
downvote count: 1
upvote count: 16
has body: I'm still newbie in tensorflow and I'm trying to understand what's happenning in details while my models' training goes on. Briefly, I'm using the slim models pretrained on ImageNet to do the finetuning on my dataset. Here are some plots extracted from tensorboard for 2 separate models: Model_1 (InceptionResnet_V2) Model_2 (InceptionV4) So far, both models have poor results on the validation sets (Average Az (Area under the ROC curve) = 0.7 for Model_1 &amp; 0.79 for Model_2). My interpretation to these plots is that the weights are not changing over the mini-batches. It's only the biases that change over the mini-batches and this might be the problem. But I don't know where to look to verify this point. This is the only interpretation I can think of but it might be wrong considering the fact that I'm still newbie. Can u please share with me your thoughts? Don't hesitate to ask for more plots in case needed. EDIT: As you can see in the plots below, it seems the weights are barely changing over time. This is applied for all other weights for both networks. This led me to think that there is a problem somewhere but don't know how to interpret it. InceptionV4 weights InceptionResnetV2 weights EDIT2: These models were first trained on ImageNet and these plots are the results of finetuning them on my dataset. I'm using a dataset of 19 classes with roughly 800000 images in it. I'm doing a multi-label classification problem and I'm using sigmoid_crossentropy as a loss function. The classes are highly unbalanced. In the table below, we're showing the percentage of presence of each class in the 2 subsets (train, validation): Objects train validation obj_1 3.9832 % 0.0000 % obj_2 70.6678 % 33.3253 % obj_3 89.9084 % 98.5371 % obj_4 85.6781 % 81.4631 % obj_5 92.7638 % 71.4327 % obj_6 99.9690 % 100.0000 % obj_7 90.5899 % 96.1605 % obj_8 77.1223 % 91.8368 % obj_9 94.6200 % 98.8323 % obj_10 88.2051 % 95.0989 % obj_11 3.8838 % 9.3670 % obj_12 50.0131 % 24.8709 % obj_13 0.0056 % 0.0…
tagged with: tensorflow
type: Question
has title: Interpreting tensorboard plots
answer count: 1
favorite count: 0
tagged with: tensorflow-slim
has comment: http://stackoverflow.com/comment/83048949
tagged with: tensorboard
has comment: http://stackoverflow.com/comment/83047717
tagged with: python

http://stackoverflow.com/q/47895059
tagged with: ubuntu
has body: while running a python file with the terminal the following ImportError occurs: ImportError: No module named pyscreenshot if I run it with spyder everything works fine... I dont know why this ImportError occurs and how to fix it. Also I execute the python file in the terminal with sudo.. if it helps.
has answer: http://stackoverflow.com/a/47895217
score: 0
tagged with: importerror
has answer: http://stackoverflow.com/a/47895121
has title: Terminal ImportError: No module named pyscreenshot
type: UnansweredQuestion
tagged with: python
type: Question
answer count: 2

http://stackoverflow.com/comment/82893811
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47962083
score: 0
has text: This isn't valid Python. Your indentation is incorrect, which means it's unclear what's happening. Can you please fix your indentation? To what level have you profiled RAM usage? Are you checking individual threads or just overall usage? Are you including your database in that?

http://stackoverflow.com/q/47878260
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82723739
tagged with: http://stackoverflow.com/tag/json
answer count: 2
accepted answer: http://stackoverflow.com/a/47878468
downvote count: 0
favorite count: 0
has body: I'm writing code that needs to reach out to this JSON file that's online, query it for data, and return the results of the search. I tried the following code: adsb_data = urllib2.urlopen('http://website.com') That will throw a urllib2.HTTPError: HTTP Error 403: Forbidden So obviously I'm not going about it the best way. What would be the best way to open that JSON page, scrape it, and display results? I feel like there's a much more elegant and pythonic way to do this.
has comment: http://stackoverflow.com/comment/82722561
possible better answer: http://stackoverflow.com/a/47896788
has comment: http://stackoverflow.com/comment/82722629
tagged with: python
has answer: http://stackoverflow.com/a/47896788
has title: Reading web-based JSON
score: 1
has answer: http://stackoverflow.com/a/47878468
upvote count: 1
linked to: http://stackoverflow.com/q/13303449
has comment: http://stackoverflow.com/comment/82722567
tagged with: urllib
type: Question

http://stackoverflow.com/q/48011746
has answer: http://stackoverflow.com/a/48011828
tagged with: python-3.x
linked to: http://stackoverflow.com/q/34246170
has comment: http://stackoverflow.com/comment/82992654
tagged with: python
has body: I know that there are a bunch of other similar questions to this, but I have built off other answers with no success. I've dug here, here, here, here, and here but this question is closest to what I'm trying to do, however it's in php and I'm using python3 My goal is to extract a substring from a body text. The body is formatted: **Header1** thing1 thing2 thing3 thing4 **Header2** dsfgs sdgsg rrrrrr **Hello Dolly** abider abcder ffffff etc. Formatting on SO is tough. But in the actual text, there's no spaces, just newlines for each line. I want what's under Header2, so currently I have: found = re.search("\*\*Header2\*\*\n[^*]+",body) if found: list = found.group(0) list = list[11:] list = list.split('\n') print(list) But that's returning "None". Various other regex I've tried also haven't worked, or grabbed too much (all of the remaining headers). For what it's worth I've also tried: \*\*Header2\*\*.+?^\**$ \*\*Header2\*\*[^*\s\S]+\*\* and about 10 other permutations of those.
tagged with: regex
possible better answer: http://stackoverflow.com/a/48011802
type: AnsweredQuestion
has title: Regex search up to first instance Python
score: 1
linked to: http://stackoverflow.com/q/5074331
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/10008064
accepted answer: http://stackoverflow.com/a/48012025
linked to: http://stackoverflow.com/q/21972432
tagged with: search
upvote count: 2
has answer: http://stackoverflow.com/a/48011802
linked to: http://stackoverflow.com/q/44314013
answer count: 3
linked to: http://stackoverflow.com/q/25825660
has comment: http://stackoverflow.com/comment/82992024
tagged with: python-3.5
has answer: http://stackoverflow.com/a/48012025
favorite count: 0

http://stackoverflow.com/comment/82926743
type: Comment
comment on: http://stackoverflow.com/a/47978607
type: AnswerComment
has text: @Topto, you're welcome. See the link https://www.crummy.com/software/BeautifulSoup/bs4/doc/#contents-and-children
score: 0

http://stackoverflow.com/a/47906777
type: Answer
upvote count: 1
has body: You could capture the \1 group too, and then use list comprehension to join them together: &gt;&gt;&gt; re.findall(r'(\d)(\1+)', n) [('4', '4'), ('5', '55'), ('2', '2')] &gt;&gt;&gt; [''.join(i) for i in re.findall(r'(\d)(\1+)', n)] ['44', '555', '22']
score: 1
answers question: http://stackoverflow.com/q/47906708
downvote count: 0

http://stackoverflow.com/comment/82895871
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47963114
has text: @AliShakiba So, what would be the length of `S`? Would it be same as the first axis or the second axis of `X`?
type: AnswerComment

http://stackoverflow.com/comment/83682232
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47955313
has text: In the first example do you intentionally hide class members with instance members of the same names? Please help understanding this idiom.
score: 7

http://stackoverflow.com/comment/82912710
has text: At least let us know what you are expecting as output
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47971596
score: 0

http://stackoverflow.com/comment/82977350
has text: 1. win32com.client works on both 32 and 64 bit COM objects, and in Python64 as well 2. I would like to run a script on a client's machine and discover in code which architecture is installed.
comment on: http://stackoverflow.com/q/47979234
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47966093
accepted answer: http://stackoverflow.com/a/47969988
has answer: http://stackoverflow.com/a/47966270
tagged with: python
has comment: http://stackoverflow.com/comment/82901856
type: AnsweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/47966349
type: Question
possible better answer: http://stackoverflow.com/a/47966314
has title: Search and split certain string in text file and saved output
upvote count: 2
has body: How to split certain string in rows that contain characters of numbers and alphabets. Set data I have is like this (tembin-data.dat): ['3317121918', '69N1345E', '15'] ['3317122000', '72N1337E', '20'] ['3317122006', '75N1330E', '20'] ['3317122012', '78N1321E', '20'] ['3317122018', '83N1310E', '25'] .......etc I need the new data arrangement by removing "N" and "E" just like this: ['3317121918', '69','1345','15'] ['3317122000', '72','1337','20'] ['3317122006', '75','1330','20'] ['3317122012', '78','1321','20'] ['3317122018', '83','1310','25'] .......etc Python script that I used at moment is like this: newfile = open('tembin-data.dat', 'w') with open('tembin4.dat', 'r') as inF: for line in inF: myString = '331712' if myString in line: data=line.split() print data newfile.write("%s\n" % data) newfile.close() tembin4.dat is as below: REMARKS: 230900Z POSITION NEAR 7.8N 118.6E. TROPICAL STORM 33W (TEMBIN), LOCATED APPROXIMATELY 769 NM EAST- SOUTHEAST OF HO CHI MINH CITY, VIETNAM, HAS TRACKED WESTWARD AT 11 KNOTS OVER THE PAST SIX HOURS. MAXIMUM SIGNIFICANT WAVE HEIGHT AT 230600Z IS 14 FEET. NEXT WARNINGS AT 231500Z, 232100Z, 240300Z AND 240900Z.// 3317121918 69N1345E 15 3317122000 72N1337E 20 3317122006 75N1330E 20 3317122012 78N1321E 20 3317122018 83N1310E 25 3317122100 86N1295E 35 3317122106 85N1284E 35 3317122112 84N1276E 40 3317122118 79N1267E 50 3317122118 79N1267E 50 3317122200 78N1256E 45 3317122206 78N1236E 45 3317122212 80N1225E 45 3317122218 79N1214E 50 3317122218 79N1214E 50 3317122300 77N1204E 55 3317122300 77N1204E 55 3317122306 77N1193E 55 3317122306 77N1193E 55 NNNN
score: 0
has answer: http://stackoverflow.com/a/47966320
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/47969988
has answer: http://stackoverflow.com/a/47966314
answer count: 5

http://stackoverflow.com/comment/82733455
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47883630
has text: you can iterate the sale_price and seller data then join it as a single list.

http://stackoverflow.com/comment/82799917
score: 0
has text: You probably want to use [os.listdir](https://docs.python.org/3/library/os.html#os.listdir) or [os.walk](https://docs.python.org/3/library/os.html#os.walk) to iterate and check names with the regex `^\d{4}2013$`. See [Getting a list of all subdirectories in the current directory](https://stackoverflow.com/questions/973473/getting-a-list-of-all-subdirectories-in-the-current-directory).
comment on: http://stackoverflow.com/q/47915831
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47904311
has comment: http://stackoverflow.com/comment/82775870
has body: You cannot apply unique() on a non-hashable type such as list. You need to convert to a hashable type to do that. A better solution using the latest version of pandas is to use duplicated() and you avoid iterating over the values to convert to list again. df[~df.col.apply(tuple).duplicated()] That would return as lists the unique values.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47901307

http://stackoverflow.com/q/47946616
tagged with: variables
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/82863274
tagged with: python
has comment: http://stackoverflow.com/comment/82863236
has answer: http://stackoverflow.com/a/47946722
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/47946683
has comment: http://stackoverflow.com/comment/82863272
has comment: http://stackoverflow.com/comment/82863242
type: Question
accepted answer: http://stackoverflow.com/a/47946706
has body: Question In python, what is the shortest/easiest way to create a function which allows me to access a variable by concatenating two string literals to generate the variable's name? Background In C, I can do something like so: #define CONCAT(x,y) x ## _ ## y Then, later in my code, I could do something like: int i = CONCAT(PRODUCT,BANANA). Assuming a macro exists with the name PRODUCT_BANANA, its value is now assigned to i. I can accomplish something similar in shell scripts via indirection. Question - Redux How can I accomplish this same functionality in python? I'm doing this because I have a python class with thousands of variables for dozens of different products, i.e. class A(object): BANANA_ADDRESS0 = 0xABCD; PINEAPPLE_ADDRESS0 = 0x1234; BANANA_ADDRESS1 = 0x4567; PINEAPPLE_ADDRESS1 = 0x1000; I'd like to be able to have a function that can be, for example, executed via someFunc("BANANA", "ADDRESS0"), resolve the value as A.BANANA_ADDRESS0, and return the associated value (0xABCD, in this case). Extra Assuming the above is possible, is it possible to have the function always interpret the supplied function arguments as string literals, so function calls don't need the arguments wrapped in single/double quotes? i.e. so it can be called via someFunc(BANANA, ADDRESS0), rather than someFunc("BANANA", "ADDRESS0")?
tagged with: variable-names
has comment: http://stackoverflow.com/comment/82863325
tagged with: python-2.7
has title: Concatenate string literals to generate variable name
possible better answer: http://stackoverflow.com/a/47946683
answer count: 3
has answer: http://stackoverflow.com/a/47946706
downvote count: 0

http://stackoverflow.com/a/47873941
accepted answer of: http://stackoverflow.com/q/47873828
type: AcceptedAnswer
downvote count: 0
score: 13
has body: You can use the distro project: $ pip install distro $ python &gt;&gt;&gt; import distro &gt;&gt;&gt; distro.linux_distribution(full_distribution_name=False) ('centos', '7.1.1503', 'Core') This project came out of issue #1322, which led to the deprecation of the function. From the project README: It is a renewed alternative implementation for Python's original platform.linux_distribution function, but it also provides much more functionality which isn't necessarily Python bound like a command-line interface The method was removed from the platform library because the correct method to detect what distribution you were using changed faster than the Python release schedule could follow. From the above bug report: The stdlib is not the right place for things that change this often. Just look at how many semi standards we've seen in the last few years. There's no point in trying to follow these in a slow moving code base as the Python stdlib. It's much better to put the functionality into a PyPI module which can be updated much more frequently.
type: Answer
upvote count: 13
answers question: http://stackoverflow.com/q/47873828
has comment: http://stackoverflow.com/comment/82714299

http://stackoverflow.com/comment/82682915
has text: Thanks for the answer, but the problem is that my idea is to be able to use that array back for a machine learning algorithm and for that it has to be the same after conversion. How could I do ?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47858996
score: 1

http://stackoverflow.com/a/48010394
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48009926
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48009926
has body: You should indeed be able to use a global for this. However you have to declare the global wherever it is used. You can't just declare it at the top of your module. In other words you have to change grid_input to this to access the global. def grid_input(grid_select,page_select,current_mode): global staff_mode if (staff_mode == 0): #Do stuff else: #Do other stuff However the goal of your code is not that clear to me so I think you could probably come up with a better approach.

http://stackoverflow.com/comment/82856063
comment on: http://stackoverflow.com/a/47940483
type: AnswerComment
score: 0
has text: @Aksakal Check out `Alternative one`.
type: Comment

http://stackoverflow.com/comment/84968351
type: QuestionComment
has text: My suggestion for Pycharm, among other things, was that it created the virtual machine for you. However, you wouldn't generally share you virtual environments because your activate script sets your PATH variable to the location of the venv -- which may differ. For sharing projects -- look at "requirements.txt", and setup.py.
type: Comment
score: 1
comment on: http://stackoverflow.com/q/47973599

http://stackoverflow.com/comment/82835378
has text: If that's `verbose=1`, then there should be `val_loss`, `val_acc` output to your terminal. That's why I asked for showing your output.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47930176

http://stackoverflow.com/comment/83018006
score: 0
has text: Yet is works perfectly now, running for a couple of days stable
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47992555

http://stackoverflow.com/comment/82680646
has text: I ran the stripped-down code. When I encounter a problem that I cannot explain, I reduce the script to the bare minimum of what the functionality would do. In that way I do not have any interference from other Python concepts that I'm not completely familiar with (like the %s you normally use in sql-statements).
score: 0
comment on: http://stackoverflow.com/q/47857632
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82957570
comment on: http://stackoverflow.com/a/47994702
has text: This is a poor abridged summary of the [Stack Overflow `cron` tag info page](/tags/cron/info) which has a good troubleshooting section.
type: AnswerComment
type: Comment
score: 2

http://stackoverflow.com/comment/82963647
comment on: http://stackoverflow.com/q/47973355
has text: hi thanks for answer me what i want to say is that the app uses celery and redis to run task in background and the task calls some stored procedures from the database. The app run in a linux server so when the server fell dawn I restaured the aplication and until that point there hasn't no problem but when i tryed to execute some reports in the app nothing happens and then i found that i had to run celery or redis and that part confuse me.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82920354
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47948160
has text: I used the Terminal to install the Keras.: pip install keras.. There were no Errors while installing..!
type: Comment

http://stackoverflow.com/a/47991346
has body: The VLC repo has a complete example for Tkinter.
has comment: http://stackoverflow.com/comment/82954487
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47990695
score: 1
upvote count: 2

http://stackoverflow.com/comment/82830011
type: AnswerComment
has text: @SergeyAndSmart Those lines is not part of the code that I have proposed, have you modified my code?
comment on: http://stackoverflow.com/a/47929916
score: 0
type: Comment

http://stackoverflow.com/q/47874952
has comment: http://stackoverflow.com/comment/82715617
has answer: http://stackoverflow.com/a/47894061
accepted answer: http://stackoverflow.com/a/47894061
tagged with: pyqt
upvote count: 1
tagged with: pyqt4
downvote count: 0
answer count: 1
has body: I know this question has been asked in similar ways, but I'm getting lost in the vast world of the many signals I can choose from when using a QSpinBox (or QDoubleSpinBox). I want to connect my function to the editingFinished signal (fine, it works perfectly), but this will not also connect to the arrow-buttons - so I need signals for those as well. I don't want to call my function every time valueChanged is emitted - only when editing is finished, or when the arrows are used.
tagged with: signals-slots
favorite count: 0
has comment: http://stackoverflow.com/comment/82715470
tagged with: python
has comment: http://stackoverflow.com/comment/82715501
type: AnsweredQuestion
type: Question
tagged with: qspinbox
has title: QSpinBox signal for arrow buttons
score: 1

http://stackoverflow.com/comment/82962883
type: QuestionComment
comment on: http://stackoverflow.com/q/47942707
has text: What is your end goal? If you just want to take into account the impact of load to miles per gallon, why not use miles per gallon per pound as your metric?
type: Comment
score: 0

http://stackoverflow.com/q/48010460
has comment: http://stackoverflow.com/comment/82997862
answer count: 1
type: UnansweredQuestion
tagged with: linear-algebra
tagged with: sparse-matrix
has comment: http://stackoverflow.com/comment/82993137
downvote count: 0
score: 1
has title: Solving an overdetermined sparse linear system produces high error solution
favorite count: 0
has answer: http://stackoverflow.com/a/50558919
tagged with: eigen
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/82995740
has body: My Code So I have written an algorithm which iteratively solves a sparse overdetermined linear system. That means my code looks like this: construct_A_matrix(); construct_B_matrix(); while(someCondition){ x=solveSystem(A,B) //solve Ax=B. This system is overdetermined //since A has more rows than cols. update_A_matrix(x) //update A based on x update_B_matrix(x) //update B based on x iterationsCounter++ } useX(); In solveSystem I use eigen's SimplicialLDLT and Conjugate Gradient solvers (I use both of them for debugging purposes, if the code worked I would use only one of them). The code I use to solve the system is: for Conjugate Gradient using SpMatrix = Eigen::SparseMatrix<double>; Eigen::ConjugateGradient<SpMatrix, Eigen::Lower | Eigen::Upper> solver; SpMatrix At = A.transpose(); SpMatrix AtA = At * A; solver.compute(AtA); EigenMatrix newVertexPositions = solver.solve(At * B); std::cout << "estimated error: " << solver.error() << std::endl; double residual=(A.transpose() * (A * x) - A.transpose() * B).norm()/(A.transpose() * B).norm(); and for SimplicialLDLT using SpMatrix = Eigen::SparseMatrix<double>; Eigen::SimplicialLDLT<SpMatrix> solver; SpMatrix At = A.transpose(); SpMatrix AtA = At * A; solver.compute(AtA); if (solver.info() != Eigen::Success) std::cout << "Decomposition failed!" << std::endl; EigenMatrix AtB = At * B; EigenMatrix x = solver.solve(AtB); if (solver.info() != Eigen::Success) std::cout << "Solving failed!" << std::endl; //simplicialLDLT has no error() function double residual=(A.transpose() * (A * x) - A.transpose() * B).norm() /(A.transpose() * B).norm(); The problem After some number of iterations of the above loop the residual/error of the solver rises and the solution I get is wrong. SimplicialLDLT is producing better results than Conjugate Gradient but still wrong after a while. This can be seen graphically below. As you can see SimplicialLDLT's residual grows later than Conjugate Gradient's. So this is my problem and I am trying to figur…
upvote count: 1

http://stackoverflow.com/comment/82925389
score: 0
comment on: http://stackoverflow.com/q/47880666
type: Comment
type: QuestionComment
has text: @Gahan I want to add custom information for the user which will be created. Such use the create time to generate a number for it.

http://stackoverflow.com/comment/82704472
comment on: http://stackoverflow.com/a/47869378
score: 0
type: AnswerComment
has text: Thank you for your response. This is the last resort i would opt for. I wanted to create a script on Linux side to fetch the file that is generated on windows.
type: Comment

http://stackoverflow.com/q/47927877
has answer: http://stackoverflow.com/a/47928918
type: Question
has body: Exposition: Using the logging module in a 3.6.3 Python there are some misunderstood issues. At first, I create 2 logs with the standard config, without a name and level = 30, which is logging.WARNING. As the docs said, the log object cames without handlers, I change the log level to 10 (logging.DEBUG) and when I'm going to print|log with INFO (which is level=20), first, being in level 10 (beneath info level) the info doesn't logs and, finally, the log hasn't got any handlers, but the doc of https://docs.python.org/3/library/logging.html?highlight=logging#module-logging says : logging.basicConfig(**kwargs)¶ : Does basic configuration for the logging system by creating a StreamHandler with a default Formatter and adding it to the root logger. The functions debug(), info(), warning(), error() and critical() will call basicConfig() automatically if no handlers are defined for the root logger. So, my questions are, what I'm doing wrong? why is this caused? Can't I instantiate the log, set level for Root as log.setLevel(logging.INFO) and make log.info("poo") as I was doing until this issue?. Code: Python 3.6.3 (default, Oct 31 2017, 11:19:55) Type 'copyright', 'credits' or 'license' for more information IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help. In [1]: import logging In [2]: log1 = logging.getLogger() In [3]: log2 = logging.getLogger() In [4]: log1.level Out[4]: 30 In [5]: log1.hasHandlers() Out[5]: False In [6]: log1.setLevel(10) ## logging.DEBUG == 10 In [7]: log1 Out[7]: &lt;RootLogger root (DEBUG)&gt; In [8]: log2 Out[8]: &lt;RootLogger root (DEBUG)&gt; In [9]: log1.info("asdad") In [10]: log2.info("asdad") In [11]: log1.hasHandlers() Out[11]: False In [12]: logging.basicConfig(level=20) # logging.INFO == 20 In [13]: log2 Out[13]: &lt;RootLogger root (INFO)&gt; In [14]: log2.info("ASDADA") INFO:root:ASDADA In [15]: log1.hasHandlers() Out[15]: True In [16]: log1.handlers == log2.handlers Out[16]: True In [17]: logging.basicConfig(level=10) # l…
upvote count: 0
answer count: 1
favorite count: 0
has title: Why Python's logging package ignores some levels?
tagged with: python
type: UnansweredQuestion
downvote count: 1
tagged with: logging
score: -1

http://stackoverflow.com/comment/82925259
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47973496
type: QuestionComment
has text: @dsgdfg So apparently I needed to use libusb and install the driver for the device. I thought I needed the `libusb1` library. xD

http://stackoverflow.com/a/47860501
score: 0
type: AcceptedAnswer
has body: List comprehension is one way like how @Micheal has. Otherwise if you want in your way try this: (Create an empty list and append it) numbers_list = [1, 2, 3] new_list = [] for i in numbers_list: new_list.append(('MIN_SPAN' + '_' + str(i))) output, print(new_list) &gt;['MIN_SPAN_1', 'MIN_SPAN_2', 'MIN_SPAN_3']
type: Answer
accepted answer of: http://stackoverflow.com/q/47860444
answers question: http://stackoverflow.com/q/47860444
has comment: http://stackoverflow.com/comment/82686032

http://stackoverflow.com/q/47980946
upvote count: 3
answer count: 2
has answer: http://stackoverflow.com/a/47983088
favorite count: 0
has comment: http://stackoverflow.com/comment/82933865
tagged with: python
accepted answer: http://stackoverflow.com/a/48046443
type: AnsweredQuestion
score: 3
downvote count: 0
possible better answer: http://stackoverflow.com/a/47983088
has comment: http://stackoverflow.com/comment/82930794
has answer: http://stackoverflow.com/a/48046443
type: Question
tagged with: aws-glue
has body: I have a table which contains few schedules for various jobs. I want to process the records and create Triggers via AWS Glue API. http://docs.aws.amazon.com/glue/latest/dg/aws-glue-api.html The above link shows the documentation go for AWS Glue. Is there anyone who can provide a code snippet on how to use the API? I have searched for long enough on the net and havent found any documentation that provides a code snippet! I am looking for code snippet for the following API CALL. CreateTrigger Action (Python: create_trigger) Any help would be great.
has title: AWS Glue create Triggers via API
tagged with: amazon-web-services

http://stackoverflow.com/a/47914330
answers question: http://stackoverflow.com/q/47913994
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/82949772
has body: You can use the Axes.set_tick_params() function to adjust the padding between the axe and the tick labels (minor, major, or both) ax.xaxis.set_tick_params(which='minor', pad=25)

http://stackoverflow.com/comment/82999581
score: 0
type: AnswerComment
type: Comment
has text: Sorry for late reply. Yes this work perfectly, I re-wrote it with Xpath instead of css and it worked great. But I still don't understand why you need to iterate over the 'table' element and can't do the same over the 'a' element (i.e. changing "tables = day.css('table')" to "tables = day.css('a')" will return "None' to all the variables you print in the Result).
comment on: http://stackoverflow.com/a/47957169

http://stackoverflow.com/a/47984511
answers question: http://stackoverflow.com/q/47978507
has body: I would use commands extension - https://github.com/Rapptz/discord.py/blob/async/examples/basic_bot.py Then make a command like, @bot.command(pass_context=True) async def id(ctx, number : int): await bot.say(number)
type: Answer
score: 0

http://stackoverflow.com/q/47863170
tagged with: tic-tac-toe
accepted answer: http://stackoverflow.com/a/47863201
type: AnsweredQuestion
score: -2
has title: how to use random function in python?
type: Question
has answer: http://stackoverflow.com/a/47863201
answer count: 2
downvote count: 2
tagged with: random
possible better answer: http://stackoverflow.com/a/47863868
favorite count: 0
has body: #program to tic-tac-toe from random import * num=[i for i in range(1,10)] flag=0 ulist=list(); xlist=list(); olist=list(); count=0 while(count &lt; 9): if(flag==0): x=random.choice(num) if(x not in ulist): ulist.append(x) xlist.append(x) flag=1 if(flag==1): o=random.choice(num) if(o not in ulist): ulist.append(o) olist.append(o) flag=0 count+=1 print (ulist) print (xlist) print (olist) this is my code i have called for the random function but still its saying i did not use the random function
tagged with: python
upvote count: 0
has answer: http://stackoverflow.com/a/47863868
has comment: http://stackoverflow.com/comment/82691359

http://stackoverflow.com/q/47905873
tagged with: email
downvote count: 0
favorite count: 0
has title: Parse read messages in Python
type: UnansweredQuestion
tagged with: python
has body: I have read several answers about how to read the email in Python. All of them partially work, as it does not handle correctly read messages or messages restored from the trash. My question is therefore: how can I read messages that are marked as read? Is there a more robust way to do this in Python? Here is the code I am using: import poplib import email mailServer = 'pop.gmail.com' emailID = 'myemail' emailPass = 'mypass' myEmailConnection = poplib.POP3_SSL(mailServer) myEmailConnection.user(emailID) myEmailConnection.pass_(emailPass) EmailInformation = myEmailConnection.stat() numberOfMails = EmailInformation[0] for i in range(numberOfMails): print(myEmailConnection.retr(i+1)[1])
tagged with: gmail
answer count: 0
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/82782213

http://stackoverflow.com/comment/82831314
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47931105
score: 0
has text: 1. My output is the first link (see the first href) for however many links there are. If there are say 50 links on the page, it prints the first link 50 times.

http://stackoverflow.com/comment/82942813
score: 0
comment on: http://stackoverflow.com/q/47986878
type: QuestionComment
type: Comment
has text: Should `az` be a list of strings, or one large string with embedded newlines, or something else?

http://stackoverflow.com/comment/82721151
comment on: http://stackoverflow.com/a/47877612
type: AnswerComment
score: 0
type: Comment
has text: This seems simple enough and looks like it should do the job, however can this be made case-insensitive?

http://stackoverflow.com/a/47948504
answers question: http://stackoverflow.com/q/47948423
has comment: http://stackoverflow.com/comment/82867276
downvote count: 0
has comment: http://stackoverflow.com/comment/82868870
type: AcceptedAnswer
has body: I would build a generator to output all the runs of characters such that l[i] &gt;= l[i-1]. Then find the longest of those runs. Something like def runs(l): it = iter(l) try: run = [next(it)] except StopIteration: return for i in it: if i &gt;= run[-1]: run.append(i) else: yield run run = [i] yield run def longest_increasing(l): return ''.join(max(runs(l), key=len)) Edit: Notes on your code for i in range(len(s)): n = 0 letter = s[i+n] if letter in a: number_list.append(a.index(letter)) n += 1 is getting the "number value" for each letter. You can use the ord function to simplify this number_list = [ord(c) - 97 for c in s if c.islower()] You never use index_list, and you never should. Look into the enumerate function. first_check = [] for i in range(len(letter_list)-1): while number_list[i] &lt;= number_list[i+1]: print(letter_list[i]) first_check.append(letter_list[i]) break this part doesn't make a ton of sense. You break out of the while loop every time, so it's basically an if. You have no way of keeping track of more than one run. You have no mechanism here for comparing runs of characters against one another. I think you might be trying to do something like max_run = [] for i in range(len(letter_list)-1): run = [] for j in range(i, len(letter_list)): run.append(letter_list[j]) if letter_list[j] &gt; letter_list[j+1]: break if len(run) &gt; len(max_run): max_run = run (Disclaimer: I'm pretty sure the above is off by one but it should be illustrative). The above can be improved in a lot of ways. Note that it loops over the last character as many as len(s) times, making it a n**2 solution. Also, I'm not sure why you need number_list, as strings can be compared directly.
upvote count: 2
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/47948423

http://stackoverflow.com/comment/82989000
score: 0
comment on: http://stackoverflow.com/q/48010218
type: Comment
type: QuestionComment
has text: Check this link -- > https://stackoverflow.com/questions/7837722/what-is-the-most-efficient-way-to-loop-through-dataframes-with-pandas.

http://stackoverflow.com/a/59522446
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/47980402
score: 1
has body: I was able to implement the following code but I have an additional requirement with this where I can have upto 300 joins in 'CONCAT' and the rest should be in separate row/rows. Example: if I have 750 values in 'CONCAT' with similar 'ISSUEID', first 300 will be in row 1, next 300 in row 2 and remaining 150 in row 3. Is there a way I can tweak this? df = (data.groupby('ISSUEID') .agg({'KICKCODE' : 'first', 'CONCAT' : ','.join}) .reset_index() .reindex(columns=data.columns))
upvote count: 1

http://stackoverflow.com/q/47862651
has body: I have multiple timeseries data imported from CSV files. Those data all have time stamps but the timestamps don't always match: Time series 1: UUT Data DateTime 2017-11-21 18:54:31 uut1 1 2017-11-22 02:26:48 uut1 2 2017-11-22 10:19:44 uut1 3 2017-11-22 15:11:28 uut1 6 2017-11-22 23:21:58 uut1 7 Time series 2: UUT Data DateTime 2017-11-21 18:47:29 uut2 1 2017-11-22 02:26:49 uut2 2 2017-11-22 10:19:44 uut2 3 2017-11-22 15:17:47 uut2 4 2017-11-22 23:21:58 uut2 5 2017-11-23 07:10:56 uut2 6 2017-11-23 15:15:48 uut2 7 2017-11-24 12:16:58 uut2 9 I can use concat function to join them together and groupby 'UUT', however, how can I fill up the empty time slot with previous value to have the final table looks similar to: DateTime UUT Data 11/21/17 18:47:29 uut1 1 11/21/17 18:54:31 1 11/22/17 2:26:48 2 11/22/17 2:26:49 2 11/22/17 10:19:44 3 11/22/17 15:11:28 6 11/22/17 15:17:47 6 11/22/17 23:21:58 7 11/23/17 7:10:56 8 11/23/17 15:15:48 8 11/23/17 15:22:16 9 11/24/17 12:16:58 11 11/21/17 18:47:29 uut2 1 11/21/17 18:54:31 1 11/22/17 2:26:48 1 11/22/17 2:26:49 2 11/22/17 10:19:44 3 11/22/17 15:11:28 3 11/22/17 15:17:47 4 11/22/17 23:21:58 5 11/23/17 7:10:56 6 11/23/17 15:15:48 7 11/23/17 15:22:16 7 11/24/17 12:16:58 9 or to this: DateTime uut1 uut2 11/21/17 18:47:29 1 1 11/21/17 18:54:31 1 1 11/22/17 2:26:48 2 1 11/22/17 2:26:49 2 2 11/22/17 10:19:44 3 3 11/22/17 15:11:28 6 3 11/22/17 15:17:47 6 4 11/22/17 23:21:58 7 5 11/23/17 7:10:56 8 6 11/23/17 15:15:48 8 7 11/23/17 15:22:16 9 7 11/24/17 12:16:58 11 9 My end goal is to be able to plot both uut1 and uut2 data on a single timeseries plot.
tagged with: multi-index
tagged with: pandas
downvote count: 0
answer count: 1
score: 1
favorite count: 0
tagged with: python
has title: Panda concat multiple timeseries with grouping and extend missing data
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47863075
upvote count: 1
type: Question
tagged with: time-series
accepted answer: http://stackoverflow.com/a/47863075
tagged with: dataframe

http://stackoverflow.com/a/47953205
answers question: http://stackoverflow.com/q/47952517
has comment: http://stackoverflow.com/comment/82876323
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82876358
type: Answer
has comment: http://stackoverflow.com/comment/82888713
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82889106
accepted answer of: http://stackoverflow.com/q/47952517
has body: There is problem some values in index are duplicated, because some names should be male and also female like Abbie. So solution is very easy - add only one value to names in read_csv and first with second column are converted to unique MultiIndex. Also was changed columns names with splicing - removed first 3 and last 4 characters. from zipfile import ZipFile zip_file = ZipFile('names1.zip') dfs = [] with zip_file as f: for name in f.namelist(): df1 = pd.read_csv(zip_file.open(name), sep=',',names=[name[3:-4]]) dfs.append(df1) result = pd.concat(dfs,axis=1) print(result.head(10)) 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 \ Aaron M 97.0 88.0 86.0 78.0 90.0 85.0 96.0 69.0 95.0 81.0 Ab M NaN 6.0 NaN 5.0 NaN NaN NaN NaN NaN NaN Abb M 5.0 NaN NaN NaN NaN NaN 6.0 5.0 NaN NaN Abbie F 98.0 88.0 84.0 104.0 137.0 107.0 140.0 124.0 119.0 115.0 M NaN NaN NaN 5.0 NaN NaN NaN 5.0 NaN NaN Abbott M NaN NaN NaN NaN 6.0 NaN NaN NaN NaN NaN Abby F 6.0 5.0 7.0 5.0 9.0 8.0 6.0 12.0 6.0 10.0 Abe M 45.0 47.0 50.0 37.0 46.0 39.0 49.0 40.0 53.0 43.0 Abel M 14.0 6.0 16.0 11.0 8.0 9.0 14.0 10.0 8.0 13.0 Abelina F NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... 1904 1905 1906 1907 1908 1909 1910 1911 1912 \ Aaron M ... 117.0 96.0 96.0 130.0 114.0 142.0 145.0 187.0 303.0 Ab M ... NaN NaN NaN NaN NaN NaN NaN NaN NaN Abb M ... NaN NaN NaN NaN NaN NaN NaN NaN NaN Abbie F ... 80.0 73.0 72.0 79.0 84.0 57.0 79.0 77.0 90.0 M ... NaN 5.0 NaN NaN NaN NaN 8.0 NaN NaN Abbott M ... NaN NaN NaN NaN NaN 5.0 NaN 8.0 8.0 Abby F ... NaN NaN 6.0 5.0 NaN 8.0 6.0 13.0 8.0 Abe M ... 52.0 65.0 50.0 65.0 57.0 67.0 74.0 94.0 172.0 Abel M ... 10.0 6.0 11.0 10.0 15.0 16.0 11.0 30.0 40.0 Abelina F ... NaN NaN NaN NaN NaN NaN NaN NaN NaN 1913 Aaron M 417.0 Ab M NaN Abb M 5.0 Abbie F 121.0 M 7.0 Abbott M 5.0 Abby F 11.0 Abe M 202.0 Abel M 48.0 Abelina F NaN [10 rows x 30 columns]
upvote count: 2

http://stackoverflow.com/comment/84487131
type: Comment
score: 0
has text: I edited the answer with the import. Library used are pandas, scipy and numpy. The code works in Python 2.7.9
type: AnswerComment
comment on: http://stackoverflow.com/a/48733822

http://stackoverflow.com/a/47933806
has comment: http://stackoverflow.com/comment/82838039
has comment: http://stackoverflow.com/comment/82838022
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/82838026
score: 2
has comment: http://stackoverflow.com/comment/82837105
has comment: http://stackoverflow.com/comment/82837793
has comment: http://stackoverflow.com/comment/82837736
accepted answer of: http://stackoverflow.com/q/47933718
has comment: http://stackoverflow.com/comment/82838044
answers question: http://stackoverflow.com/q/47933718
has comment: http://stackoverflow.com/comment/82837831
has comment: http://stackoverflow.com/comment/82836946
has comment: http://stackoverflow.com/comment/82837603
has comment: http://stackoverflow.com/comment/82838071
type: AcceptedAnswer
has body: You can either provide the query in the context passed to the template or use a custom template tag. Lets assume the file that is created is called my_template_tags.py (note that this file must me in the correct directory structure). from django import template register = template.Library() @register.simple_tag def get_method(test, user): return Test.objects.filter(test_id=test.id, user_id=user.id) And then in the template: {% load my_template_tags %} {% get_method test user %}
downvote count: 0

http://stackoverflow.com/q/47956057
tagged with: list
accepted answer: http://stackoverflow.com/a/47956326
has title: List not being recognised as a list when read from text file
has comment: http://stackoverflow.com/comment/82881602
has comment: http://stackoverflow.com/comment/82881587
type: Question
score: 0
answer count: 1
favorite count: 0
has body: I am reading lists from a txt file but when I read them back in and saved to a variable Python recognizes it has a string and not a list. Is there any way around this? def makereport(): with open('quizdb','r') as quizdata: for line in quizdata: print(line) print(line[1]) Output: ['maths(easy).txt', 'joh17', 'C', 0.0, 0] ' As you can see when I print by index position it is printing the character and not the actual position(object) in the list
has comment: http://stackoverflow.com/comment/82881551
has answer: http://stackoverflow.com/a/47956326
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82881592
upvote count: 1
downvote count: 1
type: AnsweredQuestion

http://stackoverflow.com/q/47857556
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/21122540
downvote count: 1
has body: I am making some code that is based on a game. I have gotten a traceback which I haven't encountered before even though I have used these lines of code before. Here is the code: print ("please enter your Forename") fore = input() print ("Please enter your Surname") sur = input if fore == ("Benjamin"): print("ATTENTION. System Breach Detected. Purging System.") and this is the error: line 26, in &lt;module&gt; fore = input() File "&lt;string&gt;", line 1, in &lt;module&gt; NameError: name 'Benjamin' is not defined
accepted answer: http://stackoverflow.com/a/47857622
type: Question
linked to: http://stackoverflow.com/q/16457441
score: -1
has title: Traceback that i can't fix
tagged with: python-2.7
upvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47857622
tagged with: python

http://stackoverflow.com/a/47972023
has comment: http://stackoverflow.com/comment/82931526
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/100280283
has body: right API call: from pyhive import hive cursor = hive.connect(dsn= hive_host+':10000', user=username,password=password).cursor() cursor.execute('SELECT * FROM my_awesome_data LIMIT 10', async=True) reference: https://pypi.python.org/pypi/PyHive
has comment: http://stackoverflow.com/comment/82935638
has comment: http://stackoverflow.com/comment/82931462
accepted answer of: http://stackoverflow.com/q/47964385
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47964385
has comment: http://stackoverflow.com/comment/82931490
type: Answer

http://stackoverflow.com/a/47926112
score: 3
has comment: http://stackoverflow.com/comment/82822661
upvote count: 3
has comment: http://stackoverflow.com/comment/82823869
has body: Queryset methods that return a queryset actually return a new queryset (they dont change the current queryset inplace). It's not that they are returning "regular" querysets, they are instances of your custom queryset subclass (you can check this by yourself by inspecting your queryset type), but the edit_desc() method has not been called on them. Technically you could "solve" this by overridding all the exclude/filter/ect methods to reapply your edit_desc() method, but it will be terribly inefficient (even more than it actually is), so you may want to rethink about what your real problem is and how to solve it in a more efficient and less intrusive way. Perhaps explaining your concrete use case could lead to better answers at how to solve it ? EDIT : given your comment, a possible (and much more efficient) solution would be to override the QuerySet parts that yield or return a model instance (or just the raw values) so you can process your model instance / data at this point. You may want to have a look at django/db/query.py, specially the ModelIterable and ValueIterable classes. That's a lot more work than your current solution but well... Another possibly simpler solution if you only care about model instances (not raw data) could be to use a ModelProxy, overridding it's __init__ method to add your processing at this point...
has comment: http://stackoverflow.com/comment/82845303
type: Answer
has comment: http://stackoverflow.com/comment/82821461
downvote count: 0
answers question: http://stackoverflow.com/q/47925776

http://stackoverflow.com/comment/82912641
score: 0
comment on: http://stackoverflow.com/a/47971490
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/161939/discussion-between-schwobaseggl-and-j-c-rocamonde).
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/82689518
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47861837
has text: I believe if we add to the title that it has to be FP, then it is a different question
score: 0

http://stackoverflow.com/q/47905393
has title: Finding first negative values and repacing with last non zero values?
accepted answer: http://stackoverflow.com/a/47905677
score: -1
tagged with: pandas
answer count: 1
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/47905677
tagged with: python
type: AnsweredQuestion
downvote count: 3
tagged with: dataframe
has body: I have a dataframe: hrs running_hrs 0 203.889578 24 1 155.929832 24 2 180.248357 24 3 112.502220 24 4 102.261148 24 5 86.982634 24 6 35.552699 24 7 29.260349 24 8 0.577342 24 9 -23.297091 0 10 -42.875767 0 11 -77.278587 0 I have to search for the first negative value from the hrs column and replace the running_hrs with the last non zero value of the hrs column. Expected output: hrs running_hrs 0 203.889578 24 1 155.929832 24 2 180.248357 24 3 112.502220 24 4 102.261148 24 5 86.982634 24 6 35.552699 24 7 29.260349 24 8 0.577342 24 9 -23.297091 0.577342 10 -42.875767 0 11 -77.278587 0 I tried finding the negative values but all negative values were selected. Can anybody suggest the correct way to do it?
type: Question

http://stackoverflow.com/comment/82780119
comment on: http://stackoverflow.com/a/47905435
has text: **verbose: Integer. 0, 1, or 2. Verbosity mode. 0 = silent, 1 = progress bar, 2 = one line per epoch.** Thanks @ank you rock..
type: AnswerComment
score: 54
type: Comment

http://stackoverflow.com/comment/82799660
has text: page can use JavaScript and then you can't get it with `requests`.
comment on: http://stackoverflow.com/q/47915107
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82951189
has text: @Nick The original regex was meant to only fail a match if there is `work` after `project`. Otherwise there is no sense using a regex, the non-regex solution is also supplied in my answer and that will check any string having `project` and not having `work`.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47990903

http://stackoverflow.com/a/47976898
answers question: http://stackoverflow.com/q/47976804
score: 0
has body: Because your 'k' is a dict which defined in the 'dicts' var with the value is the 10 and 11 list. So you need other for loop to traversal the inner dict or use double index to indicate the return value.
type: Answer

http://stackoverflow.com/comment/82865129
type: AnswerComment
has text: no nee to use `readlines`, it is inefficient.
type: Comment
comment on: http://stackoverflow.com/a/47947378
score: 0

http://stackoverflow.com/comment/82986403
score: 1
has text: I really don't know why it does not work for me. The approach of RyanW does not give me any errors.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48008864

timeit
tag name: timeit
tags question: http://stackoverflow.com/q/47875858
tags question: http://stackoverflow.com/q/47874623
tags question: http://stackoverflow.com/q/47878639
type: Tag
tags question: http://stackoverflow.com/q/47948762
tags question: http://stackoverflow.com/q/47877966

http://stackoverflow.com/q/47861874
downvote count: 0
has answer: http://stackoverflow.com/a/47862289
accepted answer: http://stackoverflow.com/a/47862289
has comment: http://stackoverflow.com/comment/82688983
type: Question
has comment: http://stackoverflow.com/comment/82688981
upvote count: 2
tagged with: poloniex
tagged with: rest
has comment: http://stackoverflow.com/comment/82689048
answer count: 1
tagged with: python
tagged with: cryptography
has body: I'm trying to use Python to access the trading API at coinnest.co.kr, a cryptocurrency exchange. To do this I must follow the documentation found here: https://www.coinnest.co.kr/doc/private.html We get a key pair of public key: asdf-asdf-asdf-asdf and private key: qwer-qewr-qwer-qwer. The request parameters are: "key":"asdf-asdf-asdf-asdf", "nonce":1505209177, "coin":"btc", "id":3 Then the string to be signed will be: key=asdf-asdf-asdf-asdf&nonce=1505209278&coin=btc&id=3 Now we use the md5 hash of qwer-qewr-qwer-qwer as the key and encrypt the above string by sha256 and we get 66b2935f3ba82a4a17074d439adab1043a63df4a177af68fe76a3f4f350ef55d, which will be used as the signature. My current issue is that I am unable to get the same result as the example. I am unsure if their example is accurate. Is the private key "qwer-qewr-qwer-qwer" or "qwer-qwer-qwer-qwer". Is the nonce "1505209177" or "1505209278"? #!/usr/bin/python2.7 import hashlib import hmac secret = 'qwer-qewr-qwer-qwer' message = 'key=asdf-asdf-asdf-asdf&nonce=1505209278&coin=btc&id=3' key = hashlib.md5(secret).hexdigest() print hmac.new(key, message, hashlib.sha256).hexdigest() Using the code above, I obtain a signature of "afdfb1c331670d95c93868948ff769719b28d879ac94589fa44c4d5b8eacab04" versus the expected result of "66b2935f3ba82a4a17074d439adab1043a63df4a177af68fe76a3f4f350ef55d"
favorite count: 0
has comment: http://stackoverflow.com/comment/82690369
has comment: http://stackoverflow.com/comment/82689427
has title: API Signature using MD5 has as key for sha256
type: AnsweredQuestion
score: 2

http://stackoverflow.com/comment/82797171
score: 0
type: Comment
type: QuestionComment
has text: Curious, why would you want a dataframe in that structure? Other than presentation, any analysis would be difficult here. Your original resembles an [entity-attribute-value model](https://en.wikipedia.org/wiki/Entity%E2%80%93attribute%E2%80%93value_model). Ideally, you want to transpose your desired result with *Feature* as columns.
comment on: http://stackoverflow.com/q/47914351

http://stackoverflow.com/q/47979831
favorite count: 0
has title: How to use priority in celery task.apply_async
tagged with: priority-queue
accepted answer: http://stackoverflow.com/a/47980598
tagged with: python
tagged with: rabbitmq
tagged with: celery
type: AnsweredQuestion
upvote count: 10
tagged with: queue
type: Question
has body: I have a test queue in celery and I have defined a task for it: @celery_app.task(queue='test', ignore_result=True) def priority_test(priority): print(priority) which just print the argument.I want to set the priority attribute which is defined here for appy_async. So, I wrote a for loop like this: for i in range(100): priority_test.apply_async((i%10,), queue="test", priority=i%10) I excpected to see some result like this: [2017-12-26 17:21:37,309: WARNING/ForkPoolWorker-1] 10 [2017-12-26 17:21:37,311: WARNING/ForkPoolWorker-1] 10 [2017-12-26 17:21:37,314: WARNING/ForkPoolWorker-1] 10 [2017-12-26 17:21:37,317: WARNING/ForkPoolWorker-1] 9 [2017-12-26 17:21:37,319: WARNING/ForkPoolWorker-1] 9 [2017-12-26 17:21:37,321: WARNING/ForkPoolWorker-1] 9 [2017-12-26 17:21:37,323: WARNING/ForkPoolWorker-1] 8 [2017-12-26 17:21:37,326: WARNING/ForkPoolWorker-1] 8 [2017-12-26 17:21:37,329: WARNING/ForkPoolWorker-1] 8 [2017-12-26 17:21:37,332: WARNING/ForkPoolWorker-1] 7 [2017-12-26 17:21:37,334: WARNING/ForkPoolWorker-1] 7 [2017-12-26 17:21:37,336: WARNING/ForkPoolWorker-1] 7 [2017-12-26 17:21:37,341: WARNING/ForkPoolWorker-1] 6 [2017-12-26 17:21:37,344: WARNING/ForkPoolWorker-1] 6 [2017-12-26 17:21:37,346: WARNING/ForkPoolWorker-1] 6 [2017-12-26 17:21:37,349: WARNING/ForkPoolWorker-1] 5 [2017-12-26 17:21:37,351: WARNING/ForkPoolWorker-1] 5 [2017-12-26 17:21:37,353: WARNING/ForkPoolWorker-1] 5 [2017-12-26 17:21:37,355: WARNING/ForkPoolWorker-1] 4 [2017-12-26 17:21:37,358: WARNING/ForkPoolWorker-1] 4 [2017-12-26 17:21:37,360: WARNING/ForkPoolWorker-1] 4 means execute the same priorities after each other but it executed them in the normal way: [2017-12-26 17:21:37,309: WARNING/ForkPoolWorker-1] 10 [2017-12-26 17:21:37,311: WARNING/ForkPoolWorker-1] 9 [2017-12-26 17:21:37,314: WARNING/ForkPoolWorker-1] 8 [2017-12-26 17:21:37,317: WARNING/ForkPoolWorker-1] 7 [2017-12-26 17:21:37,319: WARNING/ForkPoolWorker-1] 6 [2017-12-26 17:21:37,321: WARNING/ForkPoolWorker-1] 5 [2017-12-26 17:21:37,…
score: 10
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47980598

http://stackoverflow.com/comment/82931489
score: 0
type: Comment
has text: I have edited the question, hope it clarifies my problem.
type: QuestionComment
comment on: http://stackoverflow.com/q/47976506

aiohttp
tags question: http://stackoverflow.com/q/47881270
tags question: http://stackoverflow.com/q/47934212
tags question: http://stackoverflow.com/q/47974846
tag name: aiohttp
tags question: http://stackoverflow.com/q/48007453
type: Tag

http://stackoverflow.com/comment/138723425
has text: can you tell me where to write this file, i tried it on config.py its not working
comment on: http://stackoverflow.com/a/78389922
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47922675
has answer: http://stackoverflow.com/a/47922771
has title: Grouping timestamp strings by day in python
answer count: 4
type: AnsweredQuestion
tagged with: string
score: 1
accepted answer: http://stackoverflow.com/a/47922771
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47922784
tagged with: python
has answer: http://stackoverflow.com/a/47922784
has body: I have a number of files, in date order with the format YYMMDD_hhmmss.txt I want to isolate the files based on their days only. There would be 24 files per day, 1 for each hour... I want to isolate all the files for each day into separate lists. day = 1 list_for_a_day = [] for filename in all_files: if '%s' % (day) in filename: list_for_a_day.append(filename) day += 1 if day &gt; 31: pass This is clearly wrong way of going about this.. If I have 3 days worth of files, each day having 24 files, so thats 72 files... I'd want 3 lists, each containing the relevant files for each day.
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47923264
upvote count: 2
has answer: http://stackoverflow.com/a/47923263
downvote count: 1
tagged with: timestamp

http://stackoverflow.com/comment/82780837
comment on: http://stackoverflow.com/q/47892625
has text: If I understand correctly, you are (algorithmically) searching for a graph that meets certain conditions. Firstly, I'm unclear what you mean by "counterpart" - do you mean that {a1, a2, a3, a4} are all "A"?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47989876
has comment: http://stackoverflow.com/comment/82948548
tagged with: python
downvote count: 1
tagged with: excel
type: AnsweredQuestion
has title: Skipping the null values in python
accepted answer: http://stackoverflow.com/a/47990201
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/82948991
linked to: http://stackoverflow.com/q/9773121
has comment: http://stackoverflow.com/comment/82948913
score: 0
tagged with: xlrd
answer count: 1
has answer: http://stackoverflow.com/a/47990201
has comment: http://stackoverflow.com/comment/82948193
favorite count: 0
has comment: http://stackoverflow.com/comment/82950066
has body: I'm trying to read the data from excel sheet using the code import xlrd input= raw_input("put in the path name for file") book=xlrd.open_workbook(input) print book.nsheets print book.sheet_names() ws=book.sheet_by_index(0) for rows in range(0,14): data= ws.row_values(rows) print data and the answer I'm getting is this [u'', u'', u'', u'', u'RS2 WW10 BKC', u'', u'RS2 WW23.2 BKC', u''] [u'Slno', u'Title', u'Platform Target(W)', u'SoC Target (mW)', u'Platform Power( W)', u'SoC Power (W)', u'Platform Power(W)', u'SoC Power (W)'] [u'', u'', u'', u'', u'', u'', u'', u''] [1.0, u'Display Idle', 4766.0, 80.0, 5013.0, 145.0, 2714.0, 2422.0] [2.0, u'VPB 1080p_30fps', 4999.0, 615.0, 4726.0, 1219.0, 2800.0, 2470.0] [3.0, u'VPB _4k2k-H265', 5888.0, 1231.0, 5244.0, 1619.0, 0.0, 0.0] [4.0, u'Connected standby', 181.0, 17.0, 266.0, 124.0, 176.0, 74.0] [5.0, u'S3', 193.0, 52.0, 132.0, 94.0, 3719.0, 3245.0] [6.0, u'Angry Bird', 6804.0, 2118.0, 7730.0, 3860.0, 2668.0, 2387.0] [7.0, u'Browsing bench', 6209.0, 474.0, 5851.0, 1241.0, 3207.0, 2813.0] [8.0, u'Dash Streaming', 5411.0, 663.0, 5576.0, 1842.0, 0.0, 0.0] [9.0, u'MM14', 5651.0, 973.0, 7504.0, 3024.0, 0.0, 0.0] [10.0, u'Miracast-VPB_Extend', 5072.0, 4007.0, 4196.0, 3081.0, 0.0, 0.0] [11.0, u'Miracast-Idle', 5389.0, 756.0, 0.0, 0.0, 0.0, 0.0] is there any way to skip the [u'', u'', u'', u'', values so that I can save the rest of data in another variable. Answer: the issue was that I was directly fetching the value being unicode it got encoded with it. but if I print the index value then it comes without the u. so, I directly used print data[0], data[1],data[2] Hope this explains

http://stackoverflow.com/comment/82742029
type: Comment
type: QuestionComment
has text: I can't if i'm using digitalocean so that sounds a little weird. Or should I create it locally and when it is finished move it to Digitalocean?
comment on: http://stackoverflow.com/q/47887780
score: 0

http://stackoverflow.com/comment/82684060
has text: Hi, Can you give more details please ? The views and the url definition.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47856591
type: QuestionComment

http://stackoverflow.com/a/51991741
has body: It seems that Pandas 0.23.0 and 0.24.0 use multi values inserts with PyODBC, which prevents fast executemany from helping – a single INSERT ... VALUES ... statement is emitted per chunk. The multi values insert chunks are an improvement over the old slow executemany default, but at least in simple tests the fast executemany method still prevails, not to mention no need for manual chunksize calculations, as is required with multi values inserts. Forcing the old behaviour can be done by monkeypatching, if no configuration option is provided in the future: import pandas.io.sql def insert_statement(self, data, conn): return self.table.insert(), data pandas.io.sql.SQLTable.insert_statement = insert_statement The future is here and at least in the master branch the insert method can be controlled using the keyword argument method= of to_sql(). It defaults to None, which forces the executemany method. Passing method='multi' results in using the multi values insert. It can even be used to implement DBMS specific approaches, such as Postgresql COPY.
type: Answer
has comment: http://stackoverflow.com/comment/94851664
downvote count: 0
score: 7
answers question: http://stackoverflow.com/q/48006551
has comment: http://stackoverflow.com/comment/94851467
upvote count: 7
has comment: http://stackoverflow.com/comment/94851367

http://stackoverflow.com/q/47993317
has comment: http://stackoverflow.com/comment/82955472
has body: first of all, I don't know whether it's only my issue or someone else have it too. my production version of django admin (which I use it in my website) looks different from what I see, when I lunch a project on my personal computer. you can see the difference In two pictures : local version (127.0.0.1:8000) production version (mywebsite) something that I want to mention: My settings.py : STATIC_ROOT = '/home/django/django_project/django_project/static' STATIC_URL = '/static/' About the path: root@myuser:/home/django/django_project/django_project/static# ls admin css fa fonts img js Console log when running admin panel shows that static files related to admin panel like jquery.js does not rendering properly. mywebsite.com/:12 GET https://mywebsite.com/static/admin/js/vendor/jquery/jquery.js net::ERR_ABORTED mywebsite.com/:18 GET https://mywebsite.com/static/admin/js/vendor/xregexp/xregexp.js net::ERR_ABORTED mywebsite.com/:199 GET https://mywebsite.com/static/admin/js/change_form.js net::ERR_ABORTED mywebsite.com/:208 GET https://mywebsite.com/static/admin/js/prepopulate_init.js net::ERR_ABORTED mywebsite.com/:12 GET https://mywebsite.com/static/admin/js/vendor/jquery/jquery.js 404 (Not Found) jquery.init.js:7 Uncaught ReferenceError: jQuery is not defined at jquery.init.js:7 (anonymous) @ jquery.init.js:7 actions.js:4 Uncaught TypeError: Cannot read property 'fn' of undefined at actions.js:4 at actions.js:144 (anonymous) @ actions.js:4 (anonymous) @ actions.js:144 prepopulate.js:2 Uncaught TypeError: Cannot read property 'fn' of undefined at prepopulate.js:2 at prepopulate.js:39 (anonymous) @ prepopulate.js:2 (anonymous) @ prepopulate.js:39 mywebsite.com/:18 GET https://mywebsite.com/static/admin/js/vendor/xregexp/xregexp.js net::ERR_ABORTED mywebsite.com/:200 GET https://mywebsite.com/static/admin/js/change_form.js net::ERR_ABORTED mywebsite.com/:209 GET https://mywebsite.com/static/admin/js/prepopulate_init.js 404 (Not Found) DateTimeShortcuts.js:277 Uncaught Type…
has comment: http://stackoverflow.com/comment/82956183
has answer: http://stackoverflow.com/a/47994350
has comment: http://stackoverflow.com/comment/82956552
accepted answer: http://stackoverflow.com/a/47994350
type: Question
type: AnsweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82956308
has title: why admin panel of django appears different in production version?
has answer: http://stackoverflow.com/a/47993401
has comment: http://stackoverflow.com/comment/82955717
has comment: http://stackoverflow.com/comment/82954818
score: 0
answer count: 2
tagged with: django
possible better answer: http://stackoverflow.com/a/47993401
has comment: http://stackoverflow.com/comment/82955507
tagged with: django-admin
has comment: http://stackoverflow.com/comment/82954911

http://stackoverflow.com/q/47873936
has answer: http://stackoverflow.com/a/49512461
accepted answer: http://stackoverflow.com/a/49512461
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47877879
upvote count: 1
tagged with: datetime
has title: pybind11 zoned datetime conversions
favorite count: 0
has body: I'm currently looking for a solution to handle zoned datetime conversions between python and C++ using pybind11. In pybind11/chrono.h there support for such conversions with naive datetime using the built in python datetime objects and the std library time_point objects; however, there is explicitly no handling for the associated timezones of the python datetime.datetime objects. I'm wondering if any work has been done in pybind11 to more fully support these conversions with consideration for timezones.
tagged with: timezone
possible better answer: http://stackoverflow.com/a/47877879
tagged with: python
tagged with: c++
type: AnsweredQuestion
downvote count: 0
score: 1

http://stackoverflow.com/q/47891866
has answer: http://stackoverflow.com/a/47891881
tagged with: dataframe
tagged with: numpy
possible better answer: http://stackoverflow.com/a/47891898
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47891898
accepted answer: http://stackoverflow.com/a/47891881
type: Question
tagged with: pandas
tagged with: python
has body: if I have a DataFrame of length 3, with 3 columns a b c 1 2 3 4 5 6 7 8 9 Is there a smart way to replace the first 2 rows of column b with NaN?
has title: Remove N first rows of a column from a DataFrame
score: 0
answer count: 2

http://stackoverflow.com/q/47910177
favorite count: 0
has comment: http://stackoverflow.com/comment/82789263
has comment: http://stackoverflow.com/comment/82789203
upvote count: 2
accepted answer: http://stackoverflow.com/a/47917763
tagged with: python
has comment: http://stackoverflow.com/comment/82791974
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82793496
has answer: http://stackoverflow.com/a/47917763
tagged with: bokeh
type: Question
has title: Bar chart showing count of each category month-wise using Bokeh
has body: I have data as shown below: So, from this, I need to display the count in each category year_month_id wise. Since I have 12 months there will be 12 sub-divisions and under each count of ID within each class. Something like the image below is what I am looking for. Now the examples in Bokeh use ColumnDataSource and dictionary mapping, but how do I do this for my dataset. Can someone please help me with this? Below is the expected output in tabular and chart format.
tagged with: bar-chart
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/82690550
type: QuestionComment
comment on: http://stackoverflow.com/q/47862662
has text: DEBUG: l1 url entered is :https://www.justdial.com/Bangalore/AC-Compressor-Dealers/nct-10002128 l1 if entered <GET https://www.justdial.com/Bangalore/AC-Compressor-Dealers-Tecumseh/nct-10002136> DEBUG: Filtered duplicate request: <GET https://www.justdial.com/Bangalore/AC-Compressor-Dealers-Tecumseh/nct-10002136> - no more duplicates will be shown (see DUPEFILTER_DEBUG to show all duplicates) DEBUG: Crawled (200) <GET https://www.justdial.com/Bangalore/AC-Compressor-Dealers-Danfoss/nct-10002131> (referer: https://www.justdial.com/Bangalore/311/11060105_3/AC-Compressor-Dealers_b2c)
type: Comment
score: 0

http://stackoverflow.com/a/48005348
has comment: http://stackoverflow.com/comment/83118772
has body: If your code is based on the example code, you can update the data_json before you store it (I believe that is the best way for that). ... data = pd.read_csv(file_res) data_json = json.loads(data.to_json(orient='records')) for doc in data_json: doc['timestamp'] = timestamp db_cm.remove() db_cm.insert(data_json)
type: AcceptedAnswer
score: 0
has comment: http://stackoverflow.com/comment/83117024
type: Answer
accepted answer of: http://stackoverflow.com/q/48003362
answers question: http://stackoverflow.com/q/48003362

http://stackoverflow.com/a/47891955
has comment: http://stackoverflow.com/comment/82751909
type: Answer
downvote count: 0
score: 7
has comment: http://stackoverflow.com/comment/90251952
answers question: http://stackoverflow.com/q/47891531
has comment: http://stackoverflow.com/comment/82750764
accepted answer of: http://stackoverflow.com/q/47891531
has comment: http://stackoverflow.com/comment/90656157
has comment: http://stackoverflow.com/comment/90251722
has comment: http://stackoverflow.com/comment/82763379
upvote count: 7
type: AcceptedAnswer
has body: The problem is that you are not adding another y-range &mdash; by reassigning a new dictionary to p.extra_y_ranges, you are replacing the old one, entirely. This causes problems when the axis you add expects the "foo1" range to exist, but you've blown it away. The following code works as expected: from bokeh.plotting import output_file, figure, show from bokeh.models import LinearAxis, Range1d x = [1,2,3,4,5] y = [1,2,3,4,5] y2 = [10,9,8,7,6] y3 = [23,24,25,26,27] output_file("twin_axis.html") p = figure(x_range=(0,6), y_range=(0,6)) p.circle(x, y, color="red") p.extra_y_ranges = {"foo1": Range1d(start=0, end=11)} p.circle(x, y2, color="blue", y_range_name="foo1") p.add_layout(LinearAxis(y_range_name="foo1"), 'left') # CHANGES HERE: add to dict, don't replace entire dict p.extra_y_ranges["foo2"] = Range1d(start=21, end=31) p.circle(x, y3, color="green", y_range_name="foo2") p.add_layout(LinearAxis(y_range_name="foo2"), 'right') p.toolbar_location ="above" show(p)
has comment: http://stackoverflow.com/comment/90656861

http://stackoverflow.com/comment/82858275
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47944124
has text: Can ARP packets travel from h1 to h2 and back? If you run `arp` on h1, does it know the hardware address of h2?
score: 1

http://stackoverflow.com/comment/82989974
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48010748
score: 1
has text: Why are you trying to install it? `os` is part of the standard library, so if you have Python, you have `os` already. https://docs.python.org/2/library/os.html

http://stackoverflow.com/a/53317657
type: Answer
answers question: http://stackoverflow.com/q/47880626
upvote count: 2
has body: i've also got this error but solve it by installing pipenv first, try run this first pipenv shell django==2.1 then you should be able to run python3 manage.py runserver
score: 2
downvote count: 0

http://stackoverflow.com/q/47963284
has answer: http://stackoverflow.com/a/47963556
tagged with: python
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/82896191
type: AnsweredQuestion
tagged with: splinter
has comment: http://stackoverflow.com/comment/82895924
has title: Selenium — visiting URL with global variables
downvote count: 2
tagged with: selenium
has body: Suppose I have a config.cfg file with the following: [Info] keyword: Cool Shirt How would I pass keyword into a URL, such that driver.get("http://www.somewebsite.com/checkout?keyword") achieves the same result as driver.get("http://www.somewebsite.com/checkout?keyword=Cool+Shirt")?
type: Question
accepted answer: http://stackoverflow.com/a/47963556
has comment: http://stackoverflow.com/comment/82896526
score: -2
tagged with: python-2.7
upvote count: 0
has comment: http://stackoverflow.com/comment/82896331
answer count: 1
has comment: http://stackoverflow.com/comment/82896022
has comment: http://stackoverflow.com/comment/82895954
has comment: http://stackoverflow.com/comment/82895907
favorite count: 0

http://stackoverflow.com/a/47898377
has body: I am going to strongly disagree with the other comments. They miss the main point of correlation: How much does variable 1 increase or decrease as variable 2 increases or decreases. So in the very first place, order of the ordinal variable must be preserved during factorization/encoding. If you alter the order of variables, correlation will change completely. If you are building a tree-based method, this is a non-issue but for a correlation analysis, special attention must be paid to preservation of order in an ordinal variable. Let me make my argument reproducible. A and B are numeric, C is ordinal categorical in the following table, which is intentionally slightly altered from the one in the question. rawText = StringIO(""" A B C 0 100.1396 1.343921 Medium 1 105.3268 1.786945 Medium 2 200.3766 9.628746 High 3 150.2400 4.225647 Medium-High """) myData = pd.read_csv(rawText, sep = "\s+") Notice: As C moves from Medium to Medium-High to High, both A and B increase monotonically. Hence we should see strong correlations between tuples (C,A) and (C,B). Let's reproduce the two proposed answers: In[226]: myData.assign(C=myData.C.astype('category').cat.codes).corr() Out[226]: A B C A 1.000000 0.986493 -0.438466 B 0.986493 1.000000 -0.579650 C -0.438466 -0.579650 1.000000 Wait... What? Negative correlations? How come? Something is definitely not right. So what is going on? What is going on is that C is factorized according to the alphanumerical sorting of its values. [High, Medium, Medium-High] are assigned [0, 1, 2], therefore the ordering is altered: 0 &lt; 1 &lt; 2 implies High &lt; Medium &lt; Medium-High, which is not true. Hence we accidentally calculated the response of A and B as C goes from High to Medium to Medium-High. The correct answer must preserve ordering, and assign [2, 0, 1] to [High, Medium, Medium-High]. Here is how: In[227]: myData['C'] = myData['C'].astype('category') myData['C'].cat.categories = [2,0,1] myData['C'] = myData['C'].astype('float') myData…
accepted answer of: http://stackoverflow.com/q/47894387
answers question: http://stackoverflow.com/q/47894387
type: AcceptedAnswer
score: 32
has comment: http://stackoverflow.com/comment/93462799
type: Answer
has comment: http://stackoverflow.com/comment/93493416
downvote count: 1
has comment: http://stackoverflow.com/comment/93533757
upvote count: 33
has comment: http://stackoverflow.com/comment/93435157
has comment: http://stackoverflow.com/comment/93583087

http://stackoverflow.com/q/47992013
accepted answer: http://stackoverflow.com/a/47992080
tagged with: rhel
tagged with: linux
type: Question
tagged with: python
score: -1
possible better answer: http://stackoverflow.com/a/47992090
downvote count: 2
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/47992090
has body: I have a config file where i want to replace the line starting with IPADDR=someIP by the value stored within my variable ipaddr my code: for line in fileinput.input(["/etc/sysconfig/network-scripts/ifcfg-ens192"], inplace=True): if line.strip().startswith('IPADDR='): line ="IPADDR="+ipaddr sys.stdout.write(str((line)) + "\n") It does properly set the line i want, but also deletes every other line, but it should only remove blank lines, why isn't it keeping the other existing lines? thx
has answer: http://stackoverflow.com/a/47992080
has title: Why is python removing each line in the given file when replacing one line?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47992368
favorite count: 0

http://stackoverflow.com/comment/112723107
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47926522
has text: +1 I couldn't find any hints in the docs that this has to be disabled for wildcards to work. I am not sure, however, why using a useless function fixes the problem. @Klinky If you could provide some more insight, I would be very grateful.

http://stackoverflow.com/q/47896933
has title: Using Python requests instead of urllib3
answer count: 0
has comment: http://stackoverflow.com/comment/82760822
tagged with: python-requests
has body: I have this code for sending queries to the TinEye API: from PIL import Image from hashlib import sha1 import hmac, io, requests, string, urllib, urllib3 path = '/home/some/file.jpg' limit = 10 TINEYE_API_URL = 'http://api.tineye.com/rest/search/' TINEYE_PUBLIC_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXX' TINEYE_SECRET_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXX' img = Image.open(path) img.thumbnail((300, 300), Image.ANTIALIAS) image_data = io.BytesIO() img.save(image_data, img.format == 'PNG' and 'PNG' or 'JPEG', optimize=1, quality=88) t = int(time.time()) nonce = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(10)) # 8+ random characters boundary = '--%s--' % nonce to_sign = TINEYE_SECRET_KEY + 'POST' + 'multipart/form-data; boundary=' + boundary + 'image_data' + str(t) + nonce + TINEYE_API_URL + 'limit=%s' % limit data = { 'api_key': TINEYE_PUBLIC_KEY, 'date': t, 'nonce': nonce, 'api_sig': hmac.new(TINEYE_SECRET_KEY, to_sign, sha1).hexdigest(), 'limit': limit } r = urllib3.connection_from_url(TINEYE_API_URL).request_encode_body('POST', TINEYE_API_URL+'?'+ urllib.urlencode(data), fields={'image_upload': ('image_data', image_data.getvalue())}, multipart_boundary=boundary, timeout=5) print r.data I usually prefer the Python requests library. But I don't know how to write the urllib3.connection_from_url part with the requests lib. Is that possible? That's what I have, but it's not working: headers = { 'Content-Type': 'multipart/form-data;boundary=' + boundary } r = requests.post(TINEYE_API_URL, data=data, files={ 'image_data': image_data.getvalue() }, headers=headers, timeout=5) print r.text
type: Question
has comment: http://stackoverflow.com/comment/82764149
has comment: http://stackoverflow.com/comment/82771888
has comment: http://stackoverflow.com/comment/82760754
score: 0
has comment: http://stackoverflow.com/comment/82760775
tagged with: urllib3
has comment: http://stackoverflow.com/comment/82764814
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82771306

http://stackoverflow.com/comment/83054841
type: AnswerComment
type: Comment
has text: Thank you very much for the updated answer :). I have been thinking quite a lot on this, and on alternative solutions. I apologise for the delay, but it has taken me several days of thinking :) Please find below my suggestions on your strategy. I am very happy to discuss. Sorry if I have misunderstood some approaches in your strategy.
comment on: http://stackoverflow.com/a/47927676
score: 0

http://stackoverflow.com/q/47927599
has body: Is there a css contains in Selenium? There used to be: a:contains('Log Out') but this no longer works. Is there a css equivlent for: //*[contains(@class, 'dd')] on https://stackoverflow.com/questions How would I write the above as a CSS using contains.
score: 0
tagged with: css-selectors
answer count: 1
has answer: http://stackoverflow.com/a/47929311
duplicate of: http://stackoverflow.com/q/47883572
favorite count: 0
tagged with: xpath
linked to: http://stackoverflow.com/q/47883572
accepted answer: http://stackoverflow.com/a/47929311
upvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: selenium
downvote count: 1
type: Question
has title: Is there a contains class equivalent for css?

http://stackoverflow.com/comment/82962913
type: AnswerComment
has text: can you create a channel so that we can chat?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47981864

http://stackoverflow.com/comment/82819041
comment on: http://stackoverflow.com/a/47925441
score: 0
type: AnswerComment
type: Comment
has text: anyway I do hear you that this is the future so we've got to be disciplined about properly demarcating boundary-access code.

http://stackoverflow.com/q/47961348
answer count: 1
downvote count: 1
has title: Searching for capital letters in string using regular expressions
has comment: http://stackoverflow.com/comment/82892284
has comment: http://stackoverflow.com/comment/82892571
has answer: http://stackoverflow.com/a/47961870
tagged with: python-2.7
type: AnsweredQuestion
upvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/82893047
type: Question
accepted answer: http://stackoverflow.com/a/47961870
has body: I am attempting to locate 3, 4, or 5 consecutive capital letters within a string. They can proceed a '$' or '(' but this is optional. Below is what I have that handles the capital letters but I haven't figure out how to check for letters proceeding a '$' or '('. ex: ($ABC), (ABC), $ABC, ABC &lt;---all should trigger searches = [r'[A-Z]{5}', r'[A-Z]{4}', r'[A-Z]{3}'] correct = '$ABCD' for search in searches: confirmed = re.search(search, correct) if confirmed: return confirmed else: return False Process finished with exit code 0
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82892456
has comment: http://stackoverflow.com/comment/82891826

http://stackoverflow.com/comment/82842383
type: QuestionComment
comment on: http://stackoverflow.com/q/47936531
score: 0
has text: "34.44" is a float literal, so do `'float(a)` to get 34.44. Then if you want to truncate it to an int, `int(float(a))`.
type: Comment

http://stackoverflow.com/comment/82814502
has text: Sure, see my answer if it helps
type: Comment
comment on: http://stackoverflow.com/q/47922801
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82701012
comment on: http://stackoverflow.com/a/47867712
type: AnswerComment
score: 0
type: Comment
has text: Yup works. Removing $push makes it work. Thank you :)

http://stackoverflow.com/a/47999512
has body: Redirect stderr to a file: while read requirement; do conda install --yes $requirement; done &lt; requirements.txt 2&gt;error.log
has comment: http://stackoverflow.com/comment/82995730
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47999477
score: 1
upvote count: 1

http://stackoverflow.com/comment/82856428
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47943056
has text: Yeah, that is probably more readable, at the cost of doing two vectorized multiplies, rather than one (which probably doesn't matter most of the time).
type: AnswerComment

http://stackoverflow.com/q/47900991
has comment: http://stackoverflow.com/comment/82770030
has comment: http://stackoverflow.com/comment/82768561
tagged with: beautifulsoup
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82769775
has comment: http://stackoverflow.com/comment/82768822
tagged with: python-requests
has body: Is it possible to call a Javascript function on a website that I'm web scraping and saving the result of the function? I'm using Requests to establish a connection and saving certain pages that I need and BeautifulSoup to make it readable and accessing certain parts. There is one part that I'm not sure how to call, or even if it's possible: &lt;tr class=TRDark&gt; &lt;td width=100% colspan=3&gt; &lt;a href="" onclick="OpenPayPlan('payplan.asp?app=******');return false;"&gt; Betalingsplan &lt;/a&gt; &lt;/td&gt; &lt;/tr&gt; This function will open a new window and calculate some data that I need. Is this possible to do with Python? I cannot use Selenium or similar programs for this. This must be executed in the terminal and only the terminal.
has answer: http://stackoverflow.com/a/47901058
type: Question
has title: Execute Javascript function on website using Python
has comment: http://stackoverflow.com/comment/82769879
tagged with: python-2.7
score: 0
answer count: 1

http://stackoverflow.com/comment/82799231
type: Comment
comment on: http://stackoverflow.com/a/47915448
score: 0
type: AnswerComment
has text: Nice use of decorator. Hadn't thought of that.

http://stackoverflow.com/a/47888033
score: 0
type: AcceptedAnswer
has body: The steps within the FeatureUnion will be applied in parallel (as you allow as many jobs as you have cores with n_jobs=-1, even actually in parallel). So yes, the CountVectorizer will be applied to the cleaned text. I think the graphics in this blog post make it quite clear. Regarding "Is there a ways to find out?", see my answer here for further questions.
type: Answer
answers question: http://stackoverflow.com/q/47884566
accepted answer of: http://stackoverflow.com/q/47884566

http://stackoverflow.com/q/47983187
tagged with: java
type: Question
upvote count: 2
tagged with: number-theory
answer count: 1
has body: I'm working on a project where I print out numbers up to some limit. I want to distinguish all of the even numbers that are expressed as the sum of 3 and another prime number, then I want to distinguish all of the numbers that are expressed as the sum of 5 and another prime number and so on so forth. To distinguish these things from each other I was thinking of outputting to the console in different colors for each prime. I need to be able to increment the color in a dynamic way so that I'm not writing a specific statement and color for every prime number. Anybody know how I can arrange this? Or equivalently, anyone know a good way of printing out distinguishable items?
has comment: http://stackoverflow.com/comment/82935373
has answer: http://stackoverflow.com/a/47983216
downvote count: 1
has title: Dynamic coloring output to console in java or python
tagged with: python
favorite count: 0
type: UnansweredQuestion
score: 1

http://stackoverflow.com/comment/82803427
has text: list-comp: `[max(i, j) for i, j in zip([1,2], [3,1])]`.
comment on: http://stackoverflow.com/q/47917657
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47959383
tagged with: postgresql
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/47959506
upvote count: 1
answer count: 1
tagged with: docker-compose
has title: run_web.sh not found even though it's there in dir?
has answer: http://stackoverflow.com/a/47959506
tagged with: bash
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82894638
has body: I just installed Docker, after setting up few things like Python, Django, etc., I got an error before my web server gets running. To get web server running I have written a script named run_web.sh. It's also configured in docker-compose.yml that to run web server, run a command exec run_web.sh. When executing that command, it throws an error as below: Starting portalapi_web_1 ... error ERROR: for portalapi_web_1 Cannot start service web: oci runtime error: container_linux.go:265: starting container process caused "exec: \"./run_web.sh\": stat ./run_web.sh: no such file or directory" ERROR: for web Cannot start service web: oci runtime error: container_linux.go:265: starting container process caused "exec: \"./run_web.sh\": stat ./run_web.sh: no such file or directory" ERROR: Encountered errors while bringing up the project. Where run_web.sh file is in my root dir of the project same as docker-compose.yml, it is not able to find it. Don't know what is the issue. Even when I run exec run_web.sh from my root dir, still gets error : Not Found
downvote count: 0
score: 1
favorite count: 0
tagged with: docker

http://stackoverflow.com/q/47908596
answer count: 0
score: 0
upvote count: 1
downvote count: 1
type: Question
duplicate of: http://stackoverflow.com/q/199099
has body: I have a JS function in my HTML template which is assigned to a button tap. When the user clicks the button I'm sending a POST request to my Flask app which should make a redirect to another page. My problem is the redirection doesn't produce a real redirect, I mean my browser doesn't load the next page, while in the console I can see the 301 redirect on the network tab. According to the browser's network tab, the redirection works, but my browser doesn't load the targeted url. This is how I manage the redirection with Flask: @app.route("/signup/", methods = ['GET', 'POST']) def signup(): if request.method == 'POST': session['usess'] = request.json['usess'] #return redirect(url_for('index')) return redirect("/", code=301) if session: return redirect("/", code=301) else: return render_template("signup.html") # already tried simply # return render_template("signup.html") And this is what happens in the log of my Flask app: 127.0.0.1 - - [20/Dec/2017 15:01:33] "POST /signup/ HTTP/1.1" 301 - 127.0.0.1 - - [20/Dec/2017 15:01:33] "GET / HTTP/1.1" 200 - Based on these logs it works, however my browser doesn't want to load the '/' page. And here is the function that is responsible for the session object. The whole process starts here: btnSignUp.addEventListener('click', e =&gt; { // .... $.ajax({ type: "POST", contentType: "application/json", url: "/signup/", data: JSON.stringify({usess: 'session_str'}) }); }); As the log shows the right requests I don't have an idea what can be the problem. I hope somebody with more experience can tell me what should I alter or try.
tagged with: jquery
tagged with: flask
has comment: http://stackoverflow.com/comment/82785039
favorite count: 0
has comment: http://stackoverflow.com/comment/82785307
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/199099
tagged with: python
has title: Forcing the browser to reload/refresh content after redirect
has comment: http://stackoverflow.com/comment/82784626

http://stackoverflow.com/q/47949900
has title: how to render images dynamically in flask by using python and jinja2 html template
tagged with: http://stackoverflow.com/tag/html
tagged with: python
score: 2
upvote count: 2
type: Question
has body: I am using Flask-Python and to create a transport application that I've wanted to make for awhile. I'm having problems with a particular feature which is the standard file uploading. What I want to do is to try to dynamically render an image from my images folder based on a particular model but I seem to be having a problem trying to string interpolate. def createuser(request): file = request.files['aadharimage'] if file.filename == None: flash('No selected file') return redirect(request.url) filename='' if file: filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) users= Enduser(name=request.form["name"],fathername=request.form['fathername'],password=request.form["password"], aadhar_image=filename,email=request.form["email"],address=request.form["address"],type=request.form["type"],location_id=request.form["location_id"],mobile=request.form['mobile'],usertype=request.form['usertype'],lastlogin=request.form['lastlogin'],companyname=request.form['companyname']) sqlsession.add(users) sqlsession .commit() @app.route ('/page/newuser') def pagenewuser(): if session['username']: return render_template("newuser.html", user session['username'],Locations=getlocation().all()) else: flash('Please Login first!!') return main() @app.route('/page/edituser') def pageedituser(): if session['username']: users = getusers() if users.first()== None: return render_template("empty.html", user=session['username']) else: return render_template("edituser.html", user=session['username'], endusers=users.all() ) jinja2 template code &lt;td&gt;{{Values.id}}&lt;/td&gt; &lt;td&gt;{{Values.name}}&lt;/td&gt; &lt;td&gt;{{Values.fathername}}&lt;/td&gt; &lt;td&gt;&lt;img src="{{url_for('static',filename='assets/images/{{Values.aadhar_image}}')}}" alt="sample" width="25" height="24"/&gt;&lt;/td&gt; here {{Values.aadharimage}} is not working.can you solve my problem
tagged with: flask-restful
has answer: http://stackoverflow.com/a/61613752
answer count: 1
downvote count: 0
tagged with: flask
tagged with: flask-sqlalchemy
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/82873856
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47911988
has text: @Arioch'The I got your point. But I don't see how I could use the management app server, since it's embedded and I don't have access to the software code. Is it possible to tell FDB to use dlls inside a specific folder for the server?

http://stackoverflow.com/q/47862336
tagged with: mysql
type: Question
has answer: http://stackoverflow.com/a/47862383
score: 0
answer count: 1
has title: format specifoers not replaced by values in select query passed to mysql from python
type: UnansweredQuestion
tagged with: python
has body: i tried to query sql database from python. when i harcode the values of filter directly in string and pass i as query,query is proper. however when i use format specifiers like "%s" i am facing issues. code is as follows [import tkinter import tkinter.messagebox from tkinter import * import mysql.connector top = tkinter.Tk() #database connecion from mysql.connector import errorcode try: cnx =mysql.connector.connect(host='localhost',user='root',password='1234') cur = cnx.cursor() query="CREATE DATABASE IF NOT EXISTS prj_db" cur.execute(query) cnx =mysql.connector.connect(host='localhost',database='prj_db',user='root',password='1234') except mysql.connector.Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print("Something is wrong with your user name or password") elif err.errno == errorcode.ER_BAD_DB_ERROR: print("no db") else: print(err) else: cur = cnx.cursor() query = ("CREATE TABLE IF NOT EXISTS product_det_2" "(P_id INT(4) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT," "P_name CHAR(20) DEFAULT '' NOT NULL," "Drawing_num CHAR(20) DEFAULT '' NOT NULL," "Price INT(4) UNSIGNED ZEROFILL NOT NULL," "PRIMARY KEY(P_id))") cur.execute(query) query = ("SELECT * FROM product_det_2") cur.execute(query) print(query) for (P_id, P_name, Drawing_num,Price) in cur: print("{}, {}, {},{}".format(P_id, P_name, Drawing_num,Price)) print("*********************************") query = ("SELECT * FROM product_det_2 WHERE P_id=2") print(query) cur.execute(query) for (P_id, P_name, Drawing_num,Price) in cur: print("{}, {}, {},{}".format(P_id, P_name, Drawing_num,Price)) print("*********************************") a="2" query = ("SELECT * FROM product_det_2 WHERE P_id=%s") print(query) cur.execute(query,a) for (P_id, P_name, Drawing_num,Price) in cur: print("{}, {}, {},{}".format(P_id, P_name, Drawing_num,Price)) cnx.commit() top.mainloop()][1] here if i give %d as format specifier and a=2 even then i am facing error. please let me know where i am going wrongenter image descripti…

http://stackoverflow.com/a/51340765
has comment: http://stackoverflow.com/comment/120904856
has comment: http://stackoverflow.com/comment/116996907
has body: Can be done by converting to numpy as follows import torch x = torch.range(1,4) print(x) ===&gt; tensor([ 1., 2., 3., 4.]) nx = x.numpy() np.where(nx == 3)[0][0] ===&gt; 2
score: 0
upvote count: 7
type: Answer
downvote count: 7
answers question: http://stackoverflow.com/q/47863001

http://stackoverflow.com/a/62815170
score: 1
downvote count: 0
has body: Alternatively, you can write mcbShelf.clear(). This is my full code: #Extending the Multiclipboard import shelve, pyperclip, sys mcbShelf = shelve.open('mcb') if len(sys.argv) == 3: # If 3 arguments in the command line -&gt; save or delete the 3rd agrument if sys.argv[1].lower() == 'save': mcbShelf[sys.argv[2]] = pyperclip.paste() elif sys.argv[1].lower()=='delete': del mcbShelf[sys.argv[2]] elif len(sys.argv) == 2: # If 2 argument in the command line -&gt; copy list arguments to clipboard or # List keywords and load content. # delete all list arguments if sys.argv[1].lower() == 'list': pyperclip.copy(str(list(mcbShelf.keys()))) elif sys.argv[1].lower()=='delete': mcbShelf.clear() elif sys.argv[1] in mcbShelf: pyperclip.copy(mcbShelf[sys.argv[1]]) mcbShelf.close()
answers question: http://stackoverflow.com/q/47962161
type: Answer
upvote count: 1

http://stackoverflow.com/a/48009885
has comment: http://stackoverflow.com/comment/82988344
downvote count: 1
has comment: http://stackoverflow.com/comment/82988174
has comment: http://stackoverflow.com/comment/82989233
has body: Without conditional you can't solve the scenario. but you can do this way as you have done in yours. def odd(n): if n%2==0: return n-1 return n print(odd(3)) Hope this helps
score: -1
answers question: http://stackoverflow.com/q/48009830
upvote count: 0
has comment: http://stackoverflow.com/comment/82988212
has comment: http://stackoverflow.com/comment/82989127
has comment: http://stackoverflow.com/comment/82988803
type: Answer
has comment: http://stackoverflow.com/comment/82988312

http://stackoverflow.com/q/47870791
has comment: http://stackoverflow.com/comment/82707454
score: 0
has answer: http://stackoverflow.com/a/47878087
answer count: 1
has comment: http://stackoverflow.com/comment/82707313
favorite count: 0
has comment: http://stackoverflow.com/comment/82706766
tagged with: python
accepted answer: http://stackoverflow.com/a/47878087
type: AnsweredQuestion
has title: How to scrape webpage with scrapy framework?
tagged with: web-scraping
upvote count: 1
tagged with: scrapy
has comment: http://stackoverflow.com/comment/82707044
downvote count: 1
type: Question
has body: I am newbie in webscraping. I have started learning scrapy framework. I covered basic tutorial of scrapy. Now I am trying to scrap this page. As per this tutorial, to get whole html-page contain one should write following code: import scrapy class ClothesSpider(scrapy.Spider): name = "clothes" start_urls = [ 'https://www.chumbak.com/women-apparel/GY1/c/', ] def parse(self, response): filename = 'clothes.html' with open(filename, 'wb') as f: f.write(response.body) This code run fine. But I am not getting expected result. When I open clothes.html, the html-data is not same as when I do inspect from browser. Lot of things are missing in clothes.html. I didn't understand what's going wrong here. Please help me to push forward. Any help would be appreciated. Thanks.
has comment: http://stackoverflow.com/comment/82706830
has comment: http://stackoverflow.com/comment/82715456

http://stackoverflow.com/q/47928724
tagged with: pyqt5
type: Question
score: 0
tagged with: pyqt
answer count: 1
has title: Error in super methods
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/47929916
accepted answer: http://stackoverflow.com/a/47929916
type: AnsweredQuestion
tagged with: pycharm
has body: I try using PyQt5 to connect two ellipses with a line. To do this, slightly changed the class taken with github. Instead of PySide, i use PyQt5. The code is taken from here: https://github.com/PySide/Examples/blob/master/examples/graphicsview/diagramscene/diagramscene.py class Arrow(QGraphicsLineItem): def __init__(self, start_item, end_item, parent=None, scene=None): super(Arrow, self).__init__(parent, scene) self.arrowHead = QPolygonF() self.my_start_item = start_item self.my_end_item = end_item self.setFlag(QGraphicsItem.ItemIsSelectable, True) self.my_color = QtCore.Qt.black self.setPen(QPen(self.my_color, 2, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin)) def set_color(self, color): self.my_color = color def start_item(self): return self.my_start_item def end_item(self): return self.my_end_item def boundingRect(self): extra = (self.pen().width() + 20) / 2.0 p1 = self.line().p1() p2 = self.line().p2() return QtCore.QRectF(p1, QtCore.QSizeF(p2.x() - p1.x(), p2.y() - p1.y())).normalized().adjusted(-extra, -extra, extra, extra) def shape(self): path = super(Arrow, self).shape() path.addPolygon(self.arrowHead) return path def update_position(self): line = QtCore.QLineF(self.mapFromItem(self.my_start_item, 0, 0), self.mapFromItem(self.my_end_item, 0, 0)) self.setLine(line) def paint(self, painter, option, widget=None): if self.my_start_item.collidesWithItem(self.my_end_item): return my_start_item = self.my_start_item my_end_item = self.my_end_item my_color = self.my_color my_pen = self.pen() my_pen.setColor(self.my_color) arrow_size = 20.0 painter.setPen(my_pen) painter.setBrush(self.my_color) center_line = QtCore.QLineF(my_start_item.pos(), my_end_item.pos()) end_polygon = my_end_item.polygon() p1 = end_polygon.at(0) + my_end_item.pos() intersect_point = QtCore.QPointF() for i in end_polygon: p2 = i + my_end_item.pos() poly_line = QtCore.QLineF(p1, p2) intersect_type, intersect_point = poly_line.intersect(center_line) if intersect_type == QtCore.QLine…

http://stackoverflow.com/comment/82795877
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47893712
has text: I ran the code I posted in a jupter notebook. For some reason the except-block wasn't called even though it should have been. When I ran the code in a normal ipython terminal session, everything worked as expected and the except-block was called where I could raise the exception with the message.

http://stackoverflow.com/a/47893499
type: Answer
has body: Actually fig.tight_layout(rect=[0.1,0.1,0.9, 0.95]) does kind of the inverse of what you want. It will make the region where all the figure's content is placed fit into the rectangle given, effectively producing even more space. In theory you could of course do something in the other direction, using a rectangle with negative coordinates and ones bigger than 1, fig.tight_layout(rect=[-0.055,0,1.05, 1]). But there is no good strategy to find out the values that need to be used. Plus (what will become apparent later in this text) you would still need to change the size of the figure if a specific aspect needs to be used. Now to a solution: I don't know why setting the axes tight to the figure edge would be a "silly hack". It is precisely one option you have to get no spacings around the subplot - which is what you want. In the usual case, fig.subplots_adjust(0,0,1,1) would be enough to do that. However, since here you have a specific aspect ratio set on the axes, you would also need to adjust the figure size to the axes box. This could be done as fig.subplots_adjust(0,0,1,1) w,h = fig.get_size_inches() x1,x2 = ax.get_xlim() y1,y2 = ax.get_ylim() fig.set_size_inches(w, ax.get_aspect()*(y2-y1)/(x2-x1)*w) Alternatively, instead of subplots_adjust one may use tight_layout(pad=0) and still set the figure size accordingly, ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) fig.tight_layout(pad=0) w,h = fig.get_size_inches() x1,x2 = ax.get_xlim() y1,y2 = ax.get_ylim() fig.set_size_inches(w, ax.get_aspect()*(y2-y1)/(x2-x1)*w) Of course if you only care about the exported figure, using some of the savefig options is an easier solution, the other answer already shows the easiest one of them.
downvote count: 0
score: 7
has comment: http://stackoverflow.com/comment/82753933
upvote count: 7
answers question: http://stackoverflow.com/q/47891830

http://stackoverflow.com/comment/82903325
has text: If changing from `localhost` to `127.0.0.1` fixes it, it sounds like a DNS problem. What does `dig localhost` show?
score: 0
comment on: http://stackoverflow.com/q/47966461
type: QuestionComment
type: Comment

http://stackoverflow.com/a/47933469
has comment: http://stackoverflow.com/comment/82837536
has comment: http://stackoverflow.com/comment/82837432
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/82837265
has body: df_merged[col].shift(1)== 1.0 you compare two different types df_merged[col].shift(1) return a dataframe. If you want to get first value of that column you could use iloc. df_merged[col].iloc[0] == 1.0 a x 0 0 1 1 2 2 3 3 4 4 a.x.shift(1) x 0 NaN 1 1 2 2 3 3 4 4 a.x.iloc[0] 1
answers question: http://stackoverflow.com/q/47933158
score: 2
downvote count: 0

http://stackoverflow.com/a/47985883
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47985869
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47985869
has body: you can use urljoin: from urlparse import urljoin hotel_url = urljoin("https://www.booking.com", a['href'])
type: AcceptedAnswer

http://stackoverflow.com/q/47913203
has title: Python: Ways to monitor program is running
tagged with: python
tagged with: stateless
answer count: 0
type: Question
tagged with: monitoring
has comment: http://stackoverflow.com/comment/82795844
score: 0
has comment: http://stackoverflow.com/comment/82794338
has body: Background info: I have built a program main.py, that is built to perform work at a stateless level (meaning if something fails, it will get requeued/database etc separately)... Problem: I am trying to figure out how to monitor this main.py program from my linux instance. Main.py runs and threads out multiple workers, however I want to monitor and ensure the system is still healthy to 'perform work'... How can you do this from a single script level and determine that it is no longer working? My Ideas: Create a status notification to syslog stating it is healthy... and trigger on no longer receives? (if that is possible) Linux maybe provides a way to monitor that system is healthy? last one is creating a TCP/Socket level query mechanism to check for status... I hope i'm describing the problem right... I'm trying to ensure program is not only running ,but processing and can process[?]
type: UnansweredQuestion

http://stackoverflow.com/comment/82752197
comment on: http://stackoverflow.com/q/47890820
score: 0
type: Comment
type: QuestionComment
has text: you are the best

django-rest-auth
tag name: django-rest-auth
type: Tag
tags question: http://stackoverflow.com/q/47929991

http://stackoverflow.com/comment/82837884
comment on: http://stackoverflow.com/q/47934252
score: 0
type: Comment
has text: Matrix multiplication between two 1x1000 matrices doesn't make sense. Having the same dimensions isn't the criterion for a matrix multiplication to be valid.
type: QuestionComment

http://stackoverflow.com/q/47973609
has comment: http://stackoverflow.com/comment/82916969
tagged with: scipy
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47973659
has answer: http://stackoverflow.com/a/47973808
has answer: http://stackoverflow.com/a/47973727
has answer: http://stackoverflow.com/a/47973737
answer count: 6
tagged with: python-2.7
has answer: http://stackoverflow.com/a/48074525
has answer: http://stackoverflow.com/a/47973851
upvote count: 0
favorite count: 0
has body: how can I convert a list containing apostrophe and numbers to numbers (e.g ['2,2.4,3'] to [2,2.4,3]) in Python? I've tried this: z = [float(x) if type(x) is str else None for x in ['1 2 3 4']]
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82916784
score: -3
has title: how can I convert a list containing apostrophe and numbers to numbers (e.g ['2,2.4,3'] to [2,2.4,3]) in python
tagged with: python
has comment: http://stackoverflow.com/comment/82916805
has comment: http://stackoverflow.com/comment/82917083
downvote count: 3

http://stackoverflow.com/q/47984939
tagged with: dataformat
downvote count: 0
score: 1
has body: in the 3 section of lecture, i encounrtered a problem that I could not upload any finance data from yahoo, so I use pandas datareader to uploaded a stock info for microsoft here is that code: MS= data.DataReader(name = "MSFT", data_source = "yahoo", start = "2007-07- 10", end = "2008-12-10") MS.head() I got this : Open High Low Close Adj Close Volume Date 2007-07-10 29.700001 29.990000 29.180000 29.330000 22.709541 66013500 2007-07-11 29.240000 29.650000 29.209999 29.490000 22.833429 48017000 2007-07-12 29.559999 30.110001 29.440001 30.070000 23.282511 54302400 2007-07-13 29.940001 30.020000 29.660000 29.820000 23.088938 42173000 2007-07-16 29.760000 30.240000 29.719999 30.030001 23.251535 4802320 I got a date frame and with a date column as a index when I plot it with .plot() it works but how can i use plt.plot() to plot the pandas time data or how can i convert the format of pandas time data into readable format for matplotlib? thanks
type: Question
tagged with: matplotlib
has title: how to convert pandas time data into the format that can be processed by matplotlib
tagged with: pandas
upvote count: 1
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: datetime
tagged with: python
has answer: http://stackoverflow.com/a/47984997

http://stackoverflow.com/comment/82687517
type: Comment
type: QuestionComment
has text: I've edited my question. HealthExamination works and TechnicalExamination doesn't.
comment on: http://stackoverflow.com/q/47860840
score: 0

http://stackoverflow.com/a/47917013
type: Answer
has comment: http://stackoverflow.com/comment/82805709
answers question: http://stackoverflow.com/q/47914320
score: 3
downvote count: 0
has body: The operation you're doing: arr -= arr[3] used to be undefined behavior in NumPy. It only became defined very recently, in NumPy 1.13.0, released June 7th this year. The new, defined behavior always acts as if it makes copies of all inputs, although it tries to avoid actually making copies when it can detect that it doesn't need to. It looks like Numba does not currently attempt to mimic the new behavior, either because of how new it is, or because of Numba-specific concerns.
type: AcceptedAnswer
upvote count: 3
accepted answer of: http://stackoverflow.com/q/47914320

http://stackoverflow.com/comment/82848985
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47939843
type: Comment
has text: Thanks Willem, that's the answer... My bad!

http://stackoverflow.com/q/47985578
has body: I am fairly new to Python and in my application I am using Neomodel to load and retrieve graph data from Neo4j database. In one of my routes I have the following function: @api_mod.route('/users') def get_users(): users = User.nodes #Returns a NodeSet list_of_users = list(users) #Converts the NodeSet object to a list return json.dumps(dict(users = [user for user in list_of_users])) My User class is defined as following: class User(StructuredNode): user_id = StringProperty(unique_index=True, required=True) logged_in = RelationshipTo('Environment', 'LOGGED_IN', model=LoginAction) launched = RelationshipTo('Application', 'LAUNCHED', model=LaunchedAction) entered = RelationshipTo('Application', 'ENTERED', model=EnteredAction) accessed = RelationshipTo('Application', 'ACCESSED', model=AccessedAction) exited = RelationshipTo('Application', 'EXITED', model=ExitedAction) logged_out = RelationshipTo('Environment', 'LOGGED_OUT', model=LogoutAction) timed_out = RelationshipTo('Environment', 'TIME_OUT', model=TimeoutAction) def toJSON(self): return dict(user_id = self.user_id) My expectation is that my /users route will return a JSON object with all the users in the database. I understand that NodeSet object can't be serializable to a JSON object, hence my attempt to convert it to a list. But now when I run I get the following error: "TypeError: Object of type 'User' is not JSON serializable" and here is the whole stack trace: Traceback (most recent call last): File "/Users/mdebarros/.virtualenvs/useractivitylogs/lib/python3.6/site-packages/flask/app.py", line 1997, in call return self.wsgi_app(environ, start_response) File "/Users/mdebarros/.virtualenvs/useractivitylogs/lib/python3.6/site-packages/flask/app.py", line 1985, in wsgi_app response = self.handle_exception(e) File "/Users/mdebarros/.virtualenvs/useractivitylogs/lib/python3.6/site-packages/flask/app.py", line 1540, in handle_exception reraise(exc_type, exc_value, tb) File "/Users/mdebarros/.virtualenvs/useractivitylo…
upvote count: 3
accepted answer: http://stackoverflow.com/a/47986731
tagged with: flask-restful
type: Question
tagged with: neomodel
tagged with: flask
has title: Python NeoModel how to return query result as JSON Object
answer count: 1
downvote count: 0
tagged with: neo4j
has answer: http://stackoverflow.com/a/47986731
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 3

http://stackoverflow.com/comment/91552574
type: Comment
score: 2
has text: Tried that, but pip is still missing
comment on: http://stackoverflow.com/a/47997410
type: AnswerComment

http://stackoverflow.com/a/47930313
has comment: http://stackoverflow.com/comment/82830052
has comment: http://stackoverflow.com/comment/82830065
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47930267
has body: Convert the Value column to a list of lists, and reload it into a new dataframe. Afterwards, call plot. Something like this - df = pd.DataFrame(test.Value.tolist(), index=test.ID) df 0 1 2 3 ID seq_107 5825.6951 5972.8073 NaN NaN seq_1101 4287.7417 4422.8254 NaN NaN seq_1626_unamb 3724.3895 NaN NaN NaN seq_2888 5219.3359 5365.4089 NaN NaN seq_3535 3396.1716 3446.1970 5655.896546 NaN seq_4077 4551.9108 4754.0073 4565.987654 5668.999998 seq_418 3716.3642 3796.4124 NaN NaN seq_504 4556.9209 4631.9590 NaN NaN seq_6162 5531.5032 5645.5774 NaN NaN seq_6946 5179.3118 5364.4209 NaN NaN seq_7009 6236.9764 6367.0500 NaN NaN seq_9143_unamb 4631.9590 NaN NaN NaN df.plot()
answers question: http://stackoverflow.com/q/47930267
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/82711313
has text: I've run into this issue when I had the `requests` module installed via `pip` but **also** via `apt`. In my case the solution was to remove both of them and then re-install the `pip` version.
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47872964

http://stackoverflow.com/q/47919669
tagged with: notepad++
has comment: http://stackoverflow.com/comment/82806865
type: Question
has body: I'm just new in python but have 2 years in VBA programming. The editor (IDE) I'm using the notepad++ and just wondering about the vertical lines beside the numbers oriented vertically as you can see in the attached image. The lines that I'm referring were encircled in red. Can you please let me know what is the main purpose of these lines.
answer count: 1
has comment: http://stackoverflow.com/comment/82807902
score: 0
tagged with: python
has title: Purpose of vertical lines beside number orriented vertically in Python
has comment: http://stackoverflow.com/comment/82940190
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47919704
has comment: http://stackoverflow.com/comment/82939700

http://stackoverflow.com/q/47923412
tagged with: apache
has answer: http://stackoverflow.com/a/47926555
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/82815458
has body: I installed mod_wsgi, and loaded it in apache. This is my apache virtual host: ServerName mysite.localhost ServerAlias mysite.localhost Alias /static /var/www/mysite/static Require all granted Require all granted WSGIDaemonProcess mysite WSGIProcessGroup mysite WSGIScriptAlias / /var/www/mysite/mysite/wsgi.py When I go to mysite.localhost I get: ImportError: No module named django.core.wsgi I try to run it from python shell and everything goes well. I have django installed globally, not just in the virtualenv. Thanks.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82820634
has comment: http://stackoverflow.com/comment/82814444
type: Question
accepted answer: http://stackoverflow.com/a/47926555
tagged with: django
tagged with: python
answer count: 1
score: 0
has title: Apache Django app: ImportError: No module named django.core.wsgi
has comment: http://stackoverflow.com/comment/82815039

http://stackoverflow.com/q/47946551
duplicate of: http://stackoverflow.com/q/2077870
has comment: http://stackoverflow.com/comment/82865297
tagged with: http://stackoverflow.com/tag/r
linked to: http://stackoverflow.com/q/17723321
has comment: http://stackoverflow.com/comment/82863385
favorite count: 0
has title: Importing .NET DLL to Python or R
has body: I have a .NET DLL and a sample code in Matlab, which uses this DLL and works. The Matlab code which imports the DLL is function ReaderLib = ReaderInitialize(dllPath) netObj = NET.addAssembly(dllPath); ReaderLib = System.Activator.CreateInstance(netObj.AssemblyHandle.GetType('lib.ReaderDotNet')); end This function returns the object which exposes all functions of the DLL. I need to use this DLL in existing Python and/or R code, but I was not able to make it work. In Python I tried import ctypes DllObj = ctypes.WinDLL (dllPath) In R I tried DllObj &lt;- dyn.load(dllPath) In both cases I obtain more or less empty objects, so I assume I am not doing it right. What is the correct way to import this DLL in Python and/or R?
answer count: 0
has comment: http://stackoverflow.com/comment/82863795
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/2077870
has comment: http://stackoverflow.com/comment/82877428
upvote count: 1
tagged with: python
tagged with: dllimport
tagged with: matlab
score: 1
has comment: http://stackoverflow.com/comment/82869689
type: Question
tagged with: dll
has comment: http://stackoverflow.com/comment/82863846
downvote count: 0

http://stackoverflow.com/a/47975738
has body: As you said, a large chunk of python is written in C but these are not included with the distribution. So you can not read the source from your IDE. These are mostly compiled sources which means only the bytecode is used by the Interpreter. Not all the functions are written in C, most of it is actually written in pure python. One way to view source is through terminal by using ipython. In [10]: import string In [11]: string.lower?? Signature: string.lower(s) Source: def lower(s): """lower(s) -&gt; string Return a copy of the string s converted to lowercase. """ return s.lower() File: /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/string.py Type: function In [12]: import os In [13]: os.system?? Docstring: system(command) -&gt; exit_status Execute the command (a string) in a subshell. Type: builtin_function_or_method Alternatively you can find what you want, by using inspect.getsource(). import inspect import os print (inspect.getsource(os)) # You should see the source code here As in the above examples, this doesn't work for some built in functions. To check what is written in C, you should use the other way which is to check this link which is the official repository for the python interpreter. Most of the object types are listed in the cpython/Objects folder. For instance, this is the implementation of list object in C, and for the builtin modules refer this one. I believe this is what you want. Do comment if you need help.
type: Answer
upvote count: 18
answers question: http://stackoverflow.com/q/47900611
type: AcceptedAnswer
score: 18
accepted answer of: http://stackoverflow.com/q/47900611
downvote count: 0

3d
tags question: http://stackoverflow.com/q/47875231
type: Tag
tags question: http://stackoverflow.com/q/47913108
tags question: http://stackoverflow.com/q/47900969
tags question: http://stackoverflow.com/q/47867954
tags question: http://stackoverflow.com/q/47932955
tags question: http://stackoverflow.com/q/47879765
tag name: 3d
tags question: http://stackoverflow.com/q/47973144
tags question: http://stackoverflow.com/q/47899253
tags question: http://stackoverflow.com/q/47868134

http://stackoverflow.com/comment/82847380
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47938834
has text: @RomanPerekhrest key2 should be skipped because the value is key2 and not key1 or key3. I know that sounds ambiguous, but I am only interested in the "value" tag values of key1 and key2.
score: 0

http://stackoverflow.com/a/47905870
has body: Another solution: code: from __future__ import division, print_function, with_statement my_list =["abc 123","acd 234","NSW = 500", "stuff","morestuff"] for index in xrange(len(my_list)): if "NSW" in my_list[index]: my_list[index] = "NSW = 0" print (my_list) output: ['abc 123', 'acd 234', 'NSW = 0', 'stuff', 'morestuff'] or you can use list comprehension for purpose as follows: code: my_list =["abc 123","acd 234","NSW = 500", "stuff","morestuff"] print ["NSW = 0" if "NSW" in _ else _ for _ in my_list] output: ['abc 123', 'acd 234', 'NSW = 0', 'stuff', 'morestuff']
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47905783
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/82819786
type: QuestionComment
has text: Have you tried anything? If so, can you show us and describe how it failed?
score: 1
comment on: http://stackoverflow.com/q/47925894
type: Comment

http://stackoverflow.com/comment/82951531
has text: Thanks a lot ! I had never seen this `__new__` method. I'll try both methods a see which is best suited. I think your factory solution is the most pythonic and natural solution.
type: AnswerComment
comment on: http://stackoverflow.com/a/47984632
score: 0
type: Comment

http://stackoverflow.com/a/47918273
answers question: http://stackoverflow.com/q/47901979
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47901979
type: Answer
score: 1
upvote count: 1
has body: The Doc2Vec algorithm makes use of randomness in both initialization and training, and efficient multi-threaded training introduces more randomness because the batches across mutliple threads won't necessarily be trained-against in the same order from run-to-run. If the model is training well, the jitter in results from run-to-run shouldn't be large, and the quality of downstream assessments shouldn't vary much. If the quality-of-results does vary a lot, there are likely other problems with the application of the algorithm to your data or training. Separately: you almost certainly don't want to be using the non-default dm_concat=1 mode. It results in a much larger, much slower-to-train model, and there aren't any clear public examples of it being worth that extra cost. (I'd only try it if I had a strong baseline result from more simple modes, and lots and lots of data and time.)

http://stackoverflow.com/a/47958067
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/82885414
upvote count: 2
answers question: http://stackoverflow.com/q/47958051
has body: In if A or B, B is only evaluated if A is false. This concept is called short circuiting, and you can read a little about it here. The idea is that you go from left to right until a result is determined. Once that's the case, you stop.
accepted answer of: http://stackoverflow.com/q/47958051
score: 2

http://stackoverflow.com/comment/82984200
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48007678
has text: @RičardsLūciņš: If you really want to ask that question you should make it a separate question, with a full explanation. Don't piggy-back on your question here.

http://stackoverflow.com/q/47972525
upvote count: 1
possible better answer: http://stackoverflow.com/a/47972682
favorite count: 0
has comment: http://stackoverflow.com/comment/82914898
has comment: http://stackoverflow.com/comment/82914950
tagged with: pandas
tagged with: python
has title: Elementwise logical operation on character with pandas data frame
tagged with: jupyter-notebook
downvote count: 0
accepted answer: http://stackoverflow.com/a/47972692
has comment: http://stackoverflow.com/comment/82914965
has answer: http://stackoverflow.com/a/47972682
has body: I am working with a data frame where each entry is a character from A-E representing different intensity level For example: data frame df= 1 2 3 0 C C A 1 0 D B 2 E 0 A I want to threshold the data at different intensity level from A to E into a binary matrix. Thus, I want to perform an element-wise comparison. If it's a number, it's simply: df &gt; 0 However, when I tried with a character, df &gt; 'A' , an error is thrown "TypeError: Could not compare ['A'] with block values" I can of course do a 'for' loop but is there any one line, elegant solution to perform element-wise logical operation with character using data frame in pandas?
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/47972692
tagged with: dataframe
has comment: http://stackoverflow.com/comment/82914758
type: Question
answer count: 2

http://stackoverflow.com/comment/82712704
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47873652
has text: Short answer, you created `df` by subsetting some other dataframe, assigning a view. Just do `df = df.copy()` and then it should be fine.

http://stackoverflow.com/a/47910493
downvote count: 0
has comment: http://stackoverflow.com/comment/82820951
has body: The task of QGridLayout is to create that type of structure, for this you must use the function: void QGridLayout::addWidget(QWidget * widget, int fromRow, int fromColumn, int rowSpan, int columnSpan, Qt::Alignment alignment = 0) This is an overloaded function. This version adds the given widget to the cell grid, spanning multiple rows/columns. The cell will start at fromRow, fromColumn spanning rowSpan rows and columnSpan columns. The widget will have the given alignment. If rowSpan and/or columnSpan is -1, then the widget will extend to the bottom and/or right edge, respectively. Example: import sys from PyQt4.QtCore import * from PyQt4.QtGui import * app = QApplication(sys.argv) w = QWidget() glay = QGridLayout(w) glay.addWidget(QLabel("1"), 0, 0) glay.addWidget(QLabel("2"), 0, 1, 1, 3) glay.addWidget(QLabel("3"), 1, 0, 1, 2) glay.addWidget(QLabel("4"), 1, 2, 1, 2) qsrand(QTime.currentTime().msec()) for label in w.findChildren(QLabel): color = QColor(qrand() % 256, qrand() % 256, qrand() % 256) label.setStyleSheet('.QLabel{{background: rgb({}, {}, {});}}'.format(color.red(), color.green(), color.blue())) w.show() sys.exit(app.exec_())
type: Answer
answers question: http://stackoverflow.com/q/47910192
has comment: http://stackoverflow.com/comment/82806035
has comment: http://stackoverflow.com/comment/82816803
score: 21
upvote count: 21
accepted answer of: http://stackoverflow.com/q/47910192
has comment: http://stackoverflow.com/comment/82820854
type: AcceptedAnswer

http://stackoverflow.com/comment/82922392
type: QuestionComment
has text: @Barmar I have already done that and now want only the list of ips from the dict. In response i posted there are ips followed by counts after '\t' element. 188.68.184.188\t60777\r\n10.178.156.37.
score: 0
comment on: http://stackoverflow.com/q/47976077
type: Comment

http://stackoverflow.com/comment/106243689
type: Comment
comment on: http://stackoverflow.com/q/47927940
has text: Which _documentation then says that "A file object shall be unregistered prior to being closed"_?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82836369
has text: You're awesome, that was driving me insane. Thank you so much for your help.
comment on: http://stackoverflow.com/a/47875987
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/47918306
type: Question
possible better answer: http://stackoverflow.com/a/47918658
has answer: http://stackoverflow.com/a/47945073
has answer: http://stackoverflow.com/a/47918658
has answer: http://stackoverflow.com/a/47918478
has comment: http://stackoverflow.com/comment/82807613
accepted answer: http://stackoverflow.com/a/47918478
upvote count: 1
downvote count: 1
favorite count: 0
tagged with: beautifulsoup
score: 0
answer count: 3
tagged with: http://stackoverflow.com/tag/csv
has title: Incorrect fomat (wrong number of columns) after writing to csv files
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82855239
tagged with: screen-scraping
has body: My intention is to get the full review of all the profiles along with title of the review, user name, location of the user and the time of posting from the reliance jio reviews web pages of the website and store it in a CSV file. The website I want to crawl is http://www.mouthshut.com/mobile-operators/Reliance-Jio-reviews-925812061 When I tried storing the scraped data of first two pages in a CSV file, I got the below output. My problem is the output in each line generate more columns than desired. One sentence is parsed into many cells. My code : from bs4 import BeautifulSoup from urllib.request import urlopen as uReq from selenium import webdriver;import time from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.desired_capabilities import DesiredCapabilities import csv firefox_capabilities = DesiredCapabilities.FIREFOX firefox_capabilities['marionette'] = True firefox_capabilities['binary'] = '/etc/firefox' driver = webdriver.Firefox(capabilities=firefox_capabilities) url = "http://www.mouthshut.com/mobile-operators/Reliance-Jio-reviews-925812061" driver.get(url) wait = WebDriverWait(driver, 10) soup=BeautifulSoup(driver.page_source,"lxml") for items1 in wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, ".review-article"))): link1 = items1.find_element_by_css_selector(".reviewdata a") link1.click() time.sleep(2) csv = open('index.csv','w') column = "Name,Location,Review_data,Review_title,Review_data\n" csv.write(column) soup1 = BeautifulSoup(driver.page_source,"lxml") for item1 in soup1.select(".review-article"): name1 = item1.select("p a")[0].text location1 = item1.select("p")[1].text review_date1 = item1.select("small")[0].text review_title1 = item1.select("strong a[id^=ctl00_ctl00_ContentPlaceHolderFooter_ContentPlaceHolderBody_rptreviews]")[0].text review_data1 = ' '.join([' '.join(items1.text.split()) fo…
tagged with: selenium

google-app-engine
tags question: http://stackoverflow.com/q/47987587
tags question: http://stackoverflow.com/q/47948199
tag name: google-app-engine
tags question: http://stackoverflow.com/q/47908757
type: Tag
tags question: http://stackoverflow.com/q/47997109
tags question: http://stackoverflow.com/q/47945152
tags question: http://stackoverflow.com/q/48008086
tags question: http://stackoverflow.com/q/47870231
tags question: http://stackoverflow.com/q/47859865
tags question: http://stackoverflow.com/q/47991422
tags question: http://stackoverflow.com/q/47958066
tags question: http://stackoverflow.com/q/47954574
tags question: http://stackoverflow.com/q/48014071
tags question: http://stackoverflow.com/q/47865500
tags question: http://stackoverflow.com/q/47972522
tags question: http://stackoverflow.com/q/47911749
tags question: http://stackoverflow.com/q/47908968
tags question: http://stackoverflow.com/q/47956352
tags question: http://stackoverflow.com/q/48006154
tags question: http://stackoverflow.com/q/47893008

http://stackoverflow.com/a/47883727
has body: If I understand your question correctly you don't need regular expressions, but just use: dict(pd.value_counts(df["name"].str[-1])) Explanation: df["name"].str[-1] extracts the last character, pd.value_counts counts unique value, finally dict converts the object to a dictionary
answers question: http://stackoverflow.com/q/47883436
type: Answer
has comment: http://stackoverflow.com/comment/92705473
score: 0
has comment: http://stackoverflow.com/comment/82766297

http://stackoverflow.com/comment/82988621
has text: @LuisMuñoz Good point. I see you already have that in your answer so I'll leave it out of mine. I was trying to give a more general answer for how to navigate through elements instead of doing the whole homework problem.
type: AnswerComment
comment on: http://stackoverflow.com/a/48010031
score: 0
type: Comment

http://stackoverflow.com/comment/82997664
comment on: http://stackoverflow.com/a/48013601
type: AnswerComment
score: 1
type: Comment
has text: I think this may have been downvoted before because `var1` and `varl` have nothing to do with each other in the original code. OP's code should work as posted.

http://stackoverflow.com/comment/82987568
type: Comment
type: QuestionComment
has text: you have this line `url 'music:create_song'` in the navbar for right song info.
score: 0
comment on: http://stackoverflow.com/q/48007916

http://stackoverflow.com/q/47948967
upvote count: 2
has body: I have a pandas DataFrame whereby I'm using pandas.DataFrame.apply(). dict1 = {'file': ['filename2', 'filename2', 'filename3', 'filename4', 'filename4', 'filename3'], 'amount': [3, 4, 5, 1, 2, 1], 'front': [21889611, 36357723, 196312, 11, 42, 1992], 'back':[21973805, 36403870, 277500, 19, 120, 3210], 'type':['A', 'A', 'A', 'B', 'B', 'C']} df1 = pd.DataFrame(dict1) print(df1) file amount front back type 0 filename2 3 21889611 21973805 A 1 filename2 4 36357723 36403870 A 2 filename3 5 196312 277500 A 3 filename4 1 11 19 B 4 filename4 2 42 120 B 5 filename3 1 1992 3210 C My task is to take N random draws between columns front and back, whereby N is equal to the value in column amount: def my_func(x): return np.random.choice(np.arange(x.front, x.back+1), x.amount).tolist() I would only like to apply this function on rows whereby type is equal to A. If I didn't have the conditional, I would use pd.DataFrame.apply() as follows: df1["new_column"] = df1.apply(my_func, axis=1) To apply this only if type==A, I could do something like if set(['A']).issubset(df1['type']): df1["new_column"] = df1.apply(my_func, axis=1) However, this doesn't actually work---my_func is applied to all functions. (1) Why doesn't the above work as expected? (2) How would one efficiently only apply my_func to the rows which satisfy type==A? In the example above, this would be for the first three rows, and the next three rows would be NA
has answer: http://stackoverflow.com/a/47948991
type: Question
type: AnsweredQuestion
tagged with: conditional-statements
tagged with: dataframe
tagged with: apply
score: 2
accepted answer: http://stackoverflow.com/a/47948991
downvote count: 0
answer count: 1
favorite count: 0
has title: How to conditionally use `pandas.DataFrame.apply` based on values in a certain column?
tagged with: pandas
tagged with: python

http://stackoverflow.com/q/47983367
upvote count: 10
type: Question
has comment: http://stackoverflow.com/comment/83242631
tagged with: command-line-interface
tagged with: python-click
has comment: http://stackoverflow.com/comment/83242649
answer count: 1
has body: I have a tool with commands: step1, step2 and step3. I can chain them by calling: $ tool step1 step2 step3 I would like to have an alias named all to run all the steps by calling: $ tool all I have found a solution that works but it doesn't seem right for me because of calling cli() twice under the hood: @click.group(chain=True) def cli(): print('cli() has been called') ... @cli.command() def all(): cli(args=['step1', 'step2', 'step3']) How else could this be done without the side effect of calling cli() twice?
has answer: http://stackoverflow.com/a/47985653
has comment: http://stackoverflow.com/comment/83113719
favorite count: 0
type: UnansweredQuestion
has title: Alias for a chain of commands
has comment: http://stackoverflow.com/comment/83245326
tagged with: python
score: 7
downvote count: 3

http://stackoverflow.com/a/47958081
upvote count: 1
has body: As for the time difference, a look at the bytecode of the two functions provides some hints. Comparison between nested() and fake_nested() shows that whereas fake_nested just loads already defined global function inner(), nested has to create this function. There will be some overhead here whereas the other operations will be relatively fast. &gt;&gt;&gt; import dis &gt;&gt;&gt; dis.dis(flat) 2 0 LOAD_GLOBAL 0 (inner) 3 LOAD_FAST 0 (x) 6 CALL_FUNCTION 1 9 RETURN_VALUE &gt;&gt;&gt; dis.dis(nested) 2 0 LOAD_CONST 1 (&lt;code object inner at 0x7f2958a33830, file "&lt;stdin&gt;", line 2&gt;) 3 MAKE_FUNCTION 0 6 STORE_FAST 1 (inner) 4 9 LOAD_FAST 1 (inner) 12 LOAD_FAST 0 (x) 15 CALL_FUNCTION 1 18 RETURN_VALUE &gt;&gt;&gt; dis.dis(fake_nested) 2 0 LOAD_FAST 0 (x) 3 STORE_FAST 1 (y) 3 6 LOAD_FAST 0 (x) 9 STORE_FAST 2 (z) 4 12 LOAD_GLOBAL 0 (inner) 15 LOAD_FAST 0 (x) 18 CALL_FUNCTION 1 21 RETURN_VALUE As for the inner function caching part, the other answer already clarifies that a new inner() function will be created every time nested() is run. To see this more clearly see the following variation on nested(), cond_nested() which creates same functions with two different names based on a flag. First time this runs with a False flag second function inner2() is created. Next when I change the flag to True the first function inner1() is created and the memory occupied by second function inner2() is freed. So if I run again with True flag, the first function is again created and is assigned a memory that was occupied by second function which is free now. &gt;&gt;&gt; def cond_nested(x, flag=False): ... if flag: ... def inner1(x): ... return x*x ... cond_nested.func = inner1 ... print id(inner1) ... return inner1(x) ... else: ... def inner2(x): ... return x*x ... cond_nested.func = inner2 ... print id(inner2) ... return inner2(x) ... &gt;&gt;&gt; cond_nested(2) 139815557561112 4 &gt;&gt;&gt; cond_nested.func &lt;function inner2 at 0x7f2958a47b18&gt; &gt;&gt;&gt; cond_nested(2, f…
answers question: http://stackoverflow.com/q/47956743
score: 1
accepted answer of: http://stackoverflow.com/q/47956743
downvote count: 0
has comment: http://stackoverflow.com/comment/82916918
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82890672
type: Answer

http://stackoverflow.com/q/47862783
has title: Join whole word by its Tag Python
score: -1
possible better answer: http://stackoverflow.com/a/47863168
has answer: http://stackoverflow.com/a/47863168
tagged with: string
has comment: http://stackoverflow.com/comment/82690591
favorite count: 0
has answer: http://stackoverflow.com/a/47862859
has body: let say i have this sentences: His/O name/O is/O Petter/Name Jack/Name and/O his/O brother/O name/O is/O Jonas/Name Van/Name Dame/Name How can i get result like this: Petter Jack, Jonas Van Dame. So far i've already tried this, but still its just join 2 word : import re pattern = re.compile(r"\w+\/Name) sent = sentence.split() for i , w in sent: if pattern.match(sent[i]) != None: if pattern.match(sent[i+1]) != None: #.... #join sent[i] and sent[i+1] element #....
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/82690570
accepted answer: http://stackoverflow.com/a/47862859
type: AnsweredQuestion
downvote count: 1
type: Question
answer count: 2
upvote count: 0

http://stackoverflow.com/q/47941623
score: -1
has title: Python decode unknown character
has comment: http://stackoverflow.com/comment/82854869
has answer: http://stackoverflow.com/a/47945317
answer count: 1
tagged with: utf-8
favorite count: 0
accepted answer: http://stackoverflow.com/a/47945317
linked to: http://stackoverflow.com/q/21129020
has comment: http://stackoverflow.com/comment/82852577
tagged with: django
tagged with: python
has body: I'm trying to decode the following: UKLTD� For into utf-8 (or anything really) but I cannot workout how to do it and keep getting errors like 'ascii' codec can't decode byte 0xae in position 8: ordinal not in range(128) I'm reading from a csv and have the following: with open(path_to_file, 'rb') as f: reader = csv.reader(f) for row in reader: order = Order( ... product_name = row[11].encode('utf-8'), ... ) order.save() I would be happy right now to just ignore the character if I have keep the rest of the string.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82854936
has comment: http://stackoverflow.com/comment/82854782
has comment: http://stackoverflow.com/comment/82852730
downvote count: 1
has comment: http://stackoverflow.com/comment/82854809
type: Question
tagged with: decode
upvote count: 0

http://stackoverflow.com/q/47935707
tagged with: python-unittest
answer count: 2
tagged with: python-import
has answer: http://stackoverflow.com/a/47936061
tagged with: pythonpath
downvote count: 0
favorite count: 0
has body: I. Preface: The application directory structure and modules are listed at the end of the post. II. Statement of the Problem: If the PYTHONPATH is not set the application runs, but the unittest fails with the ImportError: No module named models.transactions. This happens when trying to import Transactions in app.py. If the PYTHONPATH is set to /sandbox/app both the application and unittest run with no errors. The constraints for a solution are that the PYTHONPATH should not have to be set, and the sys.path should not have to be modified programmatically. III. Details: Consider the case when the PYTHONPATH is set and the test_app.py is run as a package /sandbox$ python -m unittest tests.test_app. Looking at the print statements for __main__ sprinkled throughout the code: models : app.models.transactions models : models.transactions resources: app.resources.transactions app : app.app test : tests.test_app The unittest imports the app first, and so there is app.models.transactions. The next import that the app attempts is resources.transactions. When it is imported it makes its own import of models.transactions, and then we see the __name__ for app.resources.transactions. This is followed by the app.app import, and then finally the unittest module tests.test.app. Setting the PYTHONPATH allows the application to resolve models.transactions! One solution is to put the models.transactions inside resources.transaction. But is there another way to handle the problem? For completeness, when the application is run the print statements for __main__ are: models : models.transactions resources: resources.transactions app : __main__ This is expected, and no imports are being attempted which are above /sandbox/app or sideways. IV. Appendix A.1 Directory Structure: |-- sandbox |-- app |-- models |-- __init__.py |-- transactions.py |-- resources |-- __init__.py |-- transactions.py |-- __init__.py |-- app.py |-- tests |-- __init__.py |-- test_app.py A.2 Modules: (1) app: from flask im…
tagged with: importerror
tagged with: python
upvote count: 6
has title: Python Run Unittest as Package Import Error
score: 6
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47936061
has answer: http://stackoverflow.com/a/47944461
accepted answer: http://stackoverflow.com/a/47944461

http://stackoverflow.com/q/47874008
tagged with: django-models
score: 0
tagged with: django-rest-framework
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82716023
has comment: http://stackoverflow.com/comment/82714918
answer count: 0
has body: I am building an IoT project with devices that will capture climate data (like weather stations). I am using Django for the server-side functions and data management, and django-rest-framework for communication with the devices. My problem is with building the models. Here are my models.py: class Devices(models.Model): deviceid = models.CharField(max_length=100) devicesecretid = models.CharField(max_length=100) longitude = models.DecimalField(max_digits=20, decimal_places=16) latitude = models.DecimalField(max_digits=20, decimal_places=16) def __str__(self): return self.type + ' - ' + self.deviceid class DeviceData(models.Model): device = models.ForeignKey(Devices, on_delete=models.CASCADE) requestid = models.PositiveIntegerField() temperature = models.DecimalField(max_digits=5, decimal_places=2) humidity = models.DecimalField(max_digits=5, decimal_places=2) rain = models.DecimalField(max_digits=5, decimal_places=2) sunlight = models.DecimalField(max_digits=5, decimal_places=2) battery = models.DecimalField(max_digits=5, decimal_places=2) co2 = models.DecimalField(max_digits=5, decimal_places=2) added = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.requestid) + ' - ' + str(self.added) With my existing code I am building 2 tables (please correct if I am wrong), one which will contain all the weather stations (id, secretid, longitude, latitude) and the other one all the data captured by all of them. Let's assume that we have 10,000 working weather stations that will send data every 15 minutes. This will mean that after a year, our tables will look like that: -Devices: 10,000 rows because there are 10,000 devices -DeviceData: 350,400,000 rows because there are 10,000 devices sending data every 15 minutes every day of the year (4*24*365*10,000) What actually bothers me is that there are a lot of rows in the DeviceData. Wouldn't this be a problem. Is there a way to have a table dedicated to the data from every single device. This will create …
type: UnansweredQuestion
tagged with: mysql
has comment: http://stackoverflow.com/comment/82715732
type: Question
has title: Django model building for monitoring system (IoT)

http://stackoverflow.com/q/47936474
linked to: http://stackoverflow.com/q/31464345
has comment: http://stackoverflow.com/comment/82843179
has title: Is there a function similar to OpenCV findContours that detects curves and replaces points with a spline?
type: UnansweredQuestion
score: 6
tagged with: python
upvote count: 6
has body: I am trying to take the below image, trace the white shape, and export the resulting path to pdf. The problem I have is that findContours seeming only finds points along the edge of the shape. Is there a solution out there, similar to findContours, that detects curves in a shape and replaces its points with a spline wherever there is a curve? If I use scipy.interpolate it ignores straight lines and turns the entire contour into one big curved shape, which is no good either. I need something that does both things. import numpy as np import cv2 from scipy.interpolate import splprep, splev from pyx import * import matplotlib.pyplot as plt #read in image file original = cv2.imread('test.jpg') #blur the image to smooth edges im = cv2.medianBlur(original,5) #threshold the image imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) ret,thresh = cv2.threshold(imgray,170,255,cv2.THRESH_BINARY) #findContours im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_\ APPROX_SIMPLE) #drawContours cv2.drawContours(original, [approx], -1, (0,255,0), 3) cv2.imshow("Imageee", original) cv2.waitKey(0)
has answer: http://stackoverflow.com/a/47951030
tagged with: matplotlib
tagged with: scipy
has answer: http://stackoverflow.com/a/47951517
type: Question
tagged with: opencv
answer count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/82871296
has answer: http://stackoverflow.com/a/48090026
has comment: http://stackoverflow.com/comment/82864648
favorite count: 0

http://stackoverflow.com/q/48014240
answer count: 1
has comment: http://stackoverflow.com/comment/83185644
has answer: http://stackoverflow.com/a/48122915
favorite count: 0
has comment: http://stackoverflow.com/comment/83139993
tagged with: python
tagged with: curl
type: AnsweredQuestion
downvote count: 0
score: 1
has body: I am trying to request the batch log-level data from Appnexus api. Based on the official data service guide, there are four main steps: 1. Account Authentication -> return token in Json 2. GET available data feeds list and look up download parameters -> return parameters in Json 3. GET Request file download location code by passing download parameters -> extract location code from header 4. GET download log data file by passing location code -> return gz data file Those steps work perfectly in Terminal using curl: curl -b cookies -c cookies -X POST -d @auth 'https://api.appnexus.com/auth' curl -b cookies -c cookies 'https://api.appnexus.com/siphon?siphon_name=standard_feed' curl --verbose -b cookies -c cookies 'https://api.appnexus.com/siphon-download?siphon_name=standard_feed&amp;hour=2017_12_28_09&amp;timestamp=20171228111358&amp;member_id=311&amp;split_part=0' curl -b cookies -c cookies 'http://data-api-gslb.adnxs.net/siphon-download/[location code]' &gt; ./data_download/log_level_feed.gz In Python, I was trying same thing to test the api. However, it keeps giving me the "ConnectionError". In steps 1-2, it still works well so that I successfully got the parameters from the Json response to build the url for step 3 in which i need to request location code and extract it from the response's header. Step1: # Step 1 ############ Authentication ########################### # Select End-Point auth_endpoint = 'https://api.appnexus.com/auth' # API Key auth_app = json.dumps({'auth':{'username':'xxxxxxx','password':'xxxxxxx'}}) # Proxy proxy = {'https':'https://proxy.xxxxxx.net:xxxxx'} r = requests.post(auth_endpoint, proxies=proxy, data=auth_app) data = json.loads(r.text) token = data['response']['token'] Step2: # Step 2 ########### Check report list ################################### check_list_endpoint = 'https://api.appnexus.com/siphon?siphon_name=standard_feed' report_list = requests.get(check_list_endpoint, proxies=proxy, headers={"Authorization":token}) data = json.…
tagged with: python-requests
has comment: http://stackoverflow.com/comment/83136710
type: Question
tagged with: urllib2
linked to: http://stackoverflow.com/q/9419162
accepted answer: http://stackoverflow.com/a/48122915
has title: Why ConnectionError when GET requests gz data using Python requests
has comment: http://stackoverflow.com/comment/83142815
has comment: http://stackoverflow.com/comment/83107774
tagged with: api
linked to: http://stackoverflow.com/q/13137817
upvote count: 1

http://stackoverflow.com/comment/82978101
score: 0
comment on: http://stackoverflow.com/a/47993261
type: Comment
has text: Why are you resetting ? Just `ndf.set_index('time')` is enough
type: AnswerComment

http://stackoverflow.com/a/47861190
has comment: http://stackoverflow.com/comment/82687653
accepted answer of: http://stackoverflow.com/q/47860892
has comment: http://stackoverflow.com/comment/82688413
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47860892
has body: The concurrent.futures module is a great way to start work on "embarrassingly parallel" problems, and can very easily be switched between using either multiple processes or multiple threads within a single process. In your case, it sounds like the "hard work" is being done on other machines over the network, and your main program will spend most of its time waiting for them to deliver results. If so, threads should work fine. Here's a complete, executable toy example: import concurrent.futures as cf def is_valid(s): import random import time time.sleep(random.random() * 10) return random.choice([False, True]) NUM_WORKERS = 10 # number of threads you want to run strings = list("abcdefghijklmnopqrstuvwxyz") with cf.ThreadPoolExecutor(max_workers=NUM_WORKERS) as executor: # map a future object to the string passed to is_valid futures = {executor.submit(is_valid, s): s for s in strings} # `as_complete()` returns results in the order threads # complete work, _not_ necessarily in the order the work # was passed out for future in cf.as_completed(futures): result = future.result() print(futures[future], result) And here's sample output from one run: g False i True j True b True f True e True k False h True c True l False m False a False s False v True q True p True d True n False t False z True o True y False r False w False u True x False concurrent.futures handles all the headaches of starting threads, parceling out work for them to do, and noticing when threads deliver results. As written above, up through 10 (NUM_WORKERS) is_valid() invocations can be active simultaneously. as_completed() returns a future object as soon as its result is ready to retrieve, and the executor automatically hands the thread that computed the result another string for is_valid() to chew on.
has comment: http://stackoverflow.com/comment/82693943
has comment: http://stackoverflow.com/comment/82687576
type: Answer
has comment: http://stackoverflow.com/comment/82688443
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82688153
has comment: http://stackoverflow.com/comment/82690990
has comment: http://stackoverflow.com/comment/82688510

http://stackoverflow.com/q/47951514
has comment: http://stackoverflow.com/comment/82872607
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47951615
possible better answer: http://stackoverflow.com/a/47951783
has body: I want to write a programm of counting sentences. The border is (!|.|?|...). The python counts only ! and . and ?. What should I do to count ... too? I tried to write it in usual form but it counts every dot in ellipsis. Please, give me an advice. f = input ("text") znak = 0 for s in f: i = s.find('.') if i &gt; -1: znak += 1 else: i = s.find('!') if i &gt; -1: znak += 1 else: i = s.find('?') if i &gt; -1: znak += 1 else: i = s.find('...') if i&gt; -1: znak +=1 print('Предложений:', znak)
has answer: http://stackoverflow.com/a/47951783
type: Question
answer count: 2
tagged with: counter
score: 0
accepted answer: http://stackoverflow.com/a/47951615
has comment: http://stackoverflow.com/comment/82872609
has title: count ellipsis in python
tagged with: python

http://stackoverflow.com/a/59438131
answers question: http://stackoverflow.com/q/47884422
score: 44
has comment: http://stackoverflow.com/comment/114597389
has body: I had the same problem on macOS. brew reinstall python@2 solved this problem. Maybe you could try to reinstall python.
has comment: http://stackoverflow.com/comment/107646792
upvote count: 44
downvote count: 0
has comment: http://stackoverflow.com/comment/113798514
has comment: http://stackoverflow.com/comment/116661582
has comment: http://stackoverflow.com/comment/109047287
type: Answer

http://stackoverflow.com/comment/82770930
has text: Thanks for your answers!! A typical case of read-the-manual :-| sorry for that, but I coudn't find it while searching for index, re-index ,etc...
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/47898121
type: Comment

http://stackoverflow.com/a/47920807
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47920589
downvote count: 0
type: Answer
has body: In your particular example both definitions of class A will have the same effect. But if you add function1 to class B as well, then you can decide which version of function1 will be called from class A, by adjusting multiple inheritance order when defining class A. So you can do this like this: class A(B,C) or like that: class A(C,B)

http://stackoverflow.com/q/47891860
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82750188
type: UnansweredQuestion
score: -4
tagged with: python
has title: Python (3.6) doesn't let me draw on IDLE
has answer: http://stackoverflow.com/a/47892065
type: Question
downvote count: 4
has body: I am new to Python as I just started recently. I managed to draw on Python using Turtle just to have a play around. However, since I installed some modules, I yet again learned how to draw and I did the same thing as I did before but only when I run the module it comes up with an error. The only thing I have changed is that I installed some modules so it might be that. This is what is says when I run it; Traceback (most recent call last): File "/Users/Ed/Documents/Drawing.py", line 1, in &lt;module&gt; import turtle File "/Users/Ed/Documents/turtle.py", line 2, in &lt;module&gt; tut = turtle.Pen() AttributeError: module 'turtle' has no attribute 'Pen' I don't know what it means. And please let me know if you have the answer or have gone through the same experience as me and have solved it. Also if I went wrong please let me know.
upvote count: 0

http://stackoverflow.com/comment/82890469
has text: When I start the script via the command line it doesn't do anything when it isn't in focus.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47957861

http://stackoverflow.com/q/47861085
has body: I'm looking for the equivalent of R's mutate, which allows you to reference defined variables immediately after creating them within the same mutate call. new_df &lt;- old_df %&gt;% mutate(new_col = ifelse(something, 0, 1), newer_col = ifelse(new_col == 0, 'yay', 'nay')) Looking for the equivalent in python pandas. if I create the following dataframe, I was wondering if there is a way to use .assign to do the same thing? dic = {'names': ['jeff', 'alice', 'steph', 'john'], 'numbers':[4, 6, 5, 7]} df = pd.DataFrame(dic) df = df.assign(less_than_6 = np.where(df.numbers &lt; 6, 100, 0), pass_fail = np.where(df.less_than_6 == 100, 'pass', 'fail')) The alternative I can think of is.. df['less_than_6'] = np.where(df.numbers &lt; 6, 100, 0) df['pass_fail'] = np.where(df.less_than_6 == 100, 'pass', 'fail') but was wondering if there is a way to do it in the same call?
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/2921847
score: 1
tagged with: dataframe
has title: using recently created attributes in pandas dataframe to create new attribute
type: Question
has answer: http://stackoverflow.com/a/47861267
downvote count: 0
answer count: 1
tagged with: http://stackoverflow.com/tag/r
tagged with: pandas
favorite count: 0
has comment: http://stackoverflow.com/comment/82687436
accepted answer: http://stackoverflow.com/a/47861267
has comment: http://stackoverflow.com/comment/82687307
upvote count: 1
tagged with: python
tagged with: dplyr

http://stackoverflow.com/a/47976302
has body: You can speed up the check by using a set (O(1) contains check), especially if you are checking multiple strings for the same range since the initial set creation requires one iteration as well. You can then use all for the early-breaking iteration pattern which fits better than any here: import string ascii = set(string.ascii_uppercase) ascii_all = set(string.ascii_uppercase + string.ascii_lowercase) if all(x in ascii for x in my_string1): # my_string1 is all ascii Of course, any all construct can be transformed to an any via DeMorgan's Law: if not any(x not in ascii for x in my_string1): # my_string1 is all ascii Update: One good pure set based approach not requiring a complete iteration as pointed out by Artyer: if ascii.issuperset(my_string1): # my_string1 is all ascii
has comment: http://stackoverflow.com/comment/82921797
has comment: http://stackoverflow.com/comment/82922045
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/82921954
has comment: http://stackoverflow.com/comment/82921642
type: Answer
upvote count: 15
score: 14
has comment: http://stackoverflow.com/comment/82921753
has comment: http://stackoverflow.com/comment/82927180
answers question: http://stackoverflow.com/q/47976142
has comment: http://stackoverflow.com/comment/82921662
accepted answer of: http://stackoverflow.com/q/47976142
has comment: http://stackoverflow.com/comment/82926990

http://stackoverflow.com/a/47965956
has comment: http://stackoverflow.com/comment/82909868
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82909592
answers question: http://stackoverflow.com/q/47965487
has comment: http://stackoverflow.com/comment/82907727
type: Answer
accepted answer of: http://stackoverflow.com/q/47965487
has body: You can read file once and calculate for different dates. btw: as extension it could get few dates in Entry (separated by space or comma) and calculate total for every date, or calculate in range of two dates In read_data() it loads all data and convert to datetimes using datetime.datetime.strptime(date1 + ' ' + time1, "%d.%m.%Y %H:%M:%S") In calculate it get data from Entry and execute processText() with data from file and date from entry. It convert string with data from Entry into datetime. String may have incorrect date or in unexpeted format so I use try/except. It use t1 &lt;= selected_date to compare two datetime. It uses (t2-t1).seconds to get seconds between two dates (without using timestamp()). It could do this even in read_data(). Full code: Problem can be except Exception as ex: which is incorrect in Python 2. try: import Tkinter as Tk import tkFileDialog as fileDialog except ImportError: import tkinter as Tk import tkinter.filedialog as fileDialog import datetime def read_data(): ''' Read data from file and convert to list with datetime which can be used to calculate time and display. ''' global data filename = fileDialog.askopenfilename() if filename: # read all lines with open(filename) as fileHandle: lines = fileHandle.readlines() # convert to `datetime` (not `timestamp`) data = [] for line in lines: direction, date1, time1, _, date2, time2 = line.split() t1 = datetime.datetime.strptime(date1 + ' ' + time1, "%d.%m.%Y %H:%M:%S") t2 = datetime.datetime.strptime(date2 + ' ' + time2, "%d.%m.%Y %H:%M:%S") data.append([direction, t1, t2]) print(data) def processText(lines, selected_date): total = 0 start = None # if there is `selected_date` then convert to `datetime` if selected_date: try: selected_date = datetime.datetime.strptime(selected_date, "%d.%m.%Y") except Exception as ex: print("ERROR:", ex) selected_date = None # calculate time for direction, t1, t2 in lines: if direction == "DOWN": # if `selected_date` then filter times if selected_date and t1…
has comment: http://stackoverflow.com/comment/82914320
downvote count: 0
has comment: http://stackoverflow.com/comment/82906846
has comment: http://stackoverflow.com/comment/82907055
score: 3
has comment: http://stackoverflow.com/comment/82914390
upvote count: 3
has comment: http://stackoverflow.com/comment/82909300

http://stackoverflow.com/q/47936155
has title: Creating invisible folders in a set location
has answer: http://stackoverflow.com/a/47940657
has body: I am trying to create invisible folders on my pc. The problem is if my subfolder gets deleted, it does not update. If I want to add new folders, it will not update unless I delete C:/TVBA each time which is not safe. It also creates invisible folders where my python script is located and at C:/TVBA. How do I fix this? try: rootpath = r'C:/TVBA' os.mkdir(rootpath) os.chdir(rootpath) except OSError: pass for sub_folder in ['1', '2', '3', '4', '5', '6']: try: os.mkdir(sub_folder) ctypes.windll.kernel32.SetFileAttributesW(sub_folder, 2) except OSError: pass
type: AnsweredQuestion
downvote count: 0
possible better answer: http://stackoverflow.com/a/47936658
favorite count: 0
has answer: http://stackoverflow.com/a/47936658
type: Question
tagged with: glob
tagged with: python
score: 1
accepted answer: http://stackoverflow.com/a/47940657
tagged with: python-3.x
answer count: 2
tagged with: file
upvote count: 1
tagged with: hide

http://stackoverflow.com/comment/82803632
comment on: http://stackoverflow.com/a/47913012
score: 0
type: AnswerComment
type: Comment
has text: The reason I'm trying to use a service principal is that it's a script that's running 24/7. And atm it works fine until the next morning where I have to login through the Azure portal for it to authenticate my python request the rest of the day.

http://stackoverflow.com/a/47916469
has comment: http://stackoverflow.com/comment/82802253
downvote count: 0
answers question: http://stackoverflow.com/q/47915615
score: 1
has comment: http://stackoverflow.com/comment/82828882
upvote count: 1
type: AcceptedAnswer
has body: I scaled performance_x by 0.01, i.e. performance_x = np.stack((np.random.uniform(.24, .40, size), np.random.uniform(.80, 2.40, size), np.random.uniform(.80, 1.00, size), np.random.uniform(.15, .25, size)), axis=1) and got an MSE around 0.0038 after 100k steps.
has comment: http://stackoverflow.com/comment/82803584
type: Answer
accepted answer of: http://stackoverflow.com/q/47915615

http://stackoverflow.com/comment/82912645
has text: To do a depth limited iteration (i.e. just rows) with `nditer` you have use it as `np.ndindex` does.
comment on: http://stackoverflow.com/q/47971431
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82793456
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47912578
has text: Oops I think the order of the arguments was reversed. My bad. It should work now.

http://stackoverflow.com/comment/82830806
type: QuestionComment
comment on: http://stackoverflow.com/q/47892625
has text: unfortunately, nowhere in the sources have I found such a theory.
score: 0
type: Comment

http://stackoverflow.com/a/48001333
has body: Find the rows where property_type1 column is NaN, and for those rows: assign the property_type values to the pro column. df.ix[df.property_type1.isnull(), 'pro'] = df.ix[df.property_type1.isnull(), 'property_type']
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/82971950
downvote count: 1
has comment: http://stackoverflow.com/comment/82972147
answers question: http://stackoverflow.com/q/48000959
score: 0
has comment: http://stackoverflow.com/comment/82971689

http://stackoverflow.com/comment/82710875
has text: I still don't believe he has the knowledge to understand this one-liner expression if he has problems differentiating lists, from strings, from integers, etc..
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47872367

http://stackoverflow.com/comment/82794190
has text: Ok thanks, ill take onboard everyones advice here and give it a shot, from what I am understanding, I should ditch this python script and call those three individual scripts directly in the shell script, ill check for the (rm -rf) and any situations where its using 'eval'.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47897402

http://stackoverflow.com/comment/82880093
comment on: http://stackoverflow.com/a/47949888
score: 0
has text: Please let me know what's wrong instead of down voting so that I can help you with it
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47914261
downvote count: 0
has comment: http://stackoverflow.com/comment/87563098
favorite count: 0
type: Question
has body: Alright so I have a fairly basic python click CLI application that when ran with a bound volume in a container (live dev on files) appears to break the entry_point I have in setup.py Running either of the following commands $ docker run -it -v $(pwd):/opt/app gdax $ docker run -it --mount src=$(pwd),target=/opt/app,type=bind gdax I get the following Traceback (most recent call last): File "/usr/local/bin/gdax", line 6, in &lt;module&gt; from pkg_resources import load_entry_point File "/usr/local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 3144, in &lt;module&gt; @_call_aside File "/usr/local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 3128, in _call_aside f(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 3157, in _initialize_master_working_set working_set = WorkingSet._build_master() File "/usr/local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 666, in _build_master ws.require(__requires__) File "/usr/local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 984, in require needed = self.resolve(parse_requirements(requirements)) File "/usr/local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 870, in resolve raise DistributionNotFound(req, requirers) pkg_resources.DistributionNotFound: The 'gdax-cli' distribution was not found and is required by the application Dockerfile FROM python:3.6 RUN mkdir /opt/app COPY . /opt/app WORKDIR /opt/app RUN pip install --editable . CMD ["gdax", "--help"] setup.py from setuptools import setup setup( name='gdax-cli', version='0.1', py_modules=['app'], install_requires=[ 'click==6.7', 'gdax==1.0.6' ], entry_points=''' [console_scripts] gdax=app:cli ''', ) /usr/local/bin/gdax &lt;- on container #!/usr/local/bin/python # EASY-INSTALL-ENTRY-SCRIPT: 'gdax-cli','console_scripts','gdax' __requires__ = 'gdax-cli' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(…
tagged with: python
has answer: http://stackoverflow.com/a/50273660
has answer: http://stackoverflow.com/a/58922442
upvote count: 6
has comment: http://stackoverflow.com/comment/82805764
has title: Docker volume bind breaks python script CLI entry_point
has comment: http://stackoverflow.com/comment/82802302
answer count: 2
type: UnansweredQuestion
score: 6
tagged with: docker

http://stackoverflow.com/comment/82821129
score: 3
has text: `a, b = b, a` in python and C mean _very, very different_ things.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47926650

http://stackoverflow.com/comment/82716228
comment on: http://stackoverflow.com/q/47860212
type: Comment
type: QuestionComment
has text: @plumbus_bouquet X has movie overviews and y has all the thing other than title and overview basically it has genres
score: 0

http://stackoverflow.com/q/47914304
has comment: http://stackoverflow.com/comment/82796909
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82797183
score: 1
has comment: http://stackoverflow.com/comment/82796982
possible better answer: http://stackoverflow.com/a/47914419
has answer: http://stackoverflow.com/a/47914419
type: Question
answer count: 2
has body: I'm on Linux Mint and have at least 3 versions of python (2, 3.4, 3.5). Trying to use pip3.5, I get: Import Error: No module named six But, trying to install six via any of the following give the same error: sudo easy_install-3.5 six sudo python3.5 -m easy_install six sudo pip3.5 install six It feels like this is circular reasoning since I can't use pip or easy_install since I don't have six, but I can't install six since pip or easy_install won't work without it.
upvote count: 1
favorite count: 0
has title: I can't install six because pip and easy_install won't work without six
tagged with: python
has answer: http://stackoverflow.com/a/47914541
accepted answer: http://stackoverflow.com/a/47914541
downvote count: 0
tagged with: pip
linked to: http://stackoverflow.com/q/26610461

http://stackoverflow.com/comment/82793803
comment on: http://stackoverflow.com/a/47900171
type: AnswerComment
score: 0
type: Comment
has text: @DanielWillemin Nice to know that. Did your Question get answered?

http://stackoverflow.com/a/47947979
has body: My issue was with directories for sql script and the python script, even though I was specifying the full path for the sql script. They were on separate discs, and I was keep getting non-zero exit status 1 when I would use subprocess.call_check(). I've put both scripts in the same location and the issue is gone.
upvote count: 1
type: Answer
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/47945116

http://stackoverflow.com/comment/82826251
type: AnswerComment
comment on: http://stackoverflow.com/a/47928814
type: Comment
has text: Yep, I use python3
score: 0

http://stackoverflow.com/q/47984489
tagged with: while-loop
type: AnsweredQuestion
downvote count: 0
tagged with: triple-equals
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47984531
type: Question
tagged with: python
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/47984531
tagged with: if-statement
tagged with: javascript
has body: I'm starting to learn javascript for front-end programming, being python my first language to learn completely. So I'm trying to solve a while loop excersise that console-logs every number from 50-300 that is divisble by 5 and 3. So in python i would do this: i = 50 while i &lt; 301: if i % 5 == i % 3 == 0: print(i) i += 1 And works flawlessly. I know you could use and and operator but the whole point of this question is to avoid using it. So I try the same thing in javascript var i = 50; while (i &lt; 301){ if (i % 5 === i % 3 === 0){ console.log(i); } i ++; } And somehow that wont work. However, with an &amp;&amp; operator it does. Are double equalities in javascript not allowed? If they are, what am I missing?
has title: 2 equalities on an IF conditional like in python

header
tags question: http://stackoverflow.com/q/47887445
type: Tag
tags question: http://stackoverflow.com/q/47902580
tag name: header

http://stackoverflow.com/q/47994466
type: Question
has answer: http://stackoverflow.com/a/47994770
tagged with: cron
downvote count: 0
answer count: 1
tagged with: schedule
has title: How to pass argument while calling a function using schedule library?
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I am wondering if someone can help me in how to pass the argument while calling the job function using the schedule library. I see there are couple of example on the same but nothing when you are using the threading and run_threaded function. In the below code snippet i am trying to pass the 'sample_input' as an argument and confused how to define this parameter. def run_threaded(job_func): job_thread = threading.Thread(target=job_func) job_thread.start() @with_logging def job(input_name): print("I'm running on thread %s" % threading.current_thread()) main(input_name) schedule.every(10).seconds.do(run_threaded, job(‘sample_input’))
score: 1
upvote count: 1

http://stackoverflow.com/comment/82797936
has text: I tested it and changed the bg value to "black" and it is not black. it is probably hidden. so how do I make it visible
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47914501
type: Comment

http://stackoverflow.com/a/48246540
answers question: http://stackoverflow.com/q/47858022
has body: You are on the right track, however, try printing the sc1.star_list itself. You should see: [&lt;__main__.Star instance at 0x10281c680&gt;, &lt;__main__.Star_cluster instance at 0x10281c7a0&gt;] Notice that the second item is a star cluster. This is because in your Star_Cluster.merge(), you are appending the other star cluster itself, and not its stars. Instead, use: def merge(self, a_star_cluster): self.star_list.append(a_star_cluster.star_list) self.total_number_of_planets += a_star_cluster.total_number_of_planets This will copy the stars and remember how many planets the cluster now has, but without copying the other star cluster itself.
score: 0
type: Answer

http://stackoverflow.com/q/47948505
favorite count: 0
has body: I am trying to replace the uuid in the given URL /v2/merchants/e0cf059a-5080-40a5-aaf1-67eb866aa48f/secretKey with the * sign. I tried using the following regular expression, but I'm still not able to do it: regex = re.sub( r'^[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}', '*', '/v2/merchants/e0cf059a-5080-40a5-aaf1-67eb866aa48f/secretKey' ) It returns the original string /v2/merchants/e0cf059a-5080-40a5-aaf1-67eb866aa48f/secretKey.
tagged with: python
has title: want to replace uuid in given url '/v2/merchants/e0cf059a-5080-40a5-aaf1-67eb866aa48f/secretKey' with '*' using python
type: AnsweredQuestion
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47948631
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/47948631
answer count: 1
tagged with: regex

http://stackoverflow.com/comment/82708940
type: QuestionComment
comment on: http://stackoverflow.com/q/47871691
score: 0
has text: @cᴏʟᴅsᴘᴇᴇᴅ the second suggestion doesn't work
type: Comment

http://stackoverflow.com/comment/82743294
comment on: http://stackoverflow.com/q/47888644
type: Comment
has text: yes: you have to return `password` from the function... and assign the value to another variable.
type: QuestionComment
score: 2

http://stackoverflow.com/comment/82826719
score: 1
comment on: http://stackoverflow.com/q/47929077
type: Comment
type: QuestionComment
has text: It's a dupe. Use ravel or flatten with values

http://stackoverflow.com/q/47870003
tagged with: tensor
tagged with: python
accepted answer: http://stackoverflow.com/a/47871845
type: AnsweredQuestion
has body: I'm playing around with PyTorch with the aim of learning it, and I have a very dumb question: how can I multiply a matrix by a single vector? Here's what I've tried: &gt;&gt;&gt; import torch &gt;&gt;&gt; a = torch.rand(4,4) &gt;&gt;&gt; a 0.3162 0.4434 0.9318 0.8752 0.0129 0.8609 0.6402 0.2396 0.5720 0.7262 0.7443 0.0425 0.4561 0.1725 0.4390 0.8770 [torch.FloatTensor of size 4x4] &gt;&gt;&gt; b = torch.rand(4) &gt;&gt;&gt; b 0.1813 0.7090 0.0329 0.7591 [torch.FloatTensor of size 4] &gt;&gt;&gt; a.mm(b) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; RuntimeError: invalid argument 2: dimension 1 out of range of 1D tensor at /Users/soumith/code/builder/wheel/pytorch-src/torch/lib/TH/generic/THTensor.c:24 &gt;&gt;&gt; a.mm(b.t()) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; RuntimeError: t() expects a 2D tensor, but self is 1D &gt;&gt;&gt; b.mm(a) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; RuntimeError: matrices expected, got 1D, 2D tensors at /Users/soumith/code/builder/wheel/pytorch-src/torch/lib/TH/generic/THTensorMath.c:1288 &gt;&gt;&gt; b.t().mm(a) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; RuntimeError: t() expects a 2D tensor, but self is 1D On the other hand, if I do &gt;&gt;&gt; b = torch.rand(4,2) then my first attempt, a.mm(b), works fine. So the problem is just that I'm multiplying a vector rather than a matrix --- but how can I do this?
tagged with: pytorch
type: Question
tagged with: vector
score: 22
upvote count: 22
has answer: http://stackoverflow.com/a/47871845
has title: How to multiply a matrix by a vector in PyTorch
answer count: 2
has answer: http://stackoverflow.com/a/47880126
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/47880126
tagged with: matrix-vector-multiplication

http://stackoverflow.com/comment/82705984
type: Comment
has text: Thanks, @eryksun, I believe that OP indeed has enough with a console-less process.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47866216

http://stackoverflow.com/comment/82895381
type: QuestionComment
has text: @SahibSingh variables are names produced as a result of processing the procedure defined in the function.
comment on: http://stackoverflow.com/q/47963008
score: 0
type: Comment

http://stackoverflow.com/q/47896006
answer count: 0
linked to: http://stackoverflow.com/q/23294658
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82759849
has comment: http://stackoverflow.com/comment/82759309
has title: Variable is not updated after while loop is used Python
has body: I'm new to coding and Python is the first language I am learning. I'm trying to develop a basic calculator. The numbers can't be equal to zero and the user must use numbers 1-4 to choose between addition, subtraction, multiplication and division. My challenge is: when I input a number equal to zero or a number that is not 1-4, the functions should prompt me to enter the right value, then update the variable to continue accordingly with the calculation. The code generates the error message and asks for a new input for the number but it is not saving the new input so it doesn't produce the right outputs. For example, if I enter a number == 0, it prompts me to enter a new one, but then it keeps zero as the first number. Then if I do the same for the second number, the program stalls and it doesn't calculate anything. If anyone could help me, I would appreciate tremendously... I apologize if this is not the most elegant code ever, but please keep in mind this is my first try...:-)) I posted this code on dpaste in case seeing it here doesn't work: strong texthttps://dpaste.de/hyKa def number (n): while n == 0: print ("ERROR - number must be different than zero") n = float(input("Enter a different number. \n")) number (n) return n x = int(input("Enter your first number. \n")) number (x) def operator_control (user_choice): while user_choice &gt; 4 or 1 &gt; user_choice: print ("ERROR - you must choose either 1, 2, 3, or 4 depending on the operation you want") user_choice = int(input("Let's try again - enter another number for the operator \n")) return user_choice return user_choice user_choice = int(input("Now you will choose the operation! Ready? Choose 1 for addition, 2 for subtraction, 3 for multiplication and 4 for division \n")) operator_control (user_choice) z = int(input("Please choose your second number as the operand for the calculation. \n")) number (z) operator = user_choice if operator == 1: result = x + z print ("Ok - you chose to add your first number," , x ,…
has comment: http://stackoverflow.com/comment/82759172
duplicate of: http://stackoverflow.com/q/23294658
has comment: http://stackoverflow.com/comment/82762657
tagged with: loops
has comment: http://stackoverflow.com/comment/82759767
has comment: http://stackoverflow.com/comment/82759970
type: Question
tagged with: function
tagged with: calculator
tagged with: variables
has comment: http://stackoverflow.com/comment/82759051
tagged with: python

http://stackoverflow.com/q/47998184
has answer: http://stackoverflow.com/a/47998276
upvote count: 0
has comment: http://stackoverflow.com/comment/82964883
score: -7
has comment: http://stackoverflow.com/comment/82964956
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
downvote count: 7
type: Question
has comment: http://stackoverflow.com/comment/82964866
has title: Dictionary assigning
has body: listim=[['1' ,'2'], ['3' , '4'], ['1', '5'], ['4', '1']] I am trying to make dictionary using listim for each number, I want to have d={'1': 2 , 4, 5 ,'2':1, '3': 4, (...and so on)} my code is(I can't find the mistake but probably about dictionaries): a=1 dic={} while a&lt;6: for number in listim: if number[0]==a: if number[1] not in dic[a]: dic[a].append(number[1]) elif number[1]==a: if number[0] not in dic[a]: dic[a].append(number[0]) a+=1 I couldn't find enough information on web,(I know I can). I hope I was clear enough. Thank you
answer count: 2
has answer: http://stackoverflow.com/a/47998237

http://stackoverflow.com/comment/82760455
comment on: http://stackoverflow.com/q/47896022
has text: `pandas` csv reader is faster, using compiled code (at least in some cases).
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82760642
type: AnswerComment
type: Comment
has text: @KRidg, what is the output of `print(type(pd))`?
comment on: http://stackoverflow.com/a/47896745
score: 0

http://stackoverflow.com/comment/82714103
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47874340
score: 3
has text: `df.pivot_table(index='id', columns='category', values='count', aggfunc='sum', fill_value=0)`. This is a dupe.

http://stackoverflow.com/a/48016421
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/47971907
score: 2
has body: What is the return value for zmq_setsockopt()? Then you should use "" instead of a NULL, they are different. zmq_setsockopt( subscriber, ZMQ_SUBSCRIBE, "", 0 ); As API defines: Return value The zmq_setsockopt() function shall return zero if successful. Otherwise it shall return -1 and set errno to one of the values defined below. ...
downvote count: 0

http://stackoverflow.com/q/47890550
score: 1
has title: Vectorized funcion into a vectorized function Python
accepted answer: http://stackoverflow.com/a/47895364
type: Question
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/82754540
tagged with: function
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/47895364
has body: I want to solve the next problem: I have a matrix of values, every value represents the rating of a movie, and I have the next function which returns a value (distance): def getDistanceBetween2Movies(movie1, movie2): return np.linalg.norm(X[movie1]-X[movie2]) This function works fine, so then I wanted to get a list with all the distances from one specified movie to the others, and I did it like this, and it works #Vector of indices of movies without our new user's one moviesInd = np.arange(n_movies) myMovie = 1 #Vectorizing our function vfunc = np.vectorize(getDistanceBetween2Movies) arrayDistances = vfunc(myMovie,moviesInd) closestValue = np.min(arrayDistances) closestIndex = np.argmin(arrayDistances) print("Movie: " + str(closestIndex)) print("Distance: " + str(closestValue)) So the problem now is how to get a matrix with all the distances from every movie to the others, I'm trying to vectorize again this function in order to make the same operation n_movies times and gather it into a list or array. def getVectorDistances(i): vector = np.arange(n_movies) vFunc = np.vectorize(getDistanceBetween2Movies) return vFunc(i, vector) moviesInd = np.arange(n_movies) vFunc = np.vectorize(getVectorDistances) print(vFunc(moviesInd)) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-34-01b95a280035&gt; in &lt;module&gt;() 6 moviesInd = np.arange(n_movies) 7 vFunc = np.vectorize(getVectorDistances) ----&gt; 8 print(vFunc(moviesInd)) 9 10 c:\users\regis\appdata\local\programs\python\python36-32\lib\site-packages\numpy\lib\function_base.py in __call__(self, *args, **kwargs) 2737 vargs.extend([kwargs[_n] for _n in names]) 2738 -&gt; 2739 return self._vectorize_call(func=func, args=vargs) 2740 2741 def _get_ufunc_and_otypes(self, func, args): c:\users\regis\appdata\local\programs\python\python36-32\lib\site-packages\numpy\lib\function_base.py in _vectorize_call(self, func, args) 2816 2817 if ufu…
possible better answer: http://stackoverflow.com/a/47891918
upvote count: 1
tagged with: python
tagged with: vectorization
has answer: http://stackoverflow.com/a/47891918
has comment: http://stackoverflow.com/comment/82749569
type: AnsweredQuestion

http://stackoverflow.com/comment/82914884
score: 0
comment on: http://stackoverflow.com/q/47972362
type: Comment
type: QuestionComment
has text: Glenn: I use this function to print lines of a solid color throughout the program, and they all work like this. It's only this particular line that messes up.

http://stackoverflow.com/a/47975002
has comment: http://stackoverflow.com/comment/82920855
has comment: http://stackoverflow.com/comment/82920966
has body: Extend them to 3D and leverage broadcasting - x[:,None] * y.T Or with np.einsum - np.einsum('ij,jk-&gt;ikj',x,y) Going by OP's comment and the quote from the question : ... matrix multiplication operation may be repeated; the output will be used as the left-side matrix of ndarrays for the next matrix multiplication operation, which would yield a higher-order ndarray after the second matrix multiplication operation, etc.. It seems, we need to do something along these lines - s1 = x[...,None] * y s2 = s1[...,None] * z # and so on. Though, the order of the axes would be different in this case, but it seems to be the simplest way to extend the solution to a generic number of incoming 2D arrays. Following the edits in the question, seems like you are placing the incoming arrays from the first axis onwards for element-wise multiplication. So, if I got that right, you can swap axes to get the correct order, like so - s1c = (x[...,None] * y).swapaxes(1,-1) s2c = (s1c.swapaxes(1,-1)[...,None] * z).swapaxes(1,-1) # and so on. If you are only interested in the final output, swap axes only at the final stage and skip those in the intermediate ones.
accepted answer of: http://stackoverflow.com/q/47974959
type: Answer
has comment: http://stackoverflow.com/comment/82920878
has comment: http://stackoverflow.com/comment/82921033
has comment: http://stackoverflow.com/comment/82920002
has comment: http://stackoverflow.com/comment/82919496
has comment: http://stackoverflow.com/comment/82920950
has comment: http://stackoverflow.com/comment/82919442
score: 5
answers question: http://stackoverflow.com/q/47974959
upvote count: 5
has comment: http://stackoverflow.com/comment/82938650
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/a/47906415
has comment: http://stackoverflow.com/comment/82779872
has comment: http://stackoverflow.com/comment/82786887
has comment: http://stackoverflow.com/comment/82780622
has comment: http://stackoverflow.com/comment/82780179
score: 0
has comment: http://stackoverflow.com/comment/82844994
accepted answer of: http://stackoverflow.com/q/47906056
type: AcceptedAnswer
has body: You want: cursor.execute("INSERT INTO Camera (img) VALUES(%s)",(frame,)) This being said, storing images in a SQL database is seldom a good idea - but if you really want to do so, at least add a primary key to your table. EDIT : from your comments, it looks like frame is a numpy.ndarray. Your database connector does not know how to convert each and any python type to something the database will understand, so you have to manually convert your frame to a byte string (bytes in Python3, str in Python2).
has comment: http://stackoverflow.com/comment/82827872
type: Answer
has comment: http://stackoverflow.com/comment/82863712
answers question: http://stackoverflow.com/q/47906056

http://stackoverflow.com/comment/82882546
comment on: http://stackoverflow.com/q/47956527
type: Comment
type: QuestionComment
has text: Other than CAPTCHA humanity test I don't think a website can tell whether you're a bot or not. With python code you can trick the web into thinking you're real by filling the header.. For eaxmple: `req = Request(url)` `req.add_header('User-Agent', 'Mozilla/5.0')` And one last thing, they can use statistics and analyze your behavior.
score: 1

recurrent-neural-network
tags question: http://stackoverflow.com/q/47907148
tags question: http://stackoverflow.com/q/47940874
tags question: http://stackoverflow.com/q/47901580
tags question: http://stackoverflow.com/q/47898147
tags question: http://stackoverflow.com/q/47945312
tags question: http://stackoverflow.com/q/47877858
type: Tag
tags question: http://stackoverflow.com/q/47916029
tags question: http://stackoverflow.com/q/47928365
tags question: http://stackoverflow.com/q/47968975
tags question: http://stackoverflow.com/q/47972917
tags question: http://stackoverflow.com/q/47958110
tag name: recurrent-neural-network
tags question: http://stackoverflow.com/q/47965256

http://stackoverflow.com/comment/82788671
comment on: http://stackoverflow.com/q/47910547
has text: Are you able to send any requests at all? Try a simple `GET` request to another URI, do you get a proper response?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82684083
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47859656
has text: Thanks, but I was also wondering how to change the i,j th entry of an existing matrix.

http://stackoverflow.com/a/47959040
has body: I use .env file to do it. Try use .env that you can refer it to other file as well https://github.com/jpadilla/django-dotenv https://github.com/theskumar/python-dotenv This link will help how to use .env to set it up
type: Answer
answers question: http://stackoverflow.com/q/47958956
score: 0

http://stackoverflow.com/comment/82725100
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47879432
has text: @andrew_reece I had misunderstood the function, we have to use `flip` here, flipud reverses both columns as well as rows.
type: AnswerComment

http://stackoverflow.com/a/47958339
has comment: http://stackoverflow.com/comment/82886400
upvote count: 5
has body: Concat is better if you ask me. But if you have a 100 columns renaming is a pain. As a generalized approach here's one with numpy flip and vstack i.e v = df.values pd.DataFrame(pd.np.vstack((v, pd.np.fliplr(v))), columns=df.columns) A B 0 1 4 1 2 5 2 3 6 3 4 1 4 5 2 5 6 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47958318
has comment: http://stackoverflow.com/comment/82886315
type: Answer
has comment: http://stackoverflow.com/comment/82886382
score: 5
answers question: http://stackoverflow.com/q/47958318

http://stackoverflow.com/comment/82828742
type: AnswerComment
score: 0
type: Comment
has text: @StefanPochmann LOL, true, that makes it even more a side effect.
comment on: http://stackoverflow.com/a/47929689

http://stackoverflow.com/q/47981842
score: -2
has comment: http://stackoverflow.com/comment/82932498
tagged with: python-3.6
type: Question
has title: how do I create a pygame with multiple menus ?
answer count: 1
has body: if I click on play button on first menu it should open a menu for users to choose the levels . in the code I wrote , on clicking the play button , the computer is also assuming that I also clicked on the easy button which is placed in the same place as the play button in the level screen.It is directly going to the game loop .
has comment: http://stackoverflow.com/comment/82932383
favorite count: 0
has answer: http://stackoverflow.com/a/47982247
has comment: http://stackoverflow.com/comment/82932161
tagged with: python
tagged with: pygame
type: UnansweredQuestion
downvote count: 3
upvote count: 1

http://stackoverflow.com/comment/82726146
type: QuestionComment
comment on: http://stackoverflow.com/q/47864505
has text: can anyone help me?
score: 0
type: Comment

http://stackoverflow.com/a/47874513
answers question: http://stackoverflow.com/q/47874301
has comment: http://stackoverflow.com/comment/82718274
score: 4
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82717401
has comment: http://stackoverflow.com/comment/82718125
has body: in you printout you have AttributeError: 'tuple' object ..., and your cell is printing like (&lt;Cell 'Sheet1'.B3&gt;,), so your actual variable holds a tuple, but you are treating it like it is the cell. You need to unpack the tuple to get to the cell-variable. if you do: for cell, in rows: ... it's one way of unpacking, or: for tmp in rows: cell = tmp[0] is another. btw, sheets = wb2.sheetnames #list of sheetnames for i,sheet in enumerate(sheets): #for each sheet ws = wb2[sheets[i]] that section is not very pythonic, the following should do the same... for sheet in wb2.sheetnames: ws = wb2[sheet]
has comment: http://stackoverflow.com/comment/82718335
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/82717869
has comment: http://stackoverflow.com/comment/82715884
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47874301
has comment: http://stackoverflow.com/comment/82717969

http://stackoverflow.com/comment/82948052
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47988882
has text: Yes true. Its for pyofbc not for sqlalchemy.
type: Comment

http://stackoverflow.com/q/47859954
score: 0
has comment: http://stackoverflow.com/comment/82685147
tagged with: exec
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82686153
answer count: 0
has comment: http://stackoverflow.com/comment/82684912
type: UnansweredQuestion
upvote count: 1
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/82684732
has comment: http://stackoverflow.com/comment/82684769
has comment: http://stackoverflow.com/comment/82685128
has title: Python - exec(self.x=1) works but exec(x=1) doesn't in a class
type: Question
has body: The title should speak for itself. Here's an example: class Example(): def function(self): exec("self.a = 'Hello'") exec("b = 'World'") print(self.a) print(b) Then when I call the function Example()function() it returns: Hello (...) NameError: name 'b' is not defined Could someone explain why b is not defined but self.a is?
favorite count: 0
tagged with: class

http://stackoverflow.com/comment/82758026
type: Comment
has text: Yea using `del` was a shot in the dark. Another idea could be to stop/re-initialize your spark context after ever `N` tables or so. Not a very elegant solution, but it *could* work.
type: QuestionComment
comment on: http://stackoverflow.com/q/47894597
score: 0

http://stackoverflow.com/q/47879994
tagged with: mysql-python
tagged with: python
has comment: http://stackoverflow.com/comment/82728798
has comment: http://stackoverflow.com/comment/82726039
has answer: http://stackoverflow.com/a/49549039
type: UnansweredQuestion
has title: Execution of mysql query using python mysql?
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/82725945
has comment: http://stackoverflow.com/comment/82725969
tagged with: mysql
has comment: http://stackoverflow.com/comment/82728825
has comment: http://stackoverflow.com/comment/82726026
has body: Consider the code below Table="USER" fields="("+'username'+")" values=('vishnu',) dbcon = MySQLdb.connect(...) insert_query="insert into %s%s values%%s"%(Table,fields) cursor=dbcon.cursor() cursor.execute(insert_query,(values,)) cursor.close() dbcon.commit() This code work differently for two system. In my laptop its working well but in my desktop it shows MYSQL syntax error. I can't resolve this issue? What will be the reason, i am using same version of python2.7.
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/82726047
answer count: 2
favorite count: 0
has comment: http://stackoverflow.com/comment/82726174
has answer: http://stackoverflow.com/a/49549061
score: 0

http://stackoverflow.com/comment/82798216
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47914388
score: 0
has text: If the `win32ui` module isn't found, it likely means it's not installed. Did you download a version for Python 3 (verses one for Python 2)? Did it install without errors? Also make sure you have the most current version. The website is https://github.com/mhammond/pywin32

http://stackoverflow.com/comment/82945769
type: QuestionComment
comment on: http://stackoverflow.com/q/47988583
has text: @RomanPerekhrest It becomes a tuple of lists.
score: 0
type: Comment

http://stackoverflow.com/a/48009907
has comment: http://stackoverflow.com/comment/82989014
has comment: http://stackoverflow.com/comment/82989184
has comment: http://stackoverflow.com/comment/82988271
score: 3
has comment: http://stackoverflow.com/comment/82988956
has comment: http://stackoverflow.com/comment/82988265
upvote count: 4
has comment: http://stackoverflow.com/comment/82988980
has comment: http://stackoverflow.com/comment/82989578
has comment: http://stackoverflow.com/comment/82988990
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82988930
answers question: http://stackoverflow.com/q/48009830
type: Answer
has comment: http://stackoverflow.com/comment/82988770
has body: The following is a purely arithmetic solution: def greatest_odd_number_below(n): return (n//2)*2 - 1 EDIT 1: For floating point inputs: # python 2 solution from math import ceil def greatest_odd_number_below_floats(n): return (int(ceil(n))//2)*2 - 1 EDIT 2: As @PM 2Ring pointed out in the comments, math.ceil returns an int in python 3, so you can remove the additional casting to int. # python 3 solution from math import ceil def greatest_odd_number_below_floats(n): return (ceil(n)//2)*2 - 1
accepted answer of: http://stackoverflow.com/q/48009830
has comment: http://stackoverflow.com/comment/82989337
downvote count: 1

http://stackoverflow.com/q/48003732
has comment: http://stackoverflow.com/comment/94234845
score: 12
has title: How to find how many Image Generated By ImageDataGenerator
tagged with: deep-learning
answer count: 1
downvote count: 0
tagged with: keras
favorite count: 0
has answer: http://stackoverflow.com/a/59723511
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/94234536
tagged with: image-processing
has comment: http://stackoverflow.com/comment/86586624
type: Question
has body: Hi I want to ask you a question about Keras ImageDataGenerator. Can I determine how many augmented image will create? or how can find training image set size after augmentation.In Keras documentation flow function description is : "Takes numpy data &amp; label arrays, and generates batches of augmented/normalized data. Yields batches indefinitely, in an infinite loop." But how many images generated ? For example the following code how many image generates ? Infinite ? from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img from matplotlib import pyplot import numpy as np datagen = ImageDataGenerator( rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='nearest') img=load_img('cat.1.jpg') x=img_to_array(img) x = x.reshape((1,) + x.shape) print x.shape h=datagen.flow(x)
linked to: http://stackoverflow.com/q/49783945
upvote count: 12

http://stackoverflow.com/comment/82714564
has text: Do you want the actual text of the `add_student` function?
comment on: http://stackoverflow.com/q/47874585
score: 0
type: Comment
type: QuestionComment

apache
tags question: http://stackoverflow.com/q/48006740
tag name: apache
tags question: http://stackoverflow.com/q/47883284
tags question: http://stackoverflow.com/q/47956126
tags question: http://stackoverflow.com/q/47868006
tags question: http://stackoverflow.com/q/47923412
tags question: http://stackoverflow.com/q/47898252
type: Tag
tags question: http://stackoverflow.com/q/47889297
tags question: http://stackoverflow.com/q/47906730
tags question: http://stackoverflow.com/q/47995000

http://stackoverflow.com/q/47889215
type: Question
has comment: http://stackoverflow.com/comment/82744614
has comment: http://stackoverflow.com/comment/82745377
answer count: 2
possible better answer: http://stackoverflow.com/a/47889275
has comment: http://stackoverflow.com/comment/82746305
has answer: http://stackoverflow.com/a/47889275
has answer: http://stackoverflow.com/a/47889891
has title: my script isn't reformatting my csv with all the data im getting just headers\\python 3
has comment: http://stackoverflow.com/comment/82744903
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: my script isn't reformatting my csv with all the data just headers. when i ran my code it just gave me the headers and the data goes missing im not sure why?, i want to make the output csv to have my requested headers with the data underneath import csv with open('motherwell.csv','r') as csv_file: csv_reader = csv.DictReader(csv_file) with open('stats.csv', 'w') as new_file: fieldnames = ['id','name','product','temperature','density','timestamp','water'] csv_writer = csv.DictWriter(new_file, fieldnames=fieldnames) csv_writer.writeheader() for line in csv_reader: del line['shortname','state','shape','pos_x','pos_y','datum',',max_work','min_work','offset_bottom','offset_volume','offset_level','roof_density','roof_weight','roof_start','roof_end','shell_insulated','shell_cte','shell_temperature','dimension_a','dimension_b','dimension_c','dimension_d','knee_forth','knee_third','knee_second','knee_first','suction_forth,','suction_third','suction_second','suction_first','rundown_forth','rundown_third','rundown_second','rundown_first','suction_low_forth','suction_low_third','suction_low_second','suction_low_first','rundown_low_forth','rundown_low_third','rundown_low_second','rundown_low_first','sll','slu','svl','suv','swlv','swuv','swll','swul','volume','innage','flow','pressure','maximum_volume',] csv_writer.writerow(line) here is the csv with the data: also a link to get the csv https://www.dropbox.com/sh/qdcl2lrrqj6sttb/AABo_AMGzFqetgRne_7XTPy7a?dl=0 "{'id': 1, 'name': '1001A', 'shortname': 'A', 'product': '14', 'state': 'Y', 'shape': 'cylinder', 'pos_x': '72', 'pos_y': '34', 'datum': '0', 'max_work': '21000', 'min_work': '0', 'offset_bottom': '0', 'offset_volume': '0', 'offset_level': '0', 'roof_density': '0', 'roof_weight': '0', 'roof_start': '0', 'roof_end': '0', 'shell_insulated': 'N', 'shell_cte': '0', 'shell_temperature': '0', 'shell_capacity': '0', 'shell_molecular': '0', 'shell_pressure': '0', 'shell_gtemp': '0', 'dimension_a': 22000, 'dimension_b': 76000, 'dimen…
accepted answer: http://stackoverflow.com/a/47889891
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82745686
score: 0

matplotlib
tags question: http://stackoverflow.com/q/47927095
tags question: http://stackoverflow.com/q/47863776
tags question: http://stackoverflow.com/q/47960611
tags question: http://stackoverflow.com/q/47990553
tags question: http://stackoverflow.com/q/47858632
tags question: http://stackoverflow.com/q/47903691
tags question: http://stackoverflow.com/q/47913994
tags question: http://stackoverflow.com/q/47980357
tags question: http://stackoverflow.com/q/47861245
tags question: http://stackoverflow.com/q/47859486
tags question: http://stackoverflow.com/q/47971925
tags question: http://stackoverflow.com/q/47947981
tags question: http://stackoverflow.com/q/48011502
tags question: http://stackoverflow.com/q/47964897
tags question: http://stackoverflow.com/q/47878009
tags question: http://stackoverflow.com/q/47858545
tags question: http://stackoverflow.com/q/47873133
tags question: http://stackoverflow.com/q/47930196
tags question: http://stackoverflow.com/q/47870440
tag name: matplotlib
tags question: http://stackoverflow.com/q/48014586
tags question: http://stackoverflow.com/q/47913115
tags question: http://stackoverflow.com/q/47996929
tags question: http://stackoverflow.com/q/47866857
tags question: http://stackoverflow.com/q/47913108
tags question: http://stackoverflow.com/q/47997772
tags question: http://stackoverflow.com/q/47950484
tags question: http://stackoverflow.com/q/47990579
tags question: http://stackoverflow.com/q/47921361
tags question: http://stackoverflow.com/q/47866996
tags question: http://stackoverflow.com/q/47984939
tags question: http://stackoverflow.com/q/47913300
tags question: http://stackoverflow.com/q/47913841
tags question: http://stackoverflow.com/q/48004752
tags question: http://stackoverflow.com/q/48000111
tags question: http://stackoverflow.com/q/48005727
tags question: http://stackoverflow.com/q/48003559
tags question: http://stackoverflow.com/q/47906209
tags question: http://stackoverflow.com/q/47952911
tags question: http://stackoverflow.com/q/47891830
tags question: http://stackoverflow.com/q/47962876
tags question: http://stackoverflow.com/q/47933745
tags question: http://stackoverflow.com/q/47933420
tags question: http://stackoverflow.com/q/47924382
tags question: http://stackoverflow.com/q/47916205
tags question: http://stackoverflow.com/q/47930211
tags question: http://stackoverflow.com/q/47998025
tags question: http://stackoverflow.com/q/47861490
tags question: http://stackoverflow.com/q/47863742
tags question: http://stackoverflow.com/q/47903676
tags question: http://stackoverflow.com/q/47915951
tags question: http://stackoverflow.com/q/47939588
tags question: http://stackoverflow.com/q/47885072
tags question: http://stackoverflow.com/q/47954059
tags question: http://stackoverflow.com/q/47948989
tags question: http://stackoverflow.com/q/47880072
tags question: http://stackoverflow.com/q/47906782
tags question: http://stackoverflow.com/q/47962917
tags question: http://stackoverflow.com/q/47906119
tags question: http://stackoverflow.com/q/47908429
tags question: http://stackoverflow.com/q/47984466
tags question: http://stackoverflow.com/q/47979486
tags question: http://stackoverflow.com/q/47870425
tags question: http://stackoverflow.com/q/47972386
tags question: http://stackoverflow.com/q/48012513
tags question: http://stackoverflow.com/q/47879645
tags question: http://stackoverflow.com/q/47967734
tags question: http://stackoverflow.com/q/47964551
tags question: http://stackoverflow.com/q/47892339
tags question: http://stackoverflow.com/q/47887414
tags question: http://stackoverflow.com/q/47963339
tags question: http://stackoverflow.com/q/47957314
tags question: http://stackoverflow.com/q/47924733
tags question: http://stackoverflow.com/q/47872845
tags question: http://stackoverflow.com/q/47871696
tags question: http://stackoverflow.com/q/47926794
tags question: http://stackoverflow.com/q/48013355
tags question: http://stackoverflow.com/q/47954453
tags question: http://stackoverflow.com/q/47877848
tags question: http://stackoverflow.com/q/47989506

http://stackoverflow.com/a/47964140
has body: etree is going to consume a lot of memory (yes, even with iterparse()), and sax is really clunky. However, pulldom to the rescue! from xml.dom import pulldom doc = pulldom.parse('large.xml') for event, node in doc: if event == pulldom.START_ELEMENT and node.tagName == 'special': # Node is 'empty' here doc.expandNode(node) # Now we got it all if is_valid_hh(node): ...do things... It's one of those libraries no one who did not have to use it seems to know about. Docs at e.g. https://docs.python.org/3.7/library/xml.dom.pulldom.html
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83146356
answers question: http://stackoverflow.com/q/47963080
downvote count: 0
has comment: http://stackoverflow.com/comment/83146262
has comment: http://stackoverflow.com/comment/82906312

http://stackoverflow.com/q/48001956
has answer: http://stackoverflow.com/a/48002001
has body: I would like to get the current date and time in the following format: 2017-12-27T15:20:11+05:30 How do I do it ? If I do: now = datetime.datetime.now() print now.isoformat() Then it comes out like this: 2014-09-26T16:34:40.278298
tagged with: python-3.x
has title: How to format the current date and time to include which timezone?
tagged with: python
type: UnansweredQuestion
type: Question
score: 0
answer count: 1

http://stackoverflow.com/comment/82737844
has text: What @timgeb is correct, please check that also, you're not returning anything
comment on: http://stackoverflow.com/q/47886088
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82941645
has text: You could download PhantomJS sources, fix headers case and then build a binary, but using a proxy to correct headers is probably a simpler solution.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47986007

http://stackoverflow.com/comment/82870524
type: Comment
comment on: http://stackoverflow.com/a/47950250
has text: I suggest using `while np.any(np.diff(np.sort(foo)) <= interval):` instead of list comprehension. Less shuffling of data types. Also, the OP wants the differences to be strictly greater than `interval`, hence <= in the rejection criterion.
score: 2
type: AnswerComment

http://stackoverflow.com/q/47885545
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47886422
has comment: http://stackoverflow.com/comment/82736862
type: Question
score: 0
answer count: 2
tagged with: pandas
has title: Generating a new variable/column in a data frame based on two rows of another variable/column
has answer: http://stackoverflow.com/a/47885752
has body: Context: I am working with Uniform Crime Report data, indexed by city(place). I am trying to merge/concat the years 2006-2016 Problem: Not all .csv's have a state column in front of the city name, and there are different numbers of cities in each file. Since there are duplicates in the city name column, merging without the second key is not possible (for me). My solution: I made a new variable = the first letter of each city name, and a dictionary "A":1, "B":2,..."Z":26. Then I made another column with the value associated with each first letter. The goal is to subtract row n from row (n+1) and evaluate result => 0, or evaluate the inequality row(n+1)=>row(n) I spent most of the day trying to do it in a list, such as: state = [] statenum = 1 for n in firstletter: if n+1 =&gt; n: state.append(statenum) else: statenum = statenum + 1 state.append(statenum) But I could not, for the life of me, figure out how to call the n+1 object in the list, rather than simply adding 1 to value of n. It just occurred to me to try and do it in a dataframe, but I could not get that to work either. I would be happy with a solution for either; it does not really need to be particularly efficient.
tagged with: python-3.x

http://stackoverflow.com/q/47921674
tagged with: opencv3.1
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82811104
type: Question
has comment: http://stackoverflow.com/comment/82810911
has body: I am working with template matching but i change picture distance program doesn't work Codes # -- coding: cp1254 -- import cv2 import numpy as np cap = cv2.VideoCapture(0) ret, frame = cap.read() template = cv2.imread('template.jpg',0) w, h = template.shape[::-1] x,y = 0,0 while(True): ret, frame = cap.read() i= cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) res = cv2.matchTemplate(i,template,3) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) top_left = max_loc bottom_right = (top_left[0] + w, top_left[1] + h) x = (top_left[0] + bottom_right[0])/2 y = (top_left[1] + bottom_right[1])/2 #Draw Rectangle Match if x&gt;0: p1=open('kn.txt','w') p1.write('p1') print "p1" p1.flush() p1.close() cv2.rectangle(frame, top_left, bottom_right, (255, 125, 125), 3) cv2.putText(frame, "["+ str(x)+","+str(y)+"]", (bottom_right[0]+10,bottom_right[1]+10), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,125,0), 2) cv2.imshow('cikis',frame) if cv2.waitKey(1) &amp; 0xFF == ord('q'): cap.release() break cv2.destroyAllWindows()
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82811321
tagged with: python
has title: OpenCV template matching does not work if the object is moved farther or closer to the camera
tagged with: opencv
tagged with: webcam
answer count: 0

http://stackoverflow.com/q/47888546
has comment: http://stackoverflow.com/comment/82743341
has title: minimum of values in pandas calculation
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/82743277
tagged with: python
upvote count: 2
has body: I want to convert a piece of python code I wrote earlier to pandas so it is directly done in dataframe instead of messing with csv files. I want to calculate the health of a device based on multiple values (attributes). Lets say I have the following df: A B C 0 7 NaN 8 1 3 3 5 2 8 1 7 3 NaN 0 3 4 8 2 7 And I want to calculate the health as follows: note that the def attributeHealth is still in the old form and not converted to pandas since that is the part where I get stuck and this is the code that was working with the csv library df['Health'] = attributeHealth(df['A'], 10, 0.4) * attributeHealth(df['B'], 5, 0.5) * attributeHealth(df['C'],2 ,0.8) * 100 def attributeHealth(name, weight, limit): if row[name] != 'NULL': attrHealth = 1 - min(int(row[name])*weight/100, limit) else: attrHealth = 1 return attrHealth I have tried reducing it to a single attribute first but it seems that I cannot use min() in this way: inputDF['health'] = 1 - min(inputDF['A']* 2/100, 0.7) Thanks in advance!
accepted answer: http://stackoverflow.com/a/47888740
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47888693
type: Question
answer count: 2
tagged with: min
tagged with: pandas
score: 2
possible better answer: http://stackoverflow.com/a/47888693
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/47888740

http://stackoverflow.com/q/47862070
accepted answer: http://stackoverflow.com/a/47879867
has comment: http://stackoverflow.com/comment/82689359
has comment: http://stackoverflow.com/comment/82690691
has comment: http://stackoverflow.com/comment/82723939
tagged with: python
has title: How to search a certain value in series python
has body: I've got a series:p 0 353.267439 1 388.483605 2 0.494685 3 1.347499 4 404.202001 5 6.163468 6 29.782820 7 28.972926 8 2.822725 9 0.000000 10 1.309716 11 1.309716 12 0.000000 13 0.000000 14 0.000000 15 0.000000 16 63.199779 17 62.669258 18 0.306850 19 0.000000 20 28.218308 21 32.078732 22 4.394789 23 0.995053 24 236.355502 25 172.802915 26 1.207798 27 0.174134 28 0.706518 29 0.922744 1666374 0.000000 1666375 0.000000 1666376 0.000000 1666377 0.000000 1666378 0.033375 1666379 0.033375 1666380 0.118138 1666381 0.118138 1666382 12.415525 1666383 12.415525 1666384 24.252089 1666385 0.270588 1666386 24.292072 1666387 12.415525 1666388 12.415525 1666389 0.000000 1666390 0.000000 1666391 0.000000 1666392 0.118138 1666393 0.118138 1666394 0.118138 1666395 0.000000 1666396 0.000000 1666397 0.000000 1666398 0.000000 1666399 0.000000 1666400 0.118138 1666401 0.000000 1666402 0.118138 1666403 0.118138 Name: Dis, Length: 1666404, dtype: float64 and I believe there is a value '4.74036126519e-07' in it I try some methods to find the value: p[p =='value'] or function: def find(s, el): for i in s.index: if s[i] == el: return i return None but they return nothing strangely, when I call: p[p ==0] it can return the index I wanna ask why and how to find value in series properly code: def haversine_np(lon1, lat1, lon2, lat2): lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2]) dlon = lon2 - lon1 dlat = lat2 - lat1 a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2 c = 2 * np.arcsin(np.sqrt(a)) km = 6367 * c return km def DisM(df,ID): df_user=df.loc[df['UserID'] == ID] p= haversine_np(df_user.Longitude.shift(), df_user.Latitude.shift(), df_user.ix[1:, 'Longitude'], df_user.ix[1:, 'Latitude']) p=p.iloc[1:] p=p.rename("Dis") return (p) p = DisM(df,1) for num in np.arange(2,4861): p= p.append(DisM(df,num)) p=p.reset_index(drop=True) df is a dataframe contain users' location information (longtitude latitude) and use haversine to count the distance betwee…
has comment: http://stackoverflow.com/comment/82691001
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82689465
type: Question
has comment: http://stackoverflow.com/comment/82691211
has comment: http://stackoverflow.com/comment/82706157
has comment: http://stackoverflow.com/comment/82724599
has comment: http://stackoverflow.com/comment/82690713
tagged with: search
score: 0
has comment: http://stackoverflow.com/comment/82724999
has answer: http://stackoverflow.com/a/47879867
answer count: 1
has comment: http://stackoverflow.com/comment/82690498
has comment: http://stackoverflow.com/comment/82713641
tagged with: series
has comment: http://stackoverflow.com/comment/82697319

python-requests
tags question: http://stackoverflow.com/q/47916315
tags question: http://stackoverflow.com/q/48014071
tags question: http://stackoverflow.com/q/47965573
tags question: http://stackoverflow.com/q/47869039
tags question: http://stackoverflow.com/q/47963287
tags question: http://stackoverflow.com/q/47910959
type: Tag
tags question: http://stackoverflow.com/q/48014240
tags question: http://stackoverflow.com/q/47978985
tags question: http://stackoverflow.com/q/47978661
tags question: http://stackoverflow.com/q/47948947
tags question: http://stackoverflow.com/q/47891056
tags question: http://stackoverflow.com/q/47960157
tags question: http://stackoverflow.com/q/47972958
tags question: http://stackoverflow.com/q/47961468
tags question: http://stackoverflow.com/q/47957480
tags question: http://stackoverflow.com/q/47890715
tags question: http://stackoverflow.com/q/47957951
tags question: http://stackoverflow.com/q/47900991
tags question: http://stackoverflow.com/q/47995349
tags question: http://stackoverflow.com/q/47897359
tags question: http://stackoverflow.com/q/47915107
tags question: http://stackoverflow.com/q/47973341
tags question: http://stackoverflow.com/q/47910547
tags question: http://stackoverflow.com/q/47966110
tags question: http://stackoverflow.com/q/47967881
tags question: http://stackoverflow.com/q/47884375
tags question: http://stackoverflow.com/q/47935006
tags question: http://stackoverflow.com/q/47932536
tags question: http://stackoverflow.com/q/47896933
tags question: http://stackoverflow.com/q/47926726
tags question: http://stackoverflow.com/q/47928768
tags question: http://stackoverflow.com/q/47874626
tags question: http://stackoverflow.com/q/47968108
tags question: http://stackoverflow.com/q/47941954
tags question: http://stackoverflow.com/q/47872964
tags question: http://stackoverflow.com/q/47938867
tags question: http://stackoverflow.com/q/47910752
tags question: http://stackoverflow.com/q/47956702
tags question: http://stackoverflow.com/q/47958928
tag name: python-requests
tags question: http://stackoverflow.com/q/47936244
tags question: http://stackoverflow.com/q/47995144
tags question: http://stackoverflow.com/q/47880624
tags question: http://stackoverflow.com/q/48000228
tags question: http://stackoverflow.com/q/47897996
tags question: http://stackoverflow.com/q/47918884
tags question: http://stackoverflow.com/q/47898368
tags question: http://stackoverflow.com/q/47944927
tags question: http://stackoverflow.com/q/47911622
tags question: http://stackoverflow.com/q/47880811
tags question: http://stackoverflow.com/q/47858650
tags question: http://stackoverflow.com/q/47856061
tags question: http://stackoverflow.com/q/47912246
tags question: http://stackoverflow.com/q/47945029

http://stackoverflow.com/comment/82972383
comment on: http://stackoverflow.com/q/47995981
type: Comment
has text: `sqlite3.OperationalError: database is locked` I could be totally off track here, but I recall sqlite is a single-process database, so it could just be that, if Chrome has opened it, sqlite doesn't want you to do it too.
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82701369
has text: You have two versions of python installed, python2.7 and python3.5. Is this different from what you expected?
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/47868174

http://stackoverflow.com/a/47897259
type: AcceptedAnswer
type: Answer
has body: Please make these changes: if (again == 1): control = True main=True user = ("yes")
answers question: http://stackoverflow.com/q/47897163
accepted answer of: http://stackoverflow.com/q/47897163
score: 0

http://stackoverflow.com/comment/82727356
type: Comment
has text: I want to place a solid answer, let's say the list is of length 5 and 6 items are selected, what color should the sixth item have?
comment on: http://stackoverflow.com/q/47880568
score: 0
type: QuestionComment

http://stackoverflow.com/a/47949315
has body: You can also try using itertools.cycle(): &gt;&gt;&gt; import itertools &gt;&gt;&gt; list1 = [1,2,3] &gt;&gt;&gt; list2 = [4] &gt;&gt;&gt; print([list(x) for x in zip(list1, itertools.cycle(list2))]) [[1, 4], [2, 4], [3, 4]]
answers question: http://stackoverflow.com/q/47948131
score: 0
type: Answer

http://stackoverflow.com/q/47965081
has answer: http://stackoverflow.com/a/47967229
has body: I am trying to fill quad that is generated by 4 lines with GL_LINES. However, when I try to fill the quad it only fills with triangle. This is the code that draws the lines: def SurfaceContour(self, vertices, edges): glBegin(GL_LINES) for edge in edges: for vertex in edge: glColor3fv((1.0, 0.0, 0.0)) glVertex3fv(vertices[vertex]) glEnd() This is the code that draws fills the quad: def Surfaces(self, vertices): glBegin(GL_QUADS) for i in range(4): glColor4f(1, 1, 1, 0.3) glVertex3fv(vertices[i ,:]) glEnd() This is the vertices matrix that I pass into: [[ 0. -20.23 7. ] [ 0. -20.23 -7. ] [ 100. -10. 5. ] [ 100. -10. -5. ]]
has answer: http://stackoverflow.com/a/47967209
accepted answer: http://stackoverflow.com/a/47967209
possible better answer: http://stackoverflow.com/a/47967229
type: AnsweredQuestion
score: 2
downvote count: 0
tagged with: opengl
has title: GL_QUAD draws triangle
tagged with: pyopengl
type: Question
upvote count: 2
answer count: 2
tagged with: opengl-compat
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/82880456
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/47953095
has text: @EricDuminil Well obviously! If they are asked to input their password, there is no need for any algorithm! Clearly if this were to be used in a real circumstance, the check would not simply be `== goal`, it would probably be another function of sorts that goes and does some hashing / encryption etc.

http://stackoverflow.com/comment/82710076
type: QuestionComment
has text: I suppose you'd need something like a `rolling.apply`, and pass a custom function that handles those negative values.
type: Comment
comment on: http://stackoverflow.com/q/47872305
score: 0

http://stackoverflow.com/q/47976845
tagged with: othello
answer count: 1
downvote count: 0
tagged with: keras
favorite count: 0
has title: Tensorflow loss is already low
tagged with: python
has answer: http://stackoverflow.com/a/47979477
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/47979477
upvote count: 1
tagged with: tensorflow
type: Question
has body: I'm doing an AI with reinforcement learning and i'm getting weird results, the loss shows like this: Tensorflow loss: https://i.sstatic.net/hispR.jpg And while it's training, after each game, it's playing against a random player and after a player with a weighted matrix, but it goes up and down: results: https://i.sstatic.net/mtWiS.jpg Basically i'm doing a reinforcement learning agent that learns to play Othello. Using E-greedy, Experience replay and deep networks using Keras over Tensorflow. Tried different architectures like sigmoid, relu and in the images shown above, tanh. All them have similar loss but the results are a bit different. In this exemple the agent is learning from 100k professional games. Here is the architecture, with default learning rate as 0.005: model.add(Dense(units=200,activation='tanh',input_shape=(64,))) model.add(Dense(units=150,activation='tanh')) model.add(Dense(units=100,activation='tanh')) model.add(Dense(units=64,activation='tanh')) optimizer = Adam(lr=lr, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0) model.compile(loss=LOSS,optimizer=optimizer) Original code: https://github.com/JordiMD92/thellia/tree/keras So, why i get these results? Now my input is 64 neurons (8*8 matrix), with 0 void square, 1 black square and -1 white square. Is it bad to use negative inputs?
tagged with: reinforcement-learning

http://stackoverflow.com/a/74251441
has body: To revert a 2D array of tuples representing the RGB components back to an image I've used this approach: from PIL import Image import numpy as np dt = np.dtype([('x', 'u1'), ('y', 'u1'), ('z', 'u1')]) Image.fromarray(im_arr.astype(dt), 'RGB') where im_arr is your 2D array of RGB tuples. In my case I've used uint8 ('u1') to represent the R, G, B components; if your image components are of a different type adjust the dtype - need to experiment. Similar question here: Show a 2d numpy array where contents are tuples as an image
answers question: http://stackoverflow.com/q/47944089
downvote count: 1
score: -1
type: Answer
upvote count: 0

http://stackoverflow.com/comment/82865881
comment on: http://stackoverflow.com/q/47947889
has text: @Galen You're right. I initialized it wrong
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48002297
has title: How to concatenate int with str type in Jinja2 template?
tagged with: python
tagged with: templates
has answer: http://stackoverflow.com/a/48002358
type: UnansweredQuestion
score: 23
tagged with: jinja2
upvote count: 23
type: Question
has answer: http://stackoverflow.com/a/56416851
has body: I want to set a variable in jinja2 template which is a combination of string and a interger value. Code is as follows: {% set the_var = 'Wan_Links.WAN_' + i + '.wan_link_type' %} Here "i" is a dynamic value and is of type int. When I run the above code I get the below error: TypeError: cannot concatenate 'str' and 'int' objects. The expected output is the_var = Wan_Links.WAN_0.wan_link_type (i.e. i=0). Can anyone tell me how can I get this done?
answer count: 2
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/83462513
comment on: http://stackoverflow.com/a/48159986
type: AnswerComment
has text: Just to be totally clear to answer your additional question of why K is different. Imagine you calibrate using I1 and this has a K matrix with a focal length of f1. Let's say the homography H from I1 to I2 was something simple like an image rescaling by a factor s (it probably isn't but lets just use this as an example). The focal length for I2 would change! Specifically its focal length f2 would be f2=s x f1.
score: 0
type: Comment

http://stackoverflow.com/a/47972705
downvote count: 1
accepted answer of: http://stackoverflow.com/q/47972613
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/47972613
upvote count: 2
score: 1
has body: Is is 'alright? Yes, the license allows you to distribute .pyc files. Is is 'effective'? It will most likely be unnecessary, as there will be no commercial reason to copy your work. If it is super good, people will de-compile or write similar games in another language. See jonrsharpe's link. Is is intended? The main purpose of .pyc files is to avoid unnecessarily re-compiling Python code by caching the result.

http://stackoverflow.com/q/47898473
type: UnansweredQuestion
tagged with: datetime
has comment: http://stackoverflow.com/comment/82763747
tagged with: django
tagged with: python
has body: class Registration(models.Model): requester_first_name = models.CharField("First name", max_length=50) requester_last_name = models.CharField("Last name", max_length=50) requester_email = models.CharField("Email", max_length=50) requester_phone = models.CharField("Mobile", max_length=20) requester_title = models.CharField("Title", max_length=50) registration_date = models.DateTimeField(default=timezone.now) this is my model I have imported "from django.utils import timezone" and also in settings I have mentioned DATETIME_FORMAT = 'j N Y, P'
type: Question
has title: I am getting timestamp as 2017-12-16 06:32:34.715731+00:00, I want it in the format of 2017-12-16 06:32:34
tagged with: postgresql
score: 0
has comment: http://stackoverflow.com/comment/82769999
has comment: http://stackoverflow.com/comment/82763764
linked to: http://stackoverflow.com/q/1180372
answer count: 0

http://stackoverflow.com/comment/82983728
comment on: http://stackoverflow.com/a/48007656
score: 1
has text: Wow. I checked active BLAS library being used by numpy and then setting variable with `export OMP_NUM_THREADS="4";` before running the script did the trick. Thank you so much!
type: AnswerComment
type: Comment

http://stackoverflow.com/a/47881210
type: Answer
accepted answer of: http://stackoverflow.com/q/47878597
score: 1
answers question: http://stackoverflow.com/q/47878597
upvote count: 1
downvote count: 0
has body: If you're looking for a case in the wild, here's one from cpython itself (setting the global variable _ after evaluating and displaying an interactive statement). This is called when running the interpreter interactively -- for example: &gt;&gt;&gt; 999 * 999 998001 &gt;&gt;&gt; _ 998001 &gt;&gt;&gt; import builtins &gt;&gt;&gt; builtins._ 998001 Generally speaking though, you should never do this in a library / application. Adding magical super-globals will not only confuse linters but also future maintainers who expect a certain set of things to be present as builtins.
has comment: http://stackoverflow.com/comment/82729729
type: AcceptedAnswer

http://stackoverflow.com/a/47931413
upvote count: 1
has body: You can remove rows like: import pandas as pd import numpy as np df.loc[df.x&gt;=3,:] You can also use conditions using numpy logical_and and logical_or if you have upper and lower limit df = df.loc[np.logical_and(dd.x&lt;=3,df.x&lt;=0),:] You can also use ~ df.loc[~df.x.isin([1,2]),:]
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/47931248
score: 1

http://stackoverflow.com/q/47925216
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: c++
has body: I'm trying to stream the data from an ultrasonic rangefinder on an Arduino to my laptop. I seem to be having an issue with getting the new value from the Arduino. When I launch the Python script it starts printing the data just like I hoped. However this data does not change when I change the distance the sensor sees, it's almost like the serial.readline() is stuck on one of the first values. I'm new to this serial communication stuff so any help is greatly appreciated! The code is below and for sanity I did check that the sensor is working with the serial monitor in the Arduino IDE. import numpy import serial import time import sys import cv2 import pickle #set up the camera stuff cap = cv2.VideoCapture(0) #container for images images=[] #container for distances distances=[] #first frame number frame_num=1 #setup the serial connection and pause to establish it ser = serial.Serial('/dev/cu.usbmodem1421', 9600,timeout=1) time.sleep(5) while True: try: #grab and image ret,frame=cap.read() #grab the distance distance=ser.readline() print(distance) #process the image to a gray and 1241,376 #gray=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #gray_resized=cv2.resize(gray,(1241,376)) #cv2.imshow("FRAME",gray_resized) #print(distance) #images.append([frame_num,gray_resized]) #distances.append([frame_num,distance]) #ser.flush() except KeyboardInterrupt: #pickle.dump( images, open( "save.p", "wb" ) ) #pickle.dump( distances, open( "save.p", "wb" ) ) sys.exit() Arduino code: // defines pins numbers const int trigPin = 7; const int echoPin = 8; // defines variables long duration; int distance; void setup() { pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output pinMode(echoPin, INPUT); // Sets the echoPin as an Input Serial.begin(9600); // Starts the serial communication delayMicroseconds(50); } void loop() { // Clears the trigPin digitalWrite(trigPin, LOW); delayMicroseconds(2); // Sets the trigPin on HIGH state for 10 micro seconds digitalWrite(trigPin, HIGH); delayMicrosecon…
has answer: http://stackoverflow.com/a/47929236
downvote count: 0
score: 1
tagged with: arduino
has comment: http://stackoverflow.com/comment/82823375
has comment: http://stackoverflow.com/comment/82823233
has comment: http://stackoverflow.com/comment/82823581
type: Question
has comment: http://stackoverflow.com/comment/82818059
has title: Pyserial not getting new value from Arduino
tagged with: pyserial
upvote count: 1

http://stackoverflow.com/a/47874210
accepted answer of: http://stackoverflow.com/q/47874091
downvote count: 0
score: 1
type: AcceptedAnswer
upvote count: 1
answers question: http://stackoverflow.com/q/47874091
has body: The problem is that itertools.permutations produces a tuple. You need to convert it to string. Something like this: for word in itertools.permutations( list_of_letters,i): word = u''.join(word) print word
type: Answer

http://stackoverflow.com/comment/82785862
type: Comment
has text: It would be interesting to pickle your entire `nb` class and see what the performance is like.
comment on: http://stackoverflow.com/a/47907461
score: 0
type: AnswerComment

http://stackoverflow.com/q/47943336
has answer: http://stackoverflow.com/a/47958145
upvote count: 1
has comment: http://stackoverflow.com/comment/82885546
has comment: http://stackoverflow.com/comment/82884164
type: Question
tagged with: rpy2
has comment: http://stackoverflow.com/comment/82883328
tagged with: http://stackoverflow.com/tag/r
has title: R, rtools and rpy2
answer count: 1
has body: Here is my setup. I installed R-3.2.0 from source using ./configure --enable-R-shlib --enable-R-static-lib --enable-BLAS-shlib --prefix=/home/fpinto then make &amp;&amp; make install. That's because I don't have root privileges. After that, I installed python-2.7.14 from source, and setuptools-38.2.4 and pip-9.0.1 from the sources. Everything was suppossed to be fine and I could use python2 -m pip install to install locally any package. Finally, I installed rtools with the last command. However, when I try to import rtools the output is Python 2.7.14 (default, Dec 20 2017, 01:10:08) [GCC 5.3.1 20160406 (Red Hat 5.3.1-6)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import rtools /home/fpinto/lib/python2.7/site-packages/rpy2-2.8.6-py2.7-linux-x86_64.egg/rpy2/rinterface/__init__.py:186: RRuntimeWarning: Error in dyn.load(file, DLLpath = DLLpath, ...) : unable to load shared object '/home/fpinto/lib64/R/library/stats/libs/stats.so': libRlapack.so: cannot open shared object file: No such file or directory warnings.warn(x, RRuntimeWarning) /home/fpinto/lib/python2.7/site-packages/rpy2-2.8.6-py2.7-linux-x86_64.egg/rpy2/rinterface/__init__.py:186: RRuntimeWarning: During startup - warnings.warn(x, RRuntimeWarning) /home/fpinto/lib/python2.7/site-packages/rpy2-2.8.6-py2.7-linux-x86_64.egg/rpy2/rinterface/__init__.py:186: RRuntimeWarning: Warning message: warnings.warn(x, RRuntimeWarning) /home/fpinto/lib/python2.7/site-packages/rpy2-2.8.6-py2.7-linux-x86_64.egg/rpy2/rinterface/__init__.py:186: RRuntimeWarning: package ‘stats’ in options("defaultPackages") was not found warnings.warn(x, RRuntimeWarning)` Looking for a solution, people posted to look for R CMD ldd /home/fpinto/lib64/R/library/stats/libs/stats.so with the output: linux-vdso.so.1 =&gt; (0x00007ffd56bd1000) libRlapack.so =&gt; /home/fpinto/lib64/R/lib/libRlapack.so (0x00007f509d1fe000) libRblas.so =&gt; /home/fpinto/lib64/R/lib/libRblas.so (0x00007f509cfd0000) lib…
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/82884174
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82856305
has comment: http://stackoverflow.com/comment/82883343
score: 1

sockets
tags question: http://stackoverflow.com/q/47891852
tags question: http://stackoverflow.com/q/47876945
tags question: http://stackoverflow.com/q/47933042
tags question: http://stackoverflow.com/q/47939607
tags question: http://stackoverflow.com/q/47913692
tags question: http://stackoverflow.com/q/47979490
tags question: http://stackoverflow.com/q/48004504
tags question: http://stackoverflow.com/q/47970321
tags question: http://stackoverflow.com/q/47860238
tags question: http://stackoverflow.com/q/47999929
tags question: http://stackoverflow.com/q/47936365
type: Tag
tags question: http://stackoverflow.com/q/47872743
tags question: http://stackoverflow.com/q/47898250
tags question: http://stackoverflow.com/q/47857654
tags question: http://stackoverflow.com/q/47916373
tags question: http://stackoverflow.com/q/47858503
tags question: http://stackoverflow.com/q/47959093
tag name: sockets
tags question: http://stackoverflow.com/q/47928451
tags question: http://stackoverflow.com/q/47966461
tags question: http://stackoverflow.com/q/47927940
tags question: http://stackoverflow.com/q/47967591
tags question: http://stackoverflow.com/q/47900798
tags question: http://stackoverflow.com/q/47979865

variables
tags question: http://stackoverflow.com/q/47930021
tag name: variables
tags question: http://stackoverflow.com/q/47981918
tags question: http://stackoverflow.com/q/47957954
tags question: http://stackoverflow.com/q/47990512
tags question: http://stackoverflow.com/q/47915933
tags question: http://stackoverflow.com/q/47999233
tags question: http://stackoverflow.com/q/47947412
type: Tag
tags question: http://stackoverflow.com/q/47957700
tags question: http://stackoverflow.com/q/47933656
tags question: http://stackoverflow.com/q/47942306
tags question: http://stackoverflow.com/q/47917309
tags question: http://stackoverflow.com/q/47926650
tags question: http://stackoverflow.com/q/47935375
tags question: http://stackoverflow.com/q/47892321
tags question: http://stackoverflow.com/q/47930669
tags question: http://stackoverflow.com/q/47896006
tags question: http://stackoverflow.com/q/47888548
tags question: http://stackoverflow.com/q/47946616
tags question: http://stackoverflow.com/q/47919272
tags question: http://stackoverflow.com/q/47984141
tags question: http://stackoverflow.com/q/47995054
tags question: http://stackoverflow.com/q/47910573

http://stackoverflow.com/comment/82873762
type: QuestionComment
score: 0
has text: I thought i provided enough information, anyway thanks for your time :)
comment on: http://stackoverflow.com/q/47948989
type: Comment

http://stackoverflow.com/q/47947828
type: Question
accepted answer: http://stackoverflow.com/a/54913306
tagged with: matplotlib
has body: I'm trying to embed multiple matplotlib plots in a multi-column layout in a PyQt GUI. At first sight I succeed in setting up the layout as wanted but when moving the mouse over any of the canvasses they change size and 'flicker'. When pressing the zoom button on the toolbar this becomes more pronounced. For each matplotlib canvas I have connected a toolbar. If I do not connect the toolbars the problem does not appear. I have tried arranging the toolbars and canvases several ways - with a QGridLayout or nested QVBoxLayouts and QHBoxLayouts. Either way the problem appears if there are plots along side each other. If I put all plots in a single column it does not. I have tried this in Python 3.6 in Windows (Anaconda 5.0.1) with PyQt4 and Python 3.5.2 in Linux (KDE Neon 64 bit) and with both PyQt4 and PyQt5 (v. 5.7.1), matplotlib 1.5.1 but with the same result. I have also tried using add_axes instead of add_subplot. Can someone help me understand what is causing this or find some kind of workaround? I can not use matplotlib subplots. from PyQt5 import QtCore, QtGui, QtWidgets from matplotlib.figure import Figure from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar class Window(QtWidgets.QWidget): def __init__(self): super(Window, self).__init__() figure1 = Figure() figure2 = Figure() figure3 = Figure() figure4 = Figure() canvas1 = FigureCanvas(figure1) canvas2 = FigureCanvas(figure2) canvas3 = FigureCanvas(figure3) canvas4 = FigureCanvas(figure4) ax1 = figure1.add_subplot(111) ax2 = figure2.add_subplot(111) ax3 = figure3.add_subplot(111) ax4 = figure4.add_subplot(111) toolbar1 = NavigationToolbar(canvas1, self) toolbar2 = NavigationToolbar(canvas2, self) toolbar3 = NavigationToolbar(canvas3, self) toolbar4 = NavigationToolbar(canvas4, self) mainLayout = QtWidgets.QGridLayout() mainLayout.addWidget(toolbar1,0,0) mainLayout.addWidget(toolbar2,0,1) mainLayo…
tagged with: pyqt
has comment: http://stackoverflow.com/comment/82894220
answer count: 1
downvote count: 0
has title: Multiple embedded matplotlib canvases in pyqt change size on mouse over
favorite count: 0
has answer: http://stackoverflow.com/a/54913306
tagged with: python
has comment: http://stackoverflow.com/comment/82867557
has comment: http://stackoverflow.com/comment/82873780
has comment: http://stackoverflow.com/comment/82880577
type: AnsweredQuestion
score: 1
upvote count: 1

http://stackoverflow.com/q/47860850
has comment: http://stackoverflow.com/comment/82686536
has comment: http://stackoverflow.com/comment/82686598
answer count: 2
has body: I have list like below (in this example,it represent as list,but this is need not to be given as list) age=[3,4,5,6] sex=[1,2] limit=[3,4] I would like to create dataframe which has every combination. but the 'limit' column is more than 'age' columns. So my desired result is like this. age sex limit 3 1 3 3 1 4 4 1 4 3 2 3 3 2 4 4 2 4 How can I get this result?
upvote count: 0
has title: How to create dataframe in python
score: -4
accepted answer: http://stackoverflow.com/a/47860999
downvote count: 4
tagged with: pandas
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82686538
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47861283
tagged with: python
has answer: http://stackoverflow.com/a/47860999
possible better answer: http://stackoverflow.com/a/47861283

http://stackoverflow.com/a/47983400
answers question: http://stackoverflow.com/q/47983239
has body: text = "hola esto es una prueba donde esto busca la siguiente linea de esto" brk = "esto" for i, texto in enumerate(text.split(brk)): if i &gt; 0: print( texto.split()[0] if len(texto.split()) &gt; 0 else '') And now you just have to change the text and the break work
type: Answer
score: 0

http://stackoverflow.com/a/47956328
type: Answer
answers question: http://stackoverflow.com/q/47918681
has body: I figured it out on my own. Apparently, tensorflow will throw these low-level errors whenever it doesn't like the data that's coming in - for example, if it sees a value that is not on the vocabulary list or an nan. I was expecting a more meaningful error message, but apparently, it's more low-level than I thought - I need to do my own due diligence on the data before feeding it to a classifier for training.
score: 0

serverless-framework
tag name: serverless-framework
tags question: http://stackoverflow.com/q/47990383
type: Tag

apache-superset
tags question: http://stackoverflow.com/q/47990985
tag name: apache-superset
tags question: http://stackoverflow.com/q/47930871
type: Tag
tags question: http://stackoverflow.com/q/47920193

http://stackoverflow.com/comment/110592899
has text: Because it does not have packaging tools, the `+` button is disabled for me. Can't install anything.
type: Comment
score: 8
comment on: http://stackoverflow.com/a/50543463
type: AnswerComment

http://stackoverflow.com/comment/82961418
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47996516
has text: I think default username guy did a pretty good job of explaining it. You basically iterate over the same pair of elements twice, doing, and undoing the same operation at different stages. The solution, as the answer shows, is to iterate over the upper triangular indices _only_!

http://stackoverflow.com/a/47956517
type: Answer
answers question: http://stackoverflow.com/q/47956487
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47956487
has body: Removing whitespace could help: if hash.strip() == hash2.strip():
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/82754141
score: 0
comment on: http://stackoverflow.com/q/47893774
type: QuestionComment
type: Comment
has text: It would be very helpful if you could provide a example case of real input and expected output.

http://stackoverflow.com/comment/82817073
has text: Now that's more helpful, thank you.
type: Comment
comment on: http://stackoverflow.com/q/47922274
score: 0
type: QuestionComment

http://stackoverflow.com/q/47996766
has title: Importing to a list from a txt file
has body: numbers.txt: 5 6 3 8 9 10 I want to create a list from a numbers.txt, my list should be [[5,6],[3,8],[9,10] But I keep getting \t(between numbers) and \n(at the end, ex. 10\n etc.) in the output. How can I fix that? I should be getting [[5,6], [3,8], [9,10]] My code is: file=open("numbers.txt","r") l=[] for line in file: l.append(line.split(',')) print(l) thanks(note: tab is used between two numbers in every line)
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/82961605
has answer: http://stackoverflow.com/a/47996874
linked to: http://stackoverflow.com/q/7395542
has answer: http://stackoverflow.com/a/47996849
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47997933
tagged with: python
has answer: http://stackoverflow.com/a/47996789
has comment: http://stackoverflow.com/comment/82961627
answer count: 4
upvote count: 2
type: UnansweredQuestion
score: 1

http://stackoverflow.com/comment/83026638
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48026695
has text: @AlessandroPagliaro Admittedly, one TFR seems like the obvious way to manage a dataset. Makes more sense than rewriting for every new random split. I would add that restriction to your question. Meanwhile I'll look into it.

http://stackoverflow.com/q/47951486
score: 1
has comment: http://stackoverflow.com/comment/83577796
upvote count: 1
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/82872593
type: Question
tagged with: logistic-regression
has comment: http://stackoverflow.com/comment/82889392
tagged with: ipython
has comment: http://stackoverflow.com/comment/82872878
downvote count: 0
has body: I've followed Andrew Ng's machine learning course and tried to reproduce some of the examples in python SciKit. I'm trying to understand the effect of regulation parameter C. The problem I'm constantly running into is easiest to visualise with the following: for c in range(1,10): c = c/10. print( c ) classifier = LogisticRegression(C=c , max_iter=10000) classifier.fit(X_train, y_train) y_pred = classifier.predict(X_test) print(metrics.accuracy_score(y_test, y_pred)) I'm expecting to see higher accuracy with lower values of C. However, the results I'm getting are a bit biased: 0.1 .. 0.9 [0.77653631284916202, 0.77653631284916202, 0.77653631284916202, 0.77653631284916202, 0.77653631284916202, 0.77653631284916202, 0.77653631284916202, 0.77653631284916202, 0.77653631284916202] Running this outside the loop: classifier = LogisticRegression(C=0.0001,max_iter=10000) classifier.fit(X_train, y_train) y_pred = classifier.predict(X_test) metrics.accuracy_score(y_test, y_pred) results in 0.77653631284916202 as well. Kernel restart seems to be the only way to "reset" the classifier. After restart and loading of the data, running the code above gives the expected higher value: 0.8044692737430168. Is this expected behaviour? Or am I abusing python/scikit? I'm on osx 10.13.2. Tried this in IPython directly from terminal as well the (Anaconda) Spyder and (Anaconda) Notebook Jypiter (Anaconda2-5.0.1 and Anaconda3-5.0.1). All packages are up-to-date. Edit: Upon request, the complete code below. Train.csv can be downloaded from Kaggle Titanic dataset. import numpy as np import matplotlib.pyplot as plt import pandas as pd dataset = pd.read_csv('train.csv') from sklearn import preprocessing le = preprocessing.LabelEncoder() dataset['Sex'] = le.fit_transform(dataset['Sex']) le2 = preprocessing.LabelEncoder() dataset['Embarked'] = le2.fit_transform(dataset['Embarked'].astype(str) ) # remove NaN in age coloumn imputer = preprocessing.Imputer(missing_values = 'NaN', strategy = 'mean', axis =…
tagged with: scikit-learn
favorite count: 0
has comment: http://stackoverflow.com/comment/82913640
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82902799
tagged with: python
has comment: http://stackoverflow.com/comment/82913558
has comment: http://stackoverflow.com/comment/82872458
has comment: http://stackoverflow.com/comment/82872611
answer count: 0
has title: python sklearn.linear_model LogisticRegression weird behaviour inside a loop

http://stackoverflow.com/comment/82874747
type: QuestionComment
score: 0
has text: @ImportanceOfBeingErnest I don't understand what you mean by "the coordinates you want to interpolate on". what is the difference between those coordinates and the coordinates in my arrays?
comment on: http://stackoverflow.com/q/47952283
type: Comment

http://stackoverflow.com/comment/82715124
type: QuestionComment
score: 0
has text: @unutbu, i think your comment make sense. Based on your input i did 2 senario: 1. execute both .py files separately in CMD, both files run succesfully without error, both python executables are same: 'C:\Users\Breda\AppData\Local\Programs\Python\Python36\python.exe' 2. Compile GUI.py in Pycharm succesfully, but failed when click button . Error: "GUI.py python executable C:\Users\Breda\Anaconda3\python.exe. test.py python executable C:\Users\Breda\AppData\Local\Programs\Python\Python36\python.exe. 。。。 ModuleNotFoundError: No module named 'scipy'
type: Comment
comment on: http://stackoverflow.com/q/47869843

http://stackoverflow.com/comment/82966832
comment on: http://stackoverflow.com/a/47959931
type: Comment
score: 0
type: AnswerComment
has text: Hmm, it's actually `('en_US', 'UTF-8')` and `UTF-8`.

http://stackoverflow.com/q/47878386
has answer: http://stackoverflow.com/a/62186717
has body: Inside this Django tutorial i'm learning to create a blog site. Right now, we are at the point where we are using the Django ORM to interact with the database. I was following every step and i hit a wall at queryset, where the item name isn't showing up, and this was after i did this: def __str__(self): return self.title the output that i get when i type Narticle.objects.all() is queryset Narticle:Narticle object(1) instead of &lt;queryset [&lt;Narticle: 'hello world']&gt; my steps are below this model: my model for narticle is from django.db import models class Narticle(models.Model): title= models.CharField(max_length=100) slug= models.SlugField() body= models.TextField(max_length= 100) date=models.DateTimeField(auto_now_add= True) i entered the following on the command line: from narticle.model import Narticle i typed Narticle and i got &lt;class 'narticle.models.Narticle' &gt; i then entered the following Narticle.objects.all() and i got &lt;queryset[]&gt; i then typed narticle= Narticle() then narticle which gave me Narticle: Narticle object(none) i then typed narticle.title = "hello world" which was followed by Narticle.objects.all() Which gave me &lt; queryset [&lt;Narticle: Nartice object (1)&gt;]&gt; i typed narticle.save() i then exited command line,and then in models.py of narticle i typed def __str__(self): return self.title i then went back to command line and repeated the process of importing Narticle Then i typed Narticle.objects.all() which gave me &lt; queryset [&lt;Narticle: Nartice object (1)&gt;]&gt; instead of &lt;queryset [&lt;Narticle: 'hello world']&gt; oh and why is it that the word "none", and then (1), when i make an entry'like this &lt;Narticle: Narticle object (none)&gt; or in case of an entry &lt;Narticle: Narticle object (1)&gt; instead of &lt;Narticle: Narticle object&gt;
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/61192357
has title: title not showing up in queryset when __str__ method was used (django ORM)
has comment: http://stackoverflow.com/comment/82723679
tagged with: python
has comment: http://stackoverflow.com/comment/82762797
type: UnansweredQuestion
score: 1
upvote count: 1
tagged with: django
has comment: http://stackoverflow.com/comment/82723476
has comment: http://stackoverflow.com/comment/82723750
type: Question
answer count: 2

http://stackoverflow.com/comment/82792261
type: QuestionComment
has text: @Paul I was thinking along the lines that I should be able go the node in A and then get me the associated node in the other graph B. I hope that makes sense
comment on: http://stackoverflow.com/q/47901544
score: 0
type: Comment

http://stackoverflow.com/a/47970850
type: Answer
has body: You are assigning link to list and printing in each iteration, in each iteration you assign you will overwrite previous list. Instead you can append the links to list and then print it to your get desire result as below: ciao = [] for article in soup.find_all("a", {"style": "height:81px;"}): if article.has_attr("href"): # this if condition is not necessary but I recommand it while scraping so if a tag without href attribute won't throw an exception ciao.append(article.get("href")) print (ciao) If you don't want to use the list in future and just print the link you can just use print function with end=', ' like print(article.get("href")) in for loop. A one liner with list comprehension: ciao=[article.get("href") for article in soup.find_all("a", {"style": "height:81px;"}) if article.has_attr("href")]
answers question: http://stackoverflow.com/q/47970818
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82911147
has comment: http://stackoverflow.com/comment/82911155
downvote count: 0
has comment: http://stackoverflow.com/comment/82911169

http://stackoverflow.com/q/47889999
has body: I trained my CNN, with gray scale images of size 150x150, and the training went without having any errors, however, whenever I try to run the model.predict() function I get this error : expected convolution2d_input_1 to have 4 dimensions, but got array with shape (150, 150, 1) even though I do the exact same preprocessing for the images I pass to the predict function as the images I used to train the CNN. and they have a size of 150x150x1 just like my input shape in the CNN and just like the shape of the images I used to train the CNN with. here is my CNN: model = Sequential() model.add(Conv2D(32, 3, 3, input_shape=(150, 150, 1), activation = 'relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(32, 3, 3, activation = 'relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(64, 3, 3, activation = 'relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(64, activation = 'relu')) model.add(Dropout(0.5)) model.add(Dense(1, activation = 'softmax')) The input is of size 150x150x1, and the expected input my CNN says it needs is (None, 150, 150, 1) I have been trying to solve this issue for days now yet no luck whatsoever.
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47890283
tagged with: deep-learning
answer count: 1
downvote count: 0
tagged with: keras
favorite count: 0
tagged with: python
score: 2
tagged with: conv-neural-network
upvote count: 2
has title: expected convolution2d_input_1 to have 4 dimensions, but got array with shape (150, 150, 1)
has answer: http://stackoverflow.com/a/47890283
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/82746332

http://stackoverflow.com/comment/82764385
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47898294
type: QuestionComment
has text: Now I see, you want the errors as well.

http://stackoverflow.com/comment/82782540
type: Comment
has text: I put plt.cla() at the end of the function and worked!!! Thanks a lot man. Do you have any suggestion for the fact to add a worksheet inside the same xlsx file? If I would do that, I would call the file with one only name and so removing index+'.xls'. But when running the loop, it's not adding worksheets, but writing on the existing one and at the end I have the last one ran. Myabe is a feature of the module xlsxwirte? Thanks again
comment on: http://stackoverflow.com/q/47907427
type: QuestionComment
score: 0

qpropertyanimation
tag name: qpropertyanimation
tags question: http://stackoverflow.com/q/47982890
tags question: http://stackoverflow.com/q/47997230
type: Tag

websocket
tags question: http://stackoverflow.com/q/47914176
tags question: http://stackoverflow.com/q/47955736
tags question: http://stackoverflow.com/q/47973910
type: Tag
tags question: http://stackoverflow.com/q/47875007
tags question: http://stackoverflow.com/q/47943009
tags question: http://stackoverflow.com/q/47896355
tags question: http://stackoverflow.com/q/47933748
tag name: websocket

http://stackoverflow.com/comment/82743249
type: QuestionComment
comment on: http://stackoverflow.com/q/47888054
type: Comment
has text: @StevenRumbalski I agree, but you know that I meant `' '` literal space:)
score: 0

http://stackoverflow.com/comment/84978263
comment on: http://stackoverflow.com/a/47954419
has text: That is just great
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/82842436
type: AnswerComment
comment on: http://stackoverflow.com/a/47920146
has text: @MarkTolonen i did not understand your comment
type: Comment
score: 0

http://stackoverflow.com/q/47966805
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47966903
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/47966872
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/82903182
has answer: http://stackoverflow.com/a/47966872
tagged with: python
has body: It's about Rasberry PI, but in this case, it doesn't matter. I have 9 functions like: for_1..9() These functions turn on one part of a 4-digit LED display. But I want to use a button for every number on this display, so I want to call different functions every time when I push the button. No idea how can it be. Functions look like this: def for_1(): GPIO.output(15.HIGH) GPIO.output(18.HIGH) .... Smth like this: if Pin.input(number of pin): for i in range(0, 9): for_1() #next time in loop has to be next function
answer count: 3
has answer: http://stackoverflow.com/a/47966903
tagged with: loops
has answer: http://stackoverflow.com/a/47966877
has title: How to call different functions in loop Python
tagged with: algorithm

http://stackoverflow.com/q/48008390
has answer: http://stackoverflow.com/a/48008670
type: Question
has answer: http://stackoverflow.com/a/48009035
downvote count: 0
favorite count: 0
answer count: 3
has comment: http://stackoverflow.com/comment/82985198
tagged with: python
accepted answer: http://stackoverflow.com/a/48008670
has comment: http://stackoverflow.com/comment/82985276
tagged with: parsing
upvote count: 1
has comment: http://stackoverflow.com/comment/82984992
has comment: http://stackoverflow.com/comment/82985342
has body: I'm trying to select a specific key in this code which is the 163, 203 &amp; 13. Basically, each time, my function runs, I'll have one of these 3 codes stock in a variable and I can't figure out how to parse a specific element in a Json file. I'd like to make a loop who stops for example at the key '203' and return me the result of it. with open('data.json') as data_file: data = json.load(data_file, object_pairs_hook=OrderedDict) for key, value in data.items(): id = '203' id_value = value['payload']['price'] pack = id_value[id] print(pack) #pack should be returning the value of the key '203' Here's the JSON. The JSON is divided in 3 parts, each part starts with a random key, that I don't know and, if you look on the JSON, after the payload, there is the price and then the id (e.g. '203'). I need to get the value of this id. { "a506b5686": { "status": { "message": "Ok", "code": 0, "user": { "isBanned": false, "isNotConfirmed": false } }, "payload": { "vat": 0, "price": { "163": { "100": { "country_id": "CN", "product_price": 16.54, "shipment_price": 2.31, "quantity": 100, "batchsize_id": 60348 }, "200": { "country_id": "CN", "product_price": 23.17, "shipment_price": 2.31, "quantity": 200, "batchsize_id": 60354 }, "300": { "country_id": "CN", "product_price": 28.29, "shipment_price": 2.31, "quantity": 300, "batchsize_id": 60360 }, "400": { "country_id": "CN", "product_price": 34.11, "shipment_price": 2.31, "quantity": 400, "batchsize_id": 60366 }, "500": { "country_id": "CN", "product_price": 39.33, "shipment_price": 2.31, "quantity": 500, "batchsize_id": 60372 }, "600": { "country_id": "CN", "product_price": 44.04, "shipment_price": 2.95, "quantity": 600, "batchsize_id": 60378 }, "700": { "country_id": "CN", "product_price": 48.32, "shipment_price": 2.95, "quantity": 700, "batchsize_id": 60384 }, "800": { "country_id": "CN", "product_price": 52.22, "shipment_price": 2.95, "quantity": 800, "batchsize_id": 60390 }, "900": { "country_id": "CN", "product_price": 55.79, "…
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48008671
tagged with: jsonparser
score: 1
has answer: http://stackoverflow.com/a/48008671
tagged with: http://stackoverflow.com/tag/json
has title: Parse JSON and select a specific key in python

http://stackoverflow.com/q/48014493
has title: Maya 2018 Python+QT: Querying Value of Imported TextField
tagged with: textfield
has answer: http://stackoverflow.com/a/48022095
has body: I've been following This Tutorial on using a .UI file from QT designer in a Maya plugin. It states that, in order to query the value of a QtextEdit field after the UI has been loaded into Maya, I need to do the following: So now when we load our QT Ui inside of maya we can query the text of our line edit every time we want to by using the following line of code: pm.textField('textFieldName', query = True, text = True) However I can't seem to get this to function. I'm loading the UI as follows: # Load our window and put it into a variable. ebWin = cmds.loadUI(uiFile = self.BE_UIpath) No issues there, when I try cmds.showWindow(ebWin), everything works and looks exactly as intended. Now, when I try to query the QtextEdit I've named 'exportDirectoryTF', Maya insists it does not exist. I've tried two different approaches: approach A: # Connect Functions to the buttons. exportDir = ebWin.textField('exportDirectoryTF', query = True, text = True) which outputs: # Error: 'unicode' object has no attribute 'textField' # # Traceback (most recent call last): # # File "C:/Users/Censored/Documents/maya/2018/plug-ins/EB_pi_cmds.py", line 39, in doIt # # exportDir = ebWin.textField('exportDirectoryTF', query = True, text = True) # # AttributeError: 'unicode' object has no attribute 'textField' and approach B: import maya.cmds as cmds # Connect Functions to the buttons. exportDir = cmds.textField('exportDirectoryTF', query = True, text = True) which returns: # RuntimeError: Object 'exportDirectoryTF' not found. # # Traceback (most recent call last): # # File "C:/Users/Censored/Documents/maya/2018/plug-ins/EB_pi_cmds.py", line 39, in doIt # # exportDir = cmds.textField('exportDirectoryTF', query = True, text = True) # # RuntimeError: Object 'exportDirectoryTF' not found. # The tutorial has 'pm.textField('textFieldName', q = True, text = True)', and I can't figure out where the "pm" came from, if it is supposed to indicate the variable from loading the UI or the maya Python textField …
upvote count: 1
type: Question
tagged with: qt
score: 1
accepted answer: http://stackoverflow.com/a/48022095
answer count: 1
tagged with: maya
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/83000836
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/47922503
tagged with: openpyxl
has body: I have a bit of a memory problem atm. I've inherited an excel-template file which contains conditional formatting, formulas, some VBA-scripts and roughly 30 sheets. The template is basically empty initially and depending on the situtation I want to fill 1-10 of these sheets with values. The rest of the sheets will use the information that I update and fill out the rest. The data is stored in a database and I use python and openpyxl to retrieve the data and write the excel. Conceptually it works like a charm. However, I recently added some conditional formatting on 5 sheets and I now run into a memory problem. The process is killed. The simplified process is this: read template file update data (this iterates through both sheets and cells so, a lot of looping going on) store new file Sample code: wb = openpyxl.load_workbook(TEMPLATE_FILE, keep_vba=True) ws = wb[SHEETNAMEn] ws.cell(row=rownum,column=colnum).value = theValue wb.save(newFilename) So, I need some pointers on how to get this working/optimize it.
tagged with: excel
type: Question
has comment: http://stackoverflow.com/comment/82852654
score: 0
has comment: http://stackoverflow.com/comment/82816120
has title: openpyxel memory issue (template excel-file)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82825362
tagged with: python
tagged with: templates
has comment: http://stackoverflow.com/comment/82815869
has comment: http://stackoverflow.com/comment/82815689
has comment: http://stackoverflow.com/comment/82846588
answer count: 0

http://stackoverflow.com/a/47927730
has body: You can use assign + mul + sum: df1 = df.assign(**params).mul(df).sum(1) print (df1) 0 24.1 1 21.4 2 22.6 3 23.8 4 38.4 dtype: float64 And dot + Series constructor: df1 = df.dot(pd.Series(params)) print (df1) 0 24.1 1 21.4 2 22.6 3 23.8 4 38.4 dtype: float64
score: 8
accepted answer of: http://stackoverflow.com/q/47927695
has comment: http://stackoverflow.com/comment/117925367
answers question: http://stackoverflow.com/q/47927695
type: AcceptedAnswer
downvote count: 0
upvote count: 8
type: Answer

http://stackoverflow.com/a/47894906
has comment: http://stackoverflow.com/comment/82756631
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/82757376
has comment: http://stackoverflow.com/comment/82756663
accepted answer of: http://stackoverflow.com/q/47894861
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47894861
has body: From pandas str.split df=pd.concat([df,df.Info.str.split(',',expand=True)],1) df Out[611]: Name Info 0 1 2 3 0 Mike a, b, c, d a b c d 1 Joe a, f, z a f z None
has comment: http://stackoverflow.com/comment/82757441

http://stackoverflow.com/a/47931643
score: 1
upvote count: 1
has body: You could use a list comprehension &gt;&gt;&gt; [[0 if j == 'm' else j for j in i] for i in mylist] [['.', 0, '.', '.'], ['.', '.', '.', 0]]
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47931613

http://stackoverflow.com/a/47948301
upvote count: 1
score: 0
downvote count: 1
has body: Just delete migrations folder from the project and apply the migrations again. Then run these 3 commands: python manage.py migrate yourapp zero python manage.py makemigrations yourapp python manage.py migrate yourapp
has comment: http://stackoverflow.com/comment/82867096
answers question: http://stackoverflow.com/q/47947912
type: Answer

http://stackoverflow.com/q/47857971
type: Question
has body: Is it possible to create the xaxis in a Bokeh chart without using pandas? Can I just import the Python datetime module to create the xaxis? In the Bokeh documentation they show this: import pandas as pd from bokeh.plotting import figure, output_file, show from bokeh.sampledata.stocks import AAPL df = pd.DataFrame(AAPL) df['date'] = pd.to_datetime(df['date']) output_file("datetime.html") # create a new plot with a datetime axis type p = figure(plot_width=800, plot_height=250, x_axis_type="datetime") p.line(df['date'], df['close'], color='navy', alpha=0.5) show(p) I am trying something like this: from bokeh.io import curdoc from bokeh.models import ColumnDataSource, DatetimeTickFormatter from bokeh.plotting import figure from datetime import datetime p = figure(plot_height=400, plot_width=1200, x_axis_type="datetime") p.xaxis.formatter = DatetimeTickFormatter(hours=["%H:%M:%S"],days=["%H:%M:%S"],months=["%H:%M:%S"],years=["%H:%M:%S"]) The code runs but I do not see any x or y axis.
answer count: 1
has comment: http://stackoverflow.com/comment/82684694
score: 0
accepted answer: http://stackoverflow.com/a/47861125
tagged with: pandas
tagged with: datetime
tagged with: python
has title: Using Bokeh datetime with Pandas
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47861125
tagged with: bokeh

http://stackoverflow.com/q/47894011
has comment: http://stackoverflow.com/comment/82790164
has comment: http://stackoverflow.com/comment/82789843
score: 0
has comment: http://stackoverflow.com/comment/82817558
has title: Using for loop in rules and errors with shell split command
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82779579
has body: I am a first time user of Snakemake and I am having trouble with some of my rules definition. Here's the snakefile which I am running: import os import re READS="r1 r2".split() READ1=READS[0] READ2=READS[1] array=[] #To get a list of filtered reads suffixes after running the rule split_reads f_reads = os.listdir("./filtered_reads") for i in range(len(f_reads)): mm = re.match(r'(.+-)([a-z][a-z])',f_reads[i]) if mm: array.append(mm.group(2)) rule quality_filter: input: expand("data/{{sample}}_{read}.fq",read=READS) output: expand("filtered_reads/{{sample}}_{read}_q20p50.fq",read=READS) shell: """ fastq_quality_filter -Q33 -q 20 -p 50 -i {input[0]} -o {output[0]} fastq_quality_filter -Q33 -q 20 -p 50 -i {input[1]} -o {output[1]} """ rule fastq_conversion: input: expand("filtered_reads/{{sample}}_{read}_q20p50.fq",read=READS) output: expand("filtered_reads/{{sample}}_{read}_q20p50.fasta",read=READS) shell: """ fastq_to_fasta -Q33 -n -i {input[0]} -o {output[0]} fastq_to_fasta -Q33 -n -i {input[1]} -o {output[1]} """ rule fasta_temp: input: expand("filtered_reads/{{sample}}_{read}_q20p50.fasta",read=READS) output: expand("filtered_reads/{{sample}}_{read}_q20p50.fasta_temp",read=READS) shell: """ awk '/&gt;/{{temp=$0; getline; print temp "\\t" $0}}' {input[0]} | sed 's/\/1/ 1:N:0:8 /' | sort &gt; {output[0]} awk '/&gt;/{{temp=$0; getline; print temp "\\t" $0}}' {input[1]} | sed 's/\/2/ 2:N:0:8 /' | sort &gt; {output[1]} """ rule filtered_join: input: expand("filtered_reads/{{sample}}_{read}_q20p50.fasta_temp",read=READS) output: expand("filtered_reads/{{sample}}_{read}_q20p50_filtered.fasta",read=READS) shell:""" join -j 1 -o 1.1 1.2 1.3 {input[0]} {input[1]} | awk '{{print $1 " " $2 "\\n" $3}}' &gt; {output[0]} join -j 1 -o 2.1 2.2 2.3 {input[0]} {input[1]} | awk '{{print $1 " " $2 "\\n" $3}}' &gt; {output[1]} """ rule split_reads: input: expand("filtered_reads/{{sample}}_{read}_q20p50_filtered.fasta",read=READS) output: expand("filtered_reads/{{sample}}_{read}_q20p50_fi…
tagged with: python
tagged with: snakemake
has comment: http://stackoverflow.com/comment/82779532
type: Question

http://stackoverflow.com/comment/82842965
has text: @Dark I'm not so sure they even want a dictionary here because they're just inserting by index. It seems like they just want to put everything into a list and measure the length of each one. But this code really makes it hard to understand what they really want to do. Perhaps some input and expected output would help.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47936741

http://stackoverflow.com/q/47983293
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82935319
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47984220
score: 1
has comment: http://stackoverflow.com/comment/82987462
type: Question
downvote count: 0
answer count: 1
favorite count: 0
has body: I'd like to create a decorator that prints units on a number. money = 10 print(money) results in '10 dollars' money = 1 print(money) results in '1 dollar' I get that I need to wrap money.__str__(), but I'm not sure how to do that generically with a decorator. Am I on the right track here? Can the following somehow become a decorator? def str_cur(money): if money == 1 or money == -1: return f"{money} dollar" else return f"{money} dollars"
has title: Create a Decorator Printing An Integer in Python
tagged with: python-decorators

http://stackoverflow.com/comment/118988201
type: AnswerComment
has text: @HP. did you manage to get it working with JDBC? especially the case where the returned result returns rows with the columns names, and the case where it returns empty dataframe
type: Comment
comment on: http://stackoverflow.com/a/47981864
score: 0

http://stackoverflow.com/comment/82797508
has text: Well this question has been answered, it'd help if you made another question to get more eyes on it. IMHO. :)
comment on: http://stackoverflow.com/a/47912114
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/47972892
type: Question
accepted answer: http://stackoverflow.com/a/47972905
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/35989552
favorite count: 0
tagged with: pandas
has title: Setting values of multiindex dataframe using only one-level indexing
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/47972905
tagged with: indexing
score: 2
type: AnsweredQuestion
has body: My question is a logical continuation of this topic: Setting values with multiindex in pandas. So the example and answer from this, suits my situation either. They set a multiindex value with f.loc[(slice(None), "one"), 0] = 1 But in my case, i have lot's of dataframes with custom number of index levels, so i would like to use indexing only on last level, without specifying others - smth like f.loc[:::, "one"), 0] = 1. P.S. Also, if i have an Indexer for column "one", am i able to use it? Indexer can be an array: array([ True, True, True, ..., True, True, True], dtype=bool)

http://stackoverflow.com/comment/82980714
has text: You can use JS or direct call to your python script.
comment on: http://stackoverflow.com/q/48006214
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48010030
accepted answer: http://stackoverflow.com/a/48010102
upvote count: 1
linked to: http://stackoverflow.com/q/23317342
type: AnsweredQuestion
type: Question
tagged with: pandas
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48010102
score: 1
favorite count: 0
tagged with: python
has body: I have a pandas dataframe with a pipe delimited column with an arbitrary number of elements, called Parts. The number of elements in these pipe-strings varies from 0 to over 10. The number of unique elements contained in all pipe-strings is not much smaller than the number of rows (which makes it impossible for me to manually specify all of them while creating new columns). For each row, I want to create a new column that acts as an indicator variable for each element of the pipe delimited list. For instance, if the row ...'Parts'... ...'12|34|56' should be transformed to ...'Part_12' 'Part_34' 'Part_56'... ...1 1 1... Because they are a lot of unique parts, these columns are obviously going to be sparse - mostly zeros since each row only contains a small fraction of unique parts. I haven't found any approach that doesn't require manually specifying the columns (for instance, Pandas Dataframe: split column into multiple columns, right-align inconsistent cell entries). I've also looked at pandas' melt, but I don't think that's the appropriate tool. The way I know how to solve it would be to pipe the raw CSV to another python script and deal with it on a char-by-char basis, but I need to work within my existing script since I will be processing hundreds of CSVs in this manner. Here's a better illustration of the data ID YEAR AMT PARTZ 1202 2007 99.34 9321 1988 1012.99 2031|8942 2342 2012 381.22 1939|8321|Amx3
has title: Create Multiple New Columns Based on Pipe-Delimited Column in Pandas
linked to: http://stackoverflow.com/q/48014555

http://stackoverflow.com/q/47857005
has comment: http://stackoverflow.com/comment/84132684
answer count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82678494
tagged with: memory
downvote count: 1
type: Question
has body: I have troubles concerning both runtime and memory usage, when using python to compute a suffix tree via Ukkonens Algorithm (linear time and space). Currently, I want to create a suffix tree for a bacterial genome, consisting of roughly 1,6 Million characters in length. The alphabet contains of 11 different characters. The file itself has a size of 1,6 MB, but the tree in Python uses more than 2 GB RAM and it takes about one minute to finish building the tree. I am storing child nodes in a list of length 11, where each positions corresponds to a character of the alphabet. I have tried using dictionaries, as a lot of None values are stored by using this method. However, this results in even larger memory issues and takes a little bit longer. I am not even storing the sequence itself but only the corresponding intervals. I am no expert, is this overhead, produced by all of the objects? Can this be reduced? Any suggestions appreciated. Below is the contructor of a SuffixNode in the tree. As you can see, children are stored in a list. The edge, that connects to the parent node is only stored with _start and _end. class SuffixNode: _index = -1 def __init__(self, start, end,suffixlink = None): self._start = start self._end = end self._index = -1 self._suffixlink = None self._children = [None,None,None,None,None,None,None,None,None,None,None,None] The algorithm itself, although this might not be quite helpful: class SuffixTree(object): def __init__(self,sequence): self.end = len(sequence)+1 self.sequence = sequence+'#' self.virt_root = SuffixNode(-1,-1) self.root = SuffixNode(0, 0) self.virt_root.setChild(self.root,self.getChildPosition('A')) self.virt_root.setChild(self.root,self.getChildPosition('C')) self.virt_root.setChild(self.root,self.getChildPosition('G')) self.virt_root.setChild(self.root,self.getChildPosition('T')) self.virt_root.setChild(self.root,self.getChildPosition('#')) self.virt_root.setChild(self.root,self.getChildPosition('M')) self.virt_root.setChild(se…
tagged with: runtime
score: 0
favorite count: 0
tagged with: suffix-tree
type: UnansweredQuestion
tagged with: python
has title: Memory and Runtime Issues: Ukkonens Algorithm for SuffixTrees in python
has comment: http://stackoverflow.com/comment/82678783

http://stackoverflow.com/comment/82743721
type: AnswerComment
comment on: http://stackoverflow.com/a/47880127
score: 0
type: Comment
has text: @sudonym Check out my updated Answer and let me know the status.

http://stackoverflow.com/q/47903031
has comment: http://stackoverflow.com/comment/82779462
has comment: http://stackoverflow.com/comment/83046229
has comment: http://stackoverflow.com/comment/82784054
score: 0
tagged with: tcpserver
has title: Background Threaded TCP Server in Python
tagged with: python-multithreading
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82782865
tagged with: python
answer count: 0
tagged with: tcp
tagged with: multithreading
has body: I want to run TCP thread on the background even if I exit the main function and only stop that thread based on the received data but my code seems to close the TCP thread after it execute the SystemExit: class MyTCPHandler(socketserver.BaseRequestHandler): def setup(self): self._is_running = True def handle(self): while(self._is_running): self.data = self.request.recv(1024).strip() #some process here #self._is_running is assigned based on received data self.request.send(msg.encode()) def finish(self): pass class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): pass if __name__ == "__main__": map_server = ThreadedTCPServer(('192.168.1.101', 2002), MyTCPHandler) server_thread = Thread(target=map_server.serve_forever) server_thread.daemon = False server_thread.start() raise SystemExit(0)
type: Question

http://stackoverflow.com/comment/82713734
score: 0
has text: Just a comment, if the transformation you attempted was correct, then it would solve P=NP by way of reductions ;) . I think any better way will probably use heuristics/be context-specific
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47871837

http://stackoverflow.com/q/47857654
accepted answer: http://stackoverflow.com/a/47857917
has title: Python socket and Angular5
tagged with: angular
tagged with: sockets
tagged with: python
has answer: http://stackoverflow.com/a/47857917
type: AnsweredQuestion
downvote count: 1
type: Question
has body: Please help to find the reason of issue. I have a simple daemon on python with socket on 9999 port, it's working correctly and returning on each GET request some info. In the second side I have a Angular application, with the button which running function of GET, but it's not working... Please help to clarify why. Class on Angular : export class HeaderComponent implements OnInit { apiURL:string = 'hostname:9999'; constructor(private http:Http) { } ngOnInit() { } httpRequest() { this.http.get(this.apiURL).subscribe(outJson =&gt; console.log(outJson)); } } And error which I'm getting on browser : View_HeaderComponent_0 ng:///AppModule/HeaderComponent.ngfactory.js:58:8 proxyClass compiler.js:14640 DebugContext_.prototype.logError core.js:15030 ErrorHandler.prototype.handleError core.js:1488 dispatchEvent core.js:9994 renderEventHandlerClosure/&lt; core.js:10611:29 decoratePreventDefault/&lt; platform-browser.js:2628:25 ZoneDelegate.prototype.invokeTask zone.js:367 onInvokeTaskv core.js:4744 ZoneDelegate.prototype.invokeTask zone.js:366 Zone.prototype.runTask zone.js:166 ZoneTask/this.invoke zone.js:420 P.S. The reason in Angular, cause request is not coming to python at all. And this error also getting : [WDS] Disconnected! vendor.bundle.js:35042:10 log http://host/vendor.bundle.js:35042:10 closevclient:104 socket/sock.onclose socket.js:15 EventTarget.prototype.dispatchEvent eventtarget.js:51 SockJS.prototype._close/&lt; main.js:356 ZoneDelegate.prototype.invokeTask zone.js:367 Zone.prototype.runTask zone.js:166 ZoneTask/this.invoke zone.js:420 scheduleTask/data.args[0]
score: -1
upvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/q/47885072
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/47888735
possible better answer: http://stackoverflow.com/a/47889627
has title: How to set the color of y-label according to a palette
has answer: http://stackoverflow.com/a/47889627
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/47888735
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: seaborn
tagged with: python
has body: I use the following code to generate a seaborn scatterplot: import pandas as pd from matplotlib import pyplot import seaborn as sns %matplotlib inline df = pd.DataFrame({ 'Year': [2010, 2011, 2010, 2011, 2012], 'Event': ['A', 'A', 'B', 'B', 'B'] }) fig, ax = pyplot.subplots() sns.stripplot(x="Year", y="Event", ax=ax, data=df, palette=sns.color_palette("deep", 50)); The resulting image is: However, when the number of possible labels grows (eg:'Events'= ['A','B',...'Z'], it is difficult to read the y label corresponding to each circle. How can I write each y-label (eg: Event) painted with its corresponding color in the palette ? Typically, in this example, I would like the A y-label to be written in a blue color and B in green

schedule
tags question: http://stackoverflow.com/q/47984435
tags question: http://stackoverflow.com/q/47863536
tags question: http://stackoverflow.com/q/47994466
tag name: schedule
type: Tag

http://stackoverflow.com/comment/82822457
type: AnswerComment
comment on: http://stackoverflow.com/a/47881306
has text: no worries, I also started Python a while back. It takes time. But learning about python basics you better read up some basic documentation first, I cannot really transfer this knowledge over stackoverflow answers
score: 0
type: Comment

pivot
tags question: http://stackoverflow.com/q/47904813
tag name: pivot
tags question: http://stackoverflow.com/q/47991714
tags question: http://stackoverflow.com/q/47858798
type: Tag

http://stackoverflow.com/comment/82907450
comment on: http://stackoverflow.com/q/47968183
score: 0
type: Comment
type: QuestionComment
has text: That's not printing to a terminal, that's using the system call print which is just mem copying your string into system buffer and then dumping it, printing to the screen can take ages unless it's buffered, which I'm assuming by the time it takes to print is not the case here.

http://stackoverflow.com/comment/82702336
type: QuestionComment
has text: These: **IronPython.dll IronPython.Modules.dll Microsoft.Scripting.dll Microsoft.Dynamic.dll**
type: Comment
comment on: http://stackoverflow.com/q/47856496
score: 0

http://stackoverflow.com/a/47894539
type: Answer
has comment: http://stackoverflow.com/comment/82781126
answers question: http://stackoverflow.com/q/47893605
has body: Firstly, this is not a question for StackOverflow (sounds like a homework question). You can easily discern various methods to accomplish this via Google. I will however give you one solution as I need to warm up: # -*- coding: utf-8 -*- import traceback, sys, re ''' Open the bigrams file and load into an array. Assuming bigrams are cleaned (else, you can do this using method below). ''' try: with open('bigrams.txt') as bigrams_file: bigrams = bigrams_file.read().splitlines() except Exception: print('BIGRAMS LOAD ERROR: '+str(traceback.format_exc())) sys.exit(1) test_input = 'There is clear good evidence a great reward is in store.' ''' Clean input method. ''' def clean_input(text_input): text_input = text_input.lower() text_input = text_input.strip(' \t\n\r') alpha_num_underscore_only = re.compile(r'([^\s\w_])+', re.UNICODE) text_input = alpha_num_underscore_only.sub(' ', text_input) text_input = re.sub(' +', ' ', text_input) return text_input.strip() test_input_words = test_input.split() test_input_clean = clean_input(test_input) test_input_clean_words = test_input_clean.split() ''' Loop through the test_input bigram by bigram. If we match one, then increment the index to move onto the next bigram. This is a quick implementation --- you can modify for efficiency, and higher-order n-grams. ''' output_text = [] skip_index = 0 for i in range(len(test_input_clean_words)-1): if i &gt;= skip_index: if ' '.join([test_input_clean_words[i], test_input_clean_words[i+1]]) in bigrams: print(test_input_clean_words[i], test_input_clean_words[i+1]) skip_index = i+2 output_text.append('TOKEN_'+'_'.join([test_input_words[i], test_input_words[i+1]]).upper()) else: skip_index = i+1 output_text.append(test_input_words[i]) output_text.append(test_input_words[len(test_input_clean_words)-1]) print(' '.join(output_text)) Input: There is clear good evidence a great reward is in store. Output: There is clear good evidence a TOKEN_GREAT_REWARD is in store.
accepted answer of: http://stackoverflow.com/q/47893605
type: AcceptedAnswer
score: 0

http://stackoverflow.com/q/47858295
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has title: Django Rest Framework: Issue using OrderingFilter and django-filter simultaneously
has comment: http://stackoverflow.com/comment/82708870
has answer: http://stackoverflow.com/a/47879512
downvote count: 0
answer count: 1
has body: I have a viewset which needs to have both flexible ordering by parameter and filtering by parameter for a custom list() over-ride. I am able to get ordering to work as well as filtering on various parameters via django-filter, but I cannot get them both to function simultaneously. Here is my simplified views.py code that works for ordering the results: class AssetViewSet(viewsets.GenericViewSet, AssetPaginationMixin,): queryset = Asset.objects.all() pagination_class = AssetPagination serializer_class = serializers.AssetSerializer filter_backends = (OrderingFilter, ) ordering_fields = ('id', 'session_id') filter_class = AssetFilterSet def list(self, request): assets = self.filter_queryset(self.get_queryset()) serializer = self.get_serializer(assets, many=True) return Response(serializer.data) And here is the code that works for filtering: class AssetViewSet(viewsets.GenericViewSet, AssetPaginationMixin,): queryset = Asset.objects.all() pagination_class = AssetPagination serializer_class = serializers.AssetSerializer filter_backends = (OrderingFilter, ) ordering_fields = ('id', 'session_id') filter_class = AssetFilterSet def list(self, request): assets = AssetFilterSet(request.query_params) serializer = self.get_serializer(assets, many=True) return Response(serializer.data) And finally, my filters.py code: class AssetFilterSet(django_filters.FilterSet): project_id = django_filters.NumberFilter() submitted = django_filters.TypedChoiceFilter(choices=BOOLEAN_CHOICES, coerce=strtobool) class Meta: model = Asset fields = ['project', 'submitted'] The only difference is the first line in list(). For some reason, it seems like the AssetFilterSet needs to be applied directly within list() in order to take effect and is otherwise bypassed if I use self.filter_queryset in list() despite being specified by filter_class = AssetFilterSet.
tagged with: django-rest-framework
favorite count: 0
tagged with: django
accepted answer: http://stackoverflow.com/a/47879512
tagged with: python

http://stackoverflow.com/q/47858941
has comment: http://stackoverflow.com/comment/82682592
has comment: http://stackoverflow.com/comment/82682805
has comment: http://stackoverflow.com/comment/82682567
score: -1
has comment: http://stackoverflow.com/comment/82682511
upvote count: 2
has comment: http://stackoverflow.com/comment/82682833
downvote count: 3
answer count: 1
has comment: http://stackoverflow.com/comment/82682505
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/82682509
has title: Why don't I get the output that I expect?
favorite count: 0
has comment: http://stackoverflow.com/comment/82682769
type: Question
has body: I'm finding the approximate square root of the number 25. #include &lt;stdio.h&gt; main() { float a = 25.0; float b = 0.0; while (abs(b*b - a) &gt;= 0.01) { b += 0.00001; } printf("%f\n", b); } I expect b to be around 5 after the loop, can someone explain why it's showing 0? When I write this code in Python it works correctly: a=25.0 b=0.0 while abs(b*b - a) &gt;= 0.01: b+=0.00001 print(b)
has comment: http://stackoverflow.com/comment/82682519
has comment: http://stackoverflow.com/comment/82682591
has answer: http://stackoverflow.com/a/47859002
tagged with: python

http://stackoverflow.com/q/47947400
tagged with: python
score: -1
tagged with: selenium
has body: I'm trying to automate updating a service desk ticket upon receipt of an E-mail. I've already figured out the way to 'listen' for an E-mail and launch the website/login, however for the life of me one of the parts I thought would be the easiest is proving to be the most difficult. Essentially I need to click the dropdown in the image below and either type or click the option 'Acknowledged'. Service desk photo with drop down options : Here is the snippet of code for the drop down, note: the number in the ID in the code changes based on the ticket (in this example the number is 298) New Advanced Search New Please select a status New Closed Submit Error Pending Deleted Request Rejected Work In Progress Resolved Acknowledged Advanced Search closureInformationCheck();StatusChange(); Closure Information None Advanced Search None Advanced Search I've tried a whole bunch fo things like: driver.find_element_by_xpath('//*[@id="298_status"]/div/input').click() or driver.find_element_by_xpath(u"//td[contains(text(), '_status')]") But I always get errors stating that the element cant be found. Any ideas?
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/47949361
has answer: http://stackoverflow.com/a/47950862
has answer: http://stackoverflow.com/a/47957998
has title: Cannot find element I want to click - selenium
answer count: 3
upvote count: 0
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/47990952
favorite count: 0
has title: TypeError: bad argument type for built-in operation
has comment: http://stackoverflow.com/comment/82951105
has comment: http://stackoverflow.com/comment/82950333
tagged with: python
accepted answer: http://stackoverflow.com/a/47991631
score: 19
tagged with: opencv
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47994126
has answer: http://stackoverflow.com/a/47994126
downvote count: 1
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/82951432
upvote count: 20
has body: I got an error TypeError: bad argument type for built-in operation . I wrote import os import cv2 from pathlib import Path path = Path(__file__).parent path /= "../../img_folder" for f in path.iterdir(): print(f) img=cv2.imread(f) In img=cv2.imread(f), the error happens.Is this a Python error or directory wrong error?In print(f),I think right directories can be gotten.How should I fix this?
has comment: http://stackoverflow.com/comment/82951233
has answer: http://stackoverflow.com/a/47991631

http://stackoverflow.com/q/47892879
has body: Hi I'm a complete beginner with Python and PyMol, but I've done a lot of work in Java. I am trying to import pymol modules(i think they're called modules or libraries) into my python program in Eclipse, but I keep getting the error "No module named 'pymol'". Is there some code that I need to add to import pymol or do i need to change some path variables or something... I want to make sure this code can run on other computers too, so hopefully the solution to my problem will just be extra code and not going into my system and changing variables or paths.
has comment: http://stackoverflow.com/comment/82752530
type: UnansweredQuestion
tagged with: python
tagged with: protein-database
answer count: 0
has title: Importing PyMol modules into python program in Eclipse
type: Question
tagged with: eclipse
tagged with: python-2.7
score: 0
tagged with: pymol
has comment: http://stackoverflow.com/comment/82752289

http://stackoverflow.com/q/47933380
tagged with: gcc
tagged with: reinforcement-learning
has title: How to ignore compiler flags in pip?
answer count: 1
has answer: http://stackoverflow.com/a/50013537
downvote count: 0
favorite count: 0
has body: I'm trying to install mujoco-py, when I try pip install mujoco_py in my maxOS 10.12 with python 3.5 in anaconda, I got /usr/local/bin/gcc-7 -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -I/Users/Shangtong/anaconda2/envs/Python3.5/include -I/Users/Shangtong/anaconda2/envs/Python3.5/include -Wno-error=unused-command-line-argument-hard-error-in-future -Wno-error=unused-command-line-argument-hard-error-in-future -Wno-error=unused-command-line-argument-hard-error-in-future -DONMAC -Imujoco_py -I/private/var/folders/6j/gtq1cx25611ck3bft9rnfxkh0000gn/T/pip-build-3r460esi/mujoco-py/mujoco_py -I/Users/Shangtong/.mujoco/mjpro150/include -I/Users/Shangtong/anaconda2/envs/Python3.5/lib/python3.5/site-packages/numpy/core/include -I/Users/Shangtong/anaconda2/envs/Python3.5/include/python3.5m -c /private/var/folders/6j/gtq1cx25611ck3bft9rnfxkh0000gn/T/pip-build-3r460esi/mujoco-py/mujoco_py/cymj.c -o /private/var/folders/6j/gtq1cx25611ck3bft9rnfxkh0000gn/T/pip-build-3r460esi/mujoco-py/mujoco_py/generated/_pyxbld_MacExtensionBuilder/temp.macosx-10.6-x86_64-3.5/private/var/folders/6j/gtq1cx25611ck3bft9rnfxkh0000gn/T/pip-build-3r460esi/mujoco-py/mujoco_py/cymj.o -fopenmp -w cc1: error: -Werror=unused-command-line-argument-hard-error-in-future: no option -Wunused-command-line-argument-hard-error-in-future cc1: error: -Werror=unused-command-line-argument-hard-error-in-future: no option -Wunused-command-line-argument-hard-error-in-future cc1: error: -Werror=unused-command-line-argument-hard-error-in-future: no option -Wunused-command-line-argument-hard-error-in-future error: command '/usr/local/bin/gcc-7' failed with exit status 1 I have to install gcc because it doesn't accept clang. It seems gcc doesn't ignore this unknown flag. I tried ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future pip install mujoco_py But it didn't help. Is there any way that gcc can ignore this unknown flag?
tagged with: pip
upvote count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50013537
score: 1
type: Question

http://stackoverflow.com/comment/82687440
type: QuestionComment
has text: do want all instances of `AutoEncoder` to inherit from the same class based on a condition one time, or do you want to be able to set the parent class for each instance?
score: 1
comment on: http://stackoverflow.com/q/47861232
type: Comment

http://stackoverflow.com/comment/82765921
score: 1
comment on: http://stackoverflow.com/q/47899565
type: Comment
has text: Hi Prasanna. Could you please post some sample code to show what have you tried so far?
type: QuestionComment

http://stackoverflow.com/comment/82799730
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47915713
type: QuestionComment
has text: @mypetlion He should still learn the proper way to use SO.

http://stackoverflow.com/q/47872964
downvote count: 1
has body: When I run a specific python program, I faced with an issue. While debugging I found out that the program is using libraries from different python installations. For example, When I execute pip freeze | grep requests I get requests==2.18.4. But when the program runs, it somehow uses a v2.2.1 requests library from /usr/share/python-wheels/requests-2.2.1-py2.py3-none-any.whl/requests/api.py location. Then, when I executed whereis python I can see multiple directories in the output. Q1) How can I solve this type of a problem without using a virtualenv? (i.e. conflicting library versions) Q2) Or How can I upgrade the library at /usr/share/* directory? Q3) How can I get rid of the multiple installations and stick with a single python installation? Note: I am unable to use virtualenv because of an issue in the way the application is deployed.
score: 2
has comment: http://stackoverflow.com/comment/82712793
has comment: http://stackoverflow.com/comment/82712053
has title: Python: handling multiple installations of same version
type: Question
has comment: http://stackoverflow.com/comment/82714255
has comment: http://stackoverflow.com/comment/82718403
has comment: http://stackoverflow.com/comment/82712870
favorite count: 0
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/82712886
has comment: http://stackoverflow.com/comment/82712374
answer count: 0
has comment: http://stackoverflow.com/comment/82713778
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82712944
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/82711313
tagged with: python-requests

http://stackoverflow.com/comment/82751734
comment on: http://stackoverflow.com/a/47880968
score: 0
type: AnswerComment
type: Comment
has text: I'm not good at understanding words, it would be better if you update the question with expected output, I had the general solution using groupby median but thought this would be enough. So update the question for more generalized solution.

http://stackoverflow.com/q/47899965
favorite count: 0
has comment: http://stackoverflow.com/comment/82814037
tagged with: python
tagged with: user-defined-types
tagged with: pass-by-value
answer count: 0
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/82766950
tagged with: pass-by-reference
linked to: http://stackoverflow.com/q/986006
has body: I have one User defined Object. I want to pass as reference (out parameter) so that value of input Object will be changed inside function and return to called function. This can be achieved by using list or Dictionary i.e mutable object. But How to achieve with User defined object without using list &amp; Dictionary. Check below code snippet as example:- class Test: def __init__(self,data): self.data = data def display(root): # Simple Display function print(root.data) #Don't want to use List to do pass by reference and out parameter. Instead pass object itself. def assign(root,args): if root is not None: args[0] = root #Passed object itself, not as List def assign1(root,temp): if root is not None: temp = root #Driver Function call root = Test(10) display(root) temp = None args = [temp] assign(root,args) # Function in which args passed as out parameter display(args[0]) # Gives Output: 10 temp1 = None assign1(root,temp1) # Function in which object passed as out parameter print(temp1) # Gives Output: None display(temp1) # AttributeError: 'NoneType' object has no attribute 'data' May be i am missing something.
score: 1
has title: Out parameter using call by reference for User defined Object in Python
type: Question
downvote count: 0
tagged with: out-parameters
has comment: http://stackoverflow.com/comment/82766944
has comment: http://stackoverflow.com/comment/82766630

http://stackoverflow.com/comment/82847577
has text: should I use two entirely separate loops to compute te[i] and te2[i]?
type: Comment
comment on: http://stackoverflow.com/a/47938595
score: 0
type: AnswerComment

http://stackoverflow.com/q/48012086
duplicate of: http://stackoverflow.com/q/76105218
score: 4
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/82993456
has comment: http://stackoverflow.com/comment/82992832
has comment: http://stackoverflow.com/comment/82995239
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48014213
has title: tkinter import error on ubuntu 16.4
has comment: http://stackoverflow.com/comment/82993529
has comment: http://stackoverflow.com/comment/82993562
tagged with: python
type: AnsweredQuestion
tagged with: tkinter
linked to: http://stackoverflow.com/q/5459444
has comment: http://stackoverflow.com/comment/82993641
has comment: http://stackoverflow.com/comment/83039631
linked to: http://stackoverflow.com/q/76105218
has comment: http://stackoverflow.com/comment/82995291
accepted answer: http://stackoverflow.com/a/48014213
type: Question
upvote count: 4
has body: I tried to run a code which use turtle to draw a tree. There is no problem with code because I ran it on Windows 10 successfully, but on Ubuntu, the following error was encountered: mosharraf@mmh:~$ cd Desktop mosharraf@mmh:~/Desktop$ python3 Tree.py Traceback (most recent call last): File "Tree.py", line 6, in &lt;module&gt; import turtle File "/usr/local/lib/python3.6/turtle.py", line 107, in &lt;module&gt; import tkinter as TK File "/usr/local/lib/python3.6/tkinter/__init__.py", line 36, in &lt;module&gt; import _tkinter # If this fails your Python may not be configured for Tk ModuleNotFoundError: No module named '_tkinter' mosharraf@mmh:~/Desktop$ Then I tried to install tkinter but I failed. mosharraf@mmh:~$ sudo apt-get install python3-tk [sudo] password for mosharraf: Reading package lists... Done Building dependency tree Reading state information... Done python3-tk is already the newest version (3.5.1-1). 0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded. mosharraf@mmh:~$ Afterwards, I checked for the tkinter in the directories and found it. mosharraf@mmh:/usr/local/lib/python3.6$ cd tkinter mosharraf@mmh:/usr/local/lib/python3.6/tkinter$ ls colorchooser.py constants.py dnd.py font.py __main__.py __pycache__ simpledialog.py tix.py commondialog.py dialog.py filedialog.py __init__.py messagebox.py scrolledtext.py test ttk.py mosharraf@mmh:/usr/local/lib/python3.6/tkinter$ python3 Python 3.6.4 (default, Dec 22 2017, 18:44:45) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import tkinter Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python3.6/tkinter/__init__.py", line 36, in &lt;module&gt; import _tkinter # If this fails your Python may not be configured for Tk ModuleNotFoundError: No module named '_tkinter' &gt;&gt;&gt; tkinter is in the directories as you can see above, but I can't import it. I tried several ways like import…

http://stackoverflow.com/comment/82840976
type: Comment
type: QuestionComment
has text: change `template.library()` to `template.Library()`
score: 3
comment on: http://stackoverflow.com/q/47935801

http://stackoverflow.com/comment/125603257
type: AnswerComment
comment on: http://stackoverflow.com/a/47876761
has text: No need to use `transform`, `df.div(df.groupby(['foo','bar']).sum())` is more efficient.
type: Comment
score: 1

http://stackoverflow.com/q/47887264
has comment: http://stackoverflow.com/comment/82771679
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/82744680
answer count: 1
downvote count: 0
score: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/82759625
has title: Failing to create android management signup URL
tagged with: python
has comment: http://stackoverflow.com/comment/82743052
tagged with: cosu
type: UnansweredQuestion
tagged with: android-management-api
tagged with: mdm
has answer: http://stackoverflow.com/a/47903308
tagged with: android-for-work
has body: I'm trying to access the new Android Management API for our organization but I run into problems accessing the API. Everything runs fine when accessing the API through the API explorer. To run this on our server, I have created a new project in the Google cloud console and created a service account there. I downloaded the key and use this for local testing on my machine. However, upon the first signupUrl call, I get a 403 error, stating: "Caller is not authorized to manage project.". The service account I'm using has the "Project Owner" role, I don't see how I can give it even more privileges... The code I'm using: def initial_enterprise_user(request): enterprise_token = request.GET.get('enterpriseToken') usr = request.user scopes = ['https://www.googleapis.com/auth/androidmanagement'] credentials = ServiceAccountCredentials.from_json_keyfile_name(settings.SERVICE_ACCOUNT, scopes=scopes) if enterprise_token is None: androidmanagement = build('androidmanagement', 'v1', credentials=credentials) resp = androidmanagement.signupUrls().create(projectId=settings.ANDROID_MGMT_PROJECTID).execute() if resp.status_code == 200: usr.signup_url_name = resp.json()['name'] usr.save() return render(request, 'initial_login.html', {'response_url': resp.json()['url']}) else: return HttpResponse('Failed to get signup url') else: # handle token present

http://stackoverflow.com/comment/82771855
type: QuestionComment
has text: err.. just to be clear, the number of items to be appended is not fixed to 4. it can be more or less (or none!)
comment on: http://stackoverflow.com/q/47902323
score: 0
type: Comment

http://stackoverflow.com/comment/82794019
score: 0
comment on: http://stackoverflow.com/q/47912611
type: Comment
type: QuestionComment
has text: Yes, they have. I quite literally can do it in numpy using np.dot(np.stack(x),np.stack(x).T). But I want to have a dataframe so I can access things by using labels instead of indecies. Ie i want to write M['label1'] and see the dot products of vector named label1 with all the other vectors.

http://stackoverflow.com/a/48012852
score: 1
accepted answer of: http://stackoverflow.com/q/48008998
has body: To check the weights, you first need to initialize them as follows: net.collect_params().initialize(mx.init.Xavier(), ctx=mx.cpu()) In your case, because you didn't specify input size to layers in Net's constructor, the shape of parameters cannot be determined at this point. So, if you access net.weight.data() now, an exception will be raised: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python2.7/dist-packages/mxnet-0.12.1-py2.7.egg/mxnet/gluon/parameter.py", line 389, in data return self._check_and_get(self._data, ctx) File "/usr/local/lib/python2.7/dist-packages/mxnet-0.12.1-py2.7.egg/mxnet/gluon/parameter.py", line 189, in _check_and_get "nested child Blocks"%(self.name)) RuntimeError: Parameter dense0_weight has not been initialized. Note that you should initialize parameters and create Trainer with Block.collect_params() instead of Block.params because the later does not include Parameters of nested child Blocks You can initialize the weights as follows: net.collect_params().initialize(mxnet.init.Xavier(), ctx=mxnet.cpu()) print (net.weight.data())
answers question: http://stackoverflow.com/q/48008998
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0

http://stackoverflow.com/comment/82733053
type: AnswerComment
score: 1
has text: @shash678 you made great improvement to this answer, however I decided to use `copy.deepcopy()` inside function definition instead of arguments during function call.
type: Comment
comment on: http://stackoverflow.com/a/47882523

http://stackoverflow.com/q/47899830
answer count: 1
accepted answer: http://stackoverflow.com/a/47899920
downvote count: 0
linked to: http://stackoverflow.com/q/47933691
favorite count: 0
has comment: http://stackoverflow.com/comment/82766369
has title: pandas value_counts( ) not in descending order
upvote count: 5
has answer: http://stackoverflow.com/a/47899920
tagged with: python
type: AnsweredQuestion
type: Question
score: 5
has body: There is a dataframe,df Index Date Name Category 0 2017-08-09 ABC-SAP 1 1 2017-08-09 CDE-WAS 2 2 2017-08-10 DEF 3 3 2017-08-11 DEF 3 4 2017-08-11 CDE-WAS 2 5 2017-08-11 CDE-WAS 2 I executed this code: df2=pd.DataFrame(df, columns= ['Name','Category']) df2= df['Name'].groupby(df['Category']).value_counts() print(df2) Then I get: Index Name (1,ABC-SAP) 1 (2,CDE-WAS) 3 (3,DEF) 2 The value.counts( ) does not return a descending order on the NAME column. I really want to have it in descending order from highest to lowest count. Any way of doing it?
tagged with: pandas

http://stackoverflow.com/a/48016078
type: Answer
score: 2
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/83016597
has comment: http://stackoverflow.com/comment/83017033
answers question: http://stackoverflow.com/q/48012394
has comment: http://stackoverflow.com/comment/83008184
has comment: http://stackoverflow.com/comment/83016698
has body: For Twisted to process further I/O events, you have to give control back to the reactor. Twisted implements a cooperative multitasking system. Various tasks run in the reactor thread. This is accomplished by each task only spending a brief time in control. Code like: while True: ... sleep(1) prevents any other tasks from gaining control to execute and also prevents the reactor from gaining control to service I/O events. Since this code is within a function decorated with inlineCallbacks, there is a very small change that will make it at least not completely incompatible with Twisted's mode of operation. Instead of time.sleep(1), try this expression: yield deferLater(reactor, 1, lambda: None) And import deferLater from twisted.internet.task. This will perform a "sleep" which gives control back to the reactor and lets other tasks execute during the sleep. This should allow Autobahn to send the necessary ping/pong messages as well as allow it to process your publish call.

http://stackoverflow.com/comment/82710533
type: QuestionComment
comment on: http://stackoverflow.com/q/47872271
score: 0
has text: That won't happen. The changes are registered per column
type: Comment

http://stackoverflow.com/comment/90656861
has text: No, it is not possible.
type: Comment
comment on: http://stackoverflow.com/a/47891955
score: 0
type: AnswerComment

http://stackoverflow.com/a/47967209
downvote count: 0
score: 6
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/82911270
has body: The order of this vertices [[ 0. -20.23 7. ] [ 0. -20.23 -7. ] [ 100. -10. 5. ] [ 100. -10. -5. ]] is like this: If you want to draw the quad which is defined by the 4 vertices, then you have either to draw a GL_TRIANGLE_STRIP: def Surfaces(self, vertices): glBegin(GL_TRIANGLE_STRIP) for i in range(4): glColor4f(1, 1, 1, 0.3) glVertex3fv(vertices[i ,:]) glEnd() Or you have to change the order of the vertices, that it matches the requiremts for a GL_QUAD: [[ 0. -20.23 7. ] [ 0. -20.23 -7. ] [ 100. -10. -5. ] [ 100. -10. 5. ]] See further Primitive
accepted answer of: http://stackoverflow.com/q/47965081
answers question: http://stackoverflow.com/q/47965081
has comment: http://stackoverflow.com/comment/82911191
type: AcceptedAnswer

http://stackoverflow.com/comment/82800653
has text: I just modified my answer to solve that issue. Hope that answer helps you.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47916068

http://stackoverflow.com/a/47968560
accepted answer of: http://stackoverflow.com/q/47968530
answers question: http://stackoverflow.com/q/47968530
has comment: http://stackoverflow.com/comment/82907211
downvote count: 0
score: 9
has comment: http://stackoverflow.com/comment/82908013
has comment: http://stackoverflow.com/comment/82906679
has comment: http://stackoverflow.com/comment/82907686
has comment: http://stackoverflow.com/comment/82906612
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82908275
has body: Straight-forward sorting: a = [['A', 'B'], ['A', 'C'], ['D', 'D'], ['C', 'D']] a = sorted(a, key=lambda x: x[0] == x[1]) # [['A', 'B'], ['A', 'C'], ['C', 'D'], ['D', 'D']] This simple key function works because False is sorted before True while mapping all pairs to only two keys maintains stability. The downside to this approach is that sorting is O(N_logN). For a linear solution without unecessary list concatenations, you could use itertools.chain with appropriate generators: from itertools import chain a = list(chain((p for p in a if p[0] != p[1]), (p for p in a if p[0] == p[1])))
upvote count: 9
has comment: http://stackoverflow.com/comment/82907370
type: Answer
has comment: http://stackoverflow.com/comment/82907540
has comment: http://stackoverflow.com/comment/82907494

http://stackoverflow.com/comment/82681910
score: 0
type: QuestionComment
has text: Yes, for my purpose I need to append and no, it is not already at the end, sorry
comment on: http://stackoverflow.com/q/47857982
type: Comment

http://stackoverflow.com/q/47889267
answer count: 1
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/82745027
has answer: http://stackoverflow.com/a/47889747
has comment: http://stackoverflow.com/comment/82745466
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82744913
has title: How to read an API correctly with JSON and create list? In Python
tagged with: api
type: AnsweredQuestion
has body: In Python3 I made a program to read an API (from Brazilian Chamber of Deputies) and get the data in JSON import requests import pandas as pd url = 'https://dadosabertos.camara.leg.br/api/v2/deputados' First I made a list with dictionaries - they are the names of the deputies and the respective API link of each. The parameters were json, number of items per page and page number (there are more than 500 deputies, then there are six pages) deputados = [] for pagina in [1, 2, 3, 4, 5, 6]: parametros = {'formato': 'json', 'itens': 100, 'pagina': pagina} resposta = requests.get(url, parametros) for deputado in resposta.json()['dados']: dicionario = {"deputado": deputado['nome'], "link_api": deputado['uri']} deputados.append(dicionario) Content of the list: deputados [{'deputado': 'ABEL MESQUITA JR.', 'link_api': 'https://dadosabertos.camara.leg.br/api/v2/deputados/178957'}, {'deputado': 'ADAIL CARNEIRO', 'link_api': 'https://dadosabertos.camara.leg.br/api/v2/deputados/178864'}, {'deputado': 'ADALBERTO CAVALCANTI', 'link_api': 'https://dadosabertos.camara.leg.br/api/v2/deputados/178914'}, {'deputado': 'ADELMO CARNEIRO LEÃO', 'link_api': 'https://dadosabertos.camara.leg.br/api/v2/deputados/178890'}, {'deputado': 'ADELSON BARRETO', 'link_api': 'https://dadosabertos.camara.leg.br/api/v2/deputados/178968'}, {'deputado': 'ADEMIR CAMILO', 'link_api': 'https://dadosabertos.camara.leg.br/api/v2/deputados/133374'}, ... I create a dataframe with the result df = pd.DataFrame(deputados) df.reset_index().head() index deputado link_api 0 0 ABEL MESQUITA JR. https://dadosabertos.camara.leg.br/api/v2/depu... 1 1 ADAIL CARNEIRO https://dadosabertos.camara.leg.br/api/v2/depu... 2 2 ADALBERTO CAVALCANTI https://dadosabertos.camara.leg.br/api/v2/depu... 3 3 ADELMO CARNEIRO LEÃO https://dadosabertos.camara.leg.br/api/v2/depu... 4 4 ADELSON BARRETO https://dadosabertos.camara.leg.br/api/v2/depu... Then I created another list with dictionaries. This time I want to go on every deputy API page and…
accepted answer: http://stackoverflow.com/a/47889747
has comment: http://stackoverflow.com/comment/82745486
favorite count: 0
type: Question
upvote count: 2
tagged with: python

http://stackoverflow.com/q/47894861
has answer: http://stackoverflow.com/a/47894920
has title: python separate text into different column with comma
accepted answer: http://stackoverflow.com/a/47894906
possible better answer: http://stackoverflow.com/a/47894920
upvote count: 3
tagged with: python
tagged with: excel
type: AnsweredQuestion
score: 3
has body: I'm pulling data from a database and writing to a new Excel file for a report. My issue is that the last column of data has data that is separated by commas and needs to be separated into separate columns. As an example I have data like the following: Name Info Mike "a, b, c, d" Joe "a, f, z" I need to break these letters out into separate columns. The a's, b's, etc. don't have to line up so that each letter is in the "correct" column. They just need to be broken out into separate columns. I'm doing this in Python. I'm open to using other libraries like Pandas. There will be other columns included, not just two. I made a simple example. Any help is appreciated.
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47894906
downvote count: 0
favorite count: 0
tagged with: pandas

http://stackoverflow.com/a/47878261
has body: Are you not looking for itertools.combinations_with_replacement([0, 1, 2, 3, 4, 5], 6) ? :)
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/47876486
type: Answer
score: 1

http://stackoverflow.com/comment/82760341
has text: I tried both and it came up with this error 'DataFrame' object has no attribute 'to_numeric'
comment on: http://stackoverflow.com/a/47896745
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82896800
comment on: http://stackoverflow.com/a/47961427
type: Comment
has text: You can add it : -) `x.mul(x.columns.values)`
score: 0
type: AnswerComment

masked-array
tags question: http://stackoverflow.com/q/47970128
tag name: masked-array
type: Tag

http://stackoverflow.com/a/47922977
has body: By calling self.exec_() in the run() method of your worker you start a new event loop on this thread after the download finished, and this event loop then just keeps running. You don't need an event loop here, you only need a separate event loop if you want to move QObjects to it using their moveToThread() method to decouple them from the main event loop, but that is not needed here, you're not doing anything that requires a Qt event loop. That's also why calling stop() or exit() doesn't do anything, it only affects an event loop. The only way to stop this thread would be its terminate() method, and this also kind of works: from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtCore import * from youtube_dl import * class Worker(QThread): data = pyqtSignal(object) def __init__(self): super(Worker, self).__init__() self.flag = True def sendHook(self, data, status = {'status':'downloading'}): self.data.emit(data) def stop(self): self.terminate() print("QThread terminated") def run(self): self.y = YoutubeDL({'progress_hooks':[self.sendHook]}) self.y.download(['https://www.youtube.com/watch?v=LKIXbNW-B5g']) print("finished") class MainWindow(QMainWindow): def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) layout = QVBoxLayout() self.l = QLabel("Hello") b = QPushButton("Start!") b.pressed.connect(self.connectthread) layout.addWidget(self.l) layout.addWidget(b) w = QWidget() w.setLayout(layout) self.setCentralWidget(w) self.thread = None self.show() def read(self, data): print("read:", data) def connectthread(self): if self.thread is not None: # already running self.thread.stop() self.thread = None return self.thread = Worker() self.thread.data.connect(self.read) self.thread.start() app = QApplication([]) window = MainWindow() app.exec_() Here I've altered your program so the first time the button is clicked the worker is started, the second time the thread is terminated and so on. However terminating a thread this way is …
type: Answer
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/47921540
answers question: http://stackoverflow.com/q/47921540
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/82900196
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47965015
type: Comment
has text: Please provide a [a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) for future readers.

http://stackoverflow.com/comment/82875916
type: Comment
type: QuestionComment
has text: Isn't the ```<a href=``` tag what you are looking for?
score: 0
comment on: http://stackoverflow.com/q/47953076

http://stackoverflow.com/q/47930176
answer count: 3
has comment: http://stackoverflow.com/comment/82834221
has title: Printing out the validation accuracy to the console for every batch or epoch (Keras)
upvote count: 9
has comment: http://stackoverflow.com/comment/82838995
has answer: http://stackoverflow.com/a/50484745
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82835378
has answer: http://stackoverflow.com/a/58705167
has body: I'm using ImageDataGenerator and flow_from_directory to generate my data, and using model.fit_generator to fit the data. This defaults to outputting the accuracy for training data set only. There doesn't seem to be an option to output validation accuracy to the terminal. Here is the relevant portion of my code: #train data generator print('Starting Preprocessing') train_datagen = ImageDataGenerator(preprocessing_function = preprocess) train_generator = train_datagen.flow_from_directory( train_data_dir, target_size = (img_height, img_width), batch_size = batch_size, class_mode = 'categorical') #class_mode = 'categorical' #same for validation val_datagen = ImageDataGenerator(preprocessing_function = preprocess) validation_generator = val_datagen.flow_from_directory( validation_data_dir, target_size = (img_height, img_width), batch_size=batch_size, class_mode='categorical') ########################Model Creation################################### #create the base pre-trained model print('Finished Preprocessing, starting model creating \n') base_model = InceptionV3(weights='imagenet', include_top=False) x = base_model.output x = GlobalAveragePooling2D()(x) x = Dense(1024, activation='relu')(x) predictions = Dense(12, activation='softmax')(x) model = Model(input=base_model.input, output=predictions) for layer in model.layers[:-34]: layer.trainable = False for layer in model.layers[-34:]: layer.trainable = True from keras.optimizers import SGD model.compile(optimizer=SGD(lr=0.001, momentum=0.92), loss='categorical_crossentropy', metrics = ['accuracy']) #############SAVE Model ####################################### file_name = str(datetime.datetime.now()).split(' ')[0] + '_{epoch:02d}.hdf5' filepath = os.path.join(save_dir, file_name) checkpoints =ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=False, save_weights_only=False, mode='auto', period=2) ###############Fit Model ############################# model.fit_generator( train_generator, steps_per…
tagged with: deep-learning
downvote count: 0
tagged with: neural-network
has answer: http://stackoverflow.com/a/47945517
tagged with: keras
favorite count: 0
score: 9
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/82831600

http://stackoverflow.com/q/47858541
has title: why I have a extra file when listing files from S3 folder
type: Question
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/47858627
upvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47858627
tagged with: amazon-s3
score: 1
tagged with: boto3
has body: I'm trying to list the file from S3 Bucket "card-prtnr-npi". The files that I want to read are in the "ambs_ambivolatile" folder which is there in the S3 "card-prtnr-npi" bucket. This is the actual path "card-prtnr-npi/users/rtltest/ambs_ambivolatile". "ambs_ambivolatile" folder has only one file in it but Boto 3 is reading an additional file which is not present. 'users/rtltest/ambs_ambivolatile/' is not present in the folder and only part-m-00026.bz2' is present. Please see the below code. ['users/rtltest/ambs_ambivolatile/', 'users/rtltest/ambs_ambivolatile/part-m-00026.bz2'] s3_src_bucket = 'card-prtnr-npi' s3_src_prefix = 'users/rtltest/ambs_ambivolatile/' print("getting response from source") source_bucket = src_session.resource('s3').Bucket(s3_src_bucket) files = source_bucket.objects.filter(Prefix=s3_src_prefix) source_keys = [] for file in files: source_keys.append(file.key) print(source_keys) The above print statement prints the following list ['users/rtltest/ambs_ambivolatile/', 'users/rtltest/ambs_ambivolatile/part-m-00026.bz2'] How do I stop reading this extra file 'users/rtltest/ambs_ambivolatile/'.

http://stackoverflow.com/q/47979934
has comment: http://stackoverflow.com/comment/82929905
favorite count: 0
has answer: http://stackoverflow.com/a/47980778
tagged with: python
type: AnsweredQuestion
score: -4
has body: Using python, from a table like this: A B C 0 1 5 1 1 8 2 1 5 3 1 4 4 1 5 5 5 10 6 5 9 7 1 5 8 1 4 9 1 5 10 5 4 How can I create a function that scans through to find all ‘B’ values = 5, and then return the previous 4 ‘C’ values, where ‘B’ = 1? If there are only 3 ‘B’ = 1, then just return 3. After the first ‘B’ = 5, I need an output of 8, 5, 4, 5. The second ‘B’ = 5 should return nothing because it doesn’t have any ‘B’ = 1 immediately preceding it. The third ‘B’ = 5 needs to return 5, 4, 5. This should be be written into a completely new dataset with a space between every new ‘B’ = 5 value, looking like this: 8 5 4 5 5 4 5
has comment: http://stackoverflow.com/comment/82928423
type: Question
accepted answer: http://stackoverflow.com/a/47980778
has title: Scan table to find certain value in column, then return previous values of another column Python
downvote count: 4
tagged with: pandas
upvote count: 0
answer count: 1

http://stackoverflow.com/q/47902807
has title: How to use default bindtag behavior as methods?
score: 0
accepted answer: http://stackoverflow.com/a/47906468
answer count: 1
linked to: http://stackoverflow.com/q/3501849
has comment: http://stackoverflow.com/comment/82777531
favorite count: 0
has comment: http://stackoverflow.com/comment/82773585
tagged with: tcl
tagged with: binding
tagged with: python
has comment: http://stackoverflow.com/comment/82775187
linked to: http://stackoverflow.com/q/47895168
has comment: http://stackoverflow.com/comment/82775144
has comment: http://stackoverflow.com/comment/82774023
tagged with: tkinter
has answer: http://stackoverflow.com/a/47906468
has comment: http://stackoverflow.com/comment/82779602
has comment: http://stackoverflow.com/comment/82772634
tagged with: tk-toolkit
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82776333
has comment: http://stackoverflow.com/comment/82775971
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82773975
has comment: http://stackoverflow.com/comment/82781443
has comment: http://stackoverflow.com/comment/82786516
has body: I am trying to invoke default widget behavior on demand. Based on this answer I know a bit about bindtags, and taglists. Let's say for example I have two buttons, and I want to have the bindtag behavior of a specific item in its taglist, of first button, whenever I left click on the right button: import tkinter as tk root = tk.Tk() first_btn = tk.Button(root, text="1st") second_btn = tk.Button(root, text="2nd") second_btn.bind("&lt;Button-1&gt;", "expect the bindtag operation here") first_btn.pack() second_btn.pack() root.mainloop() I haven't specified command=... for first_btn as I need to have the very effect of button push for example with my second_btn binding. or as another example, I want to have second_btn to invoke all(ideally of my choosing) bindtag callbacks of first_btn: import tkinter as tk root = tk.Tk() first_btn = tk.Button(root, text="1st") second_btn = tk.Button(root, text="2nd", command="first_btn bindtag callbacks") first_btn.pack() second_btn.pack() root.mainloop() Or, what are reference names(if any) to the operations attached to bindtags?
has comment: http://stackoverflow.com/comment/82777631
has comment: http://stackoverflow.com/comment/82786231
type: Question

http://stackoverflow.com/comment/96879384
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47881010
has text: This might stop the 'invalid syntax' error but it doesn't solve the real issue: you installed Django for Python 3 and now getting an error when you try to run it with Python 2. The real fix is to use the correct Python version.
score: 17

http://stackoverflow.com/comment/82902071
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47961481
has text: the code is so messy i can't even look for what i would look for. so you have your application, and only have 404 when you want to redirect to `laws`? show us how you want to redirect there. remove the unnecessary code, so we don't have to hunt for problem.
type: Comment

http://stackoverflow.com/comment/82685117
score: 0
type: Comment
has text: The `print str(lis[j]),` doesn't add that space. The `print ""` does. Should just be `print`.
comment on: http://stackoverflow.com/a/47859555
type: AnswerComment

http://stackoverflow.com/q/47996099
has comment: http://stackoverflow.com/comment/82960522
linked to: http://stackoverflow.com/q/9856163
type: UnansweredQuestion
has body: Am trying to read an xml file(which is a french diccionary) from a python script, but am getting the error below. Is there anyway I can fix it? PS: the file is 158 643 Ko from xml.dom import minidom doc = minidom.parse("Dic.xml") Data = doc.getElementsByTagName("title")[0] titleData = Data.firstChild.data print (titleData) The error: Traceback (most recent call last): File "&lt;pyshell#3&gt;", line 1, in &lt;module&gt; doc = minidom.parse("Morphalou-2.0.xml") File "C:\Python27\lib\xml\dom\minidom.py", line 1918, in parse return expatbuilder.parse(file) File "C:\Python27\lib\xml\dom\expatbuilder.py", line 924, in parse result = builder.parseFile(fp) File "C:\Python27\lib\xml\dom\expatbuilder.py", line 204, in parseFile buffer = file.read(16*1024) MemoryError Advance Thanks
tagged with: python
has title: Python: Read a very large XML file
tagged with: http://stackoverflow.com/tag/xml
answer count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82960594
type: Question
score: 1
has comment: http://stackoverflow.com/comment/82960792
has comment: http://stackoverflow.com/comment/82968881
downvote count: 0
has comment: http://stackoverflow.com/comment/82961322
favorite count: 0

http://stackoverflow.com/comment/82818809
type: Comment
has text: Do you want the labels to contain _exactly_ what is in the entry widget? If so, you can give the entry and the label widget the same `StringVar` and they will always be in sync.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47917916

http://stackoverflow.com/comment/82797703
has text: I'm sure there's a better title that describes my problem, but I just couldn't think of a better one. Anyone is free to edit this accordingly
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47914844

http://stackoverflow.com/q/47926096
has comment: http://stackoverflow.com/comment/82819978
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47926161
tagged with: list
linked to: http://stackoverflow.com/q/9060653
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82820033
type: Question
has body: I want to make a function that takes a list which contains some words and prints only the first letter of each word in order to make one new word. So my function is right here: def word(x): li = [] for w in x: li.append(w[0]) return sum(li) But unfortunately, it gives me the following error: TypeError: unsupported operand type(s) for +: 'int' and 'str' Can you please explain me why is this happening ?
tagged with: sum
has comment: http://stackoverflow.com/comment/82819958
has title: How can I sum a list of string objects in Python?
has comment: http://stackoverflow.com/comment/82819988
answer count: 1
downvote count: 0
tagged with: string

http://stackoverflow.com/q/48011421
has comment: http://stackoverflow.com/comment/83010695
score: 1
has body: I have written a fast script to count the pages in PDF files. However, in some files it cannot be read and it returns an error of Xref table not Zero indexed. Basically when expects an Object Id (5.0) and gets Object Id (4.0) for example. Also I have got with other Object Id like (7.0) and gets Object Id(6.0), etc... My code is: from PyPDF2 import PdfFileReader from pathlib import Path import os import math import logging numPages=0 workPath = input ('Please introduce your working directory: ') print ('Your selected path is ' + workPath) os.chdir (workPath.encode()) logging.basicConfig(filename='errrors.log', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') fout= open('PagesCount.txt', 'w', encoding="utf-8") path_files = Path(workPath) for file in path_files.glob('**/*.pdf'): page_Count = 0 try: with open(str(file), "br") as PDF: try: page_Count = PdfFileReader(PDF).getNumPages() numPages = numPages + page_Count print ('Pages in ' + str(file) + ': ' + str(page_Count) + ' pages') fout.write ('Pages in ' + str(file) + ':\t' + str(page_Count) + ' pages\n') except: print('File {} cannot be read'.format(str(file))) logging.error('File cannot be read:\t {}'.format(str(file))) except: logging.error('File is not processed: {}'.format(str(file))) print ('Total number of pages:\t' + str(numPages) + ' pages') fout.write ('Total number of pages:\t' + str(numPages) + ' pages\n') So, it happens that I have to count the pages of many scanned PDF files, and a high % of them, about 80% of them go filtered to the errors file due of the mentioned error above. Is there any way to prevent the Xref table not Zero indexed error? Thank you.
has title: Python PyPDF2 counting PDF pages in scanned PDF generates Xref table not Zero indexed
type: Question
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: http://stackoverflow.com/tag/pdf
tagged with: python
has comment: http://stackoverflow.com/comment/83000569
has answer: http://stackoverflow.com/a/48011688
has comment: http://stackoverflow.com/comment/83018090
tagged with: pypdf
type: UnansweredQuestion
upvote count: 1

http://stackoverflow.com/q/47900151
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82767024
score: 1
has title: Web scraping new articles
type: Question
has comment: http://stackoverflow.com/comment/82792659
has answer: http://stackoverflow.com/a/47911858
has body: I've been learning python and BeautifulSoup functions for the past few months trying to use if mainly for web scraping news articles for my own research purposes. However, I have been having difficulties trying to get content printed out nicely as texts from the Chinese website. Which tag should I use to get the content of the article? &lt;&lt;div class="w980 wbnav clear"&gt;&lt;a href="http://english.peopledaily.com.cn/" target="_blank"&gt;English&lt;/a&gt;&amp;gt;&amp;gt;&lt;/div&gt; &lt;div class="w980 wb_10 clear"&gt; &lt;h1&gt;DPRK launches ballistic missile 'capable of hitting US mainland'&lt;/h1&gt; &lt;div&gt; (&lt;a &lt;/div&gt; &lt;div class="wb_12 clear"&gt; &lt;p style="text-align: center;"&gt; &lt;img alt="" src="/NMediaFile/2017/1129/FOREIGN201711291331000220555852915.jpg" style="width: 900px; height: 783px;" /&gt;&lt;/p&gt; &lt;p&gt; The Democratic Peopleâs Republic of Korea (DPRK) has confirmed that it successfully tested a âHwasong 15â intercontinental ballistic missile (ICBM) on Wednesday.&lt;/p&gt; &lt;p&gt; A Korean Central News Agency (KCNA) statement, which confirms earlier assessments from the United States and the Republic of Korea (ROK), claims the new type of ICBM "is capable of striking the whole mainland of the US." &lt;/p&gt; &lt;p&gt; It was Pyongyang's first test launch since a missile was fired in mid-September, days after its sixth-nuclear test.&lt;/p&gt; &lt;p&gt; The ICBM was launched at 02:48 local time on Wednesday, according to the KCNA statement, and flew to an altitude of 4,475 km and then a distance of 950 km.&lt;/p&gt; &lt;p&gt; It was launched from Sain Ni in the DPRK and flew for 53 minutes before splashing down into the Sea of Japan, said Pentagon spokesman Robert Manning.&lt;/p&gt;
answer count: 1
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
type: UnansweredQuestion

http://stackoverflow.com/a/47943056
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82855735
has comment: http://stackoverflow.com/comment/82856428
has comment: http://stackoverflow.com/comment/82855851
has comment: http://stackoverflow.com/comment/82856161
accepted answer of: http://stackoverflow.com/q/47942971
answers question: http://stackoverflow.com/q/47942971
upvote count: 2
has body: Here is one approach In [2]: a[:, -1] = a[:, -1] &gt; 0 In [3]: a Out[3]: array([[ 0.15293227, -1.50167614, 0. ], [ 1.25396778, 0.21520081, 1. ], [-1.1272423 , 1.18971277, 1. ]]) and if you don't want for the negative entries to be set to zero, here is a facetious alternative: In [4]: a[:, -1] = a[:, -1] ** (a[:, -1] &lt; 0) In [5]: a Out[5]: array([[ 0.15293227, -1.50167614, -1.04974543], [ 1.25396778, 0.21520081, 1. ], [-1.1272423 , 1.18971277, 1. ]]) In response to your comment, let's say you want to set up a custom float value to be inserted just at the positive entries (while leaving the negative entries alone). In [6]: float_to_insert_at_positives = 3.14159 In [7]: (float_to_insert_at_positives - a[:, -1]) * (a[:, -1] &gt; 0) + a[:, -1] Out[7]: array([-1.04974543, 3.14159 , 3.14159 ]) In [8]: a[:, -1] = (float_to_insert_at_positives - a[:, -1]) * (a[:, -1] &gt; 0) + ... a[:, -1] In [9]: a Out[9]: array([[ 0.15293227, -1.50167614, -1.04974543], [ 1.25396778, 0.21520081, 3.14159 ], [-1.1272423 , 1.18971277, 3.14159 ]])
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82856381

http://stackoverflow.com/a/47979952
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47979810
has body: Sample (with different data) - df = pd.DataFrame({'ID' : [1] * 3 + [2] * 3 + [3] * 3, 'response_go' : [0, 0, 0, 1, 1, 1, 0, 1, 0]}) df ID response_go 0 1 0 1 1 0 2 1 0 3 2 1 4 2 1 5 2 1 6 3 0 7 3 1 8 3 0 Use groupby + mean - v = df.groupby('ID').response_go.mean() v ID 1 0.000000 2 1.000000 3 0.333333 Name: response_go, dtype: float64 Use np.select to compute your statuses based on the mean of response_go - u = np.select([v == 1, v == 0, v &lt; 1], ['100% Go', '100% NoGo', 'Mixed Response Pattern']) Or, use a nested np.where to do the same thing (slightly faster) - u = np.where(v == 1, '100% Go', np.where(v == 0, '100% NoGo', 'Mixed Response Pattern')) Now, assign the result back - v[:] = u v ID 1 100% NoGo 2 100% Go 3 Mixed Response Pattern Name: response_go, dtype: object
accepted answer of: http://stackoverflow.com/q/47979810
has comment: http://stackoverflow.com/comment/82929109
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/q/47934715
has body: I'm implementing Andrew Ng's Coursera course in Python and I'm doing Ex2 right now, Logistic Regression. I'm trying to use SciPy's optimize.minimize but I can't seem to get it to run correctly. I'll try to give as brief a summary of my code as possible while being thorough. I'm using Python3. Here is my variable setup, I move everything to numpy after using pandas to read in the csv file: import numpy as np import pandas as pd from scipy.optimize import fmin_bfgs from scipy import optimize as opt from scipy.optimize import minimize class Ex2: def __init__(self): self.pandas_data = pd.read_csv("ex2data1.txt", skipinitialspace=True) self.data = self.pandas_data.values self.data = np.insert(self.data, 0, 1, axis=1) self.x = self.data[:, 0:3] self.y = self.data[:, 3:] self.theta = np.zeros(shape=(self.x.shape[1])) x: (100, 3) numpy ndarray y: (100, 1) numpy ndarray theta: (3,) numpy ndarray (1-d) Then, I define a sigmoid, cost and gradient function to give to Scipy's minimize: @staticmethod def sigmoid(x): return 1/(1 + np.exp(x)) def cost(self, theta): x = self.x y = self.y m = len(y) h = self.sigmoid(x.dot(theta)) j = (1/m) * ((-y.T.dot(np.log(h))) - ((1-y).T.dot(np.log(1-h)))) return j[0] def grad(self, theta): x = self.x y = self.y theta = np.expand_dims(theta, axis=0) m = len(y) h = self.sigmoid(x.dot(theta.T)) grad = (1/m) * (x.T.dot(h-y)) grad = np.squeeze(grad) return grad These take theta, a 1-D numpy ndarray. Cost returns a scalar (the cost associated with the theta given) and gradient returns a 1-D numpy ndarray of updates for theta. When I then run this code: def run(self): options = {'maxiter': 100} print(minimize(self.cost, self.theta, jac=self.grad, options=options)) ex2 = Ex2() ex2.run() I get: fun: 0.69314718055994529 hess_inv: array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) jac: array([ -0.1 , -12.00921659, -11.26284221]) message: 'Desired error not necessarily achieved due to precision loss.' nfev: 106 nit: 0 njev: 94 status: 2 success: False x: array([ 0., …
answer count: 1
favorite count: 0
tagged with: python
tagged with: python-3.x
downvote count: 0
has answer: http://stackoverflow.com/a/47949364
accepted answer: http://stackoverflow.com/a/47949364
tagged with: scipy
type: AnsweredQuestion
score: 1
has title: Python3 Scipy: Desired error not necessarily achieved due to precision loss
type: Question
tagged with: numpy
upvote count: 1

http://stackoverflow.com/a/48017102
answers question: http://stackoverflow.com/q/48001293
score: 0
type: Answer
has body: Change your last line to output idealProb as a floating point number by using %f instead of as an integer with %i as you have it. That would make the last line: print("Ideal probability: %f" %(idealProb)) See the string format documentation for more details.

http://stackoverflow.com/q/47912800
upvote count: 1
has comment: http://stackoverflow.com/comment/82829496
answer count: 0
type: UnansweredQuestion
downvote count: 0
score: 1
favorite count: 0
has title: Kivy: Image is centered in FloatLayout only sometimes
type: Question
has body: I am getting to know with kivy's manual slowly. I need to centered image in FloatLayout ans I set up size for FloatLayout according to advice: Kivy: Image sometimes is not centered in BoxLayout . Image is now in center FloatLayout sometimes. Position image in center dependes on value of parameter orientation. Influence of parameter' value is described here: orientation = 'horizontal' - ---> image is centered orientation = 'vertical' -----> image isn't centered Thank You for your help! from kivy.app import App from kivy.core.window import Window from kivy.lang import Builder from kivy.uix.image import Image from kivy.uix.button import Button from kivy.uix.floatlayout import FloatLayout from kivy.uix.boxlayout import BoxLayout from kivy.graphics import Ellipse Window.size = (300, 300) class Scene(FloatLayout): def __init__(self, **kwargs): super(Scene,self).__init__(**kwargs) self.size = 300,300 def create(self): img = Image(pos = (0, 0), source = 'grase40.png') # square 40x40pixels self.add_widget(img) with self.canvas: Color=(1,0,0) Ellipse(pos = (80,80), size = (40, 40)) class Title(BoxLayout): def __init__(self,**kwargs): super(Title, self).__init__(**kwargs) self.orientation ='vertical' self.scene = Scene() self.add_widget(self.scene) but = Button(text ='hallo', size_hint = (0.2, 1)) self.add_widget(but) class SceneApp(App): def build(self): title = Title() title.scene.create() return title if __name__ == '__main__': SceneApp().run()
tagged with: python
tagged with: kivy

http://stackoverflow.com/comment/82709354
comment on: http://stackoverflow.com/q/47871938
has text: `\b` is a **word boundary**, which is not satisfied by `) `
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47938772
tagged with: gcc
has title: C++ compiler for python supported C++11 (MinGW and MSVC) (also cl.exe fatal error)
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/55335204
favorite count: 0
tagged with: compiler-errors
upvote count: 2
has body: I'm trying to install python package from setup.py. Actually this one: https://github.com/facebookresearch/fastText I use python 3.6 (anaconda, built in in Visual Studio 2017) I have Visual Studio 2017 and install MinGW: C:\MinGW\bin&gt;gcc --version gcc (MinGW.org GCC-6.3.0-1) 6.3.0 Then I use: python setup.py install and get next error message: error: 'thread' is not a member of 'std' I found this mean I need to use C++11 features. Ok. But how? I tried to change file distutils.cfg in my python directory to use next compilers: mingw32 msvc But for msvc get another error: error C2039: 'to_string': is not a member of 'std' I found some information, to add -std=c++11 to use some c++11 features, but I can't understand where and how to use it! Do I need write it in python shell after install? Or in distutils.cfg? I tried both and got: error: option -s not recognized ---> for python error: don't know how to compile C/C++ code on platform 'nt' with 'msvc -std=c++11' compiler ---> for distutils.cfg
tagged with: c++11
type: AnsweredQuestion
score: 2
type: Question
tagged with: visual-c++
has answer: http://stackoverflow.com/a/55335204
downvote count: 0

http://stackoverflow.com/comment/82800136
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47915951
has text: Yes, but I couldn't manage to represent data correctly with np.histogram2d, can you help out with this?

http://stackoverflow.com/comment/82790403
has text: I changed row.get("C") to row.get('C').values which return a list of column element, to check if an item is in that list just do if an_item in row.get("C") : I'm sure that this should works @PythonLearner
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47904669

http://stackoverflow.com/q/47993617
accepted answer: http://stackoverflow.com/a/47994019
tagged with: python
answer count: 4
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47993696
has comment: http://stackoverflow.com/comment/82955371
has answer: http://stackoverflow.com/a/47993696
has comment: http://stackoverflow.com/comment/82955488
type: Question
has answer: http://stackoverflow.com/a/47993700
upvote count: 0
tagged with: javascript
has answer: http://stackoverflow.com/a/47993718
linked to: http://stackoverflow.com/q/47989737
tagged with: code-conversion
has title: How to convert Python [... for ... in ... if ...] to JavaScript
has comment: http://stackoverflow.com/comment/82955577
favorite count: 0
has answer: http://stackoverflow.com/a/47994019
downvote count: 8
has body: In my previous question, some kind man gave me a good answer of check username. This code checks whether username has some forbidden words. Python: FORBIDDEN_USERNAME_LIST = ['admin', 'master', 'owner'] for item in forbidden.FORBIDDEN_USERNAME_LIST: match = [nm for nm in FORBIDDEN_USERNAME_LIST if nm in username] if match: return JsonResponse({'result': item + 'banned username'}) I converted this code to JavaScript but some code is too hard for me to convert. JavaScript: for (item in FORBIDDEN_USERNAME_LIST){ match = [nm for nm in FORBIDDEN_USERNAME_LIST if nm in username] //Here match = [...] code is hard for me to convert if (match){ console.log('exist') } } How can I convert this code to JavaScript?
score: -8

http://stackoverflow.com/q/47993775
has comment: http://stackoverflow.com/comment/82956160
has body: I have a python script that acts as a webhook. A part of it is as follows: import json import os import urllib import socket import _thread from flask import Flask from flask import request from flask import make_response app=Flask(__name__) ip = ('192.168.1.75', 9050) @app.route('/webhook',methods=['GET','POST']) def webhook(): _thread.start_new_thread(sendDataToDevice,(ip)) req = request.get_json(silent=True,force=True) print("Request:") print(json.dumps(req,indent=4)) res=makeWebHookResult(req) res=json.dumps(res,indent=4) r=make_response(res) r.headers['Content-Type']='application/json' return r if __name__ == '__main__': app.run(port=8080,host='localhost') The function of the script is to send some data to a device connected to the local network. It works flawlessly when I open my web browser and type the following on the url bar: http://localhost:8080/webhook I want to host the script on a server, eg. Heroku. How can I access the local device in that case? Note: I know I can run the script on my local machine and make it visible to the internet using ngrok, but I want to keep it accessible even when my computer is switched off. Also, want a fixed link, and the links given by ngrok change on every run.
has comment: http://stackoverflow.com/comment/82956113
score: -1
tagged with: flask
has answer: http://stackoverflow.com/a/47994468
has comment: http://stackoverflow.com/comment/82956365
has title: Accessing device on local network through server hosted webhook
answer count: 1
favorite count: 0
downvote count: 2
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47994468
has comment: http://stackoverflow.com/comment/82956396
type: AnsweredQuestion
tagged with: iot
type: Question
tagged with: network-programming

http://stackoverflow.com/a/47940716
has body: Image could have colored channels. Please take help from this. https://github.com/opencv/opencv/blob/master/samples/python/squares.py
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47935733

http://stackoverflow.com/a/47864429
score: 1
has body: map solution: vals = [18985.0, 20491.0, 18554.0, 14241.0, 13390.0, 14965.0] map( lambda (ind, x): 1 if vals[ind] &gt; vals[ind - 1] and ind != 0 else 0, enumerate(vals) ) Output: [0, 1, 0, 0, 0, 1]
downvote count: 0
answers question: http://stackoverflow.com/q/47864013
type: Answer
upvote count: 1

http://stackoverflow.com/comment/83034993
type: Comment
comment on: http://stackoverflow.com/a/47994655
has text: I think the paper help a lot when using float16. thank you =)
type: AnswerComment
score: 0

http://stackoverflow.com/q/47923233
upvote count: 4
score: 3
has answer: http://stackoverflow.com/a/47923818
has comment: http://stackoverflow.com/comment/82814408
favorite count: 0
has answer: http://stackoverflow.com/a/47923364
type: Question
tagged with: python
tagged with: strip
tagged with: whitespace
answer count: 3
has comment: http://stackoverflow.com/comment/82814110
has body: i use python to read a txt file. i have tried using .lstrip to remove the whitespace from the left but it only manages to remove the whitespace from the first line. In the text file: when i use this: puzzle = puzzle.replace('',' ') x m f y c x v t l j l q b b y b k o u m j q w b t c a u b m e k n b e y d q m c n z y j p v r a n k a q a c t i v e x n y v w d v c o s h o y a o h g p a g h z k c t u d p t j d p h s z t p r h t t l s b s n a k j w q b o u f t m g n j q b t l i n u t s e w o h v o b d s d u q j i f f k y y l o d o o u k w w e f r o y a m a p m l r r p v d o l o p c q k f x t l k s j v t m t r s b y c m q r r r i k f e r v l q i d q a x a o a n f q j l m c p j h y o y y w r b p f c j l f b c b b c o e c s p w l t w b x e t y u y u f v v m a u a w j m b w l q h t x o k d e x m d b t g v h p s v s q t m l j d x d c a t e n r e h t e o x q d g e u e l j t r r n j a r t e q v t x e j f s q d d k b u h c y s f q h p d r o w s s a p x t r x h p d x c d h i c o n what i get when i use: print (puzzle.lstrip()) x m f y c x v t l j l q b b y b k o u m j q w b t c a u b m e k n b e y d q m c n z y j p v r a n k a q a c t i v e x n y v w d v c o s h o y a t j d p h s z t p r h t t l s b s n a k j w q b o u f t m g n j q b t l i n u t s e w o h v o b d s d u q j i f f k y y l o d o o u k w w e f r o y a m a p m l r r p v d o l o p c q k f x t l k s j v t m t r s b y c m q r r r i k f e r v l q i d q a x a o a n f q j l m c p j h y o y y w r b p f c j l f b c b b c o e c s p w l t w b x e t y u y u f v v m a u a w j m b w l q h t x o k d e x m d b t g v h p s v s q t m l j d x d c a t e n r e h t e o x q d g e u e l j t r r n j a r t e q v t x e j f s q d d k b u h c y s f q h p d r o w s s a p x t r x h p d x c d h i c o n Instead i want remove all the whitespace from the left to get: x m f y c x v t l j l q b b y b k o u m j q w b t c a u b m e k n b e y d q m c n z y j p v r a n k a q a c t i v e x n y v w d v c o s h o y a o h g p a g h z k c t u d p t j d p h s z …
downvote count: 1
has answer: http://stackoverflow.com/a/47923312
has title: How do you remove the whitespace in a string with multiple lines python?
type: UnansweredQuestion

http://stackoverflow.com/comment/82848834
type: Comment
score: 0
has text: What is the actual **`[TIME]`**-domain and **`[SPACE]`**-domain cost of the flail-processing inside the call to the evaluation of the **`if ( <something that reduces> )`** condition **in `[ns]` and `[MB]` of RAM mapped allocations?**
type: QuestionComment
comment on: http://stackoverflow.com/q/47930675

http://stackoverflow.com/a/47947223
has comment: http://stackoverflow.com/comment/111352042
has body: This solution is based on comments from other person. It use queue.Queue to share data between the two threads. The Tkinter GUI/Thread use a 1-second-timer to check if new data is in the Queue and use it to refresh its Labels. #!/usr/bin/env python3 # -*- coding: utf-8 -*- # based on &lt;https://stackoverflow.com/a/47920128/4865723&gt; from tkinter import * import asyncio import threading import random import queue class AsyncioThread(threading.Thread): def __init__(self, the_queue, max_data): self.asyncio_loop = asyncio.get_event_loop() self.the_queue = the_queue self.max_data = max_data threading.Thread.__init__(self) def run(self): self.asyncio_loop.run_until_complete(self.do_data()) async def do_data(self): """ Creating and starting 'maxData' asyncio-tasks. """ tasks = [ self.create_dummy_data(key) for key in range(self.max_data) ] await asyncio.wait(tasks) async def create_dummy_data(self, key): """ Create data and store it in the queue. """ sec = random.randint(1, 10) data = '{}:{}'.format(key, random.random()) await asyncio.sleep(sec) self.the_queue.put((key, data)) class TheWindow: def __init__(self, max_data): # thread-safe data storage self.the_queue = queue.Queue() # the GUI main object self.root = Tk() # create the data variable self.data = [] for key in range(max_data): self.data.append(StringVar()) self.data[key].set('&lt;default&gt;') # Button to start the asyncio tasks Button(master=self.root, text='Start Asyncio Tasks', command=lambda: self.do_asyncio()).pack() # Frames to display data from the asyncio tasks for key in range(max_data): Label(master=self.root, textvariable=self.data[key]).pack() # Button to check if the GUI is freezed Button(master=self.root, text='Freezed???', command=self.do_freezed).pack() def refresh_data(self): """ """ # do nothing if the aysyncio thread is dead # and no more data in the queue if not self.thread.is_alive() and self.the_queue.empty(): return # refresh the GUI with new data from the queue while not self.the_queue.…
type: AcceptedAnswer
downvote count: 0
score: 7
type: Answer
accepted answer of: http://stackoverflow.com/q/47934144
upvote count: 7
answers question: http://stackoverflow.com/q/47934144

http://stackoverflow.com/q/47981207
has body: I've created a Python script to get the mobile number from user I need to get the number as integer So I used, Mobile=int(input("Enter the Mobile Number: ")) While running my program, if entered any character instead of integer, the program crashes and results in an error message. But, my need is, it have to give the error message and have to run again for asking mobile number. let me know the way please....!!
answer count: 1
score: 0
linked to: http://stackoverflow.com/q/23294658
has comment: http://stackoverflow.com/comment/82930860
has comment: http://stackoverflow.com/comment/82930888
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82930912
tagged with: python
has comment: http://stackoverflow.com/comment/82930869
duplicate of: http://stackoverflow.com/q/23294658
has comment: http://stackoverflow.com/comment/82930846
has answer: http://stackoverflow.com/a/47981251
has title: Python program integer input error
type: Question

http://stackoverflow.com/comment/82884164
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47943336
has text: I don't. However I also have problems with rpy2 installed from source. I'm trying to use pymeigo (python) which calls MEIGOR (a bioconductor package). Because pymeigo calls rtools, and rtools is only compatible with python2 (because a syntax error) I installed rpy2 from source (because most updated version is incompatible with python2) and so on.
score: 0

http://stackoverflow.com/a/47994485
has body: You could use groupby passing the datetime year. But first we would need to remove (filter away) data that doesn't meet your criteria. Also make sure your date is datetime. This code will check that month is equal to December (12) and that the day is larger or equal of 25 (i.e. the last 7 days of each year). If you want the last week of the year you could look at Wen's lambda function. data = '''\ 2017-12-25 52.99 13018070.0 52.370 53.0600 51.4000 2017-01-04 52.86 12556860.0 50.770 53.3400 50.7300 2017-01-03 50.29 15794400.0 48.800 50.3000 48.4700 2016-12-30 46.75 13593420.0 48.365 48.4000 46.3600 2016-12-29 47.77 11728250.0 48.440 48.8600 47.1800 2016-12-28 48.51 14636340.0 50.580 50.7300 48.4700 2016-12-27 50.43 5594876.0 49.690 50.5500 49.6500 2016-12-23 49.59 6966559.0 49.250 49.7200 48.9900 2016-12-22 49.44 10918300.0 50.320 50.5500 49.1711 2016-12-21 50.34 9279635.0 49.820 50.4400 49.6700 2016-12-20 49.53 9533020.0 48.990 49.7900 48.9100 2016-12-19 48.55 10323930.0 47.450 48.6700 47.4300''' import io import pandas as pd df = pd.read_csv(io.StringIO(data), sep='\s+', header=None, parse_dates=[0]) df = df[df[0].dt.month.eq(12) &amp; df[0].dt.day.le(25)] # remove data # Groupby year according to: https://stackoverflow.com/a/11397052/7386332 for idx, dfx in df.groupby(df[0].map(lambda x: x.year)): print('Dataframe containing {}\'s last week:'.format(idx)) print(dfx) print() Prints Dataframe containing 2016's last week: 0 1 2 3 4 5 7 2016-12-23 49.59 6966559.0 49.25 49.72 48.9900 8 2016-12-22 49.44 10918300.0 50.32 50.55 49.1711 9 2016-12-21 50.34 9279635.0 49.82 50.44 49.6700 10 2016-12-20 49.53 9533020.0 48.99 49.79 48.9100 11 2016-12-19 48.55 10323930.0 47.45 48.67 47.4300 Dataframe containing 2017's last week: 0 1 2 3 4 5 0 2017-12-25 52.99 13018070.0 52.37 53.06 51.4
accepted answer of: http://stackoverflow.com/q/47993977
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47993977
score: 2
upvote count: 2

http://stackoverflow.com/comment/82677827
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47856479
type: Comment
has text: Umm. But it returns "M" even If we assign any number to "X". For example, I assigned x=5. It should return "F", but it returns "M" again.

http://stackoverflow.com/a/47882550
type: Answer
score: 2
downvote count: 0
has body: There is nothing wrong in this case. When you print a python list, python calls repr on each of the list's elements. In python2, the repr of a unicode string shows the unicode code points for the characters that make up the string. &gt;&gt;&gt; c = clg_list[0] &gt;&gt;&gt; c # Ask the interpreter to display the repr of c u'\u201c985\u201d\u5de5\u7a0b\u5927\u5b66\u540d\u5355\uff08\u622a\u6b62\u52302011\u5e743\u670831\u65e5\uff09' However, if you print the string, python encodes the unicode string with a text encoding (for example, utf-8) and your computer displays the characters that match the encoding. &gt;&gt;&gt; print c “985”工程大学名单（截止到2011年3月31日） Note that in python3 printing the list will show the chinese characters as you expect, because of python3's better unicode handling.
upvote count: 2
answers question: http://stackoverflow.com/q/47881857

http://stackoverflow.com/q/47948199
has title: App Engine Datastore storing email in wrong format
favorite count: 0
has answer: http://stackoverflow.com/a/47956812
has answer: http://stackoverflow.com/a/48006272
type: UnansweredQuestion
tagged with: google-app-engine
tagged with: python
has answer: http://stackoverflow.com/a/47948336
upvote count: 1
type: Question
has body: My app receives incoming email and saves the sender's email address into the datastore. Problem is it saves them in this format: John Smith &lt;jsmith@email.com&gt; Because of the way my app and it's queries are set up I can only search for addresses in this format: jsmith@email.com I have tried to use regex to format the messages but it doesn't work for some reason, I get list index out of range errors on every expression I try. here is the code for my mail handler if that is helpful. I have checked the logs in App Engine and incoming messages do come in in the format I need, but then I check the datastore entities and it adds it in with the name as well. I just need to know how I can get email addresses stored without the extra bits. import webapp2 import logging from google.appengine.ext.webapp import mail_handlers from google.appengine.api import mail import os from main import WorkRequest import re class IncomingMailHandler(mail_handlers.InboundMailHandler): def receive(self, message): (encoding, payload) = list(message.bodies(content_type='text/plain'))[0] body_text = payload.decode() logging.info('Received email message from %s, subject "%s": %s' % (message.sender, message.subject, body_text)) logging.info (message.sender) logging.info(message.subject) logging.info(body_text) sender = str(message.sender) logging.info(sender) email_address = re.findall('&lt;([^&gt;])&gt;', sender)[0] wr = WorkRequest() wr.email = email_address wr.userId = None wr.title = message.subject wr.content = body_text wr.status = "OPEN" wr.submission_type = "EMAIL" wr.assigned_to = "UNASSIGNED" wr.put() application = webapp2.WSGIApplication([('/_ah/mail/.+', IncomingMailHandler)],debug=True)
answer count: 3
tagged with: email
downvote count: 0
score: 1

http://stackoverflow.com/a/47987169
score: 3
upvote count: 3
type: AcceptedAnswer
has body: The Corresponding Model would be as follows: class DescriptionNode(BaseTreeNode): basetreenode = models.OneToOneField(BaseTreeNode, related_name="base_tree") description = models.CharField(_("Description"), max_length=200) class Meta: verbose_name = _("Description node") verbose_name_plural = _("Description nodes") Serializer would be as follows: from rest_framework_recursive.fields import RecursiveField class BaseTreeNodeSerializer(serializers.ModelSerializer): description = serializers.SerializerMethodField() subcategories = serializers.ListSerializer(source="children",child=RecursiveField()) class Meta: model = BaseTreeNode fields = ('id', 'title', 'description', 'subcategories') def get_description(self, obj): return obj.base_tree.description #base_tree is related name of basetreenode field
has comment: http://stackoverflow.com/comment/82944500
type: Answer
accepted answer of: http://stackoverflow.com/q/47986957
downvote count: 0
answers question: http://stackoverflow.com/q/47986957

http://stackoverflow.com/a/47897508
has comment: http://stackoverflow.com/comment/82761907
has comment: http://stackoverflow.com/comment/82788804
has comment: http://stackoverflow.com/comment/82761962
has comment: http://stackoverflow.com/comment/82780783
answers question: http://stackoverflow.com/q/47897401
has body: You can try following: test['StateName'] = test.apply(lambda x: FindZip(test['Zip_To_Use']) if x['StateName'] == &quot;&quot; else x['StateName'], axis = 1) The above code applies to dataframe instead of StateName and using axis = 1, applies to columns. Updated: Updated with multiple condition in if statement (looking at the solution below): test['StateName'] = test.apply(lambda x: FindZip(test['Zip_To_Use']) if ((x['StateName'] == &quot;&quot;) and (x['Zip_To_Use'] != &quot;&quot;)) else x['StateName'], axis = 1)
downvote count: 0
has comment: http://stackoverflow.com/comment/82789578
has comment: http://stackoverflow.com/comment/82800669
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/112662141
type: AnswerComment
score: 0
type: Comment
has text: @wjandrea. At the time I didnt know any better and was fascinated with functional paradigms ;)
comment on: http://stackoverflow.com/a/47944998

http://stackoverflow.com/comment/82733771
score: 0
type: Comment
type: QuestionComment
has text: It seems there is no actual data download link.
comment on: http://stackoverflow.com/q/47883843

http://stackoverflow.com/comment/82766711
score: 0
has text: yes because we are checking for 15min frequency is data is not there or missing for 15 min than will make it as 0 and if data is there within 15min than will make it as 1.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47899416

http://stackoverflow.com/q/48003651
accepted answer: http://stackoverflow.com/a/48003956
tagged with: python
has title: bash: cd: /usr/share/sqliv: No such file or directory
type: AnsweredQuestion
score: 0
type: Question
has answer: http://stackoverflow.com/a/48003956
has body: when I install sqliv with sudo python2 setup.py -i,Suddenly broken network, then I reinstall sqliv like this,but get error the code can't work sudo python2 setup.py -i What shoud I do?
answer count: 1
has comment: http://stackoverflow.com/comment/82976033
has comment: http://stackoverflow.com/comment/82975828

http://stackoverflow.com/a/47902109
downvote count: 0
has comment: http://stackoverflow.com/comment/82771264
has comment: http://stackoverflow.com/comment/82771150
has comment: http://stackoverflow.com/comment/82773985
type: Answer
has comment: http://stackoverflow.com/comment/82771475
answers question: http://stackoverflow.com/q/47901728
has comment: http://stackoverflow.com/comment/82771472
has body: Use the eval i.e from decimal import * df = pd.DataFrame(eval(my_json)) date value 0 1508760000000 0 1 1509364800000 5.989999771118164 2 1509969600000 5.989999771118164 3 1510574400000 9.579999923706055
score: 6
accepted answer of: http://stackoverflow.com/q/47901728
upvote count: 6
has comment: http://stackoverflow.com/comment/82771015
type: AcceptedAnswer

http://stackoverflow.com/comment/88696191
score: 0
comment on: http://stackoverflow.com/a/48628280
type: Comment
has text: @RoB what is this path_to_logrid? where do I find it?
type: AnswerComment

http://stackoverflow.com/q/47962472
answer count: 1
has body: I have a Python script called a.py, which takes 1 parameter from the command line. a.py is invoked as follows: python a.py 1, where 1 is the parameter value. Now, suppose I run a.py with 3 different parameter values on a single machine like this: python a.py 1 &amp; python a.py 2 &amp; python a.py 3 I only see one a.pyc file. I wonder why there is only one a.pyc file since I invoke the program 3 times with 3 different parameters values, should there be 3 a.pyc files (maybe with different names)? If not, the a.pyc file couldn't contain all 3 parameters values, so where are the parameter values (i.e., 1,2,3) stored?
has comment: http://stackoverflow.com/comment/82894202
has title: Running a single Python script with different parameter values
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/3918689
type: Question
has answer: http://stackoverflow.com/a/47962541
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/82894191

http://stackoverflow.com/a/47881778
has comment: http://stackoverflow.com/comment/82729971
type: Answer
has comment: http://stackoverflow.com/comment/82730873
accepted answer of: http://stackoverflow.com/q/47881478
has body: I have tried your code and it seems to work just fine expect: The batch file contains: @py.exe C:\path\pw.py %* @pause try specifying your interpreter full path for example: @"C:\Anaconda3\python.exe" "C:\Users\someuser\PycharmProjects\test\pw.py" %*
has comment: http://stackoverflow.com/comment/82730894
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47881478
score: 0
has comment: http://stackoverflow.com/comment/82730567

http://stackoverflow.com/q/47963205
upvote count: 2
tagged with: python-asyncio
answer count: 1
tagged with: asynchronous
favorite count: 0
has body: I am working on a big data problem and am stuck with some concurrency and async io issues. The problem is as follows: 1) Have multiple huge files (~4gb each x upto 15) which I am processing using ProcessPoolExecutor from concurrent.futures module this way : def process(source): files = os.list(source) with ProcessPoolExecutor() as executor: future_to_url = {executor.submit(process_individual_file, source, input_file):input_file for input_file in files} for future in as_completed(future_to_url): data = future.result() 2) Now in each file, I want to go line by line, process line to create a particular json, group such 2K jsons together and hit an API with that request to get response. Here is the code: def process_individual_file(source, input_file): limit = 2000 with open(source+input_file) as sf: for line in sf: json_array.append(form_json(line)) limit -= 1 if limit == 0: response = requests.post(API_URL, json=json_array) #check response status here limit = 2000 3) Now the problem, the number of lines in each file being really large and that API call blocking and bit slow to respond, the program is taking huge amount of time to complete. 4) What I want to achieve is to make that API call async so that I can keep processing next batch of 2000 when that API call is happening. 5) Things I tried till now : I was trying to implement this using asyncio but there we need to collect the set of future tasks and wait for completion using event loop. Something like this: async def process_individual_file(source, input_file): tasks = [] limit = 2000 with open(source+input_file) as sf: for line in sf: json_array.append(form_json(line)) limit -= 1 if limit == 0: tasks.append(asyncio.ensure_future(call_api(json_array))) limit = 2000 await asyncio.wait(tasks) ioloop = asyncio.get_event_loop() ioloop.run_until_complete(process_individual_file(source, input_file)) ioloop.close() 6) I am really not understanding this because this is indirectly the same as previous as it waits to colle…
has answer: http://stackoverflow.com/a/47963555
type: UnansweredQuestion
tagged with: python
score: 2
downvote count: 0
tagged with: concurrency
tagged with: http
type: Question
has title: Async HTTP API call for each line of file - Python

http://stackoverflow.com/comment/82752725
type: Comment
has text: sorry for the bad formatting, Stack overflow doesn't like spaces or tabs
comment on: http://stackoverflow.com/a/47892835
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82740495
has text: This is the link: **https://pypi.python.org/pypi/atd/0.1.5** What I am trying to reach is this code `import ATD ATD.setDefaultKey("your API key") errors = ATD.checkDocument("Looking too the water. Fixing your writing typoss.") for error in errors: print "%s error for: %s **%s**" % (error.type, error.precontext, error.string) print "some suggestions: %s" % (", ".join(error.suggestions),)` //Expected output:// `grammar error for: Looking **too the** some suggestions: to the spelling error for: writing **typoss** some suggestions: typos`
comment on: http://stackoverflow.com/q/47886265
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82892673
has text: @ShubhamSharma Sir, suppose I added title as "new title" then instead of giving "new-title" in the slug. It's giving "new-title-(& here title's id)". Even when the title "new title" is Unique.
comment on: http://stackoverflow.com/q/47961670
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/57496315
upvote count: 1
has body: I know this is a old post but this worked for me. Go to your python installation: example: C:\Python\Python37-32\Lib\site-packages\stopwordsiso Open __init__.py Change with open(STOPWORDS_FILE) as json_data: to with open(STOPWORDS_FILE, encoding="utf8") as json_data:
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47873161
score: 1

http://stackoverflow.com/q/47907032
has comment: http://stackoverflow.com/comment/82781304
tagged with: python
tagged with: python-2.x
has answer: http://stackoverflow.com/a/47907151
upvote count: 4
has comment: http://stackoverflow.com/comment/82781501
has comment: http://stackoverflow.com/comment/82781301
has comment: http://stackoverflow.com/comment/82781160
downvote count: 0
has answer: http://stackoverflow.com/a/47907139
has comment: http://stackoverflow.com/comment/82781182
tagged with: cpython
has body: I'm running: Python 2.7.8 (default, Oct 6 2017, 09:25:50) GCC 4.1.2 20070626 (Red Hat 4.1.2-14) on Linux 2 As per the documentation: The operators is and is not test for object identity: x is y is True if and only if x and y are the same object. To get an object's identity, we can use the id function. If we open up a new REPL we can see that 300 and -6 have the same identity (on CPython, this means that both refer to the same memory address): &gt;&gt;&gt; id(300) 94766593705400 &gt;&gt;&gt; id(-6) 94766593705400 Note that the actual values may differ from execution to execution, but they are always equal. However, doing 300 is -6 yields False: &gt;&gt;&gt; 300 is -6 False I have a couple of questions: Why (and how) do 300 and -6 share the same identity? If they do, why is 300 is -6 yielding False?
has comment: http://stackoverflow.com/comment/82781401
has title: The 'is' operator is not working on objects with the same identity
type: Question
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/24802740
tagged with: python-2.7
answer count: 2
score: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/82781475
duplicate of: http://stackoverflow.com/q/20753364
accepted answer: http://stackoverflow.com/a/47907139
possible better answer: http://stackoverflow.com/a/47907151

http://stackoverflow.com/a/47914020
type: Answer
answers question: http://stackoverflow.com/q/47913108
score: 2
accepted answer of: http://stackoverflow.com/q/47913108
has body: Add this line right below your ax.scatter() call: ax.plot(xs, ys, zs, zdir=zs, color="b", alpha=0.4)
type: AcceptedAnswer
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/82849008
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47921606
score: 0
has text: as a first debugging step, I'd print out the `elements` variable. Maybe you're not collecting the elements you expected?

http://stackoverflow.com/a/47920381
score: 0
answers question: http://stackoverflow.com/q/47919737
has body: This post may be deleted again for insufficient answer, but as someone who's been in a position not knowing what terms to search for when encountering these issues and wasted hours with no one telling me what to do.. I see the issue is caused by importing pandas in your case, but try searching with the error message printed. That usually leads to more clues. Last line reads 'AttributeError: module numpy has no attribute float128' There are threads on this matter on google, work from there on.
type: Answer

http://stackoverflow.com/q/47988065
tagged with: django
type: Question
tagged with: django-views
tagged with: django-models
upvote count: 1
downvote count: 0
favorite count: 0
has body: from below code i am going to print date ranges that's fine but what the problem is i need to print the date ranges , those available in database only [this image shows the created_at date field which is in look model . I need these dated to be printed if user select the date rage between dec 1 to dec 30 ]1 while (current_date &gt;= from_date): r = r + 1 ws.write(0,r,current_date,style) current_date -= timedelta(days = 1) models.py class Look(models.Model): created_at = models.DateField()
has title: Print Dates range if they are available in db
type: UnansweredQuestion
tagged with: python
tagged with: xlwt
answer count: 0
score: 1

http://stackoverflow.com/a/47960917
upvote count: 1
has body: The problem is that, basing from your example, once you are in the third line 1112 1912 1892 &lt;- When you are finally here 1234 The second line is already 1X12. So, a[] now looks like 1112 1X12 # Take note of the 'X' here. 1892 1234 So, when you reach ...and int(a[i-1][j]) &lt; int(a[i][j]) and... part of the conditional statement, a[i-1][j] would be returning 'X'. Now, since 'X' is a literal (an alphabetical character), it cannot be type casted to an integer using int(). You would need to use ord() to convert a character to its representative integer (i.e. ord('a') returns 97) but that will not give the proper results. One solution, from the top of my head, to solve this is to use two arrays. The first array (let's call it array A) will contain all the values entered by the user and is not to be modified. Array A will be used to compare the characters in each element. The second array (array B) will be used to contain the modified values. In other words, array B will have the values that have Xs. The code will look similar to your initial code but with a few changes to include the additional array. n = int(input()) a = [0 for i in range(n)] # This array will not be modified nor printed. This # will be used for comparisons only. b = [0 for i in range(n)] # This array will be used to store the modified values and # be the one printed instead. for i in range(n): a[i] = input() b[i] = a[i] # Here, we're duplicating the values from a[] to b[]. for i in range(n): if i == 0 or i == (n - 1): print(a[i]) else: for j in range(1, n - 1): if (int(a[i][j - 1]) &lt; int(a[i][j]) and int(a[i][j + 1]) &lt; int(a[i][j]) and int(a[i - 1][j]) &lt; int(a[i][j]) and int(a[i + 1][j]) &lt; int(a[i][j])): b[i] = a[i][:j] + 'X' + a[i][j + 1:] print(b[i])
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47959971
score: 1

http://stackoverflow.com/comment/82768066
has text: Aldo just wanted to know Is there any alternative to this step "filename = Tk.filedialog.askopenfilename() # Only works in 3.x" if I run in python 2.7.x ?
comment on: http://stackoverflow.com/a/47894701
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/54903693
type: Answer
answers question: http://stackoverflow.com/q/47994825
upvote count: 13
downvote count: 1
has body: this error occurs when you use wrong/invalid secret key for s3
score: 12

http://stackoverflow.com/q/47961289
upvote count: 7
tagged with: dockerfile
has answer: http://stackoverflow.com/a/66034108
has answer: http://stackoverflow.com/a/48001106
answer count: 5
has body: I have a python server that I run in a docker container. I log my messages with logging from python and I don't know how to find/view my log file from the container. # Pull base image FROM python:3 # Copy code to the container ADD src /usr/app WORKDIR /usr/app # run configuration COPY requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt # Start script CMD [ "python", "./main.py"] I start the server like this: sudo docker run -it -p 5000:5000 --rm my_app How can I access server logs? Thanks
tagged with: docker
has answer: http://stackoverflow.com/a/48002138
type: AnsweredQuestion
downvote count: 0
score: 7
accepted answer: http://stackoverflow.com/a/47961357
favorite count: 0
possible better answer: http://stackoverflow.com/a/47962266
type: Question
has answer: http://stackoverflow.com/a/47962266
tagged with: python
tagged with: logging
has answer: http://stackoverflow.com/a/47961357
has title: Access logs from docker container

http://stackoverflow.com/comment/82968945
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47959931
has text: Have you overridden ``sys.stdout`` in your WSGI script file or somehow via logging setup? What do you get for ``print(type(sys.stdout))``?
type: AnswerComment

http://stackoverflow.com/q/48004865
tagged with: if-statement
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48005237
tagged with: pandas
has title: If logic in Pandas, Python 3
favorite count: 0
possible better answer: http://stackoverflow.com/a/48005237
has answer: http://stackoverflow.com/a/48005219
tagged with: python
has body: I've got a Pandas Dataframe from which I want to compare two columns and create a new column with a calculation based off the result of the comparison. Logic would be the following: If df['column1']&gt;df['column2'] : df['New column']=(df['column1']+df['column2']) else : df['New column']=(df['column1']+df['column2']+1) I am fairly new to Pandas and Python so I'm sure I'm getting the structure wrong. Could you guys point me in the right direction?
upvote count: 2
score: 1
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82997924
accepted answer: http://stackoverflow.com/a/48005219

http://stackoverflow.com/q/47972846
linked to: http://stackoverflow.com/q/11328940
has answer: http://stackoverflow.com/a/47973597
accepted answer: http://stackoverflow.com/a/47972862
has comment: http://stackoverflow.com/comment/82915529
has comment: http://stackoverflow.com/comment/82915539
possible better answer: http://stackoverflow.com/a/47972988
linked to: http://stackoverflow.com/q/3271478
type: Question
downvote count: 4
upvote count: 0
has comment: http://stackoverflow.com/comment/82915535
has title: How do I check if a list of strings is in another list of strings?
has comment: http://stackoverflow.com/comment/82915318
has comment: http://stackoverflow.com/comment/82915506
has answer: http://stackoverflow.com/a/47972962
has answer: http://stackoverflow.com/a/47972862
answer count: 4
favorite count: 0
score: -4
has body: Example description = ['This is a random sentence. I like to travel and stuff','Hello world', 'Things on my bucket list, travel'] my_list = ['travel','fire'] I would like to check if ANY of the words on my_list is in description, if so don't do anything. If my_list is not in description I would like to return the string 'Keywords not found'. How would I go about writing this code?
linked to: http://stackoverflow.com/q/4843158
tagged with: python
has answer: http://stackoverflow.com/a/47972988
type: AnsweredQuestion

http://stackoverflow.com/comment/82899755
comment on: http://stackoverflow.com/a/47964935
type: Comment
has text: Try with this code: https://gist.github.com/eyllanesc/7f951debc8bac2c591a25a2982376397
score: 0
type: AnswerComment

http://stackoverflow.com/a/48109764
has comment: http://stackoverflow.com/comment/83209257
upvote count: 1
downvote count: 0
has body: Not sure if it can help, but I'll post it anyway I used requests to upload an image to ads import requests token = '***' url = f'https://api.vk.com/method/ads.getUploadURL?access_token={token}&amp;ad_format=1' # I set add_format randomly just to avoid an error of this parameter was missing upload_url = requests.get(url).json()['response'] post_fields = { 'access_token': token } data_fields = { 'file': open('/path/to/image.png', 'rb') } response = requests.post(upload_url, data=post_fields, files=data_fields) print(response.text) The result looks like valid photo upload, the data received can be used in further actions with ad API.
answers question: http://stackoverflow.com/q/47908968
type: Answer
has comment: http://stackoverflow.com/comment/83217576
score: 1

http://stackoverflow.com/q/47919194
score: 1
has body: I am trying to train an face detector using Dlib. I selected 300 images for training. I have used the Imglab tool to draw the bounding boxes across the images.And I have created traing.xml file. But I don't understand, How to create testing.xml file? Which type of data store in testing.xml file? Please someone help me. Thanks in advance.
type: Question
has title: How to create `testing.xml` file for dlib training?
upvote count: 1
answer count: 1
tagged with: training-data
tagged with: http://stackoverflow.com/tag/xml
favorite count: 0
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/36711905
has answer: http://stackoverflow.com/a/49079763
tagged with: c++
tagged with: dlib
downvote count: 0

http://stackoverflow.com/q/48008353
score: 0
answer count: 1
tagged with: world-map
has title: Python pygal code - World mapping
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48008693
accepted answer: http://stackoverflow.com/a/48008693
has body: Could you please help me with this code: import pygal from pygal.maps.world import World worldmap_chart = pygal.maps.world.World() worldmap_chart.title = 'Some countries' worldmap_chart.render() I use Spyder. Python 3.6 .The problem is that the map does not show up on the IPython console, and also on the second line of the code, I get yellow triangle/note that says: 'pygal.maps.world.World' imported but unused. Maybe this is the reason why the map does not show up. Otherwise, if it helps, in the IPython console I get only this: runfile('C:/Users/Nikki/.spyder-py3/untitled0.py', wdir='C:/Users/Nikki/.spyder-py3') Could you please help me to fix this?
tagged with: pygal
type: Question

http://stackoverflow.com/q/47926352
score: 2
answer count: 0
has comment: http://stackoverflow.com/comment/82822831
has comment: http://stackoverflow.com/comment/82821531
type: Question
has comment: http://stackoverflow.com/comment/82821646
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/82824414
has body: I am using Scikitlearn's labelencoder on my current data. I expect that my future data would sometimes have values for some of its variables that are not present in the current data - but I expect them to be a minority. I would like to encode them via the labelencoder as a "misc" category, rather than have them fail the transformation. Of course, I can do this via non-direct methods, i.e. use a dictionary and replace all such unknown future values with a "misc" label (and fit the encoder to recognize it), but I wonder if there is a way to do so more directly, and without the hassle of maintaining such a dictionary for every feature I want to encode in such a manner. Many thanks :)
has comment: http://stackoverflow.com/comment/82824315
has comment: http://stackoverflow.com/comment/82820942
has comment: http://stackoverflow.com/comment/82824511
downvote count: 0
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/82824995
type: UnansweredQuestion
tagged with: python
has title: Scikitlearn's labelencoder: How to add a "catch-all" miscellaneous encoding?

http://stackoverflow.com/comment/82830965
type: AnswerComment
comment on: http://stackoverflow.com/a/47930619
type: Comment
has text: so for the first example you suggested for the edit is what I already have- and it gives me the same issue where it shows one or the other. I tried modifying my code to your example, but I still got the same issue. For some reason it shows up if I'm plotting 2 lines, but if I try a bar and a line only one of them show up
score: 0

http://stackoverflow.com/a/47858074
answers question: http://stackoverflow.com/q/47857957
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/82680739
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82680898
has body: You're never making a new list, only printing things Try this list1 = ["training" , "bicycle", "working", "carrying", "bite" , "eat"] ing = [x for x in list1 if "ing" in x] print(ing) Or if you insist on having a function def filter_ing(l); return [x for x in l if "ing" in x]

http://stackoverflow.com/comment/82763079
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47879904
has text: `bin((~((1<<(32-24))-1)) & ((1<<32)-1))` => `'0b11111111111111111111111100000000`

http://stackoverflow.com/comment/82840418
type: QuestionComment
comment on: http://stackoverflow.com/q/47933724
has text: A suggestion for using symmetry is [here](https://stackoverflow.com/a/40710036). Unfortunately, there is no magic "go faster" button and I don't have a lot of time to test and verify your results, either.
score: 0
type: Comment

http://stackoverflow.com/comment/82952882
has text: I think I know what the problem was. _browser.find_element_by_css_selector("table#topnav_container2 tr td.topnavoff#topnav1 > a").click()_ This code worked after I added the Time module. Haha... I think It's because I never included sleep. This is the final code: _sleep(5) browser.find_element_by_css_selector("table#topnav_container2 tr td.topnavoff#topnav1 > a").click()_
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47990437

http://stackoverflow.com/comment/82722911
type: Comment
comment on: http://stackoverflow.com/a/47867014
score: 0
type: AnswerComment
has text: That's exactly the problem! Thank you for the clear explanation!

http://stackoverflow.com/comment/82831148
type: QuestionComment
comment on: http://stackoverflow.com/q/47931066
has text: I think you probably want to change `if hid is not in values:` to `if hid not in values:`. There is no need for `is`, while that may make sense in English, it [does something else in python](https://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is-in-python)
type: Comment
score: 0

http://stackoverflow.com/a/47859619
score: 1
answers question: http://stackoverflow.com/q/47858529
has body: Currently, you re-read each speech in memory once for each of the 250,000 names when you check "if member in self.body". You need to parse the speech body once, finding whole words, spaces, and punctuation. Then you need to see if you have found a name, using a linear time lookup of the known member names, or at worst log time. The problem is you have to find member names which have various word lengths. So here is a quick (and not very good) implementation I wrote up to handle checking the last three words. # This is where you load members from a file. # set gives us linear time lookup members = set() for line in ['First Person', 'Pele', 'Some Famous Writer']: members.add(line) # sample text text = 'When Some Famous Writer was talking to First Person about Pele blah blah blah blah' from collections import deque # pretend we are actually parsing, but I'm just splitting. So lazy. # This is why I'm not handling punctuation and spaces well, but not relevant to the current topic wordlist = text.split() # buffer the last three words buffer = deque() # TODO: loop while not done, but this sort of works to show the idea for word in wordlist: name = None if len(buffer) and buffer[0] in members: name = buffer.popleft() if not name and len(buffer)&gt;1: two_word_name = buffer[0] + ' ' + buffer[1] if two_word_name in members: name = two_word_name buffer.popleft() buffer.popleft() if not name and len(buffer)&gt;2: three_word_name = buffer[0] + ' ' + buffer[1] + ' ' + buffer[2] if three_word_name in members: name = three_word_name buffer.popleft() buffer.popleft() buffer.popleft() if name: print ('&lt;member&gt;', name, '&lt;/member&gt; ') if len(buffer) &gt;2: print (buffer.popleft() + ' ') buffer.append(word) # TODO handle the remaining words which are still in the buffer print (buffer) I am just trying to demonstrate the concept. This doesn't handle spaces or punctuation. This doesn't handle the end at all -- it needs to loop while not done. It creates a bunch of temporary str…
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82684135
type: Answer
has comment: http://stackoverflow.com/comment/82684129
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47858529
has comment: http://stackoverflow.com/comment/82684331

http://stackoverflow.com/a/47911402
score: 5
answers question: http://stackoverflow.com/q/47910328
upvote count: 5
type: Answer
downvote count: 0
has body: You can use iat to access scalar elements specifying the location by integer (i.e. 0,0 for the top left element, as opposed to at which would take the row and columns labels rather than integer index). So if you only have one element in your dataframe, df.iat[0,0] will get it for you. In [139]: import pandas as pd In [140]: df = pd.DataFrame(data=[1], columns=['col1']) In [141]: df.iat[0,0] Out[141]: 1 In [143]: df Out[143]: col1 0 1

http://stackoverflow.com/a/47913485
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/82794706
has comment: http://stackoverflow.com/comment/82794678
has body: Using np.char.find - v = df.Description.values.astype('U')[:, None] df['in list'] = (np.char.find(v, list_) &gt; 0).any(1) df Description in list 0 2 Bedroom/1.5 Bathroom end unit Townhouse. Av... True 1 Very spacious studio apartment available True 2 Two bedroom, 1 bathroom condominium, superbly... False
score: 1
answers question: http://stackoverflow.com/q/47913310
downvote count: 0

http://stackoverflow.com/q/47987345
score: 1
type: Question
has answer: http://stackoverflow.com/a/48001411
has comment: http://stackoverflow.com/comment/82946041
upvote count: 1
answer count: 1
has title: How to make a separate element-dict out of bs4.element.Tag list?
favorite count: 0
tagged with: beautifulsoup
has body: I have scrapped a webpage where I saved a defaultdict named ecg_machines['City'] = [] with &lt;li&gt;-elements as elements in list and are of type &lt;class 'bs4.element.Tag'&gt;. For example I have an elementecg_machines['Delhi'][0] = &lt;li class="lst lst_cl mft2 img llc " data-catid="" data-city="New Delhi" data-csttypnm="LEADER" data-csttypwgt="149" data-dispid="3374118533" data-glid="4291542" data-mcatid="" data-modref="2" data-state="Delhi" id="LST1"&gt;&lt;div class="clz"&gt;&lt;p class="pnt"&gt;&lt;a class="pnm ldf cur" href="http://www.goodhealthinc.in/digital-ecg-machine.html#digital-3-channel-ecg-machine" target="_blank" title=""&gt;Digital 3 Channel ECG Machine&lt;/a&gt;&lt;/p&gt;&lt;a class="ribn NP-1 " id="1imgenq"&gt;&lt;div class="bg rib"&gt;&lt;/div&gt;&lt;div class="nor_i imwd"&gt;&lt;img alt="Digital 3 Channel ECG Machine" data-limg="//4.imimg.com/data4/JC/MY/MY-4291542/digital-3-channel-ecg-machine-500x500.jpg" id="bu1" src="//4.imimg.com/data4/JC/MY/MY-4291542/digital-3-channel-ecg-machine-250x250.jpg"/&gt;&lt;/div&gt;&lt;/a&gt;&lt;div class="lstw"&gt;&lt;div class="ldc"&gt;&lt;p class="desc des_p" id="trimmed_desc1"&gt;&lt;b&gt;Application&lt;/b&gt;: Resting &amp;amp; Diagnostic&lt;br&gt;&lt;b&gt;Brand&lt;/b&gt;: Allied Medical&lt;br&gt;&lt;b&gt;Types&lt;/b&gt;: 3-Lead, 12-Lead&lt;br&gt;&lt;b&gt;Operation Mode&lt;/b&gt;: Portable&lt;br&gt;&lt;b&gt;Channel&lt;/b&gt; &lt;a class="wh mlin" href="http://www.goodhealthinc.in/digital-ecg-machine.html#digital-3-channel-ecg-machine" target="_blank"&gt; more..&lt;/a&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt;&lt;/p&gt;&lt;div class="prc NP-1" id="1prcenq"&gt;Rs 31,500/&lt;span class="quan"&gt; Piece&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class="spro"&gt;&lt;div class="nsim"&gt;&lt;span&gt;&lt;img alt="Digital ECG Machine" data-modref="2" data-prc="Rs 31,500/ Unit" data-slimg="//4.imimg.com/data4/PI/DK/MY-4291542/digital-ecg-machine-500x500.jpg" id="rp1_1" src="//4.imimg.…
tagged with: http://stackoverflow.com/tag/html
tagged with: python
downvote count: 0
type: UnansweredQuestion
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/82945671

http://stackoverflow.com/comment/82804514
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47918226
has text: Thanks, also I was wondering if I am making the backend and the frontend guys are giving a search term, can I use the term with url and how?
score: 0

http://stackoverflow.com/comment/83010673
score: 0
has text: Thanks AndreyF for the answer. I needed to process each DataFrame later and that's why I used them separately.
type: AnswerComment
comment on: http://stackoverflow.com/a/47902943
type: Comment

theano
tags question: http://stackoverflow.com/q/47927099
tag name: theano
type: Tag

http://stackoverflow.com/q/47961638
has title: Give permission to AWS Lambda to List all SNS topics
downvote count: 0
has body: I have a cloudformation template to create a lambda function and an SNS topic. The lambda function does some processing and publishes the result to the SNS topic. To get the SNS topic's ARN, I'm using the boto3.client('sns').list_topics() function and then searching for the SNS topic name that I've set in the template. But calling the list_topics() API is giving me the following error: An error occurred (AuthorizationError) when calling the ListTopics operation: User: arn:aws:sts::136732452473:assumed-role/test/severless-btc-update-PriceUpdateFunction-B38KNZMCBGB is not authorized to perform: SNS:ListTopics on resource: arn:aws:sns:eu-west-1:136732452473:* How can I add the ListTopics permission to my lambda resource in the cloudformation template YAML file? This is my cloudformation.yaml file: AWSTemplateFormatVersion: "2010-09-09" Transform: AWS::Serverless-2016-10-31 Description: Bitcoin daily update Parameters: PhoneNumber: Type: String Description: The phone number recipient of the update, in E.164 (e.g. +919876123456) format. UTCHour: Type: String Default: 3 Description: The hour at which to send the update, in the UTC time zone. Resources: PriceUpdateFunction: Type: AWS::Serverless::Function Properties: Handler: main.lambda_handler Runtime: python3.6 Timeout: 5 CodeUri: main.py Environment: Variables: PHONE_NUMBER: !Ref PhoneNumber Events: ScheduledEvent: Type: Schedule Properties: Schedule: !Join [' ', ['cron(0', !Ref UTCHour, '* * ? *)']] Policies: - SNSPublishMessagePolicy: TopicName: !GetAtt SNSTopic.TopicName SNSTopic: Type: "AWS::SNS::Topic" Properties: TopicName: "sendSMS" DisplayName: "BitcoinPriceTopic" Subscription: - Endpoint: !Ref PhoneNumber Protocol: "sms"
tagged with: boto3
tagged with: amazon-web-services
tagged with: aws-lambda
answer count: 1
accepted answer: http://stackoverflow.com/a/47962001
favorite count: 0
tagged with: amazon-sns
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
type: Question
has answer: http://stackoverflow.com/a/47962001

http://stackoverflow.com/a/47888128
answers question: http://stackoverflow.com/q/47887445
has body: Once you found the headers row, you can write it and the remaining rows to your outfile: with open(latest_file, "rb") as infile: reader = csv.reader(infile) for row in reader: if row[0] == 'date/time': break else: print("{} not found".format('name')) return with open("path/to/new.csv", "wb") as outfile: writer = csv.writer(outfile) writer.writerow(row) # headers writer.writerows(reader) # remaining rows
has comment: http://stackoverflow.com/comment/82759238
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47887445
score: 0
has comment: http://stackoverflow.com/comment/82769244
type: Answer

http://stackoverflow.com/comment/108671014
comment on: http://stackoverflow.com/q/47885927
type: Comment
type: QuestionComment
score: 2
has text: https://stackoverflow.com/questions/41648103/how-would-i-go-about-using-concurrent-futures-and-queues-for-a-real-time-scenari

http://stackoverflow.com/comment/82939917
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47985462
has text: Ah damn, new it was a dumb error. Thanks for the assist - I'll accept when it allows.
type: AnswerComment

http://stackoverflow.com/a/66873474
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47860292
has body: df.groupby(['name', 'date'])['number'].sum().unstack() Explanation: groupby name and date. Pick number from group Sum all numbers and unstack

http://stackoverflow.com/a/47929451
answers question: http://stackoverflow.com/q/47928702
downvote count: 0
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/82845313
has body: how about a 'map happy' approach - just for fun, not any advantages I can see list(map(list, map(lambda txt: map(lambda x: x.rstrip('D'), txt), texts))) Out[240]: [['abcd', 'asdfa'], ['qerq', 'asdfafdas']]

http://stackoverflow.com/q/47898427
has body: I am new to django and eventually I learnt the use of static files in Django and to my relief I was finally able to load the files while hardcoding the file name in the {%static filename.jpg %}. However, when I tried to create a string by replacing the hardcoded filename.jpg with the dynamic file name, I wasn't getting the output. Not working code snippet: &lt;script&gt; image_name = "1.png" static_start = "{% static '" static_end = "' %}" image_src = static_start.concat(image_name, static_end) window.alert(image_src) var para = document.createElement("img"); {% load static %} para.setAttribute("src", image_src) var element = document.getElementById("div_test"); element.appendChild(para); &lt;/script&gt; Working Code snippet: &lt;script&gt; var para = document.createElement("img"); {% load static %} para.setAttribute("src", "{%static '1.png'%}") var element = document.getElementById("div_test"); element.appendChild(para); &lt;/script&gt; What I am trying to do is that, I have a bunch of image files that I am getting from somewhere through an API and I am storing them in the static folder. After downloading those image, I am trying to load them on my webpage, for that I am using the static file and getting the file name dynamically as I do not know what would the file name of the downloaded file. The point is that string concatenation isn't working, while directly passing the string is. Any help would really be appreciated. P.S.: Apparently in the example shared above I am simply using 1.png which would eventually be replaced by the name of the file I wish to display. Working code using get_static_prefix (the way I actually wanted) &lt;script&gt; image_name = "1.png" var para = document.createElement("img"); {% load static %} para.setAttribute("src", "{% get_static_prefix %}" + image_name) var element = document.getElementById("div_test"); element.appendChild(para); &lt;/script&gt;
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/18040941
tagged with: django
tagged with: python
has title: Unable to load concatenated static file source
type: Question
has answer: http://stackoverflow.com/a/47900157
tagged with: static-files
tagged with: javascript
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47916685
tagged with: django-staticfiles

http://stackoverflow.com/comment/82819698
type: QuestionComment
comment on: http://stackoverflow.com/q/47925268
score: 0
type: Comment
has text: What are going to do next with this element?

http://stackoverflow.com/q/47952986
accepted answer: http://stackoverflow.com/a/47953020
type: Question
has title: Resample time-series and show time of day
has body: This is driving me crazy. I am trying to find the maximum daily value for a time series while showing the time of day when it occurred. I have a datetimeindex, a second datetime column, and a max temperature. If I do temperature_max = temperature.resample('D').max() I get maximum values for both time (23:59) and temperature. How can I get the time of day when max temperature occurred? Many thanks!
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
upvote count: 2
tagged with: datetime
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47953020
tagged with: python-datetime

http://stackoverflow.com/q/47977953
has comment: http://stackoverflow.com/comment/82924961
has comment: http://stackoverflow.com/comment/82924982
type: Question
has body: I was given this school project, which goal is to take a picture, apply the RLE method in order to compress it in a binary file (.txt), and save some space. And after struglling with it for 3 days now I'm having troubles. def read(): f2=open("data2.txt",'rb') #open a binary file in reading mod. im3=zeros((962,800,3),dtype="uint8") #create picture which size is 962*800 where every pixels are coded on 3 bytes. d=0#pixel counter i=0#lign indexation j=0#column indexation b=ord(f2.read(1))# the informations are read a first time a=ord(f2.read(1)) red=ord(f2.read(1)) green=ord(f2.read(1)) blue=ord(f2.read(1)) while i!=im3.shape[0]: #as long as it doesn't reach the final lign if d<=(a+b*255): im3[i,j,0] = red im3[i,j,1] = green im3[i,j,2] = blue d+=1 j+=1 if j==im3.shape[1]: j=0 i+=1 else: #resets pixel counter and starts reading next informations d=0 b=ord(f2.read(1)) a=ord(f2.read(1)) red=ord(f2.read(1)) green=ord(f2.read(1)) blue=ord(f2.read(1)) f2.close() imsave("done.bmp",im3) return im3 imshow(read()); show(); When I execute the pgrm, it gives me this error written in the tittle. Which is something I feel like impossible to correct, since it is writting itself in hex. Here's further information : A pixel is not coded here using bytes, like we usually do on format such as .bmp. Here RLE will search for identic pixel on a same lign, and count how many times it encounters it, by comparing 3 levels colors. Finally it stores in two additional bytes than the RGB ones : a and b. a is for the number of pixels. b is the number of 255 stacks of pixels. (Since I'm coding data into 8bits and that pictures are usually larger than 255*255 size)
has comment: http://stackoverflow.com/comment/82925285
has comment: http://stackoverflow.com/comment/82924676
has comment: http://stackoverflow.com/comment/82925328
tagged with: image
upvote count: 2
has comment: http://stackoverflow.com/comment/82924769
has comment: http://stackoverflow.com/comment/82925199
has comment: http://stackoverflow.com/comment/82924951
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82924779
has title: TypeError: ord() expected a character, but string of length 0 found
has comment: http://stackoverflow.com/comment/82924971
has comment: http://stackoverflow.com/comment/82924735
tagged with: python
tagged with: ord
score: 2
has comment: http://stackoverflow.com/comment/82924754
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47978275

http://stackoverflow.com/q/47934894
type: Question
has comment: http://stackoverflow.com/comment/82839947
has comment: http://stackoverflow.com/comment/82839988
has comment: http://stackoverflow.com/comment/82839997
has answer: http://stackoverflow.com/a/47935301
accepted answer: http://stackoverflow.com/a/47935301
tagged with: arrays
answer count: 1
has title: TypeError: must be str, not dict in Python
downvote count: 0
has body: I am following this tutorial and trying to extract certain value out to be inserted into Firebase. How can I actually group certain type together, remove duplicates and insert into Firebase with desired structure? Like for example: household cleaning kitchen appliance: conf air freshener: conf laundry &amp; ironing needs: conf kitchen appliance household cleaning: conf ... Because I intended to do something like, for each type, I get the associated type together with its conf and insert into Firebase. But as of now I not sure how can I achieve it. What I have tried so far is: result = list() calcConf() result.append((freqSet-conseq, conseq, conf)) for freqSet in result: for item in freqSet: print(item) It did split out each associated type as such: set({'household cleaning'}) set({'kitchen appliance'}) 0.5087719298245614 set({'kitchen appliance'}) set({'household cleaning'}) 0.4172661870503597 set({'household cleaning'}) set({'air freshener'}) 0.7105263157894738 But I not sure how can I proceed further to insert into the desired structure into Firebase. Previously I was doing in JavaScript with object array but I not sure if it is applicable in Python as well. Any ideas? Thanks! EDIT I tried with object array: class parts: def __init__(self, s1, s1, s3): self.s1= s1 self.s2= s2 self.s3= s3 Then, I populated the result list as such: result.append(parts(freqSet, conseq, conf)) When I tried to insert into firebase: for t in result: fstr= t.freqSet.strip('set({})') cstr= t.conseq.strip('set({})') print(fstr, cstr, t.conf) firebase.patch('/test/' + fstr+ {cstr: t.conf}) I am getting this error message: firebase.patch('/marketBasketAnalysis/' + fstr + {cstr: t.conf}) TypeError: must be str, not dict
favorite count: 0
has comment: http://stackoverflow.com/comment/82839453
upvote count: 1
tagged with: python
tagged with: firebase
type: AnsweredQuestion
tagged with: list
score: 1
tagged with: loops
has comment: http://stackoverflow.com/comment/82839511
has comment: http://stackoverflow.com/comment/82839338

wamp
tags question: http://stackoverflow.com/q/48012394
tag name: wamp
type: Tag

http://stackoverflow.com/comment/83796449
score: 0
has text: [Tridiagonal solver numpy](https://gist.github.com/ofan666/1875903) should work right off for complex too. ([Tridiagonal solver cython](https://github.com/cpcloud/PyTDMA) ? [complex-numbers-in-cython](https://stackoverflow.com/questions/30054019/complex-numbers-in-cython) look messy, at least gcc.)
comment on: http://stackoverflow.com/q/47933724
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47868903
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47868631
has body: There is no way to enforce this at DB level nor a simple way to do it in Django level. With your structure you should add some validation before creating (or modifying) both Busy and Reserved. Something like: class Busy(models.Model): room = models.ForeignKey(Room) def __save__(self, *args, **kwargs): if Reserved.object.filter(room=self.room).exists(): raise RuntimeError('Trying to make a reserved room busy.') super(Busy, self).__save__(*args, **kwargs) If you are creating Busy and Reserved objects concurrently it's subject to race condition. I suggest to move room state into Room model itself and add some helper functions (something like in room_manager.py beside models.py) to change its state and make sure related models are created/modified in a consistent manner.

http://stackoverflow.com/comment/82852222
comment on: http://stackoverflow.com/q/47941418
type: Comment
type: QuestionComment
has text: As you mentioned, you can use pip and create `requirement.txt` file to install required packages.
score: 0

http://stackoverflow.com/comment/82743454
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47888650
type: Comment
has text: And do you know how can I find all the link that contain a pdf file ?

http://stackoverflow.com/a/67819799
score: 31
upvote count: 31
has body: Although the idea can be derived from the chosen answer, I feel like I want to write that explicitly. Being able to decide when to call optimizer.zero_grad() and optimizer.step() provides more freedom on how gradients are accumulated and applied by the optimizer in the training loop. This is crucial when the model or input data is big and one training batch do not fit on the GPU. Here in this example, there are two arguments, named train_batch_size and gradient_accumulation_steps. train_batch_size is the batch size for the forward pass, following the loss.backward(). This is limited by the gpu memory. gradient_accumulation_steps is the actual training batch size, where loss from multiple forward pass is accumulated. This is NOT limited by the gpu memory. From this example, you can see how optimizer.zero_grad() may followed by optimizer.step() but NOT loss.backward(). loss.backward() is invoked in every single iteration (line 216) but optimizer.zero_grad() and optimizer.step() is only invoked when the number of accumulated train batch equals the gradient_accumulation_steps (line 227 inside the if block in line 219) Also, someone is asking about the equivalent method in TensorFlow. I guess tf.GradientTape serves the same purpose.
downvote count: 0
has comment: http://stackoverflow.com/comment/123228554
type: Answer
answers question: http://stackoverflow.com/q/48001598

http://stackoverflow.com/a/62784098
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47957230
answers question: http://stackoverflow.com/q/47957230
type: AcceptedAnswer
has body: Several options, taken from here: 1-(an older approach): {% with entry.image_set.all|first as image %} &lt;img src=&quot;{{ image.get_absolute_url }}&quot;&gt; {% endwith %} 2-Since Django 1.6ish &lt;img src=&quot;{{ entry.image_set.first.get_absolute_url }}&quot;&gt;
upvote count: 3
type: Answer
score: 3

http://stackoverflow.com/a/47942082
type: Answer
has comment: http://stackoverflow.com/comment/82855154
has comment: http://stackoverflow.com/comment/82854224
has body: I think that you have to collect the static files with this command, from the server instance : ./manage.py collectstatic Then the updates in static files will be considered.
has comment: http://stackoverflow.com/comment/82854289
score: 0
answers question: http://stackoverflow.com/q/47941991

http://stackoverflow.com/q/47929077
has comment: http://stackoverflow.com/comment/82826719
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/82828364
score: 1
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/47929115
type: Question
has answer: http://stackoverflow.com/a/47929408
accepted answer: http://stackoverflow.com/a/47929408
answer count: 2
has body: I am using pandas dataframe: import pandas as pd a = [1,2,3] i = [5,2,3] df = pd.DataFrame( { "foo" : i, "bar" : a } ) df = df.set_index("foo") l = df.values.tolist() # l = [[1], [2], [3]] This is annoying I'w like l = [1,2,3]. Why we get a list of list? How can just get a list?
downvote count: 0
tagged with: pandas
has title: Converting pandas dataframe with only one column to 1D list
has answer: http://stackoverflow.com/a/47929115
favorite count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82827378

http://stackoverflow.com/comment/82710258
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47871598
type: AnswerComment
has text: @geeg if you have tests that match the [pytest discovery logic](https://docs.pytest.org/en/latest/example/pythoncollection.html), it would auto-discover them automatically and run.

http://stackoverflow.com/comment/82757429
type: QuestionComment
comment on: http://stackoverflow.com/q/47895267
has text: `nlog(n)+2n` is `n*(log(n)+2)` hence `O(nlog(n))`. It maybe slower, but the ratio is the same: computation time increases the same way when n increases.
score: 0
type: Comment

http://stackoverflow.com/comment/82680453
has text: What's the measure of sparse-ty for your actual use-case? Percentage non-zeros?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47857372

http://stackoverflow.com/q/47893496
has comment: http://stackoverflow.com/comment/82758227
has title: cons to using flask-sqlalchemy pickletype
tagged with: flask
score: 0
has comment: http://stackoverflow.com/comment/82754334
has comment: http://stackoverflow.com/comment/82755262
has comment: http://stackoverflow.com/comment/82753782
has comment: http://stackoverflow.com/comment/82754048
tagged with: flask-sqlalchemy
has body: I have data that looks something like this: projects = [ { 'title': 'Project A', 'point_of_contact': {'name': 'Johnny', 'org': 'Box'}, 'overrides': [4, 7, 99, 42], 'tier_mapping': {1: 2000, 2: 4000, 3: 8000, 4: 12000}, 'milestones': [{'year': 2014, 'achievement': 'Model development'}, {'year': 2014, 'achievement': 'Model approved by board'}] }, { 'title': 'Project B', ... } As you can tell there's no obvious structure. I'm looking to add this to my sql-backed flask web application. The easiest option would be to create a single table using flask-sqlalchemy: class Project(db.Model): id = db.Column(db.Integer, primary_key=True) data = db.Column(db.PickleType) Another option would be to create a table for each iterative item and map that to its respective Project. For example, creating a relationship between a project and its overrides may look like this: class Project(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(50)) overrides = db.relationship('Override', backref='mapped_project', lazy='dynamic') class Override(dn.Model): id = db.Column(db.Integer, primary_key=True) override = db.Column(db.Integer) project_id = db.Column(db.Integer, db.ForeignKey('project.id')) My question is are either of the following database models "better"? Is there a con to using the first model (performance, etc.), which clearly easier to setup. I imagine the only con is the pickle type isn't clear what we are storing. Note this web app is growing every month so I prefer a flexible database model. I know MongoDB would probably be a better choice here but everything is already written with SQL and I don't want to rewrite the entire app.
type: UnansweredQuestion
tagged with: python
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/82753965

http://stackoverflow.com/comment/82856481
type: QuestionComment
has text: @PhillipMartin it ends up even worse: Traceback (most recent call last): File "C:\....", line 2, in <module> from NoteFunc import * File "C:\....y", line 2, in <module> from Notenote import main_text File "C:\....", line 54, in <module> compound='left', command=cut) NameError: name 'cut' is not defined
type: Comment
comment on: http://stackoverflow.com/q/47943413
score: 0

http://stackoverflow.com/q/47982117
tagged with: nltk
answer count: 1
linked to: http://stackoverflow.com/q/14535730
favorite count: 0
tagged with: python
linked to: http://stackoverflow.com/q/2671376
has comment: http://stackoverflow.com/comment/82932701
linked to: http://stackoverflow.com/q/42203673
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/13464152
tagged with: list
downvote count: 0
has body: I know there's been several very similar answers here on SO on this exact question, but none of them really answer my question. I'm trying to remove a series of stop words and punctuation from a list of words to perform basic natural language processing. from nltk.tokenize import word_tokenize, sent_tokenize from nltk.corpus import stopwords from string import punctuation text = "Hello there. I am currently typing Python. " custom_stopwords = set(stopwords.words('english')+list(punctuation)) # tokenizes the text into a sentence sentences = sent_tokenize(text) # tokenizes each sentence into a list of words words = [word_tokenize(sentence) for sentence in sentences] filtered_words = [word for word in words if word not in custom_stopwords] print(filtered_words) This throws a TypeError: unhashable type: 'list' error on the filtered_words line. Why is this error being thrown? I'm not providing a list collection at all- I'm providing a set? Note: I've read the post on SO on this exact error, but still have the same question. The accepted answer provides this explanation: Sets require their items to be hashable. Out of types predefined by Python only the immutable ones, such as strings, numbers, and tuples, are hashable. Mutable types, such as lists and dicts, are not hashable because a change of their contents would change the hash and break the lookup code. I'm providing a set of strings here, so why is Python still complaining? EDIT: after reading more into this SO post, which recommends using tuples, I edited my collection object: custom_stopwords = tuple(stopwords.words('english')) I also realized I have to flatten my list, since word_tokenize(sentence) will create a list of lists, and will not filter out punctuation correctly (since a list object will not be in custom_stopwords, which is a list of strings. However, this still begs the question- why are tuples considered hashable by Python but string sets not? And why does the TypeError say list?
has answer: http://stackoverflow.com/a/47982154
accepted answer: http://stackoverflow.com/a/47982154
linked to: http://stackoverflow.com/q/26600462
type: Question
upvote count: 2
has title: Type Error: unhashable type: list when using Python set of strings

http://stackoverflow.com/comment/82983197
type: AnswerComment
comment on: http://stackoverflow.com/a/48003242
type: Comment
has text: Great that it helped. BTW, you can [accept](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) an answer if it solves your problem.
score: 0

http://stackoverflow.com/comment/82703108
comment on: http://stackoverflow.com/a/47868589
score: 0
type: AnswerComment
type: Comment
has text: @splash58 The problem isn't that it doesn't work, it's that it's tedious to implement.

http://stackoverflow.com/comment/135648966
score: 0
type: Comment
has text: Hello plamut, could you tell me how i create the todo_profile.cprof file?
comment on: http://stackoverflow.com/a/47860201
type: AnswerComment

http://stackoverflow.com/q/47901069
tagged with: profiling
downvote count: 0
favorite count: 0
has title: Identify memory use
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82774701
answer count: 0
type: UnansweredQuestion
tagged with: garbage-collection
upvote count: 1
tagged with: python
score: 1
has comment: http://stackoverflow.com/comment/82770876
has body: My application has an in-memory cache which is eventually using lots of memory. I would like to quantify this. For that I have just run a memory profiler, and I have obtained the following plot: I was expecting memory use to go down when processing is complete, since I am cleaning the cache, but memory use remains constant long after processing has finished. I have introduced a big artificial delay after cleaning the cache, and I have even forced garbage collection by calling gc.collect(), but nothing is helping. How can I identify where is memory being used?
tagged with: memory
type: Question

http://stackoverflow.com/tag/html
tags question: http://stackoverflow.com/q/47881618
tags question: http://stackoverflow.com/q/48004509
tags question: http://stackoverflow.com/q/47910865
tags question: http://stackoverflow.com/q/47867758
tags question: http://stackoverflow.com/q/47949900
tags question: http://stackoverflow.com/q/47924370
tags question: http://stackoverflow.com/q/47859999
tags question: http://stackoverflow.com/q/47996814
tags question: http://stackoverflow.com/q/47966110
tags question: http://stackoverflow.com/q/47989711
tags question: http://stackoverflow.com/q/48010797
tags question: http://stackoverflow.com/q/47928120
tags question: http://stackoverflow.com/q/47995681
tags question: http://stackoverflow.com/q/47877011
tags question: http://stackoverflow.com/q/47986874
tags question: http://stackoverflow.com/q/47950680
tags question: http://stackoverflow.com/q/47869107
tags question: http://stackoverflow.com/q/47856300
tags question: http://stackoverflow.com/q/47983474
tags question: http://stackoverflow.com/q/47893423
tags question: http://stackoverflow.com/q/47872975
tags question: http://stackoverflow.com/q/47877691
tags question: http://stackoverflow.com/q/47879140
tags question: http://stackoverflow.com/q/47996863
type: Tag
tags question: http://stackoverflow.com/q/47927356
tags question: http://stackoverflow.com/q/47858928
tags question: http://stackoverflow.com/q/47917891
tags question: http://stackoverflow.com/q/47885747
tags question: http://stackoverflow.com/q/47926904
tags question: http://stackoverflow.com/q/47942308
tags question: http://stackoverflow.com/q/47904142
tags question: http://stackoverflow.com/q/47961481
tags question: http://stackoverflow.com/q/47894506
tags question: http://stackoverflow.com/q/48001958
tags question: http://stackoverflow.com/q/47903134
tags question: http://stackoverflow.com/q/47948225
tags question: http://stackoverflow.com/q/47878402
tags question: http://stackoverflow.com/q/47955660
tags question: http://stackoverflow.com/q/47980291
tags question: http://stackoverflow.com/q/47909111
tags question: http://stackoverflow.com/q/47863031
tags question: http://stackoverflow.com/q/48010839
tags question: http://stackoverflow.com/q/47964266
tags question: http://stackoverflow.com/q/48004556
tags question: http://stackoverflow.com/q/47950107
tags question: http://stackoverflow.com/q/47932550
tags question: http://stackoverflow.com/q/47945029
tags question: http://stackoverflow.com/q/47876617
tags question: http://stackoverflow.com/q/48006214
tags question: http://stackoverflow.com/q/47965265
tags question: http://stackoverflow.com/q/47863507
tags question: http://stackoverflow.com/q/47899126
tags question: http://stackoverflow.com/q/47969850
tags question: http://stackoverflow.com/q/47883911
tags question: http://stackoverflow.com/q/47931105
tags question: http://stackoverflow.com/q/47882039
tags question: http://stackoverflow.com/q/47997725
tags question: http://stackoverflow.com/q/47991145
tags question: http://stackoverflow.com/q/47987345
tags question: http://stackoverflow.com/q/47923952
tags question: http://stackoverflow.com/q/47957983
tag name: html
tags question: http://stackoverflow.com/q/47958342
tags question: http://stackoverflow.com/q/47979117
tags question: http://stackoverflow.com/q/47937366
tags question: http://stackoverflow.com/q/47905932
tags question: http://stackoverflow.com/q/47957827

http://stackoverflow.com/comment/82860364
has text: Apply the mask within `.loc`. As in `df.loc[mask,('B')] = "A"`
comment on: http://stackoverflow.com/q/47945300
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47981756
duplicate of: http://stackoverflow.com/q/30936779
tagged with: scikit-learn
has body: I'm trying to use Jython to fetch predictions from a Scikit model. But Jyton is failing to import the scikit module with an odd AttributeError. Here's the Java exception: Exception in thread "MainThread" Traceback (most recent call last): File "C:/pydata/loadModel.py", line 1, in &lt;module&gt; from sklearn.externals import joblib File "C:\Python\Python36\Lib\site-packages\sklearn\__init__.py", line 98, in &lt;module&gt; warnings.filterwarnings('always', category=DeprecationWarning, AttributeError: 'str' object has no attribute 'format' This is how I'm loading the modules in Java PythonInterpreter intep = new PythonInterpreter(); PySystemState sys = intep.getSystemState(); sys.path.append(new PyString("C:\\Python\\Python36\\Lib\\site-packages")); intep.execfile("C:/pydata/loadModel.py"); I'm on Java8 with Python 3.6.3 and Jython-Standalone 2.5.2 Thanks
has title: Jython fails to load Scikit Module
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/82944973
linked to: http://stackoverflow.com/q/30936779
answer count: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/82933182
has comment: http://stackoverflow.com/comment/82955270
tagged with: jython

http://stackoverflow.com/comment/82801551
has text: I also do think your math does not make much sense. If the jacobian is constant (and nonzero), those algorithms will probably never converge.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47916639

http://stackoverflow.com/comment/82895367
has text: how would the part of the while with the after,thank you
score: 0
comment on: http://stackoverflow.com/q/47961996
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47918756
score: 3
downvote count: 0
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/47918691
has body: Reshape and then swap the axes around: arr1 = arr.reshape(N/5,5,1,20) arr2 = arr1.transpose(0,2,3,1) for example In [476]: arr = np.arange(24).reshape(6,4) In [477]: arr Out[477]: 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]]) In [478]: arr1 = arr.reshape(2,3,1,4) In [479]: arr2 = arr1.transpose(0,2,3,1) In [480]: arr2.shape Out[480]: (2, 1, 4, 3) In [482]: arr2 Out[482]: array([[[[ 0, 4, 8], [ 1, 5, 9], [ 2, 6, 10], [ 3, 7, 11]]], [[[12, 16, 20], [13, 17, 21], [14, 18, 22], [15, 19, 23]]]])

http://stackoverflow.com/comment/82796672
type: Comment
comment on: http://stackoverflow.com/a/47900171
type: AnswerComment
score: 0
has text: Sadly no, I did find a work around not involving the text `Active:` though.

http://stackoverflow.com/comment/83123541
comment on: http://stackoverflow.com/q/47928898
has text: Can you please show the actual code that generates the error message?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82854008
has text: no, no, We'd need a clean copy/paste of the command & error you're getting
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47942031
type: Comment

http://stackoverflow.com/q/47987202
has body: I am trying to see how softmax_cross_entropy_with_logits_v2() is implemented. It calls _softmax_cross_entropy_with_logits(). But I don't see where the latter is defined. Does anybody know how to locate its definition? $ ack '\b_softmax_cross_entropy_with_logits\b' tensorflow/compiler/tests/binary_ops_test.py 176: gen_nn_ops._softmax_cross_entropy_with_logits, tensorflow/python/kernel_tests/xent_op_test.py 52: loss, backprop = gen_nn_ops._softmax_cross_entropy_with_logits( 75: loss, backprop = gen_nn_ops._softmax_cross_entropy_with_logits( 93: gen_nn_ops._softmax_cross_entropy_with_logits, 135: gen_nn_ops._softmax_cross_entropy_with_logits( 141: gen_nn_ops._softmax_cross_entropy_with_logits([0., 1., 2., 3.], tensorflow/python/ops/nn_ops.py 1803: cost, unused_backprop = gen_nn_ops._softmax_cross_entropy_with_logits(
tagged with: neural-network
score: 6
tagged with: deep-learning
type: AnsweredQuestion
favorite count: 0
has title: Where is `_softmax_cross_entropy_with_logits` defined in tensorflow?
type: Question
answer count: 2
tagged with: python
has answer: http://stackoverflow.com/a/47994713
accepted answer: http://stackoverflow.com/a/47994713
downvote count: 1
tagged with: ack
linked to: http://stackoverflow.com/q/41147734
possible better answer: http://stackoverflow.com/a/47987658
has answer: http://stackoverflow.com/a/47987658
upvote count: 7
tagged with: tensorflow
linked to: http://stackoverflow.com/q/46858070

http://stackoverflow.com/comment/82783734
type: Comment
score: 0
has text: Thank you, Shiva. It works! I want to convert all number data to float type. Is there any fast solution?
type: AnswerComment
comment on: http://stackoverflow.com/a/47908102

http://stackoverflow.com/comment/82871015
type: Comment
type: QuestionComment
has text: @DanielJ.Anderson network (scraping) :)
comment on: http://stackoverflow.com/q/47914844
score: 0

http://stackoverflow.com/q/47998634
has answer: http://stackoverflow.com/a/47998836
has title: Unicode issue trying to process JSON file
has comment: http://stackoverflow.com/comment/82968789
score: 0
answer count: 1
tagged with: unicode
linked to: http://stackoverflow.com/q/6048085
has body: I have a python script which writes JSON to a file with content that looks like this: { "album": "Night Hawk", "album_artist": "Coleman Hawkins with Eddie “Lockjaw” Davis", "artist": "Coleman Hawkins with Eddie “Lockjaw” Davis", "bitrate": 744, ... } The file is uploaded to the server and processed with this: with open(settings.JSON_UPLOAD_DIRECTORY + f.name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) This works without error on my MacOS development server. It has also worked for processing several thousands of files on my deployment server until now. Of a sudden I'm getting this error: 22. with open(settings.JSON_UPLOAD_DIRECTORY + f.name, 'wb+') as destination: Exception Value: 'ascii' codec can't encode character '“' in position 81: ordinal not in range(128) I've read other posts about this here without coming to an understanding of what I'm doing wrong. I'm running Python3.6. My question is, do I need to adjust the statement that opens the in memory file for writing, or is there a problem with the encoding of the JSON file itself.
tagged with: python
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/82966128
has comment: http://stackoverflow.com/comment/82966057
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/82863684
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47946672
has text: The `After5` class generates an instance only when you use it as a decorator. Each of your six calls of the decorated function go through the `__call__` method of the instance you created.

http://stackoverflow.com/q/47858588
upvote count: 1
has comment: http://stackoverflow.com/comment/82681951
accepted answer: http://stackoverflow.com/a/47860144
favorite count: 0
has comment: http://stackoverflow.com/comment/82682450
has title: Python Entries List
has comment: http://stackoverflow.com/comment/82681775
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82681838
has comment: http://stackoverflow.com/comment/82682500
possible better answer: http://stackoverflow.com/a/47858722
has answer: http://stackoverflow.com/a/47860144
tagged with: python
has answer: http://stackoverflow.com/a/47858722
has comment: http://stackoverflow.com/comment/82681676
has body: I am creating a log in page for a piece of software for University work and am struggling with Tkinter Entries. I want to create Entries in a neat, yet efficient manner so opted for using a function to do so, but this would remove the possibility of naming variables. How could I use the code I have to then return the values of the 'username' and 'password' entry fields once the login button is pressed? def create_widget(self, cont, args): if(args[0] == 'Button'): self.create_button(cont, args) elif(args[0] == 'Entry'): self.create_entry(args) elif(args[0] == 'CheckBox'): self.create_checkbox(args) elif(args[0] == 'Label'): self.create_label(args) else: print("Invalid Argument while creating Widget") def create_entry(self, args): if(args[4] == True): entry = tk.Entry(self, font=FONT, width=args[1]) entry.place(x=args[2],y=args[3]) else: entry = tk.Entry(self, font=FONT, width=args[1], show = '*') entry.place(x=args[2],y=args[3]) self.create_widget(controller, ["Entry", 21, 135, 30, True]) self.create_widget(controller, ["Entry", 21, 135, 60, False])
type: AnsweredQuestion
tagged with: tkinter
has comment: http://stackoverflow.com/comment/82682265
type: Question
has comment: http://stackoverflow.com/comment/82681869
score: -1
has comment: http://stackoverflow.com/comment/82682224
answer count: 2
downvote count: 2

http://stackoverflow.com/a/50212681
score: 0
type: Answer
has body: I'll break down the places which breaks the deploy into points- requirements.txt Your requirements file does not have the == required. Open CMD in the folder where your heroku python script is stored, and type pip freeze. Then copy/paste everything into your requirements.txt file. It should look like this in the end. BOT TOKEN It doesn't break the deploy, but is very dangerous. Anyone can view your bot token here, which means they have full control over your bot. I recommend making 2 seperate folder for your bot, one pushes to heroku with your token, the other pushes to github with a placeholder for the token If you build your deploys from github, then you have to pay to get a private repo. I recommend instead pushing from the CLI to heroku and github seperately, it's actually pretty easy. runtime.txt I'm not entirely sure about this, but it's not the latest version(3.6.4) supported. Leaving it be should be OK, so just ignore this This should fix your deploying issue, if you have a doubt then you can check my guide or just reply to this :)
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/47970982

http://stackoverflow.com/a/47954559
score: 0
has body: The pypi page for darketpy indicates that it requires a POSIX operating system. If you want to install it on Windows, you'll need something like cygwin.
type: Answer
answers question: http://stackoverflow.com/q/47954405

http://stackoverflow.com/comment/82978691
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48003979
has text: @furas: I've updated my question with the recent negative result.
type: QuestionComment

http://stackoverflow.com/q/47868631
has title: One table can not be foreign key to others except one table
has answer: http://stackoverflow.com/a/47868903
score: 0
answer count: 2
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47869336
type: Question
has body: For example class Room(models.Model): visitor = models.ForeignKey(Visitor) number = models.PositiveIntegerField() capacity = models.ForeignKey(Capacity, on_delete=models.PROTECT) floor = models.ForeignKey(Floor, on_delete=models.PROTECT) price = models.PositiveIntegerField() is_premium = models.BooleanField(default=False) is_vip = models.BooleanField(default=False) expiry_date = models.DateTimeField() class Meta: unique_together = ('') def __str__(self): return '№{0}'.format(self.number) class Reserved(models.Model): room = models.ForeignKey(Room) begin_date = models.DateTimeField() def __str__(self): return 'Reserved Room {0}'.format(self.room) class Busy(models.Model): room = models.ForeignKey(Room) Table Room can not be connected to Tables Reserved and Busy at the same time. Room should be reserved or busy. Is there way put validation for this? I tried to use unique_together but if for fields of table Thanks
tagged with: django-models

http://stackoverflow.com/a/47861978
accepted answer of: http://stackoverflow.com/q/47861912
upvote count: 7
answers question: http://stackoverflow.com/q/47861912
has comment: http://stackoverflow.com/comment/82707340
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82689808
type: Answer
has body: Another option using str.replace method with ^([A-Z]).*?([a-zA-Z]+)$; ^([A-Z]) captures the first letter at the beginning of the string; ([a-zA-Z]+)$ matches the last word, then reconstruct the name by adding . between the first captured group and second captured group: df['Name'].str.replace(r'^([A-Z]).*?([a-zA-Z]+)$', r'\1.\2') #0 A.Brown #1 L.McCoy #2 L.Bell #Name: Name, dtype: object
score: 7

http://stackoverflow.com/q/47893605
has answer: http://stackoverflow.com/a/47894539
answer count: 1
score: 0
has body: i want to read ngrams which are saved in a file. and then match each word of those ngrams with individual token in my corpus if it match with that then replace it with ngram.let say i have these bigrams: painful punishment worldly life straight path Last Day great reward severe punishment clear evidence what i want to do is to read first bigram and then split it and comapre its first word "painful" with my tokens in corpus where it match with the token move to the next token and match it with the next word of bigram if it is "punishment" then replace it with one token as "painful punsihment". i dont know how to do this. i want to convert this logic into code.if any one can help me i will be really very thankful.
has title: how to read ngrams from a file and then match them with tokens
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47894539
tagged with: n-gram
type: Question
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/comment/82924147
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47977552
has text: There are couple ways to do it. One easy way is through SSH (if running on Linux/Mac platform)
type: Comment

http://stackoverflow.com/q/47982604
possible better answer: http://stackoverflow.com/a/60005154
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/1132941
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/82933778
tagged with: python
tagged with: recursive-backtracking
has answer: http://stackoverflow.com/a/47985349
has comment: http://stackoverflow.com/comment/82934480
has comment: http://stackoverflow.com/comment/82933771
upvote count: 3
tagged with: backtracking
has title: "Hamiltonian" path using Python
tagged with: recursion
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/60005154
accepted answer: http://stackoverflow.com/a/47985349
has body: I am trying to implement a recursive search for an arbitrary path (not necessarily a cycle) traversing all graph vertices using Python. Here's my code: def hamilton(G, size, pt, path=[]): if pt not in set(path): path.append(pt) if len(path)==size: return path for pt_next in G[pt]: res_path = [i for i in path] hamilton (G, size, pt_next, res_path) Here, pt is the starting point and path is the list of all previously traversed vertices not including pt, empty by default. The problem is, whenever such a path is found, the return statement refers to some inner call of the procedure and therefore the program does not terminate or return the path. For example, take G = {1:[2,3,4], 2:[1,3,4], 3:[1,2,4], 4:[1,2,3]} (i.e. the complete 4-graph) and run hamilton(G,4,1,[]). It returns None, but if you print the path instead of returning it as a value, you'll see that it actually finds all six paths starting at 1. If I tell the program to print the path together with the return statement, it eventually prints all such paths and hence runs much longer than needed. How can I fix the code so that it would terminate the execution after the first suitable path is found?
has comment: http://stackoverflow.com/comment/82934543

http://stackoverflow.com/comment/82898233
type: Comment
comment on: http://stackoverflow.com/a/47963585
type: AnswerComment
has text: According to the code, I use the output['Sentiment'][i]['sentimentValue'] But if you are asking for individual iteration, then printing output for each iteration prints a dictionary of info for each sentence.
score: 0

http://stackoverflow.com/a/47912062
has comment: http://stackoverflow.com/comment/82808737
score: 25
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82851507
answers question: http://stackoverflow.com/q/47888855
type: Answer
has comment: http://stackoverflow.com/comment/84561454
accepted answer of: http://stackoverflow.com/q/47888855
upvote count: 25
has body: From Logging documentation (emphasis added): Defining your own levels is possible, but should not be necessary, as the existing levels have been chosen on the basis of practical experience. However, if you are convinced that you need custom levels, great care should be exercised when doing this, and it is possibly a very bad idea to define custom levels if you are developing a library. That’s because if multiple library authors all define their own custom levels, there is a chance that the logging output from such multiple libraries used together will be difficult for the using developer to control and/or interpret, because a given numeric value might mean different things for different libraries. An overview of default logging levels: But if you still want to, you can make your own log level: In the logging-module, _levelToName and _nameToLevel are mappings between logging names and levels. Instead of manually adding to them, the addLevelName() function does this for you. Here, a new logging level called MESSAGE is added with log level 25: import logging # Define MESSAGE log level MESSAGE = 25 # "Register" new loggin level logging.addLevelName(MESSAGE, 'MESSAGE') # addLevelName(25, 'MESSAGE') # Verify assert logging.getLevelName(MESSAGE) == 'MESSAGE' If you don't want to make your own logger class but still wants to log other log levels, then you can use the Logger.log(level, msg)-method on the traditional loggers: logging.log(MESSAGE, 'This is a message') EDIT: Add message directly def message(self, msg, *args, **kwargs): if self.isEnabledFor(MESSAGE): self._log(MESSAGE, msg, args, **kwargs) Make the message()-function available in logging: logging.message = message # or setattr(logging, 'message', message) Make the message()-function available in the logger: logging.Logger.message = message # or setattr(logging.Logger, 'message', message) Make custom Logger class You could make your own logger class to make a message(msg)-method, to be used similarily as the othe…

http://stackoverflow.com/comment/82913636
score: 0
has text: I'm sorry, I don't understand this
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47971619

http://stackoverflow.com/q/47913849
type: Question
upvote count: 4
downvote count: 0
linked to: http://stackoverflow.com/q/41356784
tagged with: abstract-class
linked to: http://stackoverflow.com/q/6025714
answer count: 1
tagged with: abc
has answer: http://stackoverflow.com/a/47930397
favorite count: 0
tagged with: interface
has title: Python Library for Function Interfaces?
tagged with: python
score: 4
type: AnsweredQuestion
has body: I'm wondering if there's an existing Python libary/technique for enforcing function interfaces/"contracts". Something like ABC but for functions. E.g. An example with made-up syntax: @implements(i_state_updater) def my_update(position, state, forces): ... return new_position, new_state Where @declare_interface def i_state_updater(position, state, forces): """ :param position: ... :returns: .... """ So that when I pass this function as an argument I can verify it, eg def compute_trajectory(update_func, n_steps, initial_state): """ :param update_func: An i_state_updater ... """ assert update_func.implements(i_state_updater) Python's existing abc module does something like this, but only for classes. Is there an equivalent out there for functions?
accepted answer: http://stackoverflow.com/a/47930397

http://stackoverflow.com/comment/82726026
has text: @SaranyaSridharan What you mean by how? I put this code in a .py file just run it
comment on: http://stackoverflow.com/q/47879994
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47937133
has comment: http://stackoverflow.com/comment/82844071
has comment: http://stackoverflow.com/comment/82864550
tagged with: installation
answer count: 0
has title: Unable to install setuptools on mac osx - bad install directory or PYTHONPATH
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82862810
has comment: http://stackoverflow.com/comment/82864258
has body: I have been trying to install setuptools to get easy_install. I'm doing the following to install: curl https://bootstrap.pypa.io/ez_setup.py -o - | python But I keep getting the following error: Installing Setuptools running install Checking .pth file support in /lib/python2.7/site-packages/ /Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python -E -c pass TEST FAILED: /lib/python2.7/site-packages/ does NOT support .pth files error: bad install directory or PYTHONPATH You are attempting to install a package to a directory that is not on PYTHONPATH and which Python does not read ".pth" files from. The installation directory you specified (via --install-dir, --prefix, or the distutils default setting) was: /lib/python2.7/site-packages/ and your PYTHONPATH environment variable currently contains: '/usr/local/lib/python2.7/site-packages/' Here are some of your options for correcting the problem: * You can choose a different installation directory, i.e., one that is on PYTHONPATH or supports .pth files * You can add the installation directory to the PYTHONPATH environment variable. (It must then also be on PYTHONPATH whenever you run Python and want to use the package(s) you are installing.) * You can set up the installation directory to support ".pth" files by using one of the approaches described here: https://setuptools.readthedocs.io/en/latest/easy_install.html#custom-installation-locations What can I do to fix this? Why is it checking in /lib/python2.7/site-packages/ when my PYTHONPATH is /usr/local/lib/python2.7/site-packages/?? which python output : /usr/local/bin/python echo $PYTHONPATH output : /usr/local/lib/python2.7/site-packages/ echo $PATH output : /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin Please help!! I've been searching the internet but haven't able to solve this. I'm using Mac osx Sierra by the way. UPDATE: I even downloaded the zip from: https://pypi.python.org/pypi/setuptools uzipped the folder and did cd into …
type: Question
tagged with: setuptools
has comment: http://stackoverflow.com/comment/82861464
has comment: http://stackoverflow.com/comment/82865227
has comment: http://stackoverflow.com/comment/82843666
tagged with: python
tagged with: macos
has comment: http://stackoverflow.com/comment/82860089
tagged with: easy-install

http://stackoverflow.com/comment/82977263
score: 1
has text: Please paste your data/code samples in the body of your question, and please take a look at [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48004577

http://stackoverflow.com/q/47873389
has title: Matplotlib move tick labels inside plot area
accepted answer: http://stackoverflow.com/a/47874059
score: 36
answer count: 2
has body: Is it possible to put tick labels inside the plotting area? I have already tried: ax.tick_params(axis="y",pad=-.5, left="off",labelleft="on") and ax.tick_params(axis="y",direction="in", left="off",labelleft="on") The former just moves the axis inward, and the latter only moves the ticks not the tick labels.
favorite count: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47874059
possible better answer: http://stackoverflow.com/a/47874089
downvote count: 1
has answer: http://stackoverflow.com/a/47874089
type: Question
upvote count: 37
tagged with: matplotlib

http://stackoverflow.com/comment/82776439
score: 1
comment on: http://stackoverflow.com/q/47904839
type: QuestionComment
type: Comment
has text: See: http://tuxette.nathalievilla.org/?p=1696, but `rpy2` is used by _scores_ of ppl who rely on it daily.

http://stackoverflow.com/comment/82712639
has text: This feels broad. It's unclear to me if you are talking about the *cold-start problem* or just about using APIs of used software. In the latter, we probably need to see code.
type: QuestionComment
comment on: http://stackoverflow.com/q/47873498
score: 0
type: Comment

http://stackoverflow.com/a/47995295
answers question: http://stackoverflow.com/q/47994996
type: Answer
has comment: http://stackoverflow.com/comment/133494419
has body: You'll need to use the paging method of the Query object.
has comment: http://stackoverflow.com/comment/136624777
upvote count: 5
has comment: http://stackoverflow.com/comment/136620511
score: 5
downvote count: 0

http://stackoverflow.com/a/47889858
has body: If want always same year then first join years with date without year: df = pd.DataFrame({'release_date':['2062-10-04','1980-12-10'],'release_year':[1962,1980]}) print (df) release_date release_year 0 2062-10-04 1962 1 1980-12-10 1980 df['release_date'] = pd.to_datetime(df['release_year'].astype(str) + df['release_date'].str[4:]) print (df) release_date release_year 0 1962-10-04 1962 1 1980-12-10 1980
has comment: http://stackoverflow.com/comment/82746023
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47889559
type: Answer
accepted answer of: http://stackoverflow.com/q/47889559
score: 1
has comment: http://stackoverflow.com/comment/82746151
upvote count: 1
has comment: http://stackoverflow.com/comment/82746049
has comment: http://stackoverflow.com/comment/82746192

http://stackoverflow.com/comment/82688419
type: QuestionComment
type: Comment
has text: I should have been more clear, I want the result to be a new df column called 'name'
comment on: http://stackoverflow.com/q/47861688
score: 0

http://stackoverflow.com/comment/82851512
comment on: http://stackoverflow.com/a/47930639
type: AnswerComment
has text: To clarify more my contour solution. Area with dense colours (points over a trashold or differing much from background) are most certainly images. Areas containing a lot of blank space is most probably text. It is easy to calculate using ratio of number of coloured points/number of blanks.
score: 0
type: Comment

http://stackoverflow.com/comment/82840428
type: QuestionComment
has text: if you know that there is `< tr` then you could simply replace `< tr` with `<tr` in `HTML` before you use `BeautifulSoup(HTML)` - `HTML` is only string.
comment on: http://stackoverflow.com/q/47935298
score: 1
type: Comment

http://stackoverflow.com/q/47957997
downvote count: 3
has answer: http://stackoverflow.com/a/47961604
has body: I have list: words = ["ALI", "SIN", "ASI", "LIR", "IRI", "INI", "KAR"] I want to check if they form matrix such as this: and return my solution as a list like: solution = ["ALI", "SIN", "IRI"] I have come up with this code: words=["ALI", "SIN", "ASI", "LIR", "IRI", "INI", "KAR"] solution =[] failedsolutions = [] def Get_next_word(): while True: for word in words: if (word in solution) == False: solution.append(word) if (solution in failedsolutions) == False: return False else: solution.pop(len(solution) - 1 ) return True def Check_word_order(): checker = True for i in range(len(solution)): for j in range(len(words[0])): for word in words: if solution[i][j] == word[j]: checker = False else: checker = True if checker == False: return checker def main(): while True: Get_next_word() check = Check_word_order() if check is False: #Backtrack failedsolutions.append(solution) solution.pop(len(solution) - 1 ) # else: # solution.append() print(solution) main() I am tired and no longer be able to debug my code. Help will be appreciated. Thank you ps: I advice not fixing my code if there is a better way to it all.
tagged with: algorithm
score: -1
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/82885543
has comment: http://stackoverflow.com/comment/82892337
favorite count: 0
has comment: http://stackoverflow.com/comment/82885358
tagged with: python
tagged with: backtracking
has title: Backtrack Algorithm To Check Strings form Matrix
has comment: http://stackoverflow.com/comment/82885559
tagged with: recursive-backtracking
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/q/47997346
upvote count: 1
downvote count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: In this piece of code: n = int(input()) for i in the range(0, n): x = input() for y in range(0, len(string)): if y % 2 == 0: print(string[y], end='') print("", end='') for y in range(0, len(string)): if y % 2 != 0: print(string[y], end='') print("") Don't know why it came so messed up. Error: File "solution.py", line 3 for i in the range(0, n): ^ SyntaxError: invalid syntax
has answer: http://stackoverflow.com/a/47997357
tagged with: syntax
type: Question
has answer: http://stackoverflow.com/a/47997453
has title: SyntaxError 255 On List
score: 0
answer count: 2

http://stackoverflow.com/comment/82754367
comment on: http://stackoverflow.com/q/47893594
score: 0
has text: @UmarAsghar I edited the question to contain the code to reproduce my problem, do not know how to share a directory of code in a more convenient way.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82999138
has text: @cmarios Yes, after you assign `my_dict` to a new (empty) dict, you don't affect the previously appended dict by changing `my_dict`. It refers to a different object now. When using `defaults`, you need to call `copy()` so that each time `my_dict` is a different object; otherwise they will all refer to `defaults` and again you'll see the same dict repeated.
type: Comment
comment on: http://stackoverflow.com/a/47997615
score: 0
type: AnswerComment

optimization
tags question: http://stackoverflow.com/q/47983289
tags question: http://stackoverflow.com/q/47998759
tags question: http://stackoverflow.com/q/47930428
tags question: http://stackoverflow.com/q/47928159
tags question: http://stackoverflow.com/q/47886509
tag name: optimization
tags question: http://stackoverflow.com/q/47916639
tags question: http://stackoverflow.com/q/47875544
tags question: http://stackoverflow.com/q/47860094
tags question: http://stackoverflow.com/q/47969149
type: Tag
tags question: http://stackoverflow.com/q/47941226

http://stackoverflow.com/a/47912816
answers question: http://stackoverflow.com/q/47910374
type: Answer
has body: Using Python Client for Google Maps Services and this code I got names and locations (and more) for query 'Rugby Club, London' You will have to create own project on developers.google.com/console, activate Places API for Web Service (there is no version for Desktop Application) and get credencial for PlacesAPI - it gives you own key= (API key). Current key= is active so you can test code, but I will deactivate it later. import googlemaps gmaps = googlemaps.Client(key='AIzaSyBiC8vKEEF-MLP9a2de0PLs-S_XrEL0kSQ') results = gmaps.places('Rugby Club, London') for key in item.keys(): print('key:', key) print('-----') for item in results['results']: print('name:', item['name']) print('lat:', item['geometry']['location']['lat']) print('lng:', item['geometry']['location']['lng']) print('location:', item['geometry']['location']) print('---') print('-----') #for item in results['results'][:1]: # for key, value in item.items(): # print(key, ':', value) Result: (available keys and some names and locations) key: formatted_address key: geometry key: icon key: id key: name key: opening_hours key: photos key: place_id key: rating key: reference key: types ----- name: East London Rugby Football Club lat: 51.5291765 lng: 0.0102242 location: {'lat': 51.5291765, 'lng': 0.0102242} --- name: Hampstead Rugby Football Club lat: 51.5571358 lng: -0.1555037 location: {'lat': 51.5571358, 'lng': -0.1555037} --- name: Chiswick Rugby Club lat: 51.47323 lng: -0.256633 location: {'lat': 51.47323, 'lng': -0.256633} --- name: Wimbledon Rugby Football Club lat: 51.41975009999999 lng: -0.2464434 location: {'lat': 51.41975009999999, 'lng': -0.2464434} --- name: Saracens Amateur RFC lat: 51.64230209999999 lng: -0.1429848 location: {'lat': 51.64230209999999, 'lng': -0.1429848} --- name: Kilburn Cosmos RFC lat: 51.55542000000001 lng: -0.2297043000000001 location: {'lat': 51.55542000000001, 'lng': -0.2297043000000001} --- name: Barnes Rugby Football Club lat: 51.47568860000001 lng: -0.2373847 location: {'lat'…
accepted answer of: http://stackoverflow.com/q/47910374
score: 2
downvote count: 0
type: AcceptedAnswer
upvote count: 2

http://stackoverflow.com/comment/82889632
has text: popuper = CustomPopup(txt_input). in CustomPopup: def __init__(self, txt_input): self.txt_input = txt_input... i guess you can use 'super()' to bind your input to popup if needed. usefull: https://kivy.org/docs/api-kivy.uix.popup.html , https://stackoverflow.com/questions/3694371/how-do-i-initialize-the-base-super-class
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47959120

http://stackoverflow.com/comment/82987873
type: QuestionComment
comment on: http://stackoverflow.com/q/48009064
has text: @PidePython is the length of the entire username (including `'`) 3-12 characters or is the just the part before the `'` that's 3-12 characters in length?
score: 0
type: Comment

http://stackoverflow.com/q/47957954
has title: Creating vaiables by looping though external text file line by line
has answer: http://stackoverflow.com/a/47958059
has comment: http://stackoverflow.com/comment/82885459
has comment: http://stackoverflow.com/comment/82885395
answer count: 2
downvote count: 4
upvote count: 0
has comment: http://stackoverflow.com/comment/82885348
has body: If i have a text file that contains an x number of lines like: hostINFO = ['hostTYPE', 'hostOS', 'hostENV', 'hostNAME', 'hostIP', 'dbUNAME', 'dbPWD', 'dbPORT', 'orgNAME', 'nrdsTOKEN'] How would I create a python script that would: import a line as a variable list so that i can refer to it as hostINFO[0] or hostINFO[1] etc.... execute the script against the variables when completed go back to the host.txt file and get the next line and continue till no more lined exist. update.... i changed my hosts.txt file format to be a comma delimited: hostTYPE,hostOS,hostENV,hostNAME,hostIP,dbUNAME,dbPWD,dbPORT,orgNAME,nrdsTOKEN` deploy.py with open("hosts.txt") as f: for line in f: hostINFO = line.strip().split(',')
tagged with: variables
favorite count: 0
has comment: http://stackoverflow.com/comment/82885416
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82885260
has comment: http://stackoverflow.com/comment/82885273
has answer: http://stackoverflow.com/a/47959793
tagged with: python
tagged with: list
linked to: http://stackoverflow.com/q/1933451
score: -4
has comment: http://stackoverflow.com/comment/82885435
linked to: http://stackoverflow.com/q/2220699
type: Question

http://stackoverflow.com/a/47878227
has comment: http://stackoverflow.com/comment/82732791
has body: Looks like all you need to define your time is: np.linspace(0,300,266336). This divides the [0, 300] interval into 266336 equal 'steps'. N = len(Bx) time = np.linspace(0, 300, N) plt.plot(time, Bx, ...) [mcve]: import numpy as np import matplotlib.pyplot as plt Bx = np.random.rand(266336) N = len(Bx) time = np.linspace(0, 300, N) # or 300000 plt.figure(1).clf() plt.plot(time, Bx) If this (alone) doesn't work, then I'm clueless why, because it works for me. If it does work but your script doesn't then find what else you are doing in your script that screws up your figure display...
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82722883
has comment: http://stackoverflow.com/comment/82740243
has comment: http://stackoverflow.com/comment/82722653
type: Answer
answers question: http://stackoverflow.com/q/47878173
score: 2
has comment: http://stackoverflow.com/comment/82722555
has comment: http://stackoverflow.com/comment/82722799
accepted answer of: http://stackoverflow.com/q/47878173
has comment: http://stackoverflow.com/comment/82740466
has comment: http://stackoverflow.com/comment/82722437

http://stackoverflow.com/comment/82873146
type: Comment
type: QuestionComment
score: 0
has text: @StefanPochmann Well in reality I'm graphing it, but there's a `print` with some initial conditions so that the code actually does something!
comment on: http://stackoverflow.com/q/47951758

http://stackoverflow.com/comment/82757346
type: Comment
type: QuestionComment
has text: that helped it got rid of my syntax error but it still doesnt seem to work, I just completely ignores the tax rate and does not print income
comment on: http://stackoverflow.com/q/47895255
score: 0

http://stackoverflow.com/a/47884126
answers question: http://stackoverflow.com/q/47881468
has body: In the way you are asking - no. When you disconnect, oracle kills your session (or at least tries to kill). But you can create a job. Job is an object managed by oracle instance. It has a schedule, which is used to run. Simplest example to create a job, which will run a stored procedure once: begin dbms_scheduler.create_job( job_name =&gt; 'My job', job_type =&gt; 'STORED_PROCEDURE', job_action =&gt; 'YOUR_SCHEMA.YOUR_PACKAGE.YOUR_PROCEDURE', start_date =&gt; 'desired date to start', repeat_interval =&gt; 'FREQ=DAILY;INTERVAL=1', /* every day */ end_date =&gt; 'desired date to stop', comments =&gt; 'I will run it from python'); end; To run your procedure only once leave start_date, repeat_interval and end_date null: begin dbms_scheduler.create_job( job_name =&gt; 'My job', job_type =&gt; 'STORED_PROCEDURE', job_action =&gt; 'YOUR_SCHEMA.YOUR_PACKAGE.YOUR_PROCEDURE', comments =&gt; 'I will run it from python'); end; Oracle Scheduler is a very complex and powerful tool. Your can run procedure with parameters, anonymous blocks, create complex schedules, etc. To learn more, see the documentation: Scheduler, DBMS_SCHEDULER.
has comment: http://stackoverflow.com/comment/83104141
score: 3
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/83089167
downvote count: 0

http://stackoverflow.com/comment/82706553
comment on: http://stackoverflow.com/a/47859567
has text: Thanks for the really in-depth solution. Still working through it, but even the indexing solution works great so far as I can see for a couple examples I've tried
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/82869386
score: 0
type: AnswerComment
type: Comment
has text: The sum are accurate and it loops through each dictionary.
comment on: http://stackoverflow.com/a/47949868

http://stackoverflow.com/comment/82979390
has text: I get this error: `pyspark.sql.utils.AnalysisException: u"Field name should be String Literal, but it's 1;"`.
comment on: http://stackoverflow.com/a/48005429
type: AnswerComment
score: 0
type: Comment

web-scraping
tags question: http://stackoverflow.com/q/47858650
tags question: http://stackoverflow.com/q/47895888
tags question: http://stackoverflow.com/q/47873388
tags question: http://stackoverflow.com/q/47968143
tags question: http://stackoverflow.com/q/47879642
tags question: http://stackoverflow.com/q/48004453
tags question: http://stackoverflow.com/q/47945029
tags question: http://stackoverflow.com/q/47872862
tags question: http://stackoverflow.com/q/47962911
tags question: http://stackoverflow.com/q/47929181
tags question: http://stackoverflow.com/q/47908372
tags question: http://stackoverflow.com/q/47977846
tags question: http://stackoverflow.com/q/47925924
tags question: http://stackoverflow.com/q/47956527
tags question: http://stackoverflow.com/q/47862662
tags question: http://stackoverflow.com/q/47966982
tags question: http://stackoverflow.com/q/47993061
tags question: http://stackoverflow.com/q/47856783
tags question: http://stackoverflow.com/q/47951987
tags question: http://stackoverflow.com/q/47973341
tags question: http://stackoverflow.com/q/47968568
tags question: http://stackoverflow.com/q/47935982
tags question: http://stackoverflow.com/q/47857042
tags question: http://stackoverflow.com/q/47875565
tags question: http://stackoverflow.com/q/48006078
tags question: http://stackoverflow.com/q/47977346
tags question: http://stackoverflow.com/q/47916901
tags question: http://stackoverflow.com/q/47966494
tags question: http://stackoverflow.com/q/47914127
tags question: http://stackoverflow.com/q/47994603
tags question: http://stackoverflow.com/q/47964015
tags question: http://stackoverflow.com/q/47956242
tags question: http://stackoverflow.com/q/47961468
tags question: http://stackoverflow.com/q/47945268
tags question: http://stackoverflow.com/q/48003815
tags question: http://stackoverflow.com/q/47922167
tags question: http://stackoverflow.com/q/47959327
tags question: http://stackoverflow.com/q/47972289
tags question: http://stackoverflow.com/q/47961214
tags question: http://stackoverflow.com/q/47983921
tags question: http://stackoverflow.com/q/47912149
tags question: http://stackoverflow.com/q/47968108
tags question: http://stackoverflow.com/q/47999832
tags question: http://stackoverflow.com/q/47971406
tags question: http://stackoverflow.com/q/47996863
tags question: http://stackoverflow.com/q/47978702
tags question: http://stackoverflow.com/q/47966110
tags question: http://stackoverflow.com/q/47938867
tags question: http://stackoverflow.com/q/47988412
tags question: http://stackoverflow.com/q/47967639
tags question: http://stackoverflow.com/q/47935006
tags question: http://stackoverflow.com/q/48004462
tag name: web-scraping
tags question: http://stackoverflow.com/q/47858886
tags question: http://stackoverflow.com/q/47862023
tags question: http://stackoverflow.com/q/47927096
tags question: http://stackoverflow.com/q/47895141
tags question: http://stackoverflow.com/q/47946640
tags question: http://stackoverflow.com/q/47872975
tags question: http://stackoverflow.com/q/47978623
tags question: http://stackoverflow.com/q/47898368
tags question: http://stackoverflow.com/q/47872366
tags question: http://stackoverflow.com/q/47993380
tags question: http://stackoverflow.com/q/47913709
tags question: http://stackoverflow.com/q/47955660
tags question: http://stackoverflow.com/q/47879574
tags question: http://stackoverflow.com/q/47928768
tags question: http://stackoverflow.com/q/47947475
tags question: http://stackoverflow.com/q/47891264
type: Tag
tags question: http://stackoverflow.com/q/47874307
tags question: http://stackoverflow.com/q/47870791
tags question: http://stackoverflow.com/q/47886090
tags question: http://stackoverflow.com/q/47916802
tags question: http://stackoverflow.com/q/47898022
tags question: http://stackoverflow.com/q/47916315
tags question: http://stackoverflow.com/q/47965265
tags question: http://stackoverflow.com/q/47956702
tags question: http://stackoverflow.com/q/47925511
tags question: http://stackoverflow.com/q/47914696

http://stackoverflow.com/comment/103808453
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47878515
has text: Well, if there are 50 categories present in a categorical variable, it wouldn't be wise to one-hot-encode them, isn't it? How do you handle this case then?

http://stackoverflow.com/a/47926241
has comment: http://stackoverflow.com/comment/82831281
type: Answer
has body: I'm not sure what exactly you plan to do with your matrix, but here's how you can generate Bernoulli distribution in tensorflow: &gt;&gt;&gt; distrib = tf.contrib.distributions.Bernoulli(probs=[0.3]) &gt;&gt;&gt; sample = distrib.sample([10]) &gt;&gt;&gt; sample &lt;tf.Tensor 'Bernoulli/sample/Reshape:0' shape=(10, 1) dtype=int32&gt; &gt;&gt;&gt; sample.eval() array([[0], [0], [1], [1], [0], [0], [0], [1], [0], [0]], dtype=int32)
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/47919309
downvote count: 0

http://stackoverflow.com/q/47899596
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/47900521
accepted answer: http://stackoverflow.com/a/47900521
tagged with: python
has title: Not scraping correct css despite correct css element in chrome inspect
tagged with: selenium-webdriver
type: AnsweredQuestion
has body: My css element giving the exact same css element in Python selenium when it appears differently as seen in image. How can I get a the css selectors in the images? I have tried different css but so far it keeps getting first element and not second. Css one: match-pop-market > #options_table > tbody > tr#mtb_row > td:nth-child(1) Css two: match-pop-market > #options_table > tbody > tr#mta_row > td:nth-child(1) Note a and b change. driver = webdriver.Chrome() driver.set_window_size(1024, 600) driver.maximize_window() driver.get('https://www.palmerbet.com/sports/soccer') time.sleep(4) langs = driver.find_elements_by_css_selector("match-pop-market &gt; #options_table &gt; tbody &gt; tr#mta_row &gt; td:nth-child(1)") langs_text = [] for lang in langs: print(lang.text) langs_text.append(lang.text) print('second css') langs2 = driver.find_elements_by_css_selector("match-pop-market &gt; #options_table &gt; tbody &gt; tr#mtb_row &gt; td:nth-child(1)") langs_text2 = [] for lang in langs: print(lang.text) langs_text2.append(lang.text) driver.close() Exact output: Arsenal Everton Brighton &amp; Hove Albion Manchester City Southampton Stoke City Swansea City West Ham Burnley Leicester City Tottenham Hotspur AFC Bournemouth Chelsea Huddersfield Town Manchester United Watford West Bromwich Albion Liverpool Newcastle United Crystal Palace AFC Bournemouth Chelsea Huddersfield Town Liverpool Newcastle United Watford Manchester United Crystal Palace West Bromwich Albion second css Arsenal Everton Brighton &amp; Hove Albion Manchester City Southampton Stoke City Swansea City West Ham Burnley Leicester City Tottenham Hotspur AFC Bournemouth Chelsea Huddersfield Town Manchester United Watford West Bromwich Albion Liverpool Newcastle United Crystal Palace AFC Bournemouth Chelsea Huddersfield Town Liverpool Newcastle United Watford Manchester United Crystal Palace West Bromwich Albion
score: 1
tagged with: selenium
type: Question
tagged with: css-selectors
upvote count: 1

http://stackoverflow.com/comment/82862651
type: Comment
has text: While yes "Jewels[]" never defined as list because my understanding was like any other variable types in python, list variables don't need to explicitly defined.Its resolved now.Thanks
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47946266

http://stackoverflow.com/comment/82823594
type: AnswerComment
type: Comment
has text: Aha, :-) got it
score: 0
comment on: http://stackoverflow.com/a/47927502

http://stackoverflow.com/comment/82815359
type: Comment
comment on: http://stackoverflow.com/q/47921638
type: QuestionComment
has text: I did not understand?
score: 0

http://stackoverflow.com/a/47987861
answers question: http://stackoverflow.com/q/47987622
upvote count: 3
has body: ''.join(str(x) for x in div.p.contents) gives me inner HTML as string on bs4 I get parent = div.parent to use it later Using div.extract() I remove div with all subtags. Using parent.append() I put inner HTML back . from bs4 import BeautifulSoup data = '''&lt;strong&gt; &lt;div&gt; &lt;p&gt; &lt;a href="" id="tnt1"&gt;[1]&lt;/a&gt;"RFC 4456 - BGP Route Reflection: An Alternative to Full ... - IETF Tools."&gt;ref="https://example.com"&gt;https://https://example.com"&lt;/a&gt;&lt;/span&gt;&lt;span&gt;. Accessed 15 Nov. 2017. &lt;/p&gt; &lt;/div&gt; &lt;/strong&gt;''' soup = BeautifulSoup(data, 'html.parser') for div in soup.find_all('div'): parent = div.parent inner = ''.join(str(x) for x in div.p.contents) + "&lt;br/&gt;" print('--- inner ---') print(inner) # remove div with all subtags div.extract() parent.append(BeautifulSoup(inner, 'html.parser')) print('--- after ---') print(parent) Result: --- inner --- &lt;a href="" id="tnt1"&gt;[1]&lt;/a&gt;"RFC 4456 - BGP Route Reflection: An Alternative to Full ... - IETF Tools."&gt;ref="https://example.com"&gt;https://https://example.com"&lt;br/&gt; --- after --- &lt;strong&gt; &lt;a href="" id="tnt1"&gt;[1]&lt;/a&gt;"RFC 4456 - BGP Route Reflection: An Alternative to Full ... - IETF Tools."&amp;gt;ref="https://example.com"&amp;gt;https://https://example.com"&lt;br/&gt;&lt;/strong&gt;
score: 3
has comment: http://stackoverflow.com/comment/82944591
has comment: http://stackoverflow.com/comment/82944412
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47987622

http://stackoverflow.com/comment/82936680
has text: https://eval.in/925686 ?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47983699

http://stackoverflow.com/comment/82977563
type: QuestionComment
comment on: http://stackoverflow.com/q/47991528
has text: I was able to form the required text by using: {% set link_type = 'xyz_Links.abc_' + i|string + '.abc_link_type' %}. However when I pass link_type to "dummy" (i.e. "dummy":"{{ link_type }}") it prints the same as text and does not fetch the value. Any leads would be highly appreciated.
type: Comment
score: 0

http://stackoverflow.com/comment/82797015
type: Comment
has text: 1. No, it is not cleaner. Importing just the function you need is much better than launching a totally separate Python interpreter. Check the comment in my code example. 2. `subprocess.Popen` already runs the logic in a new process. If you wrap it within a process you end up with two processes of which one is waiting for the other. There is no benefit whatsoever :)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47907809

http://stackoverflow.com/q/47972726
type: AnsweredQuestion
tagged with: neural-network
has title: Convolution2D vs Conv2D in Keras library, in Python
downvote count: 0
tagged with: keras
favorite count: 0
type: Question
score: 3
tagged with: python
has answer: http://stackoverflow.com/a/47972817
tagged with: conv-neural-network
upvote count: 3
answer count: 1
tagged with: tensorflow
accepted answer: http://stackoverflow.com/a/47972817
has body: Is there any documentation on whether these are the same or different modules and the differences between these? keras.layers.Conv2D keras.layers.Convolution2D keras.layers.convolutional.Conv2D keras.layers.convolutional.Convolution2D

http://stackoverflow.com/q/47926434
type: AnsweredQuestion
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/82820788
has comment: http://stackoverflow.com/comment/82820655
has comment: http://stackoverflow.com/comment/82820699
has answer: http://stackoverflow.com/a/47926490
upvote count: 0
tagged with: dataframe
score: -1
has title: Loosing the column name with getting a subset of a dataframe
has comment: http://stackoverflow.com/comment/82821272
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/82820815
has comment: http://stackoverflow.com/comment/82821310
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47926490
linked to: http://stackoverflow.com/q/16782323
has comment: http://stackoverflow.com/comment/82820717
tagged with: python
has body: I'm going to get a subset of my dataframe, but it's column name disappears. This is the code I use: my_dataframe = df["column1"] How can have the subset of df in my_dataframe without loosing the column name?
duplicate of: http://stackoverflow.com/q/16782323

http://stackoverflow.com/a/47872910
has comment: http://stackoverflow.com/comment/88538528
score: 0
has comment: http://stackoverflow.com/comment/82750934
type: Answer
has body: dev_appserver.py --help mentions: --watcher_ignore_re WATCHER_IGNORE_RE Regex string to specify files to be ignored by the filewatcher. (default: None) In this case this is related to dev_appserver.py, which will detect changes in local app.yaml and reload local server, while app.yaml running in GAE is not supposed to do because reloading is done by gcloud app deploy.
answers question: http://stackoverflow.com/q/47865500
has comment: http://stackoverflow.com/comment/82731330
has comment: http://stackoverflow.com/comment/82768571
has comment: http://stackoverflow.com/comment/82787738

http://stackoverflow.com/comment/82745745
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47889011
has text: global fileListA global fileListB fileListA = "" fileListB = "" at the start of the code after importing packages, but I'm still getting error "FileListA is not defined"

http://stackoverflow.com/q/47901771
has comment: http://stackoverflow.com/comment/82770593
accepted answer: http://stackoverflow.com/a/47959146
tagged with: logarithm
type: Question
has comment: http://stackoverflow.com/comment/82770318
upvote count: 0
score: -2
tagged with: string
has title: Python: string comparison with double conditions
has comment: http://stackoverflow.com/comment/82770507
has comment: http://stackoverflow.com/comment/82770640
favorite count: 0
has body: Trying to search 2 lists for common strings. 1-st list being a file with text, while the 2-nd is a list of words with logarithmic probability before the actual word – to match, a word not only needs to be in both lists, but also have a certain minimal log probability (for instance, between -2,123456 and 0,000000; that is negative 2 increasing up to 0). The tab separated list can look like: -0.962890 dog -1.152454 lol -2.050454 cat I got stuck doing something like this: common = [] for i in list1: if i in list2 and re.search("\-[0-1]\.[\d]+", list2): common.append(i) The idea to simply preprocess the list to remove lines under a certain threshold is valid of course, but since both the word and its probability are on the same line, isn’t a condition also possible? (Regexps aren’t necessary, but for comparison solutions both with and without them would be interesting.) EDIT: own answer to this question below.
has comment: http://stackoverflow.com/comment/82770473
answer count: 3
has answer: http://stackoverflow.com/a/47959146
possible better answer: http://stackoverflow.com/a/47902269
has answer: http://stackoverflow.com/a/47902269
downvote count: 2
has answer: http://stackoverflow.com/a/47902783
tagged with: python
has comment: http://stackoverflow.com/comment/82770596
type: AnsweredQuestion
tagged with: conditional-statements
has comment: http://stackoverflow.com/comment/82770235

http://stackoverflow.com/comment/82898116
has text: Note that the behavior you display is Python 2 only, you need to wrap it in `list`.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47964272
type: AnswerComment

http://stackoverflow.com/a/48020259
has comment: http://stackoverflow.com/comment/83018401
has body: If the state and action spaces are finite, as in your problem, Q-learning algorithm should converge asymptotically to the optimal utility (aka, Q-function), when the number of transitions approaches to infinity and under the following conditions: , where n is the number of transitions and a is the learning rate. This conditions requires updating your learning rate as learning progresses. A typical choice could be use a_n = 1/n. However, in practice, the learning rate schedule may require some tuning depending on the problem. On the other hand, another convergence condition consists in update all state-action pairs infinitely (in a asymtotical sense). This could be achieved simply by maintaining an exploration rate bigger than zero. So, in your case, you need to decrease the learning rate.
has comment: http://stackoverflow.com/comment/83048732
has comment: http://stackoverflow.com/comment/83047472
answers question: http://stackoverflow.com/q/48011874
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48011874
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83018005
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83027883
has comment: http://stackoverflow.com/comment/83047441

http://stackoverflow.com/comment/82690990
comment on: http://stackoverflow.com/a/47861190
has text: @user3666197, don't scare them needlessly ;-) The OP's description is of a vanilla load-balancing problem, involving network communication that takes thousands of times longer than anything on the local machine requires. There aren't significant subtleties in that - they're just trying to get multiple (& potentially long-running) cross-network requests running simultaneously. Any sane approach should work fine for that.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82875944
type: AnswerComment
comment on: http://stackoverflow.com/a/47953281
type: Comment
score: 2
has text: I would hope PyCharm suggest such option more clearly.

http://stackoverflow.com/comment/82842375
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47936531
type: Comment
has text: `int(float(a))`

http://stackoverflow.com/comment/82722421
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47863274
has text: thanks for recommending this library. I was looking for something that resembles FactoryGirl in RoR.
type: AnswerComment

http://stackoverflow.com/a/47862826
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47858096
has body: To the other answer I would add that this has nothing to do with SymPy. This is just how Python works. If a function references a variable that isn't defined in that function, it gets it from the outer namespace where the function is defined (you can search this site or the web for "Python scoping" for more information about this). This "worked" because you also used the variable name arg for symbols('t'). In general, I would recommend naming SymPy variables the same as their symbol name, so instead of arg, use t = symbols('t') You will avoid a lot of headache if you always do this.
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47858096

http://stackoverflow.com/a/56172736
upvote count: 3
answers question: http://stackoverflow.com/q/47859052
type: Answer
has comment: http://stackoverflow.com/comment/112241074
score: 3
has comment: http://stackoverflow.com/comment/117908476
downvote count: 0
has body: From the docs: Put item Creates a new item, or replaces an old item with a new item. If an item that has the same primary key as the new item already exists in the specified table, the new item completely replaces the existing item. To prevent an overwrite, you need to add a conditional expression specifying that the partition key does not yet exist. Something like the following should work (sorry, I didn't quite get your key scheme, so you'll have to modify this). table.put_item( Item={'userId': 1, 'productId': 2}, ConditionExpression='userId &lt;&gt; :uid AND productId &lt;&gt; :pid', ExpressionAttributeValues={':uid': 1, ':pid': 3} )

http://stackoverflow.com/a/50417079
type: Answer
answers question: http://stackoverflow.com/q/47885357
has body: The following was suggested on the Keras issue tracker. I'm not sure about the relative merits of the approach compared to using multiprocessing. in_1 = Input() lstm_1 = LSTM(...)(in_1) out_1 = Dense(...)(lstm_1) in_2 = Input() lstm_2 = LSTM(...)(in_2) out_2 = Dense(...)(lstm_2) model_1 = Model(input=in_1, output=out_1) model_2 = Model(input=in_2, output=out_2) model = Model(input = [in_1, in_2], output = [out_1, out_2]) model.compile(...) model.fit(...) model_1.predict(...) model_2.predict(...)
score: 0

http://stackoverflow.com/comment/82782189
has text: Thanks to your link, I've read the information on modifying how packages are found by pip in various repos.
comment on: http://stackoverflow.com/a/47901789
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/48010184
downvote count: 0
has body: You have inherited AbstractUser for your custom user model and you are inheriting BaseUserManager for UserManager modify your manager like below by inheriting UserManager: class MyUserManager(UserManager): def create_user(self, email, password=None, **kwargs): # override this method def create_superuser(self, email, password, **kwargs): # override this method clean up migrations and database first and then apply migration with this changes.
score: 1
answers question: http://stackoverflow.com/q/48009764
has comment: http://stackoverflow.com/comment/82988808
accepted answer of: http://stackoverflow.com/q/48009764
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82989413
type: Answer

http://stackoverflow.com/q/47873836
has title: IndexError: single positional indexer is out-of-bounds using pandas Series.from_csv
tagged with: pandas
accepted answer: http://stackoverflow.com/a/47874216
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/47874216
upvote count: 1
type: Question
tagged with: time-series
has body: I am getting error as File "C:/Users/Toshiba/PycharmProjects/untitled1/stationarity.py", line 7, in &lt;module&gt; series = Series.from_csv('flowcaida.csv') File "C:\ProgramData\Anaconda2\lib\site-packages\pandas\core\series.py", line 2640, in from_csv result = df.iloc[:, 0] File "C:\ProgramData\Anaconda2\lib\site-packages\pandas\core\indexing.py", line 1325, in __getitem__ return self._getitem_tuple(key) File "C:\ProgramData\Anaconda2\lib\site-packages\pandas\core\indexing.py", line 1662, in _getitem_tuple self._has_valid_tuple(tup) File "C:\ProgramData\Anaconda2\lib\site-packages\pandas\core\indexing.py", line 189, in _has_valid_tuple if not self._has_valid_type(k, i): File "C:\ProgramData\Anaconda2\lib\site-packages\pandas\core\indexing.py", line 1597, in _has_valid_type return self._is_valid_integer(key, axis) File "C:\ProgramData\Anaconda2\lib\site-packages\pandas\core\indexing.py", line 1638, in _is_valid_integer raise IndexError("single positional indexer is out-of-bounds") IndexError: single positional indexer is out-of-bounds using this: series = Series.from_csv('flowcaida.csv') This is my data: 651680 459151 596299 474950 631421 465275 629861 455582 650192 Thank you for your help.

http://stackoverflow.com/q/47931534
has comment: http://stackoverflow.com/comment/82833375
has comment: http://stackoverflow.com/comment/82832685
tagged with: python
has body: Is it possible to call xpath normalize-space() on html with displaying , as new line? XPath version is 1.0 We parse articles from websites. Example of real HTML code: Организовать удаленный доступ для сотрудников — задача прикладная. Решений на рынке немало, при этом, и подводных камней достаточно. Под катом рассказ о нашем «чемодане», который раскладывается быстро и удобно за 30 минут. Просьба не воспринимать это как рекламный BS, поскольку внутри реальная инструкция по применению. Parallels Remote Application Server (RAS) — это комплексное средство для доставки виртуальных приложений и рабочих столов, позволяющее работать с приложениями и данными с любого устройства, в том числе мобильного. Мы понимаем, что такие решения хочется сначала протестировать в конкретных условиях, прежде чем принимать решение о покупке. Problem not in extracting text from site. Problem is that normalize-space is remove all tags include . As a result we have one long text line. I need text line with breaks. Expected result: Организовать удаленный доступ для сотрудников — задача прикладная. Решений на рынке немало, при этом, и подводных камней достаточно. Под катом рассказ о нашем «чемодане», который раскладывается быстро и удобно за 30 минут. Просьба не воспринимать это как рекламный BS, поскольку внутри реальная инструкция по применению. Parallels Remote Application Server(RAS) — это комплексное средство для доставки виртуальных приложений и рабочих столов, позволяющее работать с приложениями и данными с любого устройства, в том числе мобильного. Мы понимаем, что такие решения хочется сначала протестировать в конкретных условиях, прежде чем принимать решение о покупке.
type: AnsweredQuestion
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/82833207
possible better answer: http://stackoverflow.com/a/47935352
has answer: http://stackoverflow.com/a/47935352
tagged with: scrapy
type: Question
has comment: http://stackoverflow.com/comment/82833703
has answer: http://stackoverflow.com/a/47941479
has comment: http://stackoverflow.com/comment/82832258
has comment: http://stackoverflow.com/comment/82832497
has comment: http://stackoverflow.com/comment/82832333
has comment: http://stackoverflow.com/comment/82833599
accepted answer: http://stackoverflow.com/a/47941479
has comment: http://stackoverflow.com/comment/82832133
answer count: 2
downvote count: 0
favorite count: 0
tagged with: xpath-1.0
tagged with: xpath
has title: XPath to select string value of element but with replaced with newline?
has comment: http://stackoverflow.com/comment/82833282

http://stackoverflow.com/a/47866463
score: 1
answers question: http://stackoverflow.com/q/47864667
accepted answer of: http://stackoverflow.com/q/47864667
has body: Visit every edge and (using the topological information that you have) find the edges that share an endpoint with it. Keep the ones that form the best alignment. If the alignment is within some tolerance, consider that these edges are linked. After processing the whole triangulation, you will have as set of linked lists containing the alignments.
has comment: http://stackoverflow.com/comment/82702241
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82699742
type: Answer
downvote count: 0

http://stackoverflow.com/comment/82921224
comment on: http://stackoverflow.com/q/47975983
score: 1
has text: Your code seems to have indentation errors
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47956975
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/47956902
has comment: http://stackoverflow.com/comment/82883442
has body: I had a similar problem and i solve it like this: Settings File STATIC_URL = '/static/' STATIC_FOLDER = 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR,STATIC_FOLDER), ] STATIC_ROOT = os.path.join(BASE_DIR, "static/") and also when i run the manage.py commands to initialize i added this python manage.py collectstatic -link --noinput
upvote count: 1
has comment: http://stackoverflow.com/comment/82883470

http://stackoverflow.com/comment/82711438
score: 0
has text: There was no copy by value. Assignment in Python *never copies*
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47871834

covariance
tags question: http://stackoverflow.com/q/47907537
tag name: covariance
type: Tag

http://stackoverflow.com/a/47962209
type: Answer
answers question: http://stackoverflow.com/q/47962148
accepted answer of: http://stackoverflow.com/q/47962148
has comment: http://stackoverflow.com/comment/82893632
has body: This is not Python: python import binance Here, you are trying to invoke the Python interpreter with the python command. But this command does not take Python code as argument, it takes an executable! So you are actually trying to run the import script, which of course, doesn't exist. If you want to access the Python interpreter without feeding him a script, just run the python command without arguments: python It will open the Python interpreter (you can recognise it by its prompt: &gt;&gt;&gt;). Now you can type Python code: &gt;&gt;&gt; import binance
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82893653
has comment: http://stackoverflow.com/comment/82893700

http://stackoverflow.com/q/47948437
favorite count: 0
tagged with: shapefile
upvote count: 2
has answer: http://stackoverflow.com/a/58398718
type: UnansweredQuestion
tagged with: python
tagged with: gis
has title: Editing shapefiles in Python via new Writer object isn't working
has comment: http://stackoverflow.com/comment/106256399
type: Question
has answer: http://stackoverflow.com/a/47949400
answer count: 2
has body: I'm currently following a Python geospatial analysis tutorial book by Joel Lawhead, and I'm running into an error when trying to edit shapefiles. The shapefile I'm using is available a http://git.io/vLd8Y. I'm running my code in a Jupyter Notebook on python3. This is my code. I'm simply reading in a shapefile as a Reader object r, and creating a new Writer object w with the same shapetype as r. Then, I'm attempting to attach the records from r to w. import shapefile r = shapefile.Reader("NYC_MUSEUMS_GEO") w = shapefile.Writer(r.shapeType) w.fields = list(r.fields) w.records.extend(r.records()) However, I'm running into this error: AttributeError Traceback (most recent call last) &lt;ipython-input-151-ceee096fbafa&gt; in &lt;module&gt;() 6 w = shapefile.Writer(r.shapeType) 7 w.fields = list(r.fields) ----&gt; 8 w.records.extend(r.records()) AttributeError: 'Writer' object has no attribute 'records' Any ideas why?
downvote count: 0
score: 2

http://stackoverflow.com/q/47960938
answer count: 2
downvote count: 0
favorite count: 0
tagged with: python
has body: I want to replicate the last row of an array in python and found the following lines of code in the numpy documentation &gt;&gt;&gt; x = np.array([[1,2],[3,4]]) &gt;&gt;&gt; np.repeat(x, [1, 2], axis=0) in the above code what does the second parameter "[1,2]" in np.repeat do? if i want to replicate a row in a 3*3 array how will this second parameter change.
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82891289
upvote count: 2
has title: How to replicate a row of an array with numpy?
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47961042
has comment: http://stackoverflow.com/comment/82891109
possible better answer: http://stackoverflow.com/a/47961054
accepted answer: http://stackoverflow.com/a/47961042
has answer: http://stackoverflow.com/a/47961054

http://stackoverflow.com/comment/82879158
comment on: http://stackoverflow.com/q/47954398
score: 0
type: Comment
type: QuestionComment
has text: If the records indexing is basic (with slices), selecting the records will work. But indexing first on the field is generally a good idea.

http://stackoverflow.com/a/61009389
upvote count: 3
has body: Although completely answered, I just wanted to add an example with a nested enumerate to cover the original question. One important thing to have in mind is that the start parameter on the enumerate signature enumerate(iterable, start=0) won't skip the actual iterable. If you want to nest loops with enumerate in a scenario in which you do not want to re-use previous loops indexes, e.g., consider the array=[1, 2, 3, 4] for the original question, you can't just make: for first_idx, first in enumerate(array): for second_idx, second in enumerate(array, first_idx + 1): for third_idx, third in enumerate(array, second_idx + 1): print(first, second, third) As you will have the first iterations: 1 1 1 1 1 2 1 1 3 1 1 4 ... Instead, you have to: for first_idx, first in enumerate(array): for second_idx, second in enumerate(array[first_idx + 1:], first_idx + 1): for third_idx, third in enumerate(array[second_idx + 1:], second_idx + 1): print(first, second, third) It will correctly print: 1 2 3 1 2 4 1 3 4 2 3 4
answers question: http://stackoverflow.com/q/47989926
downvote count: 0
score: 3
type: Answer

http://stackoverflow.com/comment/82815909
score: 2
comment on: http://stackoverflow.com/q/47923884
type: Comment
type: QuestionComment
has text: Change your `cv2.imwrite("tmp_image.jpg", img)` to write to `fred.jpg` then when it is complete and fully written, rename `fred.jpg` to `tmp_image.jpg`. That way the web server cannot read the file while OpenCV is writing it.

http://stackoverflow.com/q/47970313
type: UnansweredQuestion
tagged with: python
answer count: 0
tagged with: multithreading
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/82932437
has title: How can I identify threads that are running the same method in python
has comment: http://stackoverflow.com/comment/82910938
score: 0
has body: I am making a python program that should load a webpage and search for a cookie. I have a method called startsearch and I want it to run at the same time in 3 different threads as below. if __name__ == '__main__': Thread(target = startsearch, args=(x, )).start() Thread(target = startsearch, args=(x, )).start() Thread(target = startsearch, args=(x, )).start() How would I kill a specific thread then? I basically want to kill the thread once the cookie has been found but since each thread is the same, how to identify them?
has comment: http://stackoverflow.com/comment/82910142
favorite count: 0

http://stackoverflow.com/comment/82819644
has text: seems you're missing a `/` in your css string file path. Is that an accurate paste? `css='/....../`
comment on: http://stackoverflow.com/q/47925867
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82964689
score: 0
comment on: http://stackoverflow.com/q/47996863
type: Comment
type: QuestionComment
has text: @ Paul - I have edited what is currently the output and what I would like to have. This would loop through all the tabs, so for every new size, it would be put in a new row under the appropriate heading.

http://stackoverflow.com/comment/82700522
type: Comment
score: 0
type: QuestionComment
has text: What do you expect the result of `dist(i,o)` to be, when `i` is an `int` and `o` is a `tuple`?
comment on: http://stackoverflow.com/q/47865986

http://stackoverflow.com/comment/82759218
type: Comment
comment on: http://stackoverflow.com/a/47895813
type: AnswerComment
has text: @user5775949, this is strange, `df` in the loop should be a DataFrame, not a Series...
score: 0

http://stackoverflow.com/q/47927695
tagged with: pandas
favorite count: 0
has title: pandas multiply using dictionary values across several columns
has comment: http://stackoverflow.com/comment/82824980
score: 13
tagged with: python
possible better answer: http://stackoverflow.com/a/47927766
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47927730
downvote count: 0
has answer: http://stackoverflow.com/a/71055940
has body: Given the following dataframe: import pandas as pd df = pd.DataFrame({ 'a': [1,2,3,4,5], 'b': [5,4,3,3,4], 'c': [3,2,4,3,10], 'd': [3, 2, 1, 1, 1] }) And the following list of parameters: params = {'a': 2.5, 'b': 3.0, 'c': 1.3, 'd': 0.9} Produce the following desired output: a b c d output 0 1 5 3 3 24.1 1 2 4 2 2 21.4 2 3 3 4 1 22.6 3 4 3 3 1 23.8 4 5 4 10 1 38.4 I have been using this to produce the result: df['output'] = [np.sum(params[col] * df.loc[idx, col] for col in df) for idx in df.index] However, this is a very slow approach and I'm thinking there has to be a better way using built-in pandas functionality. I also thought of this: # Line up the parameters col_sort_key = list(df) params_sorted = sorted(params.items(), key=lambda k: col_sort_key.index(k[0])) # Repeat the parameters *n* number of times values = [v for k, v in params_sorted] values = np.array([values] * df.shape[0]) values array([[ 2.5, 3. , 1.3, 0.9], [ 2.5, 3. , 1.3, 0.9], [ 2.5, 3. , 1.3, 0.9], [ 2.5, 3. , 1.3, 0.9], [ 2.5, 3. , 1.3, 0.9]]) # Multiply and add product = df[col_sort_key].values * values product array([[ 2.5, 15. , 3.9, 2.7], [ 5. , 12. , 2.6, 1.8], [ 7.5, 9. , 5.2, 0.9], [ 10. , 9. , 3.9, 0.9], [ 12.5, 12. , 13. , 0.9]]) np.sum(product, axis=1) array([ 24.1, 21.4, 22.6, 23.8, 38.4]) But that seems a bit convoluted! Any thoughts on a native pandas try?
has answer: http://stackoverflow.com/a/47927766
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47927730
upvote count: 13
has comment: http://stackoverflow.com/comment/82825063
answer count: 3

http://stackoverflow.com/comment/83193678
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48007536
type: Comment
has text: OK, your question was not clear. I updated te answer to fit your needs :)

system-calls
type: Tag
tag name: system-calls
tags question: http://stackoverflow.com/q/47929915

http://stackoverflow.com/comment/112269187
comment on: http://stackoverflow.com/a/47894932
has text: @RovshanMusayev, take a look at https://cloud.google.com/docs/authentication and see if any of those strategies work for you. I'm not sure how the state of things has changed since I wrote this answer, but its possible that its now incomplete.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/47998169
score: 2
downvote count: 0
tagged with: urlopen
favorite count: 0
tagged with: urllib
has answer: http://stackoverflow.com/a/47998698
type: Question
has title: Python 3.6.3 urlopen removing server name from URI for html file stored on remote server
upvote count: 2
has body: I need to parse hundreds of HTML files that are archived on a server. The files are accessed via UNC, and then I use pathlib's as_uri() method to convert the UNC path to as URI. Full UNC path for example below: \\dmsupportfs\~images\sandbox\test.html from urllib.request import urlopen from bs4 import BeautifulSoup import os, pathlib source_path = os.path.normpath('//dmsupportfs/~images/sandbox/') + os.sep filename = 'test.html' full_path = source_path + filename url = pathlib.Path(full_path).as_uri() print('URL -&gt; ' + url) url_html = urlopen(url).read() So the URI(L) I'm passing to urlopen is: file://dmsupportfs/%7Eimages/sandbox/test.html I can plug this into any web browser and return the page, however, when urlopen goes to read the page, it's ignoring/removing the server name (dmsupportfs) from the URI, and so the read fails with not able to find the file. I assume this is something with how the urlopen method processes the URI, but I'm stumped at this point (likely something quick and easy to resolve...sorry, a bit new to Python). If I map the UNC location to a drive letter, and then use the mapped drive letter instead of the UNC path, this works without any issue. I'd like to not have to depend on a mapped drive to accomplish this though. Any advice? Below is the output from the above code showing the error: Traceback (most recent call last): File "C:\Anaconda3\lib\urllib\request.py", line 1474, in open_local_file stats = os.stat(localfile) FileNotFoundError: [WinError 3] The system cannot find the path specified: '\\~images\\sandbox\\test.html' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "url_test.py", line 10, in &lt;module&gt; url_html = urlopen(url).read() File "C:\Anaconda3\lib\urllib\request.py", line 223, in urlopen return opener.open(url, data, timeout) File "C:\Anaconda3\lib\urllib\request.py", line 526, in open response = self._open(req, data) File "C:\Anaconda3\lib\urllib\request.py",…
answer count: 1
tagged with: python-3.x
type: UnansweredQuestion
tagged with: unc
tagged with: python

http://stackoverflow.com/comment/82750934
type: Comment
comment on: http://stackoverflow.com/a/47872910
type: AnswerComment
has text: What version are you using? The [resent version](https://github.com/GoogleCloudPlatform/python-compat-runtime/blob/743ade7e1350c790c4aaa48dd2c0893d06d80cee/appengine-compat/exported_appengine_sdk/google/appengine/tools/devappserver2/watcher_common.py#L71) seems to ignore all files starting with the dot(_IGNORED_PREFIX == '.').
score: 0

http://stackoverflow.com/q/47893764
answer count: 0
has comment: http://stackoverflow.com/comment/82754192
linked to: http://stackoverflow.com/q/47152691
type: Question
has title: Split dataframe on unique value and add as new column merged on index
has comment: http://stackoverflow.com/comment/82754819
has body: Usually I am able to solve my problems from browsing SO. However, I am stuck here. Assume I have a dataframe looking like this: import itertools lst = range(1,3) group_names = ["GROUP1","GROUP2","GROUP3"] rng = pd.date_range('1/1/2011', periods=24, freq='H') time_index = pd.Series(list(itertools.chain.from_iterable(itertools.repeat(rng, 3))), name="Time") values = pd.Series(np.random.randn(len(time_index)), index=time_index, name="Values") groups = pd.Series(list(itertools.chain.from_iterable(itertools.repeat(x, 24) for x in group_names)), index=time_index, name="Groups") df = pd.concat([values, groups], axis=1) The dataframe should like this: Values Groups Time 2011-01-01 00:00:00 0.339785 GROUP1 2011-01-01 01:00:00 0.384126 GROUP1 2011-01-01 02:00:00 -0.096264 GROUP1 ... 2011-01-01 01:00:00 1.448881 GROUP2 2011-01-01 02:00:00 1.448881 GROUP2 2011-01-01 03:00:00 1.448881 GROUP2 2011-01-01 04:00:00 -0.256500 GROUP2 2011-01-01 05:00:00 -1.818228 GROUP2 Note that the Time Index is 24 hours, but always for the same day. I want to achieve that each unique group in the "Groups" column will be inserted as a new column with the respective value for the "Values" column. All columns now are merged on the same Time Index. The aspired outcome: df2 = pd.DataFrame(np.random.randn(24, 3), columns=group_names, index=rng) GROUP1 GROUP2 GROUP3 2011-01-01 00:00:00 -0.144325 -0.883371 2.245540 2011-01-01 01:00:00 -0.311808 -0.854769 0.229355 2011-01-01 02:00:00 0.983453 -1.741552 2.409349 2011-01-01 03:00:00 0.303125 -1.363857 0.484512 ... 2011-01-01 19:00:00 1.129852 1.374176 -0.639436 2011-01-01 20:00:00 -0.793817 -1.834729 -0.089721 2011-01-01 21:00:00 1.389437 -1.198244 -0.430752 2011-01-01 22:00:00 0.321585 -0.107011 -0.083659 2011-01-01 23:00:00 0.886643 -0.390729 -2.380853 So far I have tried couple of attemps, starting from groupby to a simple loop. for group in df.Groups.unique(): df[group ] = df[(df2.Groups== group )]["Value"] However, this results in NaN for all the duplica…
score: 0
tagged with: pandas
duplicate of: http://stackoverflow.com/q/47152691
has comment: http://stackoverflow.com/comment/82754179
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82754843
tagged with: python

http://stackoverflow.com/a/47898279
answers question: http://stackoverflow.com/q/47898022
type: Answer
score: 1
has body: I suggest using the Beautiful Soup library. You could do the following assuming that the site you want to scrape is stored as html: b = BeautifulSoup(html, 'lxml') links = [i['href'] for i in b.find_all('a') if "blog" in i['href']] This makes a list of the href tags of each link on the page and then filters that list for elements that contain the string blog.
upvote count: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47898022

http://stackoverflow.com/q/47858877
type: UnansweredQuestion
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/82682543
type: Question
has title: Discord Bot - Java script code to Python
upvote count: 0
score: -2
tagged with: javascript
has comment: http://stackoverflow.com/comment/82682344
has answer: http://stackoverflow.com/a/47858987
answer count: 1
tagged with: discord
favorite count: 0
has body: Okay, so my java script bot has a line of code that i am trying to recreate in python! If anyone could tell me the pieces i would need to make it. Or even how to make it in python i would greatly appreciate it! const fs = require("fs"); let points = JSON.parse(fs.readFileSync("./points.json", "utf8")); client.on("message", message =&gt; { if (message.author.bot) return; // always ignore bots! // if the points don"t exist, init to 0; if (!points[message.author.id]) points[message.author.id] = { points: 0, level: 0 }; points[message.author.id].points++; // And then, we save the edited file. fs.writeFile("./points.json", JSON.stringify(points), (err) =&gt; { if (err) console.error(err) }); }); I want to keep using .json if possible! But if theirs a better way please tell! &lt;3

http://stackoverflow.com/comment/82690063
type: QuestionComment
comment on: http://stackoverflow.com/q/47862209
has text: You are doing enough processing that you can hit HTTP timeouts easily. I would recommend you handle this workflow using some task manager like [celery](http://www.celeryproject.org/). You can handle your workflow much better with celery and you don't need to have or manager multiple processes.
score: 0
type: Comment

http://stackoverflow.com/a/47922388
has body: You have named your foreign key building_id, therefore the id is building_id_id. If you want to assign the id instead of the instance, then you have to do: row = data( oDate=oDate, building_id_id=building_id, content=content, ) The recommended approach in Django would be to name your foreign key building. class data(models.Model): oDate = models.DateField() building = models.ForeignKey( building_list, to_field = "building_id" ) Now the id is building_id, and you can do: row = data( oDate=oDate, building_id=building_id, content=content , )
upvote count: 1
answers question: http://stackoverflow.com/q/47921673
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/q/47944124
tagged with: python
has comment: http://stackoverflow.com/comment/82859778
has comment: http://stackoverflow.com/comment/82858275
answer count: 1
has body: I created a rule to add to an open vswitch when it connects to the controller. The rule allows h1 to communicate with h2 which are both on the same switch. The rule below is added when the connection to the controller comes up. event.connection.send( of.ofp_flow_mod(action=of.ofp_action_output(port=1), priority=45, match=of.ofp_match(dl_type=0x800, nw_dst="10.0.0.7"))) For some reason the flow will not work, but if i change it to match using ports instead if IP it will work. As there is multiple switches i can't just match on ports alone. at first i though maybe ICMP wasnt IPV4 but i confirmed it is using Tcpdump. sudo tcpdump -e -r tcpdump.pcap dst 192.168.0.103 reading from file tcpdump.pcap, link-type EN10MB (Ethernet) 14:24:30.940749 00:a0:98:ae:2c:fe (oui Unknown) &gt; 00:1d:ec:0e:0b:fa (oui Unknown), ethertype IPv4 (0x0800), length 98: 192.168.0.112 &gt; 192.168.0.103: ICMP echo request, id 1962, seq 1, length 64 the network consists of a spine switch connected to 2 leaf switches and 2 hosts per leaf switch. Any help would be greatly appreciated. def _handle_ConnectionUp(self, event): #dpid = event.connection.dpid # printing the dpid # log.info("Switch with DPID of %s has come up.",dpid_to_str(event.dpid)) print("Switch with DPID of %s has come up." % (dpid_to_str(event.dpid))) # printing the dpid in hex # log.info("Switch with DPID in HEX format of %s has come up." % (hex(event.dpid))) print("Switch with DPID in HEX format of %s has come up." % (hex(event.dpid))) if event.dpid == 0x1: event.connection.send( of.ofp_flow_mod(action=of.ofp_action_output(port=2), priority=45, match=of.ofp_match(in_port = 1))) event.connection.send( of.ofp_flow_mod(action=of.ofp_action_output(port=1), priority=45, match=of.ofp_match(dl_type=0x800, nw_dst="10.0.0.1")))
score: 0
accepted answer: http://stackoverflow.com/a/47947040
has comment: http://stackoverflow.com/comment/82873429
tagged with: pox
has comment: http://stackoverflow.com/comment/82859048
tagged with: mininet
tagged with: sdn
has comment: http://stackoverflow.com/comment/82859585
has title: Pox proactive openflow rule
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47947040
type: Question
tagged with: openvswitch

http://stackoverflow.com/q/47976961
has body: I setup and launch the chat server example at here Chat server example. And I can enter login and connect and send message using the broswer and the java socket.io client. But I can't login to the chat server using python socketio-client. Below is the python client code: $ cat client.py, the port is change to 3001, original is 3000 #!/usr/bin/env python from socketIO_client import SocketIO, BaseNamespace class MyNamespace(BaseNamespace): def connect(self, *args): print('on_connect', args) def on_connect(self, *args): print('on_connect', args) def user(self, *args): print('on_aaa_response', args) def on_aaa_response(self, *args): print('on_aaa_response', args) socketIO = SocketIO('localhost', 3001) namespace = "chat" event_name = "connect" my_namespace = socketIO.define(MyNamespace, "/") #my_namespace = socketIO.define(MyNamespace, "/my_namespace") my_namespace.emit(event_name, {"message": "from python socketio-client"}) socketIO.wait(seconds=1) Below is the log when run it: $ python3 client.py Traceback (most recent call last): File "client.py", line 18, in &lt;module&gt; socketIO = SocketIO('localhost', 3001) File "/home/hexiongjun/.local/lib/python3.5/site-packages/socketIO_client/__init__.py", line 353, in __init__ resource, hurry_interval_in_seconds, **kw) File "/home/hexiongjun/.local/lib/python3.5/site-packages/socketIO_client/__init__.py", line 54, in __init__ self._transport File "/home/hexiongjun/.local/lib/python3.5/site-packages/socketIO_client/__init__.py", line 62, in _transport self._engineIO_session = self._get_engineIO_session() File "/home/hexiongjun/.local/lib/python3.5/site-packages/socketIO_client/__init__.py", line 76, in _get_engineIO_session transport.recv_packet()) StopIteration And at the node chat server, I add the DEBUG=* to view the logs, when the python client test program run, the server outputs following: engine intercepting request for path "/socket.io/" +6s engine handling "GET" http request "/socket.io/?EIO=3&amp;t=1514282079724-0&a…
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: node.js
answer count: 0
score: 1
has title: Python SocketIO client can't connect to Socket.IO chat example server
upvote count: 1
tagged with: socket.io
type: Question

http://stackoverflow.com/comment/82989184
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48009907
has text: This won't support floating point inputs, since on input `3.6` it'll return `1`.

http://stackoverflow.com/comment/82748137
type: AnswerComment
comment on: http://stackoverflow.com/a/47880324
type: Comment
has text: @DebanjanB Yep... I believe that's the core of a good answer. To explain why the OP's attempts failed so they can learn what they were doing wrong. Another crucial part of a good answer is to actually answer the question. I've done that also by providing 3 different approaches. I addressed the part about the extra text being printed but OP didn't state whether they cared if that text was in there so I described how to fix it themselves which is covered in many, many other questions and blogs and tutorials on the web so it was left to OP to figure out.
score: 0

http://stackoverflow.com/comment/82689745
score: 0
type: Comment
type: QuestionComment
has text: scrolled canvas is scrolled only when you use scrollbars or when you write code which will scroll it. When you draw with turtle then you could check position and scroll canvas.
comment on: http://stackoverflow.com/q/47861592

http://stackoverflow.com/comment/82892001
type: QuestionComment
score: 0
has text: @RoryDaulton After `s = input()` `s` is a string. I only used empty string in `''.join`, what should I have used instead? I don't get the last sentence either.
comment on: http://stackoverflow.com/q/47961401
type: Comment

http://stackoverflow.com/q/47990299
favorite count: 0
has body: I have created a model for gender classification using NLTK in python. I am using a feed-forward mechanism. How to incorporate a back propagation method into this? import nltk from nltk.corpus import names import random def gender_features(word): return {'last_letter': word[-1]} labeled_names=([(name1,'male') for name1 in names.words('male.txt')]+ (name1,'female') for name1 in names.words('female.txt')]) random.shuffle(labeled_names) featuresets = [(gender_features(n), gender) for (n, gender) in labeled_names] train_set, test_set = featuresets[1500:], featuresets[:1500] classifier = nltk.NaiveBayesClassifier.train(train_set) #name input part check=input('enter the name you wanna check: ') print(classifier.classify(gender_features(check))) print(nltk.classify.accuracy(classifier, test_set)) feedback=input('is my answer correct??? [Y/N]: ') if feedback=='Y': print('thanks') elif feedback=='N': def gender_features1(word): return {'last_letter': word[-1], 'second_last_letter': word[-2]} labeled_names=([(name1,'male') for name1 in names.words('male.txt')]+ [(name1,'female') for name1 in names.words('female.txt')]) random.shuffle(labeled_names) featuresets = [(gender_features1(n), gender) for (n, gender) in labeled_names] train_set= featuresets[:1000] classifier = nltk.NaiveBayesClassifier.train(train_set) check1=input('plz enter the name again: ') print(classifier.classify(gender_features(check1))) else: print('i dnt understand this input') NaiveBayesClassifier accepts feautresets but i want to retrain the classifier with the new input data each time the user inputs a name. I have also tried taking two feature sets the second time, but i don't know how to move forward with this part.
tagged with: python
tagged with: nlp
answer count: 0
tagged with: backpropagation
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/111463175
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/82982995
score: 1
tagged with: tags
downvote count: 0
has title: backpropagation for gender classification model using python

http://stackoverflow.com/q/47896028
tagged with: flask
score: 0
answer count: 1
has body: I working on my little package, and I came across with the weird werkzeug problem. Problem: When I tried to run my application in debug mode, and in order to run my application I use the command python3 -m my_app --start I got the error ModuleNotFoundError: No module named '__main__.helpers'; '__main__' is not a package the files are very simple app.py class Application: """Main class""" def __init__(self): self.reader = ApplicationReader() self.app = Flask(self.reader.name) def __start_server(self): """Custom method, for starting flask application""" self.app.run(debug=True) def run(self): """Run the server""" return self.__start_server() # Instance of Application class application = Application() def start_app(): """Start the mock server """ return application.run() __main__.py def cli(run, init, start): if run: print('Your API is running...') if init: create_init_file() if start: start_app() if __name__ == '__main__': cli() And seems like the bug can't be fixed, GitHub issue So, maybe someone have a solution for this case? Thanks.
tagged with: werkzeug
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51051750
type: Question
has title: Flask don't work with debug mode

http://stackoverflow.com/comment/82737405
has text: @timgeb yes, I had to rewrite it as I am looking for examples of how to do rather than just fix my code or so! Thanks
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/47884034

http://stackoverflow.com/comment/82737175
type: QuestionComment
comment on: http://stackoverflow.com/q/47885340
type: Comment
score: 0
has text: You haven't included your VIEW here so confusion got created to me, I thought it is list API but it create API, so now override create method in Serializer in your case IpCollectionSerializer and add your logic (RAW code) to create those models and use Transaction to maintain database.

http://stackoverflow.com/q/47980410
has answer: http://stackoverflow.com/a/47980557
tagged with: python
has answer: http://stackoverflow.com/a/69670473
tagged with: selenium
has answer: http://stackoverflow.com/a/69899847
type: Question
tagged with: phantomjs
has answer: http://stackoverflow.com/a/47985520
has comment: http://stackoverflow.com/comment/82939936
has title: module 'selenium.webdriver' has no attribute 'PhantomJS'
has answer: http://stackoverflow.com/a/72415296
score: 15
has comment: http://stackoverflow.com/comment/82929587
upvote count: 15
has comment: http://stackoverflow.com/comment/82929565
downvote count: 0
has body: I am running PhantomJS by driver = webdriver.PhantomJS(executable_path='E:\phantomjs\bin\phantomjs.exe') but the program fails, saying AttributeError: module 'selenium.webdriver' has no attribute 'PhantomJS'. OS is Windows 10. My python version is 3.6, selenium version is 3.8.0, and the phantomjs version is 2.1.1. All of them is newest. Thanks if anyone could offer a hand! Following is the screenshot of selenium version.
favorite count: 0
answer count: 5
type: UnansweredQuestion

http://stackoverflow.com/a/64619127
upvote count: 3
downvote count: 1
type: Answer
score: 2
has body: ''' Distributed load among several Docker containers using Python multiprocessing capabilities ''' import random import time import subprocess import queue from multiprocessing import Pool, Queue, Lock LOCK = Lock() TEST_QUEUE = Queue() class TestWorker(object): ''' This Class is executed by each container ''' @staticmethod def run_test(container_id, value): ''' Operation to be executed for each container ''' cmd = ['docker exec -it {0} echo "I am container {0}!, this is message: {1}"' \ .format(container_id, value)] process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) for line in process.stdout: print(line.decode('utf-8')[:-2]) process.wait() @staticmethod def container(container_id): ''' Here we get a value from the shared queue ''' while not TEST_QUEUE.empty(): LOCK.acquire() try: value = TEST_QUEUE.get(block=False) time.sleep(0.5) except queue.Empty: print("Queue empty ):") return print("\nProcessing: {0}\n".format(value)) LOCK.release() TestWorker.run_test(container_id, value) def master(): ''' Main controller to set containers and test values ''' qty = input("How many containers you want to deploy: ") msg_val = input("How many random values you want to send among this containers: ") print("\nGenerating test messages...\n") for _ in range(int(msg_val)): item = random.randint(1000, 9999) TEST_QUEUE.put(item) ids = [] for _ in range(int(qty)): container_id = subprocess.run(["docker", "run", "-it", "-d", "centos:7"], \ stdout=subprocess.PIPE) container_id = container_id.stdout.decode('utf-8')[:-1] ids.append(container_id) pool = Pool(int(qty)) pool.map(TestWorker.container, ids) pool.close() master()
answers question: http://stackoverflow.com/q/47989418

http://stackoverflow.com/comment/82814651
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47923442
has text: @N.Ivanov Apparently, I placed it myself in the static folder where 'collectstatic' adds them and that didn't work, I had to place it in myapp/static and that worked, not sure why :?
score: 0

http://stackoverflow.com/comment/82700374
has text: thank you. it works for me.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47867191
score: 1

http://stackoverflow.com/a/47871866
has body: The following line: health1 = 'you have', hp1 Is creating a tuple with two values: "you have" and 100 (Note that the value of hp1 is copied, and not referenced). It's then assigning this tuple to a new variable named health1. health1 has nothing to do with hp1. If hp1 get overriden, deleted, thrown away, or anything happens to it, health1 doesn't care. If you are so eager to pass this variable a reference, you can create a wrapper class around the int type: class IntWrapper(object): def __init__(self, value): self.value = value def __add__(self, value): return IntWrapper(self.value + value) def __iadd__(self, value): self.value += value return self def __sub__(self, value): return IntWrapper(self.value - value) def __isub__(self, value): self.value -= value return self def __str__(self): return str(self.value) def __repr__(self): return str(self) hp1 = IntWrapper(100) health1 = 'you have', hp1 hp1 -= 50 print hp1 # 50 print health1 # ('you have', 50)
has comment: http://stackoverflow.com/comment/82713073
has comment: http://stackoverflow.com/comment/82712679
has comment: http://stackoverflow.com/comment/82715129
score: 2
has comment: http://stackoverflow.com/comment/82711633
has comment: http://stackoverflow.com/comment/82712586
type: Answer
has comment: http://stackoverflow.com/comment/82711008
has comment: http://stackoverflow.com/comment/82714211
has comment: http://stackoverflow.com/comment/82715067
upvote count: 3
has comment: http://stackoverflow.com/comment/82712907
has comment: http://stackoverflow.com/comment/82712269
has comment: http://stackoverflow.com/comment/82714906
downvote count: 1
has comment: http://stackoverflow.com/comment/82711390
has comment: http://stackoverflow.com/comment/82712507
has comment: http://stackoverflow.com/comment/82714983
answers question: http://stackoverflow.com/q/47871806

http://stackoverflow.com/comment/82933442
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47981501
has text: I AM NOT WORTHY, I AM NOT WORTHY, I AM NOT WORTHY.

http://stackoverflow.com/comment/82832167
type: AnswerComment
comment on: http://stackoverflow.com/a/47931000
score: 0
type: Comment
has text: @TylerNG Also, just keep in mind that changing the data/question invalidates the answers, so try not to do it too often :-)

http://stackoverflow.com/comment/82703423
type: Comment
comment on: http://stackoverflow.com/a/47868659
score: 1
type: AnswerComment
has text: @RoadRunner Time complexity should be O(n), same as using `index`, but seemingly with some overhead.

http://stackoverflow.com/comment/82768172
comment on: http://stackoverflow.com/a/47896080
score: 0
has text: Now I'm quite happy with the answer. Interesting and informative. Thank you!
type: AnswerComment
type: Comment

http://stackoverflow.com/a/54670783
score: 1
answers question: http://stackoverflow.com/q/48004229
upvote count: 1
type: Answer
has body: To put this here to help others trying to use pygal to create maps. Yes, following from what @Carolos said, you can also easily export them as html. like this: import pygal from pygal.maps.world import World worldmap_chart = World() worldmap_chart.title = 'Some countries' worldmap_chart.add('F countries', ['fr', 'fi']) worldmap_chart.add('M countries', ['ma', 'mc', 'md', 'me', 'mg', 'mk', 'ml', 'mm', 'mn', 'mo', 'mr', 'mt', 'mu', 'mv', 'mw', 'mx', 'my', 'mz']) worldmap_chart.add('U countries', ['ua', 'ug', 'us', 'uy', 'uz']) worldmap_chart.render_to_file('mymap.html')
downvote count: 0

http://stackoverflow.com/q/47981366
downvote count: 1
linked to: http://stackoverflow.com/q/35817
has body: I am doing a python3 software that use google_speech and and os.system command. Everything work fine but when a user enter a string with the ' character I have this error : Syntax error: Unterminated quoted string This is my code : def textToSpeak(): global fieldValues msg = "Enter the text to speak\n\nDon't use" +str(" \' ")+str(" write it like this : je tinvite chez moi, not je t\'invite chez moi ") title = "Enter the text to speak" fieldNames = ["Text to speak"] fieldValues = [] fieldValues = multenterbox(msg, title, fieldNames) speak() def speak(): global lang, fieldValues textValue = "google_speech -l" +str(lang) +str(" \'\"")+str(fieldValues[0])+str("\"\'") os.system(textValue)
type: Question
has comment: http://stackoverflow.com/comment/82931481
has comment: http://stackoverflow.com/comment/82931233
has comment: http://stackoverflow.com/comment/82931255
has answer: http://stackoverflow.com/a/47981464
score: 0
answer count: 3
favorite count: 0
has answer: http://stackoverflow.com/a/47981440
type: UnansweredQuestion
has title: Python3 replace automaticaly single quote by \'
has answer: http://stackoverflow.com/a/47990752
upvote count: 1
tagged with: python
tagged with: quote
has comment: http://stackoverflow.com/comment/82931352

http://stackoverflow.com/comment/82879382
has text: @ForceBru Ohhh Thank you for your reply
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47954890

http://stackoverflow.com/comment/82984616
comment on: http://stackoverflow.com/q/48007699
has text: What causes the pop up show? what platform are you on? what kind of application? what have you tried? Please give us some more context so that we have a better idea of the problem.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/47969772
score: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47969721
upvote count: 1
has body: Assuming what you mean by this is that your array ['#', 'path', 'to', 'key'] has indexes leading into a nested starting from index 1, you could iterate over each item in the list starting from the second and just dig deeper through every iteration. For example, in Python 3 you could do this. def get_key_from_path(exp, path): """Returns the value at the key from &lt;path&gt; in &lt;exp&gt;. """ cur = exp for dir in path[1:]: cur = exp[dir] return cur

http://stackoverflow.com/q/47951956
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82874458
has comment: http://stackoverflow.com/comment/82873520
has comment: http://stackoverflow.com/comment/82875861
type: Question
score: 3
has comment: http://stackoverflow.com/comment/82873487
tagged with: matplotlib
has body: TL; DR How to I set the map to be exactly 1600x900 px? Description I am trying to draw a map with Jupyter Notebook using Basemap library as follows: from mpl_toolkits.basemap import Basemap import numpy as np import matplotlib.pyplot as plt atlas = Basemap( llcrnrlon = -10.5, # Longitude lower right corner llcrnrlat = 35, # Latitude lower right corner urcrnrlon = 14.0, # Longitude upper right corner urcrnrlat = 44.0, # Latitude upper right corner resolution = 'i', # Crude resolution projection = 'tmerc', # Transverse Mercator projection lat_0 = 39.5, # Central latitude lon_0 = -3.25 # Central longitude ) atlas.drawmapboundary(fill_color='aqua') atlas.fillcontinents(color='#cc9955',lake_color='aqua') atlas.drawcoastlines() plt.show() and getting the following result Is it possible to make the drawn map larger, defining the minimum width and height it should have?
answer count: 1
downvote count: 1
tagged with: matplotlib-basemap
favorite count: 0
has comment: http://stackoverflow.com/comment/82875960
has title: How to define map width/height using Matplot Basemap on Jupyter Notebook?
has comment: http://stackoverflow.com/comment/82875813
tagged with: python
has answer: http://stackoverflow.com/a/47952105
accepted answer: http://stackoverflow.com/a/47952105
upvote count: 4
tagged with: jupyter-notebook

http://stackoverflow.com/comment/82932817
has text: @HughBothwell each row is one line...No CSV file has more than a line per row....CSV stands for comma separated values..and each line is called a data record... https://en.wikipedia.org/wiki/Comma-separated_values go through this link for poof...
type: AnswerComment
comment on: http://stackoverflow.com/a/47970924
type: Comment
score: 0

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/47923795
type: Tag
tags question: http://stackoverflow.com/q/47883843
tags question: http://stackoverflow.com/q/47959593
tags question: http://stackoverflow.com/q/47992427
tags question: http://stackoverflow.com/q/48013377
tags question: http://stackoverflow.com/q/47879938
tags question: http://stackoverflow.com/q/47995002
tags question: http://stackoverflow.com/q/47942623
tags question: http://stackoverflow.com/q/47888548
tags question: http://stackoverflow.com/q/47957460
tags question: http://stackoverflow.com/q/48001004
tags question: http://stackoverflow.com/q/48007017
tags question: http://stackoverflow.com/q/47980917
tags question: http://stackoverflow.com/q/47886931
tag name: csv
tags question: http://stackoverflow.com/q/47918024
tags question: http://stackoverflow.com/q/47887603
tags question: http://stackoverflow.com/q/47956020
tags question: http://stackoverflow.com/q/47879683
tags question: http://stackoverflow.com/q/47941232
tags question: http://stackoverflow.com/q/47955218
tags question: http://stackoverflow.com/q/47878765
tags question: http://stackoverflow.com/q/47916114
tags question: http://stackoverflow.com/q/47999233
tags question: http://stackoverflow.com/q/47975028
tags question: http://stackoverflow.com/q/47907029
tags question: http://stackoverflow.com/q/47889215
tags question: http://stackoverflow.com/q/47998419
tags question: http://stackoverflow.com/q/47916009
tags question: http://stackoverflow.com/q/47940238
tags question: http://stackoverflow.com/q/48011743
tags question: http://stackoverflow.com/q/47979326
tags question: http://stackoverflow.com/q/47944526
tags question: http://stackoverflow.com/q/47873161
tags question: http://stackoverflow.com/q/47895825
tags question: http://stackoverflow.com/q/47978380
tags question: http://stackoverflow.com/q/47944567
tags question: http://stackoverflow.com/q/47903085
tags question: http://stackoverflow.com/q/47856519
tags question: http://stackoverflow.com/q/47995833
tags question: http://stackoverflow.com/q/47883188
tags question: http://stackoverflow.com/q/47907505
tags question: http://stackoverflow.com/q/47864373
tags question: http://stackoverflow.com/q/47971809
tags question: http://stackoverflow.com/q/47857982
tags question: http://stackoverflow.com/q/47857239
tags question: http://stackoverflow.com/q/47943416
tags question: http://stackoverflow.com/q/48002981
tags question: http://stackoverflow.com/q/47892567
tags question: http://stackoverflow.com/q/47964897
tags question: http://stackoverflow.com/q/47985931
tags question: http://stackoverflow.com/q/47873034
tags question: http://stackoverflow.com/q/47888546
tags question: http://stackoverflow.com/q/48003385
tags question: http://stackoverflow.com/q/47903276
tags question: http://stackoverflow.com/q/47911773
tags question: http://stackoverflow.com/q/47983782
tags question: http://stackoverflow.com/q/47983869
tags question: http://stackoverflow.com/q/47887445
tags question: http://stackoverflow.com/q/47969758
tags question: http://stackoverflow.com/q/47886090
tags question: http://stackoverflow.com/q/48005341
tags question: http://stackoverflow.com/q/47918306
tags question: http://stackoverflow.com/q/47898531
tags question: http://stackoverflow.com/q/48006780
tags question: http://stackoverflow.com/q/47879740
tags question: http://stackoverflow.com/q/47859537
tags question: http://stackoverflow.com/q/47920650
tags question: http://stackoverflow.com/q/47914844
tags question: http://stackoverflow.com/q/47896329
tags question: http://stackoverflow.com/q/48001630
tags question: http://stackoverflow.com/q/47901631
tags question: http://stackoverflow.com/q/47879813
tags question: http://stackoverflow.com/q/47968470
tags question: http://stackoverflow.com/q/47970825
tags question: http://stackoverflow.com/q/47917943
tags question: http://stackoverflow.com/q/47917135
tags question: http://stackoverflow.com/q/47925894
tags question: http://stackoverflow.com/q/47951637

http://stackoverflow.com/comment/104299832
type: Comment
score: 2
comment on: http://stackoverflow.com/a/47896300
type: AnswerComment
has text: What if I *want* a `KeyError` to be raised if there are any missing labels? That is, if I actually *want* the new behavior? Right now `.loc[list_of_names]` will give this warning, which I do not want to see. Any way to disable it?

http://stackoverflow.com/comment/82979424
comment on: http://stackoverflow.com/q/48005152
type: Comment
has text: Excellent. But you **still** haven't told us what you want to do with zeros in the data! If it's impossible for zeros to occur, you need to tell us that.
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82919131
score: 0
type: Comment
type: QuestionComment
has text: the `'r'` argument to `open` makes no difference in the two code snippets. Indeed, `'r'` is already the default argument: `open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)`
comment on: http://stackoverflow.com/q/47974914

http://stackoverflow.com/a/48000065
has body: Here is the simplest way if the order in the matching list is important. &gt;&gt;&gt; out = [] &gt;&gt;&gt; for ii, elem in enumerate(node[:-1]): ... for jj in range(ii + 1, len(node)): ... common = [subelem for subelem in elem[-1] if subelem in node[jj][-1]] ... if len(common) &gt; 0 and common != ['']: ... out.append([elem[0], node[jj][0], common]) ... &gt;&gt;&gt; for elem in out: ... print elem ... ['1003', '1004', ['Lion', 'Leopard', 'Panda']] ['1003', '1005', ['Lion', 'Panda']] ['1004', '1005', ['Lion', 'Panda', 'Tiger']] ['1004', '1007', ['Tiger']] ['1005', '1007', ['Cheetah', 'Goat', 'Tiger']] If order is not important and the lists are big use set intersection for the first line in the double loop as below common = list(set(elem[-1]).intersection(set(node[jj][-1])))
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47999883
answers question: http://stackoverflow.com/q/47999883

http://stackoverflow.com/q/47985721
answer count: 1
favorite count: 0
has title: ModuleNotFoundError: No module named 'pygal' in Anaconda. When I import on terminal I don't get errors.
has answer: http://stackoverflow.com/a/47985765
type: UnansweredQuestion
tagged with: python
downvote count: 1
type: Question
has body: I've tried running it on Python 3.6.3 and Python 3.5.4 Neither runs when I use text editors. I've tried Spyder, Idle and Sublime Text.
score: -1
upvote count: 0

http://stackoverflow.com/a/47994654
answers question: http://stackoverflow.com/q/47993977
downvote count: 0
has comment: http://stackoverflow.com/comment/82957389
upvote count: 2
type: Answer
has body: The data from Anton :-) df[df.groupby(df[0].dt.year)[0].apply(lambda x : x.dt.week==x.dt.week.max())] Out[1471]: 0 1 2 3 4 5 0 2017-12-25 52.99 13018070.0 52.370 53.06 51.40 3 2016-12-30 46.75 13593420.0 48.365 48.40 46.36 4 2016-12-29 47.77 11728250.0 48.440 48.86 47.18 5 2016-12-28 48.51 14636340.0 50.580 50.73 48.47 6 2016-12-27 50.43 5594876.0 49.690 50.55 49.65
score: 2
has comment: http://stackoverflow.com/comment/82957430

http://stackoverflow.com/comment/82989223
score: 0
comment on: http://stackoverflow.com/q/48010337
has text: Ok, I edited the original post. I pasted the wrong import.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47944089
tagged with: image
linked to: http://stackoverflow.com/q/73382388
has answer: http://stackoverflow.com/a/71970755
upvote count: 3
tagged with: arrays
downvote count: 1
has answer: http://stackoverflow.com/a/78183554
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47944127
answer count: 4
score: 2
has answer: http://stackoverflow.com/a/74251441
has body: I currently have a numpy array or RBG tuples that I want to convert to a PIL image and save. Currently I'm doing the following: final = Image.fromarray(im_arr, mode='RGB'). Here im_arr is the numpy array of tuples in the form (R, G, B). It seems to end up keeping the tuples separate when it creates the image as shown below.
type: Question
tagged with: numpy
tagged with: python-imaging-library
has title: Numpy array of tuples to PIL image

http://stackoverflow.com/comment/123456286
type: Comment
type: AnswerComment
has text: @Bill: `np.cumsum()`, exactly. Less code. The `-2` is not necessary either, that's just an artefact of the chosen kernel scale.
comment on: http://stackoverflow.com/a/48001937
score: 0

http://stackoverflow.com/q/48004577
tagged with: http://stackoverflow.com/tag/json
type: Question
has title: Structure my Dictionary in Python
score: -1
downvote count: 2
upvote count: 1
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48005765
has body: I am trying to structure my dictionary in Python. The input list looks like this: [ { "title": "Test A", "date": "28.12.17", "name": "Person 1" }, { "title": "Test B", "date": "28.12.17", "name": "Person 2" }, { "title": "Test C", "date": "28.12.17", "name": "Person 1" }, { "title": "Test D", "date": "28.12.17", "name": "Person 2" }, { "title": "Test E", "date": "29.12.17", "name": "Person 1" }, { "title": "Test F", "date": "29.12.17", "name": "Person 2" }, { "title": "Test G", "date": "29.12.17", "name": "Person 1" }, { "title": "Test H", "date": "29.12.17", "name": "Person 2" } ] Now I want to generate an output which looks like this: [ { "entries": [ { "entries": [ { "title": "Test A", "date": "28.12.17", "name": "Person 1" }, { "title": "Test B", "date": "28.12.17", "name": "Person 1" } ], "name": "Person 1" }, { "entries": [ { "title": "Test C", "date": "28.12.17", "name": "Person 2" }, { "title": "Test D", "date": "28.12.17", "name": "Person 2" } ], "name": "Person 2" } ], "date": "28.12.17" }, { "entries": [ { "entries": [ { "title": "Test E", "date": "29.12.17", "name": "Person 1" }, { "title": "Test E", "date": "29.12.17", "name": "Person 1" } ], "name": "Person 1" }, { "entries": [ { "title": "Test F", "date": "29.12.17", "name": "Person 2" }, { "title": "Test G", "date": "29.12.17", "name": "Person 2" } ], "name": "Person 2" } ], "date": "29.12.17" } ] How can I do this with Python? Thank you for your answer in advance.
has comment: http://stackoverflow.com/comment/82977263
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/48005765
type: AnsweredQuestion

http://stackoverflow.com/comment/82993467
has text: You do not have a route to the server or the server isn't running. First get ping to work from cmd.exe >Pin IP. Don't use 127.0.0.1 (loopback) because most computers aren't configured to use loopback. You would have to modify the host file on your PC for loopback to work. Instead use the IP address of your computer.
type: QuestionComment
comment on: http://stackoverflow.com/q/48012394
score: 0
type: Comment

http://stackoverflow.com/q/47873077
downvote count: 0
has body: I am using simple Python script to fetch example data from Solr using Pysolr. First I created my core using the following [user@user solr-7.1.0]$ ./bin/solr create -c json_db WARNING: Using _default configset. Data driven schema functionality is enabled by default, which is NOT RECOMMENDED for production use. To turn it off: curl http://localhost:8983/solr/json_db/config -d '{"set-user-property": {"update.autoCreateFields":"false"}}' Created new core 'json_db' [user@user solr-7.1.0]$ ./bin/post -c json_db example/exampledocs/*.json SimplePostTool version 5.0.0 Posting files to [base] url http://localhost:8983/solr/json_db/update... Entering auto mode. File endings considered are xml,json,jsonl,csv,pdf,doc,docx,ppt,pptx,xls,xlsx,odt,odp,ods,ott,otp,ots,rtf,htm,html,txt,log POSTing file books.json (application/json) to [base]/json/docs 1 files indexed. COMMITting Solr index changes to http://localhost:8983/solr/json_db/update... Time spent: 0:00:00.398 After creating the core I ran simple python script to fetch data from pysolr import Solr conn = Solr('http://localhost:8983/solr/json_db/') results = conn.search('*:*') I am getting this error Traceback (most recent call last): File "/home/user/PycharmProjects/APP/application/solr_test.py", line 4, in &lt;module&gt; results = conn.search({'*:*'}) File "/home/user/PycharmProjects/APP/venv/lib/python3.5/site-packages/pysolr.py", line 723, in search response = self._select(params, handler=search_handler) File "/home/user/PycharmProjects/APP/venv/lib/python3.5/site-packages/pysolr.py", line 421, in _select return self._send_request('get', path) File "/home/user/PycharmProjects/APP/venv/lib/python3.5/site-packages/pysolr.py", line 396, in _send_request raise SolrError(error_message % (resp.status_code, solr_message)) pysolr.SolrError: Solr responded with an error (HTTP 404): [Reason: Error 404 Not Found] But when I try to run the query directly from solr I got results like the following Can somebody guide me what I am doing …
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82711738
type: UnansweredQuestion
tagged with: python
tagged with: pysolr
score: 1
tagged with: solr
upvote count: 1
has answer: http://stackoverflow.com/a/64102408
has title: Python: Access data from Solr using Pysolr
type: Question

http://stackoverflow.com/a/47980605
answers question: http://stackoverflow.com/q/47979949
has comment: http://stackoverflow.com/comment/82930011
accepted answer of: http://stackoverflow.com/q/47979949
type: Answer
has comment: http://stackoverflow.com/comment/82930135
has comment: http://stackoverflow.com/comment/82929984
has comment: http://stackoverflow.com/comment/82930140
score: 2
has comment: http://stackoverflow.com/comment/82929813
has comment: http://stackoverflow.com/comment/82929843
downvote count: 0
has comment: http://stackoverflow.com/comment/82930052
has comment: http://stackoverflow.com/comment/82930096
upvote count: 2
type: AcceptedAnswer
has body: If it is possible, read the whole file text and apply the following regex to that text: (?&lt;=Article)[\s\S]*?(?=Article|$) Click for Demo Explanation: (?&lt;=Article) - positive lookbehind to find the position immediately preceded by the text Article [\s\S]*? - matches 0+ occurrences of any character(even the newlines). ? is present to make the match lazy. (?=Article|$) - Positive lookahead to find the position that is immediately followed by either another Article or end-of-full-string represented by $

http://stackoverflow.com/comment/82715579
comment on: http://stackoverflow.com/a/47874375
type: Comment
has text: @foobar: The Python style is to not use accessors, and to make attributes be the first-class public API instead. So instead of `c.get_mechanism()`, just use `c.mechanism` (a public attribute).
score: 0
type: AnswerComment

http://stackoverflow.com/a/48349991
downvote count: 0
answers question: http://stackoverflow.com/q/47980908
upvote count: 8
has body: Try using an interactive instead. This returns the input and output widgets, which you can combine into a VBox, and then add as a child to your tab_list from ipywidgets import * import seaborn.apionly as sns df = sns.load_dataset('iris') import matplotlib.pyplot as plt #plot def plot_image(x): data = df if x != 'Select': xplot = data[x] sns.distplot(xplot) plt.show() #define widgets x = widgets.Dropdown( options=df.columns, value=df.columns[0], description='X' ) x.set_title = 'x' #assign widgets to tabs tab_visualise = widgets.HBox([x]) #create tabs tab_nest = widgets.Tab() # tab_nest.children = [tab_visualise] tab_nest.set_title(0, 'Visualise') #interact function in isolation f = interactive(plot_image, x = x); tab_nest.children = [VBox(children = f.children)] display(tab_nest)
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84288905
score: 8
type: Answer
accepted answer of: http://stackoverflow.com/q/47980908

http://stackoverflow.com/a/48000315
has body: Start from the innermost value, working outward. At each step, use the previous step's dict as the new val. def nest_dict(lst): my_dict = lst[-1] for val in lst[-2::-1]: my_dict = {val: my_dict} return my_dict print nest_dict(range(1, 11)) Output: {1: {2: {3: {4: {5: {6: {7: {8: {9: 10}}}}}}}}}
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48000274
upvote count: 2

http://stackoverflow.com/q/47958126
type: Question
score: 3
accepted answer: http://stackoverflow.com/a/47958873
possible better answer: http://stackoverflow.com/a/77135023
has answer: http://stackoverflow.com/a/77135023
answer count: 2
tagged with: azure
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/47958873
tagged with: python
tagged with: rbac
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82887707
has title: Create service principal programmatically in Azure Python API
has body: How can I, using the Azure Python API, create a full set of credentials that can later be used to start and deallocate all VMs in a named resource group, without any other permissions? I have thoroughly researched the example code and both official and unofficial documentation, but I don't even know where to start... I know I will need a tenant ID, client ID, client secret and subscription ID. Which of those can I make using an API, and how would I go about assigning roles to allow for starting/deallocating VMs of an existing resource group? Sample code highly sought after, but will take any hint!
upvote count: 3
has comment: http://stackoverflow.com/comment/82889908
tagged with: service-principal
has comment: http://stackoverflow.com/comment/82886863

http://stackoverflow.com/q/47955153
downvote count: 1
type: Question
upvote count: 0
has title: regular expression for date, time and phone not matching
score: -1
has comment: http://stackoverflow.com/comment/82879798
has body: 29/11/16, 12:22 AM - ‪+91 99102 28632‬ I want to write a regular expression to match this pattern. I wrote something like this - \d{2}\/\d{2}\/\d{2},\s\d?\d:\d{2}\s(AM|PM)\s\-\s\+91\s\d{5}\s\d{5} But it's not matching with the pattern. I'm using Python's inbuilt Re module to compile the pattern and the finditer method to find the matches and create an interator. But, actually, there are no matches found with this. When I used sublime text to test my regex, I noticed that it worked till \d{2}\/\d{2}\/\d{2},\s\d?\d:\d{2}\s(AM|PM)\s\-\s But as soon as I added \+ it stopped recognizing the regex. Any solutions?
answer count: 1
has answer: http://stackoverflow.com/a/47955191
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/82879890

http://stackoverflow.com/comment/82726503
type: QuestionComment
comment on: http://stackoverflow.com/q/47879574
has text: What is your expected output? Grrr!!! how come this can be a question at all?
score: 0
type: Comment

http://stackoverflow.com/a/64929410
answers question: http://stackoverflow.com/q/47972430
score: 0
type: Answer
has body: I believe I understand the question, I've just had the same issue, where I'm defining a set of mixins, each of which pop some arguments out and past the rest to their superclass. They can be initialised in any order. I bumped into this error because I made the slightly different mistake of not defining the base class (to accept the (self, *args, **kwargs) function signature) at all. What I (and presumably you) want is a Base class which: accepts *args and **kwargs so you can use any combination of your mixins meets @Willem Van Onsem' concern in the comments that arguments vanish silently if you simply don't call them. That would look something like this: class ResourceBase: """ Allows you to use any combination of mixin classes which pass unused *args and **kwargs up to their superclass, without encountering: ``` Error Traceback (most recent call last): super().__init__(*args, **kwargs) TypeError: object.__init__() takes no parameters ``` on initialisation. The case of passing extra args and kwargs to your class constructor which aren't popped by the various mixins is still handled safely with the same error (to prevent loss of variables and poorly defined behaviour later). """ def __init__(self, *args, **kwargs): """ Constructor for ResourceBase """ if (len(args) > 0) or (len(kwargs.keys()) > 0): # Initialisation has gone all the way up to the base class and there are still parameters in *args or **kwargs. Scream at the user (you could probably give a more helpful error message than this) raise TypeError('object.__init__() takes no parameters') super().__init__() This allows you to create and use, in any order, any number of mixins with a signature like: class MyMixin: """ Mixin to do a thing with an important kwarg. Notice how `my_important_kwarg` is popped out of the kwargs in the constructor signature, so shouldn't end up at the base class. """ def __init__(self, *args, my_important_kwarg=None, **kwargs): """ Constructor for MyMixin """ super().__init__(*args, *…

http://stackoverflow.com/comment/82894749
type: Comment
type: QuestionComment
has text: BTW if you want efficient crawling, try looking as `scrapy`.
comment on: http://stackoverflow.com/q/47962083
score: 0

http://stackoverflow.com/q/47901157
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82769145
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/47901410
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47901493
linked to: http://stackoverflow.com/q/47903414
has answer: http://stackoverflow.com/a/47901410
score: 1
has comment: http://stackoverflow.com/comment/82769200
has title: How to compare two dataframes columns?
has body: import pandas as pd import quandl import numpy as np import matplotlib.pyplot as plt from matplotlib import style style.use("fivethirtyeight") df_2010=pd.read_csv("c:/users/ashub/downloads/documents/MLB 2010.csv",index_col=0) #print(df_2010) sliced_data=df_2010"Home Team","Away Team","Home Score","Away Score" #print(sliced_data) for win in sliced_data: flag1=sliced_data["Home Team"]+str("index") flag2=sliced_data["Away Team"]+str("index") print(sliced_data["Home Score"],sliced_data["Away Score"]) if sliced_data["Home Score"]&gt;sliced_data["Away Score"]: df_2010=df_2010.join([1,0],index=[flag1,flag2]) else: df_2010=df_2010.join([0,1],index=[flag1,flag2]) df_2010.to_html("c:/users/ashub/desktop/ashu.html") ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). The error is at if condition when i am comparing the score of home team and away team.What I want to do is to add a column to the csv file which lists the win or loss of a team,win being 1 and loss being zero so that i can add the win of a particular team in a season and calculate their probability of winning and predict the probability of winning in the next season,
type: Question
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82768906
accepted answer: http://stackoverflow.com/a/47901493
tagged with: pandas
has comment: http://stackoverflow.com/comment/82768842
favorite count: 0

http://stackoverflow.com/comment/82802781
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47916767
score: 0
has text: Sorry, it should have been `file_texts = defaultdict(str)`. You probably don't even really need defaultdict and could use a regular dict instead if you prefer.

http://stackoverflow.com/a/47909908
accepted answer of: http://stackoverflow.com/q/47909840
has body: Try this: table = boto3.resource('dynamodb', region_name=region).Table(table_name) item = { "username" : "chicken", "fav_food" : "ketchup" } table.put_item(Item=item) If you post the gotten error it will help a little bit.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47909840
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/q/47857632
has body: Having worked with other programming/scripting languages, I am completely baffled by Python's mysql interface (I am a bit new to Python) I am unable to commit my changes. I have stripped the code to the bare minimum: #!/usr/bin/python import mysql.connector as mariadb mariadb_connection = mariadb.connect( user='testdb', password='testdb', database='testdb', host='127.0.0.1', autocommit=True ) mariadb_connection.autocommit=True cursor = mariadb_connection.cursor(buffered=True) cursor.execute( "UPDATE testdb SET descr='konijn' WHERE number=14549") mariadb_connection.commit() mariadb_connection.close() I would have expected that the autocommit would do the trick, but it doesn't. Also, the mariadb_connection.commit() does nothing to commit the changes. The database is (for as much as relevant): number INTEGER, type VARCHAR(255), file VARCHAR(255), year INTEGER, month INTEGER, descr VARCHAR(4096) I am able to commit changes using the same credentials using TCL/Tk, so it should not be a permission problem. What am I doing wrong?
accepted answer: http://stackoverflow.com/a/47874560
tagged with: mysql
type: Question
has comment: http://stackoverflow.com/comment/82680125
answer count: 2
has comment: http://stackoverflow.com/comment/82680197
has comment: http://stackoverflow.com/comment/82680151
score: 10
has comment: http://stackoverflow.com/comment/82679605
has answer: http://stackoverflow.com/a/47874560
has comment: http://stackoverflow.com/comment/82679890
has comment: http://stackoverflow.com/comment/82682941
has title: Python mysql does not commit
possible better answer: http://stackoverflow.com/a/71358676
has answer: http://stackoverflow.com/a/71358676
upvote count: 10
has comment: http://stackoverflow.com/comment/82679794
has comment: http://stackoverflow.com/comment/82680025
has comment: http://stackoverflow.com/comment/82680646
favorite count: 0
has comment: http://stackoverflow.com/comment/82679976
has comment: http://stackoverflow.com/comment/82680058
has comment: http://stackoverflow.com/comment/82683058
has comment: http://stackoverflow.com/comment/82680774
tagged with: python
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/82796026
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47913377
has text: `print a[0:0]` gives `[]`, so nothing gets deleted, and you're stuck doing taking the same branch with each recursion.

http://stackoverflow.com/q/47904839
tagged with: http://stackoverflow.com/tag/r
has title: Passing values from python to Rscript and vice-versa?
has body: I have built a regression model in R and want to use it in python. import subprocess subprocess.call("/usr/local/bin/Rscript --vanilla script.r", shell=True) Above commands run the R script. But I want to pass some values to the R script, which act as the input to the model. Also want to get back the model result. How can I do that? I checked rpy2 module, but it didn't feel very dependable.
favorite count: 0
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: subprocess
score: 1
has comment: http://stackoverflow.com/comment/82776439
type: Question
downvote count: 0

http://stackoverflow.com/a/47941367
answers question: http://stackoverflow.com/q/47939702
score: 0
has body: How about this. I used css selectors to do the same. from bs4 import BeautifulSoup from urllib.parse import urljoin import requests link = "http://www.cnnvd.org.cn/web/vulnerability/querylist.tag" res = requests.get(link) soup = BeautifulSoup(res.text, "lxml") for item in soup.select('.fl p a'): print("Item: {}\nItem_link: {}".format(item.text,urljoin(link,item['href']))) Partial Output: Item: CNNVD-201712-811 Item_link: http://www.cnnvd.org.cn/web/xxk/ldxqById.tag?CNNVD=CNNVD-201712-811 Item: CNNVD-201712-810 Item_link: http://www.cnnvd.org.cn/web/xxk/ldxqById.tag?CNNVD=CNNVD-201712-810 Item: CNNVD-201712-809 Item_link: http://www.cnnvd.org.cn/web/xxk/ldxqById.tag?CNNVD=CNNVD-201712-809
type: Answer

http://stackoverflow.com/a/47942528
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/82870198
has body: Im not using setParent command, it is too confusing for me, I've corrected you problem by adding parent flag in : form and cmds.button("Submit Job....)" Most of the time im using column and row layout only import maya.cmds as cmds # Make a new window window = cmds.window( title="Render", iconName='BTD', widthHeight= (400,500),titleBar=True,minimizeButton=True,maximizeButton=True ) cmds.columnLayout( adjustableColumn=True) columnMain = cmds.columnLayout() # &lt;&lt;================================ form = cmds.formLayout(p=columnMain) tabs = cmds.tabLayout(innerMarginWidth=10, innerMarginHeight=10) cmds.formLayout(form,edit=True,attachForm=((tabs, 'top', 0), (tabs, 'left', 0), (tabs, 'bottom', 0), (tabs, 'right', 0)) ) child1 = cmds.rowColumnLayout(numberOfColumns=2) cmds.button(label='1') cmds.button(label='2') cmds.button(label='3') cmds.button(label='9') cmds.button(label='9') cmds.button(label='9') cmds.button(label='9') cmds.button(label='9') cmds.setParent( '..' ) child2 = cmds.rowColumnLayout(numberOfColumns=1,columnOffset = (1,'left',10)) #cmds.text("Output Directory",width = 50,height=50,font = "boldLabelFont") cmds.text("Output Directory",width=200, height=50,font="boldLabelFont", align='left') name = cmds.textField(w = 300,h = 20) cmds.text("Notify on job completion",width = 200,height=50,font = "boldLabelFont",align='left') name = cmds.textField(w = 370,h = 20) cmds.setParent( '..' ) child3 = cmds.rowColumnLayout(numberOfColumns=2) cmds.button(label='7') cmds.button(label='8') cmds.button(label='9') cmds.setParent( '..' ) cmds.tabLayout( tabs, edit=True, tabLabel=((child1, 'General'), (child2, 'Advanced'),(child3, 'Job Software')) ) cmds.setParent( '..' ) #cmds.setParent( '..' ) cmds.button("Submit Job",width=100, height=50, align='right', p=columnMain) # &lt;&lt;================================ cmds.showWindow( window ) EDIT ----- Here is example of how many layout, I would use : row/colum (note that the red rectangle is the tab widget) EDIT 2 ----- here …
has comment: http://stackoverflow.com/comment/82875325
accepted answer of: http://stackoverflow.com/q/47940276
answers question: http://stackoverflow.com/q/47940276

http://stackoverflow.com/a/61090187
type: Answer
has body: Try: df2 = df2.append(df1.iloc[x]) DataFrame.append(self, other, ignore_index=False, verify_integrity=False, sort=False) → 'DataFrame Append rows of other to the end of caller, returning a new object. REF
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/47963548
score: 4
has comment: http://stackoverflow.com/comment/127859068

http://stackoverflow.com/a/47867939
has comment: http://stackoverflow.com/comment/82701126
upvote count: 10
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82700925
type: Answer
accepted answer of: http://stackoverflow.com/q/47867760
answers question: http://stackoverflow.com/q/47867760
downvote count: 0
has comment: http://stackoverflow.com/comment/82701923
score: 10
has body: For a properly normalized relational database schema, you want a distinct Choice model with a foreign key on Question: class Question(models.Model): question = models.CharField(...) class Choice(models.Model): question = models.ForeignKey("Question", related_name="choices") choice = modelsCharField("Choice", max_length=50) position = models.IntegerField("position") class Meta: unique_together = [ # no duplicated choice per question ("question", "choice"), # no duplicated position per question ("question", "position") ] ordering = ("position",) And then you can get at a Question's choices with myquestion.choices.all() (and get the question from a Choice with mychoice.question). Note that this won't impose any limitation on the number of choices for a Question, not even mandates that a Question has at least one related Choice. Unless you have a very compelling reason to do otherwise, a properly normalized schema is what you want when using a relational database (rdbms are much more than mere bitbuckets, they offer a lot of useful features - as long as you do have a proper schema, that is).

http://stackoverflow.com/q/47908050
tagged with: types
tagged with: string
favorite count: 0
has title: could not convert string to float: '7,751.30'
type: Question
has answer: http://stackoverflow.com/a/47908102
tagged with: python
score: -2
has body: I get the TWSE price from Taiwan Stock Exchange. df = pd.read_csv(r'C:\Stock\TWSE.csv',encoding='Big5') df.head() 日期 開盤指數 最高指數 最低指數 收盤指數 0 96/02/01 7,751.30 7,757.63 7,679.78 7,701.54 1 96/02/02 7,754.16 7,801.63 7,751.53 7,777.03 2 96/02/05 7,786.77 7,823.94 7,772.05 7,783.12 3 96/02/06 7,816.30 7,875.75 7,802.94 7,875.75 4 96/02/07 7,894.77 7,894.77 7,850.06 7,850.06 df.loc[0][2] '7,757.63' type(df.loc[0][2]) str I want to convert the str type to float type for the purpose of plotting. But, I can not convert them. For example: float(df.loc[0][2]) ValueError: could not convert string to float: '7,757.63'
has comment: http://stackoverflow.com/comment/82783325
downvote count: 2
has answer: http://stackoverflow.com/a/47908430
answer count: 2
linked to: http://stackoverflow.com/q/37439933
has comment: http://stackoverflow.com/comment/82783893
has comment: http://stackoverflow.com/comment/82783282
duplicate of: http://stackoverflow.com/q/37439933
tagged with: dataframe
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82783668
tagged with: pandas
upvote count: 0

http://stackoverflow.com/a/47905677
has body: Find the first element lesser than 0 with lt + idxmax - i = df.hrs.lt(0).idxmax() Perform indexing and assignment with loc - df.loc[i, 'running_hrs'] = df.loc[i - 1, 'hrs'] df hrs running_hrs 0 203.889578 24.000000 1 155.929832 24.000000 2 180.248357 24.000000 3 112.502220 24.000000 4 102.261148 24.000000 5 86.982634 24.000000 6 35.552699 24.000000 7 29.260349 24.000000 8 0.577342 24.000000 9 -23.297091 0.577342 10 -42.875767 0.000000 11 -77.278587 0.000000 If required, ensure that i is greater than 0 before assigning - if i &gt; 0: df.loc[i, 'running_hrs'] = df.loc[i - 1, 'hrs'] Otherwise, you might run into indexing errors.
answers question: http://stackoverflow.com/q/47905393
score: 2
downvote count: 0
upvote count: 2
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47905393

http://stackoverflow.com/q/47967584
tagged with: one-hot-encoding
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/82904864
has comment: http://stackoverflow.com/comment/82904731
accepted answer: http://stackoverflow.com/a/47967781
upvote count: 1
has comment: http://stackoverflow.com/comment/82904930
has comment: http://stackoverflow.com/comment/82904967
tagged with: pandas
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47967781
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82904635
score: 1
has title: Pandas get_dummies generates multiple columns for the same feature
favorite count: 0
has body: I'm using a pandas series and trying to convert it to one hot encoding. I'm using the describe method in order to check how many unique categories the series has. The output is: input['pattern'].describe(include='all') count 9725 unique 7 top 1 freq 4580 Name: pattern, dtype: object When I'm trying: x = pd.get_dummies(input['pattern']) x.describe(include= 'all') I get 18 classes with 12 classes which are completely zeros. How come did get_dummies produced classes which did not occur even once in the input?
has comment: http://stackoverflow.com/comment/82904695

http://stackoverflow.com/comment/82942931
has text: Sorry @LoïcFaure-Lacroix, I missed my point, So my point was I tried to use compute method with the state field (store=True) and I set @api.depends('order_line.product_qty', 'order_line.qty_received') I want it triggers when those fields have been changed and then update the state field. But before that I have a wizard form to generate purchase.order.line in my active purchase.order then after I clicked generate button on the wizard form to execute function the infinite loading screen happen. PS. The button works well before I created the compute method and add it into the state field.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47982933

http://stackoverflow.com/comment/82720447
has text: @WoodyPride `\s` can match normal white space, tab `\t` and new line characters `\n` or `\r` on windows while `" "` only matches normal white space.
type: Comment
comment on: http://stackoverflow.com/a/47877235
score: 1
type: AnswerComment

http://stackoverflow.com/q/47900257
tagged with: visual-studio-code
downvote count: 0
has title: Autocomplete for Automation objects in VS Code and Python
favorite count: 0
answer count: 3
upvote count: 11
has body: I have the Python Extensions for Windows installed. Within the PythonWin IDE I can get autocomplete on Automation objects (specifically, objects created with win32com.client.Dispatch): How can I get the same autocomplete in VS Code? I am using the Microsoft Python extension. The Python Windows Extensions has a tool called COM Makepy, which apparently generates Python representations of Automation objects, but I can't figure out how to use it. Update Apparently, the Microsoft Python extension uses Jedi for autocompletion. I've filed an issue on the extension project on Github. Note that in general I have Intellisense in Python; it's only the Intellisense on Automation objects that I am missing.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82854823
tagged with: python
score: 11
has answer: http://stackoverflow.com/a/48012544
has answer: http://stackoverflow.com/a/47985648
tagged with: win32com
tagged with: jedi
has answer: http://stackoverflow.com/a/47984501
type: Question
linked to: http://stackoverflow.com/q/23864234

http://stackoverflow.com/q/47906708
has answer: http://stackoverflow.com/a/47906777
upvote count: 3
has answer: http://stackoverflow.com/a/47906846
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/47906864
type: Question
has title: Python re - findall vs finditer
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/47906864
answer count: 3
possible better answer: http://stackoverflow.com/a/47906777
tagged with: python
has body: I have the following string: '3 4 4 5 5 5 2 2' I need to extract all the consecutive occurrences out of it like so: '44 555 22' To do this I'm using the below code. It works fine: n = input().replace(' ', '') result = re.finditer(r'(\d)\1+', n) for match in result: print(match.group(0), end=' ') My question is how I can modify my regex so I can use findall() instead? I tried by using this: n = input().replace(' ', '') result = re.findall(r'(\d)\1+', n) print(result) It returns just this: ['4', '5', '2']. What's the reason for this behavior? By looking at the regex it looks like the pattern is capturing group 1 only instead of group 0. I think I'm unable to call group() on findall. Is it any way I can change my pattern or something else I can do to get same result from findall? For example: ['44', '555', '22'].
tagged with: regex

http://stackoverflow.com/comment/82682338
has text: Manually add a newline character `\n`
comment on: http://stackoverflow.com/q/47858869
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47889998
has comment: http://stackoverflow.com/comment/82747084
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82746929
accepted answer of: http://stackoverflow.com/q/47889024
type: Answer
answers question: http://stackoverflow.com/q/47889024
has body: You should use a callable that returns the datetime that you want, for example: from datetime import timedelta from django.utils import timezone def in_three_days(): return timezone.now() + timedelta(days=3) class TestModel(models.Model): event = models.DateTimeField(default=in_three_days) If you use x = datetime.datetime.now() + datetime.timedelta(days = 3) as in Vaibhav's answer, then x will be calculated when the module is loaded, not when each new TestModel instance is created.
upvote count: 7
score: 7

http://stackoverflow.com/a/47926490
accepted answer of: http://stackoverflow.com/q/47926434
answers question: http://stackoverflow.com/q/47926434
type: AcceptedAnswer
downvote count: 0
has body: This gives a Series: my_series = df["column1"] but this a sub-dataframe: my_dataframe = df"column1" which shows the column name.
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/a/47860867
answers question: http://stackoverflow.com/q/47860134
has body: Pandas is an amazing tool for tabular data. But while it can contain Python objects, that is not its sweet spot. I suggest you extract your data from the query prior to inserting them into a pandas.Dataframe: Extract records: To extract the desired fields as a list of dictionaries is as easy as: records = [dict(id=rec['Id'], country=rec['Account']['BillingCountry']) for rec in data['records']] Insert records into a dataframe: With a list of dicts, a dataframe is as easy as: df = pd.DataFrame(records) Test Code: import pandas as pd from collections import OrderedDict data = OrderedDict([ ('totalSize', 455), ('done', True), ('records', [ OrderedDict([ ('attributes', OrderedDict([('type', 'Opportunity'), ('url', '/services/data/v34.0/sobjects/Opportunity/0061B003451RhZgiHHF')])), ('Id', '0061B003451RhZgiHHF'), ('Account', OrderedDict([('attributes', OrderedDict([('type', 'Account'), ('url', '/services/data/v34.0/sobjects/Account/0013000000MvkRQQAZ')])), ('BillingCountry', 'United States')])), ]), OrderedDict([ ('attributes', OrderedDict([('type', 'Opportunity'), ('url', '/services/data/v34.0/sobjects/Opportunity/0061B00001Pa52QQAR')])), ('Id', '0061B00001Pa52QQAR'), ('Account', OrderedDict([('attributes', OrderedDict([('type', 'Account'), ('url', '/services/data/v34.0/sobjects/Account/0011300001vQPxqAAG')])), ('BillingCountry', 'United States')])), ]), OrderedDict([ ('attributes', OrderedDict([('type', 'Opportunity'), ('url', '/services/data/v34.0/sobjects/Opportunity/0061B00001TRu5mQAD')])), ('Id', '0061B00001TRu5mQAD'), ('Account', OrderedDict([('attributes', OrderedDict([('type', 'Account'), ('url', '/services/data/v34.0/sobjects/Account/0011300001rfRTrAAE')])), ('BillingCountry', 'United States')])), ]), ]) ]) records = [dict(id=rec['Id'], country=rec['Account']['BillingCountry']) for rec in data['records']] for r in records: print(r) print(pd.DataFrame(records)) Test Results: {'country': 'United States', 'id': '0061B003451RhZgiHHF'} {'country': 'United States', 'i…
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/138571811
downvote count: 0
upvote count: 11
type: Answer
accepted answer of: http://stackoverflow.com/q/47860134
has comment: http://stackoverflow.com/comment/138562136
score: 11
has comment: http://stackoverflow.com/comment/82686733

http://stackoverflow.com/comment/82780144
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47903890
score: 0
has text: If you have a new question, then open a new question. Don't modify the same thing, it benefits no one.

http://stackoverflow.com/comment/82801254
type: QuestionComment
comment on: http://stackoverflow.com/q/47910355
score: 2
has text: @EugeneS nope. that question only for "using profile that have already exist in chrome with selenium". what i want is to "create new profile using selenium". not manually go to setting -> manage other people -> add person. i want to create hundreds of profile.
type: Comment

http://stackoverflow.com/comment/83118297
has text: Thanks Keles ! It's really helpful !!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47963893
type: AnswerComment

http://stackoverflow.com/comment/82942818
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47986976
has text: what are you saving in these variables **var2 to var6**?
score: 0

http://stackoverflow.com/q/47925511
has comment: http://stackoverflow.com/comment/82818649
score: 2
linked to: http://stackoverflow.com/q/22392377
type: UnansweredQuestion
tagged with: web-scraping
has answer: http://stackoverflow.com/a/47925692
has comment: http://stackoverflow.com/comment/82818698
type: Question
has comment: http://stackoverflow.com/comment/82824504
has body: I had made a script for scraping some data from a web site but it only runs for a few few pages and after that it will stop with this message "'NoneType' object has no attribute 'a'".Another error which appear sometimes is this: File "scrappy3.py", line 31, in &lt;module&gt; f.writerow(doc_details) File "C:\python\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u015f' in position 251: character maps to &lt;undefined&gt; Can You please give me an advice how to resolve those errors.This is my script: import requests import csv from bs4 import BeautifulSoup import re import time start_time = time.time() page = 1 f = csv.writer(open("./doctors.csv", "w", newline='')) while page &lt;= 5153: url = "http://www.sfatulmedicului.ro/medici/n_s0_c0_h_s0_e0_h0_pagina" + str(page) data = requests.get(url) print ('scraping page ' + str(page)) soup = BeautifulSoup(data.text,"html.parser") for liste in soup.find_all('li',{'class':'clearfix'}): doc_details = [] url_doc = liste.find('a').get('href') for a in liste.find_all('a'): if a.has_attr('name'): doc_details.append(a['name']) data2 = requests.get(url_doc) soup = BeautifulSoup(data2.text,"html.parser") a_tel = soup.find('div',{'class':'contact_doc add_comment'}).a tel_tag=a_tel['onclick'] tel = tel_tag[tel_tag.find("$(this).html("):tel_tag.find(");")].lstrip("$(this).html(") doc_details.append(tel) f.writerow(doc_details) page += 1 print("--- %s seconds ---" % (time.time() - start_time))
answer count: 2
has title: why i get the "'NoneType' object has no attribute" error
downvote count: 1
has answer: http://stackoverflow.com/a/47925733
favorite count: 0
tagged with: beautifulsoup
tagged with: python-3.x
upvote count: 3
tagged with: python

http://stackoverflow.com/q/47969925
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/82909373
type: Question
has title: python use variable in Modbusclient
has body: I am having an issue with using a variable in a function. ports = ["'/dev/ttyXRUSB0'","'/dev/ttyXRUSB1'"] for item in ports: print len(ports) #port = item print item client = ModbusClient(method = 'rtu', port = item, baudrate = 115200, timeout = 0.2) print client client.connect() I want to see client = ModbusClient(method = 'rtu', port = '/dev/ttyXRUSB0' baudrate = 115200, timeout = 0.2) Where am i messing this up?
tagged with: pymodbus3
score: 0
has comment: http://stackoverflow.com/comment/82909269
has comment: http://stackoverflow.com/comment/82909223

http://stackoverflow.com/a/66319258
answers question: http://stackoverflow.com/q/47956236
upvote count: 2
score: 2
downvote count: 0
type: Answer
has body: If you're using coverage, you can modify your CI .yml file by adding NUMBA_DISABLE_JIT=1 right before your coverage command: NUMBA_DISABLE_JIT=1 coverage run -p "test_*.py"

http://stackoverflow.com/comment/82904872
has text: Because i want to use MQTT protocol for IoT with this code, so i need to send the G-Code to the CNC machine instead of keep it in the text file in laptop.@JoeIddon
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47963316

http://stackoverflow.com/comment/82789321
comment on: http://stackoverflow.com/q/47910810
score: 0
type: Comment
type: QuestionComment
has text: you forgot `./awslogs-agent-setup.py` after `python`, but that's not all, it's looks like `./awslogs-agent-setup.py` expect to read a specific file on filesystem - so you will have to update it so it can read curl's output directly as argument

http://stackoverflow.com/q/47948965
tagged with: mypy
score: 4
upvote count: 4
accepted answer: http://stackoverflow.com/a/47948986
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
type: AnsweredQuestion
has body: I have a list (of length two) and I want to convert it to a tuple from typing import List, Tuple l: List[int] = [1, 2] assert len(l) == 2 t: Tuple[int, int] = tuple(l) No matter what I do, I get the error message: Incompatible types in assignment (expression has type "Tuple[int, ...]", variable has type "Tuple[int, int]") I've tried splicing t: Tuple[int, int] = tuple(l)[0:2] t: Tuple[int, int] = tuple(l[0:2]) and recreating t: Tuple[int, int] = tuple([l[0], l[1]]) t: Tuple[int, int] = l[0], l[1] # strangely invalid syntax, even though t = l[0], l[1] is valid and I've read through the docs, but I haven't found any way to do this cleanly.
has answer: http://stackoverflow.com/a/47948986
type: Question
has title: How do I convert a list to a tuple without angering mypy?

http://stackoverflow.com/comment/82899308
type: Comment
comment on: http://stackoverflow.com/a/47964659
score: 1
type: AnswerComment
has text: But I'd like to be able to specify row indexes as first argument to groupby (analogous to specifying column indexes as first argument when doing groupby with axis=0). You see what I mean ?

http://stackoverflow.com/q/48009727
has body: Is there a way to configure cherrypy to correctly decode utf-8 encoded authentication strings? Update It's know limitation documented in issue #1680. Until the issue is resolved, CherryPy will not recognize UTF-8 encoded Basic-Auth Data. Original Problem I have trouble using basic-auth with name/passwords using umlaut characters. There seem to be no way to either bring the http-client to issue ISO-8859-1 (which cherrypy would unterstand) name:password or to configure cherrypy to decode the authentication string using utf-8. Using Python 3.6 and CherryPy 13.1.0: import cherrypy class SimpleWebpage(object): @cherrypy.expose def index(self): return " Authenticated " def dummy_validate(realm, username, password): print("realm: {realm!r}, username: {username!r}, password: {password!r}".format_map(locals())) return True cherrypy.tree.mount(SimpleWebpage(), '/', {'/': {'tools.auth_basic.checkpassword': dummy_validate, 'tools.auth_basic.on': True, 'tools.auth_basic.realm': 'MY_REALM',}}) cherrypy.config.update({'tools.sessions.on': True,}) cherrypy.engine.autoreload.unsubscribe() cherrypy.engine.start() cherrypy.engine.block() Calling curl with the following arguments: curl -u 'Céline:motörhead' -i -X GET http://127.0.0.1:8080/ Will give the following output from the cherrypy console: [28/Dec/2017:15:52:57] ENGINE Bus STARTING [28/Dec/2017:15:52:57] ENGINE Serving on http://127.0.0.1:8080 [28/Dec/2017:15:52:57] ENGINE Bus STARTED realm: 'MY_REALM', username: 'CÃ©line', password: 'motÃ¶rhead' 127.0.0.1 - C\xc3\x83\xc2\xa9line [28/Dec/2017:15:53:18] "GET / HTTP/1.1" 200 52 "" "Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US))" Tested with curl 7.56.1 (i686-pc-cygwin) on cygwin and curl 7.19.7 (x86_64-redhat-linux-gnu) on redhat6. I've also tested it with google-chrome 63.0.3239.108 with the exact same results. Kludge def decode_utf8(s): s_bytes = bytes([ord(c) for c in s]) return s_bytes.decode('utf-8') def dummy_validate(realm, username, password): username = decode…
has comment: http://stackoverflow.com/comment/83011691
favorite count: 0
answer count: 1
tagged with: basic-authentication
tagged with: python
has comment: http://stackoverflow.com/comment/83011640
tagged with: cherrypy
accepted answer: http://stackoverflow.com/a/48023459
has comment: http://stackoverflow.com/comment/83009210
upvote count: 2
downvote count: 1
has title: CherryPy allways decodes Basic Auth with ISO-8859-1
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/83011758
tagged with: character-encoding
type: Question
has comment: http://stackoverflow.com/comment/83007345
has answer: http://stackoverflow.com/a/48023459
has comment: http://stackoverflow.com/comment/83011657

http://stackoverflow.com/q/47943242
has comment: http://stackoverflow.com/comment/82856878
type: UnansweredQuestion
has body: I have 2 numpy ndarray The first contain x and y values : xy_arr = [[ 736190.125 1130. ] [ 736190.16666667 1130. ] [ 736190.20833333 1130. ] ..., [ 736190.375 1140. ] [ 736190.41666667 1140. ] [ 736190.45833333 1140. ] [ 736190.5 1140. ]] the second have x y and index values and is much bigger than the first: xyind_arr = [[ 7.35964000e+05 1.02000000e+03 0.00000000e+00] [ 7.35964042e+05 1.02000000e+03 1.00000000e+00] [ 7.35964083e+05 1.02000000e+03 2.00000000e+00] ..., [ 7.36613397e+05 1.09500000e+03 3.07730000e+04] [ 7.36613404e+05 1.10000000e+03 3.07740000e+04] [ 7.36613411e+05 1.10500000e+03 3.07750000e+04]] I want to keep all rows of the xyind_arr where values are same in xy_arr like : (xyind_arr[:,0] == xy_arr[:,0]) and (xyind_arr[:,1] == xy_arr[:,1]) My code : sub_array = xyind_arr[((xyind_arr[:, 0] == xy_arr[:, 0]) &amp; (xyind_arr[:, 1] == xy_arr[:, 1]))] Only work if the xy_array have one element. For example : import numpy as np xy_arr = np.array([[56, 400]]) xyind_arr = np.array([[5, 6, 0],[8, 12, 1],[9, 17, 2],[56, 400, 3],[23, 89, 4]]) sub_array = xyind_arr[((xyind_arr[:, 0] == xy_arr[:, 0]) &amp; (xyind_arr[:, 1] == xy_arr[:, 1]))] print(sub_array) result OK : [[ 56 400 3]] But with xy_arr = np.array([[5, 6],[8, 12],[23, 89]]) The result is [] And I expected [[5, 6, 0],[8, 12, 1],[23, 89, 4]] Is there any clean numpy method to obtain this filtered sub array ? Edit : Finally I let down the numpy solution and use the python set() : xy_arr_set = set(map(tuple, xy_arr)) xyind_arr_set = set(map(tuple, xyind_arr)) for x, y, ind in xyind_arr_set: if (x,y) in xy_arr_set: "do what i need"
has comment: http://stackoverflow.com/comment/82856343
tagged with: sub-array
type: Question
has answer: http://stackoverflow.com/a/47944753
tagged with: numpy
answer count: 1
has title: Filter numpy ndarray with another ndarray, row by row
score: 0
tagged with: filter
tagged with: multidimensional-array
has comment: http://stackoverflow.com/comment/82857641
tagged with: python
has comment: http://stackoverflow.com/comment/82856147

http://stackoverflow.com/comment/82734718
type: QuestionComment
has text: Try typing *python3* just as it is. Maybe it is a problem with the .exe wich is not really compatible with linux...
score: 0
comment on: http://stackoverflow.com/q/47883593
type: Comment

http://stackoverflow.com/comment/82802334
score: 0
type: Comment
type: QuestionComment
has text: gives not 422 error, but some other
comment on: http://stackoverflow.com/q/47917056

http://stackoverflow.com/a/48828449
type: Answer
answers question: http://stackoverflow.com/q/47894191
has comment: http://stackoverflow.com/comment/92318186
downvote count: 4
has comment: http://stackoverflow.com/comment/87712681
upvote count: 0
score: -4
has body: Well, When we talk about multi-process with python these things happens: The OS does all the multi-tasking work The only option for multi-core concurrency Duplicated use of system resources There are huge differences between osx and linux. and osx is based on Unix and treats multi tasking process in other way than linux. Unix installation requires a strict and well-defined hardware machinery and works only on specific CPU machines, and maybe osx is not designed to speed up python processes. This reason may be the cause. For more details you can read the MultiProcessing documentation. I hope it helps.

http://stackoverflow.com/a/47856244
answers question: http://stackoverflow.com/q/47856233
type: Answer
upvote count: 1
score: 0
downvote count: 1
has body: You can pass a lambda expression: def check_password(password, f): return any(f(i) for i in password) print(check_password("theString", lambda x:x.isupper())) Or, pass the desired string method to the function: print(check_password("theString", str.isupper)) Output: True

http://stackoverflow.com/q/47983782
has comment: http://stackoverflow.com/comment/82936614
has body: I´m trying to read a csv file separate with ;. Code: import csv with open('Ingresos_e_eCPM_por_fecha_y_cliente.csv', 'rb') as csvfile: spamreader = csv.reader(csvfile, quotechar='|') for row in spamreader: print ', '.join(row) I have this csv data: 21/12/2017;En;229.620;18.508;8,06%;14,56;0,79 22/12/2017;En;204.042;48.526;23,78%;43,98;0,91 23/12/2017;En;102.613;20.223;19,71%;17,86;0,88 24/12/2017;En;90.962;19.186;21,09%;14,26;0,74 25/12/2017;En;60.189;12.654;21,02%;11,58;0,92 The problem is when I try to read with my python code, It shows me these: 21/12/2017;En;229.620;18.508;8, 06%;14, 56;0, 79 22/12/2017;En;204.042;48.526;23, 78%;43, 98;0, 91 23/12/2017;En;102.613;20.223;19, 71%;17, 86;0, 88 24/12/2017;En;90.962;19.186;21, 09%;14, 26;0, 74 25/12/2017;En;60.189;12.654;21, 02%;11, 58;0, 92 I need the data in the same way as the csv!
type: Question
has comment: http://stackoverflow.com/comment/82936571
has answer: http://stackoverflow.com/a/47983906
has title: How to change the default CSV separator?
has comment: http://stackoverflow.com/comment/82936588
has answer: http://stackoverflow.com/a/47983889
answer count: 2
has comment: http://stackoverflow.com/comment/82990316
has comment: http://stackoverflow.com/comment/82936576
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/82936862
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
score: 0
type: UnansweredQuestion

http://stackoverflow.com/tag/r
tags question: http://stackoverflow.com/q/47984045
tags question: http://stackoverflow.com/q/47875130
tags question: http://stackoverflow.com/q/47861085
tags question: http://stackoverflow.com/q/47892384
tags question: http://stackoverflow.com/q/47860821
tag name: r
tags question: http://stackoverflow.com/q/47963996
tags question: http://stackoverflow.com/q/48001329
tags question: http://stackoverflow.com/q/47946551
type: Tag
tags question: http://stackoverflow.com/q/47928754
tags question: http://stackoverflow.com/q/47928211
tags question: http://stackoverflow.com/q/47890011
tags question: http://stackoverflow.com/q/47860815
tags question: http://stackoverflow.com/q/47917549
tags question: http://stackoverflow.com/q/47904839
tags question: http://stackoverflow.com/q/47943336
tags question: http://stackoverflow.com/q/47868375

http://stackoverflow.com/comment/82909154
type: AnswerComment
comment on: http://stackoverflow.com/a/47969895
type: Comment
score: 2
has text: I have to admit `align` is new to me

http://stackoverflow.com/comment/82777882
has text: The first question is bad but answer is useful, it represents how to include any library in your Azure ML Studio environment. Some Python libraries (Anaconda) are included by default - you don't need a special module to import them into the environment. The link above explains how to include library which is not already included in Azure ML environment. BUT, I can't do the same with scikit-learn because it has the same name as the version already included in Azure ML. So, if I call "import sklearn" within my script - it will call the older one because they have the same names.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47904508
score: 0

http://stackoverflow.com/a/50221340
answers question: http://stackoverflow.com/q/47932396
accepted answer of: http://stackoverflow.com/q/47932396
type: Answer
has body: I was able to solve the problem by changing the line of code: new_saver.restore(sess, tf.train.latest_checkpoint('./')) With: new_saver.restore(sess, args.model_meta_filename.replace(".meta", "")) To clarify, args.model_meta_filename is the name of the saved file that ends in .meta.
has comment: http://stackoverflow.com/comment/93787877
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/47982982
tagged with: outlook
has comment: http://stackoverflow.com/comment/83087378
answer count: 2
accepted answer: http://stackoverflow.com/a/48058331
score: 0
has comment: http://stackoverflow.com/comment/82958234
possible better answer: http://stackoverflow.com/a/47983324
has answer: http://stackoverflow.com/a/47983324
tagged with: email
tagged with: python
has title: Check whether the email is a reply or response with Python win32com
has body: I am using Python win32com to parse email from outlook . I am able to fetch email from the outlook folder , but I not able to verify whether the email is a reply or response or a forwarded message , I need to check whether the email reiceved is the reply of the previous mail (if yes then find the original mail) or email is the forwarded message. I am using following code to fetch emails from outlook. import win32com.client outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") inbox=outlook.Folders['xyz@xyz.com'].Folders['Inbox'].Folders['abc'] messagesReach = inbox.Items for message in messagesReach: if message.Unread==True: print(message.body)
has comment: http://stackoverflow.com/comment/82957973
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82935497
has answer: http://stackoverflow.com/a/48058331
type: Question

http://stackoverflow.com/comment/82843050
has text: Use `enumerate` so you don't need an external count variable.
type: AnswerComment
type: Comment
score: 2
comment on: http://stackoverflow.com/a/47936914

http://stackoverflow.com/comment/82824816
type: QuestionComment
has text: Did you consider using a `dict` for finding what you search for?
score: 1
comment on: http://stackoverflow.com/q/47928029
type: Comment

http://stackoverflow.com/comment/82785820
type: Comment
comment on: http://stackoverflow.com/a/47908477
has text: I dont think there is a easy answer that, Im not near my machine. Will try once I get back
score: 0
type: AnswerComment

http://stackoverflow.com/q/47885747
has title: How to construct form data (key-value pairs) from raw html in python?
has answer: http://stackoverflow.com/a/47941160
tagged with: http://stackoverflow.com/tag/html
tagged with: python
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/30964568
tagged with: forms
type: Question
accepted answer: http://stackoverflow.com/a/47941160
has body: is there any library that does this ? https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#constructing-the-form-data-set Here an example of what i want to achieve: data = """ &lt;form action='/'&gt; &lt;input type='text' name='test'&gt; &lt;/form&gt; """ x = buildformdata(data) print(x) {'test': ''} I know how to create this using for ex. beatifulsoup, but maybe theres something done already? For example, what about converting code that Firefox or Chrome uses to build that data into python? Here's some code that does this: https://github.com/jmcarp/robobrowser/blob/master/robobrowser/forms/fields.py https://github.com/jmcarp/robobrowser/blob/master/robobrowser/forms/form.py#L64
has comment: http://stackoverflow.com/comment/82737195
linked to: http://stackoverflow.com/q/1184624
answer count: 1
has comment: http://stackoverflow.com/comment/82737675

http://stackoverflow.com/a/47945997
downvote count: 0
has comment: http://stackoverflow.com/comment/82862068
has comment: http://stackoverflow.com/comment/82862970
has body: I am choosing map , you can also try merge and join, try look at index, in merge should be df1.merge(df2,left_on='Name1',right_index=True) df['Num1']=df.Name1.map(df1.Num) df['Num2']=df.Name2.map(df1.Num) df Out[1150]: Name1 Name2 Value Num1 Num2 0 x x-y 1 1 0 1 x x-z 2 1 5 2 y y-z 3 2 0 3 y y-x 5 2 5 4 z z-y 7 3 0 Another way df=df.set_index('Value').stack() df.map(df1.Num) pd.concat([df,df.map(df1.Num)],1).unstack() Out[1169]: 0 1 Name1 Name2 Name1 Name2 Value 1 x x-y 1 0 2 x x-z 1 5 3 y y-z 2 0 5 y y-x 2 5 7 z z-y 3 0
has comment: http://stackoverflow.com/comment/82862455
has comment: http://stackoverflow.com/comment/82862465
type: Answer
has comment: http://stackoverflow.com/comment/82862414
has comment: http://stackoverflow.com/comment/82862264
has comment: http://stackoverflow.com/comment/82861897
upvote count: 3
has comment: http://stackoverflow.com/comment/82862464
accepted answer of: http://stackoverflow.com/q/47945912
answers question: http://stackoverflow.com/q/47945912
has comment: http://stackoverflow.com/comment/82861942
score: 3
has comment: http://stackoverflow.com/comment/82862924
has comment: http://stackoverflow.com/comment/82862357
has comment: http://stackoverflow.com/comment/82862299
type: AcceptedAnswer

http://stackoverflow.com/q/47895765
has answer: http://stackoverflow.com/a/47920128
has answer: http://stackoverflow.com/a/74583971
tagged with: python
score: 34
has comment: http://stackoverflow.com/comment/82758811
has comment: http://stackoverflow.com/comment/82760358
linked to: http://stackoverflow.com/q/45600579
has comment: http://stackoverflow.com/comment/82758934
has comment: http://stackoverflow.com/comment/82759009
upvote count: 34
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/47627900
has answer: http://stackoverflow.com/a/65580416
has answer: http://stackoverflow.com/a/62442203
type: Question
has answer: http://stackoverflow.com/a/79023829
has body: I want to use asyncio in combination with a tkinter GUI. I am new to asyncio and my understanding of it is not very detailed. The example here starts 10 task when clicking on the first button. The task are just simulating work with a sleep() for some seconds. The example code is running fine with Python 3.6.4rc1. But the problem is that the GUI is freezed. When I press the first button and start the 10 asyncio-tasks I am not able to press the second button in the GUI until all tasks are done. The GUI should never freeze - that is my goal. #!/usr/bin/env python3 # -*- coding: utf-8 -*- from tkinter import * from tkinter import messagebox import asyncio import random def do_freezed(): """ Button-Event-Handler to see if a button on GUI works. """ messagebox.showinfo(message='Tkinter is reacting.') def do_tasks(): """ Button-Event-Handler starting the asyncio part. """ loop = asyncio.get_event_loop() try: loop.run_until_complete(do_urls()) finally: loop.close() async def one_url(url): """ One task. """ sec = random.randint(1, 15) await asyncio.sleep(sec) return 'url: {}\tsec: {}'.format(url, sec) async def do_urls(): """ Creating and starting 10 tasks. """ tasks = [ one_url(url) for url in range(10) ] completed, pending = await asyncio.wait(tasks) results = [task.result() for task in completed] print('\n'.join(results)) if __name__ == '__main__': root = Tk() buttonT = Button(master=root, text='Asyncio Tasks', command=do_tasks) buttonT.pack() buttonX = Button(master=root, text='Freezed???', command=do_freezed) buttonX.pack() root.mainloop() A _side problem ...is that I am not able to run the task a second time because of this error. Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python3.6/tkinter/__init__.py", line 1699, in __call__ return self.func(*args) File "./tk_simple.py", line 17, in do_tasks loop.run_until_complete(do_urls()) File "/usr/lib/python3.6/asyncio/base_events.py", line 443, in run_until_complete self._check_closed() Fil…
has title: Use asyncio and Tkinter (or another GUI lib) together without freezing the GUI
has answer: http://stackoverflow.com/a/58793529
downvote count: 0
possible better answer: http://stackoverflow.com/a/47896365
linked to: http://stackoverflow.com/q/1101750
has answer: http://stackoverflow.com/a/78620277
has answer: http://stackoverflow.com/a/47896365
has answer: http://stackoverflow.com/a/51971341
tagged with: python-asyncio
has comment: http://stackoverflow.com/comment/82769228
tagged with: user-interface
has answer: http://stackoverflow.com/a/47896975
answer count: 10
accepted answer: http://stackoverflow.com/a/62442203
tagged with: asynchronous
favorite count: 0
tagged with: tkinter

http://stackoverflow.com/comment/82798162
comment on: http://stackoverflow.com/q/47914980
score: 0
type: Comment
type: QuestionComment
has text: Have you tried `anaconda -h` in PowerShell or Command Prompt?

http://stackoverflow.com/comment/82946510
has text: Future of NumPy :) https://www.youtube.com/watch?v=fowHwlpGb34 Sparse arrays, categorical data, JIT compiled and lot more!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47988757
type: Comment

http://stackoverflow.com/q/47887790
score: 4
tagged with: python-2.7
has answer: http://stackoverflow.com/a/68993664
has comment: http://stackoverflow.com/comment/82749982
has comment: http://stackoverflow.com/comment/82742001
has answer: http://stackoverflow.com/a/68948768
downvote count: 0
tagged with: ssh
has answer: http://stackoverflow.com/a/69002723
linked to: http://stackoverflow.com/q/8475290
favorite count: 0
has comment: http://stackoverflow.com/comment/82742558
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82742272
tagged with: python
answer count: 4
tagged with: subprocess
has title: How to keep ssh session open after logging in using subprocess.popen?
has comment: http://stackoverflow.com/comment/122010791
has comment: http://stackoverflow.com/comment/82741763
has comment: http://stackoverflow.com/comment/82748999
type: Question
upvote count: 4
has body: I am new to Python. I am trying to SSH to a server to perform some operations. However, before performing the operations, i need to load a profile, which takes 60-90 seconds. After loading the profile, is there a way to keep the SSH session open so that i can perform the operations later? p = subprocess.Popen("ssh abc@xyz'./profile'", stdout=subprocess.PIPE, shell=True) result = p.communicate()[0] print result return result This loads the profile and exits. Is there a way to keep the above ssh session open and run some commands? Example: p = subprocess.Popen("ssh abc@xyz'./profile'", stdout=subprocess.PIPE, shell=True) &lt;More Python Code&gt; &lt;More Python Code&gt; &lt;More Python Code&gt; &lt;Run some scripts/commands on xyz server non-interactively&gt; After loading the profile, I want to run some scripts/commands on the remote server, which I am able to do by simply doing below: p = subprocess.Popen("ssh abc@xyz './profile;**&lt;./a.py;etc&gt;**'", stdout=subprocess.PIPE, shell=True) However, once done, it exists and the next time I want to execute some script on the above server, I need to load the profile again (which takes 60-90 seconds). I am trying to figure out a way where we can create some sort of tunnel (or any other way) where the ssh connection remains open after loading the profile, so that the users don't have to wait 60-90 seconds whenever anything is to be executed. I don't have access to strip down the profile.
has answer: http://stackoverflow.com/a/68980568
has comment: http://stackoverflow.com/comment/82741971
tagged with: session
has comment: http://stackoverflow.com/comment/82749832

http://stackoverflow.com/a/59831788
answers question: http://stackoverflow.com/q/47896555
type: Answer
score: 0
type: AcceptedAnswer
has body: I discovered a bug with how I was using with_polymorphic. This patch [1] fixes the subqueryload query, so it does not emit a query when accessing user.shapes[0].widget (which is the expected behavior). In SQLAlchemy version 1.3, the original test case fails with an exception like: ArgumentError: Attribute "Rectangle.widget" does not link from element "with_polymorphic(Shape, [])". [1] @@ -72,12 +72,13 @@ rectangle = Rectangle(owner=user, widget=widget, length=10, width=5) session.add_all([user, widget, rectangle]) session.commit() -shapes_load = subqueryload( - User.shapes.of_type( - with_polymorphic(Shape, "*", aliased=True))) +polymorphic_shape = with_polymorphic(Shape, "*", aliased=True) +shapes_load = subqueryload(User.shapes.of_type(polymorphic_shape)) session.remove() -query = session.query(User) .options(shapes_load.joinedload(Rectangle.widget)) +query = session.query(User).options( + shapes_load.joinedload(polymorphic_shape.Rectangle.widget) +) logger.info("##########subqueryload begin") user = query.one() logger.info("##########accessing widget") @@ -85,11 +86,13 @@ user.shapes[0].widget logger.info("##########subqueryload end") shapes_load = joinedload( - User.shapes.of_type( - with_polymorphic(Shape, "*", aliased=True))) + User.shapes.of_type(with_polymorphic(Shape, "*", aliased=True)) +) session.remove() -query = session.query(User).options(shapes_load.joinedload(Rectangle.widget)) +query = session.query(User).options( + shapes_load.joinedload(polymorphic_shape.Rectangle.widget) +) logger.info("##########joinedload begin") user = query.one() logger.info("##########accessing widget")
accepted answer of: http://stackoverflow.com/q/47896555

http://stackoverflow.com/comment/82736672
score: 0
has text: Does not work because the delimiters and header alignment, dialect is gone.
type: Comment
comment on: http://stackoverflow.com/a/47884773
type: AnswerComment

http://stackoverflow.com/q/47932483
type: Question
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Celery Task not retrying as Expected
has body: I am working on a celery project. I had some old code that I am trying to re-use on a new environment. It's rather simple. My failure condition is when another task returns the blank string. The two tasks are below. @app.task(track_started=True, bind=True) def get_latakoo_transcript(self, latakoo_object_id): return my_client.get_transcript(latakoo_object_id).json()['result']['transcription'] @app.task(track_started=True, bind=True) def add_latakoo_transcript(self, latakoo_document): latakoo_object_id = latakoo_document.get_document()['headers']['id'] transcript = get_latakoo_transcript(latakoo_object_id) if transcript == '': print('-----------------------') print(latakoo_object_id) self.retry(countdown=1, max_retries=100) else: success = latakoo_document.add_transcript(transcript) response = latakoo_document.insert_document(extra_collections=['untagged']) return latakoo_document Anytime the retry mechanism hits. It prints, but does not do the retry. Task nbcu_nes_ingest.Tasks.ClassificationTasks.insert_latakoo_object[94e5388d-f1a6-4649-a75a-207a5dcd3388] retry: Task can be retried. I have the same logic, on an older version if str == '': retry of the project which works just fine. My local development machine is Windows 7. Using Python 3.3. Celery Version 3.1.8. If anyone has any thoughts please let me know. I've tried doing things with try catch block, and raiseing the retry, but nothing seems to work. edit: Adding Celery App constructor app = Celery('ClassificationTasks', broker='pyamqp://guest@localhost//', backend='amqp',)
answer count: 0
score: 1
upvote count: 1
tagged with: celery

http://stackoverflow.com/a/47889891
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47889215
answers question: http://stackoverflow.com/q/47889215
type: Answer
has comment: http://stackoverflow.com/comment/82746351
has body: Your file is not a proper csv. Well, technically you could consider it as such since there are indeed things enclosed on quotes and separated by commas, but it's all on one single line and those "things" really looks like serialized python dicts (first thought this was json but json.loads() fails on it, while ast.literal_eval() do the job). Since there's only one line, and you don't pass any fieldnames to csv.DictReader, it tries to use the first line as headers, so each of those json-like objects is considered like a fieldname. Then, since the one and only line has been consumed, the iteration stops, which is why you don't have any data in the result file. You can find this out by yourself: f = open("motherwell.csv", "rb") reader = csv.DictReader(f) print(reader.fieldnames) try: row = reader.next() print(row) except StopIteration: print("nothing else here, dude") Actually, a proper csv file would look something like (header and first rows): swlv,shell_cte,maximum_volume,offset_bottom,datum,suction_second,swuv,shell_temperature,shape,swul,knee_second,roof_end,suction_low_third,swll,knee_forth,suction_forth,id,dimension_b,roof_start,dimension_a,temperature,dimension_d,rundown_low_second,water,innage,suction_low_first,state,timestamp,shortname,roof_weight,shell_capacity,svl,product,rundown_forth,dimension_c,knee_first,suv,max_work,offset_volume,rundown_third,pressure,roof_density,rundown_low_forth,suction_first,rundown_second,volume,pos_x,pos_y,name,rundown_low_first,shell_gtemp,density,flow,shell_pressure,shell_molecular,shell_insulated,sll,knee_third,offset_level,suction_low_forth,min_work,suction_third,rundown_low_third,rundown_first,suction_low_second,slu 0,0,2.88901e+11,0,0,0.0,0,0,cylinder,0,30.0,0,0.0,0,100.0,0.0,1,76000,0,22000,0.0,0,0.0,0,0.0,0.0,Y,2017-12-14 09:24:48,A,0,0,0.0,14,0.0,0,0.0,2.88901e+11,21000,0,0.0,0,0,0.0,0.0,0.0,0,72,34,1001A,0.0,0,700,0,0,0,N,0.0,70.0,0,0.0,0,0.0,0.0,0.0,0.0,22000.0 0,0,2.88901e+11,0,0,0.0,0,0,cylinder,0,30.0,0,0.0,0,100.0,…
score: 0

http://stackoverflow.com/q/47985209
type: UnansweredQuestion
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/47991269
answer count: 1
has title: About xavier_initializer in tensorflow
has body: I see the following explanation of xavier_initializer(). It says var(wi) = 1/Navg which take the number of input neurons during practical implementation. https://prateekvjoshi.com/2016/03/29/understanding-xavier-initialization-in-deep-neural-networks/ However, in the following example, there are no neurons. I calculated the variance of W. Does anybody know its variance is determined according to xavier_initializer()? Thanks! $ cat main.py #!/usr/bin/env python # vim: set noexpandtab tabstop=2 shiftwidth=2 softtabstop=-1 fileencoding=utf-8: import tensorflow as tf W = tf.get_variable("W", shape=[5], initializer=tf.contrib.layers.xavier_initializer()) init = tf.global_variables_initializer() import numpy with tf.Session() as sess: sess.run(init) print numpy.var(W.eval()) $ ./main.py 0.166031
score: 0
tagged with: initializer
tagged with: python

http://stackoverflow.com/q/48011901
has title: Python - How to add two model fields in models.py in Django
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48014396
type: Question
accepted answer: http://stackoverflow.com/a/48014396
downvote count: 0
answer count: 1
score: 1
has comment: http://stackoverflow.com/comment/82992447
favorite count: 0
tagged with: python
has body: I have a class in my models.py class Inventory(models.Model): date = models.DateField(("Date"), default=datetime.now) product = models.ForeignKey(Product) stock_in = models.IntegerField() stock_out = models.IntegerField() balance = models.IntegerField() particulars = models.CharField(max_length=250) Now I want to add some stocks in the balance. Using the stock_in values to add certain numbers to the balance of a specific product in the Inventory class. Using an UpdateView to it, so that I can just Update the stock_in field then adding that value to the balance. I'm currently using this, I've tried couple of solution in the internet but to no avail. @property def total(self): return self.stock_in + self.balance
tagged with: django
upvote count: 1

http://stackoverflow.com/a/48307412
has body: Example on documentation is a little bit inaccurate, since it states the example for stored_procedure_parameters as a string. Try setting p as a dictionary: from azure.mgmt.datafactory.models import StoredProcedureParameter p = {'DateToImportFor': StoredProcedureParameter('2017-01-04', type='String')}
answers question: http://stackoverflow.com/q/47984623
score: 0
type: Answer

http://stackoverflow.com/comment/82762150
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47895053
has text: @FlipperPA Now it gives me the error - `No module named 'blog.settings'`

http://stackoverflow.com/comment/82863330
comment on: http://stackoverflow.com/q/47936097
type: QuestionComment
type: Comment
has text: In your database, what data type is *mouse_mgi_id*?
score: 0

http://stackoverflow.com/a/47952709
type: AcceptedAnswer
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47952641
accepted answer of: http://stackoverflow.com/q/47952641
has body: Always prefix sudo before executing any installation related command no matter if it's pip or aptik, it tells the terminal that you have the authority to make this change (installation). For example: sudo apt-get update It's for updating your repository , and so it needs to be authorized to get executed. Also sometimes this error occurs when some other installation is in progress and it has locked the main directory , So you just have to wait for that process or installation to get completed.
score: 1

http://stackoverflow.com/q/47975990
possible better answer: http://stackoverflow.com/a/47976081
has comment: http://stackoverflow.com/comment/82921067
upvote count: 2
answer count: 3
downvote count: 1
has body: So, as far as I am aware, there are two distinct ways of checking whether an integer is 0 in Python. We can either do: if i == 0: ... or if not i: ... The first could be argued to be clearer, but are there any cases where they produce different results or one performs better?
favorite count: 0
has comment: http://stackoverflow.com/comment/82921017
has answer: http://stackoverflow.com/a/47976118
has answer: http://stackoverflow.com/a/47976081
tagged with: python
has answer: http://stackoverflow.com/a/47976273
accepted answer: http://stackoverflow.com/a/47976273
has title: Is there a difference in checking if an integer is equal to 0 or not False
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/82921029
has comment: http://stackoverflow.com/comment/82921086
score: 1
tagged with: evaluation

http://stackoverflow.com/comment/82713841
comment on: http://stackoverflow.com/q/47874052
type: QuestionComment
has text: There's also a misuse of `super` here: as currently structured, the `Vehicle.__init__` method won't get called. You need a common root class (a base class for both `Vehicle` and `Mechanism`), and all subclasses, including `Vehicle` and `Mechanism` should call `super`.
score: 0
type: Comment

http://stackoverflow.com/comment/83005206
comment on: http://stackoverflow.com/q/48001917
score: 0
type: Comment
type: QuestionComment
has text: Thanks @BorrajaX. I have tried to iterate through the records and do a string comparison in the loop. It did work and that was the current approach used in the program. I just wanted to know why the native find() would sometimes return results not matching the conditions, while most of the records are correct.

http://stackoverflow.com/comment/82900559
score: 0
has text: I modified the script now so it reads in the last few lines `cursor.execute("SELECT time, voltage FROM sensortable") mariadb_connection.close() result = cursor.fetchall() for row in result: print result` Terminal prints: `Decimal('2479.00')), (u'13:15', Decimal('3182.00')), (u'13:20', Decimal('3076.00')), (u'13:25', Decimal('2795.00')), (u'13:30', Decimal('3457.00')), (u'13:35', Decimal('2515.00')), (u'13:40', Decimal('3006.00')), (u'13:45', Decimal('3618.00')), (u'13:50', Decimal('3857.00'))] (and more similar data).......)`
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47963868

http://stackoverflow.com/a/47893827
type: Answer
has body: Should be done with font.setPointSize(x) where x = 12 as shown in your code below. See also inline comments. import sys from PyQt5 import QtGui, QtCore, QtWidgets QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True) app = QtWidgets.QApplication([]) window = QtWidgets.QMainWindow() window.setWindowTitle("Hello World") fileMenu = QtWidgets.QMenu("File", window) longMenu = QtWidgets.QMenu("Long Menu Title", window) window.menuBar().addMenu(fileMenu) window.menuBar().addMenu(longMenu) font = window.font() font.setPointSize(12) window.setFont(font) # set font here window.setMinimumSize(QtCore.QSize(400, 200)) # gives flexible window size with minimum size. #window.resize(400, 200) # fixed size: in case you're using fontsize 26 or so ;-) window.show() sys.exit(app.exec_())
has comment: http://stackoverflow.com/comment/82860444
has comment: http://stackoverflow.com/comment/82754209
has comment: http://stackoverflow.com/comment/82857042
answers question: http://stackoverflow.com/q/47889554
has comment: http://stackoverflow.com/comment/82754317
has comment: http://stackoverflow.com/comment/82754279
score: 0
has comment: http://stackoverflow.com/comment/82857117
has comment: http://stackoverflow.com/comment/82757134
has comment: http://stackoverflow.com/comment/82758107

http://stackoverflow.com/q/47968483
has body: i am writing a script that should look for new video releases from a private torrent tracker. So the app is done, but i now need a way to get past the login screen, that has captcha, i have no idea how to do that. Is there a way to use cookies from my own browser to get past login on the site, when i have credentials saved on my browser(firefox)? Edit: I am now trying to bypass the Captcha completely, by using cookies, i have an account to the site im trying to get in, and i read that it should be possible to bypass login and access a site by using cookies. I found an example but i cannot get it to work. Here is the bit im trying to get to work: cookies = {'uid': 'uid_here', 'pass': 'passkey', '__cfduid': 'cfduid'} try: page = requests.get(url, params=params, cookies=cookies).content The cookies info i have copied form my own browser, but i cannot get this to work by myself full bit of code im using as a refrence is here https://github.com/Flexget/Flexget/blob/97bcb6e10f654fbc5a3efa0bc00af6769d73ff69/flexget/plugins/sites/torrentday.py edit2: heres what i have so far, but its not working: def get_torrent(show_list): print('Starting torrent search...') new_eps = show_list file_name = "C:/Users/secret/Desktop/tv_torrents/ " start_url = "https://www.secretsite.com/browse.php?search=" end_url = "&amp;cata=yes" for line in new_eps: # search for *** releases for all series line += ' XAD' s_string = start_url + line + end_url cookies = {'site_cookie': 'ASDDA124fc96fb6776364asdA69c2f5ADAD921514234104'} try: read = requests.get(s_string, cookies=cookies).content soup = BeautifulSoup(read, 'lxml') links = soup.findAll('a') print(soup) torrent_links = ['https://www.secretsite.com/browse.php?search=' + link['href'] for link in links if link['href'].endswith('torrent')] except RequestException as e: raise print('Could not connect to secretsite: %s' % e) else: try: for links in torrent_links: r = request.urlretrieve(links, file_name) print('Success!' + line + ' downloaded') excep…
accepted answer: http://stackoverflow.com/a/48013580
score: 0
has title: How to loging to a website, that has password + captcha
favorite count: 0
upvote count: 1
tagged with: python
tagged with: request
has comment: http://stackoverflow.com/comment/82942548
has answer: http://stackoverflow.com/a/48013580
type: AnsweredQuestion
tagged with: captcha
tagged with: cookies
possible better answer: http://stackoverflow.com/a/47968638
has answer: http://stackoverflow.com/a/47968638
downvote count: 1
type: Question
answer count: 2

http://stackoverflow.com/comment/115515192
comment on: http://stackoverflow.com/a/47930032
score: 0
type: AnswerComment
type: Comment
has text: It should be password and not passwd.

http://stackoverflow.com/q/47916023
has comment: http://stackoverflow.com/comment/82800207
has answer: http://stackoverflow.com/a/47916108
type: Question
has comment: http://stackoverflow.com/comment/82800536
answer count: 2
tagged with: random
has comment: http://stackoverflow.com/comment/82800292
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/82800120
upvote count: 1
has body: I making a fighting game. Its like there are two players. They have 100 hp and they choose attack value btween 0-100 when they're fighting. After they choose value they should have %(100-value) chance of being successful with this attack. For example if they choose value 60, they have %40 chance to be successful with this attack.Can you please help. Sorry for my bad english.
tagged with: python
has comment: http://stackoverflow.com/comment/82800110
favorite count: 0
has comment: http://stackoverflow.com/comment/82800118
downvote count: 5
type: UnansweredQuestion
score: -4
has answer: http://stackoverflow.com/a/47916135
linked to: http://stackoverflow.com/q/3996904
has comment: http://stackoverflow.com/comment/82800478
has comment: http://stackoverflow.com/comment/82800409
has title: How to set a percentage chance to make something

http://stackoverflow.com/comment/82983113
type: Comment
has text: Thanks - your solution works for now! I request one clarification - if M has 5 columns and I want to work on only two of these at a time, can I zip these two columns in any order? Or does the column being searched need to be the first in the data, as it is the key in the dictionary?
comment on: http://stackoverflow.com/a/48003242
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83109608
comment on: http://stackoverflow.com/a/48028861
type: AnswerComment
score: 0
type: Comment
has text: That helped me get the stuff I needed registered - Thanks!!

http://stackoverflow.com/q/47856796
has body: I am trying to get a string into the shell in IDLE. It contains some non-ascii characters that I would like to remove. I can't just paste it into a multi line string, e.g. u'''✔uganda ✔zambia ✔zimbabwe and none of these… ✕afghanistan ✕armenia ✕azerbaijan''' because that would give me the following error: Unsupported characters in input and I can't use string = [raw_]input() because the string is more than one line wide. How can I get the string into the shell?
tagged with: unicode
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47873556
has answer: http://stackoverflow.com/a/47857088
has title: strip multiline string of non ascii chars
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/47856957
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/82678268
tagged with: string

http://stackoverflow.com/q/47916027
favorite count: 0
tagged with: sql-server
answer count: 3
has title: Using a variable in an SQL query
tagged with: python
downvote count: 0
has answer: http://stackoverflow.com/a/47916068
has answer: http://stackoverflow.com/a/47916646
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47916068
score: 1
has answer: http://stackoverflow.com/a/47916075
accepted answer: http://stackoverflow.com/a/47916075
type: Question
has body: NEW VIEWERS NOTE: THIS QUESTION HAS BEEN ANSWERED If I have a long SQL statement in python that references a string multiple times, how can I change the SQL statement so it references a variable equal to the string instead? In the program, the user's input will not be predefined. So when they put their keyword into the textbox and click "search", their input will be stored as a string, as a variable called "userinput". I need to use the variable "userinput" in the SQL command. So far, I can only make the SQL command work if I actually type in the user input into it. I am trialling this in a small separate program: import sqlite3 conn = sqlite3.connect(':memory:') cursor = conn.cursor() cursor.execute("""CREATE TABLE testtable ( label char, format char, catnum char, sidecat char, year char, artist char, relname char, trackname char, composer char, collection int )""") conn.commit() cursor.execute('''INSERT INTO testtable VALUES ("GBI", "LP", "104", "104 (B)", "1974", "The Mustangs", "On Tha Rocks", "Someday We'll Be Together", "Unknown", 1)''') conn.commit() cursor.execute('''INSERT INTO testtable VALUES ("GBI", "Single", "235", "235 (B)", "1978", "Willpower", "Love Makes It Alright", "The Mail", "Eddie Minnis", 1)''') conn.commit() cursor.execute('''INSERT INTO testtable VALUES ("PENN", "LP", "002", "002 (B)", "1972", "Frank Penn", "'72", "The Time For Loving Is Now", "Frank Penn", 1)''') conn.commit() cursor.execute('''INSERT INTO testtable VALUES ("PENN's", "Single", "111", "A-111", "Unknown", "Jay Mitchell", "Nitty Gritty Song", "Nitty Gritty Song", "Jay Mitchell", 0)''') conn.commit() cursor.execute('''INSERT INTO testtable VALUES ("PENN's", "Single", "111", "A-111", "Unknown", "Jay Mitchell", "Nitty Gritty Song", "Unhappy People", "Jay Mitchell", 0)''') conn.commit() cursor.execute('''INSERT INTO testtable VALUES ("PENN's", "Single", "7744-7745", "7744 (A)", "Unknown", "Wendell Stuart", "I Am Who I Am", "I Am Who I Am", "Frank Penn", 1)''') conn.commit() userin…
upvote count: 1

http://stackoverflow.com/comment/82695382
has text: how does the original list look like? Are the values strings? If yes, there are no columns just yet.
comment on: http://stackoverflow.com/q/47865223
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47986840
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/34427530
has comment: http://stackoverflow.com/comment/83016770
has comment: http://stackoverflow.com/comment/83016776
upvote count: 1
tagged with: python
tagged with: quantitative-finance
answer count: 0
has body: I am confused by the results. It seems there are multiple versions of MACD calculation to me. If not, why are they different? print(p_df.head()) c timestamp 2017-04-19 2852.0 2017-04-20 2889.0 2017-04-21 2928.0 2017-04-24 2928.0 2017-04-25 2949.0 p_arr = np.array(p) from pandas_talib import pandas_talib as pdta macd1 = pdta.MACD( p_df, 12, 26, price='c' ) print( macd1.tail( 10 ) ) c MACD_12_26 MACDsign_12_26 MACDdiff_12_26 timestamp 2017-10-17 3738.0 -27.479893 -44.220449 16.740556 2017-10-18 3688.0 -27.154199 -40.807199 13.653000 2017-10-19 3604.0 -33.289945 -39.303748 6.013803 2017-10-20 3776.0 -23.997889 -36.242576 12.244687 2017-10-23 3699.0 -22.586382 -33.511337 10.924955 2017-10-24 3740.0 -17.952636 -30.399597 12.446961 2017-10-25 3705.0 -16.909496 -27.701577 10.792081 2017-10-26 3649.0 -20.366536 -26.234569 5.868032 2017-10-27 3577.0 -28.586273 -26.704910 -1.881363 2017-10-30 3571.0 -35.179075 -28.399743 -6.779332 import talib macd2 = np.vstack( talib.MACD( p_arr, 12, 26, 9 ) ) macd2 = pd.DataFrame( macd2.T, index = p_df.index, columns = ['macd','macdsignal','macdhist'] ) macd2 = p_df.join( macd2 ) print( macd2.tail( 10 ) ) c macd macdsignal macdhist timestamp 2017-10-17 3738.0 -27.384079 -44.076077 16.691997 2017-10-18 3688.0 -27.065785 -40.674018 13.608233 2017-10-19 3604.0 -33.208822 -39.180979 5.972157 2017-10-20 3776.0 -23.922497 -36.129283 12.206786 2017-10-23 3699.0 -22.516715 -33.406769 10.890054 2017-10-24 3740.0 -17.888063 -30.303028 12.414965 2017-10-25 3705.0 -16.849797 -27.612382 10.762585 2017-10-26 3649.0 -20.311556 -26.152217 5.840661 2017-10-27 3577.0 -28.535880 -26.628949 -1.906930 2017-10-30 3571.0 -35.132875 -28.329735 -6.803141 A plot for comparison My TA-Lib is installed from TA_Lib‑0.4.10‑cp36‑cp36m‑win_amd64.whl ( https://www.lfd.uci.edu/~gohlke/pythonlibs/ ). Name: TA-Lib Version: 0.4.10 Summary: Python wrapper for TA-Lib Home-page: http://github.com/mrjbq7/ta-lib Author: John Benediktsson Author-email: mrjbq7@gmail.com License: UNKNO…
has title: Why different results from pandas_talib.MACD() and talib.MACD()?
type: Question
has comment: http://stackoverflow.com/comment/83070703
has comment: http://stackoverflow.com/comment/82986493
tagged with: technical-indicator
has comment: http://stackoverflow.com/comment/82982278
tagged with: ta-lib
tagged with: pandas
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/q/47988417
downvote count: 0
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/82945715
upvote count: 1
has body: I have a couple of (python) scripts running every 15 minutes, about 99% of the time they run without issues but in that 1% of cases it has the following issue: botocore.exceptions.EndpointConnectionError: Could not connect to the endpoint URL: "https://s3-eu-west-1.amazonaws.com/bucketname/path/file.txt" or botocore.exceptions.EndpointConnectionError: Could not connect to the endpoint URL: "https://sts.amazonaws.com/" Multiple checks run at the same time, lets call them check1.1 check1.2 check1.3 check1.4 In the past 30 days, 1.1 has failed 1 time, 1.2 never, 1.3 has failed with the sts error twice, 1.4 has failed twice. The code is in all instances the same, the only difference is that they try to assume different roles. A couple of threads I've read pointed to the config not being correct, but if that was the case why does it only fail this 1%? Just in case this is the file from which it pulls it's profile settings: { "key_id": "MYSECRETKEYID", "key_secret": "MYv3ryS3cur3K3y", "region": "eu-west-1" } These get used in the following code: # open the credential file credfile = open("myfile.json", "r").read() json_obj_cred = json.loads(credfile) awsaccesskeyid = json_obj_cred['key_id'] awssecretaccesskey = json_obj_cred['key_secret'] awsdefaultregion = json_obj_cred['region'] bucket = boto3.resource( 's3', aws_access_key_id=awsaccesskeyid, aws_secret_access_key=awssecretaccesskey, region_name=awsdefaultregion) Do you guys have any idea what this could be or where i should start looking?
tagged with: python
has comment: http://stackoverflow.com/comment/108181253
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/67512784
tagged with: amazon-s3
score: 1
has comment: http://stackoverflow.com/comment/82945590
has title: AWS sporadic "could not connect to endpoint" s3 & sts
type: Question
has comment: http://stackoverflow.com/comment/108236892
answer count: 1

http://stackoverflow.com/comment/82892401
score: 0
type: Comment
has text: so i think i need to change the way i'm redirecting all my print statements to a file.
type: AnswerComment
comment on: http://stackoverflow.com/a/47961432

http://stackoverflow.com/q/48000610
type: Question
tagged with: reduce
score: -1
has comment: http://stackoverflow.com/comment/82970418
has comment: http://stackoverflow.com/comment/82970287
has comment: http://stackoverflow.com/comment/83041478
has answer: http://stackoverflow.com/a/48000898
answer count: 2
tagged with: functional-programming
has body: # Compute the XOR of all numbers from 0 to |A| - 1 and all entries in A # Assume A is a list of integers miss_XOR_dup = functools.reduce(lambda v, i: v ^ i[0] ^ i[1], enumerate(A), 0) I believe that the value the function begins accumulating at is 0 and that v and i are the index of and element value of the items in array A. However, it's a bit confusing that v doesn't stand for "value" but rather "index" and vice versa for i. This also contradicts that the code i[0] is possible because you can't select an index from an integer. If someone could expand the reduce into a for loop or better explain how this code fulfills the comment above it, I would be very appreciative. Thanks!
has comment: http://stackoverflow.com/comment/82969885
favorite count: 0
has comment: http://stackoverflow.com/comment/82969983
tagged with: python
accepted answer: http://stackoverflow.com/a/48000898
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82969871
has title: How does a Python reduce XORing two indices on a lambda variable work?
downvote count: 2
possible better answer: http://stackoverflow.com/a/48000697
upvote count: 1
has answer: http://stackoverflow.com/a/48000697

http://stackoverflow.com/comment/82892565
type: Comment
has text: Thanks Dan! This is better than regex!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47961455

http://stackoverflow.com/comment/83007130
has text: Can you include the entire exception?
type: Comment
comment on: http://stackoverflow.com/q/48011891
type: QuestionComment
score: 0

http://stackoverflow.com/q/47934222
has title: OOP code works fine in Python 3.6 but in Python 2.7 throws max recursion depth runtime error
has comment: http://stackoverflow.com/comment/82837840
accepted answer: http://stackoverflow.com/a/47934233
tagged with: python
type: AnsweredQuestion
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/47934233
tagged with: python-2.7
score: 0
answer count: 1
has body: I am trying to implement the __gt__ method in Python 2.7 in my class but I seemed am receiving a run time error. class FoodProduct: def __init__(self, name, price, weight, vitamins): self.name=name self.price=price self.weight=weight self.vitamins=vitamins def get_vitamins_num(self): count=0 for i in range(len(self.vitamins)): if self.vitamins[i]=="1": count+= 1 return count def __gt__(self,other): if self.price &lt; other.price: return True elif self.price &gt; other.price: return False else: if self.get_vitamins_num &gt; other.get_vitamins_num: return True else: return False My code is not recursive, so I am puzzled by this error. Also, When I tried to run it on Python 3.6 it worked just fine. As I mainly use Python 3, I checked and confirmed the that indeed __gt__ is supposed to work on python 2.7 Could anyone please help and explain what might be the problem, and maybe why it happens only on Python 2.7? Thanks!
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/82921029
score: 0
comment on: http://stackoverflow.com/q/47975990
type: QuestionComment
type: Comment
has text: `if not` checks the `truthy` while `==` tries to match the value, generally speaking, if you just want to check the truthy `if not` or `if i` is faster

http://stackoverflow.com/comment/84302871
type: Comment
type: QuestionComment
has text: Suzanne, I actually figured out the problem not too long ago. I can't post it right now, but I'll reply to this thread with the solution when I can.
comment on: http://stackoverflow.com/q/48000268
score: 0

http://stackoverflow.com/q/47894748
favorite count: 0
type: UnansweredQuestion
upvote count: 1
has body: This code works only when the selected camera has the image plane. So I would like to make it pop up window saying to add image plane first when the camera doesn't have image plane. But how can I check if current selected camera has image plane or not? import maya.cmds as cmds c = cmds.ls(sl=True,dag=True,s=True) cmds.setAttr((c[0] + '.nearClipPlane'), 0.5) cmds.setAttr((c[0] + '.farClipPlane'), 10000000) ip = cmds.listConnections(c[0], type="imagePlane") cmds.setAttr((ip[0] + '.depth'), 80000)
score: 1
type: Question
answer count: 1
downvote count: 0
has title: How can I check if current selected camera has image plane or not?
has answer: http://stackoverflow.com/a/47897188
has comment: http://stackoverflow.com/comment/82756606
tagged with: maya
tagged with: python

http://stackoverflow.com/a/47985114
score: 0
type: Answer
has body: Thanks for the help! Got this as working code: def GetNames(web_data, counter): #get all names from the database connection = create_engine('mysql+pymysql://user:pwd@server:3306/db').connect() result = connection.execute('select * from price_usd') a = 0 sql_matrix = [0 for x in range(counter + 1)] for v in result: while a == 0: for column, value in v.items(): a = a + 1 if a &gt; 1: sql_matrix[a] = str(('{0}'.format(column))) This will get all column names from the existing sql database
answers question: http://stackoverflow.com/q/47962043

http://stackoverflow.com/a/47931427
answers question: http://stackoverflow.com/q/47931066
accepted answer of: http://stackoverflow.com/q/47931066
has body: Had to remove the 'is' in 'if hid is not in values:'. Thanks roganjosh!
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/99449510
score: 0
type: Answer

http://stackoverflow.com/comment/82986938
comment on: http://stackoverflow.com/q/48006780
type: QuestionComment
has text: There's really a `decimal.Decimal` type in pandas? Please post `print(df.dtypes)`.
score: 0
type: Comment

http://stackoverflow.com/a/47970332
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/83029939
answers question: http://stackoverflow.com/q/47970263
has body: To call a function inside a class, you have to first of all create an instance of the class. To do this: unit = Unit() So now you have an instance of the class stored in unit and you can call any of it's properties (including functions) directly from it. So to call the wait function : unit = Unit() unit.wait() Note that you don't have to include self as a parameter because you already created an instance of Unit() in the unit variable As a sidenote if you want to pause the program for three seconds after you change the background to red, then change it back to black, you can use the time module. After importing time you can simply type in: window.fill(red) pygame.display.flip() time.sleep(3) window.fill(black) pygame.display.flip() at whatever part in your code where you want it to pause. After the pause is done you can then change the background back to black. But you will have to call pygame.display.flip() each time you change the background for this to take effect.
has comment: http://stackoverflow.com/comment/82966143

http://stackoverflow.com/comment/82983674
type: QuestionComment
comment on: http://stackoverflow.com/q/48007130
has text: I _think_ that since `struct` does _not_ have to keep the order of fields (similarly to a map) you'd have to access the 2nd item by finding it by type, i.e. `integer`. That could work. Also, you know the schema of the input DataFrame so why don't you find the field name before `explode`?
score: 0
type: Comment

parsing
tags question: http://stackoverflow.com/q/47945145
tags question: http://stackoverflow.com/q/47861773
tags question: http://stackoverflow.com/q/47980715
tags question: http://stackoverflow.com/q/48000143
tag name: parsing
tags question: http://stackoverflow.com/q/47982949
tags question: http://stackoverflow.com/q/47863781
tags question: http://stackoverflow.com/q/47976077
tags question: http://stackoverflow.com/q/47953076
type: Tag
tags question: http://stackoverflow.com/q/47959320
tags question: http://stackoverflow.com/q/47950628
tags question: http://stackoverflow.com/q/47883188
tags question: http://stackoverflow.com/q/47981652
tags question: http://stackoverflow.com/q/47929402
tags question: http://stackoverflow.com/q/48014244
tags question: http://stackoverflow.com/q/48008390

http://stackoverflow.com/a/47997108
has comment: http://stackoverflow.com/comment/82962437
has body: click start in the run box type "cmd.exe" in the terminal type "cd /path/to/my/prog" then type "my_prog.exe" output should be printing to the console .... it should be noted you have not really supplied enough information to actually answer this question, but i think this should work as long as the exe is printing to stdout
has comment: http://stackoverflow.com/comment/82962692
answers question: http://stackoverflow.com/q/47997038
type: Answer
has comment: http://stackoverflow.com/comment/82962727
has comment: http://stackoverflow.com/comment/82962651
score: 0

http://stackoverflow.com/comment/82803307
comment on: http://stackoverflow.com/q/47882038
has text: great thank you. I'm also looking to translate the code to C# to see if it runs faster in this environment.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47914320
has answer: http://stackoverflow.com/a/47916938
downvote count: 0
has comment: http://stackoverflow.com/comment/98781813
possible better answer: http://stackoverflow.com/a/47916938
has body: Functions decorated with numba njit which is an alias to jit(nopython=True) yields different result from numpy on inplace operations (simple @jit(nopython=False) also gives different results from numpy): In [1]: import numpy as np from numba import njit def npfun(arr): arr -= arr[3] @njit def jitfun(arr): arr -= arr[3] arr1 = np.ones((6,2)) arr2 = arr1.copy() npfun(arr1) jitfun(arr2) arr1 == arr2 Out[1]: array([[ True, True], [ True, True], [ True, True], [ True, True], [False, False], [False, False]], dtype=bool) It looks like numpy evaluates rhs and passes it as a copy, while numba treats rhs as a view. Is there any technical reason to do so? numpy 1.13.3 numba 0.35
tagged with: in-place
has title: Why numba and numpy performs differently on inplace operations?
favorite count: 0
linked to: http://stackoverflow.com/q/43151152
has comment: http://stackoverflow.com/comment/82797270
upvote count: 2
tagged with: numba
has answer: http://stackoverflow.com/a/47917013
tagged with: python
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/82799646
type: Question
tagged with: numpy
answer count: 2
accepted answer: http://stackoverflow.com/a/47917013

http://stackoverflow.com/comment/82842875
score: 1
type: Comment
type: QuestionComment
has text: Have you tried inserting [`distinct()`](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#distinct) into your query?
comment on: http://stackoverflow.com/q/47936215

http://stackoverflow.com/comment/82800265
type: QuestionComment
score: 0
has text: Could you please explain which lines need to be removed in another way, perhaps an example would work well?
comment on: http://stackoverflow.com/q/47916095
type: Comment

http://stackoverflow.com/q/48000228
type: Question
has answer: http://stackoverflow.com/a/48000351
has comment: http://stackoverflow.com/comment/82971390
has comment: http://stackoverflow.com/comment/83007254
tagged with: post
score: 0
has comment: http://stackoverflow.com/comment/82980759
answer count: 1
has title: Python Post request with REQUESTS/ Shiftplanning API
has body: I am trying to call the shiftplanning API with the following code: import requests url= "https://humanity.com/api/" payload = {"key": "keyvalue", "request": { "module": "staff.login", "method": "GET","username": "myusername", "password": "mypassword"}}" headers = { 'content-type': "application/x-www-form-urlencoded", 'cache-control': "no-cache", } r = requests.post(url, data = payload , headers= headers) r.text I used Postman to test the api beforehand and it worked fine. The payload in the Postman code creator, however, looks like this: payload = "data={\r\n \"key\": \"keyvalue\",\r\n \"request\": {\r\n \"module\": \"staff.login\",\r\n \"method\": \"GET\",\r\n \"username\": \"myusername\",\r\n \"password\": \mypassword\"\r\n }\r\n}" I assume, that the payload variable actually needs to be formatted as a string, as the doc at shiftplanning api says: Remember that any data passed to the API is to be formatted as JSON, and its string value needs to be sent via the POST HTTP request method all as the post variable 'data' (Checkout the 9th line from an example below). Also Content-Type needs to be set to application/x-www-form-urlencoded. However, no matter what I do, I always get the html of the api as a return, not the json response to my http request. Using r.json() doesn't do anything, except raising an error, due to the returned html. I also tried using json = payload in the post request, that didn't change anything either.` Any help and explanation is appreciated. I'd really like to understand what I am doing wrong, as it seems to be pretty straightforward to execute.
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82971408
tagged with: python-requests

http://stackoverflow.com/comment/82886674
type: QuestionComment
has text: @coldspeed it is a binary number in a tuple such as 1001 looks like (1,0,0,1)
score: 0
comment on: http://stackoverflow.com/q/47958651
type: Comment

http://stackoverflow.com/q/47979670
answer count: 1
score: -1
tagged with: cassandra-python-driver
has title: How to use prepared statement on materialized view in python Cassandra driver?
has comment: http://stackoverflow.com/comment/82928099
favorite count: 0
has answer: http://stackoverflow.com/a/48093191
type: UnansweredQuestion
tagged with: scylla
downvote count: 2
has body: i am using Scylla Database and python Cassandra driver for my project, i used prepared statement on every query and it works, but when i use prepared statement on materialized view, it returns me nothing, can you please help me, is there any restriction or something else? here is my schema CREATE TABLE channelfollowers( channelid bigint, userid bigint, isfavorite boolean, isBlocked boolean, followDate bigint, PRIMARY KEY(userid,channelid,followDate)); CREATE MATERIALIZED VIEW favoriteChannels AS SELECT channelid, userid, isfavorite FROM channels.channelfollowers WHERE channelid IS NOT NULL and userid IS NOT NULL and isfavorite IS NOT NULL PRIMARY KEY (isfavorite,userid,channelid,followDate);
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82945017
has comment: http://stackoverflow.com/comment/82927971
type: Question
has comment: http://stackoverflow.com/comment/82928125

http://stackoverflow.com/a/47908102
has comment: http://stackoverflow.com/comment/82784433
type: Answer
has comment: http://stackoverflow.com/comment/82784156
has comment: http://stackoverflow.com/comment/82783778
has comment: http://stackoverflow.com/comment/82783734
has comment: http://stackoverflow.com/comment/82783830
answers question: http://stackoverflow.com/q/47908050
has body: float(df.loc[0][2].replace(',',''))
has comment: http://stackoverflow.com/comment/82784003
score: 0
has comment: http://stackoverflow.com/comment/82784092

http://stackoverflow.com/comment/82841946
has text: what is the status of your **Allow less secure apps.** in your gmail setting?
type: Comment
comment on: http://stackoverflow.com/a/47884028
score: 0
type: AnswerComment

http://stackoverflow.com/q/47866437
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/3025162
upvote count: 1
downvote count: 1
type: Question
tagged with: combinations
has answer: http://stackoverflow.com/a/47866548
duplicate of: http://stackoverflow.com/q/3025162
score: 0
answer count: 1
favorite count: 0
has title: simulate binominal coefficent (nCr) in python
tagged with: python
tagged with: simulation
has comment: http://stackoverflow.com/comment/82698132
has body: Out of curiosity, I was wondering if there's a way to solve a binominal coefficient by simulation in python. I tried a little bit, but the numbers are getting so big so quickly that I wasn't able to solve it for anything but really small numbers. I'm aware of this question but wasn't able to identify one solution that uses only brute force to solve the coefficient. But I have to admit that I don't understand all the implementations listed there. Here's my naive approach: import random import numpy as np from math import factorial as fac # Calculating the reference with help of factorials def comb(n,k): return fac(n) // fac(k) // fac(n-k) # trying a simple simulation with help of random.sample random.seed(42) n,k = 30,3 n_sim = 100000 samples = np.empty([n_sim,k], dtype=int) for i in range(n_sim): x = random.sample(range(n),k) samples[i] = sorted(x) u = np.unique(samples, axis=0) print(len(u)) print(comb(n,k)) Would it be possible to do this efficiently and fast for big numbers?

macos
tags question: http://stackoverflow.com/q/47997164
tags question: http://stackoverflow.com/q/48001202
tags question: http://stackoverflow.com/q/47931597
tags question: http://stackoverflow.com/q/47897823
tags question: http://stackoverflow.com/q/47856289
tags question: http://stackoverflow.com/q/47875799
tags question: http://stackoverflow.com/q/47970758
tags question: http://stackoverflow.com/q/47906801
tags question: http://stackoverflow.com/q/47971414
tags question: http://stackoverflow.com/q/47910189
tags question: http://stackoverflow.com/q/48010233
tags question: http://stackoverflow.com/q/47979645
tags question: http://stackoverflow.com/q/47916318
tags question: http://stackoverflow.com/q/47992358
tags question: http://stackoverflow.com/q/47937133
tags question: http://stackoverflow.com/q/47946008
tags question: http://stackoverflow.com/q/47986565
tags question: http://stackoverflow.com/q/47974626
tags question: http://stackoverflow.com/q/47869598
tags question: http://stackoverflow.com/q/47945481
tags question: http://stackoverflow.com/q/47874461
tags question: http://stackoverflow.com/q/47987425
tags question: http://stackoverflow.com/q/47894191
type: Tag
tags question: http://stackoverflow.com/q/48014443
tags question: http://stackoverflow.com/q/47897270
tags question: http://stackoverflow.com/q/47856004
tags question: http://stackoverflow.com/q/47872743
tags question: http://stackoverflow.com/q/47998318
tags question: http://stackoverflow.com/q/47932607
tags question: http://stackoverflow.com/q/47879805
tag name: macos
tags question: http://stackoverflow.com/q/47892964
tags question: http://stackoverflow.com/q/47979158
tags question: http://stackoverflow.com/q/47973401

http://stackoverflow.com/comment/82860105
score: 1
has text: Resolved: I corrected my virtualenv to point to tensorflow.
comment on: http://stackoverflow.com/q/47945077
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47878725
score: 8
has comment: http://stackoverflow.com/comment/82735099
has comment: http://stackoverflow.com/comment/82741790
answers question: http://stackoverflow.com/q/47878009
has comment: http://stackoverflow.com/comment/82741983
has comment: http://stackoverflow.com/comment/82742599
has body: As workaround we can repaint the whole plot to Output widget and then display it without flickering. %matplotlib inline from matplotlib.pyplot import * button = ipywidgets.Button(description="Button") out = ipywidgets.Output() def on_button_clicked(b): with out: clear_output(True) plot([1,2],[2,1]) show() button.on_click(on_button_clicked) display(button) with out: plot([1,2],[1,2]) show() out
downvote count: 0
upvote count: 8
type: Answer

http://stackoverflow.com/a/47895403
answers question: http://stackoverflow.com/q/47893421
type: Answer
has body: You can use tf.expand_dims() to convert the smaller tensor to the correct rank, followed by tf.concat(): tensor_3d = tf.placeholder(tf.float32, shape=[2, 2, 3]) tensor_2d = tf.placeholder(tf.float32, shape=[2, 2]) tensor_2d_as_3d = tf.expand_dims(tensor_2d, 2) # shape: [2, 2, 1] result = tf.concat([tensor_3d, tensor_2d_as_3d], 2) # shape: [2, 2, 4]
upvote count: 7
accepted answer of: http://stackoverflow.com/q/47893421
type: AcceptedAnswer
downvote count: 0
score: 7

http://stackoverflow.com/comment/82900824
comment on: http://stackoverflow.com/q/47965473
type: Comment
type: QuestionComment
has text: I think I just solved it myself changed settings/staging.py to include ` 'loggers': { 'django': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), }, 'accounts': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), }, },`
score: 1

http://stackoverflow.com/q/47945162
favorite count: 0
has title: Instantiate class dynamically with locate
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/66857498
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
tagged with: reflection
type: Question
has body: I am trying to instantiate a class dynamically from a string that is fed to a method. from pydoc import locate name = "folder.subfolder.classname" my_class = locate(name) instance = my_class() Doing this results in an error: TypeError: 'module' object is not callable My question is: how can I dinamically know which class I need to call? If I hardcode the value and do my_class.classname() I can instantiate it, but I want that last part to be dynamic, instead of hardcoded. How can I do that?
has answer: http://stackoverflow.com/a/47945283
has answer: http://stackoverflow.com/a/66857498
accepted answer: http://stackoverflow.com/a/47945283
upvote count: 2
answer count: 2

http://stackoverflow.com/q/47922290
type: UnansweredQuestion
tagged with: python
has title: Add new rows to an existing dataframe/series
type: Question
tagged with: time-series
score: 0
tagged with: arima
answer count: 1
has answer: http://stackoverflow.com/a/47922470
has body: My last 4 records of my dataset looks like this: date Outbound 11/26/2017 21:00 175.5846438 11/26/2017 22:00 181.1182961 11/26/2017 23:00 112.011672 11/27/2017 00:00 43.99501014 I have done my Out of Sample forecasting, and have predicted next 7 outputs i.e. for 27th November 01:00, 02:00 and so on.. My forecast is in form of a list like this: [100, 120, 130....] How do i add the forecast along with the date to my dataframe or the series, as i need to plot the data..

http://stackoverflow.com/comment/82887725
score: 0
type: Comment
type: QuestionComment
has text: Also, the Linux may have had tcltk already but it was not something I could access. I am not sure the inner workings of my server. I am a novice. I apologize I am unsure.
comment on: http://stackoverflow.com/q/47959076

http://stackoverflow.com/q/47928608
tagged with: python-3.x
upvote count: 8
tagged with: python
has answer: http://stackoverflow.com/a/47933205
possible better answer: http://stackoverflow.com/a/66967177
accepted answer: http://stackoverflow.com/a/47933205
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82835253
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/66967177
has body: I am trying to parse the first page of google search results. Specifically, the Title and the small Summary that is provided. Here is what I have so far: from urllib.request import urlretrieve import urllib.parse from urllib.parse import urlencode, urlparse, parse_qs import webbrowser from bs4 import BeautifulSoup import requests address = 'https://google.com/#q=' # Default Google search address start file = open( "OCR.txt", "rt" ) # Open text document that contains the question word = file.read() file.close() myList = [item for item in word.split('\n')] newString = ' '.join(myList) # The question is on multiple lines so this joins them together with proper spacing print(newString) qstr = urllib.parse.quote_plus(newString) # Encode the string newWord = address + qstr # Combine the base and the encoded query print(newWord) source = requests.get(newWord) soup = BeautifulSoup(source.text, 'lxml') The part I am stuck on now is going down the HTML path to parse the specific data that I want. Everything I have tried so far has just thrown an error saying that it has no attribute or it just gives back "[]". I am new to Python and BeautifulSoup so I am not sure the syntax of how to get to where I want. I have found that these are the individual search results in the page: https://ibb.co/jfRakR Any help on what to add to parse the Title and Summary of each search result would be MASSIVELY appreciated. Thank you!
has title: How to use BeautifulSoup to parse google search results in Python
tagged with: lxml
has comment: http://stackoverflow.com/comment/82829482
downvote count: 0
score: 8
favorite count: 0
tagged with: beautifulsoup

http://stackoverflow.com/q/48004171
has body: I made a column by concatenating integers and converting into string format. Later I am converting the string column into datetime, everything is working just fine except an additional day field is added to the new datetime column. Here is what I mean to say. I am making a column of type string like this, '1-1992' where 1 reflects month and 1992 reflects year But, when I am converting the column with "Month-Year" to datetime format,an additional "Day" field is getting added to the new column, here is what it looks like. "1992-01-01" (last 01 is added to all the values,which i don't want, I only want month and year keeping datetime format - with me). How can I get rid of the last 01 which is present in all the rows, keeping the format to datetime ? Thank you.
type: Question
tagged with: datetime
tagged with: python
has answer: http://stackoverflow.com/a/48004326
score: 0
tagged with: machine-learning
answer count: 1
type: UnansweredQuestion
tagged with: pandas
has title: Pandas- Unnecessay values included while converting a column into datetime format

http://stackoverflow.com/comment/82958078
comment on: http://stackoverflow.com/q/47994872
type: QuestionComment
type: Comment
has text: There's a bug in your program, you're trying to look up '.--...-' in your dictionary but your dictionary has just individual letters, not the whole message. You haven't shown us how you called your functions, so it's a little difficult to help any further without more information.
score: 1

http://stackoverflow.com/a/47981257
type: Answer
answers question: http://stackoverflow.com/q/47980938
downvote count: 0
score: 1
has body: You can only jit-compile classes with numba data types as attributes. For example this works: from numba import jitclass, float64 axisspec = [('x', float64), ('y', float64)] @jitclass(axisspec) class Axis(object): def __init__(self, x, y): self.x = x self.y = y Numba is good for number crunching, not working with general Python objects. Your case looks more like an application of PyPy.
upvote count: 1

http://stackoverflow.com/comment/82865733
has text: What do you mean with : ''you need to give them to specify an initial-value-problem?(my english is not the best, sorry) How can i define the condition in point t_0 ? Or is it this point t_0 defined as 0 (first value) in interval [t_0,t_1] ? (if it is so, why do i get a wrong solution?)
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47944083

http://stackoverflow.com/comment/83297128
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48005933
has text: The focal length is usually given in pixels. To rotate the 3D points you just pick their coordinates as (x,y,f), and apply a 3D rotation matrix, then reproject them at f*(x'/z', y'/z'). You can easily find references about 3D rotations not to mention the pinhole model on the web. To guess the f you should really just experiment with this until you're satisfied with the result. The angles of the parallel horizontal lines in that image can also probably guide you. I really can't tell what else you might like to know, if this isn't enough you should just do a proper camera calibration.
type: Comment

http://stackoverflow.com/q/47897491
type: Question
upvote count: 4
tagged with: numpy
has answer: http://stackoverflow.com/a/47897649
downvote count: 0
has answer: http://stackoverflow.com/a/47897658
score: 4
has answer: http://stackoverflow.com/a/47897918
possible better answer: http://stackoverflow.com/a/47897649
tagged with: pandas
has body: Is it possible to covert a df into a matrix like the following? Given df: Name Value x 5 x 2 x 3 x 3 y 3 y 2 z 4 The matrix would be: Name 1 2 3 4 5 x 4 4 3 1 1 y 2 2 1 0 0 z 1 1 1 1 0 Here's the logic behind it: Name 1 2 3 4 5 (5 columns since 5 is the max in Value) -------------------------------------------------------------------- x 4 (since x has 4 values &gt;= 1) 4 (since x has 4 values &gt;= 2) 3 (since x has 3 values &gt;= 3) 1 (since x has 1 values &gt;= 4) 1 (since 1 x &gt;= 5) y 2 (since y has 2 values &gt;= 1) 2 (since y has 2 values &gt;= 2) 1 (since y has 1 values &gt;= 3) 0 (since no more y &gt;= 5) 0 (since no more y &gt;= 5) z 1 (since z has 1 values &gt;= 1) 1 (since z has 1 values &gt;= 2) 1 (since z has 1 values &gt;= 3) 1 (since z has 1 values &gt;= 4) 0 (since no more z &gt;= 5) Let me know if this makes sense. I know I have to use sort, group, and count but couldn't figure out how to set up the matrix. Thank you!!!
favorite count: 0
answer count: 5
has title: Pandas converting df into matrix by conditions
has answer: http://stackoverflow.com/a/47898755
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47898755
has answer: http://stackoverflow.com/a/47897651
tagged with: dataframe
linked to: http://stackoverflow.com/q/45255236

http://stackoverflow.com/a/63131845
answers question: http://stackoverflow.com/q/47893324
has body: you should use empty_label parameter in form.ModelChoiceField() title = forms.ModelChoiceField(queryset=.... , empty_label="YOUR_DEFAULT_TITLE")
score: 0
type: Answer

http://stackoverflow.com/q/47919869
tagged with: matrix-indexing
linked to: http://stackoverflow.com/q/41233678
has answer: http://stackoverflow.com/a/47919998
has answer: http://stackoverflow.com/a/47920436
tagged with: python
has title: Is there a canonical way of obtaining a 0D numpy subarray?
favorite count: 0
type: AnsweredQuestion
score: 3
has body: Given a numpy ndarray and an index: a = np.random.randint(0,4,(2,3,4)) idx = (1,1,1) is there a clean way of retrieving the 0D subarray of a at idx? Something equivalent to a[idx + (None,)].squeeze() but less hackish? Note that @filippo's clever a[idx][...] is not equivalent. First, it doesn't work for object arrays. But more seriously it does not return a subarray but a new array: b = a[idx][...] b[()] = 7 a[idx] == 7 # False
possible better answer: http://stackoverflow.com/a/47919998
upvote count: 3
type: Question
tagged with: numpy
answer count: 2
accepted answer: http://stackoverflow.com/a/47920436
tagged with: arrays
downvote count: 0

http://stackoverflow.com/comment/82749200
score: 0
has text: Are there any `iframes` in page source, if it logs in successfully?
comment on: http://stackoverflow.com/q/47891264
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47873968
answers question: http://stackoverflow.com/q/47873828
score: 1
downvote count: 0
has body: This functionality will be removed from Python, as per Jim's answer. The distro package seems to be the recommended alternative: $ pip3 install --user distro $ python3 Python 3.6.3 (default, Oct 9 2017, 12:07:10) [GCC 7.2.1 20170915 (Red Hat 7.2.1-2)] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import distro &gt;&gt;&gt; distro.linux_distribution() ('Fedora', '27', 'Twenty Seven')
type: Answer
upvote count: 1

http://stackoverflow.com/comment/82991035
score: 0
type: Comment
has text: Can I use `ranks[product] = ranks.get(product,{})` instead of `if product not in ranks: ranks[product] = {}`?
type: AnswerComment
comment on: http://stackoverflow.com/a/48011191

http://stackoverflow.com/q/47963080
upvote count: 1
type: Question
has title: python xml iterating over elements takes a lot of memory
has comment: http://stackoverflow.com/comment/82895691
has comment: http://stackoverflow.com/comment/82895528
has comment: http://stackoverflow.com/comment/82895778
has comment: http://stackoverflow.com/comment/82895452
downvote count: 0
answer count: 1
score: 1
has comment: http://stackoverflow.com/comment/82895611
favorite count: 0
linked to: http://stackoverflow.com/q/9856163
has body: I have some very big XML files (around ~100-150 MB each). One element in my XML is M (for member), which is a child of HH (household) - i.e. - each household contains one or more members. What I need to do is to take all the members that satisfies some conditions (the conditions can change, and can be both on the household and on the members - e.g. - just members from households with high income (constraint on the household), who's age is between 18-49 (constraint on the member)) - and to further process them in a rather complicated function. this is what I'm doing: import lxml.etree as ET all_members=[] tree=ET.parse(whole_path) root=tree.getroot() HH_str='//H' #get all the households HH=tree.xpath(HH_str) for H in HH: '''check if the hh satisfies the condition''' if(is_valid_hh(H)): M_str='.//M' M=H.xpath(M_str) for m in M: if(is_valid_member(m)): all_members.append(m) for member in all_members: '''do something complicated''' the problem with this is that it takes all my memory (and I have 32 GB)! how can I iterate over xml elements more efficiently? any help will be appreciated...
type: UnansweredQuestion
tagged with: python
tagged with: generator
tagged with: http://stackoverflow.com/tag/xml
tagged with: xpath
has comment: http://stackoverflow.com/comment/82895809
tagged with: list
has answer: http://stackoverflow.com/a/47964140

http://stackoverflow.com/comment/82988083
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48009830
has text: You are not using statements here, but a trinary operator.
score: 0

google-cloud-ml
tags question: http://stackoverflow.com/q/47957240
tags question: http://stackoverflow.com/q/47979698
type: Tag
tags question: http://stackoverflow.com/q/47885698
tags question: http://stackoverflow.com/q/47942693
tag name: google-cloud-ml
tags question: http://stackoverflow.com/q/47958845
tags question: http://stackoverflow.com/q/47856852
tags question: http://stackoverflow.com/q/48003394

http://stackoverflow.com/a/48410929
answers question: http://stackoverflow.com/q/47856195
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47856195
type: Answer
score: 4
upvote count: 4
has body: They are not separate instances. You can see this: In Tree View, the start/end dates and duration of both circles will be exactly the same. In Gantt view, you will see the duration for only a single instance of print_date. In general, you can't map a DAG to a tree view without duplicating nodes like they've done.

http://stackoverflow.com/a/47986441
accepted answer of: http://stackoverflow.com/q/47985917
answers question: http://stackoverflow.com/q/47985917
score: 1
has comment: http://stackoverflow.com/comment/82945824
has comment: http://stackoverflow.com/comment/82945549
has comment: http://stackoverflow.com/comment/82946190
type: AcceptedAnswer
downvote count: 0
has body: You can get the absolute path of the script you are executing with (there are other variants also using __file__, but this should work) import os wk_dir = os.path.dirname(os.path.realpath('__file__')) print( wk_dir ) and then get your dir with it, e.g. import sys sys.path.append(wk_dir+'/../utils') PS: You might need to use __file__ instead of '__file__'.
type: Answer
upvote count: 1

session-cookies
tags question: http://stackoverflow.com/q/47869039
tag name: session-cookies
type: Tag

http://stackoverflow.com/comment/82811743
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47921244
type: QuestionComment
has text: Also `sox` is a tool that can do such things out of the box.

http://stackoverflow.com/comment/82746839
comment on: http://stackoverflow.com/q/47889297
score: 0
type: Comment
type: QuestionComment
has text: How did you configure your Apache server?

http://stackoverflow.com/q/47949871
tagged with: dataframe
has answer: http://stackoverflow.com/a/47949888
answer count: 3
tagged with: pandas
has body: This question is an additional question of my previous question that I posted. What I would like to do is to replace DataFrame's string value to its first initial string. For example, s = pd.DataFrame({'A':['S12','S1','E53',np.NaN], 'B':[1,2,3,4]}) s.A.fillna('P', inplace=True) This will give me a Dataframe A B 0 S12 1 1 S1 2 2 E53 3 3 P 4 But then, I would like to change the string values of column 'A' to ['S', 'S', 'E', 'P'], which is their first character. What I did is following, for i, row in s.iterrows(): if len(row['A']) &gt; 1: s['A'][i] = row['A'][0] and I got this warning. /anaconda/lib/python2.7/site-packages/ipykernel/__main__.py:3: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: http://pandas.pydata.org/pandas- docs/stable/indexing.html#indexing-view-versus-copy app.launch_new_instance() /anaconda/lib/python2.7/site-packages/ipykernel/__main__.py:7: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy I understand that this is a non-preferred way, but what exactly I am doing inefficiently and what would be the preferred way? Is it possible to do it without converting them to numpy array? Thank you!
has answer: http://stackoverflow.com/a/47951438
downvote count: 0
favorite count: 0
has title: Accessing each entries of DataFrame and replacing them in a better way?
upvote count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47951438
score: 1
type: Question
has answer: http://stackoverflow.com/a/47955453
possible better answer: http://stackoverflow.com/a/47949888

http://stackoverflow.com/comment/82853593
has text: Got it but how can I reopen the process.stdin without the need for instantiating another Popen(). Is this possible ? because I need to keep communicating without closing the process.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47941728

http://stackoverflow.com/comment/82803479
type: QuestionComment
score: 0
type: Comment
has text: Thanks, i install it successfully.
comment on: http://stackoverflow.com/q/47917517

http://stackoverflow.com/a/47861842
score: 1
has comment: http://stackoverflow.com/comment/82761320
has body: We can using groupby after sort_values df.SALE_DATE=pd.to_datetime(df.SALE_DATE,format='%d/%m/%y') df=df.sort_values(['PRODUCT_ID','SALE_DATE','SALE_PRICE']) df1=df.copy() df1=df.copy().sort_index() df1['SALE_GROUP_ID']=df.groupby([df['PRODUCT_ID'],(df['SALE_DATE'].diff().abs()/np.timedelta64(1, 'M')).lt(1).ne(1).cumsum(),df['SALE_PRICE'].diff().lt(10).ne(1).cumsum()]).ngroup().add(1).sort_index().values df1 Out[294]: PRODUCT_ID SALE_DATE SALE_PRICE PROVIDER SALE_GROUP_ID 0 1 2016-02-01 25 1 1 1 1 2016-10-02 60 1 2 2 1 2016-11-01 63 2 2 3 1 2016-10-09 65 3 2 4 2 2015-11-11 54 1 3 5 2 2016-01-13 34 2 4 6 3 2014-05-19 45 1 5 7 3 2015-10-15 38 1 6 8 3 2014-06-16 53 2 5 9 3 2015-10-18 58 2 7 More info: you require 3 condition when get the group , 1. PRODUCT_ID 2. Date different within in 1 month 3. SALE_PRICE different less than 10 (df['SALE_DATE'].diff().abs()/np.timedelta64(1, 'M')).lt(1).ne(1).cumsum(), is to getthing the group of date within one month (df['SALE_DATE'].diff().abs()/np.timedelta64(1, 'M')).lt(1).ne(1).cumsum() Out[274]: 0 1 1 2 3 2 2 2 4 3 5 4 6 5 8 5 7 6 9 6 Name: SALE_DATE, dtype: int32 df['SALE_PRICE'].diff().lt(10).ne(1).cumsum() is to get the value within 10 df['SALE_PRICE'].diff().lt(10).ne(1).cumsum() Out[275]: 0 1 1 2 3 2 2 2 4 2 5 2 6 3 8 3 7 3 9 4 Name: SALE_PRICE, dtype: int32 After the groupby we just combine (getting the intersection of each group condition), then we using ngroup to get the group Id
accepted answer of: http://stackoverflow.com/q/47861189
answers question: http://stackoverflow.com/q/47861189
has comment: http://stackoverflow.com/comment/82759991
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/82760206
has comment: http://stackoverflow.com/comment/82762555

http://stackoverflow.com/q/48003731
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48004204
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/48004204
has body: I have the following 2 dataframes: df1: col1 col2 col3 a d 1 a d 2 b e 3 b e 4 c f 5 c f 6 df2: col4 col5 col6 g d 1 g b 2 h c 3 h f 4 i a 5 i b 6 I want to merge the two dataframes by comparing values in col5 of df2 with col2 of df1 and only retain the matching values. So the merged dataframe would look like this: df3: col1 col2 col3 col4 col5 col6 a d 1 NaN NaN NaN a d 2 NaN NaN NaN NaN NaN NaN g d 1 c f 5 NaN NaN NaN c f 6 NaN NaN NaN NaN NaN NaN h f 4 I realize I can merge but it combines the rows, but I'd like to keep the rows separate.
has title: Pandas conditionally merge dataframes
score: 0
tagged with: pandas

http://stackoverflow.com/comment/82790053
comment on: http://stackoverflow.com/q/47911093
has text: Did you look at the [docs](https://keras.io/layers/convolutional/#conv2d)?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82852568
score: 0
has text: After that its a simple matter of assigning the newly generated `dict` to the old one, or you can use `update()`. The heavy work is done.
comment on: http://stackoverflow.com/a/47941455
type: AnswerComment
type: Comment

http://stackoverflow.com/a/47992555
has body: I got it working! # adding missing entities to mysql database connection = create_engine('mysql+pymysql://user:pwd@server:3306/db').connect() for j in range(1, counter + 1): if missing_matrix[j] != 0: query1 = ("ALTER TABLE price_usd ADD IF NOT EXISTS %s DOUBLE ") %(missing_matrix[j]) connection.execute(query1) Connection.close The problem I had was that my column names had spaces in their names. I wrote another function that replaces these spaces with a _ then it worked perfectly.
has comment: http://stackoverflow.com/comment/83018006
has comment: http://stackoverflow.com/comment/82953743
type: Answer
answers question: http://stackoverflow.com/q/47985066
score: 0

http://stackoverflow.com/comment/82892744
has text: Python 2.7.14. I am using MacOS and it works perfect under `/Users/myusername/` directory. However, if I try to run under `/Users/myusername/Desktop/`, it gives error. I try to install boto3 globally by `sudo pip install boto3` and also install boto3 user wise by `pip install boto3 --user`. Both has same issue.
comment on: http://stackoverflow.com/a/47946618
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47896283
answer count: 3
has title: How to have inherited type hints in python?
tagged with: python-typing
has answer: http://stackoverflow.com/a/47896478
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82759633
score: 16
tagged with: python
has answer: http://stackoverflow.com/a/55251337
upvote count: 16
has answer: http://stackoverflow.com/a/62357745
has body: So my problem is That when I have a class of type A that does things and I use those functions as a subclass(B) they are still typed for class A and do not accept my class B object as arguments or as function signature. My problem simplified: from typing import TypeVar, Generic, Callable T = TypeVar('T') class Signal(Generic[T]): def connect(self, connector: Callable[[T], None]) -> None: pass def emit(self, payload: T): pass class A: def __init__(self) -> None: self.signal = Signal[A]() def do(self) -> None: self.signal.emit(self) def handle_b(b: "B") -> None: print(b.something) class B(A): def __init__(self) -> None: super().__init__() self.signal.connect(handle_b) @property def something(self) -> int: return 42 I can provide the complete signal class as well but that just distracts from the problem. This leaves me with one error in mypy: error: Argument 1 to "connect" of "Signal" has incompatible type Callable[[B], None]; expected Callable[[A], None] Since the signal handling is implemented in A the subclass B can't expect B type objects to be returned even though it clearly should be fine...
type: Question
has comment: http://stackoverflow.com/comment/82759660
tagged with: mypy
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/82924676
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47977953
has text: The error indicates that one of your `f2.read(1)` calls returned an empty string; that happens when you have reached the end of the file.
score: 0

http://stackoverflow.com/a/47886254
has comment: http://stackoverflow.com/comment/110610093
type: Answer
score: 19
downvote count: 0
has comment: http://stackoverflow.com/comment/93591722
has comment: http://stackoverflow.com/comment/94254082
has body: No need to bring in separate shell and python scripts, a single file can be both! Replace your shebang line with this sequence: #!/bin/sh # Shell commands follow # Next line is bilingual: it starts a comment in Python, and is a no-op in shell """:" # Find a suitable python interpreter (adapt for your specific needs) for cmd in python3.5 python3 /opt/myspecialpython/bin/python3.5.99 ; do command -v &gt; /dev/null $cmd &amp;&amp; exec $cmd $0 "$@" done echo "OMG Python not found, exiting!!!!!11!!eleven" &gt;2 exit 2 ":""" # Previous line is bilingual: it ends a comment in Python, and is a no-op in shell # Shell commands end here # Python script follows (example commands shown) import sys print ("running Python!") print (sys.argv)
has comment: http://stackoverflow.com/comment/82745740
upvote count: 19
accepted answer of: http://stackoverflow.com/q/47882916
answers question: http://stackoverflow.com/q/47882916
type: AcceptedAnswer

http://stackoverflow.com/q/47940236
has comment: http://stackoverflow.com/comment/82849704
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/82849701
tagged with: http://stackoverflow.com/tag/json
type: Question
accepted answer: http://stackoverflow.com/a/47940338
has comment: http://stackoverflow.com/comment/82849658
has comment: http://stackoverflow.com/comment/82849793
has answer: http://stackoverflow.com/a/47940338
score: 0
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
has body: I'm collecting weather data and trying to create a list that has the latest (temperature) value by minute. I want to add them to a list, and if the list does not contains the "minute index" it should at it as a new element in the list. So the list always keeps the latest temperature value per minute: def AddValue(arr, value): timestamp = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M") for v in arr['values']: try: e = v[timestamp] # will trigger the try/catch if not there v[timestamp] = value except KeyError: v.append({ timestamp: value }) history = [ { 'values': [ {'2017-12-22 10:20': 1}, {'2017-12-22 10:21': 2}, {'2017-12-22 10:22': 3} ] }, ] AddValue(history, 99) However, I'm getting AttributeError: 'dict' object has no attribute 'append'**
has title: Append values to a list of json objects
tagged with: python

http://stackoverflow.com/comment/82994465
has text: When i changed to dataframe and intend to saw the dtype i get the following error **ValueError: failed to cast to 'float64' (Exception was: setting an array element with a sequence.)**
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48012711

http://stackoverflow.com/q/47967299
answer count: 1
has title: How to bring xlwings excel file foreground using Python
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
score: 2
tagged with: xlwings
has answer: http://stackoverflow.com/a/47969038
upvote count: 2
tagged with: excel
type: Question
has body: I am using xlwings to modify an excel file in Python 3.6. xlwings opens the excel instance and runs my python script, as a results the Excel file would go to the background of my pycharm window. Is there any straightforward way to bring the excel file to the foreground at the end of the program? My code is similar to this: import xlwings as xw wb = xw.Book('Excel.xlsx') sheet_ranges = wb.sheets['Sheet1'] def updatingExcel(input): value = 'Hello World' sheet_ranges.range('H' + str(i + 3)).value = value return value print(updatingExcel(anyinput) I understand that if I run the.py file outside pycharm this issue most probably won't occur as the screen terminates itself. However I would appreciate your input.

http://stackoverflow.com/q/47869723
tagged with: ssl
upvote count: 13
tagged with: root-certificate
tagged with: certifi
has title: how do I update root certificates of certifi?
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47869879
tagged with: python
accepted answer: http://stackoverflow.com/a/47869879
has body: I am using certifi python module to verify ssl connections. I looked at the root certificates included in certifi (python2.7/site-packages/certifi/cacert.pem) and some of those certificates have expired. How do I update those certificates? I tried updating certifi package using pip but that only updates the package and not the root CA files.
type: AnsweredQuestion
downvote count: 0
score: 13
tagged with: urllib
type: Question

http://stackoverflow.com/comment/82943724
type: QuestionComment
has text: The database is in plaintext ASCII according to https://wordnet.princeton.edu/wordnet/frequently-asked-questions/database/ , so you could edit the database using a text editor like Notepad++. The link describes the necessary format for each word in the dictionary.
score: 0
comment on: http://stackoverflow.com/q/47987383
type: Comment

http://stackoverflow.com/q/47946967
has answer: http://stackoverflow.com/a/47947026
type: Question
tagged with: dataframe
tagged with: numpy
tagged with: pandas
has answer: http://stackoverflow.com/a/47947042
score: 3
accepted answer: http://stackoverflow.com/a/47947026
downvote count: 0
has answer: http://stackoverflow.com/a/47947177
favorite count: 0
has body: I have 4 lists where the elements are one-to-one mapped. There are tens of thousands of elements. I want to create one dict giving the 4 properties for each element, and then I want to put these dicts into a list. (My end goal is to create a pandas DataFrame and save it as an HDF5 file.) Is there an easy memory-efficient way to do this, perhaps using zip() and dict() instead of a for loop? As a working example for Python, please consider: list1 = ['obj1','obj2','obj3'] list2 = ['cat','dog','tree'] list3 = [7,8,9] list4 = ['red','green','blue'] So the idea is that in the end I want a list of dicts that looks like [{'obj':'obj1','type':'cat','num':7,'color':'red'}, {'obj':'obj2','type':'dog','num':8,'color':'green'}, {'obj':'obj3','type':'tree','num':9,'color':'blue'}]
tagged with: python
tagged with: dictionary
answer count: 4
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47947058
upvote count: 3
has answer: http://stackoverflow.com/a/47947058
has title: Convert 4 one-to-one mapped lists into a list of dicts (python)

http://stackoverflow.com/a/47894587
type: Answer
upvote count: 3
has comment: http://stackoverflow.com/comment/82755973
score: 3
has body: I am not sure you can open php tags inside onClick event. You should call javascript function maybe and use ajax (to avoid refresh) to call the php page which will have the exec(python program) function. take a look here Execute PHP function with onClick
downvote count: 0
answers question: http://stackoverflow.com/q/47894506

http://stackoverflow.com/q/47917309
favorite count: 0
has comment: http://stackoverflow.com/comment/82802680
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82802615
has comment: http://stackoverflow.com/comment/82802860
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82802608
has comment: http://stackoverflow.com/comment/82802708
type: Question
has body: I'm making a guessing game where you have the option of an easy medium and hard mode but when I adjusted my code so that the display changes from 100 to 1,000,000 I get an error saying: File "C:/Users/Zach Hirschman/AppData/Local/Programs/Python/Python35-32/GuessGame.py", line 38, in main if guess &gt; randomNumber: UnboundLocalError: local variable 'randomNumber' referenced before assignment I can't seem to figure out how I can fix this, any help would be appreciated. """ Zach Hirschman 12/20/2017 GuessGame.py This program asks the user to guess a number """ import random def main(): difficulty = input("Enter a difficulty level: 'easy','medium', or 'hard' : ") print("At any time, type 'hint' to get a hint") if difficulty == "easy": randomNumber = random.randint(1,100) elif difficulty == "medium": randumNumber = random.randint(1,10000) elif difficulty == "hard": randomNumber = random.randint(1,1000000) found = False while not found: if difficulty == "easy": guess = int(input("Guess a number between 1 and 100")) if guess &gt; randomNumber: print("Too high") elif guess == randomNumber: print("Thats correct!!") found = True else : print("Too Low") elif difficulty == "medium": guess = int(input("Guess a number between 1 and 10000")) if guess &gt; randomNumber: print("Too high") elif guess == randomNumber: print("Thats correct!!") found = True else : print("Too Low") elif difficulty == "hard": guess = int(input("Guess a number between 1 and 1000000")) if guess &gt; randomNumber: print("Too high") elif guess == randomNumber: print("Thats correct!!") found = True else : print("Too Low") x = input("would you like to play again? Type 'yes' or 'no': ") if x == "yes": main() else: print("See you later!") main()
answer count: 2
has title: Variable issue with my python guessing game
tagged with: variables
score: 0
has answer: http://stackoverflow.com/a/47965091
upvote count: 1
has answer: http://stackoverflow.com/a/47917491
downvote count: 1

http://stackoverflow.com/comment/82710650
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47872609
has text: Maybe I am just missing it, but where do you call the `spider_opened` function?
score: 0

http://stackoverflow.com/comment/83340750
comment on: http://stackoverflow.com/q/48000637
has text: This doesn't help for your immediate problem, of course. If the network cable is unplugged, sending mail is going to fail one way or another.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82734341
comment on: http://stackoverflow.com/a/47881409
score: 0
type: AnswerComment
has text: Are you passing the 'soup' argument correctly? What is the print statement of soup?
type: Comment

http://stackoverflow.com/a/47999105
has comment: http://stackoverflow.com/comment/98527148
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/131419112
upvote count: 86
type: Answer
has comment: http://stackoverflow.com/comment/113148837
downvote count: 0
has body: It seems like the problem is the amount of data you are trying to pull back to to your driver is too large. Most likely you are using the collect method to retrieve all values from a DataFrame/RDD. The driver is a single process and by collecting a DataFrame you are pulling all of that data you had distributed across the cluster back to one node. This defeats the purpose of distributing it! It only makes sense to do this after you have reduced the data down to a manageable amount. You have two options: If you really need to work with all that data, then you should keep it out on the executors. Use HDFS and Parquet to save the data in a distributed manner and use Spark methods to work with the data on the cluster instead of trying to collect it all back to one place. If you really need to get the data back to the driver, you should examine whether you really need ALL of the data or not. If you only need summary statistics then compute that out on the executors before calling collect. Or if you only need the top 100 results, then only collect the top 100. Update: There is another reason you can run into this error that is less obvious. Spark will try to send data back the driver beyond just when you explicitly call collect. It will also send back accumulator results for each task if you are using accumulators, data for broadcast joins, and some small status data about each task. If you have LOTS of partitions (20k+ in my experience) you can sometimes see this error. This is a known issue with some improvements made, and more in the works. The options for getting past if if this is your issue are: Increase spark.driver.maxResultSize or set it to 0 for unlimited If broadcast joins are the culprit, you can reduce spark.sql.autoBroadcastJoinThreshold to limit the size of broadcast join data Reduce the number of partitions
accepted answer of: http://stackoverflow.com/q/47996396
has comment: http://stackoverflow.com/comment/123447627
score: 86
answers question: http://stackoverflow.com/q/47996396
has comment: http://stackoverflow.com/comment/135291399
has comment: http://stackoverflow.com/comment/98526616
has comment: http://stackoverflow.com/comment/98527547

http://stackoverflow.com/a/47927058
has comment: http://stackoverflow.com/comment/82841640
accepted answer of: http://stackoverflow.com/q/47927026
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47927026
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/82841232
has body: If you pass arguments that are not None they are never assigned as attributes of self. You could modify your __init__ to simply provide default values then assign them as attributes to your class def __init__(self, id=101, salary=20000, emp_name="Default"): print("Constructing MyClass") self.id = id self.salary = salary self.emp_name = emp_name
has comment: http://stackoverflow.com/comment/82841560

http://stackoverflow.com/q/47864048
has comment: http://stackoverflow.com/comment/82693875
has answer: http://stackoverflow.com/a/47864595
has body: How can I change this code to make both: the y-axis and the y-axis label appear to the right? Which arguments should I pass on to plt.ylabel? plt.matshow(set_color_matrix, interpolation='nearest',cmap=cmap) plt.title("Crystal Growth by DLA", y=1.08) plt.xlabel("x", fontdict=dict(weight='bold')) plt.ylabel("y", fontdict=dict(weight='bold'), rotation=0) plt.savefig("Gifs_and_Images/{}_walkers.png".format(label), dpi=200)
downvote count: 1
type: Question
tagged with: graph
accepted answer: http://stackoverflow.com/a/47864595
has comment: http://stackoverflow.com/comment/82693139
has title: How to plot y-axis on the right of the figure? Without having to make subplots
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/82693454
upvote count: 0
answer count: 1
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/82693314
score: -1
type: AnsweredQuestion

http://stackoverflow.com/comment/82997523
comment on: http://stackoverflow.com/a/48014139
type: Comment
has text: that gives me the total count, not count per department
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82709746
score: 0
comment on: http://stackoverflow.com/q/47871696
type: Comment
type: QuestionComment
has text: Despite it being possible to do this (see the linked duplicated), you might consider that using red and green on the same colormap is not a great idea, since people with red-green colourblindness will not be able to interpret your plot.

http://stackoverflow.com/q/47948003
has answer: http://stackoverflow.com/a/47948133
has comment: http://stackoverflow.com/comment/82866066
type: Question
tagged with: dataframe
score: 0
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/47948133
has comment: http://stackoverflow.com/comment/82866087
linked to: http://stackoverflow.com/q/20625582
has body: What I wanted to do is to replace a single entry NaN value of pandas DataFrame to a single string. Here is what I did. s = pd.DataFrame({'A':['S12','S1','E53',np.NaN], 'B':[1,2,3,4]}) s['A'][s['A'].isnull()==True] = 'P' This code will try to find 'NaN' value in the DataFrame and replace it to the string 'P' and result looks like this. A B 0 S12 1 1 S1 2 2 E53 3 3 P 4 But I also get a warning like this: /Users/grr/anaconda/bin/ipython:3: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy # -*- coding: utf-8 -*- Could anyone explain to me what this means and what I should do to avoid this? Thank you!
has title: Replacing single entry of DataFrame warning?
tagged with: python
has answer: http://stackoverflow.com/a/47948099
accepted answer: http://stackoverflow.com/a/47948099
type: AnsweredQuestion

image
tags question: http://stackoverflow.com/q/47969587
tags question: http://stackoverflow.com/q/47990350
tags question: http://stackoverflow.com/q/47869107
tags question: http://stackoverflow.com/q/47906056
tags question: http://stackoverflow.com/q/47908480
tags question: http://stackoverflow.com/q/47976507
tags question: http://stackoverflow.com/q/47985387
tags question: http://stackoverflow.com/q/47908968
tags question: http://stackoverflow.com/q/47910947
tags question: http://stackoverflow.com/q/47885897
tags question: http://stackoverflow.com/q/47899966
tags question: http://stackoverflow.com/q/47962048
tags question: http://stackoverflow.com/q/47933169
tags question: http://stackoverflow.com/q/47862317
tags question: http://stackoverflow.com/q/47922425
tags question: http://stackoverflow.com/q/48013355
tags question: http://stackoverflow.com/q/47981497
tags question: http://stackoverflow.com/q/47937366
tags question: http://stackoverflow.com/q/47909323
tags question: http://stackoverflow.com/q/47864794
tags question: http://stackoverflow.com/q/47938864
tags question: http://stackoverflow.com/q/47977953
tags question: http://stackoverflow.com/q/48004520
tags question: http://stackoverflow.com/q/47894673
tags question: http://stackoverflow.com/q/47896298
tags question: http://stackoverflow.com/q/47975482
tags question: http://stackoverflow.com/q/47887806
tags question: http://stackoverflow.com/q/47925346
tags question: http://stackoverflow.com/q/47884836
tag name: image
tags question: http://stackoverflow.com/q/47944089
tags question: http://stackoverflow.com/q/47984870
type: Tag
tags question: http://stackoverflow.com/q/47878223

http://stackoverflow.com/a/47969625
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82918941
has body: You are misusing the "self" argument, as the function itself should be in the class indentation (thus, it should be a class's method) or receive the instance as argument. In your code, functioni will only receive the signal argument (all buttons, including QPushButtons, have a checked argument). This means that you are calling functioni with False as argument (QPushButton's checked state after clicking), and self will actually be a bool variable. Remember that self is just a convention in python, it actually is a normal positional argument, you could call it as you want. To solve your problem, it's enough to make the functioni function a class method by adding the right indentation (and calling self.functioni in the signal connection). If, for any reason, you need to leave the function outside the class, you could either add the text or the class instance as an argument: self.pushButton.clicked.connect(lambda checked: functioni(self.le.text()) self.pushButton.clicked.connect(lambda checked: functioni(self)) Unrelated, but important. Remember that the second execute argument for sqlite has to be an iterable (tuple, list, etc.). If you only have one parameter, a single value tuple can be obtained by adding a comma before closing the parenthesis: cur.execute("INSERT INTO Name (Name) VALUES (?)", (self.le.text(), ))
has comment: http://stackoverflow.com/comment/82910816
type: Answer
has comment: http://stackoverflow.com/comment/82913219
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47969397
accepted answer of: http://stackoverflow.com/q/47969397

http://stackoverflow.com/comment/82739734
has text: Are you talking about "regex" here, or "regex-like strings in a very specific, limited notation"? If the former, how to loop through all the possibilities for `".*"`? If the latter, please clarify.
type: Comment
comment on: http://stackoverflow.com/q/47886800
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82887146
type: QuestionComment
score: 1
has text: I recommended `joblib`, the second example there because it has some advantages to it (such as parallellization).
comment on: http://stackoverflow.com/q/47958697
type: Comment

http://stackoverflow.com/a/47927445
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82824119
has comment: http://stackoverflow.com/comment/82824748
has comment: http://stackoverflow.com/comment/82825463
has comment: http://stackoverflow.com/comment/82824200
has comment: http://stackoverflow.com/comment/82823202
type: Answer
has body: change your __init__.py: from cvImageUtils.ColorUtils import ColorUtils I don't think you'll need to import sys anymore, and you don't have import ColorUtils twice. but just like you have to instantiate an object, you should create a ColorUtils object. my personal preference would be not creating a Class for Utils. you might have done this already, but if you want to use a method straight from a class like you did in python, you might want to declare it static. class ColorUtils: @staticmethod def util_method(): pass then you can just do: ColorUtils.util_method() Update: you can read more about relative/absolute import from here as well. to fix your actual problem though, you can do: color.py remove your import sys and sys call from color.py change: import cvImageUtils.ColorUtils as ct to: from cvImageUtils.ColorUtils import * remove all your ct reference instead just use the actual functions. cvImageUtils/__init__.py change: from . import ColorUtils to __all__=['ColorUtils'] I was able to run color.py to get all the images printed out on screen. a image.png was also generated locally as well.
has comment: http://stackoverflow.com/comment/82824155
has comment: http://stackoverflow.com/comment/82823879
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/82823274
has comment: http://stackoverflow.com/comment/82824708
has comment: http://stackoverflow.com/comment/82823075
accepted answer of: http://stackoverflow.com/q/47926642
answers question: http://stackoverflow.com/q/47926642
has comment: http://stackoverflow.com/comment/82824299
has comment: http://stackoverflow.com/comment/82824077
has comment: http://stackoverflow.com/comment/82824127

http://stackoverflow.com/comment/82937565
comment on: http://stackoverflow.com/a/47984257
type: AnswerComment
score: 0
type: Comment
has text: I made mine a little bit clearer. You do have access to the instance here as well since it is always passed as an argument to the function anyway.

http://stackoverflow.com/q/47915793
type: Question
has body: I am new to OpenCV and Python as well. I am getting some errors in my code which I have tried my best but .....I hope anyone would help me out. I want that when I run the code it should capture 10-15 frames per second...below is the error I am getting...could anyone help me with the changes Code... import cv2 import time import sys import numpy as np if __name__ == '__main__': faceCascade = cv2.CascadeClassifier('C:\\Users\\Mudit\\Desktop\\Thesis\\CNN-master\\haarcascade_frontalface_default') faceNeighborsMax = 10 neighborStep = 1 # Start default camera video = cv2.VideoCapture(0); # Number of frames to capture num_frames = 10; print("Capturing {0} frames".format(num_frames)) # Start time start = time.time() # Grab a few frames for i in range(0, num_frames): ret, frame = video.read() frameGray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) for neigh in range(1, faceNeighborsMax, neighborStep): faces = faceCascade.detectMultiScale(frameGray, 1.2, neigh) frameClone = np.copy(frame) # Display the image for (x, y, w, h) in faces: cv2.rectangle(frameClone, (x, y), (x + w, y + h), (255, 0, 0), 2) cv2.putText(frameClone, "# Neighbors = {}".format(neigh), (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 4) cv2.imshow('Face Detection', frameClone) if cv2.waitKey(500) &amp; 0xFF == 27: cv2.destroyAllWindows() sys.exit() # End time end = time.time() # Time elapsed seconds = end - start print("Time taken : {0} seconds".format(seconds)) # Calculate frames per second fps = num_frames / seconds; print("Estimated frames per second : {0}".format(fps)) # Release video video.release() Error: Traceback (most recent call last): File "C:/Users/Mudit/PycharmProjects/CNN/findframerateofacamera/webcam.py", line 28, in &lt;module&gt; faces = faceCascade.detectMultiScale(frameGray, 1.2, neigh) cv2.error: C:\projects\opencv-python\opencv\modules\objdetect\src\cascadedetect.cpp:1698: error: (-215) !empty() in function cv::CascadeClassifier::detectMultiScale
has title: OpenCV Web Cam Video Capture issue
tagged with: python
has comment: http://stackoverflow.com/comment/82801920
tagged with: opencv3.0
score: 0
answer count: 1
tagged with: opencv
has comment: http://stackoverflow.com/comment/82800627
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82799851
has answer: http://stackoverflow.com/a/47917473
tagged with: python-3.x

http://stackoverflow.com/q/47896709
has comment: http://stackoverflow.com/comment/83179238
has answer: http://stackoverflow.com/a/47896769
has comment: http://stackoverflow.com/comment/83184218
downvote count: 1
tagged with: python
tagged with: python-decorators
favorite count: 0
has comment: http://stackoverflow.com/comment/82760340
has comment: http://stackoverflow.com/comment/83179735
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82760272
has comment: http://stackoverflow.com/comment/83184769
upvote count: 0
has comment: http://stackoverflow.com/comment/83184397
score: -1
type: Question
has body: I want to print Hello World on every function call and I'm using decorators to achieve this. def hello_decorator(fn): def ret_fn(*args, **kwargs): print("Hello world") return fn(*args, **kwargs) return ret_fn Assuming that this caused a function to error out, while an undecorated version of that function worked fine, what might be the problem with the decorator? The issue isn't with print since I can remove that and the issue remains. Is there a better way to wrap a function and call it exactly the way it would have been called without the prototype?
has title: A decorator that works on every function
answer count: 1
has comment: http://stackoverflow.com/comment/82760307

flask
tags question: http://stackoverflow.com/q/47888472
tags question: http://stackoverflow.com/q/47860912
tags question: http://stackoverflow.com/q/47894674
tags question: http://stackoverflow.com/q/47917385
tags question: http://stackoverflow.com/q/47860718
tags question: http://stackoverflow.com/q/47889880
tags question: http://stackoverflow.com/q/47948766
tags question: http://stackoverflow.com/q/47998286
tags question: http://stackoverflow.com/q/47955046
tags question: http://stackoverflow.com/q/47906882
tags question: http://stackoverflow.com/q/48012327
tags question: http://stackoverflow.com/q/48011682
tags question: http://stackoverflow.com/q/47954185
tags question: http://stackoverflow.com/q/47949900
tags question: http://stackoverflow.com/q/47859999
tags question: http://stackoverflow.com/q/47893496
tags question: http://stackoverflow.com/q/47944401
tags question: http://stackoverflow.com/q/47971334
tags question: http://stackoverflow.com/q/47908596
tags question: http://stackoverflow.com/q/47873235
tags question: http://stackoverflow.com/q/47942514
tags question: http://stackoverflow.com/q/47998500
tags question: http://stackoverflow.com/q/47877011
tags question: http://stackoverflow.com/q/47863317
tags question: http://stackoverflow.com/q/47863536
tags question: http://stackoverflow.com/q/47896028
tags question: http://stackoverflow.com/q/47950680
tags question: http://stackoverflow.com/q/47976084
tags question: http://stackoverflow.com/q/47981939
tags question: http://stackoverflow.com/q/47955680
tags question: http://stackoverflow.com/q/47935495
tags question: http://stackoverflow.com/q/47885251
tags question: http://stackoverflow.com/q/47967872
tags question: http://stackoverflow.com/q/47980515
tags question: http://stackoverflow.com/q/47945449
tags question: http://stackoverflow.com/q/47859054
tags question: http://stackoverflow.com/q/47871185
tags question: http://stackoverflow.com/q/48014309
tags question: http://stackoverflow.com/q/47904931
tags question: http://stackoverflow.com/q/47877691
tags question: http://stackoverflow.com/q/47955872
type: Tag
tags question: http://stackoverflow.com/q/47975521
tags question: http://stackoverflow.com/q/48005602
tags question: http://stackoverflow.com/q/47900727
tags question: http://stackoverflow.com/q/47901481
tags question: http://stackoverflow.com/q/47981630
tags question: http://stackoverflow.com/q/47909332
tags question: http://stackoverflow.com/q/47961481
tags question: http://stackoverflow.com/q/47970625
tags question: http://stackoverflow.com/q/48001958
tags question: http://stackoverflow.com/q/47857173
tags question: http://stackoverflow.com/q/47918884
tags question: http://stackoverflow.com/q/47966255
tags question: http://stackoverflow.com/q/47973490
tags question: http://stackoverflow.com/q/47875488
tags question: http://stackoverflow.com/q/47950991
tags question: http://stackoverflow.com/q/47905108
tags question: http://stackoverflow.com/q/47871401
tags question: http://stackoverflow.com/q/47995000
tags question: http://stackoverflow.com/q/47996637
tags question: http://stackoverflow.com/q/47931287
tags question: http://stackoverflow.com/q/47888579
tags question: http://stackoverflow.com/q/47899093
tags question: http://stackoverflow.com/q/47951605
tags question: http://stackoverflow.com/q/47992539
tags question: http://stackoverflow.com/q/47936640
tags question: http://stackoverflow.com/q/47856949
tags question: http://stackoverflow.com/q/48013544
tags question: http://stackoverflow.com/q/47964574
tags question: http://stackoverflow.com/q/47906730
tags question: http://stackoverflow.com/q/47993775
tags question: http://stackoverflow.com/q/47988765
tags question: http://stackoverflow.com/q/47981081
tags question: http://stackoverflow.com/q/47891935
tags question: http://stackoverflow.com/q/47946267
tags question: http://stackoverflow.com/q/47941234
tag name: flask
tags question: http://stackoverflow.com/q/47951227
tags question: http://stackoverflow.com/q/47865418

http://stackoverflow.com/comment/82798524
comment on: http://stackoverflow.com/a/47915221
type: Comment
has text: Thanks, this is what I was looking for
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82956397
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47989797
has text: Maybe. I will show briefly code since the source code project is too big. I guess this code simulate the brush motion.But I do't know why it does work. PLZ give some advice to me.Thank you

http://stackoverflow.com/a/47858808
has comment: http://stackoverflow.com/comment/82682733
has comment: http://stackoverflow.com/comment/82710199
type: Answer
has comment: http://stackoverflow.com/comment/82710540
score: 3
has comment: http://stackoverflow.com/comment/82682816
has comment: http://stackoverflow.com/comment/82683970
answers question: http://stackoverflow.com/q/47857982
has comment: http://stackoverflow.com/comment/82682759
upvote count: 3
has comment: http://stackoverflow.com/comment/82682341
has comment: http://stackoverflow.com/comment/82682687
has comment: http://stackoverflow.com/comment/82682652
has comment: http://stackoverflow.com/comment/82683283
has comment: http://stackoverflow.com/comment/82712123
downvote count: 0
has body: Your code should work properly. I couldn't reproduce described behavior. Here is a bit more "pandaic" version: df.to_csv('File.csv', header=False, mode='a') PS pay attention at the mode='a' (append) parameter... UPDATE: How to get rid of ellipsis when displaying / printing a DF: with pd.option_context("display.max_columns", 0): print(df)
has comment: http://stackoverflow.com/comment/82682430

http://stackoverflow.com/q/47874622
tagged with: hadoop
score: 0
has comment: http://stackoverflow.com/comment/82715935
tagged with: apache-spark
answer count: 1
tagged with: hdfs
has comment: http://stackoverflow.com/comment/82743921
tagged with: python
accepted answer: http://stackoverflow.com/a/47875307
type: AnsweredQuestion
has body: I'm trying to write an image classification algorithm using Python and Spark. I'm following this tutorial, which is taken from the official databricks documentation and works perfectly when running locally. My problem now, shifting the algorithm on a cluster, is that I have to load my images from two folders on the HDFS in .jpg format, and I can't find a way to create a dataframe the way it's done locally in the examples. I'm looking for a substitute for this code: from sparkdl import readImages jobs_df = readImages(img_dir + "/jobs").withColumn("label", lit(1))
has answer: http://stackoverflow.com/a/47875307
type: Question
linked to: http://stackoverflow.com/q/39699107
tagged with: pyspark
has title: Image dataframe from HDFS for Image Classification

http://stackoverflow.com/comment/83018005
score: 0
type: Comment
has text: My QLearning algorithm converges, I have no problem with that. The question I am asking is, will the converged utility values for states in Value Iteration Algorithm be the same as Q-function utility values when it converges.
type: AnswerComment
comment on: http://stackoverflow.com/a/48020259

http://stackoverflow.com/comment/82751250
score: 1
type: QuestionComment
has text: ..... `ad[cp]`?
comment on: http://stackoverflow.com/q/47892383
type: Comment

http://stackoverflow.com/a/49187554
has comment: http://stackoverflow.com/comment/125440394
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48009243
type: Answer
upvote count: 1
has body: Solution: 1 Installing TensorFlow from Source on windows is not generally supported. But you can try building this using bazel or tensorflow cmake build. Refer: https://www.tensorflow.org/install/install_sources Solution: 2 Create Intel optimized conda environment as below: conda create -n tf -c intel python=3.6 To install tensorflow: conda install -c intel tensorflow This will install tensorflow version 1.2.1 with mkl. This might help. Prerequisites: Install Anaconda on your windows machine.

http://stackoverflow.com/comment/82694628
type: QuestionComment
has text: A simplification which you might have missed is that an empty list `[]` gives `False`. So `if elements ==[]` can be written as `if not elements` (although rewriting the `if` so the `not` is not required.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47864803

http://stackoverflow.com/comment/82774096
comment on: http://stackoverflow.com/q/47903085
type: Comment
has text: I just noticed I probably have made a mistake in the second last line of the edit. `v = Volkstelling(??? , io.StringIO(data))` I do not know what goes here.
score: 0
type: QuestionComment

http://stackoverflow.com/q/47869663
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47872763
accepted answer: http://stackoverflow.com/a/47873112
possible better answer: http://stackoverflow.com/a/47872763
tagged with: python
has title: Creating a column text box in python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47873112
type: Question
has body: I am working on a school project to make Yahtzee in python ( I am pretty new to the language) and I would like to know if it is possible, and if so, how to have a column of text appear in the command line to display player scores that are updated whenever they decide to score something in a certain category. Here is what I want to print: print:(''' ╔═══════════╗╔═══════════╗ ║ Ones ║║ ║ ╠═══════════╣╠═══════════╣ ║ Twos ║║ ║ ╠═══════════╣╠═══════════╣ ║ Threes ║║ ║ ╠═══════════╣╠═══════════╣ ║ Fours ║║ ║ ╠═══════════╣╠═══════════╣ ║ Fives ║║ ║ ╠═══════════╣╠═══════════╣ ║ Sixes ║║ ║ ╠═══════════╣╠═══════════╣ ║ Total ║║ ║ ╠═══════════╬╬═══════════╬ ╠═══════════╬╬═══════════╬ ║ Three of ║║ ║ ║ a kind ║║ ║ ╠═══════════╣╠═══════════╣ ║ Four of ║║ ║ ║ a kind ║║ ║ ╠═══════════╣╠═══════════╣ ║ Full House║║ ║ ╠═══════════╣╠═══════════╣ ║ Small ║║ ║ ║ Straight ║║ ║ ╠═══════════╣╠═══════════╣ ║ Large ║║ ║ ║ Straight ║║ ║ ╠═══════════╣╠═══════════╣ ║ Chance ║║ ║ ╠═══════════╣╠═══════════╣ ║ Yahtzee ║║ ║ ╚═══════════╝╚═══════════╝ ''') I would like the second column to be duplicated and updated with variables depending on the number of players and what they score in each category. Any ideas would be helpful.

http://stackoverflow.com/comment/82991662
score: 0
comment on: http://stackoverflow.com/a/48011496
type: AnswerComment
type: Comment
has text: Is it possible to add additional validators for the other fields? Or is it maybe more effective to create a model form that you stuff your data in and let that raise validation errors?

http://stackoverflow.com/a/47908266
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47888736
downvote count: 0
type: Answer
score: 3
upvote count: 3
has body: It seems that proxies have to be specified on the session level. Then they are not required in browser.open and submitting the form also works: import mechanicalsoup proxies = { 'https': 'my.https.proxy:8080', 'http': 'my.http.proxy:8080' } url = 'https://stackoverflow.com/' browser = mechanicalsoup.StatefulBrowser() browser.session.proxies = proxies # THIS IS THE SOLUTION! front_page = browser.open(url, verify=False) form = browser.select_form('form[action="/search"]') form["q"] = "MechanicalSoup" result = browser.submit(form, url=url) result.status_code returns 200 (i.e. "OK").
accepted answer of: http://stackoverflow.com/q/47888736

http://stackoverflow.com/q/47878492
type: UnansweredQuestion
has title: No module named Tkinter error
has answer: http://stackoverflow.com/a/47878536
downvote count: 1
has body: I have been using http://python.codnex.net/index.php. I have tried to use Tkinter but it shows ImportError: No module named Tkinter on line 1 I have tried many things including: import Tkinter import tkinter from tkinter import * If you find something please let me know.
score: -1
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/47878519
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/47883079
favorite count: 0
tagged with: tkinter

http://stackoverflow.com/a/47863201
score: 0
accepted answer of: http://stackoverflow.com/q/47863170
has body: Correct usage of random function: In case of continuous numbers randint or randrange are probably the best choices but if you have several distinct values in a sequence (i.e. a list) you could also use choice: &gt;&gt;&gt; import random &gt;&gt;&gt; values = list(range(10)) &gt;&gt;&gt; random.choice(values) 5 choice also works for one item from a not-continuous sample: &gt;&gt;&gt; values = [1, 2, 3, 5, 7, 10] &gt;&gt;&gt; random.choice(values) 7 If you need it "cryptographically strong" there's also a secrets.choice in python 3.6 and newer: &gt;&gt;&gt; import secrets &gt;&gt;&gt; values = list(range(10)) &gt;&gt;&gt; secrets.choice(values) 2
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/47863170

http://stackoverflow.com/comment/82872199
comment on: http://stackoverflow.com/q/47944250
score: 0
type: Comment
type: QuestionComment
has text: @martineau exactly that, I will add the source data, thanks

http://stackoverflow.com/comment/82912286
score: 0
comment on: http://stackoverflow.com/q/47971334
type: Comment
type: QuestionComment
has text: If it helps at all, I'm an admin on my computer.

http://stackoverflow.com/a/48013821
has comment: http://stackoverflow.com/comment/83106884
has comment: http://stackoverflow.com/comment/82996570
has comment: http://stackoverflow.com/comment/83108350
has comment: http://stackoverflow.com/comment/82996453
has body: EDIT: I initially misread your question, and thought you wanted to concatenate all the DataFrames into one. This does that: dfx = pd.concat([df for df in analysisdict.values()], ignore_index=True) (Thanks to @paul-h for the ignore_index=True tip) I read your question more carefully and realized that you're asking how to assign each DataFrame in your dictionary to its own variable, resulting in separate DataFrames named df1, df2, ..., dfn. Everything in my experience says that dynamically creating variables in this way is an anti-pattern, and best left to dictionaries. Check out the discussion here: How can you dynamically create variables via a while loop?
type: Answer
has comment: http://stackoverflow.com/comment/82999121
upvote count: 2
has comment: http://stackoverflow.com/comment/82996521
has comment: http://stackoverflow.com/comment/82996495
accepted answer of: http://stackoverflow.com/q/48013737
answers question: http://stackoverflow.com/q/48013737
has comment: http://stackoverflow.com/comment/82999218
has comment: http://stackoverflow.com/comment/82996856
has comment: http://stackoverflow.com/comment/82996546
score: 2
has comment: http://stackoverflow.com/comment/82999358
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82996524

http://stackoverflow.com/comment/82750006
type: AnswerComment
comment on: http://stackoverflow.com/a/47877692
type: Comment
has text: darkrinoa: Hard for me to understand why you would prefer the much more involved code in the answer you accepted. Seems like the relatively simple approach I suggested is much more "elegant" (even though, as I said, it does not explicitly compare their contents). Hmmm, maybe that's why...
score: 0

http://stackoverflow.com/comment/82812086
has text: Hint: `itertools.groupby`. What've you tried thus far?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47922235
score: 0

http://stackoverflow.com/a/47877247
has comment: http://stackoverflow.com/comment/82720432
accepted answer of: http://stackoverflow.com/q/47877164
has body: Your patch arguments need to be in the reverse order of the @patch decorators.
upvote count: 2
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82720529
answers question: http://stackoverflow.com/q/47877164

http://stackoverflow.com/a/47913183
accepted answer of: http://stackoverflow.com/q/47912611
type: AcceptedAnswer
downvote count: 0
has body: Here's a better way of doing it with numpy - y = np.array(x.tolist()) pd.DataFrame(y.dot(y.T), index=x.index, columns=x.index) label1 label2 label3 label1 1 0 1 label2 0 1 1 label3 1 1 2 The pandas way - df = pd.DataFrame(x.tolist(), index=x.index) df.dot(df.T) label1 label2 label3 label1 1 0 1 label2 0 1 1 label3 1 1 2
type: Answer
answers question: http://stackoverflow.com/q/47912611
score: 2
upvote count: 2

http://stackoverflow.com/comment/82832098
has text: "" but you're matching most instead of $most "" , Yes this was the problem , thanks for explanation, given regex is simpler than mine,
type: Comment
comment on: http://stackoverflow.com/a/47929439
score: 1
type: AnswerComment

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/48004369
tags question: http://stackoverflow.com/q/47892039
tags question: http://stackoverflow.com/q/47963688
tags question: http://stackoverflow.com/q/48004229
tags question: http://stackoverflow.com/q/47874461
type: Tag
tags question: http://stackoverflow.com/q/47867191
tags question: http://stackoverflow.com/q/47898792

http://stackoverflow.com/comment/82692884
has text: I can add timings for it too, but apply + groupby is realy slow, so I think it will be slowier too.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47863123

http://stackoverflow.com/comment/82714400
has text: Thanks! This works perfectly. Can you explain what you mean by negative look ahead? What does the "?!" part of the pattern mean? Thanks again!
comment on: http://stackoverflow.com/a/47873349
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/95107946
has text: I believe the issue arises becuase of tabula updating the method. Now the method read_pdf sits inside of wrapper.
score: 0
comment on: http://stackoverflow.com/a/49997114
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82862208
comment on: http://stackoverflow.com/a/47943382
score: 0
type: AnswerComment
has text: Thanks a lot Ken Syme! The dataframe was generate as I wanted. I have one more comment, that is the following: I want to work with the dataframe, and need to store an acces to it in an independent object. I mean I need to do some analyis with the dataframe, but the program is in OOP, and I only see the output when I put print inside the program.
type: Comment

http://stackoverflow.com/comment/82724761
type: Comment
type: QuestionComment
has text: No, that's not going to work; serial ports are usually exclusive. Why wouldn't you use the same object, as intended?
comment on: http://stackoverflow.com/q/47879366
score: 0

http://stackoverflow.com/comment/82919601
has text: You may run the command `docker run --rm -v /home/user/Projects/Application/:/home/user/Projects/Application/ -it python:3 sh` to get into a terminal. Navigate to the folder `/home/user/Projects/Application/` and make sure you have all the required files, configs etc.
type: Comment
comment on: http://stackoverflow.com/a/47974970
score: 0
type: AnswerComment

http://stackoverflow.com/q/47979645
type: UnansweredQuestion
upvote count: 1
type: Question
has title: -bash: jupyter: command not found (Mac OSx High Sierra 10.13)
has comment: http://stackoverflow.com/comment/82927854
linked to: http://stackoverflow.com/q/35848096
tagged with: python-2.7
tagged with: bash
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/82944511
tagged with: macos
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/82927883
answer count: 0
has body: Looking for some direction on what's going on with my path variable &amp; why jupyter notebook won't run. I just bought a new laptop (Mac, Sierra 10.13), used pip to install jupyter, and am using Python 2.7 that comes already installed. When I try to enter the command 'jupyter notebook', I get: -bash: jupyter: command not found There is a 'jupyter' script located in '/Library/Python/2.7/lib/bin' and my PATH is set to the same in bash_profile. When I type 'echo $PATH', it returns: /Library/Python/2.7/lib/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin The only way I can get the jupyter notebook interface up &amp; running is by entering 'python -m "jupyter" notebook' in terminal. I have a feeling there is something wrong with where my packages are installed, but cannot figure it out. Happy to provide more information if someone can help. Thank you!

http://stackoverflow.com/comment/82860877
comment on: http://stackoverflow.com/a/47927580
has text: Unfortunately I need a 20 reputation before I am able to talk.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/82749843
score: 0
comment on: http://stackoverflow.com/q/47891444
type: Comment
type: QuestionComment
has text: Perhaps it's a lexical scoping issue? You're doing stuff to df inside of a function, but you're not returning anything, so df stays the same outside the scope of the function call. Try defining your function with `def diagnostic(df):` and then calling it with `df = diagnostic(df)`

http://stackoverflow.com/comment/82897773
has text: I did make it executable with `chmod a+x file.py`, and when I `ls al` it says `-rwxr-xr-x`
comment on: http://stackoverflow.com/a/47964058
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/82932253
type: AnswerComment
score: 0
type: Comment
has text: Thanks a lot!! If I apply: df.name=df.name+'_'+df.G.astype(str) at the end to change the names, I get name_False or name_True, but no number? How can I get: name_0,name_1 etc. again ?
comment on: http://stackoverflow.com/a/47981476

http://stackoverflow.com/comment/82908532
type: Comment
type: QuestionComment
has text: You should think about what value you want the centroid to take when no points are assigned to it (which can happen quite easily as you've set up the algorithm!)
comment on: http://stackoverflow.com/q/47965565
score: 0

http://stackoverflow.com/comment/82986535
has text: the exact same error?
comment on: http://stackoverflow.com/q/48008837
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82703858
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47869283
has text: @MayurMahajan That probably means there are no nulls in the column, I suppose? I'm not sure, and I don't think it's a problem. Unless you're getting an incorrect result?
score: 0

http://stackoverflow.com/q/47863220
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/47933230
has body: I converted a label into sparse a sparse label tuple (indices, values, shape). However, when I feed it to the classifier, I encounter this error: Traceback (most recent call last): File ..., line 23, in &lt;module&gt; classifier.fit(x=x_train, y=sparse_y_train, batch_size=128, steps=10) File "...tensorflow\python\util\deprecation.py", line 316, in new_func return func(*args, **kwargs) File "...tensorflow\contrib\learn\python\learn\estimators\estimator.py", line 464, in fit SKCompat(self).fit(x, y, batch_size, steps, max_steps, monitors) File "...tensorflow\contrib\learn\python\learn\estimators\estimator.py", line 1429, in fit epochs=None) File "...tensorflow\contrib\learn\python\learn\estimators\estimator.py", line 139, in _get_input_fn epochs=epochs) File "...tensorflow\contrib\learn\python\learn\learn_io\data_feeder.py", line 151, in setup_train_data_feeder x, y, n_classes, batch_size, shuffle=shuffle, epochs=epochs) File "...tensorflow\contrib\learn\python\learn\learn_io\data_feeder.py", line 326, in __init__ if y_is_dict else check_array(y, y.dtype)) AttributeError: 'tuple' object has no attribute 'dtype' How do I feed a sparse tuple into the classifier?
tagged with: tensorflow
type: Question
has title: Feeding a Sparse Data into Tensorflow Estimator's Fit
upvote count: 1
answer count: 1
linked to: http://stackoverflow.com/q/48201725
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/47969305
possible better answer: http://stackoverflow.com/a/47969359
answer count: 2
has body: Let's say I have the following tensors: X = np.zeros((3,201, 340)) Y = np.zeros((340, 28)) Making a dot product of X, Y is successful with numpy, and yields a tensor of shape (3, 201, 28). However with tensorflow I get the following error: Shape must be rank 2 but is rank 3 error ... minimal code example: X = np.zeros((3,201, 340)) Y = np.zeros((340, 28)) print(np.dot(X,Y).shape) # successful (3, 201, 28) tf.matmul(X, Y) # errornous Any idea how to achieve the same result with tensorflow?
upvote count: 2
has title: Broadcasting np.dot vs tf.matmul for tensor-matrix multiplication (Shape must be rank 2 but is rank 3 error)
accepted answer: http://stackoverflow.com/a/47969388
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/47969359
tagged with: tensor
has answer: http://stackoverflow.com/a/47969388
tagged with: python
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/41870228
tagged with: tensorflow
tagged with: matrix-multiplication
type: Question
tagged with: numpy

http://stackoverflow.com/a/47945041
answers question: http://stackoverflow.com/q/47938359
has body: Floating point numbers are poison for symbolic computations, especially as complicated as symbolic integration. Don't put them in symbolic integrals. Also, declaring positive variables as such can be a big help. x = symbols('x', positive=True) int1 = integrate(log(x)**2 / (1 + x**2), (x, 0, 1)) int2 = integrate(log(1/x) / (1 - x), (x, 0, 1)) No errors now, but int1 is just the original integral un-evaluated; SymPy did not succeed in finding its value. It seems to be beyond its ability. For the second one it returns polylog(2, -exp_polar(I*pi)). The presence of complex number I*pi and exp_polar means SymPy was doing some complex plane work where the amount of winding around the origin might matter. The function exp_polar is different from exp in that exp_polar(2*I*pi) does not simplify to 1 like exp(2*I*pi) does: it keeps the distinction between turning by 360 degrees and not turning at all. But if we ignore all that and put exp in the result, polylog(2, -exp(I*pi)) evaluates to pi**2 / 6, the correct value of the second integral.
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47938359

http://stackoverflow.com/comment/82870047
type: AnswerComment
has text: Indeed, I did not notice the example outputs, (or it was edited after I answered). Now trying different passwords for each users is not something I am familiar with :P
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47947444

http://stackoverflow.com/comment/82891836
comment on: http://stackoverflow.com/q/47961303
type: Comment
type: QuestionComment
has text: Is your input exactly `"A, B, C\nC, D, A, E\nD, E"`?
score: 0

http://stackoverflow.com/comment/113610563
score: 0
comment on: http://stackoverflow.com/q/47968998
type: Comment
type: QuestionComment
has text: any solutions ?

http://stackoverflow.com/a/47957861
type: Answer
answers question: http://stackoverflow.com/q/47957487
has body: You can combine two answers from StackOverflow to (almost) solve this issue. Use this answer (by tehvan) to create a getch() like method to read in one character from the user without the need for a \n. (repeated below from the answer) Use the Python3 version of this answer (by Barafu Albino) to call the previously defined _Getch() class in a separate process. Please note that the following code works for Python3 only and uses any key to stop the process, not just the insert key. # This code is a combination of two StackOverflow answers # (links given in the answer) # ------- Answer 1 by tehvan ----------------------------------- class _Getch: """Gets a single character from standard input. Does not echo to the screen.""" def __init__(self): try: self.impl = _GetchWindows() except ImportError: self.impl = _GetchUnix() def __call__(self): return self.impl() class _GetchUnix: def __init__(self): import tty, sys def __call__(self): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch class _GetchWindows: def __init__(self): import msvcrt def __call__(self): import msvcrt return msvcrt.getch() getch = _Getch() # -------- Answer 2 by Barafu Albino (modified) ------- import _thread def input_thread(a_list): _Getch().__call__() a_list.append(True) def do_stuff(): a_list = [] _thread.start_new_thread(input_thread, (a_list,)) print('Press any key to stop.') while not a_list: pass # This is where you can put the stuff # you want to do until the key is pressed print('Stopped.') do_stuff()
has comment: http://stackoverflow.com/comment/82890469
score: 0
has comment: http://stackoverflow.com/comment/82895326

http://stackoverflow.com/q/47877144
has answer: http://stackoverflow.com/a/47877235
downvote count: 0
has comment: http://stackoverflow.com/comment/82720763
has body: I want to return true if name is valid. Name can contain: upper or lower case characters no numbers or special characters can be one or two words with a single space in the middle first name and last name can be between 2-25 characters each eg. John Smith = true John = true JoHn = true John Sm1th = false John $mith = false J0hn = false John Smith = false (two spaces between names) Here is my code thus far. It fails some of these test cases. import re if re.findall('[A-Za-z]{2,25}\s[A-Za-z]{2,25}', string): print("true") else: print("false")
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82720159
possible better answer: http://stackoverflow.com/a/47877177
score: 1
type: Question
answer count: 2
upvote count: 1
linked to: http://stackoverflow.com/q/4923380
has comment: http://stackoverflow.com/comment/82720989
favorite count: 0
accepted answer: http://stackoverflow.com/a/47877235
has title: Validate name using Python regex
has answer: http://stackoverflow.com/a/47877177
tagged with: python
tagged with: regex
tagged with: python-3.x

http://stackoverflow.com/comment/82854411
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47940123
has text: @AskMe blank or NULL? Also, what is the "problem"?
type: Comment

http://stackoverflow.com/comment/82910258
has text: No, furas, I did copy+paste. I removed top.after(100, read_data) just before mainloop()
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47970163
type: Comment

on-the-fly
type: Tag
tags question: http://stackoverflow.com/q/47896703
tag name: on-the-fly

http://stackoverflow.com/comment/82890183
has text: Follow-up question for multiple IDs here: https://stackoverflow.com/questions/47960566/performing-pct-change-that-only-considers-the-prior-year-in-a-time-series-data
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47959073

http://stackoverflow.com/comment/82858649
type: Comment
score: 1
type: QuestionComment
has text: @ShalithaSuranga `expr: command not fund`
comment on: http://stackoverflow.com/q/47944453

http://stackoverflow.com/comment/82790704
score: 0
comment on: http://stackoverflow.com/q/47898340
type: Comment
type: QuestionComment
has text: I just added the stack trace and the iframe I'm targeting.

http://stackoverflow.com/comment/82932161
type: QuestionComment
comment on: http://stackoverflow.com/q/47981842
has text: Hi, welcome to SO! Could you add more details? What have you tried so far? What problems are you facing? See [this page](https://stackoverflow.com/help/how-to-ask) for more help on posing the right question on SO
score: 3
type: Comment

http://stackoverflow.com/q/47909321
has answer: http://stackoverflow.com/a/57068892
has comment: http://stackoverflow.com/comment/82805599
favorite count: 0
has comment: http://stackoverflow.com/comment/82810590
type: Question
upvote count: 2
has body: I have a multiple camera setup but I'm narrowing it down to two cameras for this question. The two cameras are aligned and the right side of camera 1 overlaps the left side of camera 2 to ensure no area is left out of sight. Both cameras share a common reference system i.e: the x axis in the image 2 is the continuity of the x axis in image 1. I have no problem for simple scenarios like the following picture when the object is fully contained in one image : My problem: I don't know how to proceed when the object is across this overlapping area like in the picture below. For my application I need to return for each detect object : center point (x,y), height of the bounding box and width of the bounding box. My approach so far: I'm using for both images cv2.findContours and cv2.boundingRect. I calculate based on size of the rect and size of the image if the object touches either side of the image. If they don't it's the easy part but if they do that's were I am stuck at the moment. I don't know how to juggle between the values of both images and creating a unique (x,y,w,h) point from both contours. There is my current code: import numpy as np import cv2 img1 = cv2.imread('image_from_cam1.png') img2 = cv2.imread('image_from_cam2.png') gray1= cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) gray2= cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) img1_width = img1.shape[1] img2_width = img2.shape[1] #Thresholds on both images then find the contours ret1, thresh1 = cv2.threshold(gray1, 127, 255, 1) ret2, thresh2 = cv2.threshold(gray2, 127, 255, 1) cnts1, _ = cv2.findContours(thresh1, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) cnts2, _ = cv2.findContours(thresh2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) result = [] #result list that will contain [(x1,y1,w1,h1), ...] overlap = False #is the object overlapping across several images l1 = [] #storage list for sub-results in image1 l2 = [] #storage list for sub-results in image2 #loop over contours of image1 to draw rectangles and check if they touch e…
tagged with: python
tagged with: computer-vision
has title: How to detect an object across overlapping cameras
tagged with: opencv
has comment: http://stackoverflow.com/comment/82794640
answer count: 1
type: UnansweredQuestion
tagged with: python-2.7
score: 2
downvote count: 0

http://stackoverflow.com/q/47880389
has comment: http://stackoverflow.com/comment/82743472
has comment: http://stackoverflow.com/comment/82726707
tagged with: python
has comment: http://stackoverflow.com/comment/82726825
has comment: http://stackoverflow.com/comment/82743389
answer count: 0
type: UnansweredQuestion
has body: I basically want to implement a django view that accepts some json data and then also posts a json data which would be displayed.The confirm group view accepts a list of people via json data , forms a group and then returns the group code back to display. I was getting the Forbidden(403) CSRF token missing or incorrect Error I am beginner in django and js so please answer accordingly. Thanking you in advance :) view.py import json def confirm_group(request): data = json.loads(request.body.decode("utf-8")) grp = Group() grp.group_code = group_code_generator() grp.save() for i in range(len(data)): Player = Regplayer.objects.filter(pk=data[i]["pk"]) pl = Enteredplayer() pl.regplayer = Player pl.group = grp pl.save() return JsonResponse(grp.group_code, safe=False) script.js function confirm() { var i = 0; var rows= document.getElementById("group").children; var num= document.getElementById("group").childElementCount; if(num==0) { } else { // alert("Confirm grouping of "+num+" people?"); for(i=0; i < num; i++) { send_name=rows[i].children[0].children[0].innerHTML; send_gender=rows[i].children[3].children[0].innerHTML; send_clgname=rows[i].children[1].children[0].innerHTML; send_sport=rows[i].children[2].children[0].innerHTML; send_id=rows[i].children[5].innerHTML; myObj["data"].push({"name":send_name, "gender":send_gender, "college":send_clgname, "sport": send_sport, "pk": send_id}); alert(JSON.stringify(myObj)); } csrf_token = document.getElementById('csrf_token').innerHTML; myObj["data"].push({"csrfmiddlewaretoken": csrf_token }); //POST TO BACKEND // Sending and receiving data in JSON format using POST method // var ourRequest = new XMLHttpRequest(); var url = "/confirm_group/"; ourRequest.open("POST", url, true); ourRequest.setRequestHeader("Content-type", "application/json"); // POST var data = JSON.stringify(myObj); ourRequest.send(data); // Obtain ourRequest.onreadystatechange = function () { if (ourRequest.readyState === 4 && ourRequest.status === 200) { var json…
tagged with: django
has comment: http://stackoverflow.com/comment/82726909
type: Question
has title: How to add csrf token in django with js only without ajax?
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/82737305
score: 0
tagged with: javascript
has comment: http://stackoverflow.com/comment/82726814

cron
tags question: http://stackoverflow.com/q/47890464
tags question: http://stackoverflow.com/q/47969544
tags question: http://stackoverflow.com/q/47994631
tags question: http://stackoverflow.com/q/48000835
tags question: http://stackoverflow.com/q/47994466
tags question: http://stackoverflow.com/q/47897875
type: Tag
tag name: cron
tags question: http://stackoverflow.com/q/47955558
tags question: http://stackoverflow.com/q/47868306
tags question: http://stackoverflow.com/q/47964034

http://stackoverflow.com/a/47935340
score: 7
upvote count: 7
has body: The None dimension in the shape tuple refers to the batch dimension which simply means that the layer can accept input of any size. For example, a dataset (e.g. MNIST) could have the following shape tuple (60000, 28, 28, 1) but the input layer's shape would be (None, 28, 28, 1). References: keras-team/keras#2054 Keras Documentation - Core Layers
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47935253
type: Answer
accepted answer of: http://stackoverflow.com/q/47935253

http://stackoverflow.com/q/47955667
has answer: http://stackoverflow.com/a/47963410
has comment: http://stackoverflow.com/comment/82880772
tagged with: pyqt5
has body: I have two Forms. I need to get text from (lineedit) in Ui_Mainwindow1 and make label in Ui_MainWindow2 with that text. and this two forms in two seprate files Can anyone please explain how can update label in (Ui_MainWindow2) with the text in (lineedit) in (Ui_Mainwindow1) when i press on pushbutton in (Ui_MainWindow1) &gt; class Ui_MainWindow1(object): &gt; def setupUi(self, MainWindow): &gt; MainWindow.setObjectName("MainWindow") &gt; self.lineEdit = QtWidgets.QLineEdit(self.centralwidget) &gt; self.lineEdit.setGeometry(QtCore.QRect(130, 70, 181, 21)) &gt; self.lineEdit.setObjectName("lineEdit") &gt; self.pushButton = QtWidgets.QPushButton(self.centralwidget) &gt; self.pushButton.setGeometry(QtCore.QRect(140, 100, 161, 23)) &gt; self.pushButton.setObjectName("pushButton") &gt; self.retranslateUi(MainWindow) &gt; QtCore.QMetaObject.connectSlotsByName(MainWindow) &gt; &gt; def retranslateUi(self, MainWindow): &gt; _translate = QtCore.QCoreApplication.translate &gt; MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) &gt; self.pushButton.setText(_translate("MainWindow", "update")) &gt; &gt; &gt; if __name__ == "__main__": &gt; import sys &gt; app = QtWidgets.QApplication(sys.argv) &gt; MainWindow = QtWidgets.QMainWindow() &gt; ui = Ui_MainWindow1() &gt; ui.setupUi(MainWindow) &gt; MainWindow.show() &gt; sys.exit(app.exec_()) class Ui_MainWindow2(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(410, 165) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(160, 40, 111, 21)) self.label.setText("") self.label.setObjectName("label") self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) if __name__ == "_…
type: Question
has comment: http://stackoverflow.com/comment/82880983
score: 0
linked to: http://stackoverflow.com/q/22916570
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: PYQT Application with python

http://stackoverflow.com/q/47953045
has comment: http://stackoverflow.com/comment/82877905
has answer: http://stackoverflow.com/a/47953105
has body: As a newbie python programmer, I've been doing some exercises, but I don't understand why this code will not work for me. Now my exercise is this: Define and test a function named removeDuplicates(somelist) that removes all duplicates from a given list and returns the remaining elements as a list while keeping the original order. Also define a main() function that calls on the removeDuplicates function for the given command line argument and prints the resulting list. And here is my code so far: import sys def main(): userInput = int(input("")) removeDuplicates(somelist) print (unique) def removeDuplicates(userInput): duplicate = set() unique = [] for x in userInput: if x not in duplicate: unique.append(x) duplicate.add(x) print (unique) def removeDuplicates(somelist): duplicate = set() unique = [] for line in sys.stdin: line = line.rstrip() if x not in sys.stdin: unique.append(x) duplicate.add(x) return unique if __name__ =='__main__': main() And I keep getting error codes no matter what I do. The error code for this code is: Traceback (most recent call last): File "removeDuplicates.py", line 31, in &lt;module&gt; main() File "removeDuplicates.py", line 5, in main removeDuplicates(somelist) NameError: name 'somelist' is not defined`
tagged with: python
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47953147
type: UnansweredQuestion
downvote count: 1
has comment: http://stackoverflow.com/comment/82875381
type: Question
score: -1
has title: Removing duplicates code debugging
answer count: 2
upvote count: 0

http://stackoverflow.com/a/47873445
has comment: http://stackoverflow.com/comment/82712382
has body: You can use a recursive function to drill down to the strings that are nested in your input data structure. def replace_ids(obj, new_ids=None): if new_ids is None: new_ids = {} if isinstance(obj, dict): return {key: replace_ids(value, new_ids) for key, value in obj.items()} if isinstance(obj, list): return [replace_ids(item, new_ids) for item in obj] if isinstance(obj, str): if obj not in new_ids: new_ids[obj] = generate_new_id() return new_ids[obj] return obj generate_new_id is a function that should determine how you want to generate new ids.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82712758
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/47873033
has comment: http://stackoverflow.com/comment/82713146
accepted answer of: http://stackoverflow.com/q/47873033
has comment: http://stackoverflow.com/comment/82712443

http://stackoverflow.com/a/47983231
accepted answer of: http://stackoverflow.com/q/47983017
has comment: http://stackoverflow.com/comment/82935613
has comment: http://stackoverflow.com/comment/82935725
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47983017
has comment: http://stackoverflow.com/comment/82935797
type: Answer
has comment: http://stackoverflow.com/comment/82935602
has comment: http://stackoverflow.com/comment/82935559
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82935281
has comment: http://stackoverflow.com/comment/82936014
has body: If you run processText() with None instead of date then you get total number of minutes when it was down total_down, start = processText(data, None) and you can use it to calculate percentage. percentage = (down/total_down) * 100 and you can use string formatting {:.2f} to display only two digits after dot def calculate(): all_dates = entry.get().split(',') print(all_dates) all_dates = [date.strip() for date in all_dates] # calculate total number of minutes when it was down total_down, start = processText(data, None) # &lt;-- None print('total_down:', total_down) txt = '' for current_date in all_dates: down, start = processText(data, current_date) # calculate percetage percentage = (down/total_down) * 100 # use string formatting {:.2f} to display only two digits after dot txt += "Total Downtime is {} min from {} ({:.2f}%)\n".format(down, start, percentage) textVar.set(txt) If you want total number of minutes when it was down or up then you have to change processText and add new parameter (ie. word) which will check if direction is DOWN or UP or both (word = None) def processText(lines, selected_date, word="DOWN"): total = 0 start = None print(selected_date) # if there is `selected_date` then convert to `datetime` if selected_date: try: selected_date = datetime.datetime.strptime(selected_date, "%d.%m.%Y") except AttributeError as ex: print("ERROR:", ex) selected_date = None # calculate time for direction, t1, t2, seconds in lines: if not word or word == direction: # if `selected_date` then filter times if selected_date and t1 &lt;= selected_date: continue if not start: start = t1.strftime("%d.%m.%Y %H:%M:%S") total += seconds # convert to minutes after summing all second total = total//60 return total, start def calculate(): all_dates = entry.get().split(',') print(all_dates) all_dates = [date.strip() for date in all_dates] # calculate total number of minutes when it was down and up total_down, start = processText(data, None, None) print('total_down:', total_down) tx…

http://stackoverflow.com/a/61109551
type: Answer
answers question: http://stackoverflow.com/q/47990985
has comment: http://stackoverflow.com/comment/138738732
score: 3
upvote count: 3
downvote count: 0
has body: Just for next ones arriving here. Followed instructions here: https://superset.incubator.apache.org/installation.html#middleware But not working: TOO MANY REDIRECTS. Flask App-Builder code here: https://github.com/dpgaspar/Flask-AppBuilder/blob/167c13ec6dda6e7d8286e590233cd603a7d13928/flask_appbuilder/security/views.py#L728 Finally made my own custom remote login (Draft version below). # Apache superset REMOTE_USER authentication # https://superset.incubator.apache.org/installation.html#middleware from flask_appbuilder.security.manager import AUTH_REMOTE_USER # Define AUTH_TYPE # AUTH_TYPE = AUTH_REMOTE_USER # Allow users to auto register and be assigned to Remote role # AUTH_USER_REGISTRATION = True # AUTH_USER_REGISTRATION_ROLE = "Remote" # For testing without a proxy just calling http://localhost:9000/superset/welcome?logme=user1 from flask import request, g from flask_login import login_user, logout_user import logging # Middleware to extract user from header HTTP_X_PROXY_REMOTE_USER # and place it at REMOTE_USER class RemoteUserLogin(object): def __init__(self, app): self.app = app def log_user(self, environ): from superset import security_manager as sm username = self.get_username(environ) logging.info("REMOTE_USER Checking logged user") if hasattr(g, "user") and \ hasattr(g.user, "username"): if g.user.username == username: logging.info("REMOTE_USER user already logged") return g.user else: logout_user() user = sm.find_user(username=username) logging.info("REMOTE_USER Look up user: %s", user) if user: logging.info("REMOTE_USER Login_user: %s", user) login_user(user) return user def get_username(self, environ): user = environ.pop('HTTP_X_PROXY_REMOTE_USER', None) if not user and self.app.debug: # Dev hack user = environ.get("werkzeug.request").args.get("logme") if user: logging.error("Logging user from request. Remove me ASAP!!!: %s", user) environ['REMOTE_USER'] = user return user def before_request(self): user = self.log_user(request.environ) if not user: ra…

http://stackoverflow.com/q/47880010
has comment: http://stackoverflow.com/comment/82725983
has body: I have a for loop which is going through multiple dictionaries and adding the values under common keys. The input dictionary has keys that are strings and values that are int's. For some reason its adding the values as lists of one value (e.g. {"01":[12],[44]}). I want it to add the int on its own but cant get that working for some reason. I'm using the code below, is there something i am missing ? dw = defaultdict() dw = {} for key, value in listb.items(): dw[key].append(value)
has comment: http://stackoverflow.com/comment/82726266
has answer: http://stackoverflow.com/a/47880717
upvote count: 1
has comment: http://stackoverflow.com/comment/82727761
has answer: http://stackoverflow.com/a/47880071
has comment: http://stackoverflow.com/comment/82726301
favorite count: 0
has title: int values in dict appending as list
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82726007
has comment: http://stackoverflow.com/comment/82726023
answer count: 4
has answer: http://stackoverflow.com/a/47880138
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/82726064
has comment: http://stackoverflow.com/comment/82727050
has answer: http://stackoverflow.com/a/47880287
type: Question

http://stackoverflow.com/a/47892727
has comment: http://stackoverflow.com/comment/82753023
upvote count: 2
type: Answer
score: 2
has body: Here's a simple method based on list comprehensions: x = ['For,IN', ....] y = [w.split(',')[0] for w in x if ',NN' in w] It basically iterates over all words, takes only those that contain ",NN" and cuts out the part before the comma.
answers question: http://stackoverflow.com/q/47892689
has comment: http://stackoverflow.com/comment/82752936
downvote count: 0

twilio-api
tags question: http://stackoverflow.com/q/47928852
tag name: twilio-api
type: Tag

http://stackoverflow.com/a/47979796
has body: There's a way to run Python on JVM, it's called Jython. With that, you can call Java objects' methods from Python code. OTOH I have doubts that the Coursera course would alow you to submit code for some non-trivial setup. I'd ask them first. Also, porting a bit of Java code to Python should not be too hard, provided this code is an exercise, not industry-grade.
type: Answer
has comment: http://stackoverflow.com/comment/82928370
has comment: http://stackoverflow.com/comment/82928361
score: 0
answers question: http://stackoverflow.com/q/47979723
has comment: http://stackoverflow.com/comment/82929165

http://stackoverflow.com/q/47947094
type: UnansweredQuestion
score: 1
upvote count: 1
type: Question
tagged with: morelikethis
answer count: 1
downvote count: 0
has body: Is it possible to query multiple elasticsearch indices simultaneously when searching with a more_like_this query? I am constructing my queries in python, but I do not believe it matters. Here is the body for calling a single index: { "query": { "more_like_this": { "fields": [ "Title", "Description" ], "like": { "_id": "62546841", "_index": "puppies", "_type": "puppies_little" } } } } ... and here is the curl call: curl -XPOST http://machineName:9200/puppies/_search?pretty=true -d
favorite count: 0
tagged with: elasticsearch
tagged with: python
has answer: http://stackoverflow.com/a/47947700
has title: more_like_this elasticsearch query of multiple indices

http://stackoverflow.com/q/47974349
tagged with: coroutine
type: Question
has comment: http://stackoverflow.com/comment/82918211
tagged with: tornado
has comment: http://stackoverflow.com/comment/82918268
answer count: 2
score: 2
possible better answer: http://stackoverflow.com/a/78909168
downvote count: 0
tagged with: asynchronous
has answer: http://stackoverflow.com/a/78909168
has body: I wrote a helper decorator for Tornado RequestHandler: def return_response(method): @wraps(method) async def wrapper(self, *args, **kwargs): response = method(self, *args, **kwargs) if inspect.isawaitable(response): response = await response self.set_status(response.status) self.write(response.body) return wrapper For some reason it fails with the following error: Traceback (most recent call last): File ".../.venv/lib/python3.6/site-packages/tornado/web.py", line 1511, in _execute result = yield result File ".../.venv/lib/python3.6/site-packages/tornado/gen.py", line 1055, in run value = future.result() File ".../.venv/lib/python3.6/site-packages/tornado/concurrent.py", line 238, in result raise_exc_info(self._exc_info) File "&lt;string&gt;", line 4, in raise_exc_info File ".../.venv/lib/python3.6/site-packages/tornado/gen.py", line 307, in wrapper yielded = next(result) File "&lt;string&gt;", line 6, in _wrap_awaitable File ".../src/http_handlers/decorators.py", line 106, in wrapper response = await response File ".../src/http_handlers/decorators.py", line 106, in wrapper response = await response File ".../src/http_handlers/decorators.py", line 106, in wrapper response = await response [Previous line repeated 959 more times] File ".../src/http_handlers/decorators.py", line 104, in wrapper response = method(self, *args, **kwargs) RecursionError: maximum recursion depth exceeded in comparison This error appeares only when the application is up for a while. Is it a bug in Python, Tornado or my code is wrong? Did somebody come across the same problem? Update I've managed to solve the problem. It was in completely different place. I used to apply this decorator at runtime in the __new__ method. By mistake I was applying it to methods of the cls, not the actual instance. So methods were being wrapped again each time a new instance af a class was created.
favorite count: 0
has comment: http://stackoverflow.com/comment/82918246
upvote count: 2
has answer: http://stackoverflow.com/a/47974453
tagged with: python
linked to: http://stackoverflow.com/q/3323001
has title: "RecursionError: maximum recursion depth exceeded in comparison" in async function
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47974453

http://stackoverflow.com/comment/82992910
type: Comment
has text: Can you help me understand how you're performing this assignment? What is a Buddy? Describe, at a high level, the problem you're trying to solve?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48012084

http://stackoverflow.com/comment/119517780
type: AnswerComment
comment on: http://stackoverflow.com/a/48009142
type: Comment
score: 1
has text: A follow-up question on this: so you're saying we shouldn't call optimizer.zero_grad() when training RNN models such as LSTM, for example?

http://stackoverflow.com/comment/82955745
score: 1
type: QuestionComment
has text: I don't understand how you get two or three sevens in some of your result lists.
comment on: http://stackoverflow.com/q/47993740
type: Comment

http://stackoverflow.com/comment/82803311
type: AnswerComment
comment on: http://stackoverflow.com/a/47916844
score: 0
type: Comment
has text: I see. Thanks for the info. From your answer I was able to use unit vector of unit_vector = np.cos(np.radians(-phi-90)), -np.sin(np.radians(-phi-90)), then from the coordinate of x (starting point), keep incrementing the starting coord (and rounding/int) with the unit vector and check if the matrix value in that coord is '1'. Do it until you find '1' or its out of bounds. Basically keep moving down the line of the unit vector until you hit a '1' or its out of bounds. You think that would be faster? Since your solution evaluates all 1s and if the array is quite large, it could be slower

http://stackoverflow.com/comment/82861303
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47945728
has text: yes, i see that.so the program doesnt run at all..

http://stackoverflow.com/q/47988332
has answer: http://stackoverflow.com/a/47988655
accepted answer: http://stackoverflow.com/a/47988655
has body: I would like to implement a transparent IMAPS (SSL/TLS) proxy from zero using python (pySocks and imaplib). The user and the proxy are in the same network and the mail server is outside (example: gmail servers). All the traffic on port 993 is redirected to the proxy. The user should retrieve his emails using his favorite email application (example: thunderbird). The proxy should receive the commands and transmit it to the user/server and should be able to read the content of the retrieved emails. However, as the traffic is encrypted, I don't know how to get the account and the password of the user (without using a database) OR how to read the content of the emails without knowing the account and the password of the user. After few days looking for a solution, I still don't have any track. Maybe it is not possible ? If you have any track, I would be happy to read it. Thank you.
type: Question
tagged with: imap
score: 0
has title: Transparent IMAPs proxy
answer count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/82714987
score: 0
comment on: http://stackoverflow.com/q/47874207
type: Comment
type: QuestionComment
has text: http://pytorch.org/docs/master/notes/broadcasting.html

http://stackoverflow.com/a/47877779
score: 5
type: Answer
has comment: http://stackoverflow.com/comment/82722428
type: AcceptedAnswer
upvote count: 5
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47877691
has body: Try changing the line to this: &lt;img src="{{url_for('static', filename=hist)}}" alt="{{hist}}"&gt; You had an extra set of {{ }} in there which was rendering as %7B and %7D.
answers question: http://stackoverflow.com/q/47877691
has comment: http://stackoverflow.com/comment/82722528

http://stackoverflow.com/a/47894320
upvote count: 1
has comment: http://stackoverflow.com/comment/82758846
answers question: http://stackoverflow.com/q/47893201
downvote count: 0
has comment: http://stackoverflow.com/comment/82758702
type: Answer
has body: I have dealt with this same issue a few times, I have found that most the time you can move to the element first and then issue the .click() command: Element = driver.find_element_by_link_text('link') actions = ActionChains(driver) # try this actions.move_to_element(Element) # or this driver.execute_script("return arguments[0].scrollIntoView();", Element) Element.click() EDIT: Or, a third option for click in case the top two do not work, if you can get the element with selenium and the element is in view, but just can't interact with it, then it's probably behind a &lt;div that is not visible. Try this click instead of your normal .click(): driver.execute_script("arguments[0].click()", Element) If that does not work, you may need to try interacting with the attributes to get the element in a state of visibility for selenium before you make the click, such as: driver.execute_script("arguments[0].style.display = 'block'", Element)
score: 1

http://stackoverflow.com/a/47964408
accepted answer of: http://stackoverflow.com/q/47963996
type: Answer
has body: In answer to your questions: a) They use different representations for numbers. Most numbers in R are represented as double precision floating point values. These are all 64 bits long, and give about 15 digit precision throughout the range, which goes from -double.xmax to double.xmax, then switches to signed infinite values. R also uses 32 bit integer values sometimes. These cover the range of roughly +/- 2 billion. R chooses these types because it is geared towards statistical and numerical methods, and those rarely need more precision than double precision gives. (They often need a bigger range, but usually taking logs solves that problem.) Python is more of a general purpose platform, and it has types discussed in MichaelChirico's comment. b) Besides Brobdingnag, the gmp package can handle arbitrarily large integers. For example, &gt; as.bigz(2)^1500 Big Integer ('bigz') : [1] 35074662110434038747627587960280857993524015880330828824075798024790963850563322203657080886584969261653150406795437517399294548941469959754171038918004700847889956485329097264486802711583462946536682184340138629451355458264946342525383619389314960644665052551751442335509249173361130355796109709885580674313954210217657847432626760733004753275317192133674703563372783297041993227052663333668509952000175053355529058880434182538386715523683713208549376 &gt; nchar(as.character(as.bigz(2)^1500)) [1] 452 I imagine the as.character() call would also be needed with Brobdingnag.
downvote count: 0
has comment: http://stackoverflow.com/comment/82898608
score: 7
answers question: http://stackoverflow.com/q/47963996
has comment: http://stackoverflow.com/comment/82898508
upvote count: 7
type: AcceptedAnswer

database
tags question: http://stackoverflow.com/q/47995701
tags question: http://stackoverflow.com/q/47911608
tags question: http://stackoverflow.com/q/47879952
tags question: http://stackoverflow.com/q/47919913
type: Tag
tags question: http://stackoverflow.com/q/47898271
tags question: http://stackoverflow.com/q/47862345
tags question: http://stackoverflow.com/q/47857955
tags question: http://stackoverflow.com/q/47960299
tag name: database
tags question: http://stackoverflow.com/q/47862032
tags question: http://stackoverflow.com/q/47967921
tags question: http://stackoverflow.com/q/48009021
tags question: http://stackoverflow.com/q/47927910
tags question: http://stackoverflow.com/q/47926891
tags question: http://stackoverflow.com/q/47936526
tags question: http://stackoverflow.com/q/47928883
tags question: http://stackoverflow.com/q/47958892
tags question: http://stackoverflow.com/q/47915247
tags question: http://stackoverflow.com/q/47990958
tags question: http://stackoverflow.com/q/47911968
tags question: http://stackoverflow.com/q/47947912

http://stackoverflow.com/comment/82747578
score: 0
type: Comment
type: QuestionComment
has text: You can create a computed field with the format that you want
comment on: http://stackoverflow.com/q/47890399

http://stackoverflow.com/q/47964611
has answer: http://stackoverflow.com/a/47964652
score: -6
favorite count: 0
has answer: http://stackoverflow.com/a/47964658
tagged with: python
has title: KeyError in String Formatting of Raw Input
downvote count: 6
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47964652
possible better answer: http://stackoverflow.com/a/47964658
has comment: http://stackoverflow.com/comment/82898863
type: Question
has comment: http://stackoverflow.com/comment/82898856
has body: name = raw_input("kemal ") quest = raw_input("To learn python ") color = raw_input("Blue i guess ") print "Ah, so your name is {name}, your quest is {quest}, " \ "and your favorite color is {color}.".format(name, quest, color) I can't find what's wrong with this code. Python says " KeyError: 'name' " when I run it.
has comment: http://stackoverflow.com/comment/82898849
has comment: http://stackoverflow.com/comment/82899125
answer count: 2
upvote count: 0

http://stackoverflow.com/comment/82751065
comment on: http://stackoverflow.com/q/47892006
score: 0
type: QuestionComment
type: Comment
has text: What do you mean by "it's not writing into the file"? Is the file being created but not populated? Also, you seem to be using imports that are not provided here. Please provide the full code for your [mcve]

http://stackoverflow.com/comment/82936919
type: Comment
comment on: http://stackoverflow.com/a/47983871
score: 0
type: AnswerComment
has text: Your last line should probably be `crnt.setdefault(getattr(item, last_index), []).append(item)`

http://stackoverflow.com/comment/83178725
comment on: http://stackoverflow.com/a/47948376
type: AnswerComment
score: 0
type: Comment
has text: Devil is usually in the details. Its hard to see the details without the code. You almost certainly made more than 2 line change to your code. Also, I highly recommend following the style of tensorflow tutorials. For example, use the Dataset API instead of queues, runners, coordinators. It is much simpler.

http://stackoverflow.com/comment/82967602
type: AnswerComment
comment on: http://stackoverflow.com/a/47999504
type: Comment
has text: Yes. Let me rephrase it. When I will unpickle the object I can only have one Point definition which has to be the new/ custom object which supports y variable. So I need to somehow define a class which is compatible with the already pickled objects. Makes sense?
score: 0

http://stackoverflow.com/a/47929255
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82827246
has body: You wrote while (iteration&lt;1): and never assign any value to iteration after initialization with 0, and you never broke the while loop, obviously your script will never terminate !
has comment: http://stackoverflow.com/comment/82827141
type: Answer
answers question: http://stackoverflow.com/q/47929181

http://stackoverflow.com/a/47986375
accepted answer of: http://stackoverflow.com/q/47986344
upvote count: 7
has body: To remove 2 random elements, sample 2 random elements, then remove them: a.difference(random.sample(a, 2)) or just sample two elements less than the size of the set: set(random.sample(a, len(a) - 2)) If you want a destructive operation (so that a changes), you can use difference_update on it instead: a.difference_update(random.sample(a, 2))
answers question: http://stackoverflow.com/q/47986344
score: 7
has comment: http://stackoverflow.com/comment/82941690
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/47891918
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47890550
type: Answer
has body: Since you are calculating the difference betwen matrix rows we are trying to vectorize the following double for loop a = numpy.arange(25).reshape(5, 5) y = numpy.zeros(5, 5) for i in range(len(a)): for j in range(len(a)): y[i, j] = numpy.linalg.norm(a[i, :] - a[j, :]) The first step is to vectorize the row difference a[i, :] - a[j, :] # difference between rows `i` and `j` by calculating the "outer diffence" of your matrix rows, which yields a 3D tensor: x = a[:, None, :] - a[None, :, :] x.shape # (5, 5, 5) Afterwards, the difference of rows i and j can be found in the corresponding positions in the tensor: x[i, j, :] # difference between rows `i` and `j` And the loop becomes for i in range(len(a)): for j in range(len(a)): y[i, j] = numpy.linalg.norm(x[i, j, :]) However since we are now only iterating over the first two axes of x we can substitute the double loop with a vectorized call to numpy.linalg.norm(): y = numpy.linalg.norm(x, axis=-1) and get the distance of rows i and j again in the corresponding position y[i, j] # distance between rows `i` and `j`
downvote count: 0

http://stackoverflow.com/comment/82915776
type: QuestionComment
comment on: http://stackoverflow.com/q/47972967
type: Comment
has text: I do not understand you, explain better please, it would be great if you put images of what you get and what you want to obtain.
score: 0

http://stackoverflow.com/a/47908824
has body: The longest key in all matches. A sorted with lambda may help. This gets each match in a list of lists and uses sorted and key=lambda... on the length of the 1st item in each list (which is the saved key name). It will sort shortest key name to longest. Get the last list and the last item of that list to get the value of value1. MY_D = { "first_k": "first_v", "sec_k": "sec_v", "some_key_name_that_includes_others": "value1", "some_other_key": "value2", "last_k": "last_v" } key_I_am_looking_for = "some" # List of lists of matches. value = list([k, v] for k, v in MY_D.items() if key_I_am_looking_for in k) # Sort by index 0 of each inner list. key_len = sorted(value, key=lambda l: len(l[0])) # Last list is longest index 0 so get last item of that list. print('longest:', key_len[-1][-1])
type: Answer
answers question: http://stackoverflow.com/q/47905078
score: 0

http://stackoverflow.com/comment/89967753
type: AnswerComment
has text: As a reference, I deleted consecutive points that are too similar to their neighbors by following code. `newPointsFiltered = newPoints[1:][~ (np.sum(np.diff(newPoints, axis=0) ** 2, axis=1) < 1e-4)]`
type: Comment
comment on: http://stackoverflow.com/a/47949170
score: 0

http://stackoverflow.com/comment/82907387
comment on: http://stackoverflow.com/q/47968535
type: Comment
type: QuestionComment
score: 1
has text: This is an odd thing to test. `as_view` returns a new callable object each time, and without any other instructions objects are compared by id. What's the point of testing this?

http://stackoverflow.com/a/47928968
type: Answer
has body: The error is saying that you do not have the package cStringIO. To resolve this use following: pip install cStringIO if this does not help, try: pip install StringIO Here is more documentation about the packages StringIO and cStringIO https://docs.python.org/2/library/stringio.html
answers question: http://stackoverflow.com/q/47928845
score: 0

http://stackoverflow.com/q/47864265
score: 1
tagged with: hough-transform
linked to: http://stackoverflow.com/q/47342025
tagged with: scikit-image
tagged with: image-processing
has title: How would I detect the angle of these two lines?
type: Question
upvote count: 1
accepted answer: http://stackoverflow.com/a/47867294
has comment: http://stackoverflow.com/comment/82696835
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47867294
tagged with: python
tagged with: opencv
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82693556
has body: As you can see in the picture a cone is generated when a person is using maps. I would like to know if it is possible to detect the two outer-lines of the cones like this but the ultimate goal is to use this information to find the angles at which the lines are at. I was following this tutorial on hough-transform but end up with this. Looking for an easier way to find the angles if possible. import numpy as np from skimage.transform import hough_line from scipy import misc import matplotlib.pyplot as plt from matplotlib import cm image = misc.imread("cone.jpg", flatten=True) # Classic straight-line Hough transform h, theta, d = hough_line(image) # Generating figure 1 fig, axes = plt.subplots(1, 3, figsize=(9, 3), subplot_kw={'adjustable': 'box-forced'}) ax = axes.ravel() ax[0].imshow(image, cmap=cm.gray) ax[0].set_title('Input image') ax[0].set_axis_off() ax[1].imshow(np.log(1 + h), extent=[np.rad2deg(theta[-1]), np.rad2deg(theta[0]), d[-1], d[0]], cmap=cm.gray, aspect=1/1.5) ax[1].set_title('Hough transform') ax[1].set_xlabel('Angles (degrees)') ax[1].set_ylabel('Distance (pixels)') ax[1].axis('image') ax[2].imshow(image, cmap=cm.gray) for _, angle, dist in zip(*hough_line_peaks(h, theta, d)): y0 = (dist - 0 * np.cos(angle)) / np.sin(angle) y1 = (dist - image.shape[1] * np.cos(angle)) / np.sin(angle) ax[2].plot((0, image.shape[1]), (y0, y1), '-r') ax[2].set_xlim((0, image.shape[1])) ax[2].set_ylim((image.shape[0], 0)) ax[2].set_axis_off() ax[2].set_title('Detected lines') plt.tight_layout() plt.show()
downvote count: 0

http://stackoverflow.com/q/47957018
has body: I am looking to schedule my python script runs with jenkins. The issue is, my scripts use a lot of libs like pandas etc that are installed on my mac terminal. Is there a way to allow Jenkins to pick up these modules (or run the scripts as if it was terminal)? Also is there a way to run Python3 in jenkins? I have already configured Jenkins to execute from custom workspace and have tried both shell and plugin executions.
tagged with: jenkins
type: UnansweredQuestion
upvote count: 1
tagged with: python
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/47958630
score: 0
has title: Running Python Scripts with Jenkins
answer count: 1
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/82694662
has text: yes, but the off-by-one index issue is probably there for j as well. And my question was "is there a loop in the code you're showing?" because AFAIR a loop is `DO I in 1,5` ... the python version has a loop, the fortran code doesn't seem to have a loop.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47864617

http://stackoverflow.com/q/47900696
type: Question
tagged with: gzip
downvote count: 0
has body: Is there a way to list all files without extracting all the files? AFAIK, current tools can list dirs/files, but can't handle nested archives. E.g., can I list all the files in archive.tar.gz, and extract only file4 w/o extracting all the files? I think theoretically it can be done by parsing the archive headers and extracting desired files only, but before I start to do this from scratch, I'd like to know if there are any existing tools/libs to do this. Thanks. archive.tar.gz |----file1 |----dir1 | |----file2 |----archive1.tar |----file3 |----archive2.tar.bz2 |----file4
has answer: http://stackoverflow.com/a/49883831
answer count: 1
tagged with: 7zip
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: php-ziparchive
score: 3
has title: List or extract file from recursive archived file without fully extraction
upvote count: 3
has comment: http://stackoverflow.com/comment/82768044
has comment: http://stackoverflow.com/comment/82803222

http://stackoverflow.com/comment/82722134
type: QuestionComment
score: 0
has text: The while loop is in the first code section of the text.The point of the invalid input is to check whether the loop properly functions, because the assignment demands that the user enter filenames until he enters a non-existent one.
comment on: http://stackoverflow.com/q/47877945
type: Comment

http://stackoverflow.com/q/47917242
has comment: http://stackoverflow.com/comment/82802641
tagged with: algorithm
tagged with: greedy
has title: Greedy algorithm Python - code hitting infinite loop
type: Question
score: 0
answer count: 2
tagged with: infinite-loop
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/47917381
has comment: http://stackoverflow.com/comment/82802685
favorite count: 0
has comment: http://stackoverflow.com/comment/82802513
linked to: http://stackoverflow.com/q/21895756
has answer: http://stackoverflow.com/a/47917355
tagged with: python
has body: I am trying to write a greedy algorithm in python 3. The premise is to take change, owed by user, as input and them give them as few coins as possible. Available coins are: Quarters (0.25); Dimes(0.1); Nickels (0.05); and Pennies (0.01). My code currently ends up in an infinite loop and i don't know what i am doing wrong. Can anyone see where i am going wrong with the following code? Code: validacion = False pennies = 0.01 nickels = 0.05 dimes = 0.1 quarters = 0.25 coinCounter = 0 penniesCounter = 0 nickelsCounter = 0 dimesCounters = 0 quartersCounter = 0 cambio = False while validacion is False: changeOwed = float(input("Change owed: ")) if changeOwed &gt; 0: validacion = True else: validacion = False while cambio is False: if changeOwed &gt; dimes and changeOwed &lt;= quarters: coinCounter += 1 quartersCounter += 1 changeOwed -= quarters if changeOwed == 0.0: cambio = True elif changeOwed &gt; nickels and changeOwed &lt;= dimes: coinCounter += 1 nickelsCounter += 1 changeOwed -= nickels if changeOwed == 0.0: cambio = True elif changeOwed &gt; pennies and changeOwed &lt;= nickels: coinCounter += 1 dimesCounters += 1 changeOwed -= dimes if changeOwed == 0.0: cambio = True else: coinCounter += 1 penniesCounter += 1 changeOwed -= pennies if changeOwed == 0.0: cambio = True print(coinCounter)
has comment: http://stackoverflow.com/comment/82802704
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82802570
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82802571
has comment: http://stackoverflow.com/comment/82802602

http://stackoverflow.com/a/66967177
score: 8
has comment: http://stackoverflow.com/comment/124639265
has comment: http://stackoverflow.com/comment/124639302
has comment: http://stackoverflow.com/comment/124616835
downvote count: 0
has body: Default Google search address start doesn't contain # symbol. Instead, it should have ? and /search pathname: ---> https://google.com/#q= ---> https://www.google.com/search?q=cake Make sure you're passing user-agent into HTTP request headers because the default requests user-agent is python-requests and sites could identify that it's a bot and block the request thus you would receive a different HTML with some sort of an error that contains different elements/selectors which is the reason you were getting an empty result. Check what's your user-agent, and a list of user-agents for mobile, tablets, etc. Pass user-agent in request headers: headers = { 'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36' } requests.get('YOUR_URL', headers=headers) Code and example in the online IDE: from bs4 import BeautifulSoup import requests, json, lxml headers = { 'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36' } # https://requests.readthedocs.io/en/latest/user/quickstart/#passing-parameters-in-urls params = { 'q': 'tesla', # query 'gl': 'us', # country to search from 'hl': 'en' # language } # https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts html = requests.get("https://www.google.com/search", headers=headers, params=params, timeout=30) soup = BeautifulSoup(html.text, 'lxml') data = [] for result in soup.select('.tF2Cxc'): title = result.select_one('.DKV0Md').text link = result.select_one('.yuRUbf a')['href'] # sometimes there's no description and we need to handle this exception try: snippet = result.select_one('#rso .lyLwlc').text except: snippet = None data.append({ 'title': title, 'link': link, 'snippet': snippet }) print(json.dumps(data, indent=2, ensure_ascii=False)) ------------- ''' [ { "title": "Tesla: Electric Cars, Solar & Clean Energy", "link": "https://www.tesla.com/", "snippet": "Tesla is accelera…
upvote count: 8
type: Answer
has comment: http://stackoverflow.com/comment/125247714
has comment: http://stackoverflow.com/comment/124592817
answers question: http://stackoverflow.com/q/47928608

http://stackoverflow.com/comment/82865593
comment on: http://stackoverflow.com/a/47943218
type: Comment
score: 0
type: AnswerComment
has text: There might indeed be another solution to this but they always told me : 'first make it work, then make it better'. At the moment, it's the only thing that I can think of.

http://stackoverflow.com/q/47966494
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/47966567
accepted answer: http://stackoverflow.com/a/47966575
has title: Need help on trying to add the len(item) as an index.
answer count: 3
has comment: http://stackoverflow.com/comment/82903387
has comment: http://stackoverflow.com/comment/82902961
has comment: http://stackoverflow.com/comment/82902607
possible better answer: http://stackoverflow.com/a/47966567
score: -2
favorite count: 0
downvote count: 2
has answer: http://stackoverflow.com/a/47966686
tagged with: web-scraping
tagged with: python
has body: I'm trying to scrape some data and I think I found the solution but I'm struggling with writing the code for it. # This returns a list that changes depending on the page description = response.xpath('.//*[@class="txtGrey size14-description"]/text()').extract() I need to get the exact len(description) and have that length added as an index for the description (not sure if I am using the word index correctly) So for example description = response.xpath('.//*[@class="txtGrey size14-description"]/text()').extract() len(description) if length of description is 4 the code needs to say description = response.xpath('.//*[@class="txtGrey size14-description"]/text()').extract()[-4:] note: I need the '-' and ':' in there. I will be scraping through several pages so the len is always changing. I'm assuming I need to write a new function for this. Any help will be appreciated.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47966575
tagged with: scrapy

http://stackoverflow.com/comment/82928163
score: 0
type: Comment
has text: Now it makes sense. Thanks for the edit.
type: QuestionComment
comment on: http://stackoverflow.com/q/47977346

http://stackoverflow.com/a/51224706
upvote count: 1
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/47937256
has body: I had a similar problem... I was only able to fix it by downloading Visual Studio Build tools and installing the Visual C++ Build Tools, Windows 10 SDK, and VC++ 2015.3 v14
answers question: http://stackoverflow.com/q/47937256
type: AcceptedAnswer

wpf
tags question: http://stackoverflow.com/q/47953638
tags question: http://stackoverflow.com/q/47964151
type: Tag
tag name: wpf
tags question: http://stackoverflow.com/q/47954644
tags question: http://stackoverflow.com/q/48013569

http://stackoverflow.com/q/47907555
tagged with: python
type: AnsweredQuestion
tagged with: pipe
has comment: http://stackoverflow.com/comment/82782740
has title: Retrieve stderr from a python program in a c++ one
accepted answer: http://stackoverflow.com/a/47909711
tagged with: traceback
type: Question
score: 2
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/82782619
answer count: 1
tagged with: stderr
tagged with: c++
has answer: http://stackoverflow.com/a/47909711
upvote count: 2
has body: I'm currently trying to launch a file written in python from my C++ program with the pstream library (http://pstreams.sourceforge.net/). My code look like this: QStringList res; QStringList resErrors; // run a process and create a streambuf that reads its stdout and stderr redi::pstream proc(cmd, redi::pstreams::pstdout | redi::pstreams::pstderr); std::string line; // read child's stdout while (std::getline(proc.out(), line)) res.append(QString::fromStdString(line)); // read child's stderr while (std::getline(proc.err(), line)) resErrors.append(QString::fromStdString(line)); Usually I correctly receive out and err message from any command entered in the pstream constructor. But if I try to execute a python file that raise a traceback I don't have any output (in stdout or in stderr). For example, this python file: #!/usr/bin/env python test = 5 / 0 print "test" will no print "test" in stdout and nothing in stderr. But if I execute it in a terminal, I correctly got: Traceback (most recent call last): File "test.py", line 3, in &lt;module&gt; test = 5 / 0 ZeroDivisionError: integer division or modulo by zero In both case I used the same command: "python test.py" I guess I need to tell to python to print its traceback to stderr? But why it isn't done in a subprocess ? Or can it be a bug in the library? Another possibility that I have in mind is that I read the stdout and stderr too early and python hadn't the time to write in it. But I have tried to add a sleep function before read it, without any effect.

http://stackoverflow.com/comment/82853500
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47939933
has text: I am not sure, sorry. The only other thing that comes to mind is something like this https://packaging.python.org/guides/multi-version-installs/ if you had a previous install leftover but I don't know if it would cause this error or not.

http://stackoverflow.com/q/47945809
downvote count: 1
answer count: 1
tagged with: apache-spark-sql
tagged with: pyspark
has body: I am currently struggling with implementing a Spark-y way to do an operation with PySpark. I have a large DataFrame (of ~ 500,000 rows) with the following structure ID DATE CHANGE POOL ----------------------------- 1 ID1 DATE1 CHANGE1 POOL1 2 ID2 DATE2 CHANGE2 POOL2 3 ID3 DATE3 CHANGE3 POOL3 4 ID4 DATE4 CHANGE4 POOL4 .... where IDs are unique, DATEs are not necessarily equidistant from each other (and could potentially be repeating), CHANGEs could be any number of float type (usually, but not always, between, say, -500.0 to +500.0), and POOLs can be either an empty list [] or a non-empty list of varied length, depending on the specific row. We can safely assume that the DataFrame is sorted by DATE. I want to replace the empty lists in the POOL column via the following operation. I am only considering events within a window of W days (say, W is 180 days). For a row with an empty POOL, I note the DATE of that row I select all the rows from the original DataFrame which fall within a window of W days in the past from the date mentioned in step 1. From this subset, I collect the list of all CHANGEs (possibly with collect_list() function). I assign this list to the POOL column corresponding to the row mentioned in step 1. I tried to (partially) achieve this with window functions as follows (I can safely remove the line with partitionBy()) POOL_DAYS = 180 days = lambda i: i * 86400 window_glb = Window\ .partitionBy()\ .orderBy(col('DATE').cast('long'))\ .rangeBetween(-days(POOL_DAYS), 0) df = df.withColumn('POOL', collect_list('CHANGE').over(window_glb)) but it is crashing with this error Py4JJavaError: An error occurred while calling o1859.collectToPython. : org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 203.1 failed 4 times, most recent failure: Lost task 0.3 in stage 203.1 (TID 6339, xxxxxxxxxx.com, executor 1): java.lang.IllegalArgumentException: Size exceeds Integer.MAX_VALUE which, to me, looks like a running-out-of-memory issue. T…
has answer: http://stackoverflow.com/a/48153533
type: AnsweredQuestion
has title: Applying an operation (whose result depends on the information in the entire DataFrame) on certain rows of the DataFrame in PySpark
score: 1
accepted answer: http://stackoverflow.com/a/48153533
favorite count: 0
type: Question
upvote count: 2
tagged with: python

http://stackoverflow.com/a/47883064
type: Answer
has body: You could create a shell script that uses python 3.5 if it is installed, otherwise uses python 3 and executes your script with the correct version. No need for python shebang. In your shell script you may test if which python3.5 returns something; if it does, then python3.5 is installed, otherwise you'd have to use python3
has comment: http://stackoverflow.com/comment/82732906
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47882916
downvote count: 0

http://stackoverflow.com/comment/82986435
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48008774
has text: Modify you answer so that it grab all keys like `list(capitals.keys())` . It will be compatible with both 2.7 and 3.x
type: AnswerComment

http://stackoverflow.com/q/47985956
upvote count: 3
has answer: http://stackoverflow.com/a/52969689
has comment: http://stackoverflow.com/comment/82943200
has comment: http://stackoverflow.com/comment/83376973
has comment: http://stackoverflow.com/comment/82946444
type: Question
has comment: http://stackoverflow.com/comment/82942250
has comment: http://stackoverflow.com/comment/82942412
tagged with: win32com
has body: Environment Windows 10 + python 3.6.3 64 bit (also tried 32 bit). I am a python developer trying to use COM for (nearly) the first time and hit this huge blocker. Problem I have had various errors when trying to use an IRTDServer implemented in a dll (not written by me), via either win32com or comtypes. Using win32com turned out to be more difficult. I have an included an example unittest for both libraries below. Accessing the server from Excel 2016 works as expected; this returns the expected value: =RTD("foo.bar", , "STAT1", "METRIC1") Code using win32com library Here is a simple test case which should connect to the server but doesn't. (This is just one version, as I have changed it many times trying to debug the problem.) from unittest import TestCase class COMtest(TestCase): def test_win32com(self): import win32com.client from win32com.server.util import wrap class RTDclient: # are these only required when implementing the server? _com_interfaces_ = ["IRTDUpdateEvent"] _public_methods_ = ["Disconnect", "UpdateNotify"] _public_attrs_ = ["HeartbeatInterval"] def __init__(self, *args, **kwargs): self._comObj = win32com.client.Dispatch(*args, **kwargs) def connect(self): self._rtd = win32com.client.CastTo(self._comObj, 'IRtdServer') result = self._rtd.ServerStart(wrap(self)) assert result &gt; 0 def UpdateNotify(self): print("UpdateNotify() callback") def Disconnect(self): print("Disconnect() called") HeartbeatInterval = -1 _rtd = RTDclient("foo.bar") _rtd.connect() Result: Traceback (most recent call last): File "env\lib\site-packages\win32com\client\gencache.py", line 532, in EnsureDispatch ti = disp._oleobj_.GetTypeInfo() pywintypes.com_error: (-2147467263, 'Not implemented', None, None) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "test\test.py", line 23, in test_win32com _rtd.connect() File "test\test.py", line 16, in connect self._rtd = win32com.client.CastTo(dispatch, 'IRtdServer') File "env\lib…
answer count: 3
tagged with: com
tagged with: pywin32
has answer: http://stackoverflow.com/a/47990433
downvote count: 0
has comment: http://stackoverflow.com/comment/82946690
has comment: http://stackoverflow.com/comment/83376998
favorite count: 0
has comment: http://stackoverflow.com/comment/82941358
has answer: http://stackoverflow.com/a/79366159
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83343591
has comment: http://stackoverflow.com/comment/82941412
score: 3
tagged with: comtypes
has title: How to use COM from python win32com or comtypes to access an IRTDServer?

http://stackoverflow.com/q/47878919
answer count: 1
has answer: http://stackoverflow.com/a/47890409
tagged with: calculator
has comment: http://stackoverflow.com/comment/82723958
tagged with: python
tagged with: user-input
type: AnsweredQuestion
tagged with: pycharm
has title: Multiple inputs are needed for a basic calculator before resetting
has comment: http://stackoverflow.com/comment/82724301
has body: My program is almost complete but I can't seem to allow the... "Would you like to do more calculations? Enter (Y) for yes, or any ""other character for no. " ...output from going through without first entering my selection (e.g. "Y" or any other character") numerous times. Output I would really appreciate some help! """My First Program!!!""" # Modules: import time # Provides time-related functions # Delayed text to give it a "Turing" feel def calculator_print(*args, delay=1): print(*args) time.sleep(delay) # Operations: def add(num1, num2): # Returns the sum of num1 and num2 return num1 + num2 def sub(num1, num2): # Returns the difference of num1 and num2 return num1 - num2 def mul(num1, num2): # Returns the product of num1 and num2 return num1 * num2 def div(num1, num2): # Returns the quotient of num1 and num2 try: return num1 / num2 except ZeroDivisionError: # Handles division by zero calculator_print("Division by zero cannot be done. You have broken the universe. Returning zero...") return 0 def exp(num1, num2): # Returns the result of num1 being the base and num2 being the exponent return num1 ** num2 # Run operational functions: def run_operation(operation, num1, num2): # Determine operation if operation == 1: calculator_print("Adding...\n") calculator_print(num1, "+", num2, "=", add(num1, num2)) elif operation == 2: calculator_print("Subtracting...\n") calculator_print(num1, "-", num2, "=", sub(num1, num2)) elif operation == 3: calculator_print("Multiplying...\n") calculator_print(num1, "*", num2, "=", mul(num1, num2)) elif operation == 4: calculator_print("Dividing...\n") calculator_print(num1, "/", num2, "=", div(num1, num2)) elif operation == 5: calculator_print("Exponentiating...\n") calculator_print(num1, "^", num2, "=", exp(num1, num2)) else: calculator_print("I don't understand. Please try again.") def main(): # Ask if the user wants to do more calculations or exit: def restart(response): # uses "in" to check multiple values, # a replacement for (respon…
type: Question
has comment: http://stackoverflow.com/comment/82723962
accepted answer: http://stackoverflow.com/a/47890409
score: 0

linphone-sdk
tag name: linphone-sdk
type: Tag
tags question: http://stackoverflow.com/q/47865475

http://stackoverflow.com/a/47936216
has body: Use the key named argument for list.sort to use the file attribute of each tag as the key for sorting: key specifies a function of one argument that is used to extract a comparison key from each list element (for example, key=str.lower). The key corresponding to each item in the list is calculated once and then used for the entire sorting process. The default value of None means that list items are sorted directly without calculating a separate key value. import xml.etree.ElementTree xml_string = r'''<?xml-stylesheet type='text/xsl' href='image_metadata_stylesheet.xsl'?> imglab dataset Created by imglab tool. groundpainting_hotstar groundpainting_yesbank groundpainting_vodafone sightscreen_pepsi ''' root = xml.etree.ElementTree.fromstring(xml_string) images_root = root.find('images') images = images_root.findall('image') images.sort(key = lambda x: x.attrib['file']) images_root[:] = images print(xml.etree.ElementTree.tostring(root)) Alternate solution using lxml based off of this answer that points out that lxml serializes attributes in the order they are set (unlike xml): import lxml.etree xml_string = r'''<?xml-stylesheet type='text/xsl' href='image_metadata_stylesheet.xsl'?> imglab dataset Created by imglab tool. lol groundpainting_hotstar groundpainting_yesbank groundpainting_vodafone sightscreen_pepsi ''' root = lxml.etree.fromstring(xml_string) images_root = root.find('images') images = images_root.findall('image') images.sort(key = lambda x: x.attrib['file']) images_root[:] = images print(lxml.etree.tostring(root)) Note: This will remove any child (immediate descendant) of that is not a .
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47936003
answers question: http://stackoverflow.com/q/47936003
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/82846423
score: 1
has comment: http://stackoverflow.com/comment/82845924

http://stackoverflow.com/q/47940360
has comment: http://stackoverflow.com/comment/82855144
downvote count: 1
has comment: http://stackoverflow.com/comment/82858556
type: Question
has title: how to open windows explorer with search result from python
has comment: http://stackoverflow.com/comment/82855406
has comment: http://stackoverflow.com/comment/82858093
has comment: http://stackoverflow.com/comment/82855068
tagged with: windows
has body: I have created a File indexer and searcher script in python which indexes all files which could be used later for fast search . I want to open the search result in windows explorer . I know subprocess.Popen(r'explorer /select,"C:\path\of\folder\file") this command execution will open a specified directory . I have also read https://support.microsoft.com/en-us/help/314853/explorer-exe-command-line-options-for-windows-xp https://answers.microsoft.com/en-us/windows/forum/windows_7-performance/windows-7-explorerexe-command-line-switches/ad7242df-566a-4378-913c-920393f6e674?auth=1 How to do it ??
tagged with: shell
tagged with: windows-explorer
favorite count: 0
tagged with: command-line
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82854666
tagged with: python
score: 2
answer count: 0
upvote count: 3

http://stackoverflow.com/a/47987770
upvote count: 5
accepted answer of: http://stackoverflow.com/q/47987707
score: 5
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: How about you convert the list to a set before you start converting? Set-lookups are faster than linear search in lists. input_set = set(input) Once you have it, you can use regular dict-comprehension, in my opinion: output = {key: [x for x in value if x in input_set] for key, value in master_dict.items()} Result: output == {'KeyB': ['Foo', 'Bar', 'Dog'], 'KeyA': ['Aron'], 'KeyZ': ['Foo', 'Bar']}
answers question: http://stackoverflow.com/q/47987707

http://stackoverflow.com/comment/82755744
type: Comment
has text: Where are you exactly changing the car positions ? I don't see you are changing car's x and y anywhere.. are you missing something on update or am i missing something.. ? In short, am i missing where you are using waypoints in car.py or main.py ?
score: 0
comment on: http://stackoverflow.com/q/47894415
type: QuestionComment

http://stackoverflow.com/q/48000475
has title: Django raising ValueError: invalid literal for int() with base 10 on POST
tagged with: django
type: AnsweredQuestion
tagged with: django-models
type: Question
has answer: http://stackoverflow.com/a/48000742
answer count: 1
has comment: http://stackoverflow.com/comment/82969628
score: 0
accepted answer: http://stackoverflow.com/a/48000742
has comment: http://stackoverflow.com/comment/82969632
tagged with: python
has body: Django is consistently throwing a ValueError on every POST request to the server. From cruising around forms and SE, it seems like this an issue with my Django models. However, I'm not sure why the models would throw this error or why they would be called by Django since this is thrown in a POST event. View in question: def channel(request, channel): user_form = weblog_userForm(request.POST or None) if request.method == 'POST' and user_form.is_valid(): nickname = user_form.cleaned_data['nickname'] message = user_form.cleaned_data['message'] password = user_form.cleaned_data['password'] postDetails = {} ... process request and eventually ... return HttpResponse(json.dumps(postDetails), content_type="application/json") My application models: class Line(models.Model): message = models.TextField(blank=True, default="") nick = models.CharField(max_length=50) hostname = models.CharField(max_length=300) channel = models.CharField(max_length=200) timestamp = models.DateTimeField(auto_now_add=True) LINE_TYPES = ( ('PMSG', 'PRIVMSG'), ('SMSG', 'SOCKETMSG'), ('WMSG', 'WEBMSG'), ('NTCE', 'NOTICE'), ('ACTN', 'ACTION'), ('JOIN', 'JOIN'), ('PART', 'PART'), ('QUIT', 'QUIT'), ('NICK', 'NICK'), ('TPIC', 'TOPIC'), ) msgType = models.CharField(max_length=4, choices=LINE_TYPES, default='PRIVMSG') def __str__(self): return self.message class banned_ips(models.Model): bannedIp = models.GenericIPAddressField() Traceback: Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/django/weblogs/log/views.py", line 96, in channel json_data = …

http://stackoverflow.com/q/48011275
has title: Custom User model fields (AbstractUser) not showing in django admin
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48013640
downvote count: 0
has answer: http://stackoverflow.com/a/60084208
accepted answer: http://stackoverflow.com/a/48013640
has answer: http://stackoverflow.com/a/64777161
type: Question
upvote count: 29
has body: I have extended User model for django, using AbstractUser method. The problem is, my custom fields do not show in django admin panel. My models.py: from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_bot_flag = models.BooleanField(default=False) My admin.py: from django.contrib.auth.admin import UserAdmin from .models import User admin.site.register(User, UserAdmin) Thanks
has comment: http://stackoverflow.com/comment/82991495
has comment: http://stackoverflow.com/comment/82992836
has comment: http://stackoverflow.com/comment/82992156
possible better answer: http://stackoverflow.com/a/60084208
answer count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/69491631
score: 29
tagged with: django
tagged with: python

http://stackoverflow.com/a/47993718
has body: This looks like you're looking for a match or submatch of the user name. Given the error message provided, a submatch doesn't seem to make sense, so I'll assume an exact match is actually needed. If you do want a submatch, use the .includes() method on username const username = "master"; const FORBIDDEN_USERNAME_LIST = ['admin', 'master', 'owner']; const match = FORBIDDEN_USERNAME_LIST.some(n =&gt; n === username); if (match) { console.log(username, 'exists'); }
upvote count: 2
has comment: http://stackoverflow.com/comment/82956917
answers question: http://stackoverflow.com/q/47993617
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/q/48009130
type: Question
tagged with: twitch
downvote count: 0
score: 1
tagged with: connection
favorite count: 0
type: UnansweredQuestion
tagged with: irc
has body: I'm writing a Twitch bot and it will only send one message to server. When executing code below "Connected" shows up in Twitch chat, "Testing" does not. import socket HOST = "irc.chat.twitch.tv" PORT = 6667 NICK = "mybot" PASS = 'oauth:mytoken' CHANNEL = "mychannel" def send_message(msg): s.send(bytes("PRIVMSG #" + CHANNEL + " :" + msg + "\r\n", "UTF-8")) s = socket.socket() s.connect((HOST, PORT)) s.send(bytes("PASS " + PASS + "\r\n", "UTF-8")) s.send(bytes("NICK " + NICK + "\r\n", "UTF-8")) s.send(bytes("JOIN #" + CHANNEL + " \r\n", "UTF-8")) send_message("Connected") send_message("Testing")
tagged with: python
answer count: 0
upvote count: 1
has title: Python IRC bot will only send 1 message

http://stackoverflow.com/comment/82776375
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/47904293
has text: Maybe [`start_new_session=True`](https://docs.python.org/3/library/subprocess.html#subprocess.Popen) when creating the process does what you need?

http://stackoverflow.com/comment/82944509
has text: `/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/difflib.py:433: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal a[besti-1] == b[bestj-1]:`
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47987913

http://stackoverflow.com/q/47984583
has comment: http://stackoverflow.com/comment/82938100
duplicate of: http://stackoverflow.com/q/20449427
tagged with: for-loop
has title: Why is Python not recognizing the newly inserted keys and values in the updated dictionary?
has body: The exercise I'm currently taking has three different dictionaries. What I wanted to do was update the first dictionary with keys and values from the other two with two different for loops like this. def give_me_new(dic1, dic2, dic3): for key, value in dic2.items(): dic1.update({key:value}) for k, v in dic3.items(): dic1.update({k:v}) After I updated, I housed all the keys inside a variable. some_keys = dic1.keys() What I decided to do was utilize a while loop to check to see if the key exists inside the dictionary. I created it like this value = False while value == False: check_key = input('Lets check to see if key has been updated: ') if check_key not in some_keys: input('Nope, not in there. Press enter to try again') elif check_key in some_keys: return 'It is in there', dic1 value = True However, each time the input is prompted and the value is entered, it keeps showing that the key is not in there. What exactly happened inside the entire function created to cause this issue to come up? Down below is the entire script created, please let me know what exactly I've done wrong. def give_me_new(dic1, dic2, dic3): for key, value in dic2.items(): dic1.update({key:value}) for k, v in dic3.items(): dic1.update({k:v}) some_keys = dic1.keys() value = False while value == False: check_key = input('Lets check to see if key has been updated: ') if check_key not in (some_keys): input('Nope, not in there. Press enter to try again') elif check_key in (some_keys): return 'It is in there', dic1 value = True print(give_me_new({1:10, 2:20}, {3:30, 4:40}, {5:50,6:60}))
score: 0
tagged with: while-loop
tagged with: python
has comment: http://stackoverflow.com/comment/82938572
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82938113
answer count: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/82938104

http://stackoverflow.com/comment/82931843
has text: You're creating a dictionary, but you're presumably *accessing* a list: `obj`. If you want proper help, you should show the data you are trying to use.
comment on: http://stackoverflow.com/q/47981693
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82762449
has text: Yes and I gave you the same answer: use `for i, file_i in enumerate(files)`... this will remove the tuple error. (and of course use `file_i` everywhere instead of `file`)
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47897662
type: AnswerComment

http://stackoverflow.com/comment/82869309
comment on: http://stackoverflow.com/q/47949404
score: 0
type: QuestionComment
has text: @ateesdalejr Oh! That is a very good idea! Thanks for the hint! I have not thought about that. :-)
type: Comment

http://stackoverflow.com/a/47898958
has comment: http://stackoverflow.com/comment/82891440
type: Answer
has body: I find no indication that this library is meant to work with archive.org, or that it works with archive.org. Both [1][2] lists of sources contain no mention of either archive.org or web.archive.org. I downloaded the entire repository to search the source code, and it also contains no mention of either Internet Archive domain. From what I can tell based on this file, the articles attribute is based on RSS/ATOM feeds. I don't think Internet Archive archives those, and even if it does, since they would link back to the live version of the site, some changes in the library itself would be needed to get them to work with Internet Archive. You've already opened an issue, where you specify it doesn't work at all (even on single articles -- this is probably an issue elsewhere, such as in the node scoring algorithm it uses to decide which nodes contain the article) so if you don't want to dive into the library source code and fix it yourself, all you can do is wait.
upvote count: 2
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82981277
answers question: http://stackoverflow.com/q/47887618
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47887618
has comment: http://stackoverflow.com/comment/82892487

http://stackoverflow.com/q/47928561
has answer: http://stackoverflow.com/a/47928661
has comment: http://stackoverflow.com/comment/82825608
type: Question
duplicate of: http://stackoverflow.com/q/14932247
possible better answer: http://stackoverflow.com/a/47928643
upvote count: 12
has answer: http://stackoverflow.com/a/47928643
duplicate of: http://stackoverflow.com/q/15728321
score: 10
has answer: http://stackoverflow.com/a/47928628
favorite count: 0
linked to: http://stackoverflow.com/q/41853132
tagged with: string-formatting
downvote count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/47928628
has title: Python - Using a variable as part of string formatting
duplicate of: http://stackoverflow.com/q/41853132
answer count: 4
has answer: http://stackoverflow.com/a/47928646
has body: I want to be able to use a int variable instead of the number (5) used in the code below. I hope there is a way or else I will have to put my code within if blocks which I am trying to avoid if possible (I don't want it to go through a condition everytime in my loop). my_array[1, 0] = '{0:.5f}'.format(a) Is there a way for me to write the code below using a variable like: x = 5 my_array[1, 0] = '{0:.xf}'.format(a)
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82825848
has comment: http://stackoverflow.com/comment/82825783

http://stackoverflow.com/q/47952503
favorite count: 0
tagged with: django-2.0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82876013
has answer: http://stackoverflow.com/a/47960735
downvote count: 3
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/82876290
has comment: http://stackoverflow.com/comment/82876340
has answer: http://stackoverflow.com/a/47954587
has body: django noobie. ive been going through tutorials but in urlpatterns they use url instead of path which is now introduced in django 2.0 i want to make /appname/anything-gibberish take the user back to the view im giving in /appname/ urlpatterns = [ path('', views.index, name='index'), path('contact/', views.contact, name='contact'), ] i want 127.0.0.1:8000/contact/asaskhask to go to views.contact is there any way to do this without using url and regular expression?
upvote count: 3
score: 0
has title: how to switch to path instead of url in urlpatterns [django]
answer count: 2

http://stackoverflow.com/comment/82829909
type: Comment
comment on: http://stackoverflow.com/a/47883299
score: 0
type: AnswerComment
has text: Hi sorry to post again but couldn't find a way to private message you. I have used convert and that has increased speed by over 500% and completely fixed my problem thanks. I am rewriting the body code and was not sure if it is bad to keep resetting the self.image or the current code is fine( changing the loading to global variables). Thanks

odoo
tags question: http://stackoverflow.com/q/47922948
tags question: http://stackoverflow.com/q/47905986
tags question: http://stackoverflow.com/q/48006292
tags question: http://stackoverflow.com/q/48006887
tags question: http://stackoverflow.com/q/47981276
tags question: http://stackoverflow.com/q/47889929
tags question: http://stackoverflow.com/q/48010835
tags question: http://stackoverflow.com/q/47886193
tags question: http://stackoverflow.com/q/47890399
tags question: http://stackoverflow.com/q/47910644
tags question: http://stackoverflow.com/q/47982933
type: Tag
tags question: http://stackoverflow.com/q/47951097
tags question: http://stackoverflow.com/q/47892006
tags question: http://stackoverflow.com/q/47878070
tags question: http://stackoverflow.com/q/47938134
tags question: http://stackoverflow.com/q/47893915
tags question: http://stackoverflow.com/q/47929216
tag name: odoo
tags question: http://stackoverflow.com/q/47922657

http://stackoverflow.com/a/47912388
has comment: http://stackoverflow.com/comment/82792467
has comment: http://stackoverflow.com/comment/82792521
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/82792841
has comment: http://stackoverflow.com/comment/82793266
has body: It gets called when that type of object gets created, so you can do whatever class-specific initialization is needed, and don't have to remember to make a separate initialization call. That is what it is used for; that is what purpose it serves.
answers question: http://stackoverflow.com/q/47912318

http://stackoverflow.com/comment/82722744
has text: Restore from backup. We can't tell what's going on from just this, and diagnosing your system over a long back-and-forth tech support "try this" "okay that didn't work" "show me the output of this command" "what's in this file" isn't the kind of thing we do here.
comment on: http://stackoverflow.com/q/47878060
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82850196
has text: Your code looks fine. I agree with @Sami that the hanging issue is probably something else. Please [edit] your question with more details: client OS, SQL Server version, ODBC driver version, connection string, etc..
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47931861

http://stackoverflow.com/q/47959217
has answer: http://stackoverflow.com/a/47959253
tagged with: python
type: AnsweredQuestion
upvote count: 1
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/47959253
tagged with: numpy
has title: Sort 2D NumPy array by one of the columns
tagged with: arrays
tagged with: sorting
score: 0
has body: I though this would be super easy but I am struggling a little. I have a data structure as follows array([[ 5. , 3.40166205], [ 10. , 2.72778882], [ 15. , 2.31881804], [ 20. , 2.50643777], [ 1. , 3.94076063], [ 2. , 3.80598599], [ 3. , 3.67121134], [ 6. , 3.2668874 ], [ 7. , 3.13211276], [ 8. , 2.99733811], [ 9. , 2.86256347], [ 11. , 2.64599467], [ 12. , 2.56420051], [ 13. , 2.48240635], [ 14. , 2.4006122 ], [ 16. , 1.8280531 ], [ 17. , 1.74625894], [ 18. , 1.66446479], [ 19. , 1.58267063], [ 20. , 1.50087647]]) And I want to sort it ONLY on the first column ... so it is ordered as follows: array([[1. , 3.9], [2. , 3.8], ... , [20. , 1.5]]) np.sort doesn't seem to work as it moves array to a flat structure. I've also used itemgetter from operator import itemgetter sorted(data, key=itemgetter(1)) But this doesn't give me the output I'm looking for. Help appreciated!
answer count: 1
linked to: http://stackoverflow.com/q/2828059
favorite count: 0

http://stackoverflow.com/q/47945785
tagged with: machine-learning
tagged with: python
has answer: http://stackoverflow.com/a/47954571
has comment: http://stackoverflow.com/comment/82878449
tagged with: set
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/82872358
has title: Pythonic way of finding the overlapping elements
accepted answer: http://stackoverflow.com/a/47954571
tagged with: python-2.7
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/82861381
score: 1
favorite count: 0
type: Question
has body: I have 2 regex which are extracting data and classifying them as feature-1 and feature-2 but in few scenarios the data gets classified as both feature-1(f1) and feature-2(f2). ex : Amazon is 100 years old. 100 years old is classified as f1 and 100 years is classified as f2. and when its displayed on the UI. it gets displayed as 100 years old 100 years is wrong as only 100 years old needs to be displayed. In order to handle the superset and subset. I am trying to traverse through each feature and comparing if their is a overlapping feature f2. This code is working but its a huge performance hit if there are 25000 features to process. `if df.iloc[i]['section_id'] == section_id and st_pos != -1: start_pos.append(st_pos) end_pos.append(en_pos) list.append(df.iloc[i]['id']) ''' In the below loop, the positions are stored in set form, If any subset found, then store it to list_subset ''' for i in range(0,len(start_pos)-1): for j in range(i+1,len(start_pos)): if set(range(start_pos[i],end_pos[i])).issubset(range(start_pos[j],end_pos[j])): list_subset.append(list[i]) elif set(range(start_pos[j],end_pos[j])).issubset(range(start_pos[i],end_pos[i])): list_subset.append(list[j])` Is their a better way to do this code pythonically?

http://stackoverflow.com/a/47861792
answers question: http://stackoverflow.com/q/47861773
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82688940
has body: json.loads() would convert the true to the Python's boolean True (conversion table for the reference). You just need to check for the truthiness of the testResult value instead of comparing it with a string 'True': if testResult: print("IF: success flag is TRUE") else: print("IF: success flag is FALSE") In other words, here is what happened when you compared testResult to a 'True' string: In [1]: testResult = True In [2]: testResult == 'True' Out[2]: False
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/82688811
accepted answer of: http://stackoverflow.com/q/47861773

http://stackoverflow.com/comment/82908674
type: Comment
type: QuestionComment
has text: The above error occurs when i try to provide a range of date.Also to add once I select and run the file and calculate downtime , 2nd time on same it doesn't allow me to run a another file , I need to close the program and then run again for a new file downtime calculation
comment on: http://stackoverflow.com/q/47965487
score: 0

http://stackoverflow.com/comment/82721774
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47876444
has text: It worked, thank you :) the one issue I now have is that apparently reading the file written file the response.content is stored as a so I need to convert the html to pdf

http://stackoverflow.com/q/47909873
type: UnansweredQuestion
has title: How to write a Tornado listener correctly?
tagged with: python
tagged with: listener
answer count: 0
type: Question
tagged with: tornado
score: 0
has comment: http://stackoverflow.com/comment/82800624
has body: I wanted to write a server background listener to listen to dozens of clients sending commands to this background listener on TCP port 8888. Command format is "http://myip/?c="ClientCommand=A5" Those clients could be sending commands at the same time or different time. Also, these clients will stay connected and sending few different commands until disconnect by client themselves. All the commands received by the background listener will be written to a MySQL DB. After few days of study, I found Python + Tornado framework could be a good tool to do this. However, I have tried few days with examples from the web and I still don't know how to program this background listener. Here is an example I found on a blog and it worked...How do I modify the code below to do the background listener? I know I need to use GET to get parameters from the URL. I have tried get(self.get), but I got error of invalid syntax... Thanks for your help. import tornado.ioloop import tornado.web class IndexHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, Tornado!") if __name__ == "__main__": application = tornado.web.Application([ (r"/", IndexHandler) ]) application.listen(8888) tornado.ioloop.IOLoop.current().start()
has comment: http://stackoverflow.com/comment/82787727

http://stackoverflow.com/comment/82724448
score: 0
comment on: http://stackoverflow.com/q/47878765
type: QuestionComment
type: Comment
has text: Nope- tried both "writer.writerows[myData]" and "writer.writerows([myData])"

http://stackoverflow.com/comment/82830671
comment on: http://stackoverflow.com/q/47930889
score: 0
type: Comment
type: QuestionComment
has text: numpy is not working for strings :(

http://stackoverflow.com/comment/82950333
score: 0
type: Comment
type: QuestionComment
has text: From which library does the `Path` class come from?
comment on: http://stackoverflow.com/q/47990952

http://stackoverflow.com/comment/82844003
type: Comment
type: QuestionComment
has text: @Banana of course, that than I have more functions where I define that **car** and I call the function, but it still keeps telling me the same error.
comment on: http://stackoverflow.com/q/47937240
score: 0

http://stackoverflow.com/a/47955953
type: Answer
has comment: http://stackoverflow.com/comment/82890384
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/47955849
has comment: http://stackoverflow.com/comment/82888230
has comment: http://stackoverflow.com/comment/82891290
has body: There is problem in that your view not found Comentario by slug field. Does your ajax { 'slug' : $(this).attr('titulo') ... correct? You sure that 'titulo' is correct field for slug or it must be $(this).attr('slug')? try this one : $.ajax("/home/like/",{ type: "POST", url: "{% url 'home:like' %}", data: {'slug': $(this).attr('name'), 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: "json", success: function(response) { alert(' likes count is now ' + response.likes_count); }, error: function(rs, e) { alert(rs.responseText); } });
upvote count: 1

http://stackoverflow.com/q/47996725
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82961637
has comment: http://stackoverflow.com/comment/82961642
has title: 'TemplateDoesNotExist at /' error during local development
type: Question
has comment: http://stackoverflow.com/comment/82975379
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82975088
has answer: http://stackoverflow.com/a/48003746
has body: I am following two scoops of django and mozilla tutorial for deploying my app. I set up a virtual env and base setting, local setting,etc and when i ran the command : ./manage.py runserver 0:8000 --settings=Books.settings.local the browser showed the error, template home not found... I think there might be some problem due to the env, i am not sure. base.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '2z9y' # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' ALLOWED_HOSTS = ['127.0.0.1', 'localhost','https://hackingonlineeducation.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #third party apps 'star_ratings', 'crispy_forms', #my_apps 'newsletter', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Books.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Boo…
type: UnansweredQuestion

http://stackoverflow.com/a/61303961
answers question: http://stackoverflow.com/q/47942417
has body: If your solution demands classification instead of regression then I will suggest you use non-continuous label list like [0,1,2,3] and create a one-to-one mapping with the original label list.
score: 0
type: Answer

http://stackoverflow.com/comment/109289074
type: Comment
has text: exactly, so maybe I miss understood your point... I found your question with the will to do exactly what you just said, so I had to add the async word in front of the wrapper in my case. Anyway, for your question purpose, without the 'async' syntax is the way!
comment on: http://stackoverflow.com/q/47876407
score: 0
type: QuestionComment

http://stackoverflow.com/q/47881433
duplicate of: http://stackoverflow.com/q/8929284
has title: Difference between list and set of integers for time efficiency
tagged with: python
linked to: http://stackoverflow.com/q/8929284
has body: This code works time efficiently but if I replace the two lines with comment lines (assigning value to A and B), it takes much more time to pass certain test cases. constraints: n,m in range(10^5), any integer in arr is in range(10^9) Please explain. n, m = input().split() arr=list(map(int,input().split())) A = set(map(int,input().split())) #list(map(int,input().split())) B = set(map(int,input().split())) #list(map(int,input().split())) count=0 for i in range(len(arr)): if arr[i] in A: count+=1 elif arr[i] in B: count+=-1 print(count)
tagged with: python-3.x
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/12354515
has answer: http://stackoverflow.com/a/47881510
score: 1
has comment: http://stackoverflow.com/comment/82728864
type: Question
has comment: http://stackoverflow.com/comment/82728849
upvote count: 1
downvote count: 0
answer count: 1
favorite count: 0
duplicate of: http://stackoverflow.com/q/12354515

http://stackoverflow.com/comment/82691404
comment on: http://stackoverflow.com/q/47863243
type: QuestionComment
type: Comment
has text: TypeError: 'function' object is not iterable
score: 0

http://stackoverflow.com/comment/82826225
score: 0
comment on: http://stackoverflow.com/a/47928814
has text: Right. To have it both ways: `q.strip('D') if 'strip' in dir(q) else f(q)`.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/82890957
comment on: http://stackoverflow.com/q/47960597
score: 0
type: Comment
type: QuestionComment
has text: and how would I put that into actual code?

http://stackoverflow.com/comment/82894354
has text: @COLDSPEED I'm sorry about that! Fixing that now to include all of my code. I was trying to keep it as brief as possible.
type: Comment
comment on: http://stackoverflow.com/a/47962504
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82742774
type: AnswerComment
type: Comment
has text: @ErikSteiner Cheers, it's a common gotcha for all comers with python.
comment on: http://stackoverflow.com/a/47888095
score: 0

http://stackoverflow.com/comment/82832018
comment on: http://stackoverflow.com/a/47929916
score: 0
type: Comment
has text: Maybe we need another class with a githab to connect two ellipses with a line?
type: AnswerComment

http://stackoverflow.com/a/48013013
has body: Normally PyCharm does what you want, unless the Ctrl+Click leads you to a C function. In this case you will get only minimal information on the function signature and return value, etc., just like you show in your post. built-ins are mainly written in C for an efficiency reason, so if you want to see the C code you'll have to download CPython source code and dive into it. Another alternative would be to download the PyPy source code and take a look at it. Still, you can use PyCharm to read code from modules written in Python in the standard library and that would be helpful in your learning process. Believe me, you'll find good quality code there.
answers question: http://stackoverflow.com/q/47900611
downvote count: 0
score: 6
type: Answer
upvote count: 6

http://stackoverflow.com/comment/82821073
has text: Also be aware that the OP is askig about a Django model class, which behaves differently in this regard compared to normal Python classes. See https://docs.djangoproject.com/en/2.0/ref/models/meta/#django.db.models.options.Options.get_field on how to access the field of a Django model.
type: AnswerComment
comment on: http://stackoverflow.com/a/47926473
type: Comment
score: 1

http://stackoverflow.com/q/47935108
has comment: http://stackoverflow.com/comment/82839992
has comment: http://stackoverflow.com/comment/82839724
accepted answer: http://stackoverflow.com/a/47935293
has body: I can't figure out how to call a function from a tkinter Frame. I'm trying to implement a method that would protect the information from the App in case it's closed unintentionally. Could someone please help ? from tkinter import Tk, Frame, Label class MyApp(Tk): def __init__(self, *args, **kwargs): Tk.__init__(self, *args, **kwargs) container = Frame(self) container.pack(side="top", fill="both", expand = True) frame = StartPage(container, self) frame.grid(row=0, column=0, sticky='nsew') frame.tkraise() class StartPage(Frame): def __init__(self, parent, controller): Frame.__init__(self,parent) Label(self, text="close this window from the X in the corner").grid(row=1,column=1) def Stop(self): print('exiting') app = MyApp() if __name__=='__main__': try: app.mainloop() finally: OpenApp = MyApp() OpenClass = StartPage(parent, OpenApp) OpenClass.Stop() I can't call the "Stop" function when closing tkinter. I get a NameError: name 'parent' is not defined. What should I put instead of "parent" ? If using the root.protocol("WM_DELETE_WINDOW", root.iconify) the function inside the class still has to be called.
answer count: 1
has comment: http://stackoverflow.com/comment/82840329
score: -2
favorite count: 0
tagged with: tkinter
has comment: http://stackoverflow.com/comment/82840234
downvote count: 2
has title: Can't call a function from Tkinter Frame
tagged with: python
linked to: http://stackoverflow.com/q/111155
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47935293
has comment: http://stackoverflow.com/comment/82839780
type: Question
has comment: http://stackoverflow.com/comment/82839976
has comment: http://stackoverflow.com/comment/82840497
upvote count: 0

http://stackoverflow.com/comment/82870117
comment on: http://stackoverflow.com/q/47950259
score: 4
type: QuestionComment
type: Comment
has text: It sounds like you're talking about _overwriting_ the output on a line. In that case, look into something like the *curses* library: https://docs.python.org/3/howto/curses.html

http://stackoverflow.com/comment/82781571
has text: Maybe I should rewrite the n, m, h methods in some way?
comment on: http://stackoverflow.com/q/47907076
score: 0
type: Comment
type: QuestionComment

sdn
tags question: http://stackoverflow.com/q/47944124
tag name: sdn
type: Tag

http://stackoverflow.com/a/47904473
type: Answer
has body: When you groupby you can aggregate in multiple ways simultaneously. Using erocoar's example dataframe: import pandas as pd games = pd.DataFrame(data={'Home': ['A', 'B', 'A', 'A', 'B'], 'Away': ['B', 'C', 'C', 'B', 'A'], 'Home Score': [0, 1, 4, 3, 0], 'Away Score': [1, 2, 2, 1, 1]}) games['Home Win'] = (games['Home Score'] &gt; games['Away Score']).astype(int) summary = games.groupby('Home').agg({'Home Win': 'sum', 'Home': 'count'}) summary['Home Win Ratio'] = summary['Home Win'] / summary['Home'] Will give you the output: Home Win Home Home Win Ratio Home A 2 3 0.666667 B 0 2 0.000000
score: 2
has comment: http://stackoverflow.com/comment/82778876
downvote count: 0
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47903414
answers question: http://stackoverflow.com/q/47903414

http://stackoverflow.com/comment/82971088
type: QuestionComment
score: 2
has text: It's the `%i` that explicitly instructs Python to make an integer representation. Try something like `%f` instead.
comment on: http://stackoverflow.com/q/48001293
type: Comment

http://stackoverflow.com/a/47923135
has body: Can you specify your specific goal a little further? Do you want to preserve the structure? Do you want a list for all names in the dictionary? You could write a function like this: def maxdictlist(name,dictlist): maxlst = [] for x in dictlist: if x["name"] == name: maxlst.append(x["age"]) return max(maxlst) print(maxdictlist("john",A)) which returns the max value for a given name. If you're okay with saving a list of the names you're interested in and want to preserve the structure, you could also do something like this, using a key for the max function: def ke(v,name): if v["name"] == name: return v["age"] else: return 0 #0 as default value lst = [] names = ["john","sam"] res = [max(A,key= lambda v:ke(v,name))) for name in names] print(lst) I would advise against this second method though.
type: Answer
answers question: http://stackoverflow.com/q/47922235
score: 1
upvote count: 1
downvote count: 0

utf-8
tags question: http://stackoverflow.com/q/47901824
tags question: http://stackoverflow.com/q/47948233
tags question: http://stackoverflow.com/q/47901631
tags question: http://stackoverflow.com/q/48006240
tags question: http://stackoverflow.com/q/47900129
tags question: http://stackoverflow.com/q/47968578
tags question: http://stackoverflow.com/q/47941623
tag name: utf-8
tags question: http://stackoverflow.com/q/47963789
tags question: http://stackoverflow.com/q/47948010
type: Tag

http://stackoverflow.com/comment/82996514
type: QuestionComment
comment on: http://stackoverflow.com/q/48013744
score: 0
has text: Are you using linux? If that's so check the permisions you gave to the users.txt file? maybe python can't access to the file and that's the reason of why alway don't get the user.
type: Comment

http://stackoverflow.com/q/47926302
tagged with: python
score: 1
has body: I have a pivot table that looks like this- 0 type A B C obs x NA 1 2 y 1 1 2 z 2 2 3 I want to reset the index to look like this- obs A B C x NA 1 2 y 1 1 2 z 2 2 3 Using reset_index with inplace=True does not work for me. Any suggestions?
favorite count: 0
type: Question
upvote count: 2
tagged with: pivot-table
answer count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/22233488
has answer: http://stackoverflow.com/a/47926342
has title: Change index of a pivoted table?
type: UnansweredQuestion
tagged with: pandas

http://stackoverflow.com/a/47953906
has comment: http://stackoverflow.com/comment/82877047
downvote count: 0
answers question: http://stackoverflow.com/q/47953752
type: Answer
score: 3
upvote count: 3
has body: How about with mask df1['b'].update(df2.mask(df2=='')['update']) &gt;&gt;&gt; df1 a b 0 aaa eee 1 bbb X 2 ccc ggg 3 ddd Y

http://stackoverflow.com/q/47879737
possible better answer: http://stackoverflow.com/a/47879962
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47880141
has body: I have a dataframe for which I have columns df['kVA'] and df['Phase']. I am trying to create a column df['Line'], but with the following criteria: Define line by phase df['Line']=['1PH' if x=='1PH' else '3PH' for x in df['Phase'] ] Define line by phase &amp; kVa - desired output df['Line']=['1PH' if x=='1PH' else ['3PHSM' if y&lt;=750 else '3PHLG' for y in df['kVA']] for x in df['Phase'] ] The code for define by phase works . But If I try to integrate the nested if the code stalls. I am trying to classify products to manufacturing lines by Phase and kVA characteristics. Both kVA and Phase are columns in my data frame (as attached). How can I fix this?
accepted answer: http://stackoverflow.com/a/47880141
score: 0
has comment: http://stackoverflow.com/comment/82725442
tagged with: pandas
has answer: http://stackoverflow.com/a/47879962
tagged with: python
has comment: http://stackoverflow.com/comment/82725527
type: AnsweredQuestion
tagged with: list
tagged with: dataframe
has title: nested if in list/ dataframe with python

http://stackoverflow.com/q/47863243
type: AnsweredQuestion
tagged with: reduce
accepted answer: http://stackoverflow.com/a/47863877
has body: I am trying to write the following function using functional programming. def mv(A,X,n): Y = [0]*n for i in range(n): for j in range(n): Y[i] += A[i][j] * X[j] return Y Can the reduce function multiply a vector with a matrix? Because that is what I am trying to do here. I am trying to multiply the matrix A with the vector X but receive an error. The error is: TypeError: 'function' object is not iterable def mv(A,X,n): return list(map(sum,lambda x, y: x*y(A, X))) To the input: A = [[1,2],[3,4]] X = [1,2] n = 2 print(mv(A,X,n)) The output should be: [5,11]
has comment: http://stackoverflow.com/comment/82691392
has comment: http://stackoverflow.com/comment/82691423
has comment: http://stackoverflow.com/comment/82691518
has comment: http://stackoverflow.com/comment/82691489
type: Question
has title: How to use reduce/lambda function on matrices and vectors in python?
score: 0
has comment: http://stackoverflow.com/comment/82691435
tagged with: functional-programming
answer count: 1
has comment: http://stackoverflow.com/comment/82692195
has answer: http://stackoverflow.com/a/47863877
tagged with: python
tagged with: lambda
has comment: http://stackoverflow.com/comment/82691436
has comment: http://stackoverflow.com/comment/82691404

http://stackoverflow.com/q/47926832
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: libvirt
has comment: http://stackoverflow.com/comment/84428864
type: Question
has title: Virtualize a Python3 script with its dependencies (libs & external programs)
favorite count: 0
tagged with: virtualization
upvote count: 2
tagged with: python
has body: I have developed a Python3 program/script that is fairly big. It depends on several external apps, including some apps I don't have a full control on. Just for example, I am using Selenium WebDriver and it happens that for some reason, it crashes and make my script wait undefinitely (try/catch Python structures don't even help in my case). As my script is going to be launched many times and I don't want to pollute my host server with zombie procceses, I was thinking about virtualization to launch some kind of lightweight virtual machines to execute instances of this script (and its dependencies - Python libs and external programs), get the results, and shutdown it when finished. In case of something goes wrong (let's say, no response for 20 minutes), I would then be able to shutdown this instance and keep my server clean. From the researches I made on Google, it appears that OpenVZ or libvirt both could fit this need but I would appreciate any feedbacks or ideas. I hope I'm clear enough as English is not my mother tongue. Please do not hesite to ask me to rephrase if needed. Thank you !
tagged with: openvz
score: 2

http://stackoverflow.com/comment/83007557
score: 0
type: Comment
type: QuestionComment
has text: @Lokesh thanks, I will try what you have suggested first through the link and get back in case of query.
comment on: http://stackoverflow.com/q/48011891

http://stackoverflow.com/comment/82683230
has text: The goal is to get the values of the pixels which lie along the line. The user will specify a transect along a natural image and then that transect will be analyzed and the data recorded.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47858956
score: 0

http://stackoverflow.com/q/47920259
type: AnsweredQuestion
has body: I have a list which looks like this, [('1', 'Michael'), ('2', 'Christopher'), ('3', 'Matthew'), ('4', 'Joshua'), ('5', 'Daniel'), ('6', 'David'), ('7', 'Andrew'), ('8', 'James'), ('9', 'Justin'), ('10', 'Joseph'), ('11', 'Ryan'), ('12', 'John'), ('13', 'Robert'), ('14', 'Nicholas'),] Im trying to sort it using the second element,which is the names,im not exactly sure how to do this, This is what i have tried,but i cant get it to work, sorted(mod , key = lambda x:mod[1]) sorted(mod, key = [x for x,v in enumerate(mod) mod[x][1]] Any suggestions will be helpful,thanks in advance.
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82808030
linked to: http://stackoverflow.com/q/3121979
has answer: http://stackoverflow.com/a/47920308
accepted answer: http://stackoverflow.com/a/47920308
type: Question
upvote count: 2
answer count: 2
duplicate of: http://stackoverflow.com/q/3121979
has title: sorting a list of tuples with names
favorite count: 0
linked to: http://stackoverflow.com/q/10695139
possible better answer: http://stackoverflow.com/a/47920324
tagged with: python
has answer: http://stackoverflow.com/a/47920324

http://stackoverflow.com/comment/82902463
type: QuestionComment
comment on: http://stackoverflow.com/q/47966310
score: 0
has text: but I wan to also handle it in django's default admin view and I have to work on that too, so I am looking for a way that somehow if I can change/update CHOICES then I don't have to handle both view and admin seperately
type: Comment

http://stackoverflow.com/comment/82940807
score: 0
has text: Possible duplicate of [this](https://stackoverflow.com/questions/42448628/opencv-version-3-hogdescriptor-takes-at-most-1-argument-5-given)
comment on: http://stackoverflow.com/q/47979164
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82882704
type: Comment
score: 2
has text: the `[]` is on purpose, for better performance: https://stackoverflow.com/questions/9060653/list-comprehension-without-in-python
type: AnswerComment
comment on: http://stackoverflow.com/a/47956486

http://stackoverflow.com/comment/82977594
type: Comment
comment on: http://stackoverflow.com/a/48004614
score: 0
type: AnswerComment
has text: `conn = socket.accept()` still correct but you have to unpack later

http://stackoverflow.com/comment/83033574
score: 0
type: Comment
type: QuestionComment
has text: @Evk As I mentioned in the post, the calculation process is CPU-bounded, so ProcessPool is suitable because ThreadPoolExecuter cannot make it faster due to Python's GIL. Please see https://stackoverflow.com/questions/1226584/multiprocess-or-threading-in-python
comment on: http://stackoverflow.com/q/47978171

http://stackoverflow.com/comment/83189337
comment on: http://stackoverflow.com/a/48079843
score: 0
type: Comment
has text: Thank you for the help. I'm just starting and I'm following along with a book. I had the names like this. ['alice, 'david, 'caroline] Instead of this. ['alice', 'david', 'carloine'] pycharm is fine. I goofed up. Case closed. Thanks again for helping.
type: AnswerComment

http://stackoverflow.com/comment/82800985
comment on: http://stackoverflow.com/a/47911903
type: Comment
has text: Thanks, I thought this might be the case. I just basically wrapped my code in a try, except and I'm working with that.
score: 0
type: AnswerComment

http://stackoverflow.com/q/47897402
upvote count: 1
tagged with: shell
has answer: http://stackoverflow.com/a/47897568
favorite count: 0
has comment: http://stackoverflow.com/comment/82765110
type: UnansweredQuestion
has title: Proper use of os.wait()?
has comment: http://stackoverflow.com/comment/82762162
tagged with: python
has comment: http://stackoverflow.com/comment/82761940
has body: I am trying to solve an issue with automating a series of scripts used in my workplace. I am a beginner so I apologise for what most likely will be an easy question (hopefully), I have read the literature but it didn't quite make sense to me. Essentially I have a bash script that runs a python script and an R script that needs to be run in order, currently running the code the R script begins before the python is finished and I have been told here than I cannot use the shell wait function as my python script launches child processes and shell wait cannot be used to wait on grandchild processes. Thats fine, so the solution offered was to make the python and R script wait on their own child processes so that when they exit, the the bash script can properly run in order. Unfortunately I cannot figure out the proper nomenclature of this in my python script. Here's what i have: cmd = "python %s/create_keyfile.py %s %s %s %s" %(input, input, input, input, input) print cmd os.system(cmd) cmd = "python %s/uneak_name_plus_barcode_v2.py %s %s %s %s" %(input, input, input, input, input) print cmd os.system(cmd) cmd = "python %s/run_production_mode.py %s %s %s %s %s" %(input, input, input, input, input, input) print cmd os.system(cmd) Where 'input' is actual inputs in my code, I probably just cant share exactly what we are doing :) So essentially I am trying to figure out the best way of having the whole script wait on these three scripts before exiting.
linked to: http://stackoverflow.com/q/3172470
downvote count: 0
score: 1
type: Question
has comment: http://stackoverflow.com/comment/82787512
answer count: 2
has comment: http://stackoverflow.com/comment/82765120
has answer: http://stackoverflow.com/a/59735318
has comment: http://stackoverflow.com/comment/82762172
tagged with: wait
has comment: http://stackoverflow.com/comment/82794190
has comment: http://stackoverflow.com/comment/82765078
tagged with: linux

http://stackoverflow.com/q/47904931
tagged with: postgresql
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has title: Case insensitive array query Flask-SQLAlchemy
tagged with: python
has comment: http://stackoverflow.com/comment/82777842
score: 3
upvote count: 3
tagged with: sqlalchemy
type: Question
has body: I have a text array column in a Postgres table containing user's email and alt email addresses. I'm using Flask and SQLAlchemy and I want to query the database for the row where the user's inputed email is contained in the array. At the moment I'm using .contains Users.query.filter(Users.emails.contains({email})).first() The issue I'm having is that some of the existing email addresses have a mixture of upper and lower case however I can't seem to find a method for making an Array lower or the query case insensitive. I've looked at func.lower but this doesn't want to play nicely with Arrays, the other option is .ilike however I can't seem to get this to work and my table is approx 10,000 rows and .ilike I don't think will be the most efficient? What is the best way to do this?
has comment: http://stackoverflow.com/comment/121585741
tagged with: flask
tagged with: flask-sqlalchemy
has answer: http://stackoverflow.com/a/47909863

http://stackoverflow.com/q/47988324
has answer: http://stackoverflow.com/a/47988374
downvote count: 4
answer count: 1
has comment: http://stackoverflow.com/comment/82945305
has body: Write a function, top_three, that takes a list as its argument, and returns a list of the three largest elements. For example top_three([2,3,5,6,8,4,2,1]) == [8, 6, 5] My code was: def top_three(input_list): input_list=[1,2,3,4,5] a=sorted(input_list, reverse=True) b=input_list[0:3] return b print(top_three(input_list))
tagged with: python
has title: Quiz: Top Three
favorite count: 0
upvote count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82945410
type: UnansweredQuestion
score: -4
has comment: http://stackoverflow.com/comment/82945377
type: Question

http://stackoverflow.com/q/47995710
possible better answer: http://stackoverflow.com/a/73736823
tagged with: openpyxl
tagged with: excel
type: AnsweredQuestion
has title: Getting cell data from openpyxl looped rows
has body: I have some code to create tuples from OpenPyXL in a python script that looks like: for row in sheet.iter_rows(min_row=2, max_col=2, max_row=50) print(row) Which returns (&lt;Cell 'States'.A2&gt;, &lt;Cell 'States'.B2&gt;) (&lt;Cell 'States'.A3&gt;, &lt;Cell 'States'.B3&gt;) ... (&lt;Cell 'States'.A50&gt;, &lt;Cell 'States'.B50&gt;) I would like to pull the values from the 'A-column' and the 'B-column' by using cell.value and further splitting the 'B-column' by a comma delimited value (ex. 7,100 or 100,7) then adding the values to a dictionary that would look like: StatesPriority = { A2 : (B2.ValueBeforeComma, B2.ValueAfterComma) A3 : (B3.ValueBeforeComma, B3.ValueAfterComma) ... A50 : (B50.ValueBeforeComma, B50.ValueAfterComma) } However, I am more concerned about the OpenPyXL function of getting values from a returned tuple. I think I can figure out splitting values by commas on my own with a little bit of time. Python Version: 3.6.3 OpenPyXL Version: 2.4.9 All help is appreciated!
type: Question
upvote count: 4
answer count: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/47996106
tagged with: tuples
has answer: http://stackoverflow.com/a/73736823
tagged with: python
accepted answer: http://stackoverflow.com/a/47996106
score: 4
tagged with: python-3.x

http://stackoverflow.com/comment/82794812
score: 1
comment on: http://stackoverflow.com/q/47912931
has text: I don't have an explanation for why the extra level is handled, but you can always just take the `.values` from the result and assign it back without any problems. `df['Window'] = window['Vals'].apply(lambda x: x[1] + x[2]).values`.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82743052
type: Comment
has text: Is the project of the service account the same as the project you are trying to access (settings.ANDROID_MGMT_PROJECTID)?
comment on: http://stackoverflow.com/q/47887264
score: 0
type: QuestionComment

http://stackoverflow.com/a/62926862
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/47939921
upvote count: 1
has body: Yes! I had this same problem. The file I was using to write the code was named 'tabula.py'. I wrote the code in a new file, with a new name, and had to delete the file named 'tabula.py'. Once I did that the error went away.
type: Answer

http://stackoverflow.com/comment/82702881
has text: Thank you for your response. Now this is fixed (but I have more coming!).
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47868745
score: 1

http://stackoverflow.com/comment/82720932
score: 1
has text: @Barmar Please, I don't invent all these rules, you have been on SO for 5 years, you should know this basic rule. I don't really want downvote this question cause it's a good question without the fact of image instead of text, still you want me that I don't downvote to be "nice" ? This don't make sense this user need to know that it's bad to post image instead of text for his/her future question ! It more you that don't want that people downvote question, my vote are my votes, it doesn't concern you.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47877245

http://stackoverflow.com/q/47872981
has answer: http://stackoverflow.com/a/65865696
has body: For my python extension, I have both C (from an embedded library) and C++ files and they are compiled and linked together. Only the C++ part interfaces with Python (via SWIG). This works both in windows with VS2015 and gcc under linux. However, with gcc, the C++ files need a different set of compiler flags (eg. -std=c++11, -Wno-reorder) than the C files, to avoid warnings concerning the improper flags in C. Is there a way in setuptools / distutils to change compiler flags for each file seperatly, eg. based on the file extension? I use already a custom build step from https://stackoverflow.com/a/36293331/3032680. Update: The main problem is, that distutils.ccompiler does not check the file extension for C or C++ and is running everything with $CC. Even defining CXXFLAGS does not help. I will stand the warnings, neither with export nor a definition using os.eniviron in the setup.py file. Update 2: On macOS with CLang 8.0.0 the situation gets worse: Trying to compile a .c file with -std=c++11 is not a warning but an error.
linked to: http://stackoverflow.com/q/4597228
downvote count: 1
has comment: http://stackoverflow.com/comment/121106405
has comment: http://stackoverflow.com/comment/121105449
score: 8
favorite count: 0
upvote count: 9
possible better answer: http://stackoverflow.com/a/65865696
has comment: http://stackoverflow.com/comment/121105903
linked to: http://stackoverflow.com/q/15527611
has title: Python extension: using different compiler flags for a C parts and C++ parts
tagged with: python
tagged with: c++
type: AnsweredQuestion
tagged with: setuptools
has comment: http://stackoverflow.com/comment/121079349
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/121105021
accepted answer: http://stackoverflow.com/a/49491343
linked to: http://stackoverflow.com/q/8106258
tagged with: http://stackoverflow.com/tag/c
tagged with: gcc
has answer: http://stackoverflow.com/a/49491343

http://stackoverflow.com/q/47891444
possible better answer: http://stackoverflow.com/a/47893139
has comment: http://stackoverflow.com/comment/83145578
has title: How can I update my DataFrame in Pandas and export out to Excel?
score: 0
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/47895565
has answer: http://stackoverflow.com/a/48214270
accepted answer: http://stackoverflow.com/a/48214270
has answer: http://stackoverflow.com/a/47893139
tagged with: python
tagged with: excel
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82749843
has comment: http://stackoverflow.com/comment/82960833
has comment: http://stackoverflow.com/comment/82750338
type: Question
has body: I'm new to Python and programming all together. So forgive me if my question seems silly or unclear. I have done research but quite frankly some of the explanations I've read I have trouble understanding. I have a dataframe that consists of large amounts of scheduled appointment data for a hospital that needs to be evaluated and modified so that it can be imported into their new scheduling application. Unfortunately the vendors' import tool is trash and does zero checks, so I have to write something that will check the old data and transform it into uploaded data for the new system. Here is an example of the format: start appointment department procedure resource 20171020131500 MAM BDXMAMUNI BDIAG2 20171020133000 MAM BDXMAMUNI BDIAG1 20171020141500 MAM BDXMAMUNI BDIAG2 20171020143000 MAM BDXMAMUNI BDIAG1 20171020144500 MAM BDXMAMBIL BDIAG2 20171020150000 MAM BDXMAMBIL BDIAG1 20171020151500 MAM BDXMAMUNI BDIAG2 20171023080000 MAM BDXMAMBIL BDIAG1 20171023081500 MAM BDXMAMBIL BDIAG2 I'm trying to do updates based on criteria. This is what I came up with but I cannot get it to update the field. Here are the criteria in my own words. If start appointment at Index X minutes = 15 and (hr = 8 or h= 9 or hr = 10 or hr = 11 or h =13 or hr =14 or hr =15) and resource = BDIAG1, BDIAG2 or BDIAG 3 then start appointment at Index X will be in resource ZBMDX3 at Index X If start appointment at Index X has minutes = 00 and (hr = 8 or hr = 9 or hr = 10 or hr = 11 or hr = 13 or hr = 14 or hr =15) then start appointment at Index X will be in resource ZBMDX2 at Index X If start appointment at Index X minutes = 45 and (hr = 7 or hr = 8 or hr = 9 or hr = 10 or hr 12 or hr = 13 or hr = 14) thenstart appointment at Index X will be in resource ZBMDX1 at Index X If start appointment at Index X the minutes = 30 and (hr = 8 or hr = 9 or hr = 10 or hr = 13 or hr = 14) then start appointment at Index X will be in resource ZBMDX4 at Index X When the output file is created, it does not have any up…

http://stackoverflow.com/q/47999028
answer count: 1
has body: I want to use the python-midi package (from https://github.com/vishnubob/python-midi). Hwever there is an error when I use it. import midi pattern = midi.Pattern() When I run it, I have the following error: pattern = midi.Pattern() AttributeError: 'module' object has no attribute 'Pattern' I tried to install this package with: pip install git+https://github.com/vishnubob/python-midi@feature/python3 pip install python-midi python setup.py install (in downloading the projet) Thank you in advance for your help.
has answer: http://stackoverflow.com/a/48004143
tagged with: python-2.7
type: AnsweredQuestion
upvote count: 0
has title: Python-midi has no attribute Pattern
tagged with: midi
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48004143
type: Question
has comment: http://stackoverflow.com/comment/82966956
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/82966560
tagged with: python-packaging
downvote count: 2

http://stackoverflow.com/comment/82824873
has text: @cᴏʟᴅsᴘᴇᴇᴅ how bad?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47928029

http://stackoverflow.com/a/47929666
score: 2
type: AcceptedAnswer
downvote count: 0
has body: Because you assigned the same object as the instance members. You can use np.array(x, copy=True) or x.copy() to generate a new array object: array = np.array([[11,12,13]]) a = Test(array.copy()) b = Test(np.array(array, copy=True)) Alternatively, if your arg is always a np.array, you could do it in the __init__ method (as noted by roganjosh in the comments): class Test: def __init__(self, arg): self.arg = np.array(arg, copy=True) ...
accepted answer of: http://stackoverflow.com/q/47929642
answers question: http://stackoverflow.com/q/47929642
type: Answer
has comment: http://stackoverflow.com/comment/82827843
has comment: http://stackoverflow.com/comment/82827906
upvote count: 2
has comment: http://stackoverflow.com/comment/82827863
has comment: http://stackoverflow.com/comment/82828060

http://stackoverflow.com/q/47886642
tagged with: mysql
upvote count: 1
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/47901789
downvote count: 0
favorite count: 0
tagged with: django
tagged with: python
has body: I can't figure out whether I'll bear any risk in terms of malicious software &amp; security if I download mysqlclient-python from here https://pypi.python.org/pypi/mysqlclient? Is mysqlclient-python provided in PyPI reliable in your opinion? I want to install mysqlclient in my global Python environment, not virtualenv. I've started learning Python. I want to try Django framework and Mysql database. I've already installed them. I know that PyPI is a third party repository, and everyone with a bit of experience can write and upload their package to PyPI. Is it safe to install mysqlclient, using pip and PyPI?
tagged with: mysql-connector-python
type: AnsweredQuestion
has title: mysqlclient-python & security issues
accepted answer: http://stackoverflow.com/a/47901789
score: 1

http://stackoverflow.com/comment/82838251
type: QuestionComment
comment on: http://stackoverflow.com/q/47934409
score: 1
has text: See the [documentation for `sorted`](https://docs.python.org/3/library/functions.html#sorted): "Return a new sorted list from the items in iterable."
type: Comment

http://stackoverflow.com/comment/82866055
type: Comment
type: QuestionComment
has text: Yes, of course there is a way of doing it with nested loops, possibly with a single `for` loop and possibly a vectorized way with `pandas`. What have you tried?
comment on: http://stackoverflow.com/q/47948062
score: 0

http://stackoverflow.com/comment/83017759
comment on: http://stackoverflow.com/a/48014190
type: Comment
has text: Woah holy cow, thanks! This works and I can follow most of it. Does `Match()` find all instances of an item? I.e. if there were say `5` instances of `trackinfo` or `TralbumData`, would match return `4` (I assume it starts with 0) and I could loop through the matches via `group()`?
score: 0
type: AnswerComment

http://stackoverflow.com/q/47860718
type: Question
tagged with: wtforms
answer count: 1
tagged with: flask
score: 0
has title: Flask-WTF: multiple forms of same class all returning the same data on submission
has answer: http://stackoverflow.com/a/47862984
tagged with: flask-wtforms
type: UnansweredQuestion
tagged with: python
has body: I'm generating multiple forms, one per image, and packaging the image and corresponding form as a tuple in a list. This list is then passed to Jinja where each tuple is unpacked and each image and form are inserted into a list for voting via the form. My issue is that clicking on any one of the specific forms causes all form to return as if that button was clicked. So, in effect, up or down voting one image acts as if that button was clicked for all other images. I know I am creating legitimate forms as I have tried printing the form and it's return data to console. When I do this, each form does have a unique address, and all forms show the same data (True / False) in the form.field.data attribute. Can somebody help me discover what's going on here? Form: class VoteForm(FlaskForm): upvote = SubmitField('vote up') downvote = SubmitField('vote down') Route: @index_mod.route('/', methods = ['GET', 'POST']) def index(): pics = Pic.select().order_by(Pic.score.desc()) pics_and_forms = [] for pic in pics: voteform = VoteForm() #tuple of pic and corresponding form pics_and_forms.append( (pic, voteform) ) for pic, form in pics_and_forms: if form.validate_on_submit(): if form.upvote.data: pic.score += 1 pic.save() if form.downvote.data: pic.score -= 1 pic.save() return render_template('index.html', pics_and_forms = pics_and_forms) Jinja: {% for pic, form in pics_and_forms %} {{ pic.name }} Submitted by {{ pic.user.username }} Score: {{ pic.score }} {{ form.csrf_token }} {{ form.upvote }} {{ form.downvote }} {% endfor %} EDIT So I'm figuring out that while I can embed as many forms onto the page as I want the returning post request doesn't specify which specific form was clicked. Instead I'm planning to embed the details into a hidden field and then use the flask request object to retrieve that field from the hidden form. I would rather use Flask-WTF fully for this but it seems like there's no elegant way to dynamically add multiple forms to a page and retrieve which form was…

http://stackoverflow.com/q/47863934
has answer: http://stackoverflow.com/a/47863949
has body: I have a Pandas dataframe with datetime column named time. I'd like to count the number of rows per hour. The problem is that I'd like the resulting table handle hours for which no rows exist. Example: time id lat lon type 0 2017-06-09 19:34:59.945128-07:00 75 36.999866 -122.058180 UPPER CAMPUS 1 2017-06-09 19:53:56.387058-07:00 75 36.979664 -122.058900 OUT OF SERVICE/SORRY 2 2017-06-09 19:28:53.525189-07:00 75 36.988640 -122.066820 UPPER CAMPUS 3 2017-06-09 19:30:31.633478-07:00 75 36.991657 -122.066605 UPPER CAMPUS I can get these values using df.groupby(df.time.dt.hour).count() which produces: time id lat lon type time 0 2121 2121 2121 2121 2121 1 2334 2334 2334 2334 2334 2 1523 1523 1523 1523 1523 6 8148 8148 8148 8148 8148 Which is correct: 0, 1, 2 are the hours of the day. However, I'd like to represent that there are no rows for hours 3, 4, 5. Having each of these column names is unnecessary, since the value is the same for each.
tagged with: pandas
upvote count: 1
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 1
has title: Adding missing data to dataframe grouped by date
type: Question
accepted answer: http://stackoverflow.com/a/47863949

http://stackoverflow.com/comment/88737628
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47905139
has text: A train/test split of 150/6 is a very small test set. Suggested is 70/30 of your 150+6 records. So repartition them.
score: 0

http://stackoverflow.com/a/64616828
downvote count: 0
has body: From https://docs.docker.com/get-started - "Fundamentally, a container is nothing but a running process, with some added encapsulation features applied to it in order to keep it isolated from the host and from other containers." Docker runs on a host machine. That host machine (or virtual machine) has a certain number of physical (or virtual) CPU's. The reason that multiprocessing.cpu_count() displays 8 in your case is because that is the number of CPU's your system has. Using docker options like --cpus or --cpuset-cpus doesn't change your machine's hardware, which is what cpu_count() is reporting. On my current system: # native $ python -c 'import multiprocessing as mp; print(mp.cpu_count())' 12 # docker $ docker run -it --rm --cpus 1 --cpuset-cpus 0 python python -c 'import multiprocessing as mp; print(mp.cpu_count())' 12 From https://docs.docker.com/config/containers/resource_constraints/#cpu - "By default, each container’s access to the host machine’s CPU cycles is unlimited." But you can limit containers with options like --cpus or --cpuset-cpus. --cpus can be a floating point number up to the number of physical CPU's available. You can think of this number as a numerator in the fraction <--cpus arg>/<physical CPU's>. If you have 8 physical CPU's and you specify --cpus 4, what you're telling docker is to use no more than 50% (4/8) of your total CPU's. --cpus 1.5 would use 18.75% (1.5/8). --cpuset-cpus actually does limit specifically which physical/virtual CPU's to use. (And there are many other CPU-related options that are covered in docker's documentation.) Here is a smaller code sample: import logging import multiprocessing import sys import psutil from joblib.parallel import Parallel, delayed def get_logger(): logger = logging.getLogger() if not logger.hasHandlers(): handler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter("[%(process)d/%(processName)s] %(message)s") handler.setFormatter(formatter) handler.setLevel(logging.DEBUG) logger.add…
answers question: http://stackoverflow.com/q/47989418
score: 20
upvote count: 20
type: Answer

http://stackoverflow.com/a/47973905
has comment: http://stackoverflow.com/comment/82920032
downvote count: 0
answers question: http://stackoverflow.com/q/47968757
has body: Since convolution itself is linear, inserting any linear operation can be done by doing convolution via tf.nn.conv2d first and then that operation. The (max(x) + min(x)) / 2 on each 5x5 patch can be realized by (tf.nn.max_pool(x) - tf.nn.max_pool(-x)) * 0.5. To subtract this after conv, you also need to multiple the results by corresponding sums of convolution kernels. After that, you may apply the nonlinear activation function. However, in general I don't know how to efficiently add nonlinear operations, e.g. get z-score for each 5x5 patch before convolutional multiplication. Perhaps other answers could provide some insights.
type: Answer
upvote count: 3
score: 3

mechanicalsoup
tag name: mechanicalsoup
tags question: http://stackoverflow.com/q/47888736
tags question: http://stackoverflow.com/q/47875961
type: Tag

http://stackoverflow.com/q/47997203
favorite count: 0
has answer: http://stackoverflow.com/a/48000750
tagged with: python
type: AnsweredQuestion
upvote count: 3
accepted answer: http://stackoverflow.com/a/48000750
tagged with: tensorflow
type: Question
score: 3
possible better answer: http://stackoverflow.com/a/48000752
has body: Is it possible to restore a variable, only if present? What is the most idiomatic way of doing so? For instance, consider the following minimal example: import tensorflow as tf import glob import sys import os with tf.variable_scope('volatile'): x = tf.get_variable('x', initializer=0) with tf.variable_scope('persistent'): y = tf.get_variable('y', initializer=0) add1 = tf.assign_add(y, 1) saver = tf.train.Saver(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, 'persistent')) sess = tf.InteractiveSession() tf.global_variables_initializer().run() tf.get_default_graph().finalize() print('save file', sys.argv[1]) if glob.glob(sys.argv[1] + '*'): saver.restore(sess, sys.argv[1]) print(sess.run(y)) sess.run(add1) print(sess.run(y)) saver.save(sess, sys.argv[1]) When run twice with the same argument, the program first prints 0\n1 and then 1\n2 as expected. Now suppose you update your code to have new functionality, by adding a z = tf.get_variable('z', initializer=0) after add1 within the persistent scope. Running this again when the old save file is present will break with the following: NotFoundError (see above for traceback): Key persistent/z not found in checkpoint [[Node: save/RestoreV2_1 = RestoreV2[dtypes=[DT_INT32], _device="/job:localhost/replica:0/task:0/device:CPU:0"](_arg_save/Const_0_0, save/RestoreV2_1/tensor_names, save/RestoreV2_1/shape_and_slices)]] [[Node: save/Assign_1/_18 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device_incarnation=1, tensor_name="edge_12_save/Assign_1", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:GPU:0"]()]]
has answer: http://stackoverflow.com/a/48000752
answer count: 2
has title: TensorFlow - restore if present
downvote count: 0

http://stackoverflow.com/comment/82910230
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47970322
score: 0
has text: Check my updated answer.

http://stackoverflow.com/comment/83087378
comment on: http://stackoverflow.com/q/47982982
score: 0
has text: Got the answer , the header is `ConversationID` and this will work like `message.ConversationID`. Thanks for your help @Barmar
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47996338
has answer: http://stackoverflow.com/a/70473650
linked to: http://stackoverflow.com/q/26152398
has comment: http://stackoverflow.com/comment/124576487
tagged with: python
tagged with: rpyc
favorite count: 0
tagged with: python-3.x
has body: I am using RPyC for a client-server application. I try to change the value of exposed_variable when I call exposed_change() method. I receive "UnboundLocalError: local variable 'exposed_variable' referenced before assignment" error. However, if I make exposed_variable global (before I try to modify it, like in this example), I get "NameError: name 'exposed_variable' is not defined". What am I missing? This is my server: from rpyc.utils import server import rpyc import time class DoStuffService(rpyc.Service): exposed_variable = 1 def exposed_change(self): #global exposed_variable exposed_variable = exposed_variable + 1 if __name__ == '__main__': protocol_config = dict(instantiate_custom_exceptions=True, import_custom_exceptions=True) server.ThreadedServer(DoStuffService, hostname='localhost', port=8888, auto_register=False,protocol_config=protocol_config, backlog=500).start() This is my client: import rpyc, sys import time def rpyc_call(): conn = rpyc.connect('localhost', 8888) a = 1 while a: conn.root.change() nr=conn.root.variable print("Nr is ", nr) time.sleep(10) if __name__ == '__main__': rpyc_call() Thank you. I am wainting for your advice...
upvote count: 1
answer count: 1
has title: I am trying to change the value of an exposed variable in RPyC. I receive an error. What am I doing wrong?
tagged with: client-server
downvote count: 0
type: UnansweredQuestion
score: 1
linked to: http://stackoverflow.com/q/855493
type: Question

http://stackoverflow.com/q/48013749
has body: I am currently trying to animate the dynamics of a typical saddle node bifurcation ode: dx/dt = r + x^2. Snapshots at specific values of r are realised with the streamplot function from r = -1 to 1. Unfortunately the init function and the animate function are not working properly because .set_array does not work for streamplots. I am also not sure how to update the streams at each iteration in the animate function. My question is how I should modify the animate and init function so that the funcanimation function gives a proper animated plot of the flows. import matplotlib.pyplot as plt import numpy as np import matplotlib.animation as animation nx, ny = .02, .02 x = np.arange(-15, 15, nx) y = np.arange(-10, 10, ny) X, Y = np.meshgrid(x, y) dy = -1 + Y**2 dx = np.ones(dy.shape) dyu = dy / np.sqrt(dy**2 + dx**2) dxu = dx / np.sqrt(dy**2 + dx**2) color = dyu fig, ax = plt.subplots() stream = ax.streamplot(X,Y,dxu, dyu, color=color, density=2, cmap='jet',arrowsize=1) ax.set_xlabel('t') ax.set_ylabel('x') def init(): stream.set_array([]) return stream def animate(iter): dy = -1 + iter * 0.01 + Y**2 dx = np.ones(dy.shape) dyu = dy / np.sqrt(dy**2 + dx**2) dxu = dx / np.sqrt(dy**2 + dx**2) stream.set_array(dyu.ravel()) return stream anim = animation.FuncAnimation(fig, animate, frames=100, interval=50, blit=False, repeat=False) plt.show()
favorite count: 0
has comment: http://stackoverflow.com/comment/83414896
possible better answer: http://stackoverflow.com/a/72120459
answer count: 2
tagged with: animation
has comment: http://stackoverflow.com/comment/83015221
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/19621521
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/83334427
has answer: http://stackoverflow.com/a/56304195
type: AnsweredQuestion
downvote count: 0
has title: Matplotlib Animation of Streamplot of Bifurcation
accepted answer: http://stackoverflow.com/a/56304195
linked to: http://stackoverflow.com/q/61932534
type: Question
has answer: http://stackoverflow.com/a/72120459
has comment: http://stackoverflow.com/comment/83020888
score: 1

http://stackoverflow.com/comment/82913554
score: 1
has text: [Don't post pictures of code](https://meta.stackoverflow.com/questions/303812/discourage-screenshots-of-code-and-or-errors), copy-paste the actual code and command line output instead.
comment on: http://stackoverflow.com/q/47971533
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47929501
answers question: http://stackoverflow.com/q/47928554
upvote count: 1
has body: This gives the explanation I believe: for i in range(10): print(sess.run([train, w, b, loss], {x: x_data, y: y_data})) Gives the following result: [None, array([ 4.70380012e+10], dtype=float32), array([ 8212000.], dtype=float32), 2.0248419e+12] [None, array([ -2.68116614e+19], dtype=float32), array([ -4.23342041e+15], dtype=float32), 6.3058345e+29] [None, array([ 1.52826476e+28], dtype=float32), array([ 2.41304958e+24], dtype=float32), inf] [None, array([ -8.71110858e+36], dtype=float32), array([ -1.37543819e+33], dtype=float32), inf] [None, array([ inf], dtype=float32), array([ inf], dtype=float32), inf] Your learning rate is simply too big, so you "overcorrect" the value of w at each iteration (see as it oscillates between negative and positive, with increasing absolute value). You get higher and higher values, until something reaches infinity, which creates Nan values. Just lower (a lot) the learning rate.
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/82845769
score: 1

http://stackoverflow.com/comment/82992621
type: QuestionComment
has text: It's a shame that you're forced to use Python 2, the Unicode handling in Python 3 is a lot saner. In the mean time, you may find this article helpful: [Pragmatic Unicode](http://nedbatchelder.com/text/unipain.html), which was written by SO veteran Ned Batchelder.
comment on: http://stackoverflow.com/q/48011386
score: 0
type: Comment

pca
tag name: pca
tags question: http://stackoverflow.com/q/47914966
type: Tag
tags question: http://stackoverflow.com/q/47906412

http://stackoverflow.com/q/47962540
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
has body: How do I create a button to add and remove a fields, and then save some fields using django (2.0)? my views.py def add_preventivo(request): if request.method == "POST": form = PreventivoForm(request.POST) if form.is_valid(): preventivo = form.save(commit=False) preventivo.published_date = timezone.now() preventivo.save() else: form = PreventivoForm() return render(request, 'add_preventivo.html', {'form':form}) my models.py class Preventivo(models.Model): cliente = models.ForeignKey('Cliente',on_delete=models.CASCADE) prestazione = models.ForeignKey('Prestazione',on_delete=models.CASCADE) numero = models.IntegerField(default='1') prezzo = models.IntegerField(default='0') I must be able to repeat "prestazione" and "numero" and I must have a sum of the various repetitions on "prezzo"
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/82894850
has title: dynamically add / remove fields django
score: 0
has answer: http://stackoverflow.com/a/47962574
has comment: http://stackoverflow.com/comment/82894355
has comment: http://stackoverflow.com/comment/82894350
answer count: 1
accepted answer: http://stackoverflow.com/a/47962574

http://stackoverflow.com/comment/82824200
has text: I'm going to live with the import ../ from sys at the top fo the example file.
comment on: http://stackoverflow.com/a/47927445
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/47912979
has body: I am using a well-developed Python class (let's call it Foo1D) that has a bunch of great methods but only works on 1D data. Forking the repo and modifying every method to handle 2D data is prohibitively time consuming. So, I'd like to make a "vectorized" wrapper Foo2D that accepts uncorrelated 2D input, converts it into a collection of Foo1D objects, iterates over the collection when a method is called, and returns an array of the results. Here's what I've tried: class Foo1D(object): def __init__(self, data1D): self.offset = 20 self.data = data1D+self.offset def multiply(self, x): return self.data*x def add(self, a): return self.data+a class Foo2D(object): def __init__(self, data2D): dummy = Foo1D(data2D[0]) self.__class__ = type(dummy.__class__.__name__, (self.__class__, dummy.__class__), {}) self.__dict__ = dummy.__dict__ del dummy self.data2D = [Foo1D(data1D) for data1D in data2D] def __getattr__(self, item, *args, **kwargs): result = [getattr(data1D, item)(*args, **kwargs) for data1D in self.data2D] return np.array(result) This creates the Foo1D and Foo2D objects with the correct attributes but the Foo2D methods don't behave as expected. An example: a1D = np.arange(10) a2D = a1D.reshape(2,5) A = Foo1D(a1D) B = Foo2D(a2D) So when I run A.multiply(2) I get array([40, 42, 44, 46, 48, 50, 52, 54, 56, 58]) as expected. But when I run B.multiply(2) I get array([40, 42, 44, 46, 48]) when I expect to get array([[40, 42, 44, 46, 48],[50, 52, 54, 56, 58]]). This is because B.data is only the first element of a2D but I don't understand why. Indeed if I do np.array([getattr(i, 'multiply')(2) for i in B.data2D]) I get the answer I expect array([[40, 42, 44, 46, 48],[50, 52, 54, 56, 58]]). Any idea why this is happening? Thanks!
favorite count: 0
type: Question
upvote count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/47914962
answer count: 1
tagged with: class
has title: Python wrapper that iterates over a list of classes
type: AnsweredQuestion
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/47914962

http://stackoverflow.com/a/47988908
downvote count: 1
has comment: http://stackoverflow.com/comment/82957367
type: Answer
has comment: http://stackoverflow.com/comment/82960682
has body: Destroying entire (set of) widget(s) when you only need to configure one of their attributes sounds like a very poor design, and such practice is notorious for resulting in pricey memory leaks, as you have already seen. In any case, I reckon you would be much better off by simply configuring the widgets you already have, as opposed to destroying/recreating them when the changes are due. From what I've been able to comprehend, you said you need to frequently display some text (namely, logs?) in the Text widget, so why not just clear the text you already have and insert the new one into the widget: txt.delete('1.0', 'end') # clearing the text widget txt.insert('end', my_log) # inserting the log into the text widget
has comment: http://stackoverflow.com/comment/82957243
upvote count: 2
score: 1
answers question: http://stackoverflow.com/q/47988625

http://stackoverflow.com/a/47990759
has comment: http://stackoverflow.com/comment/82949932
type: Answer
accepted answer of: http://stackoverflow.com/q/47990529
answers question: http://stackoverflow.com/q/47990529
has comment: http://stackoverflow.com/comment/82949882
has comment: http://stackoverflow.com/comment/82950290
has body: Since it is the shortcut of batch file, not the file itself, just change .bat in os.remove() to .lnk.
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/47937069
favorite count: 0
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/82843380
upvote count: 1
has title: TypeError: expected string or bytes-like object in pos tagging(perceptron)
has body: from textblob import Blobber from textblob_aptagger import PerceptronTagger blob1 = TextBlob("This is a blob.",pos_tagger=PerceptronTagger()) blob2 = TextBlob("This is another blob.") print(blob1.tags) Connected to pydev debugger (build 145.844) Traceback (most recent call last): File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 2016.1.2\helpers\pydev\pydevd.py", line 1531, in &lt;module&gt; globals = debugger.run(setup['file'], None, None, is_module) File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 2016.1.2\helpers\pydev\pydevd.py", line 938, in run pydev_imports.execfile(file, globals, locals) # execute the script File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 2016.1.2\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "D:/Tagger/Test.py", line 31, in &lt;module&gt; print(blob1.tags) File "C:\Users\karthika\AppData\Local\Programs\Python\Python35\lib\site-packages\textblob\decorators.py", line 24, in __get__ value = obj.__dict__[self.func.__name__] = self.func(obj) File "C:\Users\karthika\AppData\Local\Programs\Python\Python35\lib\site-packages\textblob\blob.py", line 475, in pos_tags return [val for sublist in [s.pos_tags for s in self.sentences] for val in sublist] File "C:\Users\karthika\AppData\Local\Programs\Python\Python35\lib\site-packages\textblob\blob.py", line 475, in &lt;listcomp&gt; return [val for sublist in [s.pos_tags for s in self.sentences] for val in sublist] File "C:\Users\karthika\AppData\Local\Programs\Python\Python35\lib\site-packages\textblob\decorators.py", line 24, in __get__ value = obj.__dict__[self.func.__name__] = self.func(obj) File "C:\Users\karthika\AppData\Local\Programs\Python\Python35\lib\site-packages\textblob\blob.py", line 478, in pos_tags for word, t in self.pos_tagger.tag(self) File "C:\Users\karthika\AppData\Local\Programs\Python\Python35\lib\site-packages\textblob_aptagger\taggers.py", line 49, in tag…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82843407
downvote count: 0
answer count: 0
score: 1

http://stackoverflow.com/comment/82979249
type: Comment
comment on: http://stackoverflow.com/a/48005368
type: AnswerComment
has text: You can also use a smaller timeframe; I just tested CPU usage for a busy loop (while True: pass) vs a 0.001 second wait (while True: time.sleep(0.001) and difference was 100% usage on one core to <1%. I'll update the answer.
score: 0

http://stackoverflow.com/a/48008693
has comment: http://stackoverflow.com/comment/82987555
type: Answer
has comment: http://stackoverflow.com/comment/82991997
has body: I do not personnaly use Spyder, but the third line of your code seems to be wrong, you should try this : import pygal from pygal.maps.world import World worldmap_chart = World() worldmap_chart.title = 'Some countries' worldmap_chart.render() Or better : import pygal worldmap_chart = pygal.maps.world.World() worldmap_chart.title = 'Some countries' worldmap_chart.render() Depends on what you need to use in pygal or pygal.maps.world. Edit : I tried to render, but nothing appears, one trick is to render in browser which works for me as follow : import pygal worldmap_chart = pygal.maps.world.World() worldmap_chart.title = 'Some countries' worldmap_chart.force_uri_protocol= "http" worldmap_chart.add('North America',{'ca': 84949494949,'mx': 494794164,'us': 99794616}) worldmap_chart.render_in_browser()
score: 0
has comment: http://stackoverflow.com/comment/82992451
accepted answer of: http://stackoverflow.com/q/48008353
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48008353
has comment: http://stackoverflow.com/comment/82990910

http://stackoverflow.com/comment/131073897
type: Comment
comment on: http://stackoverflow.com/a/47985032
type: AnswerComment
has text: Took me hours trying to figure it out before I found this great answer. The problem was, I had all the necessary methods: fill, draw, update, and flip, but in wrong order, so whoever stumbles upon this answer just remember, the order matters
score: 0

http://stackoverflow.com/a/47875305
answers question: http://stackoverflow.com/q/47875208
accepted answer of: http://stackoverflow.com/q/47875208
type: Answer
score: 3
upvote count: 3
has body: Your function, by default does not return anything. So, by default, it returns None. When calling your function, the correct thing to do would be to not assign the return value to anything, since changes are being made in-place. There are a couple of options now. The first one being: don't return anything, and don't assign anything. def upper(df, col): df[col] = df[col].str.upper() upper(df, 'reqmnt') However, this may not be the best approach (personally, I don't much fancy functions that perform in-place operations). You could, alternatively, have a copy returned via an assign call. def upper(df, col): return df.assign(**{col : df[col].str.upper()}) df = upper(df, 'reqmnt') Note that there's a caveat on this side to - assign returns a copy, and sometimes, where efficiency/performance are paramount, you don't want to be needlessly making copies of GBs of data. What to use should be decided by a combination of style and need.
has comment: http://stackoverflow.com/comment/82716204
downvote count: 0
has comment: http://stackoverflow.com/comment/82716134
type: AcceptedAnswer

http://stackoverflow.com/comment/82892760
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47961723
has text: Did you call it with ``python mainfolder/subfolder2/file2.py`` or with ``python -m mainfolder.subfolder2.file2``?

http://stackoverflow.com/comment/82754592
type: Comment
comment on: http://stackoverflow.com/a/47893860
type: AnswerComment
score: 0
has text: what may be a better advice considering that we know nothing about the list and dictionary and how do they match together

http://stackoverflow.com/comment/82941341
has text: It is supported and usage depends somewhat on the solver used. Look more carefully at [the docs](http://pythonhosted.org/PuLP/solvers.html).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47985247
score: 0

http://stackoverflow.com/a/47994699
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/47994636
type: Answer
upvote count: 1
has body: With your own code Min = YMM.groupby(['Make','Model']).StartYear.min() Max = YMM.groupby(['Make','Model']).EndYear.max() Min['Endyear']=Max.EndYear

http://stackoverflow.com/a/47880229
score: 1
has body: If you want to output 2 elements then use:- for element in a_list[:2]: print(element) If you want to output 2 elements like a string just explained in the question use:- "".join(a_list[:2])
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47880177
downvote count: 0

http://stackoverflow.com/q/47873934
answer count: 3
favorite count: 0
has answer: http://stackoverflow.com/a/47874241
score: 0
has body: i want to make quad gram for letters &gt;&gt;&gt; from nltk.probability import FreqDist &gt;&gt;&gt; from nltk.util import ngrams &gt;&gt;&gt; from nltk.text import Text &gt;&gt;&gt; fin= open(r'C:\Users\user\Desktop\quran.txt', "r", encoding='utf-8').read() i opend the folder with utf-8 &gt;&gt;&gt; generated_ngrams = ngrams(" " + fin, 4,pad_left=False, pad_right=True, right_pad_symbol=' ') generate ngrams from fin &gt;&gt;&gt; for gram in generated_ngrams : gram i+=1 if i &gt; 1000: break i make the file shorter so it is easy to handle it (' ', '\ufeff', 'ب', 'ِ') Traceback (most recent call last): File "&lt;pyshell#6&gt;", line 3, in &lt;module&gt; i+=1 NameError: name 'i' is not defined and this is the error i have
has title: whats wrong with "i" here?
tagged with: python
possible better answer: http://stackoverflow.com/a/47874241
has comment: http://stackoverflow.com/comment/82713568
has comment: http://stackoverflow.com/comment/82713344
has answer: http://stackoverflow.com/a/47874145
tagged with: python-3.x
upvote count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/82713342
accepted answer: http://stackoverflow.com/a/47874145
has answer: http://stackoverflow.com/a/47876177
type: AnsweredQuestion
type: Question

http://stackoverflow.com/comment/131098518
score: 2
comment on: http://stackoverflow.com/a/69461885
has text: Accepted answer did not work for me. This one did!
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/82722047
score: 0
type: Comment
has text: Yes, it's a python app that works great locally but not deployed.
type: QuestionComment
comment on: http://stackoverflow.com/q/47877903

http://stackoverflow.com/q/47916009
has comment: http://stackoverflow.com/comment/82807670
tagged with: python-2.7
score: 0
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/82800379
tagged with: python
has body: In the code below, I pass the path of my csv file, the topic that the user played for the quiz, the username of the user, the score obtained by the user in the quiz they played, and the difficulty the user played the quiz on into my "QuizCSV" class. In my "CSV" class, I pass the path of another csv file which contains the questions and answers for the quiz that the user chooses to play. The program is meant to take the user's score from the quiz and store the score in a csv file named "Scores", but most importantly, the program has to overwrite any previous score the user got on the quiz, with the new score the user just got which is where my program goes wrong and gives me an INDEX ERROR. This is my code(sorry for some unindented code for python): class QuizCSV: #Now Functional through 'os' and 'sys' module def __init__(self, path, topic, user, score, difficulty): self.path = path self.topic = topic self.user = user self.score = score self.difficulty = difficulty def writeScore(self): f = open(self.path, "r") for line in f: data = line.split(",") write_f = open("ScoresUpdated.csv", "a") if data[0] == self.user: if self.topic == "SCIENCE": if self.difficulty == "Easy": write_f.write(data[0] + ',' + self.score + ',' + data[2] + ',' + data[3] + ',' + data[4] + ',' + data[5] + ',' + data[6]+"\n") if self.difficulty == "Medium": write_f.write(data[0] + ',' + data[1] + ',' + self.score + ',' + data[3] + ',' + data[4] + ',' + data[5] + ',' + data[6]+"\n") if self.difficulty == "Hard": write_f.write(data[0] + ',' + data[1] + ',' + data[2] + ',' + self.score + ',' + data[4] + ',' + data[5] + ',' + data[6]+"\n") elif self.topic == "COMPUTING": if self.difficulty == "Easy": write_f.write(data[0] + ',' + data[1] + ',' + data[2] + ',' + data[3] + ',' + self.score + ',' + data[5] + ',' + data[6]+"\n") if self.difficulty == "Medium": write_f.write(data[0] + ',' + data[1] + ',' + data[2] + ',' + data[3] + ',' + data[4] + ',' + self.score + ',' + data[6]+"\n") if self.difficulty ==…
has title: Index Error: List Index out of range, when overwriting data inside a csv file
has comment: http://stackoverflow.com/comment/82807704
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82807745
type: Question

http://stackoverflow.com/comment/82676757
type: Comment
comment on: http://stackoverflow.com/q/47856298
score: 0
type: QuestionComment
has text: Try `return dictionary.dic.get(x, None)`

http://stackoverflow.com/a/48017625
type: AcceptedAnswer
downvote count: 0
score: 2
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47923068
answers question: http://stackoverflow.com/q/47923068
has comment: http://stackoverflow.com/comment/83073538
has body: There's no memory limit in child threads. (I encourage favoretti or mcy to post a similar answer for acceptance, so this doesn't join the infinite queue of unanswered questions. There's nothing wrong with OP answering his own question.)

http://stackoverflow.com/q/48009046
possible better answer: http://stackoverflow.com/a/48009113
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/48009144
has answer: http://stackoverflow.com/a/48009113
type: Question
has title: About how to find all desired format in a str
has answer: http://stackoverflow.com/a/48009131
answer count: 6
has answer: http://stackoverflow.com/a/48009095
upvote count: 1
accepted answer: http://stackoverflow.com/a/48010066
has body: I have a text like this format, s = '[aaa]foo[bbb]bar[ccc]foobar' Actually the text is Chinese car review like this 【最满意】整车都很满意，最满意就是性价比，...【空间】空间真的超乎想象，毫不夸张，...【内饰】内饰还可以吧，没有多少可以说的... Now I want to split it to these parts [aaa]foo [bbb]bar [ccc]foobar first I tried &gt;&gt;&gt; re.findall(r'\[.*?\].*?',s) ['[aaa]', '[bbb]', '[ccc]'] only got first half. Then I tried &gt;&gt;&gt; re.findall(r'(\[.*?\].*?)\[?',s) ['[aaa]', '[bbb]', '[ccc]'] still only got first half At last I have to get the two parts respectively then zip them &gt;&gt;&gt; re.findall(r'\[.*?\]',s) ['[aaa]', '[bbb]', '[ccc]'] &gt;&gt;&gt; re.split(r'\[.*?\]',s) ['', 'foo', 'bar', 'foobar'] &gt;&gt;&gt; for t in zip(re.findall(r'\[.*?\]',s),[e for e in re.split(r'\[.*?\]',s) if e]): ... print(''.join(t)) ... [aaa]foo [bbb]bar [ccc]foobar So I want to know if exists some regex could directly split it to these parts?
favorite count: 0
has answer: http://stackoverflow.com/a/48010066
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/48010328
type: AnsweredQuestion

http://stackoverflow.com/comment/82718720
comment on: http://stackoverflow.com/q/47876517
has text: Finally whether it is stored in memory or on a disk does not depend on whether you use SQL. There are database managers for SQL that can store a database completely (or partially) in RAM memory. By default most database management systems will store a large portion of the indexes in memory.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47965638
answers question: http://stackoverflow.com/q/47965618
accepted answer of: http://stackoverflow.com/q/47965618
score: 3
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: the paintEvent() method is called internally by Qt, it should not be called directly but through the update() method, but in your case you want to do it when a certain condition is used, before that you must create a flag that indicates that it should be drawn, all of the above is implemented in the following code: class Example(QWidget): def __init__(self): super(Example, self).__init__() self.initUI() self.flag = False def initUI(self): self.setFixedSize(400, 400) self.setWindowTitle('Colours') self.btn = QPushButton("Paint", self) self.btn.move(100, 100) self.btn.clicked.connect(self.onClicked) self.show() def onClicked(self): self.flag = True self.update() def paintEvent(self, e): if self.flag: qp = QPainter() qp.begin(self) self.drawRectangles(qp) qp.end() def drawRectangles(self, qp): col = QColor(0, 0, 0) col.setNamedColor('#d4d4d4') qp.setPen(col) qp.setBrush(QColor(200, 0, 0)) qp.drawRect(10, 15, 90, 60)
upvote count: 3

http://stackoverflow.com/comment/82937320
has text: @juanpa.arrivillaga actually, the initial 2 characters on the values are all the same (just realized) so I could essentially have a key value pair where both are ints, and both of the values will be 7 digits max, then append the initial characters to the value int after its retrieved.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47983993

http://stackoverflow.com/comment/82806196
has text: @lenz the error is gone but still the converted file is empty
comment on: http://stackoverflow.com/q/47901824
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82901125
type: QuestionComment
comment on: http://stackoverflow.com/q/47964808
score: 0
has text: Possible duplicate of [Selenium Web Driver & Java. Element is not clickable at point (36, 72). Other element would receive the click:](https://stackoverflow.com/questions/44912203/selenium-web-driver-java-element-is-not-clickable-at-point-36-72-other-el)
type: Comment

http://stackoverflow.com/comment/82763379
type: AnswerComment
has text: No upvote because of my lack of "reputation", but marked it correct. Thnx.
type: Comment
comment on: http://stackoverflow.com/a/47891955
score: 0

http://stackoverflow.com/q/47921202
tagged with: oauth-2.0
answer count: 1
has body: from collections import namedtuple from yaml import safe_load from uber_rides.client import UberRidesClient from uber_rides.session import OAuth2Credential from uber_rides.session import Session from builtins import input from yaml import safe_dump import utils from example.utils import import_app_credentials from uber_rides.auth import AuthorizationCodeGrant from uber_rides.client import UberRidesClient from uber_rides.errors import ClientError from uber_rides.errors import ServerError from uber_rides.errors import UberIllegalState CREDENTIALS_FILENAME = 'config.rider.yaml' # where your OAuth 2.0 credentials are stored STORAGE_FILENAME = 'session_store.yaml' filename=CREDENTIALS_FILENAME with open(filename, 'r') as config_file: config = safe_load(config_file) client_id = config['client_id'] client_secret = config['client_secret'] redirect_url = config['redirect_url'] credentials = { 'client_id': client_id, 'client_secret': client_secret, 'redirect_url': redirect_url, 'scopes': set(config['scopes']), } auth_flow = AuthorizationCodeGrant( credentials.get('client_id'), credentials.get('scopes'), credentials.get('client_secret'), credentials.get('redirect_url'), ) auth_url = auth_flow.get_authorization_url() print(auth_url) session = auth_flow.get_session("http://127.0.0.1/?state=AWBraIpW7HErfj2pMl0RTV4G1gN93yDN&amp;code=7KyJcFsWk68ZHRjUGuOyR571Y75NPk#_") client = UberRidesClient(session, sandbox_mode=True) credential = session.oauth2credential with open(storage_filename, 'w') as yaml_file: yaml_file.write(safe_dump(credential, default_flow_style=False)) output:+++++++ERROR+++++++++++++++ https://login.uber.com/oauth/v2/authorize?scope=profile+places+request+request_receipt+all_trips+history&amp;state=dO0Lo8gjVuTdIZo6UPIOfFpWKmQ133xu&amp;redirect_uri=http%3A%2F%2F127.0.0.1%2F&amp;response_type=code&amp;client_id=Ws4Za7kSxIdQdpxcZnL2WC9L8NVl3UBT Traceback (most recent call last): File "ride.py", line 53, in &lt;module&gt; session = auth_flow.get_session("http://127.0.0.…
has title: while requesting session in uber rides it is showing csrf error.and how to get the redirect url in python without going and pasting the url to browser
type: UnansweredQuestion
tagged with: uber-api
type: Question
has comment: http://stackoverflow.com/comment/82810648
tagged with: python
has answer: http://stackoverflow.com/a/47945234
score: 0

http://stackoverflow.com/q/47913548
type: UnansweredQuestion
tagged with: python
tagged with: tkinter
has answer: http://stackoverflow.com/a/48247232
tagged with: pip
has body: I have a python code that uses a gui (tkinter) and I would like to be able to use it on a website. How can this be done? For the code to work on my laptop I had to do a pip download nltk so this would also need to be done. Many thanks, Reuben
type: Question
has answer: http://stackoverflow.com/a/47914201
has comment: http://stackoverflow.com/comment/82794975
upvote count: 2
score: 0
answer count: 2
downvote count: 2
tagged with: jython
has comment: http://stackoverflow.com/comment/82794924
has comment: http://stackoverflow.com/comment/82794861
tagged with: applet
favorite count: 0
has title: Running python code on a webpage

http://stackoverflow.com/q/47938832
score: 4
has body: I ran when it was noon in turkey..this is what I got: 2017-12-22 20:11:46.038218+03:00 import pytz from pytz import timezone from datetime import datetime utc_now = datetime.now() utc = pytz.timezone('UTC') aware_date = utc.localize(utc_now) turkey = timezone('Europe/Istanbul') now_turkey = aware_date.astimezone(turkey) Why did I get 20:11:46?
tagged with: python-2.7
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47939005
favorite count: 0
has title: Python - What time is it in Turkey?
has comment: http://stackoverflow.com/comment/82846722
type: UnansweredQuestion
tagged with: python
type: Question
upvote count: 4

http://stackoverflow.com/comment/82960882
type: Comment
has text: Thanks, for help but nix found what was the problem. It was empty lines at the bottom of my csv.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47996000

http://stackoverflow.com/q/47975272
favorite count: 0
has title: How to append a value to an option in config file using Python
has answer: http://stackoverflow.com/a/47975561
has comment: http://stackoverflow.com/comment/82919772
tagged with: python
tagged with: config
answer count: 4
has body: I have config file as below: [SECTION] email = user1@exmple.com, user2@example.com Now i want to append some more email ids in email using python, which should like as given below: email = user1@exmple.com, user2@example.com, user3@example.com, user4@example.com Please let me know how to do that.
has answer: http://stackoverflow.com/a/62397233
type: AnsweredQuestion
upvote count: 0
downvote count: 2
type: Question
has answer: http://stackoverflow.com/a/47975590
accepted answer: http://stackoverflow.com/a/47975590
possible better answer: http://stackoverflow.com/a/47975561
score: -2
has answer: http://stackoverflow.com/a/76345464
has comment: http://stackoverflow.com/comment/82944686
linked to: http://stackoverflow.com/q/14087598

http://stackoverflow.com/q/47897974
has answer: http://stackoverflow.com/a/47899009
has body: I want to search for the citation using below query. After searching, I print it, it shows the results with nested list. And I want to get the number after 'citedby'. If I copy the result and store it in variable,the program works. But if I directly store in the variable, the program doesn't work. Please help me to get the number after citation and store it into DB. And the number is changing every time.Help friends. I am new to python. Attached the search result below. #!C:/Python27/python from os import * from cgi import * import scholarly import re print "content-type: text/html\n\n" search_query = scholarly.search_pubs_query('Three options for citation tracking: Google Scholar, Scopus and Web of Science') author = next(search_query).fill() print author lst = author if lst.has_key("citedby"): print lst['citedby']
has comment: http://stackoverflow.com/comment/82763655
has comment: http://stackoverflow.com/comment/82763186
score: 0
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82762987
has title: Get the number after string with search result python
accepted answer: http://stackoverflow.com/a/47899009
has comment: http://stackoverflow.com/comment/82762852
has comment: http://stackoverflow.com/comment/82763349
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82763018
has comment: http://stackoverflow.com/comment/82763169
has comment: http://stackoverflow.com/comment/82763901
type: Question
has comment: http://stackoverflow.com/comment/82763260

http://stackoverflow.com/comment/82945802
type: QuestionComment
score: 0
has text: @cᴏʟᴅsᴘᴇᴇᴅ, it's obvious that it becomes as some of that, but it should be specified evidently without confusion. Posting that is a bad habit
comment on: http://stackoverflow.com/q/47988583
type: Comment

http://stackoverflow.com/comment/84810423
comment on: http://stackoverflow.com/a/48861231
type: Comment
has text: @Pylander I've edited my answer to provide a possible solution to your memory issues. Short answer, `to_sql` is very memory intensive due to the transformation into a `list` type. (a 700MB RAM DataFrame seemed to use at peakload about 8GB RAM with the `to_sql` method due to this. )
score: 0
type: AnswerComment

http://stackoverflow.com/a/47899992
type: Answer
answers question: http://stackoverflow.com/q/47890071
score: 0
has body: You can concatenate all items inside for loop all_divs = soup.select("div.large-image") for item in all_divs: div += str(item) time += 1 or using join() time = len(all_divs) div = ''.join(str(item) for item in all_divs) You can also write in file directly inside for loop and you get to row for item in all_divs: csv_writer.writerow( [str(item).strip()] ) time += 1 Working example import urllib.request from bs4 import BeautifulSoup import csv div = "" time = 0 f = open('output.csv', 'w') csv_writer = csv.writer(f) all_urls = [ "https://www.kramerav.com/de/Product/VM-2N", "https://www.kramerav.com/de/Product/SDIA-IN2-F16", ] for url in all_urls: print('url:', url) html = urllib.request.urlopen(url).read() try: soup = BeautifulSoup(html) all_divs = soup.select("div.large-image") for item in all_divs: div += str(item) time += 1 # or time = len(all_divs) div = ''.join(str(item) for item in all_divs) # or for item in all_divs: #div += str(item) #time += 1 csv_writer.writerow( [time, str(item).strip()] ) except IndexError as ex: print('Error:', ex) time += 1 finally: print(time, div) f.close()

http://stackoverflow.com/q/47996294
has title: Python Refactor this function to reduce its Cognitive Complexity from 19 to the 15 allowed
tagged with: python
linked to: http://stackoverflow.com/q/2186525
has body: I see this message from sonarlint and trying to figure out how to reduce the Cognitive Complexity of this function. Any assistance is appreciated in advance. import os import json import click import hcl cfn = [".json", ".template", ".yaml", ".yml"] tf = ["tf"] def file_handler(dir): for root, dirs, files in os.walk(dir): for file in files: if file.endswith(tuple(cfn)): with open(os.path.join(root, file), 'r') as fin: try: file = fin.read() if "AWSTemplateFormatVersion" in file: data = json.dumps(file) print(data) except ValueError as e: raise SystemExit(e) elif file.endswith(tuple(tf)): with open(os.path.join(root, file), 'r') as file: try: obj = hcl.load(file) data = json.dumps(obj) print(data) except ValueError as e: raise SystemExit(e) return data
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/82960770
has comment: http://stackoverflow.com/comment/82960823
downvote count: 1
accepted answer: http://stackoverflow.com/a/47996644
type: Question
has answer: http://stackoverflow.com/a/47996539
tagged with: sonarlint
upvote count: 4
tagged with: python-2.7
answer count: 3
has answer: http://stackoverflow.com/a/47996403
has comment: http://stackoverflow.com/comment/82960789
favorite count: 0
has answer: http://stackoverflow.com/a/47996644
possible better answer: http://stackoverflow.com/a/47996403

http://stackoverflow.com/a/47894372
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82755654
has comment: http://stackoverflow.com/comment/85756352
accepted answer of: http://stackoverflow.com/q/47882616
has body: Instead of manually flushing and setting ids etc. you could let SQLAlchemy handle persisting your object graph. You'll just need one more adjacency list relationship in Address and you're all set: class User(Model): __tablename__ = 'user' id = Column(Integer, primary_key=True) simple = Column(String(255)) main_address = Column(String(255)) addresses = relationship("Address", cascade="all, delete-orphan") def __init__(self, addresses, simple): self.simple = simple self.main_address = addresses[0] self.addresses = Address.complex_cls_method( key="address", values=addresses ) class Address(Model): __tablename__ = 'address' id = Column(Integer, primary_key=True) keyword = Column(String(255)) value = Column(String(255)) user_id = Column(Integer, ForeignKey('user.id'), nullable=False) parent_id = Column(Integer, ForeignKey('address.id'), nullable=True) # For handling parent/child relationships in factory method parent = relationship("Address", remote_side=[id]) @classmethod def complex_cls_method(cls, key, values): main = cls(keyword=key, value="") addrs = [cls(keyword=key, value=item, parent=main) for item in values] return [main] + addrs if __name__ == "__main__": user = User([u"address1", u"address2"], "simple") session.add(user) session.commit() print(user.addresses) Note the absence of manual flushes etc. SQLAlchemy automatically figures out the required order of insertions based on the object relationships, so that dependencies between rows can be honoured. This is a part of the Unit of Work pattern.
answers question: http://stackoverflow.com/q/47882616
has comment: http://stackoverflow.com/comment/85756479
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85754183
has comment: http://stackoverflow.com/comment/85754631
upvote count: 2

http://stackoverflow.com/a/48014396
type: AcceptedAnswer
has body: There is no 'official' mechanism in Django to do this. Recently, some ideas of adding some official solution to the Django framework were discussed in this thread on the django-developers mailing list. It might serve as an inspiration for what solution is currently best for your case. Your method works well for simple calculations. If the property gets more expensive to calculate, using @cached_property can help a bit if the value is used multiple times. You can also rely on the database to compute these values by adding an annotation to the queryset. This requires defining a custom Manager: class InventoryManager(models.Manager): def get_queryset(self): super().get_queryset().annotate(total=F('stock_in') + F('balance')) class Inventory(models.Model): date = models.DateField(("Date"), default=datetime.now) product = models.ForeignKey(Product) stock_in = models.IntegerField() stock_out = models.IntegerField() balance = models.IntegerField() particulars = models.CharField(max_length=250) objects = InventoryManager() This will add a balance attribute to your Inventory model instances if they are retreived using the default manager. The problem with this approach (like discussed in the linked django-developers thread) is what your expectations are when modals are changed locally. For example, with the custom manager in place, if I were to change stock_in for a modal, the value of total would still be valid for the value of stock_in at the time of retrieving it from the database: &gt;&gt; qs = Inventory.objects.filter(date__gte=date(2017, 12, 22)) &gt;&gt; inventory0 = qs[0] &gt;&gt; print(inventory0.total, inventory0.stock_in, inventory.balance) 100, 50, 50 &gt;&gt; inventory.balance = 100 &gt;&gt; print(inventory0.total, inventory0.stock_in, inventory.balance) 100, 50, 100 Also, an model instance not fetched from the db at all wont have a total attribute: &gt;&gt; inventory = Inventory(stock_in=20, balance=10) &gt;&gt; inventory.total AttributeError: 'Inventory' object…
accepted answer of: http://stackoverflow.com/q/48011901
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48011901

boto3
tags question: http://stackoverflow.com/q/47946875
tags question: http://stackoverflow.com/q/47909840
tags question: http://stackoverflow.com/q/47942573
tags question: http://stackoverflow.com/q/47919164
tags question: http://stackoverflow.com/q/47994825
tags question: http://stackoverflow.com/q/47933931
tags question: http://stackoverflow.com/q/48014309
tags question: http://stackoverflow.com/q/47961638
tags question: http://stackoverflow.com/q/47976502
tags question: http://stackoverflow.com/q/47921273
tags question: http://stackoverflow.com/q/47858541
tags question: http://stackoverflow.com/q/47918524
tags question: http://stackoverflow.com/q/47928448
tag name: boto3
tags question: http://stackoverflow.com/q/47867995
tags question: http://stackoverflow.com/q/47890544
type: Tag
tags question: http://stackoverflow.com/q/47857179
tags question: http://stackoverflow.com/q/47942154
tags question: http://stackoverflow.com/q/47905855
tags question: http://stackoverflow.com/q/47933565
tags question: http://stackoverflow.com/q/48014551

http://stackoverflow.com/comment/82709799
has text: Now you start to see the real problem and why nobody can currently help you... You need to find out the colors for the colorcoding or devise a threshold yourself and then you are almost done.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47871213

http://stackoverflow.com/q/47978225
tagged with: default-value
linked to: http://stackoverflow.com/q/12627118
duplicate of: http://stackoverflow.com/q/4859993
has answer: http://stackoverflow.com/a/47978371
answer count: 1
downvote count: 0
has title: How to retrieve/know function's default values
favorite count: 0
duplicate of: http://stackoverflow.com/q/12627118
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/25847035
accepted answer: http://stackoverflow.com/a/47978371
type: AnsweredQuestion
score: 1
has body: I am a python beginner and I currently struggle with some (probably quite simple) stuff. I would like to know the default parameters of a python function, more specifically of cv2.ORB_create(). With the following code I managed to see the 'documentation string': import cv2 orb = cv2.ORB_create() print(cv2.ORB_create.__doc__) However, print(cv2.ORB_create.__defaults__) just gives me an error; AttributeError: 'builtin_function_or_method' object has no attribute '__defaults__' Maybe I am missing a link between functions, modules, etc. but I am really stuck... Since the concern was brought up that this is a duplicate. I also tried inspect.signature and by extension inspect.getargspec, but this give me another error ValueError: no signature found for builtin &lt;built-in function ORB_create&gt;.
duplicate of: http://stackoverflow.com/q/2677185
has comment: http://stackoverflow.com/comment/82926612
type: Question
tagged with: function

http://stackoverflow.com/comment/82786178
has text: @Usernamenotfound: That's just creating the string object yourself instead of letting `print()` do it. It would work, but I can't see any advantage.
type: AnswerComment
comment on: http://stackoverflow.com/a/47909130
score: 0
type: Comment

http://stackoverflow.com/q/47944709
has comment: http://stackoverflow.com/comment/82860142
has comment: http://stackoverflow.com/comment/82860223
type: Question
has comment: http://stackoverflow.com/comment/82860334
has body: I'm using paramiko on my local to ssh into a unix server. There is an executable file that I would like to launch from my local on the server. The executable currently fails from local/paramiko because the LD_LIBRARY_PATH environment variable isn't set correctly when I ssh using paramiko, however it's set automatically when I use putty and work interactively. When I log into the machine via putty, the executable file works as expected, but when I log in via paramiko from my local, the exectuable returns an error rleated to the LD_LIBRARY_PATH environment not being set correctly. When I log into the machine using putty, an admin .login file specifies a series of paths for variable LD_LIBRARY_PATH. It looks like this: setenv LD_LIBRARY_PATH path1:path2:path3:... However, when logging in via paramiko, this admin script isn't initiated, and I need to manually set the LD_LIBRARY_PATH variable. My connection looks like: ssh = pk.SSHClient() ssh.set_missing_host_key_policy(pk.AutoAddPolicy()) ssh.connect(hostname='server', username='user', password='password') The command I want to run looks like: stdin, stdout, stderr = ssh.exec_command('nohup executablefile') How can I set my LD_LIBRARY_PATH and then execute my program using paramiko's exec_command, or should I be looking for a different function?
has comment: http://stackoverflow.com/comment/82859857
tagged with: paramiko
has answer: http://stackoverflow.com/a/50997413
has title: Setting Environment Variables with Paramiko
has answer: http://stackoverflow.com/a/47945370
score: 0
answer count: 2
tagged with: environment-variables
duplicate of: http://stackoverflow.com/q/31964108
has comment: http://stackoverflow.com/comment/82860721
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82863843
tagged with: ssh
tagged with: python
tagged with: unix
linked to: http://stackoverflow.com/q/31964108

http://stackoverflow.com/comment/82715184
type: AnswerComment
has text: My answer yields the expected output according to your updated question. What are you trying to accomplish with the groupby()?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47872569

tensorflow
tags question: http://stackoverflow.com/q/47984969
tags question: http://stackoverflow.com/q/47976845
tags question: http://stackoverflow.com/q/47915615
tags question: http://stackoverflow.com/q/47925287
tags question: http://stackoverflow.com/q/47893421
tags question: http://stackoverflow.com/q/47902118
tags question: http://stackoverflow.com/q/47871331
tags question: http://stackoverflow.com/q/47970716
tags question: http://stackoverflow.com/q/47980060
tags question: http://stackoverflow.com/q/47965256
tags question: http://stackoverflow.com/q/47997203
tags question: http://stackoverflow.com/q/47867191
tags question: http://stackoverflow.com/q/48000248
tags question: http://stackoverflow.com/q/47907148
tags question: http://stackoverflow.com/q/47954034
tags question: http://stackoverflow.com/q/47970040
tags question: http://stackoverflow.com/q/47932738
tags question: http://stackoverflow.com/q/47993569
tags question: http://stackoverflow.com/q/47922435
tags question: http://stackoverflow.com/q/47910329
tags question: http://stackoverflow.com/q/47990621
tags question: http://stackoverflow.com/q/47857750
tags question: http://stackoverflow.com/q/47897199
tags question: http://stackoverflow.com/q/47928955
tags question: http://stackoverflow.com/q/47940874
tags question: http://stackoverflow.com/q/47948249
tags question: http://stackoverflow.com/q/47936668
tags question: http://stackoverflow.com/q/47901580
tags question: http://stackoverflow.com/q/47987202
tags question: http://stackoverflow.com/q/47885357
tags question: http://stackoverflow.com/q/47911093
tags question: http://stackoverflow.com/q/47945175
tags question: http://stackoverflow.com/q/48012287
tags question: http://stackoverflow.com/q/48007984
tags question: http://stackoverflow.com/q/47897997
tags question: http://stackoverflow.com/q/47868612
tags question: http://stackoverflow.com/q/47898147
tags question: http://stackoverflow.com/q/47935393
tags question: http://stackoverflow.com/q/48013711
tags question: http://stackoverflow.com/q/48005232
tags question: http://stackoverflow.com/q/47990089
tags question: http://stackoverflow.com/q/47891429
tags question: http://stackoverflow.com/q/48004017
tags question: http://stackoverflow.com/q/47885698
tags question: http://stackoverflow.com/q/47918681
tags question: http://stackoverflow.com/q/48003535
tags question: http://stackoverflow.com/q/47946413
tags question: http://stackoverflow.com/q/47903504
tags question: http://stackoverflow.com/q/47945312
tags question: http://stackoverflow.com/q/47942693
tags question: http://stackoverflow.com/q/47860633
tags question: http://stackoverflow.com/q/47954405
tags question: http://stackoverflow.com/q/47932396
tag name: tensorflow
tags question: http://stackoverflow.com/q/47978137
tags question: http://stackoverflow.com/q/47976616
tags question: http://stackoverflow.com/q/47985209
tags question: http://stackoverflow.com/q/47973009
tags question: http://stackoverflow.com/q/47925346
tags question: http://stackoverflow.com/q/47877858
tags question: http://stackoverflow.com/q/47907409
tags question: http://stackoverflow.com/q/47941831
tags question: http://stackoverflow.com/q/47890612
tags question: http://stackoverflow.com/q/47974502
tags question: http://stackoverflow.com/q/48006966
tags question: http://stackoverflow.com/q/47994726
tags question: http://stackoverflow.com/q/47863220
tags question: http://stackoverflow.com/q/47968975
tags question: http://stackoverflow.com/q/48009243
tags question: http://stackoverflow.com/q/47885144
tags question: http://stackoverflow.com/q/47994063
tags question: http://stackoverflow.com/q/47949159
tags question: http://stackoverflow.com/q/47929627
tags question: http://stackoverflow.com/q/47991379
tags question: http://stackoverflow.com/q/47964765
tags question: http://stackoverflow.com/q/47896378
tags question: http://stackoverflow.com/q/47888595
tags question: http://stackoverflow.com/q/47856879
tags question: http://stackoverflow.com/q/47867748
tags question: http://stackoverflow.com/q/47959640

http://stackoverflow.com/comment/82988284
has text: You can use the pipe and use stdin and stdout to read the data from each other files, But one file have to execute the completely.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48009926

http://stackoverflow.com/comment/82905417
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47967953
type: AnswerComment
has text: Thanks for your answer. Can you please explain what is the correct formatting? Also, I actually tried to pass all the headers values but got the same result.

http://stackoverflow.com/a/47978248
type: Answer
has body: 1 liner list comp that mutates the original list without saving it to a variable (kinda weird): [colony.append([i, 'b', 'c']) for i in range(1, R + 1)] print(colony) outputs [['A', 'B', 'C'], [1, 'b', 'c'], [2, 'b', 'c'], [3, 'b', 'c'], [4, 'b', 'c'], [5, 'b', 'c']]
answers question: http://stackoverflow.com/q/47976998
score: 0

http://stackoverflow.com/comment/82834458
type: Comment
comment on: http://stackoverflow.com/q/47932656
type: QuestionComment
has text: If @ChrisyantarHasiholan does subclass `int`, he might find https://stackoverflow.com/questions/3238350/subclassing-int-in-python helpful.
score: 0

http://stackoverflow.com/comment/82888210
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47959497
has text: Both pages link to the changelog.

http://stackoverflow.com/comment/82792094
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47910374
type: Comment
has text: @furas thanks for the response! I think possibly scraping data from the maps 'markers' is what I'm probably going to opt for. for example. input the county > retrieve data sets of markers > store the long/lat from markers into the database. I am just struggling to find the 'marker' information in the HTML at the moment

http://stackoverflow.com/a/48016497
has comment: http://stackoverflow.com/comment/83021901
has comment: http://stackoverflow.com/comment/83022281
upvote count: 1
has comment: http://stackoverflow.com/comment/83030799
has comment: http://stackoverflow.com/comment/83028189
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83028548
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/48014529
answers question: http://stackoverflow.com/q/48014529
has comment: http://stackoverflow.com/comment/83031023
has comment: http://stackoverflow.com/comment/83022099
has body: IIUC: Using a combination of melt so the we can merge values from returns by desired columns. Then use pivot to reshape the data back, as seen below. portfolios.columns = portfolios.columns.astype(int) newdf = portfolios.reset_index().melt(id_vars='index',var_name=['FROMDATE'],value_name='PERMNO').merge(returns,on=['FROMDATE','PERMNO'],how='left').pivot(index='index',columns='FROMDATE',values='MORET') Which returnsthe DataFrame below FROMDATE 20130630 20130731 20130831 20130930 20131031 20131130 20131231 index 0 NaN NaN NaN NaN NaN NaN -0.022304 1 NaN NaN NaN NaN NaN NaN 0.012283 2 NaN NaN NaN NaN NaN NaN -0.016453 Sort columns newdf.loc[:,newdf.columns.sort_values(ascending=False)]

http://stackoverflow.com/q/47881729
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/7204805
linked to: http://stackoverflow.com/q/3294889
has answer: http://stackoverflow.com/a/47883441
score: 1
type: Question
has title: How do you combine two similar nested dictionaries into one, each with some shared and unique nested elements (Python)?
has body: I have two large nested dictionaries that I need to merge into a single one: dict1={ 1: {"trait1: 32", "trait2": 43, "trait 3": 98}, 2: {"trait1: 38", "trait2": 40, "trait 3": 95}, .... } and dict2={ 1: {"trait1: 32", "trait2": 43, "trait 4": 54}, 2: {"trait1: 38", "trait2": 40, "trait 4": 56}, .... } and what I'd like to get is this: dict3={ 1: {"trait1: 32", "trait2": 43, "trait 3": 98, "trait 4": 54}, 2: {"trait1: 38", "trait2": 40, "trait 3": 95, "trait 4": 56}, .... } I've tried using: dict3=dict(list(dict1.items()) + list(dict2.items())) But it simply copies dict2 for me. I've also tried looping through the "main" keys like this(I copied the first dictionary to become the final output): dict3 = dict(dict1) for key1 in dict3: for key2 in dict2: dict3[key1].update({"trait4": dict2[key2]["trait4"]}) But that doesn't work, only every few entries come out as expected in the output. And I'm fairly sure that my approach is wrong on this. Any help is appreciated!
linked to: http://stackoverflow.com/q/3975376
answer count: 3
possible better answer: http://stackoverflow.com/a/47883441
downvote count: 0
tagged with: nested
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47882523
linked to: http://stackoverflow.com/q/1602934
accepted answer: http://stackoverflow.com/a/47882523
has answer: http://stackoverflow.com/a/47884895
upvote count: 1
tagged with: python
tagged with: dictionary

http://stackoverflow.com/q/47919877
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82807826
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82807623
type: Question
tagged with: opencv
linked to: http://stackoverflow.com/q/60978380
has answer: http://stackoverflow.com/a/47919891
has body: Respected All, I am using watershed algorithm in the attached image, now I want to find the size of the enclosed boundary image (irregular object in the image). The image is attached:
has comment: http://stackoverflow.com/comment/82807744
has comment: http://stackoverflow.com/comment/108840743
tagged with: contour
downvote count: 0
answer count: 1
has title: size of the enclosed region in opencv python
favorite count: 0
tagged with: python-3.x
tagged with: watershed

http://stackoverflow.com/comment/82769574
type: Comment
type: QuestionComment
score: 0
has text: ```while True: time.sleep(1) ```
comment on: http://stackoverflow.com/q/47901481

http://stackoverflow.com/comment/82869088
has text: The function works fine here. Did you remember to call it?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47949655
score: 1

http://stackoverflow.com/q/47921842
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has title: How to convert a CSV file to SVM for ML training
tagged with: python
has body: I have this dataset i wish to train multiple ML models on in Apache Spark 2.1.1. It consists of 10 columns, 2 of which contain strings. Removing these columns is not an option as they are vital to the information I wish to gather. However, I am unable to convert the CSV file to SVM to proceed with the experiment because of this problem. I have tried converting it to RDD which is successful then save as SVM but the file is never saved. Is there any other way around this?
downvote count: 1
type: Question
upvote count: 0
tagged with: naivebayes
tagged with: pyspark
score: -1
tagged with: svm
answer count: 1
has answer: http://stackoverflow.com/a/47921972
favorite count: 0

http://stackoverflow.com/comment/82823539
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47926987
score: 0
has text: I parsed it down, but I will try that too thanks.

http://stackoverflow.com/q/47994041
upvote count: 4
has answer: http://stackoverflow.com/a/47994125
answer count: 3
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/82956585
favorite count: 0
has body: I am importing excel file with 30 columns to dataframe and want to change column type of all the columns to string, how to do this? data = pd.read_excel(excelPath, sheetname='Donor', converters={'Code':str})
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/47994184
has comment: http://stackoverflow.com/comment/82956373
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/56487093
tagged with: excel
type: Question
has title: Apply converters to all the columns while reading excel file, Python 3.6
has comment: http://stackoverflow.com/comment/111651370
tagged with: dataframe
score: 4

http://stackoverflow.com/comment/82688002
comment on: http://stackoverflow.com/q/47861418
type: QuestionComment
has text: @furas I think you got the key point!!! I need to login to get the file and I just login in the phantomjs but now I'm downloading by requests. It's out of phantomjs right?
score: 0
type: Comment

http://stackoverflow.com/a/47916098
has body: Here's a way to solve this. I've included code to build the DataFrame, find the string values and then drop them. df.drop returns a modified copy of the original df unless you specify inplace=True, so if you want, you can assign the original name of the df df = df.drop..., or use the inplace argument. import pandas as pd import numpy as np # build the df df = pd.DataFrame({'col_name' : [2, 2, 'yes', 2, 'yes']}) print(df) col_name 0 2 1 2 2 yes 3 2 4 yes # ask what are the types in column df.col_name.apply(type) 0 &lt;class 'int'&gt; 1 &lt;class 'int'&gt; 2 &lt;class 'str'&gt; 3 &lt;class 'int'&gt; 4 &lt;class 'str'&gt; Name: col_name, dtype: object # you can see that the strings are in row 2 and 4 # and drop them like this df.drop([2, 4], axis='rows') col_name 0 2 1 2 3 2
score: 0
answers question: http://stackoverflow.com/q/47896617
type: Answer

http://stackoverflow.com/comment/82785039
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47908596
has text: Thank you @n00dl3! So it doesn't related to my server side code? I'm confused because I would say if the POST request works my server side code should make the redirection. I don't want to reload the code with ajax, I would like to reload it with the request I sent via ajax to my server. Or the post request can't call the `def signup()` method?
score: 0

http://stackoverflow.com/comment/82800072
score: 1
has text: I've updated my answer now. Instead of movielist2.append(list(movie)), it's movielist2.append([movie]).
comment on: http://stackoverflow.com/a/47912114
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/82809209
score: 0
type: Comment
has text: @antonagestam thanks, is this safer than the option provided by the accepted answer?
type: QuestionComment
comment on: http://stackoverflow.com/q/47920228

http://stackoverflow.com/comment/83030820
type: QuestionComment
has text: @Evert We might be making progress. I tried this command from the link you pasted above: `python3 -m pip install --upgrade --force-reinstall --no-cache-dir jupyter`. The command`python3 -m jupyter --help` does now work, but `python3 -m jupyter notebook` still gives the same error above, i.e. `Error executing Jupyter command 'notebook': [Errno 2] No such file or directory`
comment on: http://stackoverflow.com/q/48012813
score: 0
type: Comment

http://stackoverflow.com/a/47945390
type: AcceptedAnswer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/47945122
has comment: http://stackoverflow.com/comment/82861249
type: Answer
answers question: http://stackoverflow.com/q/47945122
has comment: http://stackoverflow.com/comment/82867437
upvote count: 1
has body: You probably want to set your timeseries column as your index. df = df.set_index('timestamp') This allows for much smarter time-series algorithms, including rolling operations, random access, and so on. You may want to look at http://dask.pydata.org/en/latest/dataframe-api.html#rolling-operations. Note that in general setting an index and performing a full sort can be expensive. Ideally your data comes in a form that is already sorted by time. Example So in your case, if you just want to compute a derivative you might do something like the following: df = df.set_index('timestamp') df.x.diff(...)
has comment: http://stackoverflow.com/comment/82860693
has comment: http://stackoverflow.com/comment/82861012

http://stackoverflow.com/comment/82901609
comment on: http://stackoverflow.com/q/47951605
score: 0
type: QuestionComment
has text: See [How do you sign Certificate Signing Request with your Certification Authority](http://stackoverflow.com/a/21340898/608639) and [How to create a self-signed certificate with openssl?](http://stackoverflow.com/q/10175812/608639) You will also need to place the self-signed certificate in the appropriate trust store.
type: Comment

http://stackoverflow.com/comment/82841032
score: 0
type: AnswerComment
has text: Where's the question
type: Comment
comment on: http://stackoverflow.com/a/47935755

http://stackoverflow.com/a/47972221
downvote count: 1
score: -1
answers question: http://stackoverflow.com/q/47972195
upvote count: 0
type: Answer
has body: You can use reduce for a more functional solution: import re import itertools from functools import reduce s = {'abc': 123123, 'defg': [ ['123.4', '10'], ['567.8', '10'], ['91011.12', '10'] ]} new_s = list(itertools.chain(*[[float(c) for c in itertools.chain(*b) if re.findall('^\d+\.\d+$', c)] for a, b in s.items() if isinstance(b, list)])) print(new_s) print(reduce(lambda x, y:x+y, new_s)) Output: [123.4, 567.8, 91011.12] 91702.32

cublas
tags question: http://stackoverflow.com/q/47928371
tag name: cublas
type: Tag

http://stackoverflow.com/q/47860592
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/82686312
has comment: http://stackoverflow.com/comment/82685983
has comment: http://stackoverflow.com/comment/82686982
has comment: http://stackoverflow.com/comment/82686349
has comment: http://stackoverflow.com/comment/82687452
has comment: http://stackoverflow.com/comment/82686044
tagged with: arrays
answer count: 1
favorite count: 0
has body: I have inherited a project, and I am completely new to Python. What I need to do is read records from a file that are in binary. I need to read every byte to put in an bytearray for processing. The input records can have embedded /n or any other binary value. The program currently reads the file until it reaches the /n and stops reading. So a record that has 36 bytes will find the first /n say in position 4 and quit reading. I need to be able to read the /n for processing in the program. How do I get it to read all the bytes? Here is the current file read line: lcounter = 0 fline = open(inputFileName, 'rb') while True: DataRead = fline.readline().rstrip() # I don't want the last /n in each record if lcounter == 0: processLineOne() else: if lcounter == 1: aryDataRead = [DataRead] elif lcounter == 2: aryDataRead.append(DataRead) elif lcounter == 3: aryDataRead.append(DataRead) fline.close() break lcounter += 1 ProcessDataRead() Record 3 has 36 bytes, but only puts 3 in the array because byte 4 is \n. How do I keep the \n? Thanks
has comment: http://stackoverflow.com/comment/82686136
has answer: http://stackoverflow.com/a/47876307
type: UnansweredQuestion
has title: Python Retain embedded /n during readline operations
tagged with: python
has comment: http://stackoverflow.com/comment/82686229
score: 0
upvote count: 1

django-polymorphic
type: Tag
tags question: http://stackoverflow.com/q/47986957
tag name: django-polymorphic

http://stackoverflow.com/comment/82846995
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47930656
has text: Many thanks, this is very clear and actually not as complicated as I thought would be. If I understand everything well, I do `import locale_patch` in the `__init__.py` of my library and this will cause importing of my library to automatically patch the locale. Then the only situation where `RuntimeError` may be inappropriately raised is if the user sets the locale *before* importing my library, what looks like not really good code (import statements should be at start of code).

http://stackoverflow.com/comment/82716158
has text: @VuralErdogan, I've reworked it so it does not have a scroll bar initially but adds them as the image expands past the horizontal and vertical edges of the frame. Probably not perfect but simple and uses only turtle `ScrolledCanvas`.
type: Comment
comment on: http://stackoverflow.com/a/47862969
score: 0
type: AnswerComment

http://stackoverflow.com/comment/101295618
type: Comment
has text: @jonrsharpe `namedtuples` CAN have default values. Have a look here: https://stackoverflow.com/questions/11351032/namedtuple-and-default-values-for-optional-keyword-arguments
type: QuestionComment
comment on: http://stackoverflow.com/q/47955263
score: 12

http://stackoverflow.com/a/48010885
answers question: http://stackoverflow.com/q/48010462
score: 0
type: Answer
has body: Since you have not described all the situations like what if there are two 1 at last then you want to ignore that or want to add that because that 1 is single and there are no other next two elements , But as you commented out : I am also interested that the '1' value becomes -999 So the output looks like [-999, -999, -999, 4, 5, 2, 3, -999, -999, -999, 4, 5, 1, -999, -999, 3, 2, -999, -999, -999, -999] So : Here is very simple approach without making it complicated or importing any module: a=[1,2,3,4,5,2,3,1,2,3,4,5,1,5,5,3,2,1,3,1,1] for i,j in enumerate(a): try: if j == 1: a[i] = -999 a[i + 1] = -999 a[i + 2] = -999 except IndexError: pass print(a) output: [-999, -999, -999, 4, 5, 2, 3, -999, -999, -999, 4, 5, -999, -999, -999, 3, 2, -999, -999, -999, -999]

http://stackoverflow.com/comment/82880552
comment on: http://stackoverflow.com/a/47949694
score: 0
type: AnswerComment
has text: Rolin, thank you for your awnser. But I don't think you understand my question. When I import just a package, the content of its __init__ file is executed in the script importing the package. If the content of the __init__ (as in my example) just import an object from a module as in "from module import function object" , only the function object should be accesible to the __init__ and to the script importing the content of the __init__. The whole module to which the function object belong should not be accesible. That is my doubt.
type: Comment

http://stackoverflow.com/q/47949757
tagged with: python
has answer: http://stackoverflow.com/a/47949851
has body: Django 1.11 Python 3.6 Allauth (without the social part for now) Sqlite3 db backend I am working my way through building a Django site. Allauth is handeling the basic registration/login stuff. I have a user profile that has a foreign key relationship into the user table -- it is not an extended user model per se. It is a model that links to the user table. I have a view and a form that display the profile form. I have html5 form validation plus some form validation set up that seems to work. If I enter bad form data and submit then the various field errors are reported. If I enter all the required data and hit submit a record is created in the db but not all form fields with required values are inserted into the db table. I will get first &amp; last names, phone and birthdate. The address info never makes it to the db. I do not see any errors reported. Sorry for the length of the supporting material... The model from django.contrib.auth.models import User from django.db import models class Profile(models.Model): class Meta: unique_together = [ ("last_name", "first_name", "middle_name", "birthdate"), ] get_latest_by = "dateCreated" ordering = ['last_name', 'first_name', 'middle_name', 'birthdate'] indexes = [ models.Index(fields=['last_name', 'first_name']), models.Index(fields=['last_name'], name='last_name_idx'), models.Index(fields=['first_name'], name='first_name_idx'), models.Index(fields=['birthdate']), ] user = models.OneToOneField( User, on_delete=models.CASCADE, blank=False, null=False, ) last_name = models.CharField( max_length=64, blank=False, null=False, ) first_name = models.CharField( max_length=64, blank=False, null=False, ) middle_name = models.CharField( max_length=64, blank=True, null=True, ) birthdate = models.DateField( blank=False, null=False ) Address1 = models.CharField( max_length=38, blank=False, null=False, ) Address2 = models.CharField( max_length=38, blank=True, null=True, ) City = models.CharField( max_length=15, blank=False, null=False, …
tagged with: django
type: AnsweredQuestion
type: Question
has title: Django model form not saving all fields to db
answer count: 1
accepted answer: http://stackoverflow.com/a/47949851
score: 0

http://stackoverflow.com/a/47944775
answers question: http://stackoverflow.com/q/47944706
type: Answer
score: 2
upvote count: 3
downvote count: 1
has body: Assuming what you want is to have a be keys in the outer dictionary, and b and c the key and value element of the inner dicts: d = {k: {x: y} for k, x, y in zip(a, b, c)} Update: However, in your example x and y are strings, so if that's what you want: d = {k: {str(x): str(y)} for k, x, y in zip(a, b, c)}

http://stackoverflow.com/a/47891720
has body: Passing None to a shape argument of a tf.placeholder tells it simply that that dimension is unspecified, and to infer that dimension from the tensor you are feeding it during run-time (when you run a session). Only some arguments (generally the batch_size argument) can be set to None since Tensorflow needs to be able to construct a working graph before run time. This is useful for when you don't want to specify a batch_size before run time.
type: AcceptedAnswer
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/82750407
type: Answer
answers question: http://stackoverflow.com/q/47891429
accepted answer of: http://stackoverflow.com/q/47891429
upvote count: 4

http://stackoverflow.com/q/47967836
tagged with: collision
type: AnsweredQuestion
tagged with: detection
has answer: http://stackoverflow.com/a/47970998
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/47970998
duplicate of: http://stackoverflow.com/q/63561028
score: -1
has comment: http://stackoverflow.com/comment/82906899
has body: I want to make the Collision Detection scripts. When I run my scripts Pygame always say the images are in collision. It prints "crash" when I use {"rect = cat1.img.get_rect()" then "rect.colliderect(another rect of other image)} and this way both. I used cat.png in two sprites. Questions Is cat.png bad? Am I not using the right scripts? Is my computer weird? Here are my scripts and the cat.png. import pygame, sys, time from pygame.locals import * pygame.init() Fps = 100 fpsClock = pygame.time.Clock() Displaysurf = pygame.display.set_mode((300, 300))# full is 1900, 1000 pygame.display.set_caption('Animation') white = (255, 255, 255) class cat: def __init__(self, x, y): self.img = pygame.image.load('cat.png') self.x = x self.y = y self.rect = self.img.get_rect() def draw(self): Displaysurf.blit(self.img, (self.x, self.y)) def colde(self, sprite1, sprite2): col = pygame.sprite.collide_rect(sprite1, sprite2) if col == True: print("crash!") cat1 = cat(10, 10) cat2 = cat(100, 100) while True: Displaysurf.fill(white) cat1.draw() cat2.draw() for event in pygame.event.get(): if event.type==QUIT: pygame.quit() sys.exit() keys = pygame.key.get_pressed() if keys[pygame.K_UP]: cat1.y -= 3 if keys[pygame.K_DOWN]: cat1.y += 3 if keys[pygame.K_LEFT]: cat1.x -= 3 if keys[pygame.K_RIGHT]: cat1.x += 3 cat1.colde(cat1, cat2) pygame.display.update() fpsClock.tick(Fps)`
has title: Python Collision Detection of image with pygame (image type : png)
upvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82907608
linked to: http://stackoverflow.com/q/63561028
tagged with: python
tagged with: pygame
tagged with: http://stackoverflow.com/tag/png

http://stackoverflow.com/q/47901728
tagged with: string
tagged with: pandas
upvote count: 1
favorite count: 0
has title: Decode a Python json in string with a u' and Decimal values
has comment: http://stackoverflow.com/comment/82770163
tagged with: python
has comment: http://stackoverflow.com/comment/82770165
has comment: http://stackoverflow.com/comment/82771063
has body: I need to decode and load to a DB, a string which arrives in the following format: "[{u'date': 1508760000000, u'value': 0}, {u'date': 1509364800000, u'value': Decimal('5.989999771118164')}, {u'date': 1509969600000, u'value': Decimal('5.989999771118164')}, {u'date': 1510574400000, u'value': Decimal('9.579999923706055')}]" Currently, this is the code I use in order to turn it into a dataframe: import pandas as pd import json #json for example: my_json="""[{u'date': 1508760000000, u'value': 0}, {u'date': 1509364800000, u'value': Decimal('5.989999771118164')}, {u'date': 1509969600000, u'value': Decimal('5.989999771118164')}, {u'date': 1510574400000, u'value': Decimal('9.579999923706055')}]""" my_json=my_json[1:-1] my_json=my_json.replace("u'","'") my_json=my_json.replace("'",'"') my_json=my_json.replace('Decimal("','') my_json=my_json.replace('")','') my_json=my_json.replace(', {','~ {') my_json_list=my_json.split('~') my_dict_list=[json.loads(row) for row in my_json_list] df=pd.DataFrame(my_dict_list) Is there a shorter/more elegant way to perform this?
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/82770350
score: 1
tagged with: http://stackoverflow.com/tag/json
linked to: http://stackoverflow.com/q/14611352
tagged with: dataframe
has answer: http://stackoverflow.com/a/47902028
has answer: http://stackoverflow.com/a/47902109
has comment: http://stackoverflow.com/comment/82771337
accepted answer: http://stackoverflow.com/a/47902109
has comment: http://stackoverflow.com/comment/82771049
type: Question
has comment: http://stackoverflow.com/comment/82771502
has comment: http://stackoverflow.com/comment/82773859
has comment: http://stackoverflow.com/comment/82770719
answer count: 2
possible better answer: http://stackoverflow.com/a/47902028

http://stackoverflow.com/comment/82988288
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48009783
has text: If this _is_ a Tkinter Canvas then I'm afraid you're out of luck. The Tkinter Canvas widget doesn't provide a way to access the pixel data. Allegedly, there _is_ a hack which uses another library to do it, but it's slow. As Bryan mentions [here](https://stackoverflow.com/a/28015006/4014959), you'd be better off using a PhotoImage instead of a Canvas.

http://stackoverflow.com/comment/82893748
comment on: http://stackoverflow.com/a/47962254
has text: getTuple not defined? what am I missing?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82956253
type: QuestionComment
comment on: http://stackoverflow.com/q/47993740
score: 0
type: Comment
has text: This question was a hard one to explain. I'm looking to substitute in all possible locations, thus the list of permutations are generated. I tried to explain it this way because I was focused on using itertools.permutations to solve this. Perhaps that wasn't the correct wording.

http://stackoverflow.com/a/48005958
type: AcceptedAnswer
has body: Solved: the root of the problem was the fact that subsequent calls to logging.basicConfig do nothing, only the first call affects the basic config of the root handler. So nothing worked until I restarted the kernel in my notebook or something.
type: Answer
upvote count: 15
answers question: http://stackoverflow.com/q/48002785
downvote count: 0
has comment: http://stackoverflow.com/comment/130311576
accepted answer of: http://stackoverflow.com/q/48002785
has comment: http://stackoverflow.com/comment/123898862
has comment: http://stackoverflow.com/comment/137699409
has comment: http://stackoverflow.com/comment/129907004
score: 15

http://stackoverflow.com/comment/82943696
type: Comment
type: QuestionComment
has text: I have already follow this. but still not able to fix
comment on: http://stackoverflow.com/q/47987124
score: 0

http://stackoverflow.com/q/47903168
tagged with: jmeter
has body: I need to start JMeter-server on target host with some python script. Jmeter has temporary directory like /tmp/jmeter-3sc0ppq5/. Inside the script, I have some BeanShell which is creating a file and it`s needed to have appeared in his own base directory in bin/ directory: File file = new File('errors' + File.separator + fileName); file.getParentFile().mkdirs(); But finally, it`s appearing (as well as JMeter-server.log file in /root/) My python script is (simplified): stdin, stdout, stderr = ssh.exec_command('cd /tmp/jmeter-3sc0ppq5/bin/') run_jmeter_server_cmd = 'nohup java -jar "/tmp/jmeter-3sc0ppq5/bin/ApacheJMeter.jar" -Duser.dir=/tmp/jmeter-3sc0ppq5/bin/ApacheJMeter.jar -Dserver_port=11111 -s -j jmeter-server.log &gt; /dev/null 2&gt;&amp;1' command = 'echo $$; exec ' + run_jmeter_server_cmd stdin, stdout, stderr = ssh.exec_command(command) pid = int(stdout.readline()) As you see even tried to send user.dir directory explicitly. jmeter-server.log is appearing in /root/ but it says that this jmeter process takes all configs from correct directory: 2017-12-20 09:26:49,551 INFO o.a.j.u.JMeterUtils: Setting Locale to en_DK 2017-12-20 09:26:49,566 INFO o.a.j.JMeter: Loading user properties from: /tmp/jmeter-3sc0ppq5/bin/user.properties 2017-12-20 09:26:49,567 INFO o.a.j.JMeter: Loading system properties from: /tmp/jmeter-3sc0ppq5/bin/system.properties 2017-12-20 09:26:49,567 INFO o.a.j.JMeter: Setting System property: java.rmi.server.hostname=loadtest08-qa 2017-12-20 09:26:49,567 INFO o.a.j.JMeter: Setting System property: user.dir=/tmp/jmeter-3sc0ppq5/bin/ 2017-12-20 09:26:49,567 INFO o.a.j.JMeter: Setting System property: server_port=10001 .............. 2017-12-20 09:26:49,580 INFO o.a.j.JMeter: JMeterHome=/tmp/jmeter-3sc0ppq5 2017-12-20 09:26:49,580 INFO o.a.j.JMeter: user.dir =/tmp/jmeter-3sc0ppq5/bin/ 2017-12-20 09:26:49,580 INFO o.a.j.JMeter: PWD =/tmp/jmeter-3sc0ppq5/bin But all files created by script are going to /root/ directory as well as mentioned jmeter-…
type: Question
has answer: http://stackoverflow.com/a/47903628
has comment: http://stackoverflow.com/comment/82773087
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/82773712
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47903706
has title: Starting Jmeter server with python script, base directory
tagged with: python

http://stackoverflow.com/comment/82899507
type: Comment
has text: This is *quasi* composition, not inheritance and it *breaks* methods A called upon B which exect `x` and `y` properties. It would be less confusing (ie. full composition) if class B *did not* extend A, especially since the initializer for A is never called.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47963762

http://stackoverflow.com/comment/83055681
type: AnswerComment
has text: My point was exactly to use the dataframe :) As I said, you can do what you want directly, but your question sounded like a typical [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). If you edit your question and explain _why_ you really need to do this, I can show you how.
type: Comment
comment on: http://stackoverflow.com/a/48028250
score: 0

http://stackoverflow.com/a/47963904
has comment: http://stackoverflow.com/comment/82898433
has body: The OP tries to create a table of dummy variables with a set of data points. For each data point, it contains 5 attributes. There are in total N unique attributes. We will use a simplied dataset to demonstrate how to do it: 5 unique attributes 3 data entries each data entry contains 3 attributes. x = pd.DataFrame([['a', 'b', 'c'], ['b', 'd', 'e'], ['e', 'b', 'a']]) fullmatrix = pd.DataFrame([[0 for _ in range(5)] for _ in range(3)], columns=['a','b','c','d','e']) """ fullmatrix: a b c d e 0 0 0 0 0 0 1 0 0 0 0 0 2 0 0 0 0 0 """ # each row in x_temp is a string of attributed delimited by "," x_row_joined = pd.Series((",".join(row[1]) for row in x.iterrows())) fullmatrix = x_row_joined.str.get_dummies(sep=',') The method is inspired by offbyone's answer It uses pandas.Series.str.get_dummies. We first joins each row of x with a specified delimiter. Then make use of the Series.str.get_dummies method. The method takes a delimiter that we just use to join attributes and will generate the dummy-varaible table for you. (Caution: don't pick sep that exists in x.)
downvote count: 0
has comment: http://stackoverflow.com/comment/82898363
type: Answer
answers question: http://stackoverflow.com/q/47962856
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/82901292
has comment: http://stackoverflow.com/comment/82898750

http://stackoverflow.com/comment/82989539
type: AnswerComment
comment on: http://stackoverflow.com/a/47991286
score: 0
type: Comment
has text: since I look for any similar words, I want the output to display how many times repetitions(of any words) ocurred within the text file.

http://stackoverflow.com/q/47934473
has comment: http://stackoverflow.com/comment/82900011
tagged with: arrays
accepted answer: http://stackoverflow.com/a/47935053
answer count: 2
type: AnsweredQuestion
score: 3
downvote count: 0
possible better answer: http://stackoverflow.com/a/47935202
has answer: http://stackoverflow.com/a/47935202
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/47935053
has comment: http://stackoverflow.com/comment/82839482
upvote count: 3
has title: Put numpy arrays split with np.split() back together
has body: I have split a numpy array like so: x = np.random.randn(10,3) x_split = np.split(x,5) which splits x equally into five numpy arrays each with shape (2,3) and puts them in a list. What is the best way to combine a subset of these back together (e.g. x_split[:k] and x_split[k+1:]) so that the resulting shape is similar to the original x i.e. (something,3)? I found that for k > 0 this is possible with you do: np.vstack((np.vstack(x_split[:k]),np.vstack(x_split[k+1:]))) but this does not work when k = 0 as x_split[:0] = [] so there must be a better and cleaner way. The error message I get when k = 0 is: ValueError: need at least one array to concatenate
has comment: http://stackoverflow.com/comment/82838713
tagged with: numpy

http://stackoverflow.com/comment/82767892
type: AnswerComment
has text: Thanks a lot for the response , I get below error when I run the same. attached the traceback. could you please advise.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47894701

http://stackoverflow.com/q/47926650
tagged with: recursion
has comment: http://stackoverflow.com/comment/82821842
tagged with: fibonacci
has comment: http://stackoverflow.com/comment/82821313
tagged with: http://stackoverflow.com/tag/c
type: Question
has title: What is the difference in assignment between C and Python?
tagged with: variables
has body: A = 0 B = 1 A, B = B, A + B running 5 times: the values of B in Python will be 1, 1, 2, 3, 5. the values of B in C will be 1, 1, 1, 1, 1. Would anyone explain this to me? #include &lt;stdio.h&gt; #define TRUE (1 == 1); #define FALSE (1 == 0); int fibonacci(int sequencia); int main() { fibonacci(5); return FALSE; } int fibonacci(int sequencia) { static int antigo = 0; static int novo = 1; static int copia = 0; if (sequencia == 0) { return TRUE; } else { printf("%i\n", novo); } antigo, novo = novo, antigo + novo; fibonacci(sequencia - 1); } antigo = 0 novo = 1 def fibonacci(sequencia): global antigo, novo if sequencia != 0: print novo else: return True antigo, novo = novo, antigo + novo fibonacci(sequencia - 1) if __name__ == "__main__": fibonacci(5)
has comment: http://stackoverflow.com/comment/82829240
has comment: http://stackoverflow.com/comment/82828952
tagged with: python
has comment: http://stackoverflow.com/comment/82821232
linked to: http://stackoverflow.com/q/275128
answer count: 0
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82821129
has comment: http://stackoverflow.com/comment/82821186
has comment: http://stackoverflow.com/comment/82959167
duplicate of: http://stackoverflow.com/q/275128

http://stackoverflow.com/comment/82878787
comment on: http://stackoverflow.com/a/47945948
has text: @tjalling. Garbage colection is exactly the same for lambdas. The difference is entirely due the the closure, and *any* function can form one of those. It's the closure that keeps the extra references, not the function. There is no closure in the example given in your comment.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47979647
possible better answer: http://stackoverflow.com/a/47980139
has title: Pass date range in URL in Django Rest
has answer: http://stackoverflow.com/a/47980139
upvote count: 1
tagged with: django
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47980259
score: 1
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/47980176
has body: I have a JSON structure like, [ { "date": "2017-12-17 06:26:53", "name": "ab", }, { "date": "2017-12-20 03:26:53", "name": "ab" }, { "date": "2017-12-18 04:26:53", "name": "ab" }, { "date": "2017-12-19 05:26:53", "name": "ab" } ] I am using Django Rest Framework. Whenever, I do a GET request to, localhost/namelist/{{name}}/ is returns the JSON where "name": "ab" . Now, I want to return JSON based on date range. I will pass the start date and end date in the url and it should return the value within that specific date range, time should be ignored. Also, we have to consider months also, not only dates. Here, in this example, month is same but in real scenario months might be different. Like, localhost/namelist/{{name}}/{{start_date}}/{{end_date}}/ If the URL is , localhost/namelist/abcd/2017-12-17/2017-12-19/ then it should return, [ { "date": "2017-12-17 06:26:53", "name": "ab", }, { "date": "2017-12-18 04:26:53", "name": "ab" }, { "date": "2017-12-19 05:26:53", "name": "ab" } ] views.py :- def get_queryset(self): param = self.kwargs.get('pk') param2 = self.kwargs.get('ak') return namelist.objects.filter(name=param, date = param2) urls.py :- urlpatterns = { url('^namelist/(?P&lt;pk&gt;[\w\-]+)/(?P&lt;ak&gt;[\w\-]+)/$', ListViewParam.as_view()), } I can pass the date in the URL, but what the recommended way to pass the date range ?
type: Question
accepted answer: http://stackoverflow.com/a/47980259
downvote count: 0
favorite count: 0
tagged with: python-3.x
answer count: 3
tagged with: python

http://stackoverflow.com/comment/82828344
comment on: http://stackoverflow.com/a/47929689
has text: Btw: `map(list.append, data, new_entries)`.
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/comment/82720608
has text: @DickThompson ran it what kind of error code you received ?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47877085
type: Comment

http://stackoverflow.com/a/47885939
downvote count: 1
has comment: http://stackoverflow.com/comment/82738040
accepted answer of: http://stackoverflow.com/q/47885848
has comment: http://stackoverflow.com/comment/82737471
has comment: http://stackoverflow.com/comment/82738208
has body: You should perform the condition only over the first column: x_displayed = xy_dat[((xy_dat[:,0] &gt; min) & (xy_dat[:,0] &lt; max))] What we do here is constructing a view where we only take into account the first column with xy_dat[:,0]. By now checking if this 1d is between bounds, we construct a 1D boolean array of the rows we should retain, and now we make a selection of these rows by using it as item in the xy_dat[..] parameter.
type: AcceptedAnswer
upvote count: 16
answers question: http://stackoverflow.com/q/47885848
has comment: http://stackoverflow.com/comment/82737727
score: 15
has comment: http://stackoverflow.com/comment/82737441
type: Answer

http://stackoverflow.com/comment/82771828
type: Comment
has text: @Divakar juanpa.arrivillaga it is a ragged.
type: QuestionComment
comment on: http://stackoverflow.com/q/47902323
score: 0

http://stackoverflow.com/comment/82992249
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48011743
has text: `[x.strip("""()"'""") for x in line.split(', u')]` but I don't know what to do with `L` if it's a problem
score: 0

http://stackoverflow.com/comment/82801610
type: Comment
comment on: http://stackoverflow.com/a/47914998
type: AnswerComment
score: 2
has text: You can remove `-ab 160k` as it won't do anything for wav output.

http://stackoverflow.com/comment/82965751
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47998286
has text: Yeah I'm trying that now but I'm getting a failed to decode json object. I imagine it's because I'm using Flask-RestPlus.. I'm not sure what could be going on tho, because the API endpoint works fine when sending raw json. But this form is not.
score: 0

http://stackoverflow.com/a/47862108
answers question: http://stackoverflow.com/q/47861837
has body: Sorting is a solution, but for long lists it might be more expensive than needed as it is not linear. Python is far from the most elegant language for FP, but you could use reduce to find your largest elements in one pass. def add_largest_to_pair(pair, num): # This function takes a pair and a number and returns a pair made of the two largest of those three if pair[1] &gt; num &gt;= pair[0]: return (num, pair[1]) elif num &gt;= pair[1]: return (pair[1], num) else: return pair def top_two(l): return reduce( add_largest_to_pair, l, (float('-inf'), float('-inf')) ) This will return you a tuple of the two largest values, with pair[0] being the second largest and pair[1] being the largest. Just be aware that this assumes your list has at least length two. Note: You will have to use functools.reduce if you are using Python3.
type: Answer
score: 0

http://stackoverflow.com/a/47874334
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/82717096
type: Answer
has comment: http://stackoverflow.com/comment/82717155
accepted answer of: http://stackoverflow.com/q/47871639
score: 2
has body: You're referring to the Perl's flip-flop operator (..). Basically, it sets a boolean flag to true when it encounters the first condition, and back to false after it encounters the second (start and end lines inclusive). Looking at it that way, it's fairly simple to implement. import re flip = False; for line in open(filename): if not flip and re.match('start-text',line): flip = True if flip: print(line) if re.match('end-text',line): flip = False
answers question: http://stackoverflow.com/q/47871639
has comment: http://stackoverflow.com/comment/82715929
upvote count: 3

http://stackoverflow.com/comment/82701170
score: 0
comment on: http://stackoverflow.com/a/47868033
type: Comment
type: AnswerComment
has text: this is dynamic dude. it will clip text from this type of string

http://stackoverflow.com/comment/82722831
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/47878060
has text: You seem to be trying to edit your question to be more on-topic, but what you're turning it into is easily answerable by ctrl-F-ing for `enum` in the [`re` docs](https://docs.python.org/3/library/re.html#module-contents). It's trying to import `enum.IntFlag` because it needs to use `enum.IntFlag`. That's usually why code imports things.

http://stackoverflow.com/q/47998318
has title: python - Converting a VPython program into an exe
upvote count: 2
tagged with: pyinstaller
tagged with: macos
tagged with: exe
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
has body: I am currently making a physics simulation using VPython, and want to turn it into an exe file, using pyinstaller, so that it can run on a Mac laptop. Essentially, I have two questions - one short and one long. Short question: will the exe file I create using pyinstaller run on a Mac laptop if I created it using windows? Long question: I converted my program into an exe, but it doesn't work. Here is a screen shot of the error: Pyinstaller error Good news: I think I have found a solution to my problem from another question on stackoverflow, but I am a newbie and can't comprehend a single word of the answer. And, the answer uses anaconda, but I am using pycharm... in other words I am completely lost. Link to answer: how to make vpython .exe using pyinstaller
type: Question
answer count: 2
tagged with: vpython
has answer: http://stackoverflow.com/a/76442269
linked to: http://stackoverflow.com/q/39818847
downvote count: 0
has answer: http://stackoverflow.com/a/47998374

http://stackoverflow.com/comment/82977431
has text: it all depends what intent is being revoked by the input. check your logs for details, that might help.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48004640

http://stackoverflow.com/a/47893850
upvote count: 2
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/47893774
has comment: http://stackoverflow.com/comment/82754671
has comment: http://stackoverflow.com/comment/82754698
has comment: http://stackoverflow.com/comment/82754518
type: AcceptedAnswer
has body: I would create a function that iterates through the list: d = {} d['A'] = {} d['A']['B'] = {} d['A']['B']['C'] = 'value' lst = ['A', 'B', 'C'] def get_value(d, lst): for elem in lst: d = d[elem] return d print get_value(d, lst) # outputs 'value'
downvote count: 0
has comment: http://stackoverflow.com/comment/82754434
answers question: http://stackoverflow.com/q/47893774

http://stackoverflow.com/q/47969493
has body: i write a bubble sort, but it does not work. Wish somebody can make a correction. def BubbleSort(tensor): def outer_loop(i, t): cond = lambda j, _: j &gt; i loop = tf.while_loop(cond, inner_loop, loop_vars=[j, t]) print('outer_loop', i+1, length-1) return i+1, loop[1] def inner_loop(j, t): body = tf.cond(tf.greater(t[j-1], t[j]), lambda: tf.scatter_update(t, [j-1, j], [t[j], t[j-1]]), lambda: t) print('inner_loop', i, j-1) return j-1, body length = tensor.get_shape()[-1].value i = 0 j = length-1 cond = lambda i, _: i &lt; length - 1 graph = tf.while_loop(cond, outer_loop, loop_vars=[i, tensor]) return graph
downvote count: 1
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/82908985
answer count: 1
has answer: http://stackoverflow.com/a/59559649
has comment: http://stackoverflow.com/comment/82909883
favorite count: 0
has title: Can tensorflow make a sort, such as bubble sort or even general sort?
type: UnansweredQuestion
tagged with: python
upvote count: 2
score: 1

http://stackoverflow.com/q/47891783
has comment: http://stackoverflow.com/comment/91770046
has answer: http://stackoverflow.com/a/52444225
score: 0
answer count: 1
has title: Python 3.6.1 OpenOPC install
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82751249
type: UnansweredQuestion
tagged with: python
tagged with: opc
has body: Pardon me for my ignorance but I can't seem to get OpenOPC installed with Python 2.7 or 3.6.1. I found the github code but it does not appear to include an installer. So I attempted to install the version for 2.7 from here. I can make the OpenOPC server talk using the instructions but after copying all the files from the python 3 project into my python directory I can import OpenOPC but when I try opc = OpenOPC.client() I get a fault. C:\&gt;python Python 3.6.1 |Anaconda 4.4.0 (64-bit)| (default, May 11 2017, 13:25:24) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import OpenOPC &gt;&gt;&gt; opc = OpenOPC.client() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: module 'OpenOPC' has no attribute 'client' &gt;&gt;&gt;
type: Question
has comment: http://stackoverflow.com/comment/82750618
tagged with: open-opc
has comment: http://stackoverflow.com/comment/82752305

http://stackoverflow.com/comment/82911811
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47970964
has text: No, you should probably edit it. But the question is almost accurate, it provides details for identifying a list of problems leading to the behavior. Second thing you could do (now that you know the problem) is searching for similar questions (as there should be many of them) and mark it as a duplicate. Or you could answer your own question.
score: 1

http://stackoverflow.com/comment/82711039
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47871103
type: Comment
has text: '0.18.1' is the version I ma using

http://stackoverflow.com/a/50583153
answers question: http://stackoverflow.com/q/48012582
downvote count: 0
upvote count: 84
score: 84
has comment: http://stackoverflow.com/comment/110717678
has comment: http://stackoverflow.com/comment/115478395
type: Answer
has body: What worked for me was running : sudo apt-get install libopenjp2-7 Good Luck!
has comment: http://stackoverflow.com/comment/115478570

http://stackoverflow.com/q/47963083
tagged with: anaconda
has answer: http://stackoverflow.com/a/49322558
has answer: http://stackoverflow.com/a/50020866
has body: Solving environment: failed UnsatisfiableError: The following specifications were found to be in conflict: - wordcloud - xlsxwriter Use "conda info " to see the dependencies for each package . Initially i get conflict with python 3.4 and python 3.6 so update python to 3.6 but still getting above erroe. Pls help
tagged with: data-science
score: 0
has comment: http://stackoverflow.com/comment/82897062
tagged with: pandas
has title: Can't install wordcloud in anaconda
tagged with: python
answer count: 4
tagged with: installation
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49322659
type: Question
has answer: http://stackoverflow.com/a/62610485

http://stackoverflow.com/a/48010376
has body: In my experience, I found it better to use regex after you process the string as much as possible; regex on an arbitrary string will only cause headaches. In your case, try splitting on ':' (or even workorders:) and getting the stuff after to get only the counts of statuses. After that, it's easy to get the counts for each status. s = " 3434 garbage workorders: 138 waiting, 2 running, 3 failed, 134 completed" statuses = s.split(':') #['3434 garbage workorders', ' 138 waiting, 2 running, 3 failed, 134 completed'] statusesStr = ''.join(statuses[1]) # ' 138 waiting, 2 running, 3 failed, 134 completed' statusRe = re.compile("(\d+)\s*(\w+)") statusRe.findall(statusesStr) #[('138', 'waiting'), ('2', 'running'), ('3', 'failed'), ('134', 'completed')] Edit: changed expression to meet desired outcome and more robust
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/82990464
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/82990000
answers question: http://stackoverflow.com/q/48010179

http://stackoverflow.com/q/47897562
type: Question
tagged with: visual-studio-code
score: 0
has comment: http://stackoverflow.com/comment/82762083
answer count: 1
tagged with: shared-libraries
has answer: http://stackoverflow.com/a/48069810
has comment: http://stackoverflow.com/comment/82788706
has title: Drill to C source code definition when in a Python file (VSCode)
has body: I want to navigate to the definition of modules implemented in C from my Python file. VSCode can drill to the definitions of my python objects. Some are found automatically, while others, I need to point to. To add additional locations I add the following to my user VSCode settings: "python.autoComplete.extraPaths": [ "C:/Users/me/Desktop/external_python" ], This works fine and I can right click on objects and 'Go To Definition'. I want to drill even further; into the C implementation. Now, python modules implemented in C are compiled. However, I have access to the *.h and *.c files which generated the shared objects. So, theoretically, I could jump from my python files into .h/.c files of C from within VSCode Is it possible to navigate from a python file into the source code of a compiled module?
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/82895316
comment on: http://stackoverflow.com/a/47961760
type: AnswerComment
score: 0
has text: Ok. I'll try to find out :)
type: Comment

http://stackoverflow.com/comment/82800325
has text: Thank your for the insight. I think I understand the name assignment issue, and with that in mind, I've updated my example to be more reflective of the issue I'm having. Please take a look if you can. Since I'm using *+=* and */=*, shouldn't the underlying value get updated?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47915720

http://stackoverflow.com/comment/82813737
score: 0
type: Comment
type: QuestionComment
has text: Point taken on the # of questions. I had in fact found the AutoMinorLocator, but had placed it before the cb.ax.minorticks_on() line in my code. It seems that the minorticks_on() function resets the number of ticks to auto. Getting rid of that line & using AutoMinorLocator only works. Thanks for steering me back on the right path.
comment on: http://stackoverflow.com/q/47906119

http://stackoverflow.com/comment/82906175
score: 0
comment on: http://stackoverflow.com/q/47968210
type: QuestionComment
has text: Thanks! range(int(current_ins[1])) works perfectly!
type: Comment

http://stackoverflow.com/q/47955289
tagged with: adc
has body: I need to sample analog signal (50-60Hz) through AIN0 on Beaglebone Black. What I need is a sample size of 10,000 at 1 millisecond sampling rate (should run for 10 secs). The python example I found in for beaglebone_pru_adc library is as below - import beaglebone_pru_adc as adc import time numsamples = 10000 # how many samples to capture capture = adc.Capture() capture.oscilloscope_init(adc.OFF_VALUES, numsamples) # captures AIN0 - the first elt in AIN array capture.cap_delay = 200000 # I don't understand how to write this part to achieve desired sampling rate capture.start() for _ in range(10): if capture.oscilloscope_is_complete(): break print '.' time.sleep(0.1) capture.stop() capture.wait() print 'Saving oscilloscope values to "data.csv"' with open('data.csv', 'w') as f: for x in capture.oscilloscope_data(numsamples): f.write(str(x) + '\n') print 'done' capture.close() I think I am wrong somewhere as I don't expect the acquisition to finish before 10 secs. Any help regarding how to achieve specific sample size at specific sample rate for BB ADC would be great help.
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has title: Analog Sampling using LIBPRU over beaglebone
tagged with: python
tagged with: beagleboneblack
answer count: 0
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/q/47991528
tagged with: jinja2
accepted answer: http://stackoverflow.com/a/48019914
type: Question
answer count: 1
has title: Jinja2 passing value inside value
tagged with: templates
has answer: http://stackoverflow.com/a/48019914
has comment: http://stackoverflow.com/comment/82977563
tagged with: python
has body: I am trying to pass a dynamic value to my dictionary in my jinja template which in turn is a value. Code is as below: "wan_link_info": [ {% for i in range(3) %} { "dummy": "{{ xyz_Links.abc_{{ i }}.abc_link_type }}", } {% endfor %} ] Here the dummy will have value like xyz_Links.abc_0.abc_link_type, xyz_Links.abc_1.abc_link_type, etc. These text will return a value. Example say: {{xyz_Links.abc_0.abc_link_type}} = "Stackoverflow" {{xyz_Links.abc_1.abc_link_type}} = "Facebook" When I run the above code I get this error: **"jinja2.exceptions.TemplateSyntaxError: expected token 'end of print statement', got '{'"**
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/47999315
answers question: http://stackoverflow.com/q/47994575
type: Answer
has body: Shouldn't you do an equivalent of sys.path.append("/path/to/mypkg") in pytest? Hint: define PYTHONPATH! cd /path/to/mypkg PYTHONPATH=/path/to/mypkg python py -m pytest
score: 0

http://stackoverflow.com/q/47954324
answer count: 2
linked to: http://stackoverflow.com/q/39841023
has answer: http://stackoverflow.com/a/47956368
downvote count: 0
has comment: http://stackoverflow.com/comment/82878071
has comment: http://stackoverflow.com/comment/82878654
favorite count: 0
tagged with: sql-server
has body: Having the following code, how can I output the values from the external python script into a sql table that I can query after. EXECUTE sp_execute_external_script @language = N'Python', @script = N' import pandas as pd import numpy as np rd = np.random.randn(100) df = pd.DataFrame(rd).describe() print(df)' Thanks in advance.
tagged with: pandas
tagged with: sql
tagged with: python
upvote count: 6
has title: How to output values from sp_execute_external_script into table
type: UnansweredQuestion
score: 6
has answer: http://stackoverflow.com/a/56387582
type: Question

http://stackoverflow.com/comment/82900704
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47964719
score: 0
has text: create minimal working example so everyone could run it and test solutions. And you could add url to page.

http://stackoverflow.com/comment/82748192
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47890540
type: Comment
has text: So, you're saying I need to modify the Input_Series to reflect your example? Given, that: `X = tf.placeholder(dtype=tf.float32, shape=[None, n_steps, n_inputs]) X_seqs = tf.unstack(tf.transpose(X, perm=[1, 0, 2]))` is basically the input series is it not? And the following line is basically my cell declaration? `output_seqs, states = tf.nn.static_rnn(basic_cell, X_seqs, dtype=tf.float32)`

http://stackoverflow.com/comment/82951225
score: 1
comment on: http://stackoverflow.com/q/47986224
type: Comment
type: QuestionComment
has text: Please search the web before asking questions , this question has about 80k views and so it can be easily reached!

http://stackoverflow.com/q/47950107
has comment: http://stackoverflow.com/comment/82870039
has comment: http://stackoverflow.com/comment/82870001
has title: Issue with Django Template for loop
has comment: http://stackoverflow.com/comment/82869879
has comment: http://stackoverflow.com/comment/82869903
has answer: http://stackoverflow.com/a/47950273
has comment: http://stackoverflow.com/comment/82870041
score: 0
has comment: http://stackoverflow.com/comment/82870084
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/82869998
answer count: 1
tagged with: templates
accepted answer: http://stackoverflow.com/a/47950273
tagged with: django
tagged with: python
type: AnsweredQuestion
has body: so I did some searches but couldn't find the answer to my particular issue... What is happening is that: I have a model named section which have section_title field. This field can have spaces, for example: "First Section". When I pass this to Django, I am removing the space in Python with replace(), and created a filter on Django which also removes the space like so: @register.filter(name='replace_char') def replace_char(value, arg): return value.replace(arg, '') Then on my template: {% for subsection in section.section_title|replace_char:" " %} The issue is that subsection is being shown as each character from section_title, instead of the list that section_title references. Here is the dictionary being passed to the template: {'sections': [&lt; Section: First Section>, &lt; Section: Second Section>], 'FirstSection': [&lt; Subsection: Subsection 1>, &lt; Subsection: Subsection 2>], 'SecondSection': [&lt; Subsection: Bla1>], 'teste': ['1', '2', '3']} If I hardcode: {% for subsection in FirstSection %} It works... Any ideas? Thanks! OBS: I removed the spaces because I thought they were causing the issue, but apparently not. It wasnt working with the spaces as well... Full template code: {% for section in sections %} &lt;div class="sectionHeader"&gt; {{ section.section_title }} &lt;/div&gt; &lt;div class="forumSection"&gt; {% for subsection in section.section_title|replace_char:" " %} &lt;div&gt; {{ subsection }} &lt;/div&gt; {% endfor %} &lt;/div&gt; {% endfor %} Models: class Section(models.Model): def __str__(self): return self.section_title section_title = models.CharField(primary_key = True, unique = True, max_length = 50) class Subsection(models.Model): def __str__(self): return self.subsection_title subsection_title = models.CharField(max_length = 50) subsection_section = models.ForeignKey( 'Section', on_delete = models.CASCADE, )
type: Question

http://stackoverflow.com/comment/82761202
comment on: http://stackoverflow.com/q/47897163
score: 0
type: QuestionComment
has text: How does it not work? What do you input, what do you see, and what do you expect? It looks as if it should work from a visual inspection, so please explain further. BTW, the brackets around `if (expression):` are not necessary, and `while control:` is more idiomatic.
type: Comment

http://stackoverflow.com/q/47893756
type: Question
has title: Python KIVY: recursive DropDown
score: 0
has body: I would like to create a DropDown that contains 3 other DropDowns that contains 3 buttons each. I would like the first DropDown to open three more DropDowns, when we click on one of them, three buttons appear, and in any case when a button appears, which is below down without display bug. When you click on a dropdown for se second time, it hides its children widgets. I'm using this way to create a dropdown: .py: from kivy.app import App from kivy.uix.dropdown import DropDown from kivy.uix.screenmanager import ScreenManager, Screen from kivy.lang import Builder from kivy.properties import StringProperty class MyScreenManager(ScreenManager): button_text = StringProperty('Show possibilities') def __init__(self, **kwargs): super(MyScreenManager, self).__init__(**kwargs) self.dropdown = CustomDropDown(self) def open_drop_down(self, widget): self.dropdown.open(widget) class MyScreen(Screen): def __init__(self, **kwargs): super(MyScreen, self).__init__(**kwargs) class CustomDropDown(DropDown): def __init__(self, screen_manager, **kwargs): super(CustomDropDown, self).__init__(**kwargs) self.sm = screen_manager def on_select(self, data): self.sm.button_text = data Builder.load_file("debug.kv") class MyAppli(App): def build(self): return MyScreenManager() if __name__ == '__main__': MyAppli().run() .kv: &lt;MyScreenManager&gt;: MyScreen: AnchorLayout: anchor_x: 'center' anchor_y: 'top' Button: text: root.button_text size:(200,50) size_hint:(None,None) on_release: root.open_drop_down(self) &lt;CustomDropDown&gt;: Button: text:"Item 1" size:(200,50) size_hint:(None,None) on_release: root.select("ONE") Button: text:"Item 2" size:(200,50) size_hint:(None,None) on_release: root.select(self.text) Button: text:"Item 3" size:(200,50) size_hint:(None,None) on_release: root.select("THREE")
answer count: 1
tagged with: dropdown
has answer: http://stackoverflow.com/a/47934388
type: UnansweredQuestion
tagged with: python
tagged with: kivy

http://stackoverflow.com/comment/82870324
score: 1
comment on: http://stackoverflow.com/q/47950320
type: Comment
type: QuestionComment
has text: and `/input` is *really* working?

http://stackoverflow.com/a/47966778
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47959798
answers question: http://stackoverflow.com/q/47959798
upvote count: 2
has body: Try this and let me know the result: a = list() for x in relation_list: if x.attrib1 not in [z.attrib1 for z in a]: a.append(x)
has comment: http://stackoverflow.com/comment/82903196
type: AcceptedAnswer
type: Answer
score: 2

http://stackoverflow.com/comment/83231417
type: QuestionComment
comment on: http://stackoverflow.com/q/47963425
has text: Active position toggles from 0 to 1 when signal toggles to 1. It remains 1 until one of the 3 exit conditions are met.
score: 0
type: Comment

http://stackoverflow.com/q/47857799
possible better answer: http://stackoverflow.com/a/47858373
has title: Python: ax.text not displaying in saved PDF
answer count: 2
favorite count: 0
score: 6
tagged with: python
has answer: http://stackoverflow.com/a/47858373
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47859277
downvote count: 0
tagged with: matplotlib
has body: I am creating a figure with some text (example here: a sin curve with some text on the side) in an ipython notebook. The plot and text show up inline in my notebook, but when I save the figure I only see the plot and not the text. I've reproduced the problem with this example code: import numpy as np import matplotlib.pyplot as plt fig,ax = plt.subplots(1) x = np.linspace(0, 2*np.pi, 100) y = np.sin(x) ax.plot(x, y) ax.text(8,0.9,'Some Text Here',multialignment='left', linespacing=2.) plt.savefig('sin.pdf') How can I see the text in the saved pdf?
type: Question
has answer: http://stackoverflow.com/a/47859277
has comment: http://stackoverflow.com/comment/82680075
upvote count: 6

locking
tags question: http://stackoverflow.com/q/47867835
type: Tag
tag name: locking

http://stackoverflow.com/comment/82914646
score: 0
has text: Could you show a screenshot from the output in your terminal? Also, maybe reduce the range to just `4` (instead of `44`) to show both executions next to another.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47972362

http://stackoverflow.com/a/47983143
type: AcceptedAnswer
has body: I think your problem is the NaN values in your first couple rows, that get multiplied through and result in adding NaN values. Try this: newcol = [] firstnonnan = True for index, row in df.iterrows(): if row['in_scenario_USA'].isnull(): newcol.append(row['USA_index_in']) elif firstnonnan = True: newcol.append(1) firstnonnan = False else: newcol.append(newcol[-1]*(1+row['in_scenario_USA'])) df['USA index_in'] = newcol Basically, you're going to iterate through the dataframe and build a list to overwrite your column with. If you have a NaN value, you're going to take the same value that's already in that column. The first time you see a non-NaN, you'll add a 1 to your list. After that, you'll use the last item in the list as your previous value.
accepted answer of: http://stackoverflow.com/q/47982908
type: Answer
answers question: http://stackoverflow.com/q/47982908
score: 2
downvote count: 0
upvote count: 2

http://stackoverflow.com/a/48315911
upvote count: 1
type: Answer
has body: So it was a very hacky thing to do, but it solves my purpose. I created a batch file with the run command and whenever I need to run the server, I just run it with the batch script. If I open the bat file from the command prompt or if I double click on it, I can just press ctrl+c to close it. That saved me a lot of time and I don't even need the break key.
accepted answer of: http://stackoverflow.com/q/47903196
answers question: http://stackoverflow.com/q/47903196
downvote count: 0
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/47871352
tagged with: python
has title: Pandas Dataframe to Json
downvote count: 0
score: 1
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
has body: I've this line of code made with pandas: sqltable2 = sqltable.groupby(['Grupo_Resolutor', 'Sub_Estado']).size() with this output Grupo_Resolutor Sub_Estado ANALISIS DE CREDITO CANCELADO 2 MAL ESCALADO 22 NO PROCEDE 1120 NO PROCEDE RECONEXION 41 SOLUCIONADO 4446 SOLUCIONADO POR MASIVO 11898 COBRANZAS MAL ESCALADO 2 NO PROCEDE 203 NO PROCEDE COBRO 39 NO PROCEDE POR MI PUNTO 21758 NO PROCEDE RECONEXION 32 SOLUCIONADO 533 SOLUCIONADO POR MIPUNTO 11966 And i wish to parse that groupby object to json but when i do: (i need it with records because its for amcharts) sqltable2.to_json(orient = 'records') i have this output: [2,22,1120,41,4446,11898,2,203,39,21758,32,533,11966] desire output: [ { "Grupo Resolutor": "Analisis de Credito", "CANCELADO": 2, "MAL ESCALADO": 22, "NO PROCEDE": 1120, "NO PROCEDE RECONEXION": 2, "SOLUCIONADO": 22, "SOLUCIONADO POR MASIVO": 1120 }, { "Grupo Resolutor": "Cobranzas", "MAL ESCALADO": "2", "NO PROCEDE": 203, "NO PROCEDE COBRO": 39, "NO PROCEDE POR MI PUNTO": 21758, "NO PROCEDE RECONEXION": 32, "SOLUCIONADO": 533, "SOLUCIONADO POR MIPUNTO": 11966 } ] And so on with each 'Grupo_Resolutor' (there are more but i cant put too much code on the question) any ideas?
type: Question
tagged with: pandas
upvote count: 1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47871371
accepted answer: http://stackoverflow.com/a/47871371

http://stackoverflow.com/a/47872367
has comment: http://stackoverflow.com/comment/82710756
upvote count: 2
has comment: http://stackoverflow.com/comment/82710129
has body: You could try splitting your items on space using the split() function. From the doc: For example, ' 1 2 3 '.split() returns ['1', '2', '3']. def sum_of_squares(fname): infile = open(fname, 'r') sum2 = 0 for items in infile.readlines(): sum2 = sum(int(i)**2 for i in items.split()) print("The sum of the squares is:", sum2) infile.close()
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47872237
has comment: http://stackoverflow.com/comment/82710875
type: Answer

http://stackoverflow.com/q/47883188
tagged with: numpy
has answer: http://stackoverflow.com/a/47883292
has title: Read csv online with error Error tokenizing data
linked to: http://stackoverflow.com/q/32400867
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
tagged with: parsing
accepted answer: http://stackoverflow.com/a/47883292
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: AnsweredQuestion
score: 1
has body: The datafile in the format of .csv can successfully readed in the local computer. df = pd.read_csv("./data.csv") The file is upload here. However, I use two method with the uploading data in Dropbox or Github, the reading process all occured error as follows: df = pd.read_csv("https://www.dropbox.com/s/2ew62yi0v07tjub/data-1.csv?dl=0") error: pandas/parser.pyx in pandas.parser.TextReader.read (pandas/parser.c:10364)() pandas/parser.pyx in pandas.parser.TextReader._read_low_memory (pandas/parser.c:10640)() pandas/parser.pyx in pandas.parser.TextReader._read_rows (pandas/parser.c:11386)() pandas/parser.pyx in pandas.parser.TextReader._tokenize_rows (pandas/parser.c:11257)() pandas/parser.pyx in pandas.parser.raise_parser_error (pandas/parser.c:26979)() CParserError: Error tokenizing data. C error: Expected 1 fields in line 3, saw 2 df = pd.read_csv("https://github.com/envhyf/Notebook/blob/master/data-1.csv") CParserError: Error tokenizing data. C error: Expected 1 fields in line 116, saw 3 Thus, my question is why the csv file can be read in my own computer, but failed in the cloud? How to fix this problem. I have tried the answer of this question by adding error_bad_lines=False. But it didn't work for me.
upvote count: 1
linked to: http://stackoverflow.com/q/18039057
type: Question

http://stackoverflow.com/a/47940420
has body: Using file.read(size) will read size bytes from your file. Using file.readline() will read only a line from your file without loading the whole file. If you want to create only 1GB chunks then use the first one. If you want to create about 1GB sized .csv files then use the second one and count the size of the output file at each write.
downvote count: 1
score: -1
has comment: http://stackoverflow.com/comment/82850434
answers question: http://stackoverflow.com/q/47940238
upvote count: 0
has comment: http://stackoverflow.com/comment/82850264
type: Answer

http://stackoverflow.com/comment/82856868
has text: Also, I think the [..] is too much, the split already outputs a list.
score: 3
type: QuestionComment
comment on: http://stackoverflow.com/q/47943640
type: Comment

http://stackoverflow.com/comment/82892456
has text: Sci Prog thanks for the answer, that fixed it.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47961348

http://stackoverflow.com/comment/82855433
has text: @Askme I have modified the query for if the value of `phone` is blank (this is **not** the same as *`NULL`*; as you specified blank I have only catered for that. Should you require logic for *`NULL`* I suggest you add a `IS NOT NULL` and (probably) an `ISNULL` around the entire subquery ). No further logic changes in regards to ID 1 and 3, as I am yet to have a response on this. Thanks.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47940123

http://stackoverflow.com/comment/82863739
type: QuestionComment
has text: Try to provide [a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) for improving your question.
comment on: http://stackoverflow.com/q/47946838
score: 0
type: Comment

http://stackoverflow.com/comment/82924754
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47977953
score: 0
has text: Without the actual file input data, hard to say. Your file doesn't contain as much info as you expect it to contain.

http://stackoverflow.com/q/48007965
tagged with: django-rest-swagger
possible better answer: http://stackoverflow.com/a/54193364
tagged with: python
has answer: http://stackoverflow.com/a/54193364
downvote count: 0
has answer: http://stackoverflow.com/a/48247883
accepted answer: http://stackoverflow.com/a/48247883
tagged with: django
score: 14
type: AnsweredQuestion
tagged with: swagger
type: Question
answer count: 2
has body: I've created an AssetsFilter class: from django_filters import Filter from django_filters import rest_framework as filters from django_filters.fields import Lookup from .models import Assets class MyListFilter(Filter): def filter(self, qs, value): value_list = value.split(',') return super(ListFilter, self).filter(qs, Lookup(value_list, 'in')) class AssetsFilter(filters.FilterSet): name = filters.CharFilter(lookup_expr='icontains', help_text=u'Filter by name') criticality = MyListFilter(name='critical', help_text=u'Filter by_id') class Meta: model = Assets fields = ['name', 'criticality '] Now I'm using this filter in my Viewset as follows: from .serializers import AssetSerializers from .filters import AssetsFilter class AssetViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. """ queryset = Assets.objects.all() serializer_class = AssetSerializers filter_backends = (DjangoFilterBackend,) filter_class = AssetsFilter http_method_names = ['get', 'post', 'put', 'delete'] def list(self, request): """ Returns a list of Asset. """ return super(AssetViewSet, self).list(request) def create(self, request): """ Creates a new Asset.&lt;br&gt; """ return super(AssetViewSet, self).create(request) def destroy(self, request, pk=None): """ Deletes a Asset. """ return super(AssetViewSet, self).destroy(request, pk=pk) def retrieve(self, request, pk=None): """ Returns a Asset with id={id} """ return super(AssetViewSet, self).retrieve(request, pk=pk) def update(self, request, pk=None, *args, **kwargs): """ Updates an existing Asset.&lt;br&gt; """ return super(AssetViewSet, self).update(request, pk=pk, *args, **kwargs) When the swagger documentation is created, the filter fields appear in GET (list), GET (retrieve) as expected, but they also appear in the POST, PUT, PATCH and DELETE where they shouldn't be. How can I disable those parameters from appearing in the latest version of django-rest-swagger and DR…
has title: Django swagger- How to disable DjangoFilterBackend query filters from delete, put methods?
tagged with: django-rest-framework
favorite count: 0
upvote count: 14

http://stackoverflow.com/q/47983152
has answer: http://stackoverflow.com/a/47991350
has comment: http://stackoverflow.com/comment/82964564
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48013475
has comment: http://stackoverflow.com/comment/82963587
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82963907
tagged with: orm
upvote count: 1
has comment: http://stackoverflow.com/comment/82935344
has title: SQLAlchemy ORM: Sum of products
downvote count: 1
type: Question
has body: Let's say I have a ROOMS table with width and length columns, and a corresponding SQLAlchemy model. Is there a clean and efficient way to get a total area of all rooms, i.e. sum(length x width)? It's easy enough to do by looping at the client but it must surely be more efficient if it can be fetched by a query at the server. Edit: I thought I was being helpful by reducing the problem to a simple, clean example but I now realise I was just shooting myself in the foot because my difficulties evidently stem from a more fundamental lack of understanding of SQLAlchemy and working with ORMs. My model (flask-sqlalchemy) actually involves three related tables: holdings, commodities and prices. Commodities have many prices, and each holding is a quantity of a given commodity. I have it set up as follows: class Holding(db.Model): id = db.Column(db.Integer, primary_key=True) time = db.Column(db.TIMESTAMP, index=True) quantity = db.Column(db.DECIMAL(10,5)) commodity_id = db.Column(db.Integer, db.ForeignKey('commodity.id')) commodity = db.relationship('Commodity', back_populates='holdings') class Commodity(db.Model): id = db.Column(db.Integer, primary_key=True) symbol = db.Column(db.String(20)) name = db.Column(db.String(150)) holdings = db.relationship('Holding', back_populates='commodity', lazy='dynamic') prices = db.relationship('Price', back_populates='commodity', lazy='dynamic', order_by='Price.time.desc()') class Price(db.Model): id = db.Column(db.Integer, primary_key=True) time = db.Column(db.TIMESTAMP, index=True) amount = db.Column(db.DECIMAL(10,5), index=True) commodity_id = db.Column(db.Integer, db.ForeignKey('commodity.id')) commodity = db.relationship('Commodity', back_populates='prices') I want the sum of Holding.quantity * Holding.commodity.[most recent price]. Since Commodity.prices is in descending time order I can easily calculate the value in a Holding loop examining: h.commodity.prices.first().amount * h.quantity ... but I can't see how to get at the related …
accepted answer: http://stackoverflow.com/a/48013475
tagged with: sqlalchemy
tagged with: greatest-n-per-group
score: 0
possible better answer: http://stackoverflow.com/a/47991350
answer count: 2
has comment: http://stackoverflow.com/comment/82946156

http://stackoverflow.com/q/47932607
downvote count: 0
tagged with: macos
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: py2app
answer count: 0
tagged with: installation
linked to: http://stackoverflow.com/q/15796454
score: 1
has title: Building python-based Mac app with py2app, creating an installer, generates failing installer
has body: This is similar to py2app with native python 2.6, but is different enough that it's still a puzzle. Environment: Mac OS 10.8 &amp; 10.11, Python 2.7.6, py2app 0.14 I create a Mac application bundle from python, using py2app, on Mac OS 10.8. This seems to work fine. I then build an installer package using pkgbuild and productbuild. That appears to build with no errors, until I try to use the installer to install the package. I'm running the installer on MacOS 10.11 (it will also have to run on MacOS 10.8-10.13). The installation fails, with the following in the install.log: Dec 21 15:14:46 Erics-10-11-Mac-VM shove[30757]: [src=nonrestricted] /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/pyconfig.h: unable to remove flag 0x80000 (error 1) Dec 21 15:14:46 Erics-10-11-Mac-VM shove[30757]: [source=file] failed _RelinkFile(/var/folders/zz/zyxvpxvq6csfxvn_n0000000000000/C/PKInstallSandboxManager/3BE46873-2E16-4787-81A4-335FB1DCB67B.activeSandbox/Root/Applications/MyApp.app/Contents/Resources/include/python2.7/pyconfig.h, /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/pyconfig.h): Operation not permitted Dec 21 15:14:46 Erics-10-11-Mac-VM shove[30757]: srcPath = /var/folders/zz/zyxvpxvq6csfxvn_n0000000000000/C/PKInstallSandboxManager/3BE46873-2E16-4787-81A4-335FB1DCB67B.activeSandbox/Root/Applications/MyApp.app/Contents/Resources/include/python2.7/pyconfig.h NSFileOwnerAccountID=0 NSFileHFSTypeCode=0 NSFileSystemFileNumber=1025119 NSFileExtensionHidden=0 NSFileSystemNumber=16777219 NSFileSize=36515 NSFileGroupOwnerAccountID=0 NSFileOwnerAccountName=root NSFileCreationDate=2017-12-21 20:12:33 +0000 NSFilePosixPermissions=420 NSFileHFSCreatorCode=0 NSFileType=NSFileTypeRegular NSFileGroupOwnerAccountName=wheel NSFileReferenceCount=1 NSFileModificationDate=2017-12-21 20:12:33 +0000 The issue seems to be that the installer wants to copy (or do something with) Contents/Resources/include/pyconfig.h into /System/Library/Fram…
type: Question

http://stackoverflow.com/comment/82935608
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47983315
score: 0
has text: Thank you Sir, this is simple and I could get output as desired.

http://stackoverflow.com/q/47901045
accepted answer: http://stackoverflow.com/a/47901094
has body: I've installed django version 2.0 and default for urls is path I know that if in django 1.x can be urls and follow with regular expression, how do I use path for parameters instead of urls, and so I dont want to use urls because django by default add path not urls if its can be or use urls still I want to know how to use a path with parameters in django 2.0 here's my code from django.urls import include, path from . import views urlpatterns = [ path('', views.articles_list), path('add', views.articles_add), path('edit', views.articles_edit) ]
upvote count: 8
has answer: http://stackoverflow.com/a/49623456
tagged with: django
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49623456
type: Question
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/47901094
has title: How do I add parameter in django 2.0 using path
tagged with: python
favorite count: 0
score: 8

http://stackoverflow.com/comment/82747431
has text: Pointless, rather than bad. If the idea is that you'd have multiple implementations with the same interface, then that's more sensibly handled with an abstract base class they all inherit.
score: 0
comment on: http://stackoverflow.com/q/47890059
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82772629
has text: @jonrsharpe I found a better duplicate. Swapped yours in second position. hope you don't mind
comment on: http://stackoverflow.com/q/47902957
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82703246
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47868445
type: Comment
has text: Fatal error! Cannot run scripts test

http://stackoverflow.com/comment/82762088
score: 0
has text: Oh, I feel so stupid. That was a really simple mistake. Anyway thanks for the feedback.
comment on: http://stackoverflow.com/q/47879544
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47969937
tagged with: ipython
type: Question
tagged with: jupyter-lab
has comment: http://stackoverflow.com/comment/115087331
score: 62
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/116613160
tagged with: jupyter
answer count: 4
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/92843628
has answer: http://stackoverflow.com/a/71096651
has comment: http://stackoverflow.com/comment/101476039
has comment: http://stackoverflow.com/comment/117249736
type: UnansweredQuestion
has body: I'm currently training a neural network on a remote server, using jupyter notebook. I set it up with the following: tmux jupyter-notebook --no-browser --port=5000 connecting to jupyter notebook with a browser and executing the cell for the training (output was fine when I watched for the first 10 minutes) detach tmux (ctrl-b, d) and closing the browser tab Now, when I reconnect to the jupyter notebook in the browser, I don't see the current output of the training cell, only the output that I saw when I was watching the first 10 minutes of training. I tried to find a solution for this and, I think, there are some git issues for this certain problem but they are old and I couldn't figure out if this issue was solved or not. edit// to make my intentions more clear, since I found some threads on StackOverflow that are addressing this problem: I don't want to wait for the training to complete, as I might want to kill the training before it finishes, when it absolutely doesn't go they way I would expect it to go. So some sort of 'live' output or at least regular output would be nice.
linked to: http://stackoverflow.com/q/45200375
tagged with: python
has title: Reconnecting remote Jupyter Notebook and get current cell output
has comment: http://stackoverflow.com/comment/93274646
has answer: http://stackoverflow.com/a/68808263
has answer: http://stackoverflow.com/a/66811187
has answer: http://stackoverflow.com/a/65589103
upvote count: 62

http://stackoverflow.com/q/47921250
has title: Replace selected integer value with list of values with Pandas
has answer: http://stackoverflow.com/a/47921546
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/47921334
has body: I have a pandas dataframe that has column "Survived". That column has two possible values: 1 and 0. I want to replace 1 with [1, 0] and 0 with [0, 1]. These are the ways I have tried to do it: First convert column data type from int to object: data["Survived"] = data["Survived"].astype(object) Then try changing the value (they all work with integers, but not with lists): data["Survived"][data["Survived"] == 1] = 5 # works data["Survived"][data["Survived"] == 1] = [1, 0] # ValueError: cannot assign mismatch length to masked array data["Survived"][::].replace(1, 5) # works data["Survived"][::].replace(1, [1, 0]) # {TypeError}Invalid "to_replace" type: 'int' And some other similar methods that result in these errors. Oddly enough I can set values to list one by one. So if I iterate over all entries I can change them all to lists (this gives the result I want): for i, val in enumerate(data["Survived"]): data["Survived"][i] = [1, 0] if val == 1 else [0, 1] This how ever, is slow and ugly. What is the pandas way of doing this?
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/47921334
has comment: http://stackoverflow.com/comment/82810522
tagged with: python
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47921546
upvote count: 2
has answer: http://stackoverflow.com/a/47921450
type: Question

http://stackoverflow.com/a/47976954
has comment: http://stackoverflow.com/comment/82927189
answers question: http://stackoverflow.com/q/47976792
has comment: http://stackoverflow.com/comment/82924583
score: 0
has body: the first 'u' means the string was encoder by 'utf-8', so if you pass 'u'aa'' into the function, it just feed the string which is 'aa'. So you can pass s"u'aa'" to get output u'aa'.
has comment: http://stackoverflow.com/comment/82927468
type: Answer

http://stackoverflow.com/a/47984793
type: Answer
answers question: http://stackoverflow.com/q/47984764
has comment: http://stackoverflow.com/comment/82939221
has body: Source DFs: In [172]: d1 Out[172]: txt 0 WXYnineZAB 1 EFGsixHIJ 2 QRSeightTUV 3 GHItwoJKL 4 YZAfiveBCD .. ... 25 QRSeightTUV 26 ABConeDEF 27 STUfourVWX 28 CDEtenFGH 29 GHItwoJKL [30 rows x 1 columns] In [173]: d2 Out[173]: word 0 one 1 three 2 five 3 seven 4 nine generate RegEx pattern from the second DataFrame: In [174]: pat = r'({})'.format(d2['word'].str.cat(sep='|')) In [175]: pat Out[175]: '(one|three|five|seven|nine)' extract words matching the RegEx pattern and assign them as a new column: In [176]: d1['new'] = d1['txt'].str.extract(pat, expand=False) In [177]: d1 Out[177]: txt new 0 WXYnineZAB nine 1 EFGsixHIJ NaN 2 QRSeightTUV NaN 3 GHItwoJKL NaN 4 YZAfiveBCD five .. ... ... 25 QRSeightTUV NaN 26 ABConeDEF one 27 STUfourVWX NaN 28 CDEtenFGH NaN 29 GHItwoJKL NaN [30 rows x 2 columns] you can also fill NaN's if you want in the same step: In [178]: d1['new'] = d1['txt'].str.extract(pat, expand=False).fillna('***') In [179]: d1 Out[179]: txt new 0 WXYnineZAB nine 1 EFGsixHIJ *** 2 QRSeightTUV *** 3 GHItwoJKL *** 4 YZAfiveBCD five .. ... ... 25 QRSeightTUV *** 26 ABConeDEF one 27 STUfourVWX *** 28 CDEtenFGH *** 29 GHItwoJKL *** [30 rows x 2 columns]
has comment: http://stackoverflow.com/comment/82938746
score: 0
has comment: http://stackoverflow.com/comment/82941185
has comment: http://stackoverflow.com/comment/82945587
has comment: http://stackoverflow.com/comment/82938754

http://stackoverflow.com/q/47954890
tagged with: combinations
has comment: http://stackoverflow.com/comment/82879750
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47955527
score: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82879157
tagged with: algorithm
downvote count: 0
has comment: http://stackoverflow.com/comment/82880974
has comment: http://stackoverflow.com/comment/82879197
has comment: http://stackoverflow.com/comment/82879208
has comment: http://stackoverflow.com/comment/82879797
has answer: http://stackoverflow.com/a/47955605
has comment: http://stackoverflow.com/comment/82879195
has comment: http://stackoverflow.com/comment/82879382
possible better answer: http://stackoverflow.com/a/47955527
has comment: http://stackoverflow.com/comment/82879236
answer count: 3
has body: I want to generate all possible sequence of alternative digit and numbers. For example 5j1c6l2d4p9a9h9q 6d5m7w4c8h7z4s0i 3z0v5w1f3r6b2b1z NumberSmallletterNumberSmallletter NumberSmallletterNumberSmallletter NumberSmallletterNumberSmallletter NumberSmallletterNumberSmallletter I can do it by using 16 loop But it will take 30+ hours (rough idea). Is there any efficient way. I hope there will be in python.
has title: Generate all possible sequence of altrenate digits and alphabets
has comment: http://stackoverflow.com/comment/82879380
tagged with: permutation
has answer: http://stackoverflow.com/a/47955687
accepted answer: http://stackoverflow.com/a/47955687
has comment: http://stackoverflow.com/comment/82880085
has comment: http://stackoverflow.com/comment/82879921
favorite count: 0
has comment: http://stackoverflow.com/comment/82880784
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82879989

http://stackoverflow.com/a/47918478
score: 1
has comment: http://stackoverflow.com/comment/82858386
has comment: http://stackoverflow.com/comment/82855153
type: AcceptedAnswer
downvote count: 0
has body: See page1_data = name1 + "," + location1 + "," + review_date1 + "," + review_title1 + "," + review_data1 + "\n" csv1.write(page1_data) There is already comma used in, say, location: Delhi, India. If you keep using comma like you did above, the csv file cannot be parsed properly. **One workaround is to put "" around your text containing comma. So the Delhi, India would be turned into "\Delhi, India" after this step. ** def preprocess(text): if "," in text: return '"' + text + '"' return text Wrap each of your text with the function. page1_data = preprocess(name1) + "," + preprocess(location1) + "," + preprocess(review_date1) + "," + preprocess(review_title1) + "," + preprocess(review_data1) + "\n" This should work. Another way should be changing the delimiter to other characters.
accepted answer of: http://stackoverflow.com/q/47918306
answers question: http://stackoverflow.com/q/47918306
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/82859917

http://stackoverflow.com/comment/82932037
has text: LOL. It's not related to Python per se. That is the way they accept assignements, through their scipts. I'm here to learn the logic/algorithms which I was told to be implemented in any language. Some one in the discussion stated that he/she uses F#. So, I was looking for a way to do it in Java.
comment on: http://stackoverflow.com/q/47979723
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82899728
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47963980
has text: what is ``util.wait_for_quit()` ? Better use standard `while` loop with `for event` loop.

http://stackoverflow.com/comment/82779634
score: 0
has text: index are tuples and row are dataframes, update your answer
type: AnswerComment
comment on: http://stackoverflow.com/a/47904669
type: Comment

http://stackoverflow.com/q/47957930
linked to: http://stackoverflow.com/q/29462888
upvote count: 4
linked to: http://stackoverflow.com/q/7534622
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/82886170
type: Question
tagged with: python
score: 4
tagged with: xpath
has body: I want to select text from the following html line: &lt;h3 data-reacid ='64'&gt; text to select &lt;h3&gt; I tried to use xpath. But for some reason, selenium can not find this element by xpath. I want to select the text by the 'data-reactid' attribute. I am not sure how to do this. I am using selenium with python.
answer count: 2
tagged with: selenium
has title: How to find element by atrribute using selenium?
has comment: http://stackoverflow.com/comment/82886181
has answer: http://stackoverflow.com/a/47957937
has answer: http://stackoverflow.com/a/76154247
type: UnansweredQuestion

http://stackoverflow.com/q/48007472
answer count: 1
tagged with: arrays
tagged with: neural-network
favorite count: 0
has answer: http://stackoverflow.com/a/48031853
tagged with: python-3.x
tagged with: python
downvote count: 0
type: UnansweredQuestion
score: 1
has title: Numpy arrays from tuples of arrays for matrix based neural networks
linked to: http://stackoverflow.com/q/40084931
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82983150
upvote count: 1
has body: To implement learning in a neural network I'm using stochastic gradient descent in which the mini batches are represented via the following list comprehension: mini_batches = [training_data[j:j+mini_batch_size] for j in range(0,len(training_data),mini_batch_size)] Inside the list comprehension the snippets mini_batch_size and training_data stem from inputs to the stochastic gradient descent method, which is a part of a neural network class. The training_data consists of tuples of arrays (x,y), whereby the first array x contains the input data and the second array y contains the output data (the classification). The array x has shape (784,1) and the array y has shape (10,1). The length len(training_data) outputs 50,000. I'd like to construct two Numpy arrays, whereby the first array is a matrix for the input data and the second array is a matrix for the output data. The two arrays would be utilized in a matrix based approach to the learning algorithm. However, I am not sure of a simple implementation for the array constructions. Help along this direction would be greatly appreciated. The mini_batch_size is an integer, which specifies how the training_data will be partitioned. The sliced training data, namely training_data[0] is of the following form (the first part of the tuple contains 784 floats from 0. to 1. and the latter part of the tuple contains 10 floats): (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. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ], [ 0. ]…

http://stackoverflow.com/comment/82932223
has text: That's a bad idea. Learn about lists and dictionaries instead.
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/47981918

http://stackoverflow.com/comment/82765588
type: QuestionComment
has text: True. That's not the problem... This is helping me: https://stackoverflow.com/questions/23994233/calling-a-method-from-an-existing-instance and I think I'm almost there!!
comment on: http://stackoverflow.com/q/47896952
score: 0
type: Comment

http://stackoverflow.com/q/47874350
has answer: http://stackoverflow.com/a/53746047
tagged with: jenkins
upvote count: 2
tagged with: screenshot
answer count: 1
has comment: http://stackoverflow.com/comment/82720121
has comment: http://stackoverflow.com/comment/82743281
tagged with: python-behave
type: UnansweredQuestion
score: 2
has body: There seems to be a very limited amount of people working with Allure/Python/Behave. I've been configuring my BDD (Behave) framework to run on Jenkins over the past couple of weeks and during that time i discovered Allure. It looks extremely powerful. I'm wondering how to get screenshots attached to failed steps and have them display in the Allure report in Jenkins. There is simple code being passed around here. I guess I'm just not sure what I'm missing or where i need to place this code. Here's my code right now in my environment.py file for after_step: def after_step(context, step): time.sleep(2) if step.status == "failed": allure.attach(context.browser.driver.get_screenshot_as_file ('screenshots\\{}.png'.format (step.name)), name="Screenshot", attachment_type=AttachmentType.PNG) When I open the report in Jenkins, there is no screenshot.
downvote count: 0
linked to: http://stackoverflow.com/q/29929244
favorite count: 0
has title: Allure Failure Screenshots
type: Question
has comment: http://stackoverflow.com/comment/82747113
tagged with: python
tagged with: allure

http://stackoverflow.com/q/47876407
tagged with: python-asyncio
tagged with: python
has title: Python asyncio ensure_future decorator
favorite count: 0
linked to: http://stackoverflow.com/q/37278647
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47882769
downvote count: 0
upvote count: 4
type: AnsweredQuestion
has body: Let's assume I'm new to asyncio. I'm using async/await to parallelize my current project, and I've found myself passing all of my coroutines to asyncio.ensure_future. Lots of stuff like this: coroutine = my_async_fn(*args, **kwargs) task = asyncio.ensure_future(coroutine) What I'd really like is for a call to an async function to return an executing task instead of an idle coroutine. I created a decorator to accomplish what I'm trying to do. def make_task(fn): def wrapper(*args, **kwargs): return asyncio.ensure_future(fn(*args, **kwargs)) return wrapper @make_task async def my_async_func(*args, **kwargs): # usually making a request of some sort pass Does asyncio have a built-in way of doing this I haven't been able to find? Am I using asyncio wrong if I'm lead to this problem to begin with?
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/109289074
possible better answer: http://stackoverflow.com/a/47882769
has comment: http://stackoverflow.com/comment/109254341
has answer: http://stackoverflow.com/a/47880675
accepted answer: http://stackoverflow.com/a/47880675
score: 4
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/109270327

http://stackoverflow.com/q/47935189
score: 0
has comment: http://stackoverflow.com/comment/82840041
has comment: http://stackoverflow.com/comment/82839849
has comment: http://stackoverflow.com/comment/82841319
answer count: 0
has comment: http://stackoverflow.com/comment/82839886
linked to: http://stackoverflow.com/q/437589
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82839783
has title: How to generate a .pyc file while python server is running automatically?
tagged with: python-2.7
has body: I am working for a big python project from last 3 years with some around 50 members working for that project, so now the project became too much big that atleast to restart that application server, it is taking 1 minute and 20 seconds. Here the issue is that it is becoming problem for me to modify my scripts and then dump to server and then to restart server. I am restarting server just to get my changes effected in the server, if I dont restart that server then it is not taking up my modified changes. Is there a way to make that server to take my changes automatically without restarting that python application server. Why is my new changes are not getting considered unless I restart my server, is it because .pyc file not getting generated when I dump my code to server? then is there any way to generate .pyc file while server is running. Thank you.
has comment: http://stackoverflow.com/comment/82839915
type: Question
has comment: http://stackoverflow.com/comment/82839795
tagged with: python
has comment: http://stackoverflow.com/comment/82840110
has comment: http://stackoverflow.com/comment/82839810

http://stackoverflow.com/q/47957216
has comment: http://stackoverflow.com/comment/82884950
type: Question
has comment: http://stackoverflow.com/comment/82885802
has body: I have a project related Lindenmayer system. I have stuck on something due to the algorithm. I would like to create a rule finder between two strings such as Gen1: A B A A B A B A Gen2: A B A A B A B A A B A A B The output should be: rule1: A, AB rule2: B, A This rule should be used for any strings which have relationship. I created some methods they find constants in the strings such as: "A", "B" However, I do not know how to find rules. def compare(newcode, trialrule1, trialrule2): if newcode==Genx2: print('rules are tru') print(trialrule1) print(trialrule2) sys.exit() else: return newcode, trialrule1, trialrule2 def rulefinder(): rul1 = Genx2[0] rul2 = Genx2[1] code = "" for y in range(1,len(Genx2)-1): for x in range (0,len(Genx2)-1): for cha in Genx1: if cha==repetitivestring1[0]: code +=AddingToNewString2(rul1) elif cha==repetitivestring1[1]: code +=AddingToNewString2(rul2) print(code) compare(code, rul1, rul2) rul1=AddingToNewString2(Genx2[x+1]) rul2=AddingToNewString2(Genx2[y+1]) def AddingToNewString2(rules): NewString = "" NewString = NewString + rules return NewString
has title: Challenging issue how to find rules between strings?
tagged with: string
tagged with: crossword
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 0

http://stackoverflow.com/comment/82923852
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47977251
score: 0
has text: @juanpa.arrivillaga I didnt defined in their own module because I thought there would be too many of them with awkward and lengthy names. Defining an inner class would be nicer since it doesnt force to invent a new class name every time, also, since the return type is specific to a function it makes (?) sens to constraint the scope of the definition only to this function. But yeah, looks like I have to define them in a separate module

http://stackoverflow.com/a/47946159
upvote count: 2
has comment: http://stackoverflow.com/comment/82863138
has comment: http://stackoverflow.com/comment/82865820
type: Answer
answers question: http://stackoverflow.com/q/47946061
has body: If the reference can be created with basic indexing/slicing, then you get a view (an array that does not own its data, but refers to another array’s data instead) of the initial array where changes propagate: &gt;&gt;&gt; nn = nodes[0:4:3] # reference array for rows 0 and 3 &gt;&gt;&gt; nn[0][0] = 0 &gt;&gt;&gt; nodes array([[0, 2], [2, 3], [3, 4], [4, 5], [5, 6]]) Otherwise, you get a copy from the original array as in your code, and updates do not propagate to the initial array.
score: 2
downvote count: 0

http://stackoverflow.com/q/47965618
answer count: 1
tagged with: python
favorite count: 0
tagged with: pyqt5
upvote count: 1
has answer: http://stackoverflow.com/a/47965638
has title: PyQt5: How to click a button to start the paint?
type: AnsweredQuestion
score: 1
tagged with: qpushbutton
type: Question
tagged with: qwidget
tagged with: pyqt
accepted answer: http://stackoverflow.com/a/47965638
downvote count: 0
has body: The following code makes a button and a rectangle. I would like to change it, so that the rectangle is drawn when the button is clicked. from PyQt5.QtWidgets import QWidget, QApplication, QPushButton from PyQt5.QtGui import QPainter, QColor, QBrush import sys class Example(QWidget): def __init__(self): super(Example, self).__init__() self.initUI() def initUI(self): self.setFixedSize(400, 400) self.setWindowTitle('Colours') self.btn = QPushButton("Paint", self) self.btn.move(100, 100) # self.btn.clicked.connect(self.paintEvent()) self.show() def paintEvent(self, e): qp = QPainter() qp.begin(self) self.drawRectangles(qp) qp.end() def drawRectangles(self, qp): col = QColor(0, 0, 0) col.setNamedColor('#d4d4d4') qp.setPen(col) qp.setBrush(QColor(200, 0, 0)) qp.drawRect(10, 15, 90, 60) if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) Thanks for your help!
has comment: http://stackoverflow.com/comment/82900992

http://stackoverflow.com/a/47870318
has body: Option 1 If you're getting these outputs from pip, you can do it programmatically, using pip.operations.freeze - from pip.operations import freeze modules = list( map(lambda x: x.split('=='), freeze.freeze(local_only=True)) ) print(modules) [['aiodns', '1.1.1'], ['aiohttp', '1.2.0'], ['appdirs', '1.4.0'], ['appnope', '0.1.0'], ['argparse', '1.4.0'], ... Option 2 You could also use get_installed_distributions, taken from here: import pip modules = [] for i in pip.utils.get_installed_distributions(): modules.append((i.key, i.version)) print(modules) [('pytreebank', '0.2.4'), ('cssselect', '1.0.1'), ('numba', '0.36.0.dev0+92.g2818dc9e2'), ('llvmlite', '0.0.0'), ('yarl', '0.8.1'), ('xlwt', '1.3.0'), ('xlrd', '1.1.0'), ... ] Option 3 A third method is using pip.main - import pip pip.main(['list', 'local']) However, this writes to stdout.
type: Answer
has comment: http://stackoverflow.com/comment/82706376
has comment: http://stackoverflow.com/comment/82706168
downvote count: 0
has comment: http://stackoverflow.com/comment/82706313
answers question: http://stackoverflow.com/q/47869800
score: 3
has comment: http://stackoverflow.com/comment/82706266
accepted answer of: http://stackoverflow.com/q/47869800
has comment: http://stackoverflow.com/comment/82706199
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/93131468
upvote count: 3

http://stackoverflow.com/q/47880600
has comment: http://stackoverflow.com/comment/82727175
has title: Whats wrong with my if else code?
type: Question
has answer: http://stackoverflow.com/a/47881610
accepted answer: http://stackoverflow.com/a/47881610
has comment: http://stackoverflow.com/comment/82727120
possible better answer: http://stackoverflow.com/a/47880748
favorite count: 0
has comment: http://stackoverflow.com/comment/82727169
answer count: 3
has comment: http://stackoverflow.com/comment/82727237
tagged with: python
linked to: http://stackoverflow.com/q/20449427
upvote count: 0
downvote count: 2
has answer: http://stackoverflow.com/a/47880748
has comment: http://stackoverflow.com/comment/82727062
has body: Can someone shed some light on what I'm doing wrong with my code? I'm using Python 3.6. And a beginner. Thanks! import random dice1 = random.randint(1, 2) user_input = input("Guess a number: ") if dice1 == user_input: print("Well Done!") else: print("Try again")
has answer: http://stackoverflow.com/a/47880643
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82727165
score: -2

http://stackoverflow.com/q/47927851
type: Question
has answer: http://stackoverflow.com/a/47927959
answer count: 2
linked to: http://stackoverflow.com/q/47924400
has comment: http://stackoverflow.com/comment/82824140
has body: For: df = pd.DataFrame({'a': (1,1,2,3,3), 'b':(20,21,30,40,41)}) Why is only this working df['b_new'] = df.a.map(df.groupby('a').b.nth(-1)) but not: &gt;&gt;df['b_new'] = df.a.map(df.groupby('a').nth(-1)) ... TypeError: 'DataFrame' object is not callable although both: &gt;&gt;df.groupby('a').b.nth(-1) b a 1 21 2 30 3 41 and df.groupby('a').nth(-1) - b a 1 21 2 30 3 41 do deliver quite similar results. (see also: https://stackoverflow.com/a/47924467/7450524
accepted answer: http://stackoverflow.com/a/47927959
possible better answer: http://stackoverflow.com/a/47927895
has comment: http://stackoverflow.com/comment/82824122
has answer: http://stackoverflow.com/a/47927895
tagged with: pandas-groupby
tagged with: pandas
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/82824230
has title: TypeError: 'DataFrame' object is not callable when using pd.Series.map
downvote count: 2
upvote count: 1
type: AnsweredQuestion
tagged with: group-by
score: -1
has comment: http://stackoverflow.com/comment/82824591

http://stackoverflow.com/q/47997914
answer count: 1
has comment: http://stackoverflow.com/comment/82964138
type: UnansweredQuestion
tagged with: python
has title: How do I make the same alteration to individual files in a directory?
tagged with: dataframe
type: Question
has body: I have a directory that the full set of csv files I would like to make alterations to. Each csv has a row that has date, and I would like to add a column that counts down from the length of the file down to 1 (so the last, most recent date in the file would have a value of 1 in that column. I have tried the following: &gt;import os &gt;import pandas as pd &gt;for f in os.listdir(path): &gt; df = pd.read_csv(f) &gt; df['Countdown'] = range(len(df), 1, -1) This gives me an error of FileNotFoundError: File b'Data.csv' does not exist Which is odd as it gives the specific name of the Data file that is in the directory, so it can clearly see the file as it is using it's name in the error message. I have tried using glob as well. &gt;import glob &gt;data_set = glob.glob(path) &gt;for f in data_set: &gt; df = pd.read_csv(f) &gt; df['Countdown'] = range(len(df), 1, -1) This does not work as it says: ValueError: Length of values does not match length of index This error makes sense to me, as the length of the dataframe is constantly increasing as I add more files to it, so the 'len(df)' argument is changing and doesn't match the indexes. I'm confident that what I'm trying to do isn't too unique, I'm just having trouble finding the best way to perform this task. Again, the outcome I'm looking for it to have individual files that each have a column that counts down from the earliest date to be the length of the dataframe, and the most recent date having a value of 1. Thank you for your assistance.
has answer: http://stackoverflow.com/a/47997958
score: 0
tagged with: listdir
tagged with: glob
tagged with: pandas

http://stackoverflow.com/q/47959120
accepted answer: http://stackoverflow.com/a/48108953
has comment: http://stackoverflow.com/comment/82889632
has title: Python getting attribute from other class to another class
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/3694371
has comment: http://stackoverflow.com/comment/82888093
has body: Fairly new to building apps in Python and I cannot figure out how to pass argument from other class function to other class. Based on what i read, i guess I should use def init in CustomPopup class but haven't been able to get it working. Here is a stripped version of what i am trying to do, this works but i am trying to get txt_input from popuper to CustomPopup but cannot get it working: Python: from kivy.app import App from kivy.lang import Builder from os import listdir from kivy.uix.screenmanager import Screen, ScreenManager from kivy.uix.popup import Popup import teradata import Global class CustomPopup(Popup): txt_input = 'Text' udaExec = teradata.UdaExec() kv_path = './kv/' for kv in listdir(kv_path): Builder.load_file(kv_path+kv) class LoginScreen(Screen): def buttonClicked(self): Global.u_name = self.ids.u_name.text Global.p_word = self.ids.p_word.text status = None try: with udaExec.connect("${dataSourceName}",username=self.ids.u_name.text,password=self.ids.p_word.text) as session: try: session except teradata.DatabaseError as e: status = e.code except teradata.DatabaseError as e: status = e.code if status == 8017: self.popuper('Hello') elif status == None: self.popuper('All Good') elif status == 0: self.popuper('Fill in username') else: self.popuper('Something else') def popuper(self, txt_input): popuper = CustomPopup() popuper.open() class MainScreen(Screen): pass class ScreenManagement(ScreenManager): pass application = Builder.load_file("main.kv") class MainApp(App): def build(self): self.title = 'Push Notfication Tool' return application if __name__ == "__main__": MainApp().run() Kivy: &lt;CustomPopup@Popup&gt;: size_hint: (.5,.5) auto_dismiss: False title: "af" BoxLayout: orientation: 'vertical' Label: text: root.txt_input Button: text: "Close now" on_press: root.dismiss() Thank you! *EDIT added kivy file as well.
type: Question
has comment: http://stackoverflow.com/comment/82887422
has comment: http://stackoverflow.com/comment/83164442
has comment: http://stackoverflow.com/comment/82890577
has answer: http://stackoverflow.com/a/48108953
score: 0
linked to: http://stackoverflow.com/q/625083
answer count: 1
tagged with: kivy
has comment: http://stackoverflow.com/comment/83168560
tagged with: python-3.x
tagged with: kivy-language
has comment: http://stackoverflow.com/comment/82937489
has comment: http://stackoverflow.com/comment/82887464
tagged with: python

http://stackoverflow.com/comment/82904783
score: 0
has text: Is this code Python?
type: Comment
comment on: http://stackoverflow.com/q/47967663
type: QuestionComment

http://stackoverflow.com/comment/82713636
has text: removing the quotes didnt work, and as i said below, when I replaced %1 %* with %%1 %%*, it worked only for very simple programs.
comment on: http://stackoverflow.com/q/47873361
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82886927
score: 0
type: Comment
type: QuestionComment
has text: @ShashiTunga See my link above and others' comments and answers.
comment on: http://stackoverflow.com/q/47958793

http://stackoverflow.com/comment/82721012
type: Comment
comment on: http://stackoverflow.com/a/47877223
has text: This is why I am confused with Keras' naming of the loss functions and its documentation. Either they have some additional implementation or I am missing something. Otherwise their naming & documentation is not very detailed and partly wrong?!
type: AnswerComment
score: 0

http://stackoverflow.com/q/48008612
has answer: http://stackoverflow.com/a/48048137
has comment: http://stackoverflow.com/comment/82985410
answer count: 7
possible better answer: http://stackoverflow.com/a/48008784
has comment: http://stackoverflow.com/comment/82985406
favorite count: 0
has comment: http://stackoverflow.com/comment/82985577
tagged with: python
has answer: http://stackoverflow.com/a/48008774
tagged with: dictionary
has answer: http://stackoverflow.com/a/48008719
has answer: http://stackoverflow.com/a/48008856
linked to: http://stackoverflow.com/q/10079216
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82985825
downvote count: 2
tagged with: loops
upvote count: 7
has body: I would like to know how I can loop over a Python dictionary without first and last element. My keys doesn't start at 1 so I can't use len(capitals) &gt;&gt;&gt; capitals = {'15':'Paris', '16':'New York', '17':'Berlin', '18':'Brasilia', '19':'Moscou'} &gt;&gt;&gt; for city in capitals: &gt;&gt;&gt; print(city) Paris New York Berlin Brasilia Moscou I would like this result: New York Berlin Brasilia My keys doesn't start at 1 so I can't use len(capitals)
has title: Looping over a dictionary without first and last element
linked to: http://stackoverflow.com/q/39980323
type: Question
has answer: http://stackoverflow.com/a/48008874
accepted answer: http://stackoverflow.com/a/48008719
has answer: http://stackoverflow.com/a/48008784
has answer: http://stackoverflow.com/a/61442968
score: 5

http://stackoverflow.com/comment/82872058
score: 2
comment on: http://stackoverflow.com/q/47951268
type: Comment
type: QuestionComment
has text: Your data is stored in your database not in app.

http://stackoverflow.com/comment/82950472
comment on: http://stackoverflow.com/q/47991057
score: 0
type: QuestionComment
type: Comment
has text: @Zero The problem is sorting not grouping

http://stackoverflow.com/a/47882579
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/47882420
accepted answer of: http://stackoverflow.com/q/47882420
has comment: http://stackoverflow.com/comment/82731500
has body: To extract every line containing 'NVSS' into a new file: with open('infile.txt', 'r') as infile, open('outfile.txt', 'w') as outfile: for line in infile: if 'NVSS' in line: outfile.write(line)
score: 0

http://stackoverflow.com/a/47877044
type: Answer
has body: Solved, forgot about the list method in python so all I had to do was data = list(r.db("database").table("table").run())
answers question: http://stackoverflow.com/q/47862032
score: 0

http://stackoverflow.com/q/47918665
linked to: http://stackoverflow.com/q/47906065
score: 0
tagged with: maya
has comment: http://stackoverflow.com/comment/82806929
linked to: http://stackoverflow.com/q/8724729
has body: I am getting Error when i Import Tkinter in maya.Can anyone explain me what is the meaning of this error and how to solve this ? import Tkinter Error: ImportError: file C:\Autodesk\Maya2014\Python\lib\lib-tk\Tkinter.py line 39: DLL load failed: %1 is not a valid Win32 application
answer count: 0
has comment: http://stackoverflow.com/comment/82809577
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82809639
has comment: http://stackoverflow.com/comment/82809835
tagged with: python
has comment: http://stackoverflow.com/comment/82810214
has comment: http://stackoverflow.com/comment/82809979
has comment: http://stackoverflow.com/comment/82809911
has comment: http://stackoverflow.com/comment/82806699
has comment: http://stackoverflow.com/comment/82806501
has title: Import Error while importing Tkinter in Auto Desk Maya
type: Question
has comment: http://stackoverflow.com/comment/82844906

http://stackoverflow.com/q/47957827
has title: Elements Inside Opening Tag
score: 0
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: css
tagged with: xpath
linked to: http://stackoverflow.com/q/44765194
type: UnansweredQuestion
tagged with: scrapy
has answer: http://stackoverflow.com/a/47958054
type: Question
answer count: 1
has body: I am writing a spider to download all images on the front page of a subreddit using scrapy. To do so, I have to find the image links to download the images from and use a CSS or XPath selector. Upon inspection, the links are provided but the HTML looks like this for all of them: loading... From what I can tell, it looks like all of the new elements are being initialized inside the opening tag of the element. Could you explain what exactly is going on here, and how one would go about extracting image information from this? *Sorry, I'm not quite sure how to properly format the html code, but there really isn't all too much to format, as it is all one big tag anyway.
has comment: http://stackoverflow.com/comment/82890659

http://stackoverflow.com/q/47890515
tagged with: python
has comment: http://stackoverflow.com/comment/82747999
answer count: 0
score: 0
type: UnansweredQuestion
has title: ValueError: setting an array element with a sequence when running sklearn adaboost
has body: I'm new and python and trying to use machine learning. But my code doesn't work. My dataset is very simple, it contains seven images (without fixed size). I tried to make a segmentation and run the adaboost algorithm but get this error. Error: array = np.array(array, dtype=dtype, order=order, copy=copy) **ValueError: setting an array element with a sequence.** My code from skimage import data import glob import numpy as np from sklearn import cluster from sklearn.naive_bayes import GaussianNB from sklearn.ensemble import AdaBoostClassifier initDataset = [] samplesListFiles = glob.glob("/home/bv/Downloads/sampleimage/*.*") i = 0 for fileC in samplesListFiles: img = data.imread(fileC, as_grey=True) array = np.reshape(img, (np.product(img.shape), 1)) model = cluster.KMeans(n_clusters=3, random_state=25) results = model.fit(array[::1]) X = array[::1] X = results.predict(X) initDataset.append(X) dataset = np.array(initDataset) C = 1.0 X=dataset y=[[0.], [0.], [1.], [0.], [1.], [1.], [0.]] rez = [] for i in range(0, len(y)): rez.append(y[i][0]) svc = GaussianNB() clf = AdaBoostClassifier(n_estimators=100, base_estimator=svc,learning_rate=1) X = X.reshape((7,-1)) clf.fit(X,rez) print "TEST" cancerListFiles = glob.glob("/home/bv/Downloads/cancerimage/*.*") for fileC in samplesListFiles: img = data.imread(fileC, as_grey=True) array = np.reshape(img, (np.product(img.shape), 1)) model = cluster.KMeans(n_clusters=3, random_state=25) results = model.fit(array[::1]) X = array[::1] X = results.predict(X) print clf.predict(X) Befor call .fit X is [[array([0, 0, 0, ..., 0, 0, 0], dtype=int32)] [array([0, 0, 0, ..., 0, 0, 0], dtype=int32)] [array([1, 1, 1, ..., 1, 1, 1], dtype=int32)] [array([0, 0, 0, ..., 0, 0, 0], dtype=int32)] [array([2, 2, 2, ..., 2, 2, 2], dtype=int32)] [array([0, 0, 0, ..., 0, 0, 0], dtype=int32)] [array([2, 2, 0, ..., 0, 0, 0], dtype=int32)]]
type: Question
has comment: http://stackoverflow.com/comment/82747668
tagged with: scikit-learn

http://stackoverflow.com/comment/82839052
comment on: http://stackoverflow.com/q/47921569
score: 0
type: Comment
type: QuestionComment
has text: @NareshKumar I'm using both, appending multiple csv to excel spreadsheet

http://stackoverflow.com/a/48022958
has body: Are their security threats associated with leveraging Anaconda? If so, what specifically? It depends on the environment. Do you have admin privileges ? How the global GPO policy looks like ? For example if you don't have an admin rights you can't do things like create a socket, access network stack on os level and vice versa. The thing is, that you can do similar damage with CMD/PowerShell also. Is the former secure than the latter, I don't think so .... If the risk is too great, what are alternatives to simply installing the Anaconda Suite? It depends on what kind of functionality you need from Anaconda, maybe you can use different python interpreter/framework, but from security perspective looks the same. Usually "IT Stuff" don't have a clue how to implement OS/Domain/Security in a proper manner so their solution is to tell everybody that it's a security risk. In these days, everything is a security risk.
type: Answer
has comment: http://stackoverflow.com/comment/83019332
accepted answer of: http://stackoverflow.com/q/48014537
answers question: http://stackoverflow.com/q/48014537
type: AcceptedAnswer
score: 0

http://stackoverflow.com/comment/82788451
type: AnswerComment
comment on: http://stackoverflow.com/a/47909859
type: Comment
score: 1
has text: @MikeMathMan If you want to avoid floating point imprecision, you could replace `m <= .5*r*(r+1)` with `2*m <= r*(r+1)` or `m <= (r*(r+1)) // 2` (as `(r*(r+1)` will always be even).

http://stackoverflow.com/comment/82874271
has text: how can I sort results with price?
type: Comment
comment on: http://stackoverflow.com/a/47952388
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82897683
type: Comment
has text: Is the file executable on the system? (via chmod ?)
type: AnswerComment
comment on: http://stackoverflow.com/a/47964058
score: 0

http://stackoverflow.com/comment/82956776
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47994214
has text: "Write a regex that matches words that contain 2 or more 2-letter sequences of vowels". Beautiful doesn't meet this requirement because it has only one 3-letter sequence of vowels. What I'm trying to say is that the sequence of vowels cant be bigger than 2.

http://stackoverflow.com/comment/82704733
score: 0
comment on: http://stackoverflow.com/q/47865981
type: Comment
type: QuestionComment
has text: A session is removed only on app teardown. What should I do after request? Rollback? Close session? Which approach is better? Also If I close a session, what will happen with not committed/rollbacked transactions?

http://stackoverflow.com/comment/82720887
comment on: http://stackoverflow.com/a/47877298
score: 0
type: AnswerComment
type: Comment
has text: The DateCount col works great; However, I got a syntax error for using dict. I changed it to d={'X':'X','A':'Adam'} but all I got is Other.

http://stackoverflow.com/a/70556339
type: Answer
has body: I had a similar problem. I'll describe what I did generally because application may vary. For smaller frames it won't matter so the above methods might work but for larger frames like mine (i.e.; hundreds of thousands to millions of rows) I would do this: Sort dat by 'cars' Get a unique list of cars Create a temporary list for the random numbers Loop over that list of cars and populate the temporary list of random numbers and extending a new list with the temp list Add the new list to the 'persons' column If order matters maintain and re-sort by the index
downvote count: 1
score: -1
upvote count: 0
answers question: http://stackoverflow.com/q/47995898

http://stackoverflow.com/comment/82942203
has text: Indeed it does. Thanks!
comment on: http://stackoverflow.com/a/47986474
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/47878367
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82723211
has comment: http://stackoverflow.com/comment/82722903
has body: Is there a handy way to create a json self-representation of a model Class in Django project? Say I have a model like this: class MyModel(models.Model): some_bool_field = models.BooleanField(default=True) some_char_field = models.CharField(max_length=20, blank=False) I need a serializer of some sort that will return me a json object representing model architecture of the class itself, something like: { 'model_class': 'MyModel', 'some_bool_field': {'type': 'BooleanField', 'default': 'true'}, 'some_char_field': {'type': 'CharField', 'max_length': '20', 'blank': 'false' } } I'm using Django-rest-framework for API creation, so maybe there is ready solution buried inside framework I'm not aware of?
tagged with: http://stackoverflow.com/tag/json
tagged with: django-models
has comment: http://stackoverflow.com/comment/82722801
score: 0
has comment: http://stackoverflow.com/comment/82723136
has answer: http://stackoverflow.com/a/47880444
accepted answer: http://stackoverflow.com/a/47880444
answer count: 1
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/82722755
tagged with: python
has title: Django model class self-representation
tagged with: django

http://stackoverflow.com/comment/82934774
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47973248
has text: I don't see your `update` calling parent class `update`, so you are completely overriding the original tkinter widgets `update` method, and I think you are also doing a different thing. Why don't you call it something else? You may break something with this (your widget won't update besides what you change in it by hand in your custom update)

http://stackoverflow.com/a/48012986
answers question: http://stackoverflow.com/q/47874734
score: 0
type: Answer
has body: I found a workaround for the Paramiko defect I was hitting on version 1.15.1 and did not need to do any upgrade. My suspicion is my PI has a corrupt file which is causing the upgrade to fail.

http://stackoverflow.com/q/47944927
type: UnansweredQuestion
tagged with: python
downvote count: 0
has title: Making requests to shopify domain (python) raises SSLError
has answer: http://stackoverflow.com/a/47945054
tagged with: python-requests
has comment: http://stackoverflow.com/comment/82859837
has comment: http://stackoverflow.com/comment/82860270
type: Question
score: 1
answer count: 2
upvote count: 1
has body: I am trying to make a GET request to a shopify store, packershoes as follow: endpoint = "http://www.packershoes.com" print session.get(endpoint, headers=headers) When I run a get request to the site I get the following error: File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 467, in get return self.request('GET', url, **kwargs) File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 455, in request resp = self.send(prep, **send_kwargs) File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 558, in send r = adapter.send(request, **kwargs) File "/usr/lib/python2.7/dist-packages/requests/adapters.py", line 385, in send raise SSLError(e) requests.exceptions.SSLError: hostname 'packershoes.com' doesn't match either of '*.myshopify.com', 'myshopify.com' When I request a different sites, it works fine.
has answer: http://stackoverflow.com/a/47945927
favorite count: 0

http://stackoverflow.com/a/47973281
score: 5
upvote count: 5
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/47973191
has body: Believe it's because you missed the underscore: from django.conf.urls import url from.import views # app_name not appname app_name= 'accounts' urlpatterns = [ url(r'^signup/$', views.signup_view, name= "signup"), url(r'^login/$', views.login_view, name = "login" ), ]

http://stackoverflow.com/q/48014031
upvote count: 3
tagged with: selenium
has title: Using selenium, how would I click delete and yes on reddit?
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/48014658
type: Question
has body: I am just trying to learn python by playing around with surfing the web just by using python. One thing I came across was that on some sites, they might have a hidden button. For example, here on Reddit, if you go to your account page, and want to delete the first/top comment on your account page, you can easily find delete. The only problem is pressing the hidden button 'yes'. The issue is that some posts have the ability to change some settings, such as disable inbox replies, delete, etc, and not all post have these same features/buttons. They all have the same CSS selector of 'a.yes', so even if you get all elements, with driver.find_elements, you couldn't get the button consistently because of the other buttons, like delete and disable inbox replies, etc.. As one page could be elem[0] = delete.yes, elem[1] = disable inbox.yes and another page could be elem[0]~elem[4] = delete.yes The differences in the tags are: delete button yes disable inbox replies yes Currently this is what I have, but line 3 won't work, because of what is mentioned. elem = driver.find_element_by_link_text('delete') elem.click() #elem = driver.find_elements_by_css_selector('a.yes') #elem[i].click() Does anyone know how to get around this problem?
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82996973
tagged with: python
has comment: http://stackoverflow.com/comment/82997217
has comment: http://stackoverflow.com/comment/82997521
has answer: http://stackoverflow.com/a/48014658

nginx
tags question: http://stackoverflow.com/q/48006981
tags question: http://stackoverflow.com/q/47976482
tag name: nginx
tags question: http://stackoverflow.com/q/47934150
tags question: http://stackoverflow.com/q/47923884
tags question: http://stackoverflow.com/q/47971466
type: Tag
tags question: http://stackoverflow.com/q/47916263
tags question: http://stackoverflow.com/q/47981630
tags question: http://stackoverflow.com/q/47903273
tags question: http://stackoverflow.com/q/47945783

http://stackoverflow.com/q/47871213
has comment: http://stackoverflow.com/comment/82709575
has comment: http://stackoverflow.com/comment/82707751
has body: I am generating a frequency spectrogram using Python's STFT function. An output is being generated as shown in the graphic below (x-axis is time, and y-axis is frequency). The color is determined by the magnitude of the Short-Time Fourier Transform. I am trying to figure out how to determine when the yellow area exists for longer than, say, 20 time-steps. Ideally, I would like to trigger an event notification if the magnitude is detected to be high over this period of time. Pseudo-code: if (magnitude is yellow for 20 time steps); print (notification) The x-axis is time, and the y-axis is frequency, and the magnitude is determining the color. I am having a difficult time figuring out how to determine when the magnitude lasts longer than 20 time steps. data = pd.read_csv("C:\\Users\\test5.txt") data.columns = ['X', 'Y', 'Z'] f, t, Zxx = scipy.signal.stft(data['Z'], fs=250, nperseg = 100) med_filter = scipy.signal.medfilt(np.abs(Zxx), 15) ax1.pcolormesh(t, f, med_filter, vmin=0, vmax=0.001) fig, (ax1) = plt.subplots(1, sharex = False)
score: 0
tagged with: signals
has comment: http://stackoverflow.com/comment/82709631
favorite count: 0
tagged with: fft
has comment: http://stackoverflow.com/comment/82709894
type: UnansweredQuestion
tagged with: python
answer count: 0
has title: How to extract the length or time that a value is above a threshold in a 3-axis plot
has comment: http://stackoverflow.com/comment/82708441
upvote count: 1
has comment: http://stackoverflow.com/comment/82709799
downvote count: 1
tagged with: signal-processing
has comment: http://stackoverflow.com/comment/82708199
type: Question
has comment: http://stackoverflow.com/comment/124022419
has comment: http://stackoverflow.com/comment/82707846
has comment: http://stackoverflow.com/comment/82708968

http://stackoverflow.com/q/47901273
tagged with: python
tagged with: android-ndk
type: Question
has title: Install anaconda on ARM Cortex-A9 platform
tagged with: anaconda
has body: Base situation: Platform: ARM Cortex-A9 (32-bit processor) OS: Ubuntu Mate 16.04.4 gcc version: gcc (Ubuntu/Linaro 5.4.0-6ubuntu1-16.04.4) 5.4.0 201606609 python version: 2.7.12 Question: I want to install anaconda on ARM Cortex-A9 platform. However, when I execute: $./Anaconda2-5.0.1-Linux-x86.sh It return an error: /root/anaconda2/pkgs/python-2.7.14-h41cc02d_21/bin/python:1: /root/anaconda2/pkgs/python-2.7.14-h41cc02d_21/bin/python:Syntax error:word unexpected (expecting ")") How I can fit this problem? How I can install anaconda on ARM platform? Tks.
tagged with: arm
tagged with: gcc
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/50082675
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/78510865

http://stackoverflow.com/comment/82870354
has text: Yes it would indeed.
type: AnswerComment
comment on: http://stackoverflow.com/a/47950273
score: 0
type: Comment

http://stackoverflow.com/q/47892944
favorite count: 0
has answer: http://stackoverflow.com/a/47893839
has body: I am writing a code to extract information from a directed graph. This graph has cycles as well. For example, A-&gt;B-&gt;C-&gt;D A-&gt;E-&gt;F-&gt;A B-&gt;F-&gt;G From this graph, I want to create a sub graph or the list of the nodes, where the input would be any node, and output would be the graph where the input node is the root, or the list of the nodes that has all the child nodes ( till the end of the graph ) from the input nodes For example, in the above example, 1. If the input node is C, the output would be D 2. If the input node is B, the output node would be C,D,F,G,A ( Since there is a cycle, which makes A to B bidirectional ) 3. If the input is G, the output is blank or null. Is there any functionality in python networkx, that I can use to solve this problem ? Alternatively, is there any other tool that can help me solve this problem ?
has answer: http://stackoverflow.com/a/47935007
type: UnansweredQuestion
tagged with: python
tagged with: networkx
score: 3
upvote count: 3
tagged with: directed-graph
type: Question
has comment: http://stackoverflow.com/comment/82755313
tagged with: graph
has title: Python NetworkX find a subgraph in a Directed Graph from a node as root
has comment: http://stackoverflow.com/comment/82752579
downvote count: 0
answer count: 2

http://stackoverflow.com/q/47952283
duplicate of: http://stackoverflow.com/q/7701669
has comment: http://stackoverflow.com/comment/82874622
favorite count: 0
has body: I have an array A of shape (N,2) containing coordinate positions (in my case they are nodes coordinates positions x,y) and another array B of shape (N,1) containing the corresponding field values at the nodes in array A (in my case they are velocities). I would like to convert array B to a matrix in order to have an imshow() representation of the field at the nodes. I have tried an alternative method (below) to plot my field using an interpolation on a meshgrid but the result isn't what am expecting but it the codes take too much time to compute the interpolations. I think it would be easier to use imshow() method but i can't convert the field vector to a matrice def plotField(field,coord): xcoord = coord[:,0] #x coordinate zcoord = coord[:,1] #z coordinate x,z=np.meshgrid(xcoord,zcoord) y = gd((xcoord,zcoord),field,(x,z),method='nearest') #field interpolation plt.pcolormesh(x,z,field) plt.show() NB : In matlab one can do this with the patch command but i don't know it's equivalent in python. I found this question while searching which i think advanced python users should take a look to provide an answer ploting filled polygons in python
has comment: http://stackoverflow.com/comment/82874866
has comment: http://stackoverflow.com/comment/82874774
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/26935701
tagged with: python
has comment: http://stackoverflow.com/comment/82874847
has comment: http://stackoverflow.com/comment/82874564
answer count: 0
score: 1
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/82874259
has comment: http://stackoverflow.com/comment/82874747
upvote count: 1
type: Question
tagged with: numpy
has title: convert xy coordinates to matrix python
linked to: http://stackoverflow.com/q/18764814
has comment: http://stackoverflow.com/comment/82874890
has comment: http://stackoverflow.com/comment/82875085
linked to: http://stackoverflow.com/q/7701669
downvote count: 0
linked to: http://stackoverflow.com/q/43155211

http://stackoverflow.com/comment/82729180
comment on: http://stackoverflow.com/a/47881306
has text: OK, makes sense. Unfortunately this causes another issue which was initially solve by using @classmethod. Sigh
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82751377
type: QuestionComment
comment on: http://stackoverflow.com/q/47891056
has text: I'm sorry I tried it as both, the error is the same.
score: 0
type: Comment

http://stackoverflow.com/q/47900711
score: 1
accepted answer: http://stackoverflow.com/a/47902448
upvote count: 1
type: Question
tagged with: time-series
tagged with: dataframe
tagged with: pandas
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47902448
favorite count: 0
has body: I have a dataframe with hourly values during the workweek: &gt;&gt;&gt; vol_adjust.head() Out[59]: 2011-11-01 05:00:00+11:00 3237454603.000 2011-11-01 06:00:00+11:00 3292278695.000 2011-11-01 07:00:00+11:00 6037960826.000 2011-11-01 08:00:00+11:00 7127161746.000 2011-11-01 09:00:00+11:00 3382477744.000 &gt;&gt;&gt; vol_adjust.shape Out[60]: (29658, 1) The problem is that some of the values fall on saturdays- generally only 1 value. I have 5 such dates in the whole dataframe: &gt;&gt;&gt; vol_adjust[vol_adjust.index.dayofweek == 5] Out[63]: 2012-03-03 00:00:00+11:00 794977434.400 2012-03-17 00:00:00+11:00 403171073.800 2013-03-16 00:00:00+11:00 808805223.800 2014-03-15 00:00:00+11:00 1622434962.000 2016-03-05 00:00:00+11:00 569319700.900 Name: vol, dtype: float64 Upon inspection, it seems that on some day during the week, the data skips the 00:00 AM entry(midnight) e.g. &gt;&gt;&gt; vol_adjust['2012-03-01'].tail() Out[75]: 2012-03-01 19:00:00+11:00 931207673.400 2012-03-01 20:00:00+11:00 2213366040.000 2012-03-01 21:00:00+11:00 994524108.700 2012-03-01 22:00:00+11:00 541624218.800 2012-03-01 23:00:00+11:00 2085975988.000 Name: vol, dtype: float64 &gt;&gt;&gt; vol_adjust['2012-03-02'].head() Out[70]: 2012-03-02 01:00:00+11:00 1951010063.000 2012-03-02 02:00:00+11:00 1703256493.000 2012-03-02 03:00:00+11:00 947991961.000 2012-03-02 04:00:00+11:00 1210964133.000 2012-03-02 05:00:00+11:00 908680999.300 Name: vol, dtype: float64 I have a way of identifying such dates, and would like to move the hours up by 1 from the start of troubled day to the corresponding Saturday. Is there a simple way of doing this? e.g. lets say I knew '2012-03-02' to '2012-03-03' is the period where the index is off by 1 hour, how can I shift it up by 1 hr easily only for that time while keeping the rest unchanged?
tagged with: datetime
tagged with: python
type: AnsweredQuestion
has title: shifting partial datetimeindex by 1 hour pandas

http://stackoverflow.com/a/47972697
has body: Sorry for this stupid question (I had a problem with my other code). The solution is very simple. class BookResource(Resource): author_name = Field(attribute='author__name') class Meta: fields = ('author_name',) And it works.
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47972619
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47972619
type: Answer

http://stackoverflow.com/comment/82948519
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47989926
has text: The goal is just to iterate through an array and do something with each triplet. Looks like instead of using an enhanced for-loop which references the current element directly, I just use the index values to reference the element from the array (ie array[i] vs val)

http://stackoverflow.com/q/47986934
tagged with: multithreading
tagged with: dns
upvote count: 1
has comment: http://stackoverflow.com/comment/82943460
type: Question
has comment: http://stackoverflow.com/comment/82943419
has comment: http://stackoverflow.com/comment/82960338
answer count: 1
downvote count: 0
score: 1
has body: I am new to python. I am trying to use dns.resolver module in my program, where I pass a list of domains and run them with a pool of threads that reads the contents of the file asynchronously and then prints the results for each domain from the file. Below is the code : import dns.resolver from multiprocessing.pool import ThreadPool as Pool pool_size =4 pool = Pool(pool_size) dnsResolver = dns.resolver.Resolver() dnsResolver.timeout = 1 dnsResolver.lifetime = 1 dnsResolver.nameservers = ['172.31.0.2'] #domain_list = ['google.com','facebook.com', 'amazon.com'] #for domain in domain_list: # Query results for the dig operations from a file that contains less than 1024 domains in it def fetch_dig_no_blast_results(no_blast_domains): try: no_blast_domains = no_blast_domains.strip() dnsAnswer = dnsResolver.query(no_blast_domains) for rdata in dnsAnswer: print (no_blast_domains, "resolved to",str(rdata)) except dns.resolver.NXDOMAIN: print ("No records exists for", no_blast_domains) except dns.resolver.Timeout: print ("Timeout in querying",no_blast_domains) with open("no-blast-domains.txt",'r') as fd1: for no_blast_domains in fd1: pool.apply_async(fetch_dig_no_blast_results, (no_blast_domains,)) pool.close() pool.join() I have two questions. I need to print all the results of a dns query for a particular domain in the same line. For example, dns query for a domain 'amazon.com' gives three ip's. I need to print those three ip's in the same line - example that output I am looking at is something like : ['amazon.com' resolved to 'ip1', 'ip2', 'ip3'] Current code prints them in three lines ['amazon.com' resolved to 'ip1'] ['amazon.com' resolved to 'ip2'] ['amazon.com' resolved to 'ip3'] I want to make sure that each thread queries a different domain and no threads queries the same domain. Any suggestions would immensely help me out.
has answer: http://stackoverflow.com/a/48011774
tagged with: python
favorite count: 0
has title: Python dns resolver print all results for a domain in the same line
type: UnansweredQuestion

http://stackoverflow.com/a/47963600
downvote count: 0
has body: Unless you define related_name in your OneToOneField, Django will use lowercased model name to access related object. So, note.notelabel should work.
type: Answer
score: 13
upvote count: 13
accepted answer of: http://stackoverflow.com/q/47962580
has comment: http://stackoverflow.com/comment/82900758
answers question: http://stackoverflow.com/q/47962580
has comment: http://stackoverflow.com/comment/82901004
type: AcceptedAnswer

http://stackoverflow.com/comment/82715617
has text: Exactly that, yes. Which one does not matter, just the signal that one of them has been pressed.
type: Comment
comment on: http://stackoverflow.com/q/47874952
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82688819
comment on: http://stackoverflow.com/a/47861920
type: AnswerComment
has text: thank you, you have a good idea! I think I will try to use quicksort with list comprehensions and then extract the maximums.
score: 0
type: Comment

http://stackoverflow.com/comment/82836462
type: QuestionComment
has text: I've had issues with matplotlib not ever finishing the graph I was trying to make. It turned out to be that there were just too many data points and it was hanging on that. You should try to truncate your data set and graph just that small portion of it to see if this might be what's happening.
comment on: http://stackoverflow.com/q/47933420
score: 0
type: Comment

http://stackoverflow.com/a/47858268
has comment: http://stackoverflow.com/comment/82942603
downvote count: 0
has comment: http://stackoverflow.com/comment/82943229
has body: Based on example for scrapy. Server adds to url (in any place before .html) -or5 to get second page, -or10 to get third page, etc. You could even skip words (which are for SEO) and use only https://www.tripadvisor.com/g562819-d289642-or5.html https://www.tripadvisor.com/g562819-d289642-or10.html to get next pages with reviews. from bs4 import BeautifulSoup import requests import re #import webbrowser def get_soup(url): headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0'} r = s.get(url, headers=headers) #with open('temp.html', 'wb') as f: # f.write(r.content) # webbrowser.open('temp.html') if r.status_code != 200: print('status code:', r.status_code) else: return BeautifulSoup(r.text, 'html.parser') def parse(url, response): if not response: print('no response:', url) return # get number of reviews num_reviews = response.find('span', class_='reviews_header_count').text num_reviews = num_reviews[1:-1] # remove `( )` num_reviews = num_reviews.replace(',', '') # remove `,` num_reviews = int(num_reviews) print('num_reviews:', num_reviews, type(num_reviews)) # create template for urls to pages with reviews url = url.replace('.html', '-or{}.html') print('template:', url) # load pages with reviews for offset in range(0, num_reviews, 5): print('url:', url.format(offset)) url_ = url.format(offset) parse_reviews(url_, get_soup(url_)) return # for test only - to stop after first page def parse_reviews(url, response): print('review:', url) if not response: print('no response:', url) return # get every review for idx, review in enumerate(response.find_all('div', class_='review-container')): item = { 'hotel_name': response.find('h1', class_='heading_title').text, 'review_title': review.find('span', class_='noQuotes').text, 'review_body': review.find('p', class_='partial_entry').text, 'review_date': review.find('span', class_='relativeDate')['title'],#.text,#[idx], 'num_reviews_reviewer': review.find('span', class_='badgetext').te…
has comment: http://stackoverflow.com/comment/82942554
score: 4
has comment: http://stackoverflow.com/comment/82942699
answers question: http://stackoverflow.com/q/47856273
has comment: http://stackoverflow.com/comment/82942344
type: Answer
has comment: http://stackoverflow.com/comment/84537730
upvote count: 4

ubuntu-server
type: Tag
tag name: ubuntu-server
tags question: http://stackoverflow.com/q/47913841

http://stackoverflow.com/q/47983165
tagged with: linux
tagged with: python
has body: As part of a test suite written in Python 3[.4-.6] on Linux, I have to run a number 3rd-party tests. The 3rd-party tests are bash scripts. They are designed to run with Perl's prove TAP harness. One bash script can contain up to a few thousands of individual tests - and some of them can hang indefinitely. After a timeout, I want to kill the test script and gather some information on where it got stuck. Because the bash scripts create processes of their own, I try to isolate the entire prove process tree into a new process group, so I can eventually kill the entire process group as a whole if things go wrong. Because the tests must run with root privileges, I use sudo -b for creating a new process group with root privileges. This strategy (as opposed to using setsid in one way or the other) is a result of the comments I received on this question at SE Unix&amp;Linux The problem is that I loose all output from the prove TAP harness if I kill it 'prematurely' when launched with sudo -b through Python's subprocess.Popen. I isolated it into a simple test case. The following is a bash test script named job.t: #!/bin/bash MAXCOUNT=20 echo "1..$MAXCOUNT" for (( i=1; i&lt;=$MAXCOUNT; i++ )) do echo "ok $i" sleep 1 done Just for comparison, I also wrote a Python script named job.py producing more or less the same output and exhibiting the same behavior: import sys import time if __name__ == '__main__': maxcount = 20 print('1..%d' % maxcount) for i in range(1, maxcount + 1): sys.stdout.write('ok %d\n' % i) time.sleep(1) Last but not least, the following is my stripped-down "Python test infrastructure" named demo.py: import psutil # get it with "pip install psutil" import os import signal import subprocess def run_demo(cmd, timeout_after_seconds, signal_code): print('DEMO: %s' % ' '.join(cmd)) proc = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE) try: outs, errs = proc.communicate(timeout = timeout_after_seconds) except subprocess.TimeoutExpired: prin…
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/48042420
possible better answer: http://stackoverflow.com/a/48040922
type: Question
has comment: http://stackoverflow.com/comment/83113106
answer count: 2
tagged with: perl-prove
has answer: http://stackoverflow.com/a/48042420
tagged with: perl
score: 10
tagged with: tap
has title: How do I run Perl's ``prove`` TAP harness in unbuffered mode?
upvote count: 10
has answer: http://stackoverflow.com/a/48040922
favorite count: 0

http://stackoverflow.com/comment/82977863
type: QuestionComment
has text: @sancho.s That is certainly true for Python 2, but in Python 3 CSV files _must_ be opened in text mode. This is rather annoying when you want to process CSV files with code that runs on both Python 2 & Python 3.
comment on: http://stackoverflow.com/q/48004691
score: 0
type: Comment

http://stackoverflow.com/q/48010317
has answer: http://stackoverflow.com/a/48014188
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82989370
possible better answer: http://stackoverflow.com/a/48014188
has answer: http://stackoverflow.com/a/48014629
tagged with: data-analysis
type: Question
tagged with: pandas
has comment: http://stackoverflow.com/comment/82996779
linked to: http://stackoverflow.com/q/22923775
tagged with: python
has comment: http://stackoverflow.com/comment/82990257
has title: Find difference between dates pandas using loc function
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/48014629
has body: I have this dataframe open high low close volume TimeStamp 2017-12-22 13:15:00 12935.00 13200.00 12508.71 12514.91 244.728611 2017-12-22 13:30:00 12514.91 12999.99 12508.71 12666.34 150.457869 2017-12-22 13:45:00 12666.33 12899.97 12094.00 12094.00 198.680014 2017-12-22 14:00:00 12094.01 12354.99 11150.00 11150.00 256.812634 2017-12-22 14:15:00 11150.01 12510.00 10400.00 12276.33 262.217127 I want to know if every rows have exactly 15 minutes diference in time So I build a new column with a shift of the first columns open high low close volume \ TimeStamp 2017-12-20 13:30:00 17503.98 17600.00 17100.57 17119.89 312.773644 2017-12-20 13:45:00 17119.89 17372.98 17049.00 17170.00 322.953671 2017-12-20 14:00:00 17170.00 17573.00 17170.00 17395.74 236.085829 2017-12-20 14:15:00 17395.74 17398.00 17200.01 17280.00 220.467382 2017-12-20 14:30:00 17280.00 17313.94 17150.00 17256.05 222.760598 new_time TimeStamp 2017-12-20 13:30:00 2017-12-20 13:45:00 2017-12-20 13:45:00 2017-12-20 14:00:00 2017-12-20 14:00:00 2017-12-20 14:15:00 2017-12-20 14:15:00 2017-12-20 14:30:00 2017-12-20 14:30:00 2017-12-20 14:45:00 Now I want to locate every row that don't respect the 15minutes diference rule so I did dfh.loc[(dfh['new_time'].to_pydatetime()-dfh.index.to_pydatetime())&gt;datetime.timedelta(0, 900)] I get this error, Traceback (most recent call last): File "&lt;pyshell#252&gt;", line 1, in &lt;module&gt; dfh.loc[(dfh['new_time'].to_pydatetime()-dfh.index.to_pydatetime())&gt;datetime.timedelta(0, 900)] File "C:\Users\Araujo\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\generic.py", line 3614, in __getattr__ return object.__getattribute__(self, name) AttributeError: 'Series' object has no attribute 'to_pydatetime' Is there any way of do this? EDIT: Shift just works with periodic, there is any way of do this with non periodic?
tagged with: dataframe
has comment: http://stackoverflow.com/comment/82989312

http://stackoverflow.com/comment/82949768
comment on: http://stackoverflow.com/q/47913994
score: 0
type: Comment
type: QuestionComment
has text: Sorry for not clarifying that... I'm looking for horizontal padding to move only the label itself, not the tick.

http://stackoverflow.com/q/47940850
downvote count: 0
score: 1
has title: Multiple incrementing conditional clauses in pandas
accepted answer: http://stackoverflow.com/a/47940883
type: Question
has answer: http://stackoverflow.com/a/47940883
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/47941466
upvote count: 1
has body: I have a dataframe called raw_df. I want the rows in which the first column have E01, E02, ... E14. How can I write a list comprehension (or another way) that can produce this, without typing it out manually. row_data = raw_df.loc[ (raw_df.col0=='E01') | (raw_df.col0=='E02') | (raw_df.col0=='E03') | (raw_df.col0=='E04') | (raw_df.col0=='E05') | (raw_df.col0=='E06') | (raw_df.col0=='E07') | (raw_df.col0=='E08') | (raw_df.col0=='E09') | (raw_df.col0=='E10') | (raw_df.col0=='E11') | (raw_df.col0=='E12') | (raw_df.col0=='E13') | (raw_df.col0=='E14') ] I know it can be done with eval making a string list comprehension, but I understand that it's dangerous &amp; should not be used. Similarly, setattr only works for xx.yy=z, but not xx.yy==z
favorite count: 0
possible better answer: http://stackoverflow.com/a/47941466
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/47919506
score: 15
has comment: http://stackoverflow.com/comment/82807078
has comment: http://stackoverflow.com/comment/82807244
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47919045
answers question: http://stackoverflow.com/q/47919045
has comment: http://stackoverflow.com/comment/82807315
type: Answer
upvote count: 15
has body: You can use first read_csv with parameter parse_dates for create datetimes from column date and time and then dt.round for round datetimes: import pandas as pd temp=u"""date,time,lon,lat,heading 2017-06-25,00:31:53.993000,48.1254,17.1458,a 2017-06-25,00:32:31.224000,48.1254,17.1458,a 2017-06-25,00:33:11.223000,48.1254,17.1458,a 2017-06-25,00:33:53.876000,48.1254,17.1458,a 2017-06-25,00:34:31.219000,48.1254,17.1458,a 2017-06-25,00:35:12.634000,48.1254,17.1458,a""" #after testing replace 'pd.compat.StringIO(temp)' to 'filename.csv' df = pd.read_csv(pd.compat.StringIO(temp), parse_dates={'timestamp':['date','time']}) print (df) timestamp lon lat heading 0 2017-06-25 00:31:53.993 48.1254 17.1458 a 1 2017-06-25 00:32:31.224 48.1254 17.1458 a 2 2017-06-25 00:33:11.223 48.1254 17.1458 a 3 2017-06-25 00:33:53.876 48.1254 17.1458 a 4 2017-06-25 00:34:31.219 48.1254 17.1458 a 5 2017-06-25 00:35:12.634 48.1254 17.1458 a print (df.dtypes) timestamp datetime64[ns] lon float64 lat float64 heading object dtype: object df['timestamp'] = df['timestamp'].dt.round('1s') print (df) timestamp lon lat heading 0 2017-06-25 00:31:54 48.1254 17.1458 a 1 2017-06-25 00:32:31 48.1254 17.1458 a 2 2017-06-25 00:33:11 48.1254 17.1458 a 3 2017-06-25 00:33:54 48.1254 17.1458 a 4 2017-06-25 00:34:31 48.1254 17.1458 a 5 2017-06-25 00:35:13 48.1254 17.1458 a EDIT: If you want set column with datetimes to index also: import pandas as pd temp=u"""date,time,lon,lat,heading 2017-06-25,00:31:53.993000,48.1254,17.1458,a 2017-06-25,00:32:31.224000,48.1254,17.1458,a 2017-06-25,00:33:11.223000,48.1254,17.1458,a 2017-06-25,00:33:53.876000,48.1254,17.1458,a 2017-06-25,00:34:31.219000,48.1254,17.1458,a 2017-06-25,00:35:12.634000,48.1254,17.1458,a""" #after testing replace 'pd.compat.StringIO(temp)' to 'filename.csv' df = pd.read_csv(pd.compat.StringIO(temp), parse_dates={'timestamp':['date','time']}, index_col=['timestamp']) print (df) lon lat heading timestamp 2017-06-25 00:31:53.993 48.1254 17.1458 a 2017-06-25…
downvote count: 0
has comment: http://stackoverflow.com/comment/82807209
has comment: http://stackoverflow.com/comment/82807301
has comment: http://stackoverflow.com/comment/82831160
has comment: http://stackoverflow.com/comment/82807111

http://stackoverflow.com/comment/82797320
comment on: http://stackoverflow.com/q/47914234
type: Comment
type: QuestionComment
has text: @srig, it was contrived data I made up. Ultimately was just for example purpose
score: 0

http://stackoverflow.com/comment/82776755
comment on: http://stackoverflow.com/a/47904653
score: 0
has text: @StefanPochmann Gosh, that does qualify as unreadable. Transposing first looks like a good idea btw.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47970430
downvote count: 0
has comment: http://stackoverflow.com/comment/82910416
has comment: http://stackoverflow.com/comment/82913012
has comment: http://stackoverflow.com/comment/82910199
has comment: http://stackoverflow.com/comment/82910956
tagged with: pandas
has comment: http://stackoverflow.com/comment/82916314
has comment: http://stackoverflow.com/comment/82911184
favorite count: 0
score: 2
has comment: http://stackoverflow.com/comment/82910773
has comment: http://stackoverflow.com/comment/82910205
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82910298
has comment: http://stackoverflow.com/comment/82916338
has title: Columns that sums the last x instances of value y to another column
has body: I have a dataset that looks like the following. The "HomeForm" column is what I'm trying to create and fill with values, i.e. the output. HomeTeam AwayTeam FTHG FTAG HomeForm Date 9 0 12 1 0 9 2 3 0 0 9 4 13 1 0 9 8 5 0 3 9 10 16 4 1 9 14 19 0 3 9 17 7 1 4 8 1 9 0 4 8 18 11 1 2 7 6 15 3 1 What I'm trying to do is to create another column called "HomeForm" that has, say, the sum of goals scored by the Home team in each of the last 6 matches. Bear in mind that the team can appear either in the "HomeTeam" column or in the "AwayTeam" column. What would be the best way to achieve this using python? Thanks.
tagged with: python
has comment: http://stackoverflow.com/comment/82910796
type: Question
has comment: http://stackoverflow.com/comment/82910868

sorting
tags question: http://stackoverflow.com/q/47985433
tags question: http://stackoverflow.com/q/47886931
tags question: http://stackoverflow.com/q/47929216
tags question: http://stackoverflow.com/q/47913824
tags question: http://stackoverflow.com/q/47945163
tags question: http://stackoverflow.com/q/47878044
tags question: http://stackoverflow.com/q/47913215
tags question: http://stackoverflow.com/q/47959217
tags question: http://stackoverflow.com/q/47889916
tags question: http://stackoverflow.com/q/47914274
type: Tag
tags question: http://stackoverflow.com/q/48005035
tags question: http://stackoverflow.com/q/47987412
tags question: http://stackoverflow.com/q/47865128
tags question: http://stackoverflow.com/q/47914234
tags question: http://stackoverflow.com/q/47995001
tags question: http://stackoverflow.com/q/47911773
tags question: http://stackoverflow.com/q/47913881
tags question: http://stackoverflow.com/q/47960190
tag name: sorting
tags question: http://stackoverflow.com/q/47938945
tags question: http://stackoverflow.com/q/48003589
tags question: http://stackoverflow.com/q/47983699
tags question: http://stackoverflow.com/q/47944137
tags question: http://stackoverflow.com/q/47882514
tags question: http://stackoverflow.com/q/47920845
tags question: http://stackoverflow.com/q/47970707
tags question: http://stackoverflow.com/q/48009133
tags question: http://stackoverflow.com/q/47993418

http://stackoverflow.com/q/47945077
has comment: http://stackoverflow.com/comment/82860105
has comment: http://stackoverflow.com/comment/102811984
type: UnansweredQuestion
has body: In attempting to run the following in PyCharm 2017.3.1: with open('../data/UrbanSound8K/retrained_graph.pb', 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) tf.import_graph_def(graph_def, name='') I receive the following: /anaconda/bin/python3 /Users/PycharmProjects/UrbanSound/src/recognize_sound.py Traceback (most recent call last): File "/Users/PycharmProjects/UrbanSound/src/recognize_sound.py", line 12, in &lt;module&gt; graph_def = tf.GraphDef() AttributeError: module 'tensorflow' has no attribute 'GraphDef' Here is some environment information: (tensorflow) $ python3 -c 'import tensorflow as tf; print(tf.__version__)' 1.4.0 (tensorflow) $ python -V Python 3.6.2 Thank you in advance for your help.
has title: AttributeError: module 'tensorflow' has no attribute 'GraphDef'
has answer: http://stackoverflow.com/a/61717647
downvote count: 0
has answer: http://stackoverflow.com/a/58217896
has comment: http://stackoverflow.com/comment/82860109
favorite count: 0
type: Question
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/97044308
score: 4
has answer: http://stackoverflow.com/a/61643025
answer count: 3
tagged with: tensorflow
upvote count: 4

http://stackoverflow.com/comment/82930506
comment on: http://stackoverflow.com/a/47980478
type: AnswerComment
score: 0
has text: needed to use regular template folder and your advice: path('reset/done', auth_views.password_reset_done, {'template_name': 'password_reset_done.html'}, name='password_reset_done'), It works now! Thank you!
type: Comment

http://stackoverflow.com/a/47894549
has body: You'll want to do something like this: class Person(Model): name = TextField() class Follower(Model): from_person = ForeignKeyField(Person, related_name='followers') to_person = ForeignKeyField(Person, related_name='followed_by')
type: Answer
answers question: http://stackoverflow.com/q/47880166
upvote count: 1
score: 1
downvote count: 0

http://stackoverflow.com/comment/82945103
comment on: http://stackoverflow.com/a/47976660
has text: I got it! But I thought regular explessions are slow by themselves and always avoided to use them if it is possible. But now I see I was wrong :)
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47882916
tagged with: shell
has answer: http://stackoverflow.com/a/47883064
favorite count: 0
has comment: http://stackoverflow.com/comment/82731724
answer count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/82732974
score: 10
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47883104
has body: I'm developing a set of script in python3, as shebang I use this: #!/usr/bin/env python3 Everything goes ok, but in some virtual machines where are executed the name of interpreter is python3.5. I will like to be able to execute my scripts in both enviroment but I can't change the filesystem of virtual machine (so I discard solutions like make a link from python3.5 to python3 ) I look at man of env but I don't find any way to specify a searching pattern or something like that. I try to set an alias at begining of my sessions pointing to right python interpreter but env don't use it. My unique solution is call my scripts saying which interpreter must use but is very anoying: python3.5 myscript.py Any idea is welcome!, thanks!
has comment: http://stackoverflow.com/comment/82731650
has comment: http://stackoverflow.com/comment/82735592
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47883104
has answer: http://stackoverflow.com/a/47886254
upvote count: 10
tagged with: shebang
type: Question
has title: How to make the Shebang be able to choose the correct Python interpreter between python3 and python3.5
tagged with: bash
accepted answer: http://stackoverflow.com/a/47886254
downvote count: 0

http://stackoverflow.com/q/47979966
has comment: http://stackoverflow.com/comment/83570355
tagged with: travis-ci
has title: Python Travis-CI: Importing main code in test code
tagged with: python
type: AnsweredQuestion
has body: I am writing a simple package in python. In the root directory, my structure currently is, my_package init.py main_code.py tests init.py test_main_code.py I want to import all functions from main_code.py in test_main_code.py. To achieve this, I did import sys import os sys.path.append(os.path.dirname(os.path.realpath(__file__)) + '\..' + '\my_package') from main_code import * This runs smoothly on my system. But when I push the code to github and tests are run on travis-ci, all tests fail and return NameError. It says given function name not defined. How do I make sure that tests run on travis-ci as well ?
accepted answer: http://stackoverflow.com/a/48292561
tagged with: python-unittest
type: Question
has answer: http://stackoverflow.com/a/48292561
score: 0
answer count: 1

http://stackoverflow.com/comment/82947591
comment on: http://stackoverflow.com/a/47919625
type: AnswerComment
has text: @ImdadulChoudhury I don't know what's wrong on your side, the output is what I pasted above using Python 3, and is exactly what you posted with the addition of `sequenc`, which I posted above. Both versions work.
score: 0
type: Comment

http://stackoverflow.com/a/52270893
has comment: http://stackoverflow.com/comment/110438853
has body: Not impossible, but not easy. First of all, you need to authenticate the user or to find him in LDAP. Example: user = authenticate( username=request.user.username, password=request.POST['password'] ) Now, the user has some properties that the request.user object has not, like ldap_user. This property can be used to modify the password, for example: # remember to add: import ldap.modlist as modlist pwd = "new password" ldif = modlist.modifyModlist( {'userpassword': user.ldap_user.attrs['userpassword']}, {'userpassword': [pwd.encode()]} ) user.ldap_user.connection.modify_s(user.ldap_user.dn, ldif) And that's it.
answers question: http://stackoverflow.com/q/47994698
type: Answer
has comment: http://stackoverflow.com/comment/110478996
score: 0

http://stackoverflow.com/comment/82838376
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47934461
type: Comment
has text: You need an extra set of parens or brackets in your `join` code; `join` takes a single iterable, not varargs. Either `'\n'.join(['G0 F' + self.options.travel_speed, 'G0 Z5', something_else])` (temporary `list`) or `'\n'.join(('G0 F' + self.options.travel_speed, 'G0 Z5', something_else))` (temporary `tuple`) would work.

http://stackoverflow.com/comment/82830556
has text: Some people may find this question somewhat, "dumb". If you checked the Python docs a little bit you may have found the accepted answer.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47930827
score: 0

http://stackoverflow.com/q/47982484
has body: import time import os clear = lambda: os.system('cls') clear() print('Movement Computer') print('') distance = float(input('Distance (km): ')) currVelocity = float(input('Velocity (km/h): ')) acceleration = float(input('Acceleration (km/h^2): ')) timeLeap = float(input('Time leap (h): ')) path = '' gap = '' travel = '' travelled = 0 multiplier = 1 loop = 0 for x in range(0, 100): path = path + '=' for y in range(0, 50): gap = gap + ' ' eachCube = distance / 100 while True: clear() print('eachCube: ' + str(eachCube)) print ('Travelled / eachCube: ' + str(travelled / eachCube)) print ('eachCube * multiplier: ' + str(eachCube * multiplier)) print ('multiplier: ' + str(multiplier)) print('') print(gap + ' Space') print(' ' + path) print(travel + '^') print('') print('Current velocity : ' + str(currVelocity)) print('Distance traveled : ' + str(travelled) + '/' + str(distance)) print('Time: ' + str(loop)) if travelled &gt;= distance: print('') print('Journey complete.') break time.sleep(timeLeap) loop += 1 currVelocity += acceleration * timeLeap travelled += currVelocity * timeLeap if travelled &gt;= eachCube * multiplier: for z in range(0, int(int(travelled / eachCube) / loop)): travel = travel + ' ' multiplier = loop I've been killing some time making this object movement visualizer.. Everything works ok when Acceleration is set 0 but when I change it the arrow (pointer) gets all messed up. Could someone help me? Also I do know that the arrow can go off the chart (couldn't fix that either) There's probably something wrong with the code that makes the pointer (arrow) move: if travelled &gt;= eachCube * multiplier: for z in range(0, int(int(travelled / eachCube) / loop)): travel = travel + ' ' multiplier = loop where eachCube = distance / 100 and travelled is the distance the object has already moved.
tagged with: math
has comment: http://stackoverflow.com/comment/82938487
has comment: http://stackoverflow.com/comment/82937543
downvote count: 1
has title: Movement visualizer (travel time calculator) issues
type: Question
has comment: http://stackoverflow.com/comment/82938432
has comment: http://stackoverflow.com/comment/82938192
has comment: http://stackoverflow.com/comment/82938128
has comment: http://stackoverflow.com/comment/82937533
score: 0
has comment: http://stackoverflow.com/comment/82938417
tagged with: calculator
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82938082
answer count: 0
has comment: http://stackoverflow.com/comment/82938444
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82938331
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82935562

http://stackoverflow.com/comment/82894082
type: QuestionComment
has text: instead of using `chunk_space(chunk)` inside `"".join()` you could use space instead of empty string in `" ".join()` ( `" here put space ".join()` )
score: 0
comment on: http://stackoverflow.com/q/47959327
type: Comment

http://stackoverflow.com/comment/82878472
score: 1
has text: I'd recommend `i = iter(it)` and then `zip(i, i)`, it's a lot cleaner. Well done though, I like your answer.
comment on: http://stackoverflow.com/a/47954502
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/82697736
type: QuestionComment
comment on: http://stackoverflow.com/q/47861325
score: 0
has text: Yes brilliant. We can save/read float values using the tiff image file type efficiently, and it provides a reasonable compression of the file. If you turn it to an answer I will mark it.
type: Comment

http://stackoverflow.com/a/47901993
answers question: http://stackoverflow.com/q/47892254
score: 5
has body: You are missing BR2_PACKAGE_PYTHON_HASHLIB option. Perform following actions: enebale this option via make menuconfig remove your target Python rm -fr output/build/python-2.7* invoke make to rebuild Python with hashlib module
upvote count: 5
type: Answer
downvote count: 0

http://stackoverflow.com/comment/82719851
comment on: http://stackoverflow.com/q/47874060
score: 0
has text: @ImportanceOfBeingErnest i tried `plt.tight_layout()` but i did not get satisfying adjusments. i tried `plt.subplots_adjust(top=1.5, bottom=0.18, left=1, right=1, hspace=0.4, wspace=0.7)` and this worked but finding the right configuration is beginning to be a real challenge
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82889189
score: 0
type: QuestionComment
type: Comment
has text: but that's not the error. i'm getting error when i'm trying to insert 'X' the first time itself
comment on: http://stackoverflow.com/q/47959971

http://stackoverflow.com/q/47995898
has answer: http://stackoverflow.com/a/70556339
possible better answer: http://stackoverflow.com/a/47996595
type: Question
has answer: http://stackoverflow.com/a/47996083
downvote count: 0
tagged with: dataframe
has title: Create random.randint with condition in a group by?
tagged with: pandas
has answer: http://stackoverflow.com/a/47996084
answer count: 4
favorite count: 0
has body: I have a column called: cars and want to create another called persons using random.randint() which i have: dat['persons']=np.random.randint(1,5,len(dat)) This is so I can put the number of persons who use these but I'd like to know how to put a condition so in the suv category will be generated only numbers from 4 to 9 for example. cars | persons suv 4 sedan 2 truck 2 suv 1 suv 5
accepted answer: http://stackoverflow.com/a/47996083
upvote count: 2
tagged with: python
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/47996595

http://stackoverflow.com/a/47932706
score: 0
answers question: http://stackoverflow.com/q/47932455
type: Answer
has comment: http://stackoverflow.com/comment/82861871
has comment: http://stackoverflow.com/comment/82846658
has body: You need to provide a date when constructing the datetime. You could get the time from your input and the date from datetime.now() and combine both. bustime = datetime.datetime.strptime(m2, "%I:%M").time() todaydate = datetime.datetime.now().date() bustime = datetime.datetime.combine(todaydate, bustime)
has comment: http://stackoverflow.com/comment/82836785
has comment: http://stackoverflow.com/comment/82873267

http://stackoverflow.com/comment/82889136
comment on: http://stackoverflow.com/a/47959073
has text: Thanks. How can this solution be scaled to multiple "Name" IDs (e.g. "B", "C", etc.) with different range of Year values?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/47888240
has comment: http://stackoverflow.com/comment/82747791
answers question: http://stackoverflow.com/q/47887603
has comment: http://stackoverflow.com/comment/82747182
has comment: http://stackoverflow.com/comment/82748500
has comment: http://stackoverflow.com/comment/82748728
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82766505
has comment: http://stackoverflow.com/comment/82747405
type: Answer
has body: I think you can return tuples from get_precip, append them to list and use DataFrame constructor: def get_precip(gooddate): urlstart = 'http://api.wunderground.com/api/API_KEY/history_' urlend = '/q/Switzerland/Zurich.json' url = urlstart + str(gooddate) + urlend data = requests.get(url).json() for summary in data['history']['dailysummary']: return (gooddate,summary['date']['year'],summary['date']['mon'],summary['date']['mday'],summary['precipm'], summary['maxtempm'], summary['meantempm'],summary['mintempm']) if __name__ == "__main__": from datetime import date from dateutil.rrule import rrule, DAILY a = date(2013, 1, 1) b = date(2013, 12, 31) L = [] for dt in rrule(DAILY, dtstart=a, until=b): tup = get_precip(dt.strftime("%Y%m%d")) L.append(tup) what is same as: L = [get_precip(dt.strftime("%Y%m%d")) for dt in rrule(DAILY, dtstart=a, until=b)] cols = ['date','date.year','date.mon','date.mday','precipm','maxtempm', 'meantempm','mintempm'] df = pd.DataFrame(L, columns=cols) print (df.head()) date date.year date.mon date.mday precipm maxtempm meantempm mintempm 0 20130101 2013 01 01 0.0 7 2 -2 1 20130102 2013 01 02 0.0 5 2 -3 2 20130103 2013 01 03 0.0 4 0 -3 3 20130104 2013 01 04 0.0 7 5 3 df.to_csv('/home/user/Desktop/2013_weather.csv', index=False)
accepted answer of: http://stackoverflow.com/q/47887603
score: 1
has comment: http://stackoverflow.com/comment/82747305

http://stackoverflow.com/comment/82952429
comment on: http://stackoverflow.com/a/47990201
has text: The `u` part is for unicode string, but you can replace all brackets with `string.replace` method. `u'Platform Power( W)'.replace("(","").replace(")","")` will return `u"Platform Power W"` the quotes are also represents string type. I hope this will help you, if I understand your question correctly.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/83165568
type: QuestionComment
comment on: http://stackoverflow.com/q/47905056
has text: @georgexsh the remote script uses a variable that is defined in ~/.profile I realise that when I ssh to the remote server, the ./.profile is not the one being used hence why that variable is different. So i am wondering what is the best way to ssh to remote, source ~/.profile and excute the bash script
score: 0
type: Comment

http://stackoverflow.com/comment/82859407
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47944787
has text: According to Python documentation, it should be opened with `newline=''`. https://docs.python.org/3/library/csv.html
type: AnswerComment

http://stackoverflow.com/a/47882767
answers question: http://stackoverflow.com/q/47882565
has comment: http://stackoverflow.com/comment/82734013
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82731663
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/82734752
type: Answer
has body: Update 2 This code should produce the output that you're after. import csv import gzip import re with gzip.open('file.txt.gz', mode='rt') as f, \ open('newfile.gz', 'w') as final: writer = csv.writer(final, delimiter=' ') reader = csv.reader(f, delimiter='\t') _ = next(reader) # skip header row for row in reader: writer.writerow(re.split(r'_|:|/', row[0])) Update Open the gzip file in text mode because str objects are required by the CSV module in Python 3. f = gzip.open('file.txt.gz', 'rt') Also specify the delimiter when creating the csv.reader. original_l = csv.reader(original, delimiter='\t') This will get you past the first hurdle. Now you need to explain what the data is, which columns you wish to extract, and what the output should look like. Original answer follows... One obvious problem is that the output file is constantly being overwritten by the next row of input. This is because the output file is opened in (over)write mode (`'w`` ) once per row. It would be better to open the output file once outside of the loop. Also, the CSV file delimiter is not specified when creating the reader. You said that the file is tab delimited so specify that: original_l = csv.reader(original, delimiter='\t') On the other hand, your code attempts to split each row using other delimiters, however, the rows coming from the csv.reader are represented as a list, not a string as the re.split() code would require. Another problem is that the output file is not zipped as the name suggests.
score: 2
has comment: http://stackoverflow.com/comment/82733210
has comment: http://stackoverflow.com/comment/82731498
accepted answer of: http://stackoverflow.com/q/47882565

http://stackoverflow.com/a/48009142
has comment: http://stackoverflow.com/comment/118617040
accepted answer of: http://stackoverflow.com/q/48001598
has comment: http://stackoverflow.com/comment/135131737
has comment: http://stackoverflow.com/comment/119517780
type: AcceptedAnswer
score: 531
has comment: http://stackoverflow.com/comment/136616926
upvote count: 532
type: Answer
has comment: http://stackoverflow.com/comment/138724570
has comment: http://stackoverflow.com/comment/119883111
has comment: http://stackoverflow.com/comment/121227664
has comment: http://stackoverflow.com/comment/119951810
has comment: http://stackoverflow.com/comment/104842287
downvote count: 1
has comment: http://stackoverflow.com/comment/108268683
has comment: http://stackoverflow.com/comment/111092137
answers question: http://stackoverflow.com/q/48001598
has body: In PyTorch, for every mini-batch during the training phase, we typically want to explicitly set the gradients to zero before starting to do backpropagation (i.e., updating the Weights and biases) because PyTorch accumulates the gradients on subsequent backward passes. This accumulating behavior is convenient while training RNNs or when we want to compute the gradient of the loss summed over multiple mini-batches. So, the default action has been set to accumulate (i.e. sum) the gradients on every loss.backward() call. Because of this, when you start your training loop, ideally you should zero out the gradients so that you do the parameter update correctly. Otherwise, the gradient would be a combination of the old gradient, which you have already used to update your model parameters and the newly-computed gradient. It would therefore point in some other direction than the intended direction towards the minimum (or maximum, in case of maximization objectives). Here is a simple example: import torch from torch.autograd import Variable import torch.optim as optim def linear_model(x, W, b): return torch.matmul(x, W) + b data, targets = ... W = Variable(torch.randn(4, 3), requires_grad=True) b = Variable(torch.randn(3), requires_grad=True) optimizer = optim.Adam([W, b]) for sample, target in zip(data, targets): # clear out the gradients of all Variables # in this optimizer (i.e. W, b) optimizer.zero_grad() output = linear_model(sample, W, b) loss = (output - target) ** 2 loss.backward() optimizer.step() Alternatively, if you're doing a vanilla gradient descent, then: W = Variable(torch.randn(4, 3), requires_grad=True) b = Variable(torch.randn(3), requires_grad=True) for sample, target in zip(data, targets): # clear out the gradients of Variables # (i.e. W, b) W.grad.data.zero_() b.grad.data.zero_() output = linear_model(sample, W, b) loss = (output - target) ** 2 loss.backward() W -= learning_rate * W.grad.data b -= learning_rate * b.grad.data Note: The accumulation (i.e.,…
has comment: http://stackoverflow.com/comment/124215762

http://stackoverflow.com/a/47943456
score: 1
answers question: http://stackoverflow.com/q/47943319
upvote count: 1
has comment: http://stackoverflow.com/comment/82856461
type: Answer
has body: Python 3.5+ K = [{**d, 'S': [2 , 124, 123 , 3532, 35]} if d['nodeid'] == 106 else d for d in K]
downvote count: 0

http://stackoverflow.com/q/47993882
answer count: 0
linked to: http://stackoverflow.com/q/29992153
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82956447
tagged with: python
type: Question
tagged with: gdb-python
has comment: http://stackoverflow.com/comment/82956672
tagged with: gdb
has body: I want to pass command line arguments to sys.args (to a gdb python script). I saw this solution but would like pass arbitrary number of arguments. Like: gdb --batch -x myScript.py 2 3 4 12 23 .. myScript.py: import gdb import sys print(sys.argv[1:]) Is is possible?
has comment: http://stackoverflow.com/comment/82959105
score: 0
has title: How to pass variables to sys.args? (python gdb script)
has comment: http://stackoverflow.com/comment/82956637

http://stackoverflow.com/a/76630682
score: 0
answers question: http://stackoverflow.com/q/48010160
type: Answer
has body: You are right: _ip is an instance of SysUtil, however there is nothing special about that first self parameter. The behaviour of _ip does not depend on it being defined as an attribute of a ClientSetup instance, so lets consider this example: >>> class A: ... def f(self): ... return ... >>> a = A() >>> type(A.f) function >>> type(a.f) method A.f is still a function until A is instantiated! We call this bounding. Definition: a bound method in Python is a function that has an object associated with it. (The concept of unbound method has been deprecated in Python 3.0). That's it. In the above example, there is no conceptual difference between A.f and a generic function in a "non-class scope" def g(self): return i.e. they can be called in the same way. g and A.f are just a function that accept an instance of A as first positional argument. When you instantiate A into a, a.f is a method. In a method (bound to an instance) the first parameter self (may be named in another way) is implicitly passed as the instance itself. I.e. when calling a.f() self gets the value of a. A simple function such A.f (or g) does not behave in such way, the first parameter is not implicit, since the function is not bound to any instance. However you can pass the instance explicitly, as you would do with a parameter in any normal function, i.e. A.f(a). So... A.f(a) is the same as a.f(). In your case A is SysUtil. The line SysUtil.validateIP(self._ip, '127.0.0.1') could be replaced with self._ip.validateIP('127.0.0.1'). The above line-replacement is also recommended in terms of design style, as @RomanPerekhrest pointed out. I suggest you to take a look at this docs.python.org article to a deeper insight at how Python classes work. When would this be useful This design choice would be useful when wanting to specify you want that very implementation to be executed. We may need this when the class is subclassed. In our example: >>> class B(A): ... def f(self): # May depend on `A.f`. ... print('From…

http://stackoverflow.com/q/47995901
upvote count: 4
tagged with: graph-algorithm
answer count: 1
downvote count: 0
tagged with: bellman-ford
favorite count: 0
has body: I'm trying to adapt a Bellman-Ford graph algorithm in Python to my needs. I've worked out the parsing part from a json file. Here is the Bellman Ford code I found on github: https://github.com/rosshochwert/arbitrage/blob/master/arbitrage.py And here is my code I adapted from it: import math, urllib2, json, re def download(): graph = {} page = urllib2.urlopen("https://bittrex.com/api/v1.1/public/getmarketsummaries") jsrates = json.loads(page.read()) result_list = jsrates["result"] for result_index, result in enumerate(result_list): ask = result["Ask"] market = result["MarketName"] pattern = re.compile("([A-Z0-9]*)-([A-Z0-9]*)") matches = pattern.match(market) if (float(ask != 0)): conversion_rate = -math.log(float(ask)) if matches: from_rate = matches.group(1).encode('ascii','ignore') to_rate = matches.group(2).encode('ascii','ignore') if from_rate != to_rate: if from_rate not in graph: graph[from_rate] = {} graph[from_rate][to_rate] = float(conversion_rate) return graph # Step 1: For each node prepare the destination and predecessor def initialize(graph, source): d = {} # Stands for destination p = {} # Stands for predecessor for node in graph: d[node] = float('Inf') # We start admiting that the rest of nodes are very very far p[node] = None d[source] = 0 # For the source we know how to reach return d, p def relax(node, neighbour, graph, d, p): # If the distance between the node and the neighbour is lower than the one I have now if d[neighbour] &gt; d[node] + graph[node][neighbour]: # Record this lower distance d[neighbour] = d[node] + graph[node][neighbour] p[neighbour] = node def retrace_negative_loop(p, start): arbitrageLoop = [start] next_node = start while True: next_node = p[next_node] if next_node not in arbitrageLoop: arbitrageLoop.append(next_node) else: arbitrageLoop.append(next_node) arbitrageLoop = arbitrageLoop[arbitrageLoop.index(next_node):] return arbitrageLoop def bellman_ford(graph, source): d, p = initialize(graph, source) for i in range(len(graph…
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48019848
has comment: http://stackoverflow.com/comment/82992658
type: Question
has title: Implementing Bellman-Ford in python
tagged with: algorithm
tagged with: math
score: 4
accepted answer: http://stackoverflow.com/a/48019848
has comment: http://stackoverflow.com/comment/82985020

http://stackoverflow.com/comment/82737357
type: Comment
type: QuestionComment
has text: Thanks @Chris_Rands just forgot about `remove()`, you are right
comment on: http://stackoverflow.com/q/47867145
score: 0

http://stackoverflow.com/comment/112869122
comment on: http://stackoverflow.com/a/47948784
score: 0
type: Comment
has text: @jTiKey i have tried this in django 1.7 and it's not callable, it's just a list. i belive this is a mistake
type: AnswerComment

http://stackoverflow.com/q/47948423
has body: I'm going through Problem 3 of the MIT lead python course, and I have an admittedly long drawn out script that feels like it's getting close. I need to print the longest substring of s in which the letters occur in alphabetical order. I'm able to pull out any characters that are in alphabetical order with regards to the character next to it. What I need to see is: Input : 'aezcbobobegghakl' needed output: 'beggh' my output: ['a', 'e', 'b', 'b', 'b', 'e', 'g', 'g', 'a', 'k'] My code: s = 'aezcbobobegghakl' a = 'abcdefghijklmnopqrstuvwxyz' len_a = len(a) len_s = len(s) number_list = [] letter_list = [] for i in range(len(s)): n = 0 letter = s[i+n] if letter in a: number_list.append(a.index(letter)) n += 1 print(number_list) for i in number_list: letter_list.append(a[i]) print(letter_list) index_list = [] for i in range(len(letter_list)): index_list.append(i) print(index_list) first_check = [] for i in range(len(letter_list)-1): while number_list[i] &lt;= number_list[i+1]: print(letter_list[i]) first_check.append(letter_list[i]) break print(first_check) I know after looking that there are much shorter and completely different ways to solve the problem, but for the sake of my understanding, is it even possible to finish this code to get the output I'm looking for? Or is this just a lost cause rabbit hole I've dug?
has answer: http://stackoverflow.com/a/47948504
has answer: http://stackoverflow.com/a/47948468
favorite count: 0
tagged with: python-3.x
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/47951817
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/47948843
score: 1
upvote count: 1
tagged with: loops
type: Question
has title: How to split a list based on whether the elements were next to each other in the list they came from?
accepted answer: http://stackoverflow.com/a/47948504
downvote count: 0
possible better answer: http://stackoverflow.com/a/47951817

http://stackoverflow.com/q/47993763
has comment: http://stackoverflow.com/comment/82955962
has comment: http://stackoverflow.com/comment/82955991
has comment: http://stackoverflow.com/comment/82960296
has body: Hello I have this dataframe: TimeStamp low high open close volume 0 1514331900 15699.54 15800.00 15699.55 15790.88 62.675508 1 1514331000 15651.57 15745.80 15662.01 15699.54 83.040542 2 1514330100 15661.00 15820.01 15820.01 15662.00 67.716571 3 1514329200 15780.00 15856.00 15780.01 15820.00 41.608696 4 1514328300 15780.00 15867.01 15789.98 15780.00 50.103055 5 1514327400 15719.00 15856.99 15856.99 15789.99 120.660673 I set timestamp as index df.set_index('TimeStamp') I get low high open close volume TimeStamp 1514331900 15699.54 15800.00 15699.55 15790.88 62.675508 1514331000 15651.57 15745.80 15662.01 15699.54 83.040542 1514330100 15661.00 15820.01 15820.01 15662.00 67.716571 1514329200 15780.00 15856.00 15780.01 15820.00 41.608696 1514328300 15780.00 15867.01 15789.98 15780.00 50.103055 Now I want to convert the timestamp to ISO human readable DateTime. So I use pandas library df.index = pd.to_datetime(df.index, unit='s') But I don't get the expected datetime, I get this: TimeStamp low high open close \ 1970-01-01 00:00:00 1514331900 15699.54 15800.00 15699.55 15790.88 1970-01-01 00:00:01 1514331000 15651.57 15745.80 15662.01 15699.54 1970-01-01 00:00:02 1514330100 15661.00 15820.01 15820.01 15662.00 1970-01-01 00:00:03 1514329200 15780.00 15856.00 15780.01 15820.00 1970-01-01 00:00:04 1514328300 15780.00 15867.01 15789.98 15780.00 It's not the correct form because If I do: &gt;&gt;&gt; pd.to_datetime(1514331900, unit='s') Timestamp('2017-12-26 23:45:00') I get the accurate date. What Am I doing wrong?
type: Question
has comment: http://stackoverflow.com/comment/82955813
has comment: http://stackoverflow.com/comment/82955921
tagged with: dataframe
score: 0
tagged with: pandas
answer count: 1
has title: Datetime unix to ISO Pandas
has comment: http://stackoverflow.com/comment/82956097
has comment: http://stackoverflow.com/comment/82964097
tagged with: data-analysis
type: UnansweredQuestion
tagged with: datetime
tagged with: python
has answer: http://stackoverflow.com/a/47997360

http://stackoverflow.com/comment/101424747
type: Comment
comment on: http://stackoverflow.com/a/47971072
score: 0
type: AnswerComment
has text: But what if you want to test multiple methods of different classes that work together? In that case you cant separate it that nicely. What would be your advice in such a case?

http://stackoverflow.com/q/47997425
favorite count: 0
has answer: http://stackoverflow.com/a/47997568
tagged with: while-loop
has body: I've already ruled out os.exit, sys.exit(), raise SystemExit(0), quit, and exit(). I want to completely stop once one of my multiple while conditions are fulfilled. while x: #do something #for loop #if a: #do something print "Game over" os.exit #elif b: #do something print "Game over" os.exit break while y: #(...same form as the previous one^) #get user input for the next turn #while 1 #... #while n When I play the game, and the game over message is printed on to the screen, it still asks for the user input despite being told to stop.
tagged with: python
has answer: http://stackoverflow.com/a/47997540
downvote count: 3
upvote count: 1
accepted answer: http://stackoverflow.com/a/47997568
type: Question
type: AnsweredQuestion
has title: How do I stop the code completely as soon as a certain thing is done?
score: -2
has comment: http://stackoverflow.com/comment/82963044
has comment: http://stackoverflow.com/comment/82963070
has comment: http://stackoverflow.com/comment/82963171
possible better answer: http://stackoverflow.com/a/47997507
has comment: http://stackoverflow.com/comment/82963118
has answer: http://stackoverflow.com/a/47997507
answer count: 3
has comment: http://stackoverflow.com/comment/82963129

http://stackoverflow.com/a/47936896
has comment: http://stackoverflow.com/comment/82843492
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/47936681
has comment: http://stackoverflow.com/comment/82843296
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82843749
has comment: http://stackoverflow.com/comment/82843195
answers question: http://stackoverflow.com/q/47936681
has body: You don't need to get "topping estimate" as the result. What you really want is to check whether each line starts with topping followed by 2 or fewer words, then estimate or estimates. This regex will help you: ^topping(\s\S+){0,2}\sestimates?\s*$ Match this against each line, or multiple lines if you turn on m. It will tell you whether the string satisfies the requirement.
type: Answer
has comment: http://stackoverflow.com/comment/82843540

http://stackoverflow.com/q/47930669
has comment: http://stackoverflow.com/comment/82831032
type: Question
answer count: 1
tagged with: variables
has title: How to know when a new object is created in Python on contrary to just assigning a variable to the same object
tagged with: pointers
has answer: http://stackoverflow.com/a/47930863
score: 0
has comment: http://stackoverflow.com/comment/82830449
has comment: http://stackoverflow.com/comment/82830394
tagged with: python
accepted answer: http://stackoverflow.com/a/47930863
has body: So this question is not a super concrete question but I can give some examples. I am very afraid of Python since you never know when a variable is pointing at a new object or just have two variables pointing at the same object. For example I am scared of assigning like this: def function(self): number = self.value return number In this case I don't want number to change if I change self.value. Also just copying lists like: list = [1,2,3] list2 = list In this case if I change list, list2 will also be changed which is not desirable. Why would I copy it if i don't want it to be a new variable! Anyway, I just wonder if anybody knows a safe method to create new variables in these cases or maybe has a complete explanation of when a new object is created and when two variables point at the same object. I want to code in peace and not worry about this all the time because my code is big and I can't sit and check which variables have changed and which have not after every calculation. The question is related to mutability and immutability so the link to the question: Immutable vs Mutable types, might be good but this is another way of asking the question which might be helpful for some. Also this is more focused on avoiding mutating.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82830060
linked to: http://stackoverflow.com/q/8056130
has comment: http://stackoverflow.com/comment/82831271

http://stackoverflow.com/comment/82785317
type: QuestionComment
has text: You can do `myList = '1,2,3 and 4'`... However, what do you mean by "If I print it the output"? Output of what???
comment on: http://stackoverflow.com/q/47908919
score: 1
type: Comment

http://stackoverflow.com/comment/82959042
score: 0
comment on: http://stackoverflow.com/q/47995144
has text: no it is not in the same machine, i have a PHP script that is in a server, and the Python script that is on a raspberry the goal is that i use the request.get function in the script python for the api.PHP script to send me the value of "state"
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82937534
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47984257
type: AnswerComment
has text: I need the descriptor because I need to access the attributes of the instance of MyClass (not in my code). I've added a line to clarify.

http://stackoverflow.com/q/48012341
has comment: http://stackoverflow.com/comment/82993422
type: UnansweredQuestion
score: -4
tagged with: random
type: Question
has comment: http://stackoverflow.com/comment/82993365
has body: I would like to create a pattern the contains uppercase letters and numbers, also random spacing in between as OI00 XKB or IT IEEW 88 ... etc I have started with this code it generate random code but the spacing is constant between as {}{}{}{} {}{}{} code def codeGen(): return "{}{}{}{} {}{}{}".format( random.choice(common.LETTERS), random.choice(common.LETTERS), random.choice(common.DIGITS), random.choice(common.DIGITS), random.choice(common.LETTERS), random.choice(common.LETTERS), random.choice(common.LETTERS)) how I can apply randomness on format Thanks, in advance
has comment: http://stackoverflow.com/comment/82993358
has answer: http://stackoverflow.com/a/48012744
favorite count: 0
tagged with: python
answer count: 1
has title: Random string generated with random spacing in between
downvote count: 4
upvote count: 0

http://stackoverflow.com/comment/82830531
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47912485
has text: The code you provided is not really complete so I could not run and check the output. os.system is strongly discouraged for executing command. Use [subprocess.Popen](https://docs.python.org/2/library/subprocess.html#popen-constructor) instead. Do you see your list score printed when you run new_image.py from command line? If so, you can use the subprocess.Popen constructor to capture this output and store it in a variable in task2.py.

http://stackoverflow.com/comment/82906233
comment on: http://stackoverflow.com/q/47968232
type: QuestionComment
has text: What differentiates it is the third parameter, the step, as described in the opening paragraph. It fails because the list on the right hand side of the statement does not contain the same number of items (3) as the slice it is replacing (2), which is what the text you've copied says is required. That's why they use it as an illustration for that description. It's unclear what you mean by *"why"*.
type: Comment
score: 2

http://stackoverflow.com/q/47964385
has comment: http://stackoverflow.com/comment/82913845
tagged with: hive
type: Question
has title: Connect to Hive and create tables using pandas
score: 3
has comment: http://stackoverflow.com/comment/82913365
has comment: http://stackoverflow.com/comment/82899521
tagged with: pandas
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82913293
favorite count: 0
has comment: http://stackoverflow.com/comment/82913330
has answer: http://stackoverflow.com/a/47972023
tagged with: python
has body: I have a pandas data frame in PYTHON. I want to create/load this data frame into a hive table. I know that we can create spark data frame from pandas data frame and create hive table. I would like to do this using pure python way not using pyspark. I have installed pyhive pyhs2 in my local python Using pyhive conn_1 = hive.Connection(host=hive_host, port=10000, username=username) I receive the following error: NotImplementedError: Wrong number of arguments for overloaded function 'Client_setAttr'. Possible C/C++ prototypes are: setAttr(saslwrapper::Client *,std::string const &amp;,std::string const &amp;) setAttr(saslwrapper::Client *,std::string const &amp;,uint32_t) Using pyhs2: conn_1 = pyhs2.connect(host='host', port=10000,authMechanism="NOSASL", user='hive', database='default') returns TTransportException: TSocket read 0 bytes How can I connect to hive and create hive tables using pandas Error for pyhive --------------------------------------------------------------------------- NotImplementedError Traceback (most recent call last) &lt;ipython-input-7-bf6a49c722d5&gt; in &lt;module&gt;() ----&gt; 1 conn_1 = hive.Connection(host=hive_host, port=10000, username=username) C:\Users\viru\AppData\Local\Continuum\Anaconda2\lib\site-packages\pyhive\hive.pyc in __init__(self, host, port, username, database, auth, configuration, kerberos_service_name, password, thrift_transport) 157 158 try: --&gt; 159 self._transport.open() 160 open_session_req = ttypes.TOpenSessionReq( 161 client_protocol=protocol_version, C:\Users\viru\AppData\Local\Continuum\Anaconda2\lib\site-packages\thrift_sasl\__init__.pyc in open(self) 72 type=TTransportException.NOT_OPEN, 73 message="Already open!") ---&gt; 74 self.sasl = self.sasl_client_factory() 75 76 ret, chosen_mech, initial_response = self.sasl.start(self.mechanism) C:\Users\viru\AppData\Local\Continuum\Anaconda2\lib\site-packages\pyhive\hive.pyc in sasl_factory() 134 def sasl_factory(): 135 sasl_client = sasl.Client() --&gt; 136 sasl_cli…
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47972023
upvote count: 3

http://stackoverflow.com/q/48011574
has comment: http://stackoverflow.com/comment/82992511
tagged with: index-error
tagged with: cross-validation
has comment: http://stackoverflow.com/comment/83235568
has comment: http://stackoverflow.com/comment/82992098
has comment: http://stackoverflow.com/comment/83094573
has comment: http://stackoverflow.com/comment/82992773
has comment: http://stackoverflow.com/comment/82991967
has body: I tried to compute a simple cross_val_score with a Logistic regression, but I don't understand why I get an error : "Too many indices for array" About the data frame, there are 11 input variables, all of them with dtype float64. There are 2 output variable, quality (int) and cat_quality (string) (which is a categorization of quality, with only two possible values : good / not_good) There are 1599 observations. Here is my code : def split_input_output(X): target = X'cat_quality' X = X.drop(['quality','cat_quality'], axis=1) #quality is a non numerical variable return X, target X, y = split_input_output(df.copy()) lr = LogisticRegression() cross_val_score(lr, X, y) Here is the error message : IndexErrorTraceback (most recent call last) &lt;ipython-input-107-f8517fdb5e22&gt; in &lt;module&gt;() 8 9 lr = LogisticRegression() ---&gt; 10 cross_val_score(lr, X, y) 11 12 #lr.fit(X, y) C:\Users\user\Anaconda2\lib\site-packages\sklearn\model_selection\_validation.pyc in cross_val_score(estimator, X, y, groups, scoring, cv, n_jobs, verbose, fit_params, pre_dispatch) 319 n_jobs=n_jobs, verbose=verbose, 320 fit_params=fit_params, --&gt; 321 pre_dispatch=pre_dispatch) 322 return cv_results['test_score'] 323 C:\Users\user\Anaconda2\lib\site-packages\sklearn\model_selection\_validation.pyc in cross_validate(estimator, X, y, groups, scoring, cv, n_jobs, verbose, fit_params, pre_dispatch, return_train_score) 193 fit_params, return_train_score=return_train_score, 194 return_times=True) --&gt; 195 for train, test in cv.split(X, y, groups)) 196 197 if return_train_score: C:\Users\user\Anaconda2\lib\site-packages\sklearn\externals\joblib\parallel.pyc in __call__(self, iterable) 777 # was dispatched. In particular this covers the edge 778 # case of Parallel used with an exhausted iterator. --&gt; 779 while self.dispatch_one_batch(iterator): 780 self._iterating = True 781 else: C:\Users\user\Anaconda2\lib\site-packages\sklearn\externals\joblib\parallel.pyc in dispatch_one_batch(self, i…
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/83142620
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83198016
tagged with: python
answer count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82993547
has title: python error : 'Too many indices for array' using cross_val_score from sklearn
has comment: http://stackoverflow.com/comment/83156988
type: Question
has comment: http://stackoverflow.com/comment/83201606

http://stackoverflow.com/comment/82989578
score: 1
type: AnswerComment
type: Comment
has text: FWIW, in Python 3 `math.ceil` returns an `int`.
comment on: http://stackoverflow.com/a/48009907

http://stackoverflow.com/q/48010462
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48010557
has answer: http://stackoverflow.com/a/48010585
upvote count: 4
has body: I have a list that looks like this: a=[1,2,3,4,5,2,3,1,2,3,4,5,1,5,5,3,2,1,3,1] I am looking for a way that every time it finds a 1, this element AND the next two elements are replaced by -999. The following code seems to work. b = a x = 2 #number of continuous elements to browse for n,i in enumerate(a): if i==1: for t in range(x): print n+t b[n+t]=-999 print b However, when a 1 is located at the end of the list I get: IndexError: list assignment index out of range Is there a better way to do it?
downvote count: 0
has answer: http://stackoverflow.com/a/48010826
favorite count: 0
type: Question
has title: Replace element and following elements in a list if condition met
answer count: 8
has answer: http://stackoverflow.com/a/48011357
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/48010539
tagged with: loops
has answer: http://stackoverflow.com/a/48010732
has answer: http://stackoverflow.com/a/48010885
has answer: http://stackoverflow.com/a/48011064
has comment: http://stackoverflow.com/comment/82989743

http://stackoverflow.com/a/68487238
downvote count: 0
score: 1
upvote count: 1
has body: Another way of getting good results would be image[np.where((image&gt;[0,0,0]).all(axis=2))] = [0,0,255]. Here, you change the non-black pixels to red.
answers question: http://stackoverflow.com/q/47939437
type: Answer

http://stackoverflow.com/a/47909711
score: 1
upvote count: 1
type: AcceptedAnswer
has body: Ok, the problem is effectively solved with a part of the answer from @Jean-François Fabre. I noticed that pstreams provide a way to read on pipe without blocking, so I reuse that code (found in the doc of the library): const redi::pstreams::pmode mode = redi::pstreams::pstdout|redi::pstreams::pstderr; redi::ipstream child(cmd, mode); char buf[1024]; std::streamsize n; bool finished[2] = { false, false }; while (!finished[0] || !finished[1]) { if (!finished[0]) { while ((n = child.err().readsome(buf, sizeof(buf))) &gt; 0) { std::string ret(buf, n); resErrors.append(QString::fromStdString(ret)); } if (child.eof()) { finished[0] = true; if (!finished[1]) child.clear(); } } if (!finished[1]) { while ((n = child.out().readsome(buf, sizeof(buf))) &gt; 0) { std::string out(buf, n); res.append(QString::fromStdString(out)); } if (child.eof()) { finished[1] = true; if (!finished[0]) child.clear(); } } } res = res.join("").split("\n"); resErrors = resErrors.join("").split("\n"); res.removeLast(); resErrors.removeLast(); With this, I have all outputs in my QStringLists!
type: Answer
accepted answer of: http://stackoverflow.com/q/47907555
answers question: http://stackoverflow.com/q/47907555
downvote count: 0

http://stackoverflow.com/comment/82680147
has text: Try 11{2}. 11+ will not work as regex by nature will find longest match.
score: 0
comment on: http://stackoverflow.com/q/47857863
type: QuestionComment
type: Comment

shell
tags question: http://stackoverflow.com/q/47982731
tags question: http://stackoverflow.com/q/47897402
tags question: http://stackoverflow.com/q/48001370
tags question: http://stackoverflow.com/q/47911289
tags question: http://stackoverflow.com/q/48008645
tags question: http://stackoverflow.com/q/47945110
tags question: http://stackoverflow.com/q/48001410
tags question: http://stackoverflow.com/q/47955588
tag name: shell
tags question: http://stackoverflow.com/q/47948120
tags question: http://stackoverflow.com/q/47992578
tags question: http://stackoverflow.com/q/48011531
tags question: http://stackoverflow.com/q/47967211
tags question: http://stackoverflow.com/q/47940360
tags question: http://stackoverflow.com/q/47862148
tags question: http://stackoverflow.com/q/47893138
type: Tag
tags question: http://stackoverflow.com/q/47882916
tags question: http://stackoverflow.com/q/47939713
tags question: http://stackoverflow.com/q/48004543
tags question: http://stackoverflow.com/q/48003276
tags question: http://stackoverflow.com/q/47994214
tags question: http://stackoverflow.com/q/47895454
tags question: http://stackoverflow.com/q/47974949
tags question: http://stackoverflow.com/q/47897270
tags question: http://stackoverflow.com/q/47934622

http://stackoverflow.com/a/47881744
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47881611
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/47881611
upvote count: 1
has body: No need to iterate the file twice. Just update the counts while you go through the lines:: lc, wc = 0, 0 with open('file.txt','r') as f: for line in f: lc += 1 wc += len(line.strip().split()) avg = wc / lc

http://stackoverflow.com/comment/82709937
comment on: http://stackoverflow.com/q/47871602
has text: There is some code on this Question: https://bitcoin.stackexchange.com/questions/25024/how-do-you-get-a-bitcoin-public-key-from-a-private-key, maybe you can better specify your question after looking at this (or already answer it).
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47895548
type: Answer
answers question: http://stackoverflow.com/q/47888605
has body: Note that this statement if random.randint(1, IRON_CHANCE) != 1: can be equal to one, and the next if statement can not be equal to one at the same time, because you are using 2 different numbers. Perhaps you want an else. We can not help further without code that is more complete and the complete trackback from the error. if random.randint(1, IRON_CHANCE) != 1: stone = c.create_rectangle(x2, y2, x2 + 50, y2 + 50, fill='dim gray') everything.append(stone) y2 += 50 else: ironStone = c.create_rectangle(x2, y2, x2 + 50, y2 + 50, fill='dim gray') ironRect = c.create_rectangle(x2 + 10, y2 + 10, x2 + 40, y2 + 40, fill='ivory') irons.append(ironRect) etc
score: 0

http://stackoverflow.com/q/47960757
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82890629
score: 1
has answer: http://stackoverflow.com/a/47960843
favorite count: 0
has body: I'm trying to recursively rename the files in a directory, so I wrote a python script to handle the renaming. So ideally, the script should be able to turn this Nicholass-MacBook-Air-2:RenameXtalTest nick$ ls RM01_03_000_0213_Proj1_Clon1_RC_0000RC000870_010_171222_01_03_02_E0_00_031_001_RAI.jpg RM01_03_000_0213_Proj1_Clon1_RC_0000RC000870_010_171222_07_07_01_E0_99_031_001_RAI.jpg rename.py into Nicholass-MacBook-Air-2:RenameXtalTest nick$ ls RC000870-C1_02-E0_00.jpg RC000870-G7_01-E0_99.jpg rename.py I can get rename.py to work on a single name in Python if it looks like this: #!/usr/bin/python oldname = 'RM01_03_000_0213_Proj1_Clon1_RC_0000RC000870_010_171222_01_03_02_E0_00_031_001_RAI.jpg' #manually set an old name rowdic = {"01" : "A", "02" : "B", "03" : "C", "04" : "D", "05" : "E", "06" : "F", "07" : "G", "08" : "H"} #dictionary to translate oldname char 59 to 61 coldic = {"01" : "1", "02" : "2", "03" : "3", "04" : "4", "05" : "5", "06" : "6", "07" : "7", "08" : "8", "09" : "9", "10" : "10", "11" : "11", "12" : "12"} #dictionary to translate oldname char 56 to 58 subwdic = {"01" : "1", "02" : "2", "03" : "3"} #dictionary to translate oldname char 62 to 64 newname = oldname[36:44]+"-"+rowdic[oldname[59:61]]+coldic[oldname[56:58]]+"_"+subwdic[oldname[62:64]]+"-"+oldname[65:70]+".jpg" #definition for how to shorten, rearrange, and swap out some parts of oldname print newname But as soon as I try to get the script to work on multiple files in Unix - it fails. Here's my script attempt at the aforementioned: #!/usr/bin/python import os rowdic = {"01" : "A", "02" : "B", "03" : "C", "04" : "D", "05" : "E", "06" : "F", "07" : "G", "08" : "H"} #dictionary to translate oldname char 59 to 61 coldic = {"01" : "1", "02" : "2", "03" : "3", "04" : "4", "05" : "5", "06" : "6", "07" : "7", "08" : "8", "09" : "9", "10" : "10", "11" : "11", "12" : "12"} #dictionary to translate oldname char 56 to 58 subwdic = {"01" : "1", "02" : "2", "03" : "3"} #dictionary to translate oldname cha…
type: Question
has comment: http://stackoverflow.com/comment/82890596
tagged with: python
tagged with: dictionary
tagged with: subprocess
upvote count: 2
accepted answer: http://stackoverflow.com/a/47960843
answer count: 1
downvote count: 1
tagged with: for-loop
has title: My python script, which recursively renames files, fails
tagged with: substring

http://stackoverflow.com/comment/82681357
type: Comment
has text: @Bert I am trying to read data from a .dat file tho.. Those 32 bits are from the film.. what you are saying is I am reading the wrong part ????
score: 0
comment on: http://stackoverflow.com/q/47857950
type: QuestionComment

http://stackoverflow.com/comment/82713067
type: Comment
comment on: http://stackoverflow.com/a/47859609
has text: yes! Now it is working...Actually as I mentioned earlier I am new to web scraping, I don't understand your without selenium version code fully.So, I started learning your code line by line. :-)
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82771788
comment on: http://stackoverflow.com/q/47902323
has text: @Divakar perhaps, OP can elaborate.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47918295
type: AnsweredQuestion
tagged with: mysql
tagged with: django
type: Question
accepted answer: http://stackoverflow.com/a/47918448
has title: Django DateTimeField date filter not working
linked to: http://stackoverflow.com/q/1317714
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/47918371
has comment: http://stackoverflow.com/comment/82804557
has answer: http://stackoverflow.com/a/47918371
has comment: http://stackoverflow.com/comment/82804530
has comment: http://stackoverflow.com/comment/82804452
has comment: http://stackoverflow.com/comment/82804501
has answer: http://stackoverflow.com/a/47918448
has comment: http://stackoverflow.com/comment/82804444
tagged with: python
has body: I have a DateTimeField named created_at in my model. I Would like to query the objects which are created today. From this question I have used the following query set, In [70]: today = datetime.datetime.today().date() In [72]: Business.objects.filter(created_at__date=today) Out[72]: &lt;QuerySet []&gt; It returns zero results. I have make sure that there is an entry in the database, which was created today. I know that I can also use Business.objects.filter(created_at__contains=today) But it yields results with a warning: django/db/backends/mysql/base.py:71: Warning: (1292, "Incorrect datetime value: '%2017-12-21%' for column 'created_at' at row 1") I'm using MySQL database. My Model is class Business(models.Model): name = models.CharField(max_length=255, blank=True, null=True) url = models.CharField(max_length=255, blank=True, null=True) created_at = models.DateTimeField() category = models.CharField(max_length=120) class Meta: managed = False db_table = 'Business' unique_together = (('name', 'url'),)

http://stackoverflow.com/comment/82962071
type: Comment
type: QuestionComment
score: 0
has text: Your "full code example" doesn't have anything named `list_1`, which is what is in the error message.
comment on: http://stackoverflow.com/q/47925731

http://stackoverflow.com/comment/82860804
type: Comment
has text: Because the order is different?
comment on: http://stackoverflow.com/q/47945540
score: 1
type: QuestionComment

http://stackoverflow.com/comment/82865270
comment on: http://stackoverflow.com/q/47947676
has text: You probably want to compare `type()` in this case.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47972710
has comment: http://stackoverflow.com/comment/82915892
accepted answer of: http://stackoverflow.com/q/47972633
has comment: http://stackoverflow.com/comment/82916669
has body: In general, you can get a view if the data-frame has a single dtype, which is not the case with your original data-frame: In [4]: df Out[4]: age name student1 21 Marry student2 24 John In [5]: df.dtypes Out[5]: age int64 name object dtype: object However, when you do: In [6]: df.loc['student3'] = ['old','Tom'] ...: The first column get's coerced to object, since columns cannot have mixed dtypes: In [7]: df.dtypes Out[7]: age object name object dtype: object In this case, the underlying .values will always return an array with the same underlying buffer, and changes to that array will be reflected in the data-frame: In [11]: vals = df.values In [12]: vals Out[12]: array([[21, 'Marry'], [24, 'John'], ['old', 'Tom']], dtype=object) In [13]: vals[0,0] = 'foo' In [14]: vals Out[14]: array([['foo', 'Marry'], [24, 'John'], ['old', 'Tom']], dtype=object) In [15]: df Out[15]: age name student1 foo Marry student2 24 John student3 old Tom On the other hand, with mixed types like with your original data-frame: In [26]: df = pd.DataFrame([{'name':'Marry', 'age':21},{'name':'John','age':24}] ...: ,index=['student1','student2']) ...: In [27]: vals = df.values In [28]: vals Out[28]: array([[21, 'Marry'], [24, 'John']], dtype=object) In [29]: vals[0,0] = 'foo' In [30]: vals Out[30]: array([['foo', 'Marry'], [24, 'John']], dtype=object) In [31]: df Out[31]: age name student1 21 Marry student2 24 John Note, however, that a view will only be returned if it is possible to be a view, i.e. if it is a proper slice, otherwise, a copy will be made regardless of the dtypes: In [39]: df.loc['student3'] = ['old','Tom'] In [40]: df2 Out[40]: name student3 Tom student2 John In [41]: df2.loc[:] = 'foo' In [42]: df2 Out[42]: name student3 foo student2 foo In [43]: df Out[43]: age name student1 21 Marry student2 24 John student3 old Tom
upvote count: 18
type: AcceptedAnswer
downvote count: 0
score: 18
type: Answer
answers question: http://stackoverflow.com/q/47972633

http://stackoverflow.com/q/47999271
tagged with: class
has body: I am looking at the iris dataset as part of the sklearn datasets and when I assign the following: &gt; iris = sklearn.datasets.load_iris() writing the following gives me: &gt; type (iris) &lt;class 'tuple'&gt; What exactly does it mean by a class of tuples? I have read the documentation but it is still not clear to me how you can access &gt; iris.data and &gt; iris.target but then how can you also do : &gt; iris.target[[10, 25, 50]] Can someone please explain this in more detail? Thanks!
score: 0
answer count: 2
has title: What is the type of load_iris in scikit-learn library in python?
tagged with: dataset
tagged with: scikit-learn
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47999396
tagged with: machine-learning
type: Question
has answer: http://stackoverflow.com/a/48018968

http://stackoverflow.com/comment/82929883
type: Comment
type: AnswerComment
has text: I did the some thing as you described following your instructions and received the same error as before
score: 0
comment on: http://stackoverflow.com/a/47965166

http://stackoverflow.com/q/47924481
has comment: http://stackoverflow.com/comment/82816566
accepted answer: http://stackoverflow.com/a/47924533
has answer: http://stackoverflow.com/a/47924583
answer count: 4
has body: I am trying to add my sub dictionary element in list. It is giving me type error. Here is dictionary and my code: { "key1": "value1", "key2": { "skey1": "svalue2", "skey2": { "sskey1": [{ "url": "value", "sid": "511" }, { "url": "value", "sid": "522" }, { "url": "value", "sid": "533" }] } } } I want to add the sid into the list like [511,522,533]: here is my code: rsId=[] for i in op['key2']['skey2']['sskey1']: for k,v in i.items(): if k=='sid': rsId.append(v)
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47924582
has answer: http://stackoverflow.com/a/47924582
type: Question
has answer: http://stackoverflow.com/a/47924533
has comment: http://stackoverflow.com/comment/82816522
has answer: http://stackoverflow.com/a/47951056
tagged with: python
has title: Add the sub dictonary element in list in python
has comment: http://stackoverflow.com/comment/82816680
score: 0

http://stackoverflow.com/comment/82915492
score: 0
has text: BTW: see example with [circle collision](https://github.com/furas/python-examples/tree/master/pygame/collisions) and [mask collision](https://github.com/furas/python-examples/tree/master/pygame/mask-collision)
type: Comment
comment on: http://stackoverflow.com/a/47972941
type: AnswerComment

http://stackoverflow.com/comment/82925736
comment on: http://stackoverflow.com/a/47970211
type: AnswerComment
score: 0
type: Comment
has text: @Linbin yes, I suppose. Also you can make model Team and relate it with Stat, so then you'll be able to get history of matches for one team.

http://stackoverflow.com/comment/82684323
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47858008
has text: Is [sys.getallocatedblocks()](https://docs.python.org/3/library/sys.html#sys.getallocatedblocks) helpful? Perhaps you need to look deeper into the [gc](https://docs.python.org/3/library/gc.htm) modules.
score: 0

http://stackoverflow.com/a/48002867
has comment: http://stackoverflow.com/comment/83202370
has body: We build nightly zip files off the latest HEAD, available here. It would be great if you could try out the latest windows version and let us know on IRC at #pypy, or on the pypy-dev mailing list, or by filing an issue on our bitbucket issue tracker whether it works for you, so that we will not need to do a 5.10.2 bug release fix after the current one.
upvote count: 1
has comment: http://stackoverflow.com/comment/82988854
accepted answer of: http://stackoverflow.com/q/47999518
type: AcceptedAnswer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/47999518
has comment: http://stackoverflow.com/comment/82980132
has comment: http://stackoverflow.com/comment/83007291
type: Answer

http://stackoverflow.com/q/47953621
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/64262889
type: AnsweredQuestion
upvote count: 3
has title: Flask - 404 not found
has comment: http://stackoverflow.com/comment/82876520
has answer: http://stackoverflow.com/a/68388378
type: Question
has comment: http://stackoverflow.com/comment/82876519
has comment: http://stackoverflow.com/comment/82876750
score: 3
linked to: http://stackoverflow.com/q/44949338
has answer: http://stackoverflow.com/a/47953970
has answer: http://stackoverflow.com/a/60215471
downvote count: 0
tagged with: web
possible better answer: http://stackoverflow.com/a/51628183
tagged with: flask
favorite count: 0
has answer: http://stackoverflow.com/a/51628183
has body: I am a newbie in the flask development this is my first program in the flask but it shows me this error: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. &amp; this is my code from flask import Flask app = Flask(__name__) @app.route('/index') def index(): return 'Hello World' if __name__ == '__main__': app.run(debug=True)
accepted answer: http://stackoverflow.com/a/47953970

http://stackoverflow.com/comment/82887306
has text: First one will remove first `j` items from the `list`. The second one will remove the _j+1_ th item.
comment on: http://stackoverflow.com/q/47959077
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/q/48001492
has body: I have a sample code for getting a message from Mqtt broker import paho.mqtt.client as mqtt def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) client.subscribe("123") def on_message(client, userdata, msg): x = int(msg.payload)*10 print(msg.topic+" "+str(msg.payload)) client = mqtt.Client() client.connect("broker.hivemq.com", 1883) client.on_connect = on_connect client.on_message = on_message client.loop_forever() How can I get the variable of msg.payload in on_message? I add the x variable in function of on_connect: def on_message(client, userdata, msg): x = int(msg.payload)*10 print(msg.topic+" "+str(msg.payload)) return x Question: How do I get the variable x?
type: Question
has comment: http://stackoverflow.com/comment/83751446
has comment: http://stackoverflow.com/comment/82971792
answer count: 1
tagged with: paho
score: 0
tagged with: mqtt
tagged with: python
has title: How to get publish value about Python paho Mqtt
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48873959

http://stackoverflow.com/a/47956840
answers question: http://stackoverflow.com/q/47888784
score: 0
has body: First I'd like to point out that InstallShield has a default compiler setting of generating a new PackageCode every time you build your MSI. This is a best practice so I really don't see why you would need to edit the ISM at all for this scenario. The second thing I would point out is that the RAW DTD XML formatting of an ISM is very difficult to work with. I tend to use the COM automation inferface for the majority of dynamic authoring and then save the project in Binary format so I can edit it as a relational database just like I would using ORCa. WiX C#/DTF custom actions have LINQ support that makes this much easier to do. You could even write a C# helper class and call it from python too. You can then open it in the automation interface and save it back in XML format if you want to.
type: Answer

http://stackoverflow.com/a/47942578
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47929310
answers question: http://stackoverflow.com/q/47929310
has body: You have to use a Gauge and not a Counter. Example from the README: from prometheus_client import Gauge g = Gauge('my_inprogress_requests', 'Description of gauge') g.inc() # Increment by 1 g.dec(10) # Decrement by given value g.set(4.2) # Set to a given value See also Prometheus metric types: https://prometheus.io/docs/concepts/metric_types/ Counter A counter is a cumulative metric that represents a single numerical value that only ever goes up. A counter is typically used to count requests served, tasks completed, errors occurred, etc. Counters should not be used to expose current counts of items whose number can also go down, e.g. the number of currently running goroutines. Use gauges for this use case. Gauge A gauge is a metric that represents a single numerical value that can arbitrarily go up and down. Gauges are typically used for measured values like temperatures or current memory usage, but also "counts" that can go up and down, like the number of running goroutines.
score: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47926823
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47926876
type: AnsweredQuestion
has body: I'm trying to return a list in one of my methods for interacting with vmware via pyvmomi. active_list = self.vss.spec.policy.nicTeaming.nicOrder.activeNic when I do return active_list I get: (str) [ 'vmnic0', 'vmnic1' ] Type: type(active_list) &lt;class 'pyVmomi.VmomiSupport.str[]'&gt; Since I'm able to iterate over the active_list as it is, shoud I be concerned about the (str) prefix. I was able to avoid the (str) [...] prefix by coping active_list, new_list=list(active_list) What is the best pythonic approach to this?
score: 1
has answer: http://stackoverflow.com/a/47926876
has title: Should I be concerned about return "(str) ['item1', 'item2' ]"
type: Question
tagged with: python-2.7
answer count: 1
downvote count: 0
favorite count: 0
tagged with: pyvmomi

http://stackoverflow.com/comment/82693840
comment on: http://stackoverflow.com/a/47857975
score: 0
type: AnswerComment
has text: Thank you but I tried `111010` and it is returning `3`, not `2` as I need. This because it is matching `11101`, `1101` and `101`. I need the 1s used for a matching not to be reconsidered. This way `111010` would match only to `11101` and `1101`.
type: Comment

http://stackoverflow.com/comment/82960961
type: QuestionComment
has text: Peewee does not use ".all()". And like previous commenter said, ".get()" returns a single instance, not a collection. Just remove the call to ".get()". Also, ".update()" isn't the correct invocation. You want .save(). Did you even read the docs? This is way wrong.
score: 0
comment on: http://stackoverflow.com/q/47995101
type: Comment

http://stackoverflow.com/a/58544128
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/47952691
has body: This error message will occur when the provided latitude or longitude is out of range. A latitude of 96.95 is not within the valid latitude range. Latitudes range from -90 to 90. Longitudes range from -180 to 180. range source: https://stackoverflow.com/a/16743805/1816667
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47952691
downvote count: 0

http://stackoverflow.com/comment/82730196
type: QuestionComment
has text: Can you clarify if I understand correctly? You want the URL `/` to always redirect to a slug `/my-custom-home-slug` OR do you just want there to be no `/` URL, just a `/my-custom-home-slug` Maybe it would be good to edit the question with the page tree you are hoping to achieve.
score: 0
comment on: http://stackoverflow.com/q/47863175
type: Comment

http://stackoverflow.com/a/47889005
has body: In line 44, the interpreter finds the following expression controller.show_frame(messagescreenpagevar) In this scope, controller was not defined. That's why the interpreter prompts the error name 'controller' is not defined. Python uses lexical scope. So in order to have a variable controller defined at line 44, you would either have to define it in: the method checkpassword the class passwordpage in the global scope of your module
downvote count: 0
answers question: http://stackoverflow.com/q/47888904
type: Answer
score: 1
upvote count: 1

odoo-8
tags question: http://stackoverflow.com/q/48010835
type: Tag
tag name: odoo-8
tags question: http://stackoverflow.com/q/47878070
tags question: http://stackoverflow.com/q/47922657
tags question: http://stackoverflow.com/q/47893915

http://stackoverflow.com/comment/82809759
score: 0
type: AnswerComment
type: Comment
has text: which column do you want to fill?
comment on: http://stackoverflow.com/a/47909291

http://stackoverflow.com/q/47974320
has body: Given this code ("sleep" instances used to help display what's going on): from splinter import Browser import time with Browser() as browser: # Visit URL url = "https://mdoe.state.mi.us/moecs/PublicCredentialSearch.aspx" browser.visit(url) browser.fill('ctl00$ContentPlaceHolder1$txtCredentialNumber', 'IF0000000262422') # Find and click the 'search' button button = browser.find_by_name('ctl00$ContentPlaceHolder1$btnSearch') # Interact with elements button.first.click() time.sleep(5) #Only click the link next to "Professional Teaching Certificate Renewal" certificate_link = browser.find_by_xpath("//td[. = 'Professional Teaching Certificate Renewal']/following-sibling::td/a") certificate_link.first.click() time.sleep(10) I am now trying to get the values from the table that shows after this code runs. I am not well-versed in xpath commands, but based on the response to this question, I have tried these, to no avail: name = browser.find_by_xpath("//td[. ='Name']/following-sibling::td/a") name = browser.find_by_xpath("//td[. ='Name']/following-sibling::td/[1]") name = browser.find_by_xpath("//td[. ='Name']/following-sibling::td/[2]") I tried [2] because I do notice a colon (:) sibling character between "Name" and the cell containing the name. I just want the string value of the name itself (and all other values in the table). I do notice a different structure (span is used within td instead of just td) in this case (I also tried td span[. ='Name']... but no dice): Updated to show more detail Name : MICHAEL WILLIAM LANCE
has answer: http://stackoverflow.com/a/47985285
tagged with: python
tagged with: xpath
tagged with: splinter
type: UnansweredQuestion
has title: Python Splinter Get Value From Table (Following-Sibling)
upvote count: 1
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/47971823
answer count: 1
has comment: http://stackoverflow.com/comment/82918454
has comment: http://stackoverflow.com/comment/82918536
favorite count: 0
score: 0

http://stackoverflow.com/comment/82890217
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47939683
type: AnswerComment
has text: @johnnym With "removing the "..." " I meant removing the quotes around the individual entries. Also, if this helped you with your problem, please consider accepting the answer to mark the question as being resolved. An happy holidays!

http://stackoverflow.com/comment/82982788
type: Comment
score: 1
comment on: http://stackoverflow.com/q/47968040
has text: @tevemadar answer to your linked question suggests using kivy. However, it will limit me to just using kivy..what about other functionalities GUIs service broadcast receivers which are more easier to do using plain android...don't want to develop the entire app using just kivy and the bundle it into apk....hence this isn't a duplicate...what I was looking for was some api using which my java and python code can interact in android environment .Regarding "write my entire code part" , I can give a simple activity code and a simple python script which adds two numbers retrieved from java code
type: QuestionComment

http://stackoverflow.com/comment/82921581
type: QuestionComment
has text: @SergeBallesta you are right. Actually I use two intervals: `range(65,91)` and `range(48,58)`. So I use double condition in `if` statement.
score: 0
comment on: http://stackoverflow.com/q/47976142
type: Comment

http://stackoverflow.com/q/47920965
favorite count: 0
has body: The idea of the program is to take a "language" and turn it into numbers. The language is build quite easy K = 10 P = 20 T = 40 V = 80 anything smaller then 10 will be represented in normal numbers Now the numbers shouldn't be something to worry about I explain this so it's easier to get what I try to achieve here. I build up a class called "Mangarevaans" which looks as following: def mag2arab(getal): #this function is designed to turn the letters into the normal numbers we're used to mag = str(getal) waarde = {"K": 10, "P": 20, "T": 40, "V": 80} arab = 0 for index, j in enumerate(mag): if index == 0 and j.isnumeric(): if len(getal) == 1: x = 0 else: x = 1 arab += int(j) * waarde[mag[x]] elif j.isnumeric(): arab += int(j) elif not (str(mag[0]).isnumeric() and index == 1): arab += waarde[j] return arab class Mangarevaans(): """ &gt;&gt;&gt;612 // Mangarevaans(26) Mangarevaans('P3') """ def __init__(self, getal): if isinstance(getal, int): assert 1 &lt;= getal &lt; 799, 'ongeldige waarde' #this is one of the rules of the language that if there is a number it should be between these values self.getal = getal else: for letter in getal: if isinstance(getal, str): for letter in getal: if letter in "VTPK": self.getal = getal else: raise AssertionError('ongeldige waarde') self.getal = mag2arab(getal) def __int__(self): return self.getal def __str__(self): return arab2mag(self.getal) def __repr__(self): return f"Mangarevaans('{str(arab2mag(self.getal))}')" def __rfloordiv__(other, self): return Mangarevaans(other // self.getal) #The problem occurs here Now when I want to run the doctest """ &gt;&gt;&gt;612 // Mangarevaans(26) Mangarevaans('P3') """ I get an error saying 'int' object has no attribute 'getal' but if I change my self to a string I get 'str' object has no attribute 'getal' how can i define if the attribute "getal" belongs with "str" or "int" ? Can anyone help me ? Thanks a lot already
has answer: http://stackoverflow.com/a/47921280
downvote count: 2
tagged with: python
type: AnsweredQuestion
has title: "'int' object has no attribute 'getal'" in self made class Python
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/47921280
score: -1
tagged with: class
tagged with: int
answer count: 1
tagged with: string

http://stackoverflow.com/comment/82856705
type: Comment
comment on: http://stackoverflow.com/a/47943560
score: 0
type: AnswerComment
has text: first, provide explanation than post the link in the answer.

http://stackoverflow.com/comment/99241260
type: AnswerComment
score: 0
type: Comment
has text: Hmm.. Last version of pip's mypy (0.5.0) looks fine. Sadly, too busy to dive deeper into this for now.
comment on: http://stackoverflow.com/a/55251337

http://stackoverflow.com/comment/82691731
type: Comment
comment on: http://stackoverflow.com/a/47863335
score: 0
type: AnswerComment
has text: oops, I lost your comment, sorry:(

http://stackoverflow.com/a/47979900
downvote count: 1
answers question: http://stackoverflow.com/q/47979843
score: -1
has comment: http://stackoverflow.com/comment/82928325
has body: Only immutable objects are hashable in Python. Sets require their items to be hashable. List in not hashable. You can do smth like this: gender = set() for x in leglist_: if x[3] not in gender: gender.add(x[3])
upvote count: 0
has comment: http://stackoverflow.com/comment/82934335
type: Answer

http://stackoverflow.com/comment/82735592
score: 0
has text: Why don't you create a 'bootstrap' script to go through your `.py` files and adjust their shebang in accordance with the current environment?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47882916

http://stackoverflow.com/comment/82914778
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47972274
has text: Possible duplicate of [Why this print changing the following result?](https://stackoverflow.com/questions/47936065/why-this-print-changing-the-following-result)
score: 0

http://stackoverflow.com/q/47937256
type: Question
possible better answer: http://stackoverflow.com/a/47943236
accepted answer: http://stackoverflow.com/a/51224706
has answer: http://stackoverflow.com/a/51224706
tagged with: twisted
upvote count: 1
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/47943236
favorite count: 0
has comment: http://stackoverflow.com/comment/83716022
has answer: http://stackoverflow.com/a/62070682
tagged with: django-channels
has answer: http://stackoverflow.com/a/63960094
tagged with: django
tagged with: python
has title: Error while installing Django-channels on Python 3.5 on Windows
answer count: 4
type: AnsweredQuestion
downvote count: 0
score: 1
has body: I'm also getting the same error while installing Twisted. Here's version info: Django : 1.9 Python : 3.5 Trying to install latest version of Django-channels Command used : pip install channels The error : running build_ext building 'twisted.test.raiser' extension error: [WinError 2] The system cannot find the file specified (Almost) full error message .......pip install channels Collecting channels Using cached channels-1.1.8-py2.py3-none-any.whl Collecting daphne~=1.3 (from channels) Using cached daphne-1.3.0-py2.py3-none-any.whl Requirement already satisfied: asgiref~=1.1 in g:\django\projectChat\venv\lib\site-packages (from channels ) Requirement already satisfied: Django&gt;=1.8 in g:\django\projectChat\venv\lib\site-packages (from channels) Requirement already satisfied: autobahn&gt;=0.18 in g:\django\projectChat\venv\lib\site-packages (from daphne ~=1.3-&gt;channels) Collecting twisted&gt;=17.1 (from daphne~=1.3-&gt;channels) Using cached Twisted-17.9.0.tar.bz2 Requirement already satisfied: six in g:\django\projectChat\venv\lib\site-packages (from asgiref~=1.1-&gt;cha nnels) Requirement already satisfied: txaio&gt;=2.7.0 in g:\django\projectChat\venv\lib\site-packages (from autobahn &gt;=0.18-&gt;daphne~=1.3-&gt;channels) Requirement already satisfied: zope.interface&gt;=4.0.2 in g:\django\projectChat\venv\lib\site-packages (from twisted&gt;=17.1-&gt;daphne~=1.3-&gt;channels) Requirement already satisfied: constantly&gt;=15.1 in g:\django\projectChat\venv\lib\site-packages (from twis ted&gt;=17.1-&gt;daphne~=1.3-&gt;channels) Requirement already satisfied: incremental&gt;=16.10.1 in g:\django\projectChat\venv\lib\site-packages (from twisted&gt;=17.1-&gt;daphne~=1.3-&gt;channels) Requirement already satisfied: Automat&gt;=0.3.0 in g:\django\projectChat\venv\lib\site-packages (from twiste d&gt;=17.1-&gt;daphne~=1.3-&gt;channels) Requirement already satisfied: hyperlink&gt;=17.1.1 in g:\django\projectChat\venv\lib\site-packages (from twi sted&gt;=17.1-&gt;daphne…

http://stackoverflow.com/q/47893991
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/82754677
has body: I am trying to make a model for a "Question/Quiz" . A question can have as many choices (Charfields) as user wants , and there can be one or many correct answers (out of those options) . How should I define this model?﻿ Question: Some long description. Choice 1 Choice 2 Choice 3 - Correct Ans Choice 4 - Correct Ans So far I came up with this but I think it is a bad design: class Question(models.Model): description = models.CharField('Description', max_length=300) correct_answer_id = models.UUIDField('answer_id', null=True) options = models.ManyToManyField(Answer) class Answer(models.Model): """ Answer's Model, which is used as the answer in Question Model """ text = models.CharField(max_length=128, verbose_name=u'Answer\'s text') ans_id = models.UUIDField(default=uuid.uuid1())
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/47894215
accepted answer: http://stackoverflow.com/a/47894215
possible better answer: http://stackoverflow.com/a/47894235
tagged with: django
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47894235
has title: How to create a "Quiz" model that has unknown number of options with one or more correct answers?
tagged with: django-models

http://stackoverflow.com/comment/82778437
type: Comment
comment on: http://stackoverflow.com/q/47905757
type: QuestionComment
score: 0
has text: Also, 0.17 is an old version. Try upgrading to the latest version and see if it fixes your problem.

http://stackoverflow.com/a/47946268
score: 0
type: Answer
has body: def adminRoute(*route_args, **route_kwargs): def outer(action_function): @app.route(*route_args, **route_kwargs) @requiresAdmin @functools.wraps(action_function) def inner(*f_args, **f_kwargs): return action_function(f_args, f_kwargs) return inner return outer
answers question: http://stackoverflow.com/q/47946267

http://stackoverflow.com/a/47935741
has comment: http://stackoverflow.com/comment/82854714
has comment: http://stackoverflow.com/comment/82854974
accepted answer of: http://stackoverflow.com/q/47935300
has comment: http://stackoverflow.com/comment/82867811
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47935300
has body: Your xml is missing closing tags for 2 folders (4th to last & 3rd to last lines below. Just copy & paste them into your XML file). Indented XML using this tool https://www.freeformatter.com/xml-formatter.html#ad-output <?xml version="1.0" encoding="UTF-8"?> One Line Diagram 0 SectionOne 0 Node 0 5680420 #Style_0 <description /> -83.6514766,67.0234192 -83.6515403,67.0233918 -83.6515309,67.0233134 -83.6514609,67.0232885 -83.5778406,67.0246267 -83.5777768,67.0246541 -83.5777861,67.0247325 -83.5778560,67.0247574 -83.6514766,67.0234192 25934531 #Style_0 ML60 <description /> -83.6512679,67.0216805 -83.6513317,67.0216531 -83.6513222,67.0215747 -83.6512522,67.0215498 -83.5967049,67.0225434 -83.5966412,67.0225708 -83.5966505,67.0226492 -83.5967204,67.0226741 -83.6512679,67.0216805 Using xmltodict to extract coordinates from coordinates.xml file containing your XML (with 2 missing folder closing tags included) import xmltodict with open('coordinates.xml') as coords: doc = xmltodict.parse(coords.read()) coordinates = [] #Loop and get each placemark tag in document for placemark in doc['kml']['Document']['Folder']['Folder']['Folder']['Placemark']: #Get coordinates string from current placemark coordinateString=placemark['MultiGeometry']['Polygon']['outerBoundaryIs']['LinearRing']['coordinates'] #split coordinates string into lists of coordinates. Split co-ord pairs by space (" "). Split x & y of each co-ord by comma (",") coordinateList=[x.split(",") for x in coordinateString.split(" ")] coordinates.append(coordinateList) print(coordinates) Output of printing "coordinates" list [[[u'-83.6514766', u'67.0234192'], [u'-83.6515403', u'67.0233918'], [u'-83.6515309', u'67.0233134'], [u'-83.6514609', u'67.0232885'], [u'-83.5778406', u'67.0246267'], [u'-83.5777768', u'67.0246541'], [u'-83.5777861', u'67.0247325'], [u'-83.5778560', u'67.0247574'], [u'-83.6514766', u'67.0234192']], [[u'-83.6512679', u'67.0216805'], [u'-83.6513317', u'67.0216531'], [u'-83.6513222', u'67.0215747'], [u'-83.…
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82855091

http://stackoverflow.com/a/47899709
score: 1
answers question: http://stackoverflow.com/q/47899683
type: Answer
upvote count: 1
has body: I believe you need: print (arr.argmax(axis=1)) [5 5] print (arr.argmax(axis=0)) [0 0 0 0 0 1] First get argmax and then use DataFrame constructor: print (pd.DataFrame(arr.argmax(axis=0), columns=['a'])) a 0 0 1 0 2 0 3 0 4 0 5 1 print (pd.DataFrame(arr.argmax(axis=0)[None, :])) 0 1 2 3 4 5 0 0 0 0 0 0 1 print (pd.DataFrame(arr.argmax(axis=1), columns=['a'])) a 0 5 1 5 Or create DataFrame and call idxmax print (pd.DataFrame(arr).idxmax().to_frame('a')) #same as #print (pd.DataFrame(arr).idxmax(axis=0).to_frame('a')) a 0 0 1 0 2 0 3 0 4 0 5 1 print (pd.DataFrame(arr).idxmax().to_frame(0).T) 0 1 2 3 4 5 0 0 0 0 0 0 1 print (pd.DataFrame(arr).idxmax(axis=1).to_frame('a')) a 0 5 1 5
downvote count: 0

http://stackoverflow.com/a/47938494
has comment: http://stackoverflow.com/comment/83430990
score: 0
answers question: http://stackoverflow.com/q/47924553
type: Answer
has comment: http://stackoverflow.com/comment/83504049
has comment: http://stackoverflow.com/comment/83275635
has body: Squish got changed at some point to allow script execution after the AUT exited, so ensure that you have a recent Squish package. The Update application and the newly started AUT can probably be hooked up again: On Windows they need to be started via dllpreload.exe or startaut.exe, or have the attachable Built-in Hook compiled into them (Using the Built-in Hook). On Unix sub-process hooking must be enabled in the test suite settings and the environment of the original AUT instance be kept intact, or they need to have the attachable Built-in Hook compiled into them.
has comment: http://stackoverflow.com/comment/83316167

http://stackoverflow.com/q/48012911
tagged with: python
has answer: http://stackoverflow.com/a/48013061
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
type: Question
accepted answer: http://stackoverflow.com/a/48013061
has title: NYTimes Article Search API - UndefinedError: 'unicode object' has no attribute 'repsonse'
score: 0
answer count: 1
tagged with: unicode
has body: I'm having some trouble with the NYTimes Article Search API. I'm using the python package "NYTimesArtcile" and I'm trying to work with a simple example just so I can become comfortable/familiar with passing data to webpages from the NYTimes. here's my app.py from flask import Flask from flask_mysqldb import MySQL from nytimesarticle import articleAPI api = articleAPI("*****") app = Flask(__name__) app.config['MYSQL_HOST'] = 'localhost' app.config['MYSQL_USER'] = 'root' app.config['MYSQL_PASSWORD'] = '*****' app.config['MYSQL_DB'] = '*****' app.config['MYSQL_CURSORCLASS'] = 'DictCursor' app.config['SECRET_KEY'] = '*****' mysql = MySQL(app) from views import * if __name__=='__main__': app.run(debug=True) Here's where my view for a "featured page": @app.route('/featured', methods=['GET']) def featured(): results = api.search(q = 'Obama') return render_template('featured.html', results=results) Here's my html page, featured.html: {% extends 'base/base.html' %} {% block body %} title URL {% for result in results %} {{result.title() }} {{ result.title() }} {% endfor %} {% endblock %} I've placed results.title() in the jinja formate because it's the only thing that works. When I return results.title(), I get the first 3 objects from the JSON data (status, response, copyright). What I want is the title of the article and the web_url. I know that the info I want is in results.response.docs, but when I try that, I get the above error. Here's a bit of the JSON from NYTimes (one article). Any help is appreciated: { "status": "OK", "copyright": "Copyright (c) 2017 The New York Times Company. All Rights Reserved.", "response": { "docs": [ { "web_url": "https://www.nytimes.com/2017/12/01/books/review/peter-baker-obama-the-call-of-history.html", "snippet": "Peter Baker’s “Obama: The Call of History” is a tribute to a man and an office.", "print_page": "53", "blog": {}, "source": "The New York Times", "multimedia": [ { "rank": 0, "subtype": "xlarge", "caption": null, "credit": null,…

http://stackoverflow.com/comment/82683819
comment on: http://stackoverflow.com/a/47859292
has text: Could you explain the reason for the -2 ? Based on some googling for map and lambda it doesnt seem to be needed by either of those
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/82869767
has text: Still not counting down. Alright, I'm going to take a look at this from the ground up as I don't think this approach works.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47908431

http://stackoverflow.com/comment/82783778
has text: np, if possible make it as correct answer, it might helpfull for some one :)
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47908102

http://stackoverflow.com/comment/82760733
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47896478
type: Comment
has text: Sorry, had to step away from the keyboard for a while; it probably is possible to use a `TypeVar()` marked as covariant instead of `A` but won’t be able to test until tomorrow.

http://stackoverflow.com/q/47956297
tagged with: python
score: 2
type: AnsweredQuestion
has title: SQLITE3 - Put Data in columns with a loop
has body: I am using SQLITE3. In my SQL Table, I have a table of 50 columns, and I would like to put in each column each value of My_List, which has 50 elements. Is there any way to code a loop in python to put my data in my table ? I tried to find it out but didn't get anything... My current code for 3 variables instead of 50 is: import sqlite3 conn = sqlite3.connect("testdatabase.db") c.execute('''CREATE TABLE mytable (Column1 text, Column2 text, Column3, text) ''') c.execute('''INSERT INTO mytable (Column1, Column2, Column3) VALUES (?, ?, ?)''', (myliste[0], myliste[1], myliste[2]) conn.commit() Thank you very much. Lcs
type: Question
possible better answer: http://stackoverflow.com/a/47957370
has comment: http://stackoverflow.com/comment/82882104
tagged with: sql-insert
downvote count: 0
upvote count: 2
accepted answer: http://stackoverflow.com/a/47956442
answer count: 3
tagged with: sql
tagged with: sqlite
favorite count: 0
has answer: http://stackoverflow.com/a/47957370
has answer: http://stackoverflow.com/a/47958252
has answer: http://stackoverflow.com/a/47956442
linked to: http://stackoverflow.com/q/47929592

http://stackoverflow.com/comment/82759203
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47894883
has text: No, it will not reduce memory, there are the same numbers in that array as in the list of lists. Is the question how to reduce memory consumption when plotting a contour plot? In that case one would start thinking about how much data is actually needed. If the data is that big that it fills the complete memory of a modern computer, one would surely find a way to obtain the same visual result but with much less data.
score: 0

http://stackoverflow.com/comment/82994389
comment on: http://stackoverflow.com/q/48012370
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/162121/discussion-between-brucewayne-and-martijn-pieters).
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47974949
tagged with: python
has comment: http://stackoverflow.com/comment/82919158
type: AnsweredQuestion
has body: I'm wondering how to iterate through suggestions that you can see after tapping TAB (or you must type one of them manually?) Ex: screenshot with suggestions How to choose one of the variants?
tagged with: ipython
type: Question
has title: How to iterate through autocomplete suggestions in IPython shell
accepted answer: http://stackoverflow.com/a/48033431
answer count: 1
tagged with: console
score: 0
has answer: http://stackoverflow.com/a/48033431
has comment: http://stackoverflow.com/comment/82919463
has comment: http://stackoverflow.com/comment/82919567
tagged with: shell
has comment: http://stackoverflow.com/comment/82919118

http://stackoverflow.com/comment/82774253
has text: Thanks. I want pip to install mysqlclient from PyPI. Could you explain how to specify this repository for pip?
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47901789
score: 0

http://stackoverflow.com/a/49876424
downvote count: 0
score: 1
upvote count: 1
has body: This bug is not completely resolved on the version being developed. In particular concerning the intersections between the lines and circles of non simple coordinates. You can use shapely instead: [What is most efficient way to find the intersection of a line and a circle in python?
type: Answer
answers question: http://stackoverflow.com/q/47879246

http://stackoverflow.com/q/47984091
has body: Say I have a dictionary like the following: {'keyid': ['foo', '1', 'bar', '2', '(FancyStrininParathesis)']} How could I extract the strings in the value of the dictionary and create and print one long string such as print (finalstring) #Desired output: 'foo - 1 bar - 2 (FancyStrininParathesis)' I've been able to output the value fine, but I can't figure out how to output the array as one long string. I'm new to python as well, I'm more familer with PHP, however I have to use a special python library for this project. Thanks for the help!
tagged with: regex
has comment: http://stackoverflow.com/comment/82937264
favorite count: 0
has answer: http://stackoverflow.com/a/47984209
tagged with: python
tagged with: dictionary
answer count: 4
has answer: http://stackoverflow.com/a/47984201
has comment: http://stackoverflow.com/comment/82937218
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47984194
has comment: http://stackoverflow.com/comment/82937201
downvote count: 1
type: Question
has title: Print dictionary value into string with Python3.6
has answer: http://stackoverflow.com/a/47984254
possible better answer: http://stackoverflow.com/a/47984201
accepted answer: http://stackoverflow.com/a/47984209
score: 0
has comment: http://stackoverflow.com/comment/82937276
upvote count: 1

http://stackoverflow.com/q/47861087
has body: I'm trying to install the NCAR command language suite ncl, which has some data processing tools for atmospheric scientists. Every time I get the message: conda create -n ncl -c conda-forge ncl ..... UnsatisfiableError: The following specifications were found to be in conflict: -ncl But how can packages be in conflict when ncl is the only package listed? What does this mean?
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
tagged with: anaconda
has title: conda: packages found to be in conflict, but only ONE package is listed. What does this mean?
has answer: http://stackoverflow.com/a/47943560
tagged with: conda
tagged with: ncl
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82701353
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47943560
tagged with: python

http://stackoverflow.com/a/47879159
upvote count: 2
downvote count: 1
accepted answer of: http://stackoverflow.com/q/47878893
score: 1
has body: Here is how you need to solve it. S3 stores everything as objects and there is no folder or filename. It is all for user convenience. aws s3 ls s3://bucket/folder1/folder2/filenamepart --recursive will get all s3 objects name that matches to that name. import boto3 s3 = boto3.resource('s3') my_bucket = s3.Bucket('bucketname') for obj in my_bucket.objects.filter(Prefix='012345'): print(obj) To speed up the list you can run multiple scripts parallelly. Hope it helps.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47878893
type: Answer

http://stackoverflow.com/comment/82730274
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47881815
has text: Does a list comprehension also count as for loop?
score: 0

http://stackoverflow.com/q/47886509
tagged with: optimization
type: Question
tagged with: python
has title: 2D integral on a non-regular grid
has comment: http://stackoverflow.com/comment/82823346
has comment: http://stackoverflow.com/comment/82739575
score: 0
has body: I have two arrays coord and values. The first one contains a set of 2D coordinates on a grid of size N*N. The second contains the values of a function F on each of these coordinates. For instance on a 5*5 grid, I have the following 10 coordinates and values: coord = np.array([(0,0),(2,1),(0,2),(2,3),(3,4),(4,0),(1,3),(4,2),(3,0),(1,4)]) values = np.array([1,5,1,4,6,3,2,0,5,2]) which look like this on the grid: 4| x 2 x 6 x 3| x 2 4 x x 2| 1 x x x 0 1| x x 5 x x 0| 1 x x 5 3 ^ _ _ _ _ _ Y X&gt;0 1 2 3 4 I wish to compute the integral of the function F in Python, and to do so, I use the following code: from scipy import integrate import numpy as np coord = coord.swapaxes(0,1) nx = np.unique(coord[1]).size ny = np.unique(coord[0]).size intg_x = np.zeros(nx) for x in range(nx): indices = np.where(coord[1] == x)[0] v = values[indices] c = coord[0][indices] intg_x[x] = integrate.trapz(v,c) intg = integrate.trapz(intg_x,np.unique(coord[0]).sort()) print(intg) Out[1]: -3.0 However, when using it on the above example, it outputs 3 which is obviously wrong. What is wrong with this code? Is there any way to improve its performance for large sets of coordinates?
tagged with: scipy
has comment: http://stackoverflow.com/comment/82747712
tagged with: performance
has comment: http://stackoverflow.com/comment/82797997
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82739757
tagged with: numpy
has comment: http://stackoverflow.com/comment/82739704
answer count: 0

http://stackoverflow.com/q/47928659
favorite count: 0
accepted answer: http://stackoverflow.com/a/47928813
has comment: http://stackoverflow.com/comment/82825944
tagged with: python
has body: I have a python file with name Pqr.py which contains a class holding a static method. import subprocess class Pqr: @staticmethod def callTheService(a,b,c): subprocess.call(a,b,c) Now I am trying to access this static method from another class which is in other python file. Both .py files are located in same directory. The code in second file is, import Pqr class Rst: Pqr.callTheService("a", "b", "c") When I try to run this, I get an error of AttributeError: module 'Pqr' has no attribute 'callTheService' Could you please help me solve this error?
has comment: http://stackoverflow.com/comment/82826008
type: AnsweredQuestion
score: 3
upvote count: 3
type: Question
tagged with: attributeerror
has answer: http://stackoverflow.com/a/47928813
downvote count: 0
has title: Call a static method from other class in python
has comment: http://stackoverflow.com/comment/82825845
has comment: http://stackoverflow.com/comment/82826060
tagged with: static-methods
answer count: 1

http://stackoverflow.com/a/47957169
type: Answer
has comment: http://stackoverflow.com/comment/82999581
has body: With css selector it was easier for me. import scrapy class MySpider(scrapy.Spider): name = 'myspider' start_urls = ['https://www.hltv.org/matches'] def parse(self, response): print('url:', response.url) days = response.css('.match-day') for day in days: date = day.css('.standard-headline::text').extract_first() print('date:', date) tables = day.css('table') for table in tables: time = table.css('div.time::text').extract_first() teams = table.css('.team::text').extract() event = table.css('.event-name::text').extract_first() placeholder = table.css('.placeholder-text-cell::text').extract_first() print(' time:', time) if teams: print(' teams 1:', teams[0]) print(' teams 2:', teams[1]) print(' event:', event) else: print(' placeholder:', placeholder) # --- it runs without project and saves in `output.csv` --- from scrapy.crawler import CrawlerProcess c = CrawlerProcess({ 'USER_AGENT': 'Mozilla/5.0', # save in file as CSV, JSON or XML 'FEED_FORMAT': 'csv', # csv, json, xml 'FEED_URI': 'output.csv', # }) c.crawl(MySpider) c.start() Result url: https://www.hltv.org/matches date: 2017-12-24 time: 03:00 teams 1: NSPR teams 2: MiTH event: WESG 2017 Thailand LAN time: 06:00 teams 1: Signature teams 2: Beyond event: WESG 2017 Thailand LAN time: 09:00 placeholder: WESG Thailand - Grand Final time: 10:00 teams 1: DKISS teams 2: Izako Boars event: Winner of the Future 2017 date: 2017-12-26 time: 14:00 teams 1: Recca teams 2: Signature event: GOTV.GG Invitational #1 time: 17:00 teams 1: AGO teams 2: Vega Squadron event: LOOT.BET Cup 2 time: 20:00 teams 1: mousesports teams 2: Spirit event: LOOT.BET Cup 2 date: 2017-12-27 time: 12:00 teams 1: Singularity teams 2: GoodJob event: CSesport.com XMAS Cup time: 13:00 placeholder: GOTV.GG - Semi-Final #1 time: 15:00 placeholder: GOTV.GG - Semi-Final #2 time: 15:00 teams 1: MANS NOT HOT teams 2: VenatoreS event: CSesport.com XMAS Cup time: 17:00 teams 1: Heroic teams 2: Valiance event: LOOT.BET Cup 2 date: 2017-12-28 time: 13:00 placehold…
has comment: http://stackoverflow.com/comment/83000256
accepted answer of: http://stackoverflow.com/q/47948598
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47948598
score: 0

http://stackoverflow.com/comment/82973030
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48002298
has text: As @FranciscoCouzo hinted, you might find this other thread interesting: https://stackoverflow.com/q/104420/289011
score: 0

http://stackoverflow.com/a/47988263
type: Answer
score: 13
has comment: http://stackoverflow.com/comment/127464619
has comment: http://stackoverflow.com/comment/130170780
upvote count: 14
downvote count: 1
has body: That's kinda like asking "everywhere I see mySQL database used, I could have just stored the data in a variable in the program, and written it to a text file when I wanted to power off; why do we bother with databases?" A dictionary is a temporary key based data structure in your own program's memory. A redis cache is a temporary key based data storage facility; it's standalone and self contained caching software that can be installed, scaled, and shared as an enterprise-wide service. It also provides for managing the stored data; expiry etc. Sure, it might look like it works like a local memory based dictionary (which is part of the appeal; simplicity and familiarity with a low grade device that does the same thing), but just imagine your boss comes and says "we're getting really popular, we need to put the website on 20 web servers to handle the load" .. sharing that cache if it's implemented with a dictionary is a nightmare. Using a caching service designed to be a shared makes the job easier. If you don't think you'll ever need a redis cache because your application will never grow big enough, then fine- don't use one. That's not to say that you should implement everything perfectly to handle the billion hypothetical users; just make some sensible quick win design decisions at the outset be realistic about what your app will one day be asked to do: 640k wasn't enough for anybody, after all
answers question: http://stackoverflow.com/q/47988087

http://stackoverflow.com/comment/82883520
type: Comment
has text: @edgarstack The same solution works for me on Python2 with or without the `universal_newlines=True` option. (If you have a choice, use Py3: Py2 is approaching [end-of-life.](https://pythonclock.org/))
type: AnswerComment
comment on: http://stackoverflow.com/a/47949695
score: 0

opencv
tags question: http://stackoverflow.com/q/47899253
type: Tag
tags question: http://stackoverflow.com/q/47856074
tags question: http://stackoverflow.com/q/47963386
tags question: http://stackoverflow.com/q/47921674
tags question: http://stackoverflow.com/q/47870573
tags question: http://stackoverflow.com/q/47925688
tags question: http://stackoverflow.com/q/47947718
tags question: http://stackoverflow.com/q/47889759
tags question: http://stackoverflow.com/q/47969587
tags question: http://stackoverflow.com/q/47935147
tags question: http://stackoverflow.com/q/47859327
tags question: http://stackoverflow.com/q/47935846
tags question: http://stackoverflow.com/q/47906056
tags question: http://stackoverflow.com/q/48003424
tags question: http://stackoverflow.com/q/47999030
tags question: http://stackoverflow.com/q/47983035
tags question: http://stackoverflow.com/q/47962840
tags question: http://stackoverflow.com/q/47975115
tags question: http://stackoverflow.com/q/47917906
tags question: http://stackoverflow.com/q/47981791
tags question: http://stackoverflow.com/q/48002776
tags question: http://stackoverflow.com/q/47899071
tags question: http://stackoverflow.com/q/47875456
tags question: http://stackoverflow.com/q/47946187
tags question: http://stackoverflow.com/q/47939437
tags question: http://stackoverflow.com/q/47949828
tags question: http://stackoverflow.com/q/47899966
tags question: http://stackoverflow.com/q/47991814
tags question: http://stackoverflow.com/q/47988877
tag name: opencv
tags question: http://stackoverflow.com/q/47977474
tags question: http://stackoverflow.com/q/48011604
tags question: http://stackoverflow.com/q/47929932
tags question: http://stackoverflow.com/q/47864265
tags question: http://stackoverflow.com/q/47935733
tags question: http://stackoverflow.com/q/47992804
tags question: http://stackoverflow.com/q/47991178
tags question: http://stackoverflow.com/q/47924385
tags question: http://stackoverflow.com/q/47963234
tags question: http://stackoverflow.com/q/47925877
tags question: http://stackoverflow.com/q/48001164
tags question: http://stackoverflow.com/q/48003559
tags question: http://stackoverflow.com/q/47867440
tags question: http://stackoverflow.com/q/47857141
tags question: http://stackoverflow.com/q/47933073
tags question: http://stackoverflow.com/q/48008223
tags question: http://stackoverflow.com/q/47936474
tags question: http://stackoverflow.com/q/47915793
tags question: http://stackoverflow.com/q/47922303
tags question: http://stackoverflow.com/q/47906158
tags question: http://stackoverflow.com/q/47919877
tags question: http://stackoverflow.com/q/47972217
tags question: http://stackoverflow.com/q/47909321
tags question: http://stackoverflow.com/q/47937122
tags question: http://stackoverflow.com/q/47973238
tags question: http://stackoverflow.com/q/47885958
tags question: http://stackoverflow.com/q/47979490
tags question: http://stackoverflow.com/q/47894673
tags question: http://stackoverflow.com/q/47884976
tags question: http://stackoverflow.com/q/47971026
tags question: http://stackoverflow.com/q/47959140
tags question: http://stackoverflow.com/q/47859699
tags question: http://stackoverflow.com/q/47998371
tags question: http://stackoverflow.com/q/47929626
tags question: http://stackoverflow.com/q/47887806
tags question: http://stackoverflow.com/q/48011093
tags question: http://stackoverflow.com/q/47864590
tags question: http://stackoverflow.com/q/47990952
tags question: http://stackoverflow.com/q/48001890
tags question: http://stackoverflow.com/q/48009322
tags question: http://stackoverflow.com/q/47877068
tags question: http://stackoverflow.com/q/47967582
tags question: http://stackoverflow.com/q/47989368
tags question: http://stackoverflow.com/q/47967070
tags question: http://stackoverflow.com/q/47936365
tags question: http://stackoverflow.com/q/47979164
tags question: http://stackoverflow.com/q/47959640
tags question: http://stackoverflow.com/q/47920789

http://stackoverflow.com/comment/107646792
has text: If that still doesn't work, you may need to run this: `curl https://raw.githubusercontent.com/Homebrew/homebrew-core/94d572a132a63651739fef1931f540404b7eaa31/Formula/python%402.rb > python@2.rb; brew install python@2.rb`
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/59438131
score: 24

vectorization
tags question: http://stackoverflow.com/q/47890550
tags question: http://stackoverflow.com/q/47963425
tags question: http://stackoverflow.com/q/47914475
tags question: http://stackoverflow.com/q/48013431
tags question: http://stackoverflow.com/q/47954401
tags question: http://stackoverflow.com/q/47994661
tags question: http://stackoverflow.com/q/47920985
tags question: http://stackoverflow.com/q/47993966
tags question: http://stackoverflow.com/q/47954010
tag name: vectorization
type: Tag
tags question: http://stackoverflow.com/q/47916950

http://stackoverflow.com/q/47888784
downvote count: 0
has title: Python: xml.etree.ElementTree destroys xml format
favorite count: 0
possible better answer: http://stackoverflow.com/a/47956840
tagged with: installshield
has answer: http://stackoverflow.com/a/47956840
tagged with: python
has answer: http://stackoverflow.com/a/47891871
tagged with: http://stackoverflow.com/tag/xml
score: 2
type: AnsweredQuestion
upvote count: 2
type: Question
accepted answer: http://stackoverflow.com/a/47891871
tagged with: python-2.7
has body: I'm having an ISM file (InstallShield project) that is formatted as XML. I need to change some attributes in the file, so I used xml.etree.ElementTree (Python Library). I can find the values and change them, however, after saving the file with updated values, I can't open it in InstallShield (I get a general error that file cant be open). When I compare the old file with the new one, I see that beside the values I changed, some lines are simply missing from new XML and in some line the tags name had changed. Why does it happen? Is there anything to do to make the file stay exactly as it was except for the changes I've made? Should I use other tool to make the change? For example, the following section appears in original XML: &lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt; &lt;?xml-stylesheet type="text/xsl" href="is.xsl" ?&gt; &lt;!DOCTYPE msi [ &lt;!ELEMENT msi (summary,table*)&gt; &lt;!ATTLIST msi version CDATA #REQUIRED&gt; &lt;!ATTLIST msi xmlns:dt CDATA #IMPLIED codepage CDATA #IMPLIED compression (MSZIP|LZX|none) "LZX"&gt; &lt;!ELEMENT summary (codepage?,title?,subject?,author?,keywords?,comments?, template,lastauthor?,revnumber,lastprinted?, createdtm?,lastsavedtm?,pagecount,wordcount, charcount?,appname?,security?)&gt; &lt;!ELEMENT codepage (#PCDATA)&gt; &lt;!ELEMENT title (#PCDATA)&gt; &lt;!ELEMENT subject (#PCDATA)&gt; &lt;!ELEMENT author (#PCDATA)&gt; &lt;!ELEMENT keywords (#PCDATA)&gt; &lt;!ELEMENT comments (#PCDATA)&gt; &lt;!ELEMENT template (#PCDATA)&gt; &lt;!ELEMENT lastauthor (#PCDATA)&gt; &lt;!ELEMENT revnumber (#PCDATA)&gt; &lt;!ELEMENT lastprinted (#PCDATA)&gt; &lt;!ELEMENT createdtm (#PCDATA)&gt; &lt;!ELEMENT lastsavedtm (#PCDATA)&gt; &lt;!ELEMENT pagecount (#PCDATA)&gt; &lt;!ELEMENT wordcount (#PCDATA)&gt; &lt;!ELEMENT charcount (#PCDATA)&gt; &lt;!ELEMENT appname (#PCDATA)&gt; &lt;!ELEMENT security (#PCDATA)&gt; &lt;!ELEMENT table (col+,row*)&gt; &lt;!ATTLIST table name CDATA #REQUIRED&gt; &lt;!ELEMENT col (#PCDATA)&gt; &lt;!ATTLI…
answer count: 2

http://stackoverflow.com/comment/82825975
has text: Copy the formatted text `HTML` of that concerned `WebElement` within the new question for our reference.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47925805
type: Comment

http://stackoverflow.com/comment/82899310
score: 0
comment on: http://stackoverflow.com/q/47964783
type: Comment
type: QuestionComment
has text: @Galen I see it now. 11 in binary is `1011`, and `00001011` is the first half of the number, 90 is `1011010` and `01011010` is the second half. So it seems as if they want to convert numbers in a list to binary, add 0's to the front until each is 8 bits long, then append them together.

http://stackoverflow.com/comment/82707945
comment on: http://stackoverflow.com/q/47871104
type: QuestionComment
type: Comment
score: 1
has text: @Wen Perfect, I had the feeling it would be as simple as that.

http://stackoverflow.com/a/47984997
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47984939
has body: If your Date column holds those date strings, try this: MS['date'] = pd.to_datetime(MS['date'])

http://stackoverflow.com/q/47890665
tagged with: dataframe
tagged with: pandas
has body: I am currently working on a project where I have to measure someones activity over time on a site, based on whether they edit a site. I have a data frame that looks similar to this: df = pd.DataFrame({"x":["a", "b", "c", "b","b"], "y":["red", "blue", "green", "yellow","red"], "z":[1,2,3,4,5]}) I want to add a column to the dataframe such that it counts the number of repeated values (number of edits, which is column x) there are, using the "z" column as the measure of when the events happened. E.g. to have an additional column of: df["activity"] = pd.Series([1,1,1,2,3]) How would I best go about this in Python? Not sure what my best approach here is.
answer count: 1
has comment: http://stackoverflow.com/comment/82748052
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/47890899
has comment: http://stackoverflow.com/comment/82748227
upvote count: 1
tagged with: python
has title: Sequentially counting repeated entries
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/82748036
has comment: http://stackoverflow.com/comment/82747944
accepted answer: http://stackoverflow.com/a/47890899
has comment: http://stackoverflow.com/comment/82747693
type: Question
has comment: http://stackoverflow.com/comment/82747713
has comment: http://stackoverflow.com/comment/82747695
has comment: http://stackoverflow.com/comment/82748156

http://stackoverflow.com/comment/82808864
score: 0
type: Comment
type: QuestionComment
has text: Thanks! I wanted to check if a general Trie does this in O(M) time?
comment on: http://stackoverflow.com/q/47919655

http://stackoverflow.com/q/47988849
tagged with: geopandas
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/47991016
favorite count: 0
has title: split lines based on names
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: geolocation
upvote count: 1
has comment: http://stackoverflow.com/comment/82947794
type: Question
linked to: http://stackoverflow.com/q/47972049
has comment: http://stackoverflow.com/comment/82948700
has body: I have a GeoPandas Dataframe, created from a shapefile object. However, certian line have the same name but are at very different places. I want to have a unique name for each line ! Therefore, I need to somehow split the line, if they are geometrically apart and rename them. One could try to compute the distances between all street chunks and regroup them if they are close by. The computation of the distance can easily be done in Geopandas: Distance Between Linestring Geopandas A set of lines to try: from shapely.geometry import Point, LineString import geopandas as gpd line1 = LineString([ Point(0, 0), Point(0, 1), Point(1, 1), Point(1, 2), Point(3, 3), Point(5, 6), ]) line2 = LineString([ Point(5, 3), Point(5, 5), Point(9, 5), Point(10, 7), Point(11, 8), Point(12, 12), ]) line3 = LineString([ Point(9, 10), Point(10, 14), Point(11, 12), Point(12, 15), ]) df = gpd.GeoDataFrame( data={'name': ['A', 'A', 'A']}, geometry=[line1, line2, line3] )
has answer: http://stackoverflow.com/a/47991016
has comment: http://stackoverflow.com/comment/82948455
tagged with: pandas
has comment: http://stackoverflow.com/comment/82950289

http://stackoverflow.com/a/47940736
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47940391
type: Answer
has comment: http://stackoverflow.com/comment/82850941
score: 1
has body: I think you can use the difflib lib to accomplish what your are trying. Sample Code import difflib n = [(('Bild', 'mild'), ('bitte', 'Bitte'), ('bitte', 'bitten'), ('Bitte', 'Mitte'), ('Fahne', 'ahne'), ('Schlange', 'Schlangen'), ('windet','wendet'), ('sprich', 'sprach'), ('ob', 'Bob'), ('weiße', 'weise'), ('Heidi', 'Hilde'), ('aktiv', 'aktiv'), ('wild', 'Wind'), ('schlagen', 'Schlangen'), ('Küche', 'Mücke'), ('Rücken', 'Küken'), ('Eleonore', 'Elefant'))] for i in n[0]: diff = difflib.ndiff(i[0], i[1]) a, s = 0, 0 for j in diff: if j.startswith('-'): s += 1 if j.startswith('+'): a += 1 if a &gt; 1 or s &gt; 1: print "Edit more that 1", i else: print "Only One Edit", i
has comment: http://stackoverflow.com/comment/82851083
upvote count: 1
answers question: http://stackoverflow.com/q/47940391

http://stackoverflow.com/comment/82734748
comment on: http://stackoverflow.com/q/47883593
type: Comment
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/161514/discussion-between-evan-rosica-and-creyd).
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82992797
comment on: http://stackoverflow.com/q/48011891
has text: No, you need to have pre-built spark present on your system and have the environment variable: SPARK_HOME set to that directory. You might also need to set HADOOP_HOME if you are doing read operations from spark. Follow this to do it: https://stackoverflow.com/questions/35652665/java-io-ioexception-could-not-locate-executable-null-bin-winutils-exe-in-the-ha
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47996929
type: Question
has title: Animating axes size and 2 sequential animations in python and matplotlib
has answer: http://stackoverflow.com/a/48021041
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/82970099
answer count: 1
has body: I am teaching myself python math animation so I don't even know if what I'm asking is possible with matplotlib. What I want is (1)for the axes to start off small then expand. After this, I want it to (2) plot two lines sequentially (one after the other) rather than concurrently (at the same time) which is what it is doing. My code is below except for my attempts to expand the axes (at best my attempts didn't crash python). import time import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation #from matplotlib.animation import FuncAnimation maxsize = 8 size = 1 fig = plt.figure(figsize=(maxsize, maxsize)) # fig will start at "size" if I ever figure out the animation xmin = -10 xmax = 10 ymin = -10 ymax = 10 ax = plt.axes(xlim=(xmin, xmax), ylim=(ymin, ymax)) plt.axhline(linewidth=3, color='black') plt.axvline(linewidth=3, color='black') line, = ax.plot([], [], lw=2) def init1(): line.set_data([], []) return line, def animate1(i): x1 = np.linspace(-10, i/5 - 10, 1000) y1 = -1*x1 line.set_data(x1, y1) return line, def init2(): line.set_data([], []) return line, def animate2(j): x2 = np.linspace(0, j/10, 1000) y2 = 2*x2 line.set_data(x2, y2) return line, plt.grid() plt.xticks(np.arange(xmin, xmax+1, 1.0)) plt.yticks(np.arange(ymin, ymax+1, 1.0)) anim1 = animation.FuncAnimation(fig, animate1, init_func=init1, frames=100, interval=20, blit=True) plt.plot() plt.show() time.sleep(1) anim2 = animation.FuncAnimation(fig, animate2, init_func=init2, frames=100, interval=20, blit=True) plt.plot() plt.show() So I guess my questions are: Is what I want to do possible in matplotlib? One? The other? Both? If so, how do I do it.
has comment: http://stackoverflow.com/comment/82988322
tagged with: animation
tagged with: python
score: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/82865628
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47946875
type: Comment
has text: Yes. Suppose it s called 'termination_alarm'

concurrency
tag name: concurrency
tags question: http://stackoverflow.com/q/47965355
tags question: http://stackoverflow.com/q/47997812
tags question: http://stackoverflow.com/q/47914176
tags question: http://stackoverflow.com/q/47899453
type: Tag
tags question: http://stackoverflow.com/q/47860892
tags question: http://stackoverflow.com/q/47963205
tags question: http://stackoverflow.com/q/47897457

http://stackoverflow.com/a/47973190
accepted answer of: http://stackoverflow.com/q/47973173
has body: guess is a string. You need to do conversion of the string and handle error conditions. int() will convert a string to an integer, but it will throw an exception if the string is not purely numbers.
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/47973173
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/a/47941278
has comment: http://stackoverflow.com/comment/82851949
score: -1
has comment: http://stackoverflow.com/comment/82856036
downvote count: 1
accepted answer of: http://stackoverflow.com/q/47941234
type: Answer
answers question: http://stackoverflow.com/q/47941234
upvote count: 0
has comment: http://stackoverflow.com/comment/82851906
has body: You need to modify your query. Currently you are comparing timestamp with string date_obj which is why postgreSQL is throwing you error, since it cannot compare timestamp with string. Use string formatting to pass your date_obj in query: cur.execute(""" SELECT event_id, timestamp FROM event_tbl WHERE timestamp &lt; %s ORDER BY timestamp LIMIT 25 """, (date_obj,))` According to docs, as mentioned in the comments below, the previous revision of an answer could cause SQL injections, so be aware of using string formatting, and use the API correctly.
type: AcceptedAnswer

http://stackoverflow.com/a/48043233
score: 0
type: Answer
has body: @Igor, thanks by the tip of use config_base. I created this code based on: configHandle = wx.Config(CONFIG_FILE) # Sweep all elements in `self()` to find the grafical ones # instance of the wxPython and salve the specific configuration. for wxElement_name, wxElement_handle in self.__dict__.items(): # Each wxPython object have a specific parameter value # to be saved and restored in the software initialization. if isinstance(wxElement_handle, wx._core.TextCtrl): configHandle.Write(wxElement_name, wxElement_handle.GetValue() ) elif isinstance(wxElement_handle, wx._core.CheckBox): configHandle.Write(wxElement_name, ('True' if wxElement_handle.GetValue() else 'False') ) elif isinstance(wxElement_handle, wx._core.SpinCtrl): configHandle.Write(wxElement_name, str(wxElement_handle.GetValue()) ) . . . To restore I use the reverse logic of this code.
accepted answer of: http://stackoverflow.com/q/47971928
answers question: http://stackoverflow.com/q/47971928
type: AcceptedAnswer

typing
tags question: http://stackoverflow.com/q/47977251
tag name: typing
type: Tag

http://stackoverflow.com/comment/82971944
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48001444
has text: `kill -9` should be the last resort. Try `kill -15 $pid` first. Good luck to all.
type: Comment

http://stackoverflow.com/comment/82903194
has text: Thanks so much. Even if I do that, I get "TypeError: 'float' object is not callable". Please see the edits in my question.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47966728
score: 0

http://stackoverflow.com/comment/82899293
has text: No, that's it - your two options are a `lambda`, limited to a single expression, or a regular function.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47964796
score: 7

http://stackoverflow.com/q/48002051
tagged with: python
score: 11
upvote count: 11
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52600360
tagged with: parquet
tagged with: pyarrow
has answer: http://stackoverflow.com/a/52600360
has body: I have a somewhat large (~20 GB) partitioned dataset in parquet format. I would like to read specific partitions from the dataset using pyarrow. I thought I could accomplish this with pyarrow.parquet.ParquetDataset, but that doesn't seem to be the case. Here is a small example to illustrate what I want. To create a random dataset: from collections import OrderedDict from itertools import product, chain from uuid import uuid4 import os from glob import glob import numpy as np import pandas as pd import pyarrow as pa from pyarrow.parquet import ParquetWriter, ParquetDataset def get_partitions(basepath, partitions): """Generate directory hierarchy for a paritioned dataset data ├── part1=foo │ └── part2=True ├── part1=foo │ └── part2=False ├── part1=bar │ └── part2=True └── part1=bar └── part2=False """ path_tmpl = '/'.join(['{}={}'] * len(partitions)) # part=value path_tmpl = '{}/{}'.format(basepath, path_tmpl) # part1=val/part2=val parts = [product([part], vals) for part, vals in partitions.items()] parts = [i for i in product(*parts)] return [path_tmpl.format(*tuple(chain.from_iterable(i))) for i in parts] partitions = OrderedDict(part1=['foo', 'bar'], part2=[True, False]) parts = get_partitions('data', partitions) for part in parts: # 3 columns, 5 rows data = [pa.array(np.random.rand(5)) for i in range(3)] table = pa.Table.from_arrays(data, ['a', 'b', 'c']) os.makedirs(part, exist_ok=True) out = ParquetWriter('{}/{}.parquet'.format(part, uuid4()), table.schema, flavor='spark') out.write_table(table) out.close() I want to read all values for partition one, and only True for partition 2. With pandas.read_parquet, that's not possible, I have to read the whole column always. I tried the following with pyarrow: parts2 = OrderedDict(part1=['foo', 'bar'], part2=[True]) parts2 = get_partitions('data', parts2) files = [glob('{}/*'.format(dirpath)) for dirpath in parts2] files = [i for i in chain.from_iterable(files)] df2 = ParquetDataset(files).read().to_pandas() That doesn'…
type: Question
tagged with: apache-arrow
has answer: http://stackoverflow.com/a/48012659
answer count: 2
downvote count: 0
has title: Reading specific partitions from a partitioned parquet dataset with pyarrow
favorite count: 0
accepted answer: http://stackoverflow.com/a/48012659

http://stackoverflow.com/q/47948939
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/82867985
upvote count: 0
score: -2
has answer: http://stackoverflow.com/a/47948958
has answer: http://stackoverflow.com/a/47949032
favorite count: 0
tagged with: statistics
possible better answer: http://stackoverflow.com/a/47948958
has comment: http://stackoverflow.com/comment/82867916
has comment: http://stackoverflow.com/comment/82867949
tagged with: python
has comment: http://stackoverflow.com/comment/82867911
has comment: http://stackoverflow.com/comment/82867970
downvote count: 2
accepted answer: http://stackoverflow.com/a/47949032
has body: Say N=150 and I have steps=100. I want a function that will make 100 (or any number I choose) entries to an array, that are increasing at some rate I can set and they all sum to N. Ideally i would set a min and max. Examples: min=1, max=4 distributed_array = [1, 1.1, 1.2, 1.3 ... 3.9, 4] np.sum(distributed_array) = 150
type: Question
type: AnsweredQuestion
has title: How to distribute increasing numbers across range and ensure they sum to N?

http://stackoverflow.com/comment/82757530
score: 1
type: AnswerComment
type: Comment
has text: Great analysis. If you have a moment, could you add this information to the [scipy issue that @rfire created](https://github.com/scipy/scipy/issues/8235)?
comment on: http://stackoverflow.com/a/47895342

http://stackoverflow.com/comment/82765078
comment on: http://stackoverflow.com/q/47897402
type: QuestionComment
type: Comment
score: 1
has text: Python running new Python instances is almost always an antipattern in its own right. Can you `import` the modules you are running and call them in-line?

http://stackoverflow.com/comment/82872302
type: Comment
type: QuestionComment
has text: post the route code, all the thing we might need to re-build the error you are getting. by the code you have pasted, `/input` is the route should throw error's. so show us some more of the code.
comment on: http://stackoverflow.com/q/47950320
score: 0

http://stackoverflow.com/a/47934068
has body: for key, value in characters.iteritems(): Reason is that you only get the keys if you iterate over a dict. You need to explicitly iterate over items() or iteritems() (the later using less memory in general) &gt;&gt;&gt; d=dict(a=1, b=2) &gt;&gt;&gt; d {'a': 1, 'b': 2} &gt;&gt;&gt; [x for x in d] ['a', 'b'] &gt;&gt;&gt; [x for x in d.iteritems()] [('a', 1), ('b', 2)] &gt;&gt;&gt; [x for x in d.items()] [('a', 1), ('b', 2)] Note how iteritems and items are tuples and the straight iteration over a dictionary is not? You can learn more at https://www.python-course.eu/dictionaries.php Or straight from the source https://docs.python.org/2/library/stdtypes.html#dict
has comment: http://stackoverflow.com/comment/82837683
has comment: http://stackoverflow.com/comment/82837928
has comment: http://stackoverflow.com/comment/82837613
answers question: http://stackoverflow.com/q/47933978
score: 0
type: Answer

http://stackoverflow.com/q/47860237
tagged with: tensorflow
type: Question
tagged with: matrix-multiplication
tagged with: attributeerror
score: 4
upvote count: 4
answer count: 1
has answer: http://stackoverflow.com/a/47878440
downvote count: 0
has body: I am trying to us tensorflow operations within a keras model and I am quite confused about the mechanism and what Lambda layers do to tf tensors. So this works: a = keras.layers.Input(shape=[1, 2], dtype='float', name='a') s= keras.layers.Lambda(lambda x: tf.transpose(tf.transpose(x)))(a) model = keras.models.Model(inputs=a, outputs=s) but this does not work: a = keras.layers.Input(shape=[1, 2], dtype='float', name='a') s = tf.transpose(tf.transpose(a)) s = keras.layers.Lambda(lambda x: x)(s) model = keras.models.Model(inputs=a, outputs=s) and it says: AttributeError: 'Tensor' object has no attribute '_keras_history' so is it always necessary to pack up tf operations within a layer? Question 2 (was why I came up the previous one): do we have to pack with a custom layer to do matrix multiplication in keras? thanks.
tagged with: keras
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: how to use tf operations in keras models

http://stackoverflow.com/q/47948233
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/19255832
has comment: http://stackoverflow.com/comment/82867188
has comment: http://stackoverflow.com/comment/82866767
tagged with: utf-8
has body: I am trying to convert Arabic text to utf8 encoded bytes then to binary by using this answer here. First, I used the code as it is in the example: '{:b}'.format(int(u'سلام'.encode('utf-8').encode('hex'), 16)) But I got this error: AttributeError: 'bytes' object has no attribute 'encode' Also I removed .encode('hex') but still gives the same error. Is there any way to convert utf8 codes to binary and vise versa?
favorite count: 0
has comment: http://stackoverflow.com/comment/82866866
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82866484
tagged with: python
type: AnsweredQuestion
has title: Converting Unicode to Binary
has answer: http://stackoverflow.com/a/47948854
has comment: http://stackoverflow.com/comment/82866958
linked to: http://stackoverflow.com/q/8815592
type: Question
has comment: http://stackoverflow.com/comment/82866819
score: 4
upvote count: 4
accepted answer: http://stackoverflow.com/a/47948854
has comment: http://stackoverflow.com/comment/82866970

http://stackoverflow.com/comment/82849196
comment on: http://stackoverflow.com/a/47938595
score: 0
type: AnswerComment
has text: You need to index by the condition on the `t` that you used to calculate the values, not some other `t`.
type: Comment

http://stackoverflow.com/comment/82908888
has text: @Jason : No experience of using logging...any clue how can i use it with my code ?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47969034

http://stackoverflow.com/a/48009144
has body: Here it is: &gt;&gt;&gt; re.findall(r"(\[\w*\]\w+)",s) ['[aaa]foo', '[bbb]bar', '[ccc]foobar'] Explanation: parenthesis means the group to search. Witch group: it should start by a braked \[ followed by some letters \w then the matched braked braked \] followed by more letters \w Notice you should to escape braked with \.
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48009046
downvote count: 0

http://stackoverflow.com/q/47997537
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/47997611
tagged with: mixins
downvote count: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/47997611
tagged with: python
has body: I am trying to inject a mixin to a class with a decorator. When the code runs the class no longer has a dict property even though the dir(instance) says it has one. I'm not sure where the property is disappearing. Is there a way that I can get dict or otherwise find the instance's attributes? def testDecorator(cls): return type(cls.__name__, (Mixin,) + cls.__bases__, dict(cls.__dict__)) class Mixin: pass @testDecorator class dummyClass: def __init__(self): self.testVar1 = 'test' self.testVar2 = 3.14 inst = dummyClass() print(dir(inst)) print(inst.__dict__) This code works if the decorator is commented out yet causes an error when the decorator is present. Running on python 3.5.1
tagged with: python-decorators
has title: Python object losing __dict__ after mixin injection
type: AnsweredQuestion
tagged with: oop

http://stackoverflow.com/q/47965083
score: 10
upvote count: 10
type: Question
has answer: http://stackoverflow.com/a/47970232
answer count: 1
downvote count: 0
favorite count: 0
has body: I'm trying to create a generic class to express that a value has lower and upper bounds, and to enforce those bounds. from typing import Any, Optional, TypeVar T = TypeVar("T") class Bounded(object): def __init__(self, minValue: T, maxValue: T) -> None: assert minValue <= maxValue self.__minValue = minValue self.__maxValue = maxValue However, mypy complains that: error: Unsupported left operand type for <= ("T") Apparently typing module doesn't allow me to express this (although it looks like adding Comparable might happen in the future). I think it would be enough to check that object has __eq__ and __lt__ methods (for my use case at least). Is there any way to currently express this requirement in Python so that Mypy would understand it?
tagged with: python
tagged with: python-typing
accepted answer: http://stackoverflow.com/a/47970232
tagged with: mypy
type: AnsweredQuestion
has title: Comparable types with mypy

http://stackoverflow.com/q/47989980
type: Question
score: 0
has title: MySQL : rename primary key column which is foregin key to another table
answer count: 2
has answer: http://stackoverflow.com/a/47990160
has body: I have a 2 table in mysql databse: Personnel: personnel_id (PK) name age qualification: qualification_id (PK) personnel_id (FK) clg name schl name How can I rename a PK of personnel table(personnel_id)? As it is serving as Fk of qualification table, while i rename that personnel_id I'm facing issue like: "Cannot change column 'personnel_id': used in a foreign key constraint 'qualification_ibfk_1' of table 'mobilemeta.qualification" A possible way that I know is: Drop FK, Rename Column, Add FK But I'm handling these database operations using python. So it is not possible to find to which table it is referenced as the foreign key, is there any way to handle it dynamically? Any solutions?
tagged with: python
has comment: http://stackoverflow.com/comment/82948552
has comment: http://stackoverflow.com/comment/82948367
type: UnansweredQuestion
tagged with: mysql
has answer: http://stackoverflow.com/a/47990064
has comment: http://stackoverflow.com/comment/82948930
has comment: http://stackoverflow.com/comment/82949832

http://stackoverflow.com/comment/82995248
type: Comment
type: QuestionComment
has text: `browser.refresh()` doesn't affect the result (I tried after `browser.get("https://canihazip.com/s")`and also just after `mybrowser.set_new_ip()` ).
score: 0
comment on: http://stackoverflow.com/q/47969563

http://stackoverflow.com/comment/82691518
has text: but then would I not have to assume that the input given to me was a numpy matrix? I currently don't want to make any assumptions about the input and want to be able to handle an arbitrary input.
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47863243

http://stackoverflow.com/q/47889310
answer count: 4
upvote count: 1
has title: Prisoner's Dilemma in Python
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/47889397
has answer: http://stackoverflow.com/a/47889410
has comment: http://stackoverflow.com/comment/82744981
score: 0
has comment: http://stackoverflow.com/comment/82744887
has answer: http://stackoverflow.com/a/47889409
favorite count: 0
type: UnansweredQuestion
has body: At school in my CSE class, I'm working on an optional project, which is code a version of Prisoner's Dilemma into Python. This is my code. When i run it, it starts to work, then once it hits the if statements, it returns with the error, 'TypeError: 'bool' object is not iterable. How do I fix this? import random def ipd_start(): print("Welcome to Prisoner's Dilemma. \n If you don't know what Game Theory is, you're in the wrong place. \n \n Enter Collude to collude, or Betray to betray.") round_one() def round_one(): answer=(input("You and a buddy got caught commiting a crime. Do you keep quiet, or rat on your best friend? \n ")) a = ["Collude", "Betray"] G = random.choice(a) print("You chose " + answer + ", and your partner chose " + G + ". ") if all(G == "Collude" and answer==("Collude")): both_free() if all(G == 'Collude' and answer==('Betray')): you_free() if all(G == 'Betray' and answer=='Betray'): both_jail if all(G == 'Betray' and answer=='Collude'): you_jail
tagged with: python
has answer: http://stackoverflow.com/a/47889390

http://stackoverflow.com/a/49765709
has body: You have to run it once by using shortcut key shift+ctrl p, and type "Python run all unit tests". It won't show up in the editor until it was successfully executed at least once or use the discover unit test method. However one thing catch me many times is that the Python file has to be a valid Python file. The intellisense in VS Code for Python is not complex(compare to Javascript or Typescript), and it won't highlight any syntax error. You can verify that by force it to run all unit test and observe the Python Test Log window.
has comment: http://stackoverflow.com/comment/129358262
answers question: http://stackoverflow.com/q/47960521
type: Answer
downvote count: 3
upvote count: 21
score: 18

http://stackoverflow.com/a/48008192
has comment: http://stackoverflow.com/comment/82985134
has comment: http://stackoverflow.com/comment/82984805
score: 9
has comment: http://stackoverflow.com/comment/82990041
has comment: http://stackoverflow.com/comment/82984867
has body: TL;DR This is debattedly a bug in eval. See the open github issue GH16289. Why am I getting this error? This is because pd.eval cannot parse series with more than 100 rows. Here's an example. len(s) 300000 pd.eval(s.head(100)) # returns a parsed result Whereas, pd.eval(s.head(101)) AttributeError: 'PandasExprVisitor' object has no attribute 'visit_Ellipsis' This issue persists, regardless of the parser or the engine. What does this error mean? pd.eval operates on the __repr__ of the Series, rather than the objects contained within it (which is the cause of this bug). The __repr__ truncated rows, replacing them with a ... (ellipsis). This ellipsis is misinterpreted by the engine as an Ellipsis object - ... Ellipsis pd.eval('...') AttributeError: 'PandasExprVisitor' object has no attribute 'visit_Ellipsis' pd.eval technically is not supposed to parse series of strings (the documentation mentioned it is meant to receive strings) and (as described by the accepted answer) will try to make a reasonable guess at the result instead of rejecting the input outright. Whether this is intended behavior or incomplete behavior (a lot of pandas methods operate differently based on the input - and eval could work on a series by mapping itself onto each row, which is how I initially assumed this was working anyway) is up for discussion, since there's an open issue tracking this. What can I do to make this to work? Right now, there isn't a solution (the issue is still open as of 12/28/2017), however, there are a couple of workarounds. Option 1 ast.literal_eval This option should work out of the box if you can guarantee that you do not have any malformed strings. from ast import literal_eval s.apply(literal_eval) 0 [133, 115, 3, 1] 1 [114, 115, 2, 3] 2 [51, 59, 1, 1] dtype: object If there is a possibility of malformed data, you'll need to write a little error handling code. You can do that with a function - def safe_parse(x): try: return literal_eval(x) except (SyntaxError, ValueError…
answers question: http://stackoverflow.com/q/48008191
has comment: http://stackoverflow.com/comment/82984766
upvote count: 9
type: Answer
has comment: http://stackoverflow.com/comment/82990093
has comment: http://stackoverflow.com/comment/82986262
has comment: http://stackoverflow.com/comment/82987648
downvote count: 0

http://stackoverflow.com/q/47956527
tagged with: python
downvote count: 4
score: 6
has title: How do websites detect bots?
tagged with: web-scraping
type: Question
type: AnsweredQuestion
tagged with: bots
has answer: http://stackoverflow.com/a/47956652
accepted answer: http://stackoverflow.com/a/47956652
answer count: 1
tagged with: web
favorite count: 0
has comment: http://stackoverflow.com/comment/82882546
has body: I am learning python and i am currently scraping reddit. Somehow reddit has figured out that I am a bot (which my software actually is) but how do they know that? And how we trick them into thinking that we are normal users. I found practical solution for that, but I am asking for bit more in depth theoretical understanding.
upvote count: 10

http://stackoverflow.com/comment/82884043
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47957305
has text: What's up with the inconsistent order? (Why `[ 1. 0. ]` and why `[ 14. 15. ]`?)

http://stackoverflow.com/a/47986474
has comment: http://stackoverflow.com/comment/82942806
type: Answer
has body: I hardly know pandas but the numpy side of the operation can be done like so (on Python 3; use 'S1' in place of 'U1' on Python 2): npchrs = df.values.astype(str).view('U1') # array([['A', 'A', 'V', 'F', 'D', '', '', '', '', '', '', '', '', '', ''], # ['T', 'Y', 'U', '?', 'W', '_', 'Z', '', '', '', '', '', '', '', ''], # ['S', 'o', 'm', 'e', 'O', 't', 'h', 'e', 'r', 'S', 't', 'r', 'i', 'n', 'g'], # ['E', 'T', 'C', '.', '', '', '', '', '', '', '', '', '', '', '']], # dtype='&lt;U1') If you are ok with empty strings instead of Nones or if replacing them in pandas is easy, you can convert this back to df and be done. According to @COLDSPEED's timings the following step is slow, so it'd be better if you could avoid it. If not: npobjs = npchrs.astype(object) npobjs[npobjs==''] = None # array([['A', 'A', 'V', 'F', 'D', None, None, None, None, None, None, None, # None, None, None], # ['T', 'Y', 'U', '?', 'W', '_', 'Z', None, None, None, None, None, # None, None, None], # ['S', 'o', 'm', 'e', 'O', 't', 'h', 'e', 'r', 'S', 't', 'r', 'i', 'n', 'g'], # ['E', 'T', 'C', '.', None, None, None, None, None, None, None, None, # None, None, None]], dtype=object)
has comment: http://stackoverflow.com/comment/82942173
upvote count: 2
has comment: http://stackoverflow.com/comment/82942112
has comment: http://stackoverflow.com/comment/82943472
score: 2
has comment: http://stackoverflow.com/comment/82942203
has comment: http://stackoverflow.com/comment/82942685
has comment: http://stackoverflow.com/comment/82943279
has comment: http://stackoverflow.com/comment/82942721
has comment: http://stackoverflow.com/comment/82943028
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47986305
answers question: http://stackoverflow.com/q/47986305
has comment: http://stackoverflow.com/comment/82942864

http://stackoverflow.com/q/47977846
type: Question
has answer: http://stackoverflow.com/a/71646927
upvote count: 1
has title: AttributeError: 'NoneType' object has no attribute 'encode' while writing into file?
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/47977922
has body: I want to scrape new content and write it into a file but it is giving 'NoneType' object has no attribute 'encode' #!/usr/bin/python # -*- coding: utf-8 -*- import urllib2 as urllib from bs4 import BeautifulSoup import codecs link = 'http://www.hindustantimes.com/delhi-news/delhi-man-shoots- girlfriend-in-leg-after-argument-blames-snatchers/story- CzA8JmgafX7tNUroilovoO.html' reqlink = urllib.Request(link) page = urllib.urlopen(reqlink) soup = BeautifulSoup(page,'html.parser') fw = codecs.open('hlink7.txt','w') var = soup.findAll('p') for i in var: fw.write(i.string.encode('utf-8')) how to resolve it?
answer count: 3
tagged with: web-scraping
tagged with: python
accepted answer: http://stackoverflow.com/a/47977939
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47977922
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/82924512
has answer: http://stackoverflow.com/a/47977939

http://stackoverflow.com/q/48003370
duplicate of: http://stackoverflow.com/q/3099987
score: -1
tagged with: alphabet
type: Question
answer count: 2
has body: Having an alphabet of letters A-Z and numbers 0-9, how to get all 1296 possible combinations like: ['AA', 'AB', ..., 'AZ', 'A0', 'A1', ..., 'Z9', '0A', '0B', ..., '98', '99'] As a side question, what is this type of number system called?
upvote count: 0
has comment: http://stackoverflow.com/comment/82979312
has answer: http://stackoverflow.com/a/48015081
tagged with: python
tagged with: number-systems
favorite count: 0
type: UnansweredQuestion
tagged with: cartesian-product
has title: How to calculate all possible combinations of two alphanumeric characters?
has answer: http://stackoverflow.com/a/48003707
downvote count: 1
tagged with: combinations

http://stackoverflow.com/q/48006939
type: Question
tagged with: python
has body: I'm porting the tests of a Flask application from unittest to pytest. For tests that need a database I added a fixture that returns a DB session The DB is an SQLAlchemy object that runs a PostgreSQL database import pytest from app import create_app, db from app.models import Project, Client @pytest.fixture(scope='function') def db_session(): app = create_app('testing') app_context = app.app_context() app_context.push() db.create_all() yield db.session db.session.remove() db.drop_all() app_context.pop() def test_getJson_withOneProjectSet_returnsBasicClientJson(db_session): testClient = Client() db_session.add(testClient) testProject = Project() db_session.add(testProject) testClient.projects.append(testProject) db_session.commit() clientJson = testClient.getJson() assert len(clientJson['projects']) == 1 def test_getJson_withThreeProjectsSet_returnsBasicClientJson(db_session): testClient = Client() db_session.add(testClient) testProject1 = Project() db_session.add(testProject1) testProject2 = Project() db_session.add(testProject2) testProject3 = Project() db_session.add(testProject3) testClient.projects.append(testProject1) testClient.projects.append(testProject2) testClient.projects.append(testProject3) db_session.commit() clientJson = testClient.getJson() assert len(clientJson['projects']) == 3 When running the tests, the first one passes but the second one returns an integrity error: sqlalchemy.exc.IntegrityError: (psycopg2.IntegrityError) duplicate key value violates unique constraint "project_code_key" Apparently the DB is not cleaned up after finishing a test-function The fixture is a port from a working unittest setup/teardown function that has no problems with integrity errors: # def setUp(self): # self.app = create_app('testing') # self.app_context = self.app.app_context() # self.app_context.push() # db.create_all() # # def tearDown(self): # db.session.remove() # db.drop_all() # self.app_context.pop()
upvote count: 2
answer count: 1
has title: Integrity error in pytest Flask-SQLAlchemy session
tagged with: pytest
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/64208832
score: 2
downvote count: 0
tagged with: flask
tagged with: flask-sqlalchemy
favorite count: 0
tagged with: postgresql

http://stackoverflow.com/comment/82869317
has text: It looks like you almost have it. What's the trouble?
type: Comment
comment on: http://stackoverflow.com/q/47949810
type: QuestionComment
score: 0

http://stackoverflow.com/q/47971514
type: Question
has body: I am new to using the library Sympy. I am need to extract all coefficients of the characteristic polynomial to be used later. For example, my code is: import sympy as sp M = sp.Matrix([[0, 0, 0, 1, 0, 1], [0, 0, 0, 0, 1, 0], [0, 1, 0, 1, 0, -1], [1, 0, -1, 0, 1, 0], [0, 0, 0, 1, 0, 0], [-1, 0, 1, 0, 0, 0]]) lamda = symbols('lamda') p = M.charpoly(lamda) print(p) print(p.coeffs()) which gives output: PurePoly(lamda**6 + lamda**4 - lamda**2, lamda, domain='ZZ') [1, 1, -1] However, I need [1, 0, 1, 0, 1, 0, 0], which includes the zero coefficients of the lamda too the exponents 4, 3, 1, and 0, terms. I would normally use a for loop to iterate over the equation to see which terms are missing so a zero can be inserted into the appropriate spot in the array of coefficients. However, when I attempted to do so, I received an error saying PurePoly type doesn't support indexing. So, I was wondering if anyone knows how to make sympy include the zeros or a way to do it myself? I need will eventually have to incorporate this code into a loop for lots of matrices so I can't manually do it. Thanks.
tagged with: sympy
downvote count: 0
tagged with: matrix
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47972510
score: 3
has title: Coefficients of Charpoly using Sympy in Python
upvote count: 3

http://stackoverflow.com/comment/82758582
type: QuestionComment
has text: Is the csv from a PC that might have a different locale? It might not be UTF-8 and even though it looks like a comma, it could actually be something else from a different character set. I see this happen with the " from german PCs. I would open the text file in Notepad ++ and double check the encoding.
comment on: http://stackoverflow.com/q/47895825
score: 1
type: Comment

http://stackoverflow.com/comment/82911847
comment on: http://stackoverflow.com/a/47970924
has text: It is quite possible to have a multi-line text field in quotes; you cannot safely assume that each record is only one line (unless your data independently guarantees this).
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48006213
has answer: http://stackoverflow.com/a/48006933
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83034541
tagged with: matrix
tagged with: python
favorite count: 0
linked to: http://stackoverflow.com/q/24591917
upvote count: 2
has comment: http://stackoverflow.com/comment/83012408
accepted answer: http://stackoverflow.com/a/48006933
has comment: http://stackoverflow.com/comment/82983473
tagged with: indexing
type: AnsweredQuestion
score: 2
possible better answer: http://stackoverflow.com/a/48008104
has answer: http://stackoverflow.com/a/48008104
has title: Based on BFS output how to select sparse matrix elements
has body: I am trying to select sparse matrix elements row-wise based on BFS output array. Suppose my BFS output is [1, 2, 3, 6, 4, 7, 5, 8, 11, 9, 12, 10, 13, 15, 14, 16, 17, 18, 19, 20] and I have a sparse matrix of 20x20 for example. Now I want to use BFS output as row index and select nonzero values from the sparse matrix in same order as that of BFS output array and plot. Here is my code through which I can do some job but not perfectly what I wanted. a = numpy.loadtxt('sparsematrix.txt', float, delimiter=',') # import data y = numpy.reshape(a, np.size(a)) pos = np.delete(y, np.arange(0, y.size, 19)) plt.plot(pos) plt.xlabel(sample) plt.ylabel(position) Problem with the above code is: It selects every value in row-wise, but not in defined order of my BFS output. (it should use BFS output array as row index number to select nonzero values one-by-one) It selects all the values, even zeros. - How to get only nonzero values? Indexing is starting from 0 and goes to 19. I want indexing to start from 1 onwards.
linked to: http://stackoverflow.com/q/2397141
type: Question
has comment: http://stackoverflow.com/comment/83152151
has comment: http://stackoverflow.com/comment/83014718
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83047724
has comment: http://stackoverflow.com/comment/83047727

http://stackoverflow.com/a/47978988
type: Answer
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47978929
has body: You are writing a wrong query, and using a wrong operator. If you want to get last 3 of a kind, you should use the slices in Python: last = mpost.objects.all()[-3:] Executing the last = mpost.objects.count(3) will try to count object, not to select ones.
accepted answer of: http://stackoverflow.com/q/47978929

http://stackoverflow.com/comment/82930484
score: 0
type: AnswerComment
has text: As I was saying : What you want to do if you encounter a masked value is up to you. You didn't say anything about that, and/or how to get there.
type: Comment
comment on: http://stackoverflow.com/a/47970482

http://stackoverflow.com/a/47995990
upvote count: 1
score: 1
downvote count: 0
has body: Consider applying a function to each row of the DataFrame: def row_func(row): if row['Atribute'] == 'large': return row['quantity'] etc... df['new_column'] = df.apply(row_func, axis=1)
type: Answer
answers question: http://stackoverflow.com/q/47995848

http://stackoverflow.com/q/47986269
has body: I am using Tensorflow Dataset API to read TFRecords files, but the GPU usage is still low (10%). I reckon the cause is that I preprocess the data before they are fed into the sess.run(). Here is my code below. 1. Create a dataset from 3 separate files. tf.reset_default_graph() # The content of TFRecords files is that each row is an array. Calculate total rows. n_total_row = sum(1 for _ in tf.python_io.tf_record_iterator(epd)) def get_epd_dataset(filename): dataset = tf.data.TFRecordDataset(filename) def _parse_function(example_proto): keys_to_features = {'data':tf.VarLenFeature(tf.int64)} parsed_features = tf.parse_single_example(example_proto, keys_to_features) return tf.sparse_tensor_to_dense(parsed_features['data']) # Parse the record into tensors. dataset = dataset.map(_parse_function) return dataset # There are 3 essential files comprising input data. It reads 3 seperate # files "epd", "y_id", "x_feat" into 3 separate dataset respectively, and # uses `Dataset.zip()` to combine these 3 separate files into 1 dataset. epd_ds = get_epd_dataset(epd) n_lexicon, id_ds = get_id_dataset(y_id) feat_ds = get_feat_dataset(x_feat) data_ds = tf.data.Dataset.zip((feat_ds, epd_ds, id_ds)) # Shuffle the dataset data_ds = data_ds.shuffle(buffer_size=n_total_row, reshuffle_each_iteration=True) # Repeat the input indefinitly data_ds = data_ds.repeat(epoch) # Generate batches data_ds = data_ds.batch(1) # Create a one-shot iterator iterator = data_ds.make_one_shot_iterator() data_iter = iterator.get_next() 2. Build a Tensorflow graph. n_input = DIM*(LEFT+1+RIGHT) n_classes = n_lexicon mlp = MultiLayerPerceptron.MultiLayerPerceptron(DIM*(LEFT+1+RIGHT), n_lexicon) # tf Graph input X = tf.placeholder("float", [None, n_input]) Y = tf.placeholder("float", [None, n_classes]) logits = mlp.multilayer_perceptron(X, dropout_mode) loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y), name='loss_op') optimizer = tf.train.AdamOptimizer(learning_rate=lr) train…
type: UnansweredQuestion
upvote count: 1
tagged with: tensorflow
tagged with: performance
has answer: http://stackoverflow.com/a/49530655
score: 1
type: Question
answer count: 2
downvote count: 0
tagged with: tfrecord
has title: Preprocess the input data slow down the input pipeline when using Tensorflow Dataset API to read TFRecords file
favorite count: 0
has answer: http://stackoverflow.com/a/47995836
tagged with: python

http://stackoverflow.com/comment/117744714
type: Comment
comment on: http://stackoverflow.com/a/48861231
type: AnswerComment
has text: #Respect This is the only solution works for me, speeding up to_sql() of pandas writting on SQL Server. After thounsand of tests with many drivers and configurations... Thank you very much!!!
score: 0

http://stackoverflow.com/comment/82831369
comment on: http://stackoverflow.com/a/47931203
type: AnswerComment
has text: Thanks, it worked. Mistake in my code was - I tried to find the days different first and then changing the period to M.
score: 0
type: Comment

http://stackoverflow.com/comment/82930912
has text: Using loop along with try except may be the correct option?
comment on: http://stackoverflow.com/q/47981207
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48038967
has body: The vocabulary is supposed to be strings but you are adding integers (you are calling str(i) and ignoring the result when you probably mean i = str(i)).
accepted answer of: http://stackoverflow.com/q/48001211
type: Answer
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48001211

http://stackoverflow.com/a/58295830
score: 2
has body: I was looking for a similar issue (unable to import tensorflow in jupyter) and found that maybe most answers are outdated because now conda installs tf in its own environment. The most useful thing I found is: https://docs.anaconda.com/anaconda/user-guide/tasks/tensorflow/ which explains in very few steps how to install tf or tf-gpu in its own environment. Then my problem was that the jupyter notebook is in its own base environment, not in the tf-gpu environment. How to work with that from a jupyter notebook based on the base environment? The solution comes from the very helpful answer from Nihal Sangeeth to this question https://stackoverflow.com/questions/53004311/how-to-add-conda-environment-to-jupyter-lab conda activate tf-gpu (tf-gpu)$ conda install ipykernel (tf-gpu)$ ipython kernel install --user --name=&lt;any_name_you_like_for_kernel&gt; (tf-gpu)$ conda deactivate Close and reopen your jupyter notebook. Then in your jupyter notebook you will find the option, under "kernel" of "change kernel". Change kernel to your newly created kernel and you will be able to import tensorflow as tf and go on from there. Hope it helps somebody
upvote count: 2
answers question: http://stackoverflow.com/q/47892038
type: Answer
downvote count: 0

http://stackoverflow.com/comment/82823258
has text: Traditionally, in a tree, each node only has 1 parent but can have multiple children; what does having multiple parents even mean in this context?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47926068
score: 0

http://stackoverflow.com/comment/82832164
has text: @ScottBoston nice. I didn't know about it.
comment on: http://stackoverflow.com/a/47931354
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/55047565
upvote count: 1
downvote count: 0
type: Answer
score: 1
answers question: http://stackoverflow.com/q/47864074
has body: I am assuming you need all records from left DF and matching records from right DF you can use join condition like below df1.join(df2,[&lt;column name&gt;],'left_outer') please post, if you need more help what will left_outer join returns LEFT OUTER join contains all rows from both tables that meet the WHERE clause criteria, same as an INNER join result set. In addition, any rows from the left table that do not have a matching row that exists in the right table will also be included in the result set.

http://stackoverflow.com/q/47897199
has answer: http://stackoverflow.com/a/47900127
type: Question
answer count: 1
score: 0
has body: I have noticed a strange behavior when I use TensorFlow-GPU + Python multiprocessing. I have implemented a DCGAN with some customizations and my own dataset. Since I am conditioning the DCGAN to certain features, I have training data and also test data for evaluation. Due to the size of my datasets, I have written data loaders that run concurrently and preload into a queue using Python's multiprocessing. The structure of the code roughly looks like this: class ConcurrentLoader: def __init__(self, dataset): ... class DCGAN ... net = DCGAN() training_data = ConcurrentLoader(path_to_training_data) test_data = ConcurrentLoader(path_to_test_data) This code runs fine on TensorFlow-CPU and on TensorFlow-GPU &lt;= 1.3.0 using CUDA 8.0, but when I run the exact same code with TensorFlow-GPU 1.4.1 and CUDA 9 (latest releases of TF &amp; CUDA as of Dec 2017) it crashes: 2017-12-20 01:15:39.524761: E tensorflow/stream_executor/cuda/cuda_blas.cc:366] failed to create cublas handle: CUBLAS_STATUS_NOT_INITIALIZED 2017-12-20 01:15:39.527795: E tensorflow/stream_executor/cuda/cuda_blas.cc:366] failed to create cublas handle: CUBLAS_STATUS_NOT_INITIALIZED 2017-12-20 01:15:39.529548: E tensorflow/stream_executor/cuda/cuda_blas.cc:366] failed to create cublas handle: CUBLAS_STATUS_NOT_INITIALIZED 2017-12-20 01:15:39.535341: E tensorflow/stream_executor/cuda/cuda_dnn.cc:385] could not create cudnn handle: CUDNN_STATUS_INTERNAL_ERROR 2017-12-20 01:15:39.535383: E tensorflow/stream_executor/cuda/cuda_dnn.cc:352] could not destroy cudnn handle: CUDNN_STATUS_BAD_PARAM 2017-12-20 01:15:39.535397: F tensorflow/core/kernels/conv_ops.cc:667] Check failed: stream-&gt;parent()-&gt;GetConvolveAlgorithms( conv_parameters.ShouldIncludeWinogradNonfusedAlgo&lt;T&gt;(), &amp;algorithms) [1] 32299 abort (core dumped) python dcgan.py --mode train --save_path ~/tf_run_dir/test --epochs 1 What really confuses me is that if I just remove test_data the error does not occur. Thus, for some strange reason, Ten…
linked to: http://stackoverflow.com/q/54402154
tagged with: python
favorite count: 0
type: UnansweredQuestion
tagged with: multithreading
upvote count: 1
downvote count: 1
tagged with: tensorflow
tagged with: multiprocessing
has title: Bug when using TensorFlow-GPU + Python multiprocessing?

http://stackoverflow.com/comment/82870039
type: QuestionComment
comment on: http://stackoverflow.com/q/47950107
has text: @UmarAsghar, isnt the context variable the one in bold on my first comment?
score: 0
type: Comment

http://stackoverflow.com/comment/82794653
comment on: http://stackoverflow.com/q/47913278
has text: What is you delete method route? Add your delete method and route.. as per 404 means the route not created
score: 0
type: Comment
type: QuestionComment

postman
tags question: http://stackoverflow.com/q/47936640
tags question: http://stackoverflow.com/q/47874233
tags question: http://stackoverflow.com/q/47884601
tag name: postman
tags question: http://stackoverflow.com/q/47905639
type: Tag

http://stackoverflow.com/comment/82943279
type: AnswerComment
comment on: http://stackoverflow.com/a/47986474
type: Comment
has text: @PaulPanzer Sorry, realised my "Option 2" was exactly your answer, so removed it. Not converting to object makes the solution much faster, and you should mention that.
score: 0

http://stackoverflow.com/comment/82942209
comment on: http://stackoverflow.com/a/47986604
has text: Thank you so much for the answer! Installing Pillow solved part of the problem. The sdl2 part of the error still remains.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/82825579
score: 1
comment on: http://stackoverflow.com/q/47928430
type: Comment
type: QuestionComment
has text: See the Traceback I added

http://stackoverflow.com/comment/83861763
type: Comment
comment on: http://stackoverflow.com/q/47976502
has text: Are you saying that when you add even a test comment then go to the console inside the Cloudformation template tab you do not see the new comment?
score: 0
type: QuestionComment

http://stackoverflow.com/q/47999233
type: Question
score: 0
has title: Assigning string from a csv cell to a variable using pandas/python
has comment: http://stackoverflow.com/comment/82966982
tagged with: pandas
tagged with: variables
tagged with: string
has body: For example, at some point in my csv file there is a cell with the string 'username', which is in say cell b6 (note: this is not a row or column header). 2 cells to the right of this, there is the associated value for the 'username', let's say it is 'Jason', in b8. How can I copy the string 'Jason' and assign it to a variable x for future use? Ideally I would like to bypass having the code interact with excel in any way
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/82973012
answer count: 0
has comment: http://stackoverflow.com/comment/82966981

http://stackoverflow.com/comment/82885567
score: 0
type: Comment
type: QuestionComment
has text: The answer is on the GitHub page you linked to.
comment on: http://stackoverflow.com/q/47958023

http://stackoverflow.com/comment/82912390
comment on: http://stackoverflow.com/q/47971226
score: 0
has text: You shouldn't post the `developerKey` value if that's your real one.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47976802
has body: Your resized_image variable is a tensor as you have initialized it to tf.image.resize_images(image, [272, 272]) ... your feed has to be a numpy array whose shape has to match the tensor x that you have defined in the code For example if in your case x = tf.placeholder(tf.float32, (None, 272, 272, 3)) and then you have to give it bacth of images which has to be of shape (bacth_number, 272, 272, 3) I would suggest you following code for reading the image ... take this code as an example import matplotlib.image as mpimg image = mpimg.imread(path_to_the_image) x = tf.placeholder(tf.float32, (None, 272, 272, 3)) and when running it in the session: sess.run([optimizer], feed_dict={x: image.reshape((1, image.shape[0], image.shape[1], image.shape[2])), y: 1})
has comment: http://stackoverflow.com/comment/82923400
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/83043346
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47976507
answers question: http://stackoverflow.com/q/47976507
type: Answer
has comment: http://stackoverflow.com/comment/82923194

http://stackoverflow.com/comment/82751560
type: Comment
type: AnswerComment
has text: yeah, it was only for illustration purposes. but i'll refrain from doing so even for illustration purposes.
score: 0
comment on: http://stackoverflow.com/a/47892379

http://stackoverflow.com/comment/82822661
type: AnswerComment
score: 0
type: Comment
has text: Well, you might still be able to implement your feature by subclassing `QuerySet`, but doing it the "right" way (well, the one I can think of) might require a bit more work - cf my edited answer.
comment on: http://stackoverflow.com/a/47926112

http://stackoverflow.com/comment/82833802
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47920356
has text: I added an image to help explain what I am trying to build @eyllanesc

http://stackoverflow.com/q/47974035
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82918097
has body: The lists i am passing in the pyzillow API add_list = ['913 COMANCHE DR OXON HILL MD ','70 CLAY ST ANNAPOLIS MD ','9125 SCOTT ST SPRINGFIELD VA '] zip_list = [20745, 21401, 22153] This is the API I am running from pyzillow.pyzillow import ZillowWrapper, GetDeepSearchResults hometype = [] for add,zip_code in zip(add_list,zip_list): address = add zipcode = zip_code zillow_data = ZillowWrapper('X1-ZWz18uczm57uvf_56tmg') deep_search_response = zillow_data.get_deep_search_results(address, zipcode) result = GetDeepSearchResults(deep_search_response) hometype.append(result.home_type) This runs perfectly and gives proper output But when I use these lists add_list_edited = ['913 COMANCHE DR OXON HILL MD ','16640 HARWOOD OAKS CT DUMFRIES VA ','70 CLAY ST ANNAPOLIS MD ','9125 SCOTT ST SPRINGFIELD VA '] zip_list_edited = [20745, 22026, 21401, 22153] I get following error on running the same API TypeError: __str__ returned non-string (type dict) I checked that the second address in list isnt specific hence the scraper is throwing error. I removed it and the code worked but the issue is I used trial and error on only 4 elements. I am working on large number of elements and after dropping values having the second address i ran the code and again it threw the same error but its virtually impossible to identify which address is giving a problem. Is there a way to add exception to the loop? I dont mind dropping values which give me errors. Any suggestion would be welcome.
upvote count: 1
downvote count: 1
type: Question
score: 0
tagged with: pandas
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/50804770
tagged with: zillow
has title: Using pyzillow on multiple lists but getting errors

http://stackoverflow.com/q/47920985
tagged with: numerical-integration
has comment: http://stackoverflow.com/comment/82811751
has comment: http://stackoverflow.com/comment/82826285
upvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/41223186
type: UnansweredQuestion
has body: I have a function which looks like this: def test(x,q0): q = q0/(1+x**2) h_func = lambda t: 1/sp.cosh(t)**2 fun = lambda t: sp.log(1+q*h_func(t)) return spi.quad(fun,-sp.inf,sp.inf)[0] How do I make it vectorized so that it can accept x as an array? Right now, it shows TypeError: only length-1 arrays can be converted to Python scalars I can achieve this in Matlab using integral(fun,-Inf,Inf,'ArrayValued',true), but is there a Python equivalent of the 'ArrayValued',true in Matlab?
tagged with: python
tagged with: vectorization
answer count: 0
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/82812016
tagged with: scipy
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82810354
has comment: http://stackoverflow.com/comment/82811364
has comment: http://stackoverflow.com/comment/82811487
has title: How to define a vectorized function which incorporates scipy integrate?

http://stackoverflow.com/q/47903905
tagged with: apache-spark-sql
tagged with: pyspark
score: 40
type: Question
has answer: http://stackoverflow.com/a/47903978
answer count: 2
tagged with: apache-spark
upvote count: 40
favorite count: 0
has title: AssertionError: col should be Column
has body: How to create a new column in PySpark and fill this column with the date of today? This is what I tried: import datetime now = datetime.datetime.now() df = df.withColumn("date", str(now)[:10]) I get this error: AssertionError: col should be Column
possible better answer: http://stackoverflow.com/a/73162046
has answer: http://stackoverflow.com/a/73162046
tagged with: python
downvote count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47903978

http://stackoverflow.com/a/47927331
answers question: http://stackoverflow.com/q/47921273
type: Answer
score: 2
downvote count: 0
upvote count: 2
has body: In boto3, you can use s3.client.head_object() this will return a dict of meta data for the particular object. You just need to look into the LastModified element. 'LastModified': datetime(2015, 1, 1)

http://stackoverflow.com/a/47953866
type: Answer
has comment: http://stackoverflow.com/comment/82877265
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/82876941
has body: Use combine_first or fillna: df1['b'] = df2['update'].mask(lambda x: x=='').combine_first(df1['b']) #alternative #df1['b'] = df2['update'].mask(lambda x: x=='').fillna(df1['b']) print (df1) a b 0 aaa eee 1 bbb X 2 ccc ggg 3 ddd Y But is necessary same index values in both DataFrames.
upvote count: 3
has comment: http://stackoverflow.com/comment/82877273
answers question: http://stackoverflow.com/q/47953752

spark-structured-streaming
tags question: http://stackoverflow.com/q/47903276
type: Tag
tag name: spark-structured-streaming

http://stackoverflow.com/q/47975521
score: 0
duplicate of: http://stackoverflow.com/q/30328586
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82921247
type: AnsweredQuestion
has body: In this link http://flask.pocoo.org/docs/0.12/tutorial/setup/#tutorial-setup In file in flaskr.py : app = Flask(__name__) # create the application instance :) app.config.from_object(__name__) # load config from this file , flaskr.py # Load default config and override config from an environment variable app.config.update(dict( DATABASE=os.path.join(app.root_path, 'flaskr.db'), SECRET_KEY='development key', USERNAME='admin', PASSWORD='default' )) app.config.from_envvar('FLASKR_SETTINGS', silent=True) The explanation for the line DATABASE=os.path.join(app.root_path, 'flaskr.db'), is : Operating systems know the concept of a current working directory for each process. Unfortunately, you cannot depend on this in web applications because you might have more than one application in the same process. For this reason the app.root_path attribute can be used to get the path to the application. Together with the os.path module, files can then easily be found. In this example, we place the database right next to it. Can anyone explain it with example as I am unable to understand the explanation?
has answer: http://stackoverflow.com/a/47975781
accepted answer: http://stackoverflow.com/a/47975781
has title: Why os.path.join(app.root_path, 'flaskr.db')?
type: Question
upvote count: 1
answer count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/30328586
tagged with: flask
favorite count: 0

http://stackoverflow.com/comment/82831307
type: Comment
score: 2
comment on: http://stackoverflow.com/q/47931241
has text: Possible duplicate of [Django says port is already in use](https://stackoverflow.com/questions/46025002/django-says-port-is-already-in-use)
type: QuestionComment

http://stackoverflow.com/a/62442203
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47895765
has body: I had similar task solved with multiprocessing. Major parts: Main process is Tk's process with mainloop. daemon=True process with aiohttp service that executes commands. Intercom using duplex Pipe so each process can use it's end. Additionaly, I'm making Tk's virtual events to simplify massage tracking on app's side. You will need to apply patch manually. You can check python's bug tracker for details. I'm checking Pipe each 0.25 seconds on both sides. $ python --version Python 3.7.3 main.py import asyncio import multiprocessing as mp from ws import main from app import App class WebSocketProcess(mp.Process): def __init__(self, pipe, *args, **kw): super().__init__(*args, **kw) self.pipe = pipe def run(self): loop = asyncio.get_event_loop() loop.create_task(main(self.pipe)) loop.run_forever() if __name__ == '__main__': pipe = mp.Pipe() WebSocketProcess(pipe, daemon=True).start() App(pipe).mainloop() app.py import tkinter as tk class App(tk.Tk): def __init__(self, pipe, *args, **kw): super().__init__(*args, **kw) self.app_pipe, _ = pipe self.ws_check_interval = 250; self.after(self.ws_check_interval, self.ws_check) def join_channel(self, channel_str): self.app_pipe.send({ 'command': 'join', 'data': { 'channel': channel_str } }) def ws_check(self): while self.app_pipe.poll(): msg = self.app_pipe.recv() self.event_generate('&lt;&lt;ws-event&gt;&gt;', data=json.dumps(msg), when='tail') self.after(self.ws_check_interval, self.ws_check) ws.py import asyncio import aiohttp async def read_pipe(session, ws, ws_pipe): while True: while ws_pipe.poll(): msg = ws_pipe.recv() # web socket send if msg['command'] == 'join': await ws.send_json(msg['data']) # html request elif msg['command'] == 'ticker': async with session.get('https://example.com/api/ticker/') as response: ws_pipe.send({'event': 'ticker', 'data': await response.json()}) await asyncio.sleep(.25) async def main(pipe, loop): _, ws_pipe = pipe async with aiohttp.ClientSession() as session: async with session.ws_connect('…
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47895765
has comment: http://stackoverflow.com/comment/110435814
score: 1
type: AcceptedAnswer

http://stackoverflow.com/a/47860606
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/82686026
upvote count: 1
answers question: http://stackoverflow.com/q/47860572
score: 1
has body: As documentation for ForeignKey in Django 1.1 states on_delete is becoming required in Django 2.0 ForeignKey A many-to-one relationship. Requires two positional arguments: the class to which the model is related and the on_delete option. (on_delete isn’t actually required, but not providing it gives a deprecation warning. It will be required in Django 2.0.) Also your error points to the same author = models.ForeignKey('auth.User') TypeError: __init__() missing 1 required positional argument: 'on_delete' You should set on_delete attribute on each foreign key for it to be Django 2.0 compatible

evaluation
tags question: http://stackoverflow.com/q/47941831
tags question: http://stackoverflow.com/q/47975990
tag name: evaluation
type: Tag

http://stackoverflow.com/a/48010031
has body: First of all, we need to add your missing closing tags: &lt;/IP&gt; &lt;/DAYPROFILE&gt; &lt;/D4&gt; &lt;/UTILITYTYPE&gt; &lt;/CDF&gt; Now, you can use either the .find() or the .findall() method (.find() will return a single element, while .findall() will return multiple elements). The syntax for finding elements is a little weird, but this should work: d1 = tree.find('.//D1') # D1 is a decendant of the tree. d4 = tree.find('.//D4') # D4 is a decendant of the tree. From here you can find your G values: g1 = d1.find('G1') # G1 is a direct child of D1. g1_value = g1.text # Handle the value however you need, and do something similar for the # remaining G elements. Now to find your IP values: for ip in d4.findall('.//IP'): # IPs are decendants of D4. # Get each parameter. for param in ip.findall('PARAMETER'): # PARAMETERs are direct children of IPs. # Get parameter attributes. param_code = param.attrib['PARAMCODE'] param_value = param.attrib['VALUE'] param_unit = param.attrib['UNIT'] # Handle the IP parameters. # Handle any final things for the IP element.
has comment: http://stackoverflow.com/comment/82988550
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/82988621
answers question: http://stackoverflow.com/q/48009547
has comment: http://stackoverflow.com/comment/82990463
has comment: http://stackoverflow.com/comment/82993953
has comment: http://stackoverflow.com/comment/83028052

http://stackoverflow.com/q/47981151
type: UnansweredQuestion
tagged with: python
tagged with: pygame
has comment: http://stackoverflow.com/comment/82931002
has comment: http://stackoverflow.com/comment/82932768
type: Question
has answer: http://stackoverflow.com/a/47982115
has title: TypeError: integer argument expected, got float, python 3.6.3 with pygame
has comment: http://stackoverflow.com/comment/82932603
score: 0
has answer: http://stackoverflow.com/a/47981263
has comment: http://stackoverflow.com/comment/82932556
tagged with: typeerror
answer count: 2
has body: I am having problem with my python game, it's my first project. I am getting an error (TypeError: integer argument expected, got float). It's starting to come when I insert my user-defined function shoot. How to solve this problem or make a SuperMario image shoot a circular object with a class. Thanks :) import pygame import time pygame.init() display_height = 600 display_width = 800 white = (255,255,255) gameDisplay = pygame.display.set_mode((display_width, display_height)) pygame.display.set_caption('Igra1') clock = pygame.time.Clock() bg = pygame.image.load('background.jpg') bg = pygame.transform.scale(bg,(800, 600)) Img_SuperMario = pygame.image.load('SuperMario.png') SuperMario_width = 611 SuperMario_height = 611 Img_SuperMario = pygame.transform.scale(Img_SuperMario, (100, 100)) def shoot(xshoot): while xshoot &lt; display_width: pygame.draw.circle(gameDisplay, white, (xshoot,50), 20 ,0) xshoot += 10 def SuperMario(x,y): gameDisplay.blit(Img_SuperMario,(x,y)) def gameloop(): x = (display_width * 0.1) y = (display_height * 0.1) x_change = 0 y_change = 0 game_exit = False while not game_exit: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: x_change = -5 elif event.key == pygame.K_RIGHT: x_change = 5 elif event.key == pygame.K_UP: y_change = -5 elif event.key == pygame.K_DOWN: y_change = 5 if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_DOWN or event.key == pygame.K_UP: x_change = 0 y_change = 0 if x == display_width - 100 or x == 0: x_change = 0 if y == (display_height - 100) or y == 0: y_change = 0 x += x_change y += y_change xshoot = x gameDisplay.fill(white) gameDisplay.blit(bg,(0,0)) if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: while xshoot &lt; display_width: shoot(x) SuperMario(x,y) pygame.display.update() clock.tick(60) gameloop() pygame.quit() quit()

http://stackoverflow.com/comment/82964154
type: Comment
comment on: http://stackoverflow.com/q/47997816
score: 0
type: QuestionComment
has text: Check if IFTTT works for you: https://ifttt.com/. If it does then you can use their REST API via python's `requests` package.

http://stackoverflow.com/q/48000185
possible better answer: http://stackoverflow.com/a/48000264
has title: Python ctypes DLL is "not a valid Win32 application"
favorite count: 0
has comment: http://stackoverflow.com/comment/82968992
tagged with: python
has comment: http://stackoverflow.com/comment/82969025
has answer: http://stackoverflow.com/a/48027639
type: AnsweredQuestion
score: 2
upvote count: 3
downvote count: 1
type: Question
tagged with: ctypes
accepted answer: http://stackoverflow.com/a/48027639
has answer: http://stackoverflow.com/a/48000264
has body: I am using ctypes to load a 64-bit Windows DLL into a 64-bit Python 3.6.2 environment, but Python complains that the DLL is not a 32-bit DLL. This is all 64-bit, so I don't know why it expects a 32-bit DLL. This same error message appears in Visual Studio 2017 and in PyCharm 2017.1.5. Here is the problem code: ThisDLL = ctypes.WinDLL(r"C:\Temp2\Test_Project\Std_Math_Formulas.dll") Here are the error messages: File "C:\Project Backups\Python Projects - PyCharm\Test_DLL\Main_Entry.py", line 73, in CTypes_Test_02 ThisDLL = ctypes.WinDLL(r"C:\Temp2\Test_Project\Std_Math_Formulas.dll") File "C:\Program Files\Python36\lib\ctypes\__init__.py", line 348, in __init__ self._handle = _dlopen(self._name, mode) OSError: [WinError 193] %1 is not a valid Win32 application I have researched this at length, and the answers all apply to a mixed 32-bit to 64-bit situation -- 32-bit DLL in 64-bit environment or 64-bit DLL in 32-bit environment. Here they both environment and DLL are 64-bit. I know that Windows 32-bit DLLs use the stdcall calling convention and 64-bit uses the fastcall convention, but ctypes should be able to load a 64-bit DLL.
answer count: 2

http://stackoverflow.com/comment/82834971
type: Comment
type: QuestionComment
has text: Can you show a full code!? Is not clear!
comment on: http://stackoverflow.com/q/47932809
score: 0

http://stackoverflow.com/comment/82994276
type: Comment
type: QuestionComment
score: 1
has text: Also, `findall()` only gives you a list of the matches as strings; it doesn't provide `Match` objects. You could use `finditer()`, but if you just wanted the first you'd need `next(finditer(...))` so you might as well use `search()`.
comment on: http://stackoverflow.com/q/48012824

http://stackoverflow.com/comment/82884300
type: AnswerComment
has text: also, more practically, I would like to pass a 'table'parameter from the command line to dynamically set a table variable that is accessible to the pipeline.
type: Comment
comment on: http://stackoverflow.com/a/47955715
score: 0

http://stackoverflow.com/q/47985387
has body: I have four images that I converted to a vector. I'm trying to save those vectors in a numpy array to have a similar structure to the following matrix: np.array([[0,0,1], [0,1,1], [1,0,1], [1,1,1]]) This is what I did: import numpy as np from PIL import Image image1 = Image.open('cat0.jpg').convert('L') image_array1 = arr = np.array(image1) image_array_to_vector1 = image_array1.ravel() image2 = Image.open('cat1.jpg').convert('L') image_array2 = arr = np.array(image2) image_array_to_vector2 = image_array2.ravel() image3 = Image.open('cat2.jpg').convert('L') image_array3 = arr = np.array(image3) image_array_to_vector3 = image_array3.ravel() image4 = Image.open('dog1.jpg').convert('L') image_array4 = arr = np.array(image4) image_array_to_vector4 = image_array4.ravel() X = np.array(image_array_to_vector1,image_array_to_vector2,image_array_to_vector3,image_array_to_vector4) I'm however getting the following error: X = np.array(image_array_to_vector1,image_array_to_vector2,image_array_to_vector3,image_array_to_vector4) ValueError: only 2 non-keyword arguments accepted What am I doing wrong? How can I solve this issue? Thanks.
has title: Saving vectorized images to a numpy array
type: Question
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/47985488
score: 0
tagged with: numpy
tagged with: python-imaging-library
tagged with: arrays
has comment: http://stackoverflow.com/comment/82939777
tagged with: image
accepted answer: http://stackoverflow.com/a/47985488
type: AnsweredQuestion

http://stackoverflow.com/a/47953435
upvote count: 1
has body: You're probably not entering in the else part of the loop. To avoid that, you'll probably need to move the td part to the top of the loop, so it's always defined: def load_data(): with open('train.csv','rb') as csvfile: reader = csv.DictReader(csvfile,delimiter=',') td = [] for row in reader: ...
downvote count: 0
answers question: http://stackoverflow.com/q/47952885
type: Answer
score: 1

http://stackoverflow.com/a/47958873
type: Answer
score: 6
has comment: http://stackoverflow.com/comment/105105819
has comment: http://stackoverflow.com/comment/108817777
has comment: http://stackoverflow.com/comment/108488666
downvote count: 0
has comment: http://stackoverflow.com/comment/108538906
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/105096318
upvote count: 6
has comment: http://stackoverflow.com/comment/108817760
accepted answer of: http://stackoverflow.com/q/47958126
has comment: http://stackoverflow.com/comment/105895210
has body: You need the azure-graphrbac package to create a Service Principal: https://learn.microsoft.com/python/api/overview/azure/activedirectory The closer to a sample might be this unittest: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/graphrbac/azure-graphrbac/tests/test_graphrbac.py For role and permissions, you need azure-mgmt-authorization: https://learn.microsoft.com/python/api/overview/azure/authorization Best sample for this one, is probably the sub-part of this sample: https://github.com/Azure-Samples/compute-python-msi-vm#role-assignement-to-the-msi-credentials "msi_identity" is a synonym of "service principal" in your context. Note that all of this is supported by the CLI v2.0: https://learn.microsoft.com/cli/azure/ad/sp https://learn.microsoft.com/cli/azure/role/assignment It might be interested to test the CLI in --debug mode and sniffing in the code repo at the same time: https://github.com/Azure/azure-cli (full disclosure, I work at MS in the Azure SDK for Python team)
has comment: http://stackoverflow.com/comment/100112165
answers question: http://stackoverflow.com/q/47958126
has comment: http://stackoverflow.com/comment/105930263

http://stackoverflow.com/comment/82682340
type: QuestionComment
type: Comment
has text: I don't understand you mean by "I want `sifre = open(i, "r") Write i instead of F:/sifreler.txt". What is the full problem you're trying to solve with this code? It sounds like you're missing some logic to make it work for your purposes.
score: 1
comment on: http://stackoverflow.com/q/47858740

http://stackoverflow.com/comment/82842311
type: Comment
type: QuestionComment
has text: Replying to @georgexsh, i change the file format to EPS but there is still error. Is there a different way to open EPS file using matplotlib?
comment on: http://stackoverflow.com/q/47864794
score: 0

http://stackoverflow.com/comment/82801765
type: Comment
type: QuestionComment
has text: Note: for development, clone the repository and then run `pip install -e .` in the project directory. You should then be able to edit the C files; recompile with running `pip install -e .` again.
comment on: http://stackoverflow.com/q/47916452
score: 0

http://stackoverflow.com/comment/82932852
comment on: http://stackoverflow.com/q/47982203
score: 0
type: Comment
has text: https://docs.python.org/2/library/subprocess.html#popen-constructor: split your command and pass it as a list to `Popen`
type: QuestionComment

annotate
tag name: annotate
type: Tag
tags question: http://stackoverflow.com/q/47882271

http://stackoverflow.com/comment/82762814
type: Comment
comment on: http://stackoverflow.com/q/47893224
score: 0
has text: could you share some reading material on this, I wasn't aware of this requirement.
type: QuestionComment

http://stackoverflow.com/comment/82959105
type: QuestionComment
has text: With `gdb` you specify the argument list to the `run` command. The `-x` statement is followed by a file containing `gdb` commands, not a python script.
comment on: http://stackoverflow.com/q/47993882
score: 0
type: Comment

http://stackoverflow.com/q/47879368
has comment: http://stackoverflow.com/comment/82724808
has comment: http://stackoverflow.com/comment/82765161
has comment: http://stackoverflow.com/comment/82725738
type: Question
has comment: http://stackoverflow.com/comment/82724813
score: 0
linked to: http://stackoverflow.com/q/5259882
tagged with: python
has body: I want to know about the best way to find the difference between two time objects in Django. I want to know whether the time of a particular object is in a difference of 4 hours or not. I have my models.py as class Task(models.Model): time = models.TimeField() In the shell, I tried something like from django.utils.timzone import datetime, timedelta obj_time = Task.objects.first().time obj_time - datetime.now().time() &lt; timedelta(hours=4) But I get the following error TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time' How should I go about solving this?
answer count: 0
type: UnansweredQuestion
tagged with: django
has title: Finding difference of two time objects in django

http://stackoverflow.com/comment/82697429
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47865986
has text: @NilsWerner, sorry! Updated it now, thanks.

http://stackoverflow.com/comment/82851394
type: Comment
has text: No references for dev0 anywhere.. by the way, when I change `__version__ ` back to `0.1.dev0` and install it it works.
comment on: http://stackoverflow.com/a/47939933
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83008184
has text: When changing to yield deferLater(reactor, 1, lambda: None), it gives the same error. When changing to (5), it gives the following error: session closed with reason wamp.close.transport_lost [WAMP transport was lost without closing the session before]. Is it safe to say that through Twisted, Autobahn or Crossbar sending data on a 'high' frequency is nearly infeasible?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48016078
type: Comment

http://stackoverflow.com/comment/82762092
has text: so i feel like there is a way to do it using this method
score: 0
comment on: http://stackoverflow.com/q/47897359
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47965756
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82901329
accepted answer: http://stackoverflow.com/a/47965901
tagged with: selenium
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/48334245
score: 0
has answer: http://stackoverflow.com/a/48334245
has comment: http://stackoverflow.com/comment/82901493
has answer: http://stackoverflow.com/a/47965901
tagged with: path-variables
has title: Python Splinter geckodriver PATH OSX
tagged with: splinter
tagged with: geckodriver
has body: After reading numerous answers on StackOverflow, I found that in order to get Splinter to work, I needed to add the geckodriver executable to my PATH variable. Here's what I did: In terminal: echo 'export PATH=$PATH: /Applications/anaconda/pkgs/geckodriver I then confirmed it was in there via: echo $PATH ...which shows: /Applications/anaconda/pkgs/geckodriver:... Then I tried this (after restarting my Spyder IDE): from splinter import Browser browser = Browser('firefox') ...and STILL go this error: WebDriverException: 'geckodriver' executable needs to be in PATH.
tagged with: python

http://stackoverflow.com/comment/82986347
type: Comment
type: QuestionComment
score: 1
has text: When you say `proceeded by a blank space` I assume you meant `preceded`?
comment on: http://stackoverflow.com/q/48009064

http://stackoverflow.com/a/47910856
score: 1
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47910532
answers question: http://stackoverflow.com/q/47910532
has body: Starting with Python 2.6 you can use ast.literal_eval. import ast ast.literal_eval('{"a":1, "b":2, "c":3}') {'a': 1, 'b': 2, 'c': 3} If whole column of your pandas DataFrame is a dict, then you can save it to CSV normaly (with separator other than ,) and then map this dictionary-like column strings into dictionaries: df['DICTIONARY_COLUMN'].map(ast.literal_eval) Naturally you can ignore dataframe part - you can transform them also in loop or whatever way you like. Important parts are: ast.literal_eval and using non-comma separator (because you use commas in dict-like strings).
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/82693395
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47860905
has text: Your end game is probably to end up with bitcoin, mine is to end up with USD, i want to know the relative USD profit/loss of all trades. Its like my local currency is USD, and i'm in a AUD/JPY trade, if both those currencies are falling like a stone in comparison to USD it doesn't matter what profit i make, i'm still loosing because eventually i'm going to need to convert back to USD. Have you ever traded forex?

http://stackoverflow.com/q/47869368
accepted answer: http://stackoverflow.com/a/47869578
has body: I have a text file like this (this is a sample, the actual file in very large): [52639 - 2017-12-08 11:56:58,680] INFO __main__.master 251 Finished pre-smap protein tag ('4h02', [], 35000, 665, '67') [52639 - 2017-12-08 11:57:37,686] INFO __main__.master 251 Finished pre-smap protein tag ('4nqk', [], 35000, 223, '18') [52639 - 2017-12-08 11:58:46,984] INFO __main__.master 251 Finished pre-smap protein tag ('3j60', [], 3500, 1052, '65') [52639 - 2017-12-08 12:01:10,073] INFO __main__.master 251 Finished pre-smap protein tag ('4ddg', [], 35000, 541, '38') [52639 - 2017-12-08 12:03:37,570] INFO __main__.master 251 Finished pre-smap protein tag ('4ksl', [], 35000, 1303, '68') and I want to count the values before the last comma. The result would be 665+223+1052+541+1303 = 3784. I cannot figure out how to achive this. Any help will be appreciated.
downvote count: 5
tagged with: python-2.7
answer count: 2
score: -4
favorite count: 0
possible better answer: http://stackoverflow.com/a/47869595
has answer: http://stackoverflow.com/a/47869595
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47869578
tagged with: file
upvote count: 1
has title: Count certain values of file in python
type: Question

http://stackoverflow.com/comment/82823132
has text: @Gino thats for a simple representation for understanding what `sum(int)` does. There is a need for appending data to a empty list or a list comprehension. And map is an iterator function.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47927302

http://stackoverflow.com/a/47895501
accepted answer of: http://stackoverflow.com/q/47893838
score: 4
answers question: http://stackoverflow.com/q/47893838
type: AcceptedAnswer
type: Answer
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/82758965
has body: If you want links to always open in the same window, you can reimplement the createWindow method, so that it returns the same view: class HtmlView(QWebEngineView): def createWindow(self, wintype): return self The wintype argument provides information about which type of window is being requested. You may want to treat dialog windows differently. Note that the WebEnginePage subclass in your example is not needed for this to work.
has comment: http://stackoverflow.com/comment/82761081
has comment: http://stackoverflow.com/comment/82759454

http://stackoverflow.com/q/47980908
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48349991
tagged with: python
has body: I am trying to display an interact function in an ipywidget tab. The code below is my attempt to do this but I only see the dropdown list but the plot is not shown. I also included the interact() function in isolation to show the way it works out of the tab. Any help on this is much appreciated. Thank you. from ipywidgets import * import seaborn.apionly as sns df = sns.load_dataset('iris') #plot def plot_image(x): data = df if x != 'Select': xplot = data[x] sns.distplot(xplot) plt.show() #define widgets x = widgets.Dropdown( options=df_cols, value=df_cols[0], description='X' ) x.set_title = 'x' #assign widgets to tabs tab_visualise = widgets.HBox([x]) #create tabs tab_nest = widgets.Tab() tab_nest.children = [tab_visualise] tab_nest.set_title(0, 'Visualise') tab_nest #interact function in isolation interact(plot_image, x = x)
accepted answer: http://stackoverflow.com/a/48349991
tagged with: tabs
upvote count: 2
type: AnsweredQuestion
tagged with: ipywidgets
tagged with: widget
has title: How to display interact() in tab in ipywidgets Python
type: Question
score: 2

http://stackoverflow.com/a/55800668
downvote count: 0
type: Answer
score: 1
has body: If you need your processing callbacks to run sequentially, you would be better off using a message passing model than modifying the subscriber internals. If you push the received messages to an explicit queue.Queue, you can ensure that only one worker is pulling off of this queue, and only one is being processed at a time. Note however, that while this provides you a ‘one at a time’ guarantee for processing if there is only one subscribing job, it does not provide you with any ordering guarantees. Messages may still be processed in any arbitrary order relative to the order that they were published.
upvote count: 1
answers question: http://stackoverflow.com/q/48009911

http://stackoverflow.com/a/47981156
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47981065
upvote count: 3
score: 3
has body: The fields are imported in django/db/models/__init__.py Take a look at the source code. Possibly relevant: What is init.py for?
accepted answer of: http://stackoverflow.com/q/47981065
type: AcceptedAnswer

http://stackoverflow.com/a/47894224
has body: As Zerodf points out, the problem is likely that your current working directory is not the same as the dataset_path directory you specified. So when os.rename goes to rename sound1.wav, it looks for it in your current working directory (which might not be the same as dataset_path), can't find it, and throws that error. Since your dataset_path variable contains an absolute path, you can make sure that everything that os.rename tries to rename is an absolute path by tacking each filename onto dataset_path using os.path.join(). That is, change os.rename(old_name, str(i) + '.wav') to os.rename(os.path.join(dataset_path, old_name), os.path.join(dataset_path, str(i) + '.wav')) Then when os.rename goes to rename sound1.wav, it will look for C:/dataset/sound1.wav, which it should find without a problem. Also note that you can see what your current working directory is with the getcwd() function in os. import os print(os.getcwd())
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/82755214
has comment: http://stackoverflow.com/comment/82755180
accepted answer of: http://stackoverflow.com/q/47893961
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47893961

http://stackoverflow.com/q/47898294
has body: I'm trying to convert text file to excel sheet in python. The txt file contains data in the below specified formart Column names: reg no, zip code, loc id, emp id, lastname, first name. Each record has one or more error numbers. Each record have their column names listed above the values. I would like to create an excel sheet containing reg no, firstname, lastname and errors listed in separate rows for each record. How can I put the records in excel sheet ? Should I be using regular expressions ? And how can I insert error numbers in different rows for that corresponding record? Expected output: Here is the link to the input file: https://github.com/trEaSRE124/Text_Excel_python/blob/master/new.txt Any code snippets or suggestions are kindly appreciated.
linked to: http://stackoverflow.com/q/3976711
possible better answer: http://stackoverflow.com/a/47907946
has comment: http://stackoverflow.com/comment/82764242
tagged with: python-2.7
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/82763561
has comment: http://stackoverflow.com/comment/82764130
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82764828
has title: Txt file to excel conversion in python
has comment: http://stackoverflow.com/comment/82763943
tagged with: python
has comment: http://stackoverflow.com/comment/82763576
has answer: http://stackoverflow.com/a/47907946
has comment: http://stackoverflow.com/comment/82764858
has comment: http://stackoverflow.com/comment/82764278
has comment: http://stackoverflow.com/comment/82764385
has comment: http://stackoverflow.com/comment/82764689
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82763476
has comment: http://stackoverflow.com/comment/82790249
type: Question
has answer: http://stackoverflow.com/a/47911058
has comment: http://stackoverflow.com/comment/82763396
accepted answer: http://stackoverflow.com/a/47911058

http://stackoverflow.com/comment/82856157
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47940483
has text: @Aksakal That's using slicing there. Read more here - https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.indexing.html#basic-slicing-and-indexing

http://stackoverflow.com/comment/82902961
comment on: http://stackoverflow.com/q/47966494
score: 0
has text: Whatever len was I was going to use that to index description. I'm running into a snag where when I output the scraped data as a csv the "description" cells are always empty. though when I used [-1:] as an index those with only 1 list in description would appear and the rest would not appear. I'm hoping that by using the exact len I would be able to get all the descriptions working.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47974802
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47974637
type: Answer
has body: You can do this with iloc but I prefer to do this with Numpy. Essentially, use ffill to forward fill values, then mask the values that are NaN all the way to the end. v = df.values mask = np.logical_and.accumulate( np.isnan(v)[:, ::-1], axis=1)[:, ::-1] df.ffill(axis=1).mask(mask) 2007 2008 2009 2010 2011 0 1.0 2.0 3.0 3.0 5.0 1 1.0 3.0 3.0 4.0 NaN 2 4.0 4.0 7.0 NaN NaN
answers question: http://stackoverflow.com/q/47974637
upvote count: 5
score: 5

http://stackoverflow.com/comment/82921907
has text: @kessi The project is named "Accor"
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47975983
score: 0

http://stackoverflow.com/q/47994336
has comment: http://stackoverflow.com/comment/82958653
score: 9
has title: Django-filter | Boolean fields
downvote count: 0
has answer: http://stackoverflow.com/a/75043123
tagged with: django-filter
has answer: http://stackoverflow.com/a/58870125
favorite count: 0
has answer: http://stackoverflow.com/a/47999036
tagged with: python
has answer: http://stackoverflow.com/a/47995581
answer count: 4
has comment: http://stackoverflow.com/comment/82956974
type: UnansweredQuestion
tagged with: django
type: Question
upvote count: 9
has body: I'm using django-filter package and I have many boolean fields. Is there a way to filter only when field is True? And show all other posibilities? For example if I have 3 fields: True, False, False... Render objects that have 1st field equal True but doesn't matter about de rest, don't consider it False. model.py class Product(models.Model): name = models.CharField(max_length=15) is_dangerous = models.BooleanField() is_secret = models.BooleanField() is_active = models.BooleanField() filters.py class SearchFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='icontains') class Meta: model = Product fields = ['name', 'is_dangerous', 'is_secret', 'is_active',] filter_overrides = { models.BooleanField: { 'filter_class': django_filters.BooleanFilter, 'extra': lambda f: { 'widget': forms.CheckboxInput, }, }, } urls.py url(r'^products/$', views.products, name='products') When I enter to products/ for the first time, I only see products that has all boolean fields = False and I want to see ALL products.

http://stackoverflow.com/comment/83306619
type: Comment
type: QuestionComment
has text: Can you show me the shape of XX and YY?
comment on: http://stackoverflow.com/q/48001879
score: 0

http://stackoverflow.com/a/48873959
type: Answer
answers question: http://stackoverflow.com/q/48001492
score: 0
has body: My approach to solve this would be as follows: import paho.mqtt.client as mqtt msg_arrived_flag = False global_X = 0 def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) client.subscribe("123") def on_message(client, userdata, msg): global_X = int(msg.payload)*10 print(msg.topic+" "+str(msg.payload)) msg_arrived_flag = True client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("broker.hivemq.com", 1883) while True: client.loop_start() time.sleep(5) client.loop_stop() if msg_arrived_flag: msg_arrived_flag = False #Use global_X here Time to sleep between start and stop may be set as convenience. Also I suggest to set callbacks before connect. Hope this helps!

http://stackoverflow.com/q/47939632
has body: View Contact Details Principal name, mobile number and email id are the contents I'm interested in. When I specify soup.find('a', {'class':'tip'}) it gives me only "View Contact Details". Is there a way to extract contents within rel?
accepted answer: http://stackoverflow.com/a/47940166
tagged with: rel
type: Question
answer count: 1
tagged with: beautifulsoup
score: 0
has title: How do I extract contents within rel in tag?
tagged with: python
has answer: http://stackoverflow.com/a/47940166
tagged with: web-scraping
type: AnsweredQuestion

http://stackoverflow.com/comment/82918820
type: QuestionComment
comment on: http://stackoverflow.com/q/47973352
has text: @Murthi I added the outerhtml of the tab in pastebin above, here is entirety of outerhtml: https://pastebin.com/eziGR7Pq
score: 0
type: Comment

http://stackoverflow.com/a/47875530
has body: #views.py def addentry(request): if request.method =='POST': form = entryform(request.POST) if form.is_valid(): form.save(commit=Fale) num = form.cleaned_data['num'], title = form.cleaned_data['title'], text = form.cleaned_data['text'] form.save(commit=True) return redirect('/') else: form=entryform() return render(request,....,{'form':form}) #template &lt;form action="{% url 'addentry' %}" method="post" enctype="multipart/form-data"&gt; {% csrf_token %} {{form.as_p}} &lt;input type="submit" name="submit"&gt; &lt;/form&gt;
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47875322

http://stackoverflow.com/a/48364397
has body: Try to compile using: gcc pythonTest.cc -I/$HOME/anaconda3/include/python3.6m -lpython3.6m
downvote count: 1
answers question: http://stackoverflow.com/q/47932685
score: -1
upvote count: 0
type: Answer

http://stackoverflow.com/a/47977299
has comment: http://stackoverflow.com/comment/82924798
has comment: http://stackoverflow.com/comment/82923451
has comment: http://stackoverflow.com/comment/82923407
type: Answer
score: 11
has comment: http://stackoverflow.com/comment/82923626
has comment: http://stackoverflow.com/comment/82924874
answers question: http://stackoverflow.com/q/47977238
has comment: http://stackoverflow.com/comment/82925792
downvote count: 0
has comment: http://stackoverflow.com/comment/82923423
has comment: http://stackoverflow.com/comment/82925749
upvote count: 11
has comment: http://stackoverflow.com/comment/82923984
has body: It seems like you're looking for a transpose followed by a reshape. x.transpose((2, 0, 3, 1)).reshape(np.prod(x.shape[:2]), -1) array([[ 0, 5, 0, 10], [ 6, 7, 12, 14], [ 0, 15, 0, 20], [18, 21, 24, 28]]) To help you understand why a transposition is needed, let's analyse your incorrectly shaped output (obtained by a single reshape call) to understand why it is incorrect. A simple 2D reshaped version of this result (without any transposition) looks like this - x.reshape(4, 4) array([[ 0, 0, 0, 0], [ 5, 10, 15, 20], [ 6, 12, 18, 24], [ 7, 14, 21, 28]]) Now consider this output with respect to your expected output - array([[ 0, 5, 0, 10], [ 6, 7, 12, 14], [ 0, 15, 0, 20], [18, 21, 24, 28]]) You'll notice that your actual result is obtained by a Z-like traversal of your incorrectly shaped output - start | /| /| /| |/ | / |/ | / / / / / / | /| / | /| |/ |/ |/ | end This implies that you must move over the array in varying strides to get your actual result. In conclusion, a simple reshape is not enough. You must transpose the original array, in such a manner that these Z-like elements are made to be contiguous to each other, such that a subsequent reshape call gives you the output you need. To understand how to transpose correctly, you should trace the elements along the input and figure out what axes you need to jump to get to each one in the output. The transposition follows accordingly. Divakar's answer does a sterling job of explaining this.
has comment: http://stackoverflow.com/comment/82923591

http://stackoverflow.com/q/47964675
has comment: http://stackoverflow.com/comment/82899032
tagged with: bash
has comment: http://stackoverflow.com/comment/82899104
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
answer count: 0
has body: I just installed pipenv, yet pipenv isn’t available in my shell post-installation. I'm struggling to follow the instructions from Hitchhiker's Guide to Python: macOS Instructions My user base binary directory is: /Users/DoubleA/Library/Python/3.6 When I enter nano ~/.bash_profile, here's what's entered into my profile: Bash Profile Can someone help me discover where I've gone wrong, so that I can continue setting up my pip environment per Hitchhiker's instructions? Thank you!!!
score: 1
tagged with: pip
upvote count: 1
has comment: http://stackoverflow.com/comment/82899048
type: Question
tagged with: pipenv
has title: How do I access pipenv after a successful installation?

http://stackoverflow.com/comment/112020408
has text: This is an old question and the OP is most likely not looking for a quick answer. If you want to post an answer, please take your time to explain what you code does and how does it add to the already existing answers. The code block as it is now is of very little value to the community
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/63349186

http://stackoverflow.com/q/47880551
has answer: http://stackoverflow.com/a/47881203
has comment: http://stackoverflow.com/comment/82727454
has comment: http://stackoverflow.com/comment/82726993
has answer: http://stackoverflow.com/a/47882687
upvote count: 3
has answer: http://stackoverflow.com/a/47880591
accepted answer: http://stackoverflow.com/a/47880591
has title: find max average from a list python
has comment: http://stackoverflow.com/comment/82727258
favorite count: 0
possible better answer: http://stackoverflow.com/a/47880787
has answer: http://stackoverflow.com/a/47880787
has comment: http://stackoverflow.com/comment/82727031
tagged with: python
answer count: 4
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/82727422
downvote count: 0
type: Question
has body: I have a list: input= [ ["Pakistan", 23], ["Pakistan", 127], ["India", 3], ["India", 71], ["Australia", 31], ["India", 22], ["Pakistan", 81] ] Now i want to filter out only that key value who has highest average . Like in this case output should be "Pakistan": out = "Pakistan" Can anybody help

http://stackoverflow.com/comment/82912553
score: 1
type: QuestionComment
type: Comment
has text: `^G Get Help ^O WriteOut...` ***is*** `nano`'s UI. Either you're opening the wrong file and are getting a blank editor, or you aren't properly using `nano` to locate the section labeled `DATABASES`.
comment on: http://stackoverflow.com/q/47971485

http://stackoverflow.com/q/47950259
has body: How do I make: c=5 for i in range(10): print(c) c+=1 so that instead of printing across several lines like: 5 6 7 8 9 10 11 12 13 14 In each loop it will go: 5 Then when it loops again it will overwrite the existing line with: 6 How do I go about that?
has answer: http://stackoverflow.com/a/47950285
duplicate of: http://stackoverflow.com/q/465348
has comment: http://stackoverflow.com/comment/82870147
has comment: http://stackoverflow.com/comment/82870166
has answer: http://stackoverflow.com/a/47950374
has comment: http://stackoverflow.com/comment/82870256
has comment: http://stackoverflow.com/comment/82870114
score: 0
answer count: 3
has title: Make loop only print a single value at a time
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/82870117
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47950382
linked to: http://stackoverflow.com/q/465348
has comment: http://stackoverflow.com/comment/82870192
upvote count: 1
downvote count: 1
tagged with: list
has comment: http://stackoverflow.com/comment/82870097
linked to: http://stackoverflow.com/q/3249524
has comment: http://stackoverflow.com/comment/82870189
type: Question
duplicate of: http://stackoverflow.com/q/3249524

http://stackoverflow.com/a/48000778
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48000522
has body: One can also use quantiles for outlier detection with grouping and transformation as in other answers. Following uses 0.05 and 0.95 quantiles as limits: # FIND LOWER AND UPPER LIMITS: df["lower"] = df.groupby("ProductFamily").transform(lambda x: x.quantile(0.05)) df["upper"] = df.iloc[:,0:2].groupby("ProductFamily").transform(lambda x: x.quantile(0.95)) print(df) # SELECT ROWS THAT MEET CRITERIA: df = df[(df.Prices &gt; df.lower) &amp; (df.Prices &lt; df.upper)] print(df) # TO KEEP ORIGINAL 2 COLUMNS: df = df.iloc[:,0:2] print(df) Output: Prices ProductFamily lower upper 0 1.99 Yoplait 1.650 6.79 1 1.89 Yoplait 1.650 6.79 2 1.59 Yoplait 1.650 6.79 3 1.99 Yoplait 1.650 6.79 4 7.99 Yoplait 1.650 6.79 5 12.99 Hunts 4.415 12.99 6 12.99 Hunts 4.415 12.99 7 2.99 Hunts 4.415 12.99 8 12.49 Hunts 4.415 12.99 Prices ProductFamily lower upper 0 1.99 Yoplait 1.650 6.79 1 1.89 Yoplait 1.650 6.79 3 1.99 Yoplait 1.650 6.79 8 12.49 Hunts 4.415 12.99 Prices ProductFamily 0 1.99 Yoplait 1 1.89 Yoplait 3 1.99 Yoplait 8 12.49 Hunts
downvote count: 0

http://stackoverflow.com/comment/82851890
type: QuestionComment
has text: Please, tag Python too.
score: 0
comment on: http://stackoverflow.com/q/47941281
type: Comment

http://stackoverflow.com/q/47856882
type: Question
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/82678139
has answer: http://stackoverflow.com/a/47857017
has body: i need some help with parsing json objects on python 3.6 .. i dont have any idea how to parse this jsons ({"d":"{\"events\":{\"keys\":[\"time\",\"room\",\"groups\",\"teacher\",\"name\",\"comment\",\"class\"],\"values\":[[1513593000,[71],[1309],9713,\"MATH\",\"\",\"normal\"],[1513599300,[71],[1309],15653,\"ENGLISH\",\"\",\"normal\"],[1513673100,[71],[1309],15728,\"SPORT\",\"\",\"normal\"],[1513679400,[74],[1309],15651,\"BIOLOGY\",\"\",\"normal\"]]}}"}) or ({"d":"{\"events\":{\"keys\":[\"time\",\"room\",\"groups\",\"teacher\",\"name\",\"comment\",\"class\"],\"values\":[[1513673100,[71],[1309],15728,\"MATH\",\"\",\"normal\"],[1513679400,[74],[1309],15651,\"SPANISH\",\"\",\"normal\"],[1513683100,[71],[1309],15728,\"ENGLISH\",\"\",\"normal\"],]}}"}) i need time , room , teacher and name in separate variables for all lessons (next i will decode it) p.s: i have small experience in programming . and small experience with json objects . it is my first question here ...
tagged with: python
has comment: http://stackoverflow.com/comment/82678571
has title: parsing json objects on python 3.6
has answer: http://stackoverflow.com/a/47856979
accepted answer: http://stackoverflow.com/a/47856979
has comment: http://stackoverflow.com/comment/82678558
has comment: http://stackoverflow.com/comment/82678070
has comment: http://stackoverflow.com/comment/82678033
possible better answer: http://stackoverflow.com/a/47857017
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82678188
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/q/47992539
has title: Inserting HTML into mysql Database showing Type Error
type: Question
has comment: http://stackoverflow.com/comment/82954755
tagged with: http://stackoverflow.com/tag/json
linked to: http://stackoverflow.com/q/3410455
accepted answer: http://stackoverflow.com/a/47993468
upvote count: 0
tagged with: mysql-python
answer count: 1
duplicate of: http://stackoverflow.com/q/3410455
tagged with: flask
favorite count: 0
has body: I am developing a Webapp using Flask. At some point, I have to insert a certain HTML script into a MySQL database: Welcome! Some text When I insert it into the database (when it is returned by flask's 'render_template' function): \n\n Welcome! \n\n\n\n Some text I get the following error: TypeError: ProgrammingError(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '\\\\\\\\n\\\\n Welcome! \\\\n\\\\n\\\\n\\\\n Some text' at line 1") is not JSON serializable I first don't understand what 'JSON serializable' means, and I want to know what I am doing wrong. I have already tried taking off the linebreaks (\n) but it still shows the same error. Why? I am thankful for any answer you can provide.
score: -3
tagged with: python
type: AnsweredQuestion
downvote count: 3
tagged with: mysql
has answer: http://stackoverflow.com/a/47993468

http://stackoverflow.com/q/47888639
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/82743412
upvote count: 1
has title: Django Ajax POST empty Error 500
type: Question
has body: I am trying to let the user select x and y coordinates from an image using cropper.js and pass the data with using ajax to the next view. I am using Django 1.9.4. I am also not really practiced with Javascript, the Javascript part is not written by me. Using the Firefox Dev Tools Network Tab I seem to get a 500 Internal Server Error. In the Dev Tools view the request has the needed JSON data. However Django does not seem to work the request properly. Why? Relevant part from views.py: def render_stl(request): print("Got to STL render") if request.method == 'POST': print("BELOW DATA") print(request.POST) # <QueryDict: {}> print(request.is_ajax()) # False print(request.POST.__dict__) # {'_encoding': 'utf-8', '_mutable': False} # This is old from a former version, but should be updated if ajax works x_start = request.POST.get("x_start") z_start = request.POST.get("z_start") x_end = request.POST.get("x_end") z_end = request.POST.get("z_end") print(x_start, z_start, x_end, z_end) run_stl_render(x_start, z_start, x_end, z_end) # os.chdir(settings.MEDIA_ROOT) stl_file = open(settings.MEDIA_ROOT + "/mySTL.stl", "r") django_file = File(stl_file) return render(request, 'img_crop/render_stl.html', {'django_file': django_file}) urls.py: urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^render_img$', views.upload_file, name='render_img'), url(r'^render_stl$', views.render_stl, name='render_stl'), url(r'^download_stl$', views.download_stl, name='download_stl'), # url(r'^media/mySTL.stl', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ] Javascript (the csrftoken is defined in another function): sendDataOfCroppedImage = function(dataOfCroppedImage) { // var data = 'data : [' + JSON.stringify(dataOfCroppedImage) + ']'; var data_s = JSON.stringify(dataOfCroppedImage); console.log('data',data_s); $.ajax({ async: true, crossDomain: true, method: 'POST', data: data_s, dataType: 'json', headers: { 'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest', 'content-type'…
has answer: http://stackoverflow.com/a/47888737
tagged with: javascript
accepted answer: http://stackoverflow.com/a/47888737
answer count: 1
downvote count: 0
tagged with: jquery
favorite count: 0
has comment: http://stackoverflow.com/comment/82743307
tagged with: ajax
tagged with: django
tagged with: python

http://stackoverflow.com/comment/82893039
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47961389
has text: Ok,thanks,I will go to learn what's anaconda3 and how to use it.

http://stackoverflow.com/q/47934545
has comment: http://stackoverflow.com/comment/82838537
answer count: 1
has comment: http://stackoverflow.com/comment/82839206
accepted answer: http://stackoverflow.com/a/47934985
has comment: http://stackoverflow.com/comment/82838691
has comment: http://stackoverflow.com/comment/82839188
tagged with: python
tagged with: pyodbc
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82839159
has comment: http://stackoverflow.com/comment/82839253
has comment: http://stackoverflow.com/comment/82839127
has body: Using pyodbc I'm working on dealing with executing stored procedures with outputs. import pyodbc conn = pyodbc.connect('DRIVER=' + driver + ';PORT=1433;SERVER=' + server + ';PORT=1443;DATABASE=' + database + ';UID=' + username + ';PWD=' + password) cmd = conn.cursor() sql = """\ Too long to post """ params = ('EOXH39020220', 'EOXH39020245', 'EOXH3E360011') for item in params: cmd.execute(sql, item) rst = cmd.fetchall() print(rst) conn.close The output of a particular stored procedure I am testing with produces the following: [(False, 1, 3, 2, 967, 6, 'ABC-DE-FGHI', 'LOREM', 'IPSUM', 'CLASS PRODUCT', 'F/P', 'LABELDESCRIPTION', 'N/A', 'DESCRIPTION', 'ASL66', 'ASL10', '3FE50712BA', 'ABC-DE-FGHI', 'PO', 'ITEM#', 'OEM#', 'F/P', '1')] [(False, 1, 4, 1, 967, 7, 'ABC-DE-FGHI', 'LOREM', 'IPSUM', 'CLASS PRODUCT', 'F/P', 'LABELDESCRIPTION', 'N/A', 'DESCRIPTION', 'ASL66', 'ASL10', '3FE50712BA', 'ABC-DE-FGHI', 'PO', 'ITEM#', 'OEM#', 'F/P', '1')] [(False, 1, 4, 2, 967, 8, 'ABC-DE-FGHI', 'LOREM', 'IPSUM', 'CLASS PRODUCT', 'F/P', 'LABELDESCRIPTION', 'N/A', 'DESCRIPTION', 'ASL66', 'ASL10', '3FE50712BA', 'ABC-DE-FGHI', 'PO', 'ITEM#', 'OEM#', 'F/P', '1')] I can't use .split on it since it's not really a string. How can I split up the contents of a tuple inside of a list? What I am trying to do is break the results back out into variables to use. I'm not getting the results I expect to see. Ex: testlist = [(False, 1, 3, 2, 967, 6, 'ABC-DE-FGHI', 'LOREM', 'IPSUM', 'CLASS 1 PRODUCT', 'F/P', 'DESCRIPTION', 'N/A', 'DESCRIPTION', 'ASL66', 'ASL10', '3FE50712BA', 'ABC-DE-FGHI', 'PO', 'ITEM#', 'OEM#', 'F/P', '1')] for i in testlist[0]: print(testlist[0][i]) results: False 1 2 3 As suggested by roganjosh, I completely missed what I needed in my loop. first 5 items ex: testlist = [(False, 1, 3, 2, 967, 6, 'ABC-DE-FGHI', 'LOREM', 'IPSUM', 'CLASS PRODUCT', 'F/P', 'LABELDESCRIPTION', 'N/A', 'DESCRIPTION', 'ASL66', 'ASL10', '3FE50712BA', 'ABC-DE-FGHI', 'PO', 'ITEM#', 'OEM#', 'F/P', '1')] newlist = […
type: Question
has comment: http://stackoverflow.com/comment/82838602
has title: Single comma separated tuple inside of a list
has answer: http://stackoverflow.com/a/47934985
has comment: http://stackoverflow.com/comment/82839275
has comment: http://stackoverflow.com/comment/82839295
score: 0

http://stackoverflow.com/comment/82925205
type: QuestionComment
has text: @FlipperPA Thank you - this works! The issue seems to be that I needed a `SECRET_KEY` environment variable defined, which wasn't in our setup documentation.
comment on: http://stackoverflow.com/q/47971510
score: 0
type: Comment

http://stackoverflow.com/a/67175757
type: Answer
has body: For multidimensional tensors you can do: (tensor == target_value).nonzero(as_tuple=True) The resulting tensor will be of shape number_of_matches x tensor_dimension. For example, say tensor is a 3 x 4 tensor (that means the dimension is 2), the result will be a 2D-tensor with the indexes for the matches in the rows. tensor = torch.Tensor([[1, 2, 2, 7], [3, 1, 2, 4], [3, 1, 9, 4]]) (tensor == 2).nonzero(as_tuple=False) &gt;&gt;&gt; tensor([[0, 1], [0, 2], [1, 2]])
upvote count: 26
answers question: http://stackoverflow.com/q/47863001
score: 26
has comment: http://stackoverflow.com/comment/120904348
downvote count: 0
has comment: http://stackoverflow.com/comment/120964719
has comment: http://stackoverflow.com/comment/120904849

http://stackoverflow.com/comment/82951141
has text: Use a dictionary.
comment on: http://stackoverflow.com/q/47991138
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82927399
comment on: http://stackoverflow.com/q/47968575
score: 0
type: QuestionComment
type: Comment
has text: You may want to simplify your code in order to provide the minimum amount of lines reproducing your problem. It would help testing.

http://stackoverflow.com/q/47914274
linked to: http://stackoverflow.com/q/13838405
type: Question
has comment: http://stackoverflow.com/comment/82796474
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/77761225
downvote count: 0
tagged with: sorting
favorite count: 0
possible better answer: http://stackoverflow.com/a/77761225
has title: Pandas sort_values does not sort numbers correctly
tagged with: python
has answer: http://stackoverflow.com/a/47914310
has body: I have sorted a dataframe by a specific column but the answer that pandas spits out is not exactly correct. Here is the code I have used: league_dataframe.sort_values('overall_league_position') The result that the sort method yields values in column 'overall league position' are not sorted in ascending order which is the default for the method. What am I doing wrong?
upvote count: 24
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47914310
has comment: http://stackoverflow.com/comment/82796468
tagged with: dataframe
score: 24

http://stackoverflow.com/a/47985331
answers question: http://stackoverflow.com/q/47985177
downvote count: 0
has body: If you use just a filename without a path, the file will be saved in whatever the current working directory of the Python interpreter is. To see where the current working directory is, add the following code to the beginning of your program: import os print(os.getcwd()) You should then see the working directory in the output. There is a setting for the current working directory in your IDE somewhere. See e.g. the answers to this question.
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/82764549
type: AnswerComment
type: Comment
has text: @sudonym For example, if `Price` was a column of strings and you wanted to find the string with the highest count per group, this would still work. Whereas `mode` only works for numbers.
comment on: http://stackoverflow.com/a/47898858
score: 3

http://stackoverflow.com/q/47946170
has comment: http://stackoverflow.com/comment/82862596
favorite count: 0
has comment: http://stackoverflow.com/comment/82862301
tagged with: pandas
has body: I am not sure whether this is more a statistics than pandas question. But here is my problem: I have a dataset of retail transactions from N products for the period a year. Three columns of data: Col1 – Product_ID, Col2 – TransactionTime, and Col3 – TransactionPrice. I am tasked to separate two type of transactions: a) Transactions took place during promotion period, meaning the price is “significantly” lower than the regular price for a while (could be a day, a weekend, or few days) then comes back to regular price. b) For each product, imagine/draw a regression, where X = TransactionTime, Y = TransactionPrice. How to pinpoint the outliers, meaning the transactions that are “significantly” away from the regression line? My gut is to look at the regression residual value, but how to implement in pandas?
has comment: http://stackoverflow.com/comment/82862772
type: UnansweredQuestion
has title: Discover abnormal value from time-series product sales data
upvote count: 1
tagged with: python
answer count: 0
score: 1
type: Question
tagged with: time-series
downvote count: 0

http://stackoverflow.com/comment/82747585
has text: Also, if you have an instance of a program in memory and you execute another instance, the code part is shared among instances (and it does not need to be loaded again), while each instance has its own data. The "preload" you want to do is done for you by the OS when you execute for the first time.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47890232

http://stackoverflow.com/comment/82804557
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47918295
has text: @Exprator: It's 2017-05-11 04:52:25

http://stackoverflow.com/a/48264998
has comment: http://stackoverflow.com/comment/130843042
type: Answer
has body: It is done via the Auth tab of your ngrok dashboard. From IP Whitelisting Tunnel Access: You may whitelist access to tunnel endpoints on your account. The whitelist is enforced by the ngrok.com servers. It is applied globally to all of your tunnel endpoints. Any incoming connection to any of your tunnel endpoints is checked to guarantee that the source IP address of the connection matches at least one entry in your whitelist. If a connection does not match the whitelist it is terminated immediately and never forwarded to an ngrok client. As a special case, if your whitelist is empty, all connections are allowed. Managing the whitelist You can manage the IP whitelist on the auth tab of your ngrok dashboard. Enter a new IP address under the "IP Whitelist" section and then click Add Whitelist Entry. Changes to the IP Whitelist can take up to 30 seconds to take effect. IP Ranges Sometimes, you may wish to whitelist an entire range of IPs. Instead of entering just a single IP address, you may instead specify a block of IP addresses using CIDR notation. For example, to allow all IP addresses from 10.1.2.0 to 10.1.2.255, you would add 10.1.2.0/24 to your whitelist.
answers question: http://stackoverflow.com/q/47988810
score: 0

http://stackoverflow.com/q/47891048
downvote count: 2
has body: I have a function named cached_classproperty(). That function makes a caching descriptor accessible via class. def cached_classproperty(timeout=None): class Inner(object): def __init__(self, function): self.function = function def __get__(self, inst, cls): if cache_key not in cache: cache[cache_key] = self.function(cls) return cache[cache_key] return Inner Prefix cached_ is required for that function. How to name function cached_classproperty() shorter and cleaner?
has answer: http://stackoverflow.com/a/47891142
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82748504
upvote count: 0
has title: Shorthand for long function name
type: Question
score: -2

http://stackoverflow.com/q/47866503
has answer: http://stackoverflow.com/a/47867458
has title: Pass Django list of strings to JS as an array
tagged with: django
has comment: http://stackoverflow.com/comment/82698232
type: AnsweredQuestion
score: 1
tagged with: http://stackoverflow.com/tag/json
favorite count: 0
has comment: http://stackoverflow.com/comment/82698424
type: Question
answer count: 2
upvote count: 1
linked to: http://stackoverflow.com/q/11306669
tagged with: arrays
tagged with: javascript
has answer: http://stackoverflow.com/a/63561168
linked to: http://stackoverflow.com/q/21150133
accepted answer: http://stackoverflow.com/a/47867458
linked to: http://stackoverflow.com/q/18337407
has body: Goal: I want to pass list of strings in Django to template JS as an array of strings and get index for each string in the array. Problem: Javascript indexOf() is counting each character (e.g. letters, single quotes and brackets). My tries below are based on this, this and this. Code 1: I tried escapejs and safe filters, but indexOf() is returning 2 for the first item in the array (should be 0). #views.py list = [#utf-8 encoded strings] return render(request, template, {'list': list}) #template JS $('#id').ready(function() { var array = ""; console.log(array.indexOf('{{obj}}')); #obj is item in list}); Code 2: Also tried json.dumps() with encode('utf8') or json.loads() but the problem persists. #views.py list = [#utf-8 encoded strings] list = json.dumps(list, ensure_ascii=False).encode('utf8') return render(request, template, {'list': list}) #template JS $('#id').ready(function() { var array = "{{list}}"; console.log(array.indexOf('{{obj}}')); #obj is item in list});
tagged with: python
possible better answer: http://stackoverflow.com/a/63561168
has comment: http://stackoverflow.com/comment/82698206
downvote count: 0

http://stackoverflow.com/comment/82894530
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47962246
score: 0
has text: I'm still getting the wrong image size. any idea why?

http://stackoverflow.com/q/47906792
tagged with: numpy
tagged with: xml-parsing
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
has body: I have a large XML file with entries like &lt;data num_entries="1000000000"&gt; &lt;item value="3.1324213213"&gt;&lt;/item&gt; &lt;item value="6.2432343213"&gt;&lt;/item&gt; &lt;!-- ... --&gt; &lt;/data&gt; (Actually, there are multiple data entries and they are deeper in the XML tree, but let's keep it simple.) I would like to read this file with Python and put all items into a numpy array. The file is so large that ET.parse() is not an option. To avoid choking on memory, I'm using iterparse() with elem.clear() like import xml.etree.cElementTree as ET items = [] for event, elem in ET.iterparse(filename): if elem.tag == 'item': items.append(float(elem.attrib['value'])) elem.clear() items = numpy.array(items) This works, but is fairly slow since the items is allocated bit by bit. I would like to use the num_entries information of the surrounding data block to allocate the array first, i.e., something like items = None k = 0 for event, elem in ET.iterparse(filename): if elem.tag == 'item': if items is None: num_entries = get_num_entries_somehow() items = numpy.empty(num_entries) items[k] = float(elem.attrib['value']) k += 1 elem.clear() Unfortunately, iterparse gets to the parent element only after all items have been iterated over. How to access a parent attribute with iterparse()?
tagged with: http://stackoverflow.com/tag/xml
score: 2
has answer: http://stackoverflow.com/a/47906996
upvote count: 2
has title: xml: get parent attribute from iterparse element
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47906996
type: Question

http://stackoverflow.com/q/47908591
has comment: http://stackoverflow.com/comment/82784698
has answer: http://stackoverflow.com/a/47908945
type: Question
tagged with: fibonacci
answer count: 2
has comment: http://stackoverflow.com/comment/82784552
has comment: http://stackoverflow.com/comment/82784889
has body: I am relatively new to Python, so pardon my ignorance. These two implementation of while loop for generating a Fib series is resulting in very different outputs. The first one is returning the power series of 2, though I feel it is should be doing exactly what the latter is; which is returning the expected series. The second while loop is obviously doing something right. I am guessing it has to do with the way the variables as being assigned while swapping values. What is driving this difference? Appreciate your inputs and help, First while loop: def fib(n): x=0 y=1 while y &lt; n: print(y) x = y y = x + y The second while loop: x,y=0,1 while y &lt; 100: print(y) x,y = y,x+y
score: 1
accepted answer: http://stackoverflow.com/a/47908945
favorite count: 0
tagged with: while-loop
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47908644
upvote count: 2
has answer: http://stackoverflow.com/a/47908644
has title: Python Fibonacci series - different while loops
tagged with: loops
downvote count: 1

http://stackoverflow.com/comment/82773721
score: 0
type: QuestionComment
type: Comment
has text: @Splatmistro I need to manually restart it without killing the command prompt every time. I am doing it frequently
comment on: http://stackoverflow.com/q/47903196

http://stackoverflow.com/q/47918949
has comment: http://stackoverflow.com/comment/82815819
linked to: http://stackoverflow.com/q/36122496
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/87582276
duplicate of: http://stackoverflow.com/q/36122496
favorite count: 0
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/82811393
linked to: http://stackoverflow.com/q/45220389
linked to: http://stackoverflow.com/q/50245208
has body: I am trying to set password for excel file generated using openpyxl. I went through openpyxl. Openpyxl has a workbook protection functionality, but it does not support whole workbook lock using password as it does in MS Excel. I also looked into xlsxwriter, xlrd, xlwt. Is there any way in python which i can set password for an excel file ? Thanks in advance.
has answer: http://stackoverflow.com/a/47921518
has title: Set Password for excel file using Python
upvote count: 2
type: UnansweredQuestion
tagged with: openpyxl
tagged with: python
tagged with: excel
score: 2
has comment: http://stackoverflow.com/comment/87581932
has comment: http://stackoverflow.com/comment/82809987
type: Question

http://stackoverflow.com/q/47976482
downvote count: 0
has title: Facing module error on /usr/bin/python while creating nginx container using Ansible-Container build
tagged with: ansible-container
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: module
tagged with: fatal-error
answer count: 0
has body: Code : Container.yml: version: '2' settings: conductor: base: centos:7 services: ansible.nginx-container: from: "nginx:base" roles: - nginx_container ports: - "80:3000" user: root command: [nginx,-g,'daemon off'] registries: {} OS/Environment : Ansible Container, version 0.9.2 Linux, 3.10.0-327.13.1.el7.x86_64, #1 SMP Mon Feb 29 [GCC 4.8.5 20150623 (Red Hat 4.8.5-14)] /usr/bin/python **Commands Used** sudo ansible-container --debug build sudo ansible-container --debug build --use-local-python **Expected result:** Image should be build successfully. **Actual result:** Facing module error on /usr/bin/python path. Error Logs: fatal: [ansible.nginx-container]: FAILED! =&gt; { "changed": false, "module_stderr": "/bin/sh: /usr/bin/python: not found\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 0 } Please help on steps to resolve this issue.TIA
score: 1
upvote count: 1
type: Question
tagged with: nginx

http://stackoverflow.com/a/47926530
downvote count: 0
answers question: http://stackoverflow.com/q/47919423
score: 1
upvote count: 1
has body: In order to deal with a numpy array potentially larger than available ram I would use a memory mapped numpy array. On my machine ujson was 3.8 times faster than builtin json. Assuming rows is the number of lines of json: from hdfs3 import HDFileSystem import numpy as nm import ujson as json rows=int(1e8) columns=4 # 'w+' will overwrite any existing output.npy out = np.memmap('output.npy', dtype='float32', mode='w+', shape=(rows,columns)) with hdfs.open('/user/iot_all_valid.json/') as f: for row, line in enumerate(f): data = json.loads(line) # convert data to numerical array out[row] = data out.flush() # memmap closes on delete. del out
type: Answer

http://stackoverflow.com/a/47898209
downvote count: 0
has comment: http://stackoverflow.com/comment/82764655
type: Answer
has body: urllib.request.urlopen(url) (and requests.get(url)) gets HTML direcetly from server and it means it doesn't have element added by JavaScript in web browser. And also it is not logged in. But you user Selenium which load page and runs JavaScript and you can get HTML with all changes from browser.page_source and use in soup = BeautifulSoup(browser.page_source, 'html.parser') Question is why to use BeautifulSoup if Selenium has functions find_* to seach on page. EDIT: example which uses methods in Selenium and BeautifulSoup from selenium import webdriver from bs4 import BeautifulSoup import time #chromedriver = 'C:\\chromedriver.exe' #browser = webdriver.Chrome(chromedriver) browser = webdriver.Firefox() browser.get("https://www.vudu.com/") time.sleep(1) print('--- Selenium ---') all_images = browser.find_elements_by_css_selector('.border .gwt-Image') for image in all_images[:5]: # first five elements #print('image:', image.get_attribute('src')) print('alt:', image.get_attribute('alt')) print('--- BeautifulSoup ---') soup = BeautifulSoup(browser.page_source, 'html.parser') all_images = soup.select('.border .gwt-Image') for image in all_images[:5]: # first five elements #print('image:', image['src']) print('alt:', image['alt']) Result: --- Selenium --- alt: It (2017) alt: American Made alt: Dunkirk alt: mother! alt: The LEGO NINJAGO Movie --- BeautifulSoup --- alt: It (2017) alt: American Made alt: Dunkirk alt: mother! alt: The LEGO NINJAGO Movie
score: 1
has comment: http://stackoverflow.com/comment/82764401
accepted answer of: http://stackoverflow.com/q/47897359
upvote count: 1
answers question: http://stackoverflow.com/q/47897359
has comment: http://stackoverflow.com/comment/82765105
type: AcceptedAnswer

http://stackoverflow.com/comment/82875779
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/47953130
has text: I fixed the dict a little bit and now i don't get any of the errors that you guys are fighting about?

http://stackoverflow.com/a/47890603
accepted answer of: http://stackoverflow.com/q/47890602
type: Answer
answers question: http://stackoverflow.com/q/47890602
has body: I'm not convinced this is the best way to do this, but it seems to work. Please add something if there is a better way. Since I'm only interested in 0-360 degrees, I can duplicate the dataset from -360-0, and 360-720, expanding my original data set to the left and right, like so: import numpy as np # Create left side f44il = f44i.copy() f44il.index = np.arange(-360,0) # Create right side f44ir = f44i.copy() f44ir.index = np.arange(360,720) Interpolating and plotting the result looks promising (the third command shows 0-360 in a different color): f44expanded = pd.concat([f44il, f44i, f44ir]).interpolate(method='quadratic') f44expanded.plot() f44expanded[np.arange(0,360)].plot() Then I can just create a new series from the interpolated data with an index from 0-360, which looks like it gives me exactly what I want: f44final = f44expanded[np.arange(0,360)] f44final.plot() I suspect there is a better way to do this, so feel free to add an answer if you know of one.
type: AcceptedAnswer
score: 0

http://stackoverflow.com/comment/82828593
type: AnswerComment
type: Comment
has text: well it is a huge model and same model is used to create different models. Just one exception that the sub_sit is changing to an other string. And I don't need to use the for loop, since 'Mid' is the only element of it. Yes I could use a native python variable like: sub_sit = 'Mid' and then index it, but a drawback is I cannot reach sub_sit inside my constraint declerations, since the model given to the const_rules I can always get the value of m.sub_sit inside those const_rules.
comment on: http://stackoverflow.com/a/47929389
score: 0

http://stackoverflow.com/a/47868451
has comment: http://stackoverflow.com/comment/82702136
answers question: http://stackoverflow.com/q/47868306
has comment: http://stackoverflow.com/comment/82702421
has comment: http://stackoverflow.com/comment/82702433
type: Answer
has body: I had a very similar problem and it turned out cron didn’t like importing matplotlib, I ended up having to specify Agg backend. I figured it out by putting log statements after each line to see how far the program got before it crapped out. Of course, my log was empty which tipped me off that it crashed on imports. TLDR: log each line inside the script
score: 0
has comment: http://stackoverflow.com/comment/82702714

http://stackoverflow.com/comment/82777911
comment on: http://stackoverflow.com/q/47905053
type: Comment
score: 0
has text: I would attempt the paste into a single cell; the normal behaviour of Excel is then to layout all the data in the following columns and rows. There are PasteSpecial options to explore as well.
type: QuestionComment

http://stackoverflow.com/comment/82754279
type: AnswerComment
type: Comment
has text: modified as suggested :-)
comment on: http://stackoverflow.com/a/47893827
score: 0

http://stackoverflow.com/q/47932738
answer count: 1
tagged with: tensorflow
has title: TensorFlow: restoring model in a MonitoredSession
type: AnsweredQuestion
type: Question
has body: I have a model that contains multiple variables including a global step. I've been able to successfully use a MonitoredSession to save checkpoints and summaries every 100 steps. I was expecting the MonitoredSession to automatically restore all my variables when the session is run in multiple passes (based on this documentation), however this does not happen. If I take a look at the global step after running the training session again, I find that it starts back from zero. This is a simplified version of my code without the actual model. Let me know if more code is needed to solve this problem train_graph = tf.Graph() with train_graph.as_default(): # I create some datasets using the Dataset API # ... global_step = tf.train.create_global_step() # Create all the other variables and the model here # ... saver_hook = tf.train.CheckpointSaverHook( checkpoint_dir='checkpoint/', save_secs=None, save_steps=100, saver=tf.train.Saver(), checkpoint_basename='model.ckpt', scaffold=None) summary_hook = tf.train.SummarySaverHook( save_steps=100, save_secs=None, output_dir='summaries/', summary_writer=None, scaffold=None, summary_op=train_step_summary) num_steps_hook = tf.train.StopAtStepHook(num_steps=500) # Just for testing with tf.train.MonitoredSession( hooks=[saver_hook, summary_hook, num_steps_hook]) as sess: while not sess.should_stop(): step = sess.run(global_step) if (step % 100 == 0): print(step) sess.run(optimizer) When I run this code the first time, I get this output 0 100 200 300 400 The checkpoint folder at this point has checkpoints for every hundredth step up to 500. If I run the program again I would expect to see the counter start at 500 and the increase up to 900, but instead I just get the same thing and all of my checkpoints get overwritten. Any ideas?
tagged with: python
has answer: http://stackoverflow.com/a/47935062
score: 0
accepted answer: http://stackoverflow.com/a/47935062

http://stackoverflow.com/comment/82771742
type: AnswerComment
has text: this doesn't work
type: Comment
comment on: http://stackoverflow.com/a/47901555
score: 0

pyqt5
tags question: http://stackoverflow.com/q/47893838
tags question: http://stackoverflow.com/q/47930677
tags question: http://stackoverflow.com/q/48002748
type: Tag
tags question: http://stackoverflow.com/q/47997230
tags question: http://stackoverflow.com/q/47982140
tags question: http://stackoverflow.com/q/47901618
tags question: http://stackoverflow.com/q/48007100
tags question: http://stackoverflow.com/q/47996657
tags question: http://stackoverflow.com/q/47871923
tags question: http://stackoverflow.com/q/47915941
tags question: http://stackoverflow.com/q/47943676
tags question: http://stackoverflow.com/q/47964897
tags question: http://stackoverflow.com/q/47982890
tags question: http://stackoverflow.com/q/47885885
tags question: http://stackoverflow.com/q/47904562
tags question: http://stackoverflow.com/q/47890913
tags question: http://stackoverflow.com/q/47948871
tags question: http://stackoverflow.com/q/47889281
tags question: http://stackoverflow.com/q/47856872
tags question: http://stackoverflow.com/q/47915414
tags question: http://stackoverflow.com/q/47928451
tags question: http://stackoverflow.com/q/47950484
tags question: http://stackoverflow.com/q/47928724
tags question: http://stackoverflow.com/q/47994355
tags question: http://stackoverflow.com/q/47897467
tags question: http://stackoverflow.com/q/47862036
tags question: http://stackoverflow.com/q/47889554
tags question: http://stackoverflow.com/q/47972386
tags question: http://stackoverflow.com/q/47955667
tags question: http://stackoverflow.com/q/47880568
tags question: http://stackoverflow.com/q/47965618
tags question: http://stackoverflow.com/q/47984705
tags question: http://stackoverflow.com/q/47964195
tags question: http://stackoverflow.com/q/47960368
tags question: http://stackoverflow.com/q/47859456
tags question: http://stackoverflow.com/q/47858623
tags question: http://stackoverflow.com/q/48004836
tags question: http://stackoverflow.com/q/47914378
tags question: http://stackoverflow.com/q/47863400
tags question: http://stackoverflow.com/q/47970844
tags question: http://stackoverflow.com/q/47982535
tags question: http://stackoverflow.com/q/48013190
tag name: pyqt5
tags question: http://stackoverflow.com/q/47946828
tags question: http://stackoverflow.com/q/47858801
tags question: http://stackoverflow.com/q/47960494
tags question: http://stackoverflow.com/q/47903962
tags question: http://stackoverflow.com/q/47908650
tags question: http://stackoverflow.com/q/47879413

http://stackoverflow.com/comment/82688135
comment on: http://stackoverflow.com/q/47861343
has text: if you want to change image in label then DON'T destroy it.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47858928
tagged with: selenium
upvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82685658
score: -1
has title: How to get contents of div tag using selenium (python)
accepted answer: http://stackoverflow.com/a/47859459
type: Question
possible better answer: http://stackoverflow.com/a/47862238
answer count: 2
has answer: http://stackoverflow.com/a/47862238
has comment: http://stackoverflow.com/comment/82685700
tagged with: http://stackoverflow.com/tag/html
has body: How would I get the contents of the div tag that I underlined? I have already tried copying and pasting the xpath, but it doesn't work when printing the contents of the div. div = driver.find_element_by_xpath('//div[@class="sold_out_tag"]') is another thing I've tried, but when I try typing div.text, it just prints empty spaces.
tagged with: python
tagged with: css
favorite count: 0
has comment: http://stackoverflow.com/comment/82685709
has answer: http://stackoverflow.com/a/47859459
downvote count: 2

http://stackoverflow.com/comment/100172323
type: Comment
comment on: http://stackoverflow.com/a/47896365
type: AnswerComment
score: 1
has text: I've recently tried this technique of using an asyncio loop and then updating tk with root.update() but it appears to cause a "memory leak". Even running Terry's example code shows rising memory consumption with each update.

http://stackoverflow.com/q/47938864
accepted answer: http://stackoverflow.com/a/47939034
has answer: http://stackoverflow.com/a/47938937
upvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: image
type: Question
has answer: http://stackoverflow.com/a/47939034
has body: Let's say I have a below Python code: #!/usr/bin/pyton3 import time while(True): print("Hello World") time.sleep(1) Using above Python code I have created a docker image pythondocker by using a dockerfile. Now dockerfile contains a lots of packages which it needs to install first and then build an image. After the image is build, I can easily start/stop the container. Now my question is, for example, I have made few changes to my Python code and I want to update docker image pythondocker with the new changes. How can I achieve this.? One way is to fisrt stop the container, then delete the image and again build it. But building an image again will take some time as it will again install all the packages. Is there any way I can stop the image instead of deleting it and then apply the changes to the current image or may be build the image but without installing the packages/dependencies which are mentioned in dockerfile.
has answer: http://stackoverflow.com/a/47939083
downvote count: 0
has title: How to update docker images
tagged with: docker
possible better answer: http://stackoverflow.com/a/47939083
answer count: 3
score: 1
favorite count: 0

http://stackoverflow.com/comment/82945536
has text: @Faith Akici . Thanks for your awesome code, i been trying to sort the results , however it keep failing. Do you know where should I look for more info on groupby functions ? Thanks a lot again.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47978594

http://stackoverflow.com/a/47995478
has body: You can use the built in functions to get aggregate statistics. Here's how to get mean and standard deviation. from pyspark.sql.functions import mean as _mean, stddev as _stddev, col df_stats = df.select( _mean(col('columnName')).alias('mean'), _stddev(col('columnName')).alias('std') ).collect() mean = df_stats[0]['mean'] std = df_stats[0]['std'] Note that there are three different standard deviation functions. From the docs the one I used (stddev) returns the following: Aggregate function: returns the unbiased sample standard deviation of the expression in a group You could use the describe() method as well: df.describe().show() Refer to this link for more info: pyspark.sql.functions UPDATE: This is how you can work through the nested data. Use explode to extract the values into separate rows, then call mean and stddev as shown above. Here's a MWE: from pyspark.sql.types import IntegerType from pyspark.sql.functions import explode, col, udf, mean as _mean, stddev as _stddev # mock up sample dataframe df = sqlCtx.createDataFrame( [(680, [[691,1], [692,5]]), (685, [[691,2], [692,2]]), (684, [[691,1], [692,3]])], ["product_PK", "products"] ) # udf to get the "score" value - returns the item at index 1 get_score = udf(lambda x: x[1], IntegerType()) # explode column and get stats df_stats = df.withColumn('exploded', explode(col('products')))\ .withColumn('score', get_score(col('exploded')))\ .select( _mean(col('score')).alias('mean'), _stddev(col('score')).alias('std') )\ .collect() mean = df_stats[0]['mean'] std = df_stats[0]['std'] print([mean, std]) Which outputs: [2.3333333333333335, 1.505545305418162] You can verify that these values are correct using numpy: vals = [1,5,2,2,1,3] print([np.mean(vals), np.std(vals, ddof=1)]) Explanation: Your "products" column is a list of lists. Calling explode will make a new row for each element of the outer list. Then grab the "score" value from each of the exploded rows, which you have defined as the second element in a 2-elemen…
has comment: http://stackoverflow.com/comment/111825536
accepted answer of: http://stackoverflow.com/q/47995188
answers question: http://stackoverflow.com/q/47995188
score: 51
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82978140
upvote count: 51
type: Answer
has comment: http://stackoverflow.com/comment/82959314
has comment: http://stackoverflow.com/comment/82987409
has comment: http://stackoverflow.com/comment/82977608

http://stackoverflow.com/q/47993099
answer count: 3
tagged with: google-cloud-platform
downvote count: 0
score: 4
favorite count: 0
has answer: http://stackoverflow.com/a/53333043
tagged with: python
tagged with: stringio
accepted answer: http://stackoverflow.com/a/53333043
has answer: http://stackoverflow.com/a/47994939
type: Question
type: AnsweredQuestion
has body: I succeeded in uplaoding a file to the google storage, but I would like to skip the creation of a file and use StringIO instead and create the file on the google storage directly. Since I'm new to python, I just tried to use the standard method that I used for uploading the created file: def cloud_upload(self, buffer, bucket, filename): buffer.seek(0) client = storage.Client() bucket = client.get_bucket(bucket) blob = bucket.blob(filename) blob.upload_from_filename(buffer) But I get the error: TypeError: expected string or buffer But since I gave it the StringIO object, I don't know why this isn't working?
possible better answer: http://stackoverflow.com/a/63336232
has title: google storage python API - uploading an StringIO object
has answer: http://stackoverflow.com/a/63336232
upvote count: 4

http://stackoverflow.com/q/47975705
tagged with: error-handling
type: Question
has title: Batch Error Redirecting to File
accepted answer: http://stackoverflow.com/a/47977825
tagged with: batch-file
has body: I am redirecting the output of a Python script to a file. It works fine if there is no error. But if there is any error , I wish to capture the error in another file which is not happening now. Below is the script which I have written. @echo off mode con cp select=65001 set dt=%Date:~10,4%-%Date:~4,2%-%Date:~7,2% cd C:\API_DOC\softeon_project\script python -u softeon_main.py &gt;&gt;C:\API_DOC\softeon_project\log\log_%dt%.txt 2&gt;&gt;C:\API_DOC\softeon_project\log\logerr_%dt%.txt echo "after python path" pause exit Any help would be appreciable.
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82920642
linked to: http://stackoverflow.com/q/46968425
favorite count: 0
has comment: http://stackoverflow.com/comment/82922514
tagged with: python
has comment: http://stackoverflow.com/comment/82922503
has answer: http://stackoverflow.com/a/47977825
has comment: http://stackoverflow.com/comment/82921245
type: AnsweredQuestion
score: 2
linked to: http://stackoverflow.com/q/26386697
upvote count: 2
has comment: http://stackoverflow.com/comment/82922636
linked to: http://stackoverflow.com/q/44664708

http://stackoverflow.com/q/47860107
tagged with: conditional-statements
tagged with: if-statement
score: 1
has title: Python Dataframe: Create New Column Conditionally Using If Then Else Logic --> "The truth value of a Series is ambiguous"
type: Question
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/47860328
accepted answer: http://stackoverflow.com/a/47860328
tagged with: pandas
tagged with: ambiguous
has body: I am using the following code to create a new column whose value is derived based on the values in two other columns of my Python dataframe. # Create a list to store the data MSP = [] for row in df_EVENT5_18['FLT']: if df_EVENT5_18['FLT'].str.contains('1234') &amp; df_EVENT5_18['AR'].str.contains('ABC1'): MSP.append(29) elif (df_EVENT5_18['FLT'].str.contains('1234')) &amp; (df_EVENT5_18['AR'].str.contains('ABC2')): MSP.append(25) else: MSP.append('') # Create a new column from the list df_EVENT5_18['MSP'] = MSP When I run the above code, I get the following error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
favorite count: 0
possible better answer: http://stackoverflow.com/a/47860443
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47860443
type: AnsweredQuestion

http://stackoverflow.com/q/47936741
type: Question
has comment: http://stackoverflow.com/comment/82843090
has comment: http://stackoverflow.com/comment/82842843
has title: Need to get length of data frame stored in elements of list in python pandas
accepted answer: http://stackoverflow.com/a/47936914
has comment: http://stackoverflow.com/comment/82842936
tagged with: pandas
has comment: http://stackoverflow.com/comment/82842867
answer count: 1
downvote count: 0
favorite count: 0
has body: This problem can be solved by using different variable names in the loop. However, I need to check whether we can find the length of elements of List which can store data frames. I have written code to read all .csv file stored in a folder. I have created the list containing the characters. Now, I am reading one by one csv files from a folder and storing as data frames in elements of list. Hence, all Elements of list contain data frame which is obtained by reading csv files. I.e., List element 0 - "a" contain one data frame, List element 1 - "b" contain other data frames and so on. I need to find the length of Data frames contained by elements of the list. I am using len(), but this reflects the only length of the list. Kindly suggest me some solution. Below mentioned is the code. url = "C:/Users/SONY/Desktop/SEdge/Proec/Day/Master Files/20-12-2017/" count = 0; lst = ["a", "b", "c", "d"] os.chdir(url) for file in glob.glob("*.csv"): join = url + file; lst[count] = pd.read_csv(join) count +=1; print(len(lst[1]))
has comment: http://stackoverflow.com/comment/82842923
tagged with: python
has comment: http://stackoverflow.com/comment/82843066
score: 2
has answer: http://stackoverflow.com/a/47936914
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82843063
upvote count: 2
linked to: http://stackoverflow.com/q/6181935
has comment: http://stackoverflow.com/comment/82842965

http://stackoverflow.com/comment/82866407
comment on: http://stackoverflow.com/q/47947889
score: 0
has text: @Galen Actually... When I index a path (File[0]) It gives me the data for all of the folders. I would like to initiate my array in a way that I can index each path and folder. Example.... File[0][0] would index the first file in the first directory and File[0] would index the first path selected.That way, I would be able to to access the information in that file by doing File[0][0]['Frequency (GHz)'] etc.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82939065
comment on: http://stackoverflow.com/a/47985026
score: 0
type: Comment
has text: This also uses a `strip()` on an integer `pw_length_ask` so will likely trigger an error. The strip should after the `raw_input`.
type: AnswerComment

h2o
tags question: http://stackoverflow.com/q/47925196
tags question: http://stackoverflow.com/q/47983519
tag name: h2o
type: Tag

http://stackoverflow.com/q/47901147
tagged with: python-3.x
has title: preserving timestamp of a compilated python code
tagged with: python
has answer: http://stackoverflow.com/a/47912580
has body: For some reason I had to distribute some compilated python scripts. Before I start to write some workaround: I like to know if there is a possibility to preserve the timestamp of the compilation date &amp; time using python code.
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/47912580
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/82769273
has comment: http://stackoverflow.com/comment/82775348
has comment: http://stackoverflow.com/comment/82769090

http://stackoverflow.com/a/48014252
upvote count: 5
has comment: http://stackoverflow.com/comment/105676209
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47999477
answers question: http://stackoverflow.com/q/47999477
score: 5
has body: Found a solution: Run this to install with conda or pip if the package is not available to conda: while read requirement; do conda install --yes $requirement || pip install $requirement; done &lt; requirements.txt Once it's done you can use conda to export the environment yaml: conda env export &gt; environment.yml
type: AcceptedAnswer

http://stackoverflow.com/a/47947378
has comment: http://stackoverflow.com/comment/82864802
has body: You are iterating over all the passwords with the inner loop on the first iteration of the outer loop. On the second iteration of the outer loop, there are no more passwords to iterate (fp's current position is at the end of the file). You could fp.seek(0) to reset fp after each user iteration: for user in fu: for password in fp: print "Username: " + user.rstrip('\n') + " Password: " + password.rstrip('\n') fp.seek(0) Or you could read the passwords once into a list: passwords = list(fp) for user in fu: for password in passwords: print "Username: " + user.rstrip('\n') + " Password: " + password.rstrip('\n') There's a tradeoff between file access and memory usage here.
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/82864832
has comment: http://stackoverflow.com/comment/82865129
upvote count: 3
has comment: http://stackoverflow.com/comment/82865191
has comment: http://stackoverflow.com/comment/82865674
accepted answer of: http://stackoverflow.com/q/47947341
has comment: http://stackoverflow.com/comment/82864846
answers question: http://stackoverflow.com/q/47947341
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/63517667
has body: As you have initiated a --headless google-chrome instance by setting: chrome_options.add_argument("--headless") further, it won't be possible to make the Browsing Context visible again within the same session. Reason When you configure ChromeDriver using ChromeOptions() to initiate headless in the process of initiating a new Chrome Browsing Session the configuration gets baked into the chromedriver executable and will persist till the lifetime of the WebDriver and remains uneditable. So you modify the ChromeOptions of the WebDriver instance which is currently in execution. Even if you are able to extract the ChromeDriver and ChromeSession attributes e.g. Session ID, Cookies and other session attributes from the already initiated ChromeDriver and Chrome Browsing Session still you won't be able to change the set of attributes of the ChromeDriver. A cleaner way would be to call driver.quit() within tearDown(){} method to close and destroy the current ChromeDriver and Chrome Browser instances gracefully and then span a new set of ChromeDriver and Chrome Browser instance with the new set of configurations. References You can find a couple of relevant discussions in: How to set selenium webdriver from headless mode to normal mode within the same session? Change ChromeOptions in an existing webdriver How do I make Chrome Headless after I login manually
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47972282
downvote count: 0
score: 1

http://stackoverflow.com/comment/82874829
comment on: http://stackoverflow.com/q/47952433
score: 0
type: QuestionComment
type: Comment
has text: then you are not even yet sure on what to do next. if it's just about having relation then use ManytoMany relation instead of foreign key

http://stackoverflow.com/comment/82944455
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47987707
score: 2
has text: Why are the "sets" lists instead of actual sets?

http://stackoverflow.com/comment/82963945
comment on: http://stackoverflow.com/q/47997164
has text: Just use `pip install` instead of `sudo pip install`. When in doubt, use `/usr/bin/pip`. Better yet, `brew install virtualenv`, [create a separate environment](https://virtualenv.pypa.io/en/stable/userguide/) for each project, and install project-specific dependencies. This way projects never conflict with each other.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/47897008
has title: How would I make my Python Discord bot mimic all messages sent?
has comment: http://stackoverflow.com/comment/82760800
type: Question
answer count: 1
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/47899343
tagged with: python
favorite count: 0
tagged with: python-3.x
has body: I am writing a Discord bot using Python (v. 3.6.1). One of its functions detects all messages sent in a channel, processes them, and then responds to the messages in said channel. (At least, that's what I want it to do.) I have tried this: @bot.event async def on_message(message): await bot.say(message.content) The function responds when a message is sent, but not in the way that I want it to. I instead get an error: discord.errors.InvalidArgument: Destination must be Channel, PrivateChannel, User, or Object. Received NoneType How would I fix this? Many thanks!
accepted answer: http://stackoverflow.com/a/47899343
upvote count: 1
has comment: http://stackoverflow.com/comment/82760858
type: AnsweredQuestion
tagged with: discord.py

http://stackoverflow.com/q/47986858
has answer: http://stackoverflow.com/a/47986903
downvote count: 0
has comment: http://stackoverflow.com/comment/82942501
favorite count: 0
tagged with: python-3.x
has body: I am running a python script via terminal. The script contains a main function. It runs other programs in some directory and all those programs are in Python too. While running these sub programs, I need to enter their required input values in the terminal using this main program(not command line arguments). Ex: MainProgram calls --dir1/pg1.py ----inputs 10 20 30 Main program calls --dir1/pg2.py ----inputs 100 20 30 like wise the inputs to the subprograms are to be given by the main program. I am trying to automate the process of giving input to a program and I need to do it with the help of a program. Ex: the given below is a simple program for finding factorial i=1 fact=1 num=input("Enter the num : ") while i&lt;=num: fact*=i i+=1 print fact I need a program(say MainProgram.py) that on execution calls the above program and give the required input to it and gets the output and validates if it is right or not. Please help me with this. Been searching for a solution for long.
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/3345202
upvote count: 1
tagged with: python
answer count: 4
has title: Give inputs to a running program using Python
has answer: http://stackoverflow.com/a/47987999
score: 1
has answer: http://stackoverflow.com/a/47989795
has answer: http://stackoverflow.com/a/47990014
has comment: http://stackoverflow.com/comment/82942560
type: Question

http://stackoverflow.com/a/47927438
downvote count: 1
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82827928
accepted answer of: http://stackoverflow.com/q/47924089
answers question: http://stackoverflow.com/q/47924089
type: Answer
has comment: http://stackoverflow.com/comment/82823971
has comment: http://stackoverflow.com/comment/82828474
has body: Check this AWS documentation out. I think it would be useful. http://docs.aws.amazon.com/AmazonS3/latest/dev/UploadingObjects.html The import part of the link is below: Depending on the size of the data you are uploading, Amazon S3 offers the following options: Upload objects in a single operation—With a single PUT operation, you can upload objects up to 5 GB in size. For more information, see Uploading Objects in a Single Operation. Upload objects in parts—Using the multipart upload API, you can upload large objects, up to 5 TB. The multipart upload API is designed to improve the upload experience for larger objects. You can upload objects in parts. These object parts can be uploaded independently, in any order, and in parallel. You can use a multipart upload for objects from 5 MB to 5 TB in size. For more information, see Uploading Objects Using Multipart Upload API. We recommend that you use multipart uploading in the following ways: If you're uploading large objects over a stable high-bandwidth network, use multipart uploading to maximize the use of your available bandwidth by uploading object parts in parallel for multi-threaded performance. If you're uploading over a spotty network, use multipart uploading to increase resiliency to network errors by avoiding upload restarts. When using multipart uploading, you need to retry uploading only parts that are interrupted during the upload. You don't need to restart uploading your object from the beginning. For more information about mutipart uploads, see Multipart Upload Overview.
has comment: http://stackoverflow.com/comment/82828348
score: 1

http://stackoverflow.com/q/47961341
tagged with: file-handling
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82892398
tagged with: python
has answer: http://stackoverflow.com/a/47961432
accepted answer: http://stackoverflow.com/a/47961432
type: AnsweredQuestion
upvote count: 1
downvote count: 1
has body: This is my first question so sorry if I'm not being clear in less words. I'm writing a python script in which i ask user to input operation he wants to perform. I've two functions with to specific operations (A and N). I've used if-else statement to check and apply specific function and write whole output to a new file. after closing file handle i'm calling another function in same check box (if-else). about() its output should be displayed on command prompt according to if-else check but i get "Value error: I/O operation on closed file." this is what i've done so far obj = PhysioCal() if (args.operation == 'N' or args.operation == 'n'): with open (args.output,"w") as fout: sys.stdout=fout t_n=obj.nucleotide(obj.fasta_reader(args.input)) sys.stdout.close() obj.about(t_n) elif (args.operation == 'A' or args.operation == 'a'): with open (args.output,"w") as fout: sys.stdout=fout t_a=obj.amino_acid(obj.fasta_reader(args.input)) sys.stdout.close() obj.about(t_a) else: obj.about(0) print("\n\t\t\tProcess Failed") print("\t\t\aYou have seleccted wrong operation") print("\t\tuse -h argument for help menu") here t_n and t_a are time which functions return. about function shows that time on command prompt. also is that write way to get all the outputs of function in a file instead of prints on cmd ?
type: Question
has comment: http://stackoverflow.com/comment/82891860
has comment: http://stackoverflow.com/comment/82892348
has comment: http://stackoverflow.com/comment/82891960
score: 0
has title: function call error after closing a file in python
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/82685706
score: 0
type: Comment
has text: Of course there is. But don't do that. This will be much faster.
comment on: http://stackoverflow.com/a/47860328
type: AnswerComment

http://stackoverflow.com/a/47928156
has body: I assume you meant to ask if they are arbitrary. Yes, you could use any name instead of f here, e. g. os.path.realpath(xmlfile) for xmlfile in glob.glob('*.xml').
type: Answer
answers question: http://stackoverflow.com/q/47928093
score: 3
downvote count: 1
upvote count: 4

http://stackoverflow.com/a/47867820
has body: Django's querysets have a value() method that yields {fieldname:fieldvalue} dicts instead of model instances, so assuming you don't expect to retrieve related models values, this should solve your problem: for q in queryset.values(): # your code here if you need values from related objects then you'll have to pass all the desired fields names to values, using the "relatedfield__fieldname" syntax (the same used for related lookups) for related objects fields - ie if country is actually a foreign_key to a Country models with a name field and you want the country name in your result, you'll need: fields = ["name", "place", "date", "time", "country__name", "city") for q in queryset.values(*fields): # your code here Also (unrelated but...) the way you add items to your list is uselessly complicated (and not really efficient). You could just build your dict and append it to the list: # awful name FWIW... what about 'records' or 'rows' or, # well, something meaningful ? list_dict = [] for q in queryset: d = dict(name=q.name, place=q.place, time=q.time, #etc) list_dict.append(d) which could be further improved into a list expression: list_dict = [ dict(name=q.name, place=q.place, time=q.time, #etc) for q in qs ] but since queryset.values() already yields dicts, all you really need is actually: fields = ["name", "place", "date", "time", "country", "city") list_dict = list(queryset.values(*fields))
type: Answer
has comment: http://stackoverflow.com/comment/82707678
accepted answer of: http://stackoverflow.com/q/47867345
answers question: http://stackoverflow.com/q/47867345
type: AcceptedAnswer
score: 0

http://stackoverflow.com/comment/82719452
has text: @roganjosh if you can code in python 2.7 yeah please :)
type: QuestionComment
comment on: http://stackoverflow.com/q/47876558
type: Comment
score: 0

http://stackoverflow.com/comment/82786072
comment on: http://stackoverflow.com/a/47909002
has text: @TaiLinWu you can using Jaz's answer
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47948986
has body: Don't use the tuple function, use the parenthesis syntax. t: Tuple[int, int] = (l[0], l[1])
answers question: http://stackoverflow.com/q/47948965
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/47948965
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/112823036
downvote count: 0
has comment: http://stackoverflow.com/comment/82867922
score: 4

http://stackoverflow.com/comment/82976349
type: Comment
has text: @ Maxim thanks,so its not necessary for me to use tf.nn,batch_normalization,I can use tf.layers .batch_normalization and be sure for sharing the variables
comment on: http://stackoverflow.com/a/47984274
type: AnswerComment
score: 0

ldap
tags question: http://stackoverflow.com/q/47887000
tags question: http://stackoverflow.com/q/47930431
tags question: http://stackoverflow.com/q/47941247
tag name: ldap
tags question: http://stackoverflow.com/q/47994698
tags question: http://stackoverflow.com/q/47863479
type: Tag

http://stackoverflow.com/a/47935755
has comment: http://stackoverflow.com/comment/82841653
accepted answer of: http://stackoverflow.com/q/47935681
type: AcceptedAnswer
has body: I doubt you need groupby here df= df.sort_values('Mb',ascending=False) df['ttt'] = df['Mb'].div(1000) # Based on the comment. `df['ttt'] = pd.to_numeric(df['Mb'],errors='coerce').div(1000)` Index prt Mb ttt 2 2017-08-10 uu 200 0.20 5 2017-08-16 uu 200 0.20 4 2017-08-11 tt 150 0.15 1 2017-08-09 uu 140 0.14 0 2017-08-09 tt 0 0.00 3 2017-08-11 tt 0 0.00 To remove the tt from the dataframe a simple boolean indexing would be enough i.e df[df['prt'].eq('uu')] Index prt Mb ttt 2 2017-08-10 uu 200 0.20 5 2017-08-16 uu 200 0.20 1 2017-08-09 uu 140 0.14
has comment: http://stackoverflow.com/comment/82846731
has comment: http://stackoverflow.com/comment/82841032
answers question: http://stackoverflow.com/q/47935681
has comment: http://stackoverflow.com/comment/82841353
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82840988
has comment: http://stackoverflow.com/comment/82856884
has comment: http://stackoverflow.com/comment/82856323
has comment: http://stackoverflow.com/comment/82841358
has comment: http://stackoverflow.com/comment/82840982
upvote count: 2
has comment: http://stackoverflow.com/comment/82841341

http://stackoverflow.com/comment/82679277
type: Comment
has text: The only change I made to your solution was to add two groups, `20\d{6}` -> `(20\d{6})` and `\d{6}` -> `(\d{6})` which I then parse with `"".join(match.groups())`. I could use `match.string` without the groups but I don't know how to get rid of `\D?` match in the middle. And I replaced `re.match` with `re.search` as you suggested (otherwise it does not work).
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/47856906

http://stackoverflow.com/comment/82914868
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47972522
has text: can you also put the content of `requirements.txt` into your question?
score: 0

http://stackoverflow.com/comment/82902993
score: 0
type: Comment
has text: I see what I was doing wrong. I was trying to concatenate len_ by doing '[' + len_ + ':]' . If you have the time can you explain to my why I was unable to concatenate it that way? Anyways thank you for your help =)
comment on: http://stackoverflow.com/a/47966575
type: AnswerComment

http://stackoverflow.com/q/47924373
accepted answer: http://stackoverflow.com/a/47924928
tagged with: dialog
score: 1
has comment: http://stackoverflow.com/comment/82816584
has comment: http://stackoverflow.com/comment/82817298
has title: Feed python output to whiptail
has comment: http://stackoverflow.com/comment/82816404
has comment: http://stackoverflow.com/comment/82817341
type: Question
tagged with: bash
answer count: 1
downvote count: 0
tagged with: whiptail
tagged with: linux
has body: I would like to use a TUI (text user interface) on a headless linux server by passing output of some PYTHON code to 'whiptail'. Unfortunately, nothing seems to happen in whiptail. When I pipe the output from a regular shell script, then whiptail works fine. Here is what I have: data-gen.sh #!/bin/bash echo 10 sleep 1 echo 20 sleep 1 ... ... echo 100 sleep 1 $ ./data-gen.sh | whiptail --title "TEST" --gauge "GAUGE" 0 50 0 I get the below progress bar incrementing as expected. Now I try to replicate same thing from python: data-gen.py #!/usr/bin/python import time print 10 time.sleep(1) ... ... print 100 time.sleep(1) $ ./data-gen.py | whiptail --title "TEST" --gauge "GAUGE" 0 50 0 I get the below progress bar staying at 0%. No increment seen. Whiptail does exit once the python program in the background has exited. Any ideas how to get python output to be piped successfully to whiptail ? I have not tried this with dialog; since I wanted to stick to whiptail which is pre-installed on most ubuntu distros.
has comment: http://stackoverflow.com/comment/82816466
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/47924928
upvote count: 1
type: AnsweredQuestion

http://stackoverflow.com/comment/82938571
comment on: http://stackoverflow.com/q/47984141
score: 0
has text: I tend to have the outer a = None. Reason is that, as your logic becomes more conditional and complicated, you may encounter NameError where you branches haven't assigned **a** and that will throw you. With **a** set, you can do **getattr(a, 'somevar','default')** against None for example. In your **simple** example, might not be worth it.
type: Comment
type: QuestionComment

wikipedia-api
tag name: wikipedia-api
type: Tag
tags question: http://stackoverflow.com/q/47869526

http://stackoverflow.com/comment/82934047
type: QuestionComment
comment on: http://stackoverflow.com/q/47982731
type: Comment
has text: Why are you defining functions within a function? Seems like `scope_test` must be a class, and the other functions must serve as class functions. It would be better if you could elaborate what is that you want to do.
score: 0

http://stackoverflow.com/comment/82883150
type: QuestionComment
has text: @ImportanceOfBeingErnest creating a reproducible example was definitely my aim, though I see it could have been reduced further. Given that other `plt.savefig()` experiments worked, the `subplots()` command and adding layers to `ax` was my main suspect. Thank you for the answer!
comment on: http://stackoverflow.com/q/47956746
score: 0
type: Comment

http://stackoverflow.com/q/47858219
has comment: http://stackoverflow.com/comment/82681162
has comment: http://stackoverflow.com/comment/82681020
has comment: http://stackoverflow.com/comment/82680998
has title: Open a file, reformat, and write to a new file in Python 3
has comment: http://stackoverflow.com/comment/82681180
has answer: http://stackoverflow.com/a/47858725
has body: I'm very new to Python (a couple of weeks). I'm doing the Python for Everybody course on Coursera and decided to expand some ideas into an app I'd like to write. I want to take a txt file of writing quotes, remove some unnecessary characters and newlines, and then write the newly formatted string to a new file. This file will be used to display random quotes in the terminal (the latter isn't a requirement here). An entry in the txt file looks like: “The road to hell is paved with works-in-progress.” —Philip Roth, WD some other stuff here “Some other quote.” —Another Author, Blah blah And I'd like the following to be written to a new file: "The road to hell is paved with works-in-progress." —Phillip Roth "Some other quote." —Another Author I'd like to remove the newline between the quote and author and replace with a space. I'd also like to remove everything from the comma after the author onwards (so it's just: quote [space] author). The file has 73 of these, so I'd like to run through the file making these changes, and then write to a new file with the newly formatted quotes. The final output will simply be: "blah blah blah" -Author I've tried various approaches, and currently working going through the file in a for loop writing the two segments to lists where I was thinking of joining the lists. But I'm stuck and also not sure if this is overkill. Any help would be gratefully received. Now that I have the two lists I can't seem to join them, and I'm not sure if doing it this way is even right. Any thoughts? Code so far: fh = open('quotes_source.txt') quote = list() author = list() for line in fh: # Find quote segment and assign to a string variable if line.startswith('“'): phrase_end = line.find('”')+1 phrase_start = line.find('“') phrase = line[phrase_start:phrase_end] quote.append(phrase) # Find author segment and assign to a string variable if line.startswith('—'): name_end = line.find(',') name = line[:name_end] author.append(name) print(quote) print(author)
has comment: http://stackoverflow.com/comment/82681095
has comment: http://stackoverflow.com/comment/82680967
tagged with: file
tagged with: python
type: AnsweredQuestion
tagged with: list
score: 1
has answer: http://stackoverflow.com/a/47858721
has comment: http://stackoverflow.com/comment/82681200
type: Question
upvote count: 2
answer count: 2
possible better answer: http://stackoverflow.com/a/47858721
downvote count: 1
has comment: http://stackoverflow.com/comment/82681091
tagged with: string
tagged with: string-concatenation
accepted answer: http://stackoverflow.com/a/47858725
favorite count: 0

http://stackoverflow.com/q/47944872
accepted answer: http://stackoverflow.com/a/47944941
has body: What is the difference between these two named urls in Django? re_path('articles/(?P&lt;year&gt;[0-9]{4})/', views.year_archive), path('articles/&lt;int:year&gt;/', views.year_archive), They appear to do the same?
tagged with: python
has comment: http://stackoverflow.com/comment/82859867
has comment: http://stackoverflow.com/comment/82860707
type: AnsweredQuestion
has title: Difference between named urls in Django?
upvote count: 3
tagged with: django
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/47944941
tagged with: django-urls
score: 2
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82859480
has comment: http://stackoverflow.com/comment/82862600

restructuredtext
tags question: http://stackoverflow.com/q/47944831
type: Tag
tag name: restructuredtext

http://stackoverflow.com/q/48013766
has comment: http://stackoverflow.com/comment/82998051
has comment: http://stackoverflow.com/comment/82997606
answer count: 0
has body: I have been working on a small email utility in Python after following an online tutorial. The only issue seems to be the data I am printing is None. For example, the sender and subject of the email, when printed, are None. Here is my code: import imaplib import email class email_account: #u: email username #domain: email domain #pwd: email account password #smtp_server: SMTP server for email account. I.e. "imap.gmail.com" #smtp_port: SMTP server port number. I.e. 993 def __init__(self, u, domain, pwd, smtp_server, smtp_port): self.u = u self.domain = domain self.pwd = pwd self.smtp_server = smtp_server self.smtp_port = smtp_port #extracts information from an email def read_email(self, mail): return None #open the inbox for the email account and get the IDs of all emails def open_inbox(self, mail): mail.select("inbox") type, data = mail.search(None, "all") mail_ids = data[0] id_list = mail_ids.split() #get ID of first and last email first_id = int(id_list[0]) last_id = int(id_list[-1]) print("First ID: " + str(first_id) + " -&gt; " + str(int(last_id))) #iterate through all emails retrieved from the inbox for x in range(first_id, last_id, 1): print("RAN") t, d = mail.fetch(str(x), "(RFC822)") for message_parts in d: print(isinstance(message_parts[1], str)) message = email.message_from_string(str(message_parts[1])) subject = message["subject"] sender = message["from"] print("From: " + str(sender) + "\n") print("Subject: " + str(subject) + "\n") #login to the email account with the provided credentials def login(self): mail = imaplib.IMAP4_SSL(self.smtp_server) mail.login(self.u, self.pwd) self.open_inbox(mail) new_email = email_account("my_email", "@gmail.com", "password", "imap.gmail.com", 993) new_email.login() 'print("From: " + str(sender) + "\n")' prints out From: None and print("Subject: " + str(subject) + "\n") prints out Subject: None. What is going on here?
tagged with: imaplib
type: Question
has comment: http://stackoverflow.com/comment/82996595
has title: Python: Getting Info of Email with IMAP library results in "None" for data
score: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/47857095
has comment: http://stackoverflow.com/comment/82679065
type: Answer
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47856902
downvote count: 0
answers question: http://stackoverflow.com/q/47856902
score: 1
has body: You must always call functions with variables. In this case, you are calling long_div with the variable w which must be defined elsewhere. All you need to do is replace the occurrences of w in your function call with the formula that you gave in the question. To do this, it will be easiest to create a local variable that will hold the outcome of the formula. for n in range(1, K+1): f = 16 * (1/5) ** (n*2 - 1) long_div(f, 5*5, f) we use the formula: 16 * (1/5) ** (n*2 - 1) here as it produces the sequence of calculations that you put in the question.

http://stackoverflow.com/a/48122915
type: Answer
answers question: http://stackoverflow.com/q/48014240
has comment: http://stackoverflow.com/comment/83288823
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/83290489
has comment: http://stackoverflow.com/comment/83290096
has comment: http://stackoverflow.com/comment/83290944
has comment: http://stackoverflow.com/comment/83289791
upvote count: 1
has comment: http://stackoverflow.com/comment/83290277
type: AcceptedAnswer
has body: 1) In curl you are reading and writing cookies (-b cookies -c cookies). With requests you are not using session objects http://docs.python-requests.org/en/master/user/advanced/#session-objects so your cookie data is lost. 2) You define a https proxy and then you are trying to connect over http with no proxy (to data-api-gslb.adnxs.net). Define both http and https, but only once on the session object. See http://docs.python-requests.org/en/master/user/advanced/#proxies. (This is probably the root cause of the error message you see.) 3) Requests handles redirects automatically there is no need to extract the location header and use it in the next request, it will automatically be redirected. So there are 3 steps not 4 when the other errors are fixed. (This also answers Hetzroni's question in the comments above.) So use s = requests.Session() s.proxies = { 'http':'http://proxy.xxxxxx.net:xxxxx', 'https':'https://proxy.xxxxxx.net:xxxxx' } # set this only once using valid proxy urls. then use s.get() and s.post() instead of requests.get() and requests.post()
has comment: http://stackoverflow.com/comment/83286550
has comment: http://stackoverflow.com/comment/83289206
accepted answer of: http://stackoverflow.com/q/48014240

http://stackoverflow.com/comment/82735967
has text: Why would you want to send this as form-data? You should use JSON.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47884601
type: Comment

http://stackoverflow.com/comment/82867521
type: QuestionComment
has text: `age >10 <=20` doesn't do what you think. It expands to the equivalent of `age > 10 and 10 <= 20`. Which means your `Adult` case is never reached, you only print `Kid` or `Teen`. You want `10 < age <= 20`.
score: 1
comment on: http://stackoverflow.com/q/47948749
type: Comment

http://stackoverflow.com/comment/82870001
type: Comment
type: QuestionComment
has text: The dictionary being passed to the template doesn't contain "section". Did you mean "sections"?
score: 0
comment on: http://stackoverflow.com/q/47950107

http://stackoverflow.com/comment/82787910
type: QuestionComment
comment on: http://stackoverflow.com/q/47899122
score: 1
has text: https://stackoverflow.com/questions/5666056/matplotlib-extracting-data-from-contour-lines hth
type: Comment

http://stackoverflow.com/comment/82755584
type: QuestionComment
comment on: http://stackoverflow.com/q/47894252
score: 0
has text: @guillermochamorro in the navbar are the login/register forms. As is going to be in different pages, I want to call my view in 'base'.html' once for all.
type: Comment

http://stackoverflow.com/comment/82759642
has text: Well, since I did not find someone who could answer my question, and after a few hours and hours of research, I found the solution to this inconvenience that I was presenting, the first thing was to have knowledge of the version of wkhtmltopdf that I had installed, in my case it was: "0.12.4" which did not have the (patched qt), so my solution was to return to the version "wkhtmltopdf 0.12.3 (with patched qt)"
type: QuestionComment
comment on: http://stackoverflow.com/q/47875705
score: 0
type: Comment

http://stackoverflow.com/comment/82921519
has text: Hmm, `range(65,91)` is quite small: only uppercase letters! `'Austria`' would be rejected because it contains lower case letter and `ord('a')` is already 97. Not even speaking of punctuations and digits which are indeed in ASCII charset. What are you trying to do exactly?
type: Comment
score: 1
comment on: http://stackoverflow.com/q/47976142
type: QuestionComment

http://stackoverflow.com/comment/82781769
type: Comment
type: QuestionComment
score: 2
has text: what's your question?
comment on: http://stackoverflow.com/q/47907306

http://stackoverflow.com/comment/82780229
comment on: http://stackoverflow.com/a/47898560
type: AnswerComment
has text: I receive an error saying no attribute RNN for it: AttributeError: module 'tensorflow.python.ops.nn' has no attribute 'rnn'
score: 0
type: Comment

http://stackoverflow.com/a/47876716
has comment: http://stackoverflow.com/comment/82719497
has comment: http://stackoverflow.com/comment/82719353
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47876157
has comment: http://stackoverflow.com/comment/82719328
has comment: http://stackoverflow.com/comment/82719081
has body: Thanks for adding sample data. Taking a deeper look at your data it is clearly not standardized. If you were to apply a StandardScaler to the dataset and try fitting again you will find that the prediction discrepancy disappears. While this result is at least consistent it is still troubling that it raises a LineSearchWarning and ConvergenceWarning. To that I would say you do have an exceedingly low tolerance here at 1e-15. Given the very high regularization penalty ratio (1e9) you have applied, lowering tol to the default 1e-4 will really have no impact whatsoever. This allows the model to properly converge and still produces the same outcome (in a much faster run time). My full process looks like this: import numpy as np from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression ss = StandardScaler() cols1 = np.arange(9) cols2 = np.array([1,0,2,3,4,5,6,7,8]) X = ss.fit_transform(df.drop('target', axis=1)) lr = LogisticRegression(solver='newton-cg', tol=1e-4, C=1e9) lr.fit(X[:, cols1], df['target']) preds_1 = lr.predict_proba(X[:, cols1]) lr.fit(X[:, cols2], df['target']) preds_2 = lr.predict_proba(X[:, cols2]) preds_1 array([[ 0.00000000e+00, 1.00000000e+00], [ 0.00000000e+00, 1.00000000e+00], [ 0.00000000e+00, 1.00000000e+00], ..., [ 1.00000000e+00, 9.09277801e-31], [ 1.00000000e+00, 3.52079327e-35], [ 1.00000000e+00, 5.99607407e-30]]) preds_2 array([[ 0.00000000e+00, 1.00000000e+00], [ 0.00000000e+00, 1.00000000e+00], [ 0.00000000e+00, 1.00000000e+00], ..., [ 1.00000000e+00, 9.09277801e-31], [ 1.00000000e+00, 3.52079327e-35], [ 1.00000000e+00, 5.99607407e-30]]) The assertion preds_1 == preds_2 will fail, but the difference is on the order of 1e-40 + for each value, which I would say is well beyond any plausible level of significance.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82719607
downvote count: 0
has comment: http://stackoverflow.com/comment/82719182
accepted answer of: http://stackoverflow.com/q/47876157
type: Answer

http://stackoverflow.com/comment/82739992
has text: Do you need `100 - df['abc'].cumsum())` ?
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47887131

http://stackoverflow.com/q/47983897
has comment: http://stackoverflow.com/comment/82939704
score: 0
accepted answer: http://stackoverflow.com/a/47990440
answer count: 1
has answer: http://stackoverflow.com/a/47990440
tagged with: python
has body: As a simple experiment, I want to compute the stft of an audio file: sample_rate, samples = wav.read(file) f, t, Zxx = stft(samples, sample_rate) _, reconstructed = istft(Zxx, sample_rate) padded_samples = np.zeros_like(reconstructed) padded_samples[:len(samples)] = samples print (np.sum(padded_samples - reconstructed)) Output: -1.37309940428. Pretty small, isn't it? Given that samples is of shape (9218368,). test_file = os.path.join(temp_folder, 'reconstructed.wav') wav.write(test_file, sample_rate, reconstructed) The reconstructed file sounds terrible. The original is barely heareble underneath the noise. Have I made a mistake, or is it simply impossible to recover an audio file from the STFT? Do you have any other suggestions on how to convert an audio file to some kind of processable data and then reconstruct it from that? What other kind of data structures can be used to process audio files? Thank you. EDIT: As suggested by Warren: print (samples.shape) print (samples.dtype) print (reconstructed.dtype) Output: (9218368,) int16 float64 According to the scipy docs int and float input have different meaning when writing a wav file. I tried casting reconstructed to np.int16: rounded_reconstructed = np.rint(reconstructed).astype(np.int16) test_file = os.path.join(temp_folder, 'reconstructed.wav') wav.write(test_file, sample_rate, rounded_reconstructed) The result is barely distinguishable from the original. Thank you for the help.
tagged with: audio
type: AnsweredQuestion
tagged with: scipy
tagged with: signal-processing
type: Question
has title: Python: Reconstruct audio file from STFT

http://stackoverflow.com/q/48007286
tagged with: python
accepted answer: http://stackoverflow.com/a/48247023
score: 0
type: AnsweredQuestion
tagged with: matplotlib
type: Question
tagged with: numpy
answer count: 1
has answer: http://stackoverflow.com/a/48247023
has body: Recently I followed a few tutorials on machine learning, and now I want to test if I can make some image recognition program by myself. For this I want to use the CIFAR 10 dataset, but I think I have a small problem in the conversion of the dataset. For who is not familiar with this set: the dataset comes as lists of n rows and 3072 columns, in which the first 1024 columns represent the red values, the second 1024 the green values and the last are the blue values. Each row is a single image (size 32x32) and the pixel rows are stacked after each other (first 32 values are the red values for the top-most row of pixels, etc.) What I wanted to do with this dataset is to transform it to a 4D tensor (with numpy), so I can view the images with matplotlibs .imshow(). the tensor I made has this shape: (n, 32, 32, 3), so the first 'dimension' stores all images, the second stores rows of pixels, the third stores individual pixels and the last represents the rgb values of those pixels. Here is the function I made that should do this: def rawToRgb(data): length = data.shape[0] # convert to flat img array with rgb pixels newAr = np.zeros([length, 1024, 3]) for img in range(length): for pixel in range(1024): newAr[img, pixel, 0] = data[img, pixel] newAr[img, pixel, 1] = data[img, pixel+1024] newAr[img, pixel, 2] = data[img, pixel+2048] # convert to 2D img array newAr2D = newAr.reshape([length, 32, 32, 3]) # plt.imshow(newAr2D[5998]) # plt.show() return newAr2D Which takes a single parameter (a tensor of shape (n, 3072)). I have commented out the pyplot code, as this is only for testing, but when testing, I noticed that everything seems to be ok (I can recognise the shapes of the objects in the images, but I am not sure if the colours are good or not, as I get some oddly-coloured images as well as some pretty normal images... Here are a few examples: purple plane, blue cat, normal horse, blue frog. Can anyone tell me wether I am making a mistake or not?
has title: Check if cifar10 is converted well

http://stackoverflow.com/comment/82828498
type: Comment
type: QuestionComment
has text: You passed *the same array* to both constructors... why did you not expect it to change?
comment on: http://stackoverflow.com/q/47929642
score: 0

http://stackoverflow.com/q/47935397
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: python
has title: group by two columns and cumulative sum with lookback window of 6 months on date
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/47935580
has body: Original dataset userId createDate grade 0 2016-05-08 22:00:49.673 2 0 2016-07-23 12:37:11.570 7 0 2017-01-03 12:05:33.060 7 1009 2016-06-27 09:28:19.677 5 1009 2016-07-23 12:37:11.570 8 1009 2017-01-03 12:05:33.060 9 1009 2017-02-08 16:17:17.547 4 2011 2016-11-03 14:30:25.390 6 2011 2016-12-15 21:06:14.730 11 2011 2017-01-04 20:22:31.423 2 2011 2017-08-08 16:17:17.547 7 I want rolling sum of grade for each user with lookback window of 6 months from createDate i.e (sum of all grades for that under 6 months from create date) Expected: userId createDate 0 2016-05-08 22:00:49.673 2 2016-07-23 12:37:11.570 9 2017-01-03 12:05:33.060 14 1009 2016-06-27 09:28:19.677 5 2016-07-23 12:37:11.570 13 2017-01-03 12:05:33.060 17 2017-02-08 16:17:17.547 13 2011 2016-11-03 14:30:25.390 6 2016-12-15 21:06:14.730 17 2017-01-04 20:22:31.423 19 2017-08-08 16:17:17.547 7 My current try is incorrect : df.groupby(['userId','createDate'])['grade'].mean().groupby([pd.Grouper(level='userId'),pd.TimeGrouper('6M', level='createDate', closed = 'left')]).cumsum() It gives me following result: userId createDate 0 2016-05-08 22:00:49.673 2 2016-07-23 12:37:11.570 9 2017-01-03 12:05:33.060 7 1009 2016-06-27 09:28:19.677 5 2016-07-23 12:37:11.570 13 2017-01-03 12:05:33.060 9 2017-02-08 16:17:17.547 13 2011 2016-11-03 14:30:25.390 6 2016-12-15 21:06:14.730 17 2017-01-04 20:22:31.423 19 2017-08-08 16:17:17.547 7
accepted answer: http://stackoverflow.com/a/47935580
tagged with: pandas-groupby
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
score: 1

http://stackoverflow.com/comment/82998095
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47996357
type: Comment
has text: Thanks, on one level it's good to know that this isn't a property of the Python language itself that I misundestood, but it also shows that there's a lot more to learn from the implementation.

http://stackoverflow.com/comment/83067288
score: 0
type: AnswerComment
has text: in `scrape` in last code you have code which saves in csv file. You have to only check if you request the same url and skip it and read data from file - you would have to create list with visited urls to check if you visit url again. Or you can check if you already have file for visited url and then you don't have to request this url.
type: Comment
comment on: http://stackoverflow.com/a/47971619

http://stackoverflow.com/q/47861176
score: 0
has comment: http://stackoverflow.com/comment/82687259
answer count: 0
type: UnansweredQuestion
tagged with: telegram-bot
tagged with: python-telegram-bot
type: Question
has body: I would like ask where the functions like "start" and "help" receive the arguments from? Take a look at this code : https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/echobot2.py In defining, the parameters, there are 2 arguments "bot" and "update", however, when the functions run in the main method, they do not require passing in arguments. Why is this the case? Thank you!
tagged with: python
has title: Where does the functions like "start" "help" receive the arguements from?
has comment: http://stackoverflow.com/comment/82687571

http://stackoverflow.com/comment/82682568
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47858950
score: 0
has text: try `os.path.getsize(os.path.join(newDirectory,file))`

http://stackoverflow.com/a/47874353
type: AcceptedAnswer
downvote count: 0
score: 6
has body: As @cᴏʟᴅsᴘᴇᴇᴅ pointed out, this is happening because numpy rounds half-values to the nearest even integer (see docs here and a more general discussion here), and pandas uses numpy for most of its numerical work. You can resolve this by rounding the "old-fashioned" way: import numpy as np df.anual_jobs = np.floor(df.anual_jobs + 0.5) or import pandas as pd df.anual_jobs = pd.np.floor(df.anual_jobs + 0.5) As @cᴏʟᴅsᴘᴇᴇᴅ pointed out you can also resolve the slice assignment warning by creating your dataframe as a free-standing frame instead of a view on an older dataframe, i.e., execute the following at some point before you assign values into the dataframe: df = df.copy()
accepted answer of: http://stackoverflow.com/q/47873652
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/47873652

http://stackoverflow.com/q/47908749
downvote count: 0
has body: Does anyone know if anything changed recently in stats.probplot? I am plotting a qq plot, and it works ok, but doesn't produce the R^2 statistic... Not sure why that would be? x = stats.norm.rvs(loc=0, scale=1, size=100) stats.probplot(x, dist='norm', plot=pylab) plt.show()
score: 1
tagged with: probability
tagged with: plot
type: Question
accepted answer: http://stackoverflow.com/a/48167067
tagged with: statistics
upvote count: 1
has answer: http://stackoverflow.com/a/48167067
answer count: 1
favorite count: 0
has title: R^2 not appearing in stats.probplot (python)
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/82770311
score: 1
type: QuestionComment
has text: Not only is a lot of code, it's not not helpful to reproduce it.
comment on: http://stackoverflow.com/q/47901580
type: Comment

http://stackoverflow.com/q/47909342
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/82787930
has body: I am trying to learn tkinter in python3. For some reasons the new window is empty (File > New Test) and I do not understand why. There are no messages about mistakes. I guess it is something with pack(), but documentation says that Toplevel does not need pack(). Could you please tell me how to make content visible in the new window. import tkinter as tk import sys class MenuBar(tk.Menu): def __init__(self, master): tk.Menu.__init__(self, master) fileMenu = tk.Menu(self, tearoff=0) self.add_cascade(label="File", underline=0, menu=fileMenu) fileMenu.add_command(label="Exit", underline=1, command=self.quit) fileMenu.add_command(label="Start Test", underline=1, command=self.start_test) def quit(self): sys.exit(0) def start_test(self): self.app = RunTestWindow(self) class MainWindow(tk.Frame): def __init__(self, master): tk.Frame.__init__(self, master) self.master.title("Quiz") self.menubar = MenuBar(self) self.master.config(menu=self.menubar) self.button1 = tk.Button(self) self.button1['text'] = "Hello!" self.button1.grid(row=2, column=0) self.canvas = tk.Canvas(self, bg="white", width=400, height=400, bd=0, highlightthickness=0) self.canvas.grid(row=3, column=0) class RunTestWindow(tk.Frame): def __init__(self, master): tk.Frame.__init__(self, master) self.window = tk.Toplevel(self) self.label = tk.Label(self, text="Show me my new window") self.label.grid(row=1, column=0) root = tk.Tk() mw = MainWindow(root) mw.pack() root.mainloop()
accepted answer: http://stackoverflow.com/a/47909752
has comment: http://stackoverflow.com/comment/82786038
type: AnsweredQuestion
tagged with: tkinter
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/82786160
has title: New window is empty
has answer: http://stackoverflow.com/a/47909752
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82786509
favorite count: 0

http://stackoverflow.com/a/47861354
type: Answer
score: 3
upvote count: 3
has body: Sure: def diag_windows(x, n): if x.ndim != 2 or x.shape[0] != x.shape[1] or x.shape[0] &lt; n: raise ValueError("Invalid input") w = as_strided(x, shape=(x.shape[0] - n + 1, n, n), strides=(x.strides[0]+x.strides[1], x.strides[0], x.strides[1])) return w For example: In [14]: x Out[14]: array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) In [15]: diag_windows(x, 2) Out[15]: array([[[ 0, 1], [ 4, 5]], [[ 5, 6], [ 9, 10]], [[10, 11], [14, 15]]]) In [16]: diag_windows(x, 3) Out[16]: array([[[ 0, 1, 2], [ 4, 5, 6], [ 8, 9, 10]], [[ 5, 6, 7], [ 9, 10, 11], [13, 14, 15]]]) In [17]: diag_windows(x, 4) Out[17]: array([[[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]])
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47861214
accepted answer of: http://stackoverflow.com/q/47861214

http://stackoverflow.com/comment/121950308
type: Comment
type: QuestionComment
has text: Does this answer your question? [running a command as a super user from a python script](https://stackoverflow.com/questions/567542/running-a-command-as-a-super-user-from-a-python-script)
comment on: http://stackoverflow.com/q/47881339
score: 0

http://stackoverflow.com/a/47982154
downvote count: 0
has comment: http://stackoverflow.com/comment/82932785
type: AcceptedAnswer
score: 4
answers question: http://stackoverflow.com/q/47982117
type: Answer
upvote count: 4
has body: words is a list of lists since word_tokenize() returns a list of words. When you do [word for word in words if word not in custom_stopwords] each word is actually of a list type. When the word not in custom_stopwords "is in set" condition needs to be checked, word needs to be hashed which fails because lists are mutable containers and are not hashable in Python. These posts might help to understand what is "hashable" and why mutable containers are not: In Python, why is a tuple hashable but not a list? What do you mean by hashable in Python? Hashable, immutable
accepted answer of: http://stackoverflow.com/q/47982117

http://stackoverflow.com/comment/82923987
comment on: http://stackoverflow.com/a/47964620
has text: Thanks! Really helpful.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/47891496
type: AcceptedAnswer
upvote count: 1
type: Answer
has body: According to the docs this feature does not exist. Also, if you search the source code for "delete type" I don't see anything that matches. You'd need to do a select first and iterate through all the ids deleting them.
accepted answer of: http://stackoverflow.com/q/47889912
downvote count: 0
answers question: http://stackoverflow.com/q/47889912
score: 1
has comment: http://stackoverflow.com/comment/82752577

http://stackoverflow.com/q/47889459
has answer: http://stackoverflow.com/a/51409427
has answer: http://stackoverflow.com/a/51489551
downvote count: 1
tagged with: bootstrap-4
answer count: 6
has answer: http://stackoverflow.com/a/51396003
favorite count: 0
has answer: http://stackoverflow.com/a/47890403
has title: Bootstrap does not be set to Django app
tagged with: css
upvote count: 12
has answer: http://stackoverflow.com/a/51484651
has comment: http://stackoverflow.com/comment/89749566
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82754343
tagged with: django
tagged with: python
score: 11
has answer: http://stackoverflow.com/a/51480685
has body: Bootstrap does not be set to my Django app.In google console,Failed to load resource: the server responded with a status of 404 (Not Found) bootflat.min.css error happens.I wrote in settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG =True STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") STATICFILES_DIRS = [os.path.join(BASE_DIR,'bootflat.github.io'), ] in PythonServer_nginx.conf server { # the port your site will be served on listen 8000; # the domain name it will serve for server_name MyServerIPAdress; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste location /static { alias /home/ubuntu/PythonServer/PythonServer/accounts/static; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/ubuntu/PythonServer/uwsgi_params; # the uwsgi_params file you installed } } I do not know why Bootstrap does not be set to my Django app.I run command python manage.py collectstatic but no error happens.How should I fix this?What should I write it?
type: Question

http://stackoverflow.com/q/47969544
type: Question
tagged with: cron
accepted answer: http://stackoverflow.com/a/47969812
has title: crontab 7 days before end of month now kicking off
tagged with: python
score: 0
answer count: 1
has body: on Ubuntu 16 my crontab has the following: 0 8 20-31 2-12/2 * [ $(date +\%d -d "7 days") == 01 ] &amp;&amp; python3 myscript.py &amp; I expected this to kick off this morning but it didn't. It kicked off just fine if changed to: 0 8 25 2-12/2 * python3 myscript.py &amp; Any suggestions on how I can crontab to kick off a script 7 days before the end of the month?
tagged with: ubuntu-16.04
has answer: http://stackoverflow.com/a/47969812
type: AnsweredQuestion
tagged with: python-3.x

http://stackoverflow.com/q/48007009
score: 0
tagged with: azure
has comment: http://stackoverflow.com/comment/83007298
has comment: http://stackoverflow.com/comment/83007556
has comment: http://stackoverflow.com/comment/82984787
has title: C++ Azure file upload: Server failed to authenticate the request
has comment: http://stackoverflow.com/comment/83015651
tagged with: c++
answer count: 0
has comment: http://stackoverflow.com/comment/83016381
has body: I'm trying to upload a file to my azure file service using the following C++ code (which is referenced from official documentation here): const utility::string_t storage_connection_string(U("DefaultEndpointsProtocol=https;AccountName=myaccount;" "AccountKey=mykey")); // Retrieve storage account from connection string. azure::storage::cloud_storage_account storage_account = azure::storage::cloud_storage_account::parse(storage_connection_string); // Create the Azure Files client. azure::storage::cloud_file_client file_client = storage_account.create_cloud_file_client(); // Get a reference to the share. azure::storage::cloud_file_share share = file_client.get_share_reference(_XPLATSTR("myfileservice")); //Get a reference to the root directory for the share. azure::storage::cloud_file_directory root_dir = share.get_root_directory_reference(); // Upload a file from a file. azure::storage::cloud_file file = root_dir.get_file_reference(_XPLATSTR("my-sample-file")); file.upload_from_file(_XPLATSTR("test.pdf")); This gives out the following error: terminate called after throwing an instance of 'azure::storage::storage_exception' what(): Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature. I've searched the internet and found it should be something related to authentication using SAS. I tried many example codes online but still cannot succeed. However, I can do similar file upload by the following Python code without SAS authentication and without any trouble: import os from azure.storage.file import FileService, ContentSettings currentDir = os.path.dirname(os.path.abspath(__file__)) #credentials for azure account file_service = FileService(account_name='myaccount', account_key='mykey') #path for azure file global pathStr pathStr = 'https://myaccount.file.core.windows.net/myfileservice/' #function for uploading file onto Azure container def upload(myfile): file_service.create_file_from_path( 'myfil…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82982987
has comment: http://stackoverflow.com/comment/82984212
tagged with: python
has comment: http://stackoverflow.com/comment/82982200
has comment: http://stackoverflow.com/comment/83012015
has comment: http://stackoverflow.com/comment/82984539
type: Question
has comment: http://stackoverflow.com/comment/83012279
has comment: http://stackoverflow.com/comment/83015581

http://stackoverflow.com/q/47938804
linked to: http://stackoverflow.com/q/20528328
score: 2
type: AnsweredQuestion
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/47939010
tagged with: pandas
answer count: 1
has title: Filtering rows in a DataFrame when condition is rows in another DataFrame
favorite count: 0
has body: I have a huge timeseries DataFrame (about 100 000 000 rows) and I need to filter rows by conditions. Each condition there are in an each row of an another Dataframe. This Dataframe has about 2000 rows and each row is condition. Toy example: df = pd.DataFrame({val: [1, 3, 2, 4, 3, 1, 2, 3], date: [2015-03-12, 2015-04-12, 2015-05-13, 2016-03-12, 2016-04-07, 2016-05-12, 2017-01-11, 2017-03-20]}) df_condition = pd.DataFrame({val: [2, 3], date: [2015-07-13, 2016-04-08]}) Condition is remove all raws in df, where val appears earlier than date in df_condition: df = df[(df['val']==2) &amp; (df['date']&gt;'2015-07-13')] df = df[(df['val']==3) &amp; (df['date']&gt;'2016-04-08')] and so on about 2000 conditions I use this way, but it too long (about 5 hours). Is there a faster method? vals = df_condition.val.values dates = vals = df_condition.dates.values for i in range(len(df_condition)): df = df[~((df.val==vals[i])&amp;(df.date &lt; dates[i]))]
upvote count: 2
accepted answer: http://stackoverflow.com/a/47939010
tagged with: python

http://stackoverflow.com/a/47890664
accepted answer of: http://stackoverflow.com/q/47878207
answers question: http://stackoverflow.com/q/47878207
type: Answer
has comment: http://stackoverflow.com/comment/82868016
score: 6
upvote count: 6
has body: You are on the right lines with tf.data.TFRecordDataset(filename), but the problem is that the dataset is not connected to the tensors that you are passing to sess.run(). Here's a simple example program that should produce some output: def decode(serialized_example): # NOTE: You might get an error here, because it seems unlikely that the features # called 'coord2d' and 'coord3d', and produced using `ndarray.flatten()`, will # have a scalar shape. You might need to change the shape passed to # `tf.FixedLenFeature()`. features = tf.parse_single_example( serialized_example, features={'train/coord2d': tf.FixedLenFeature([], tf.float32), 'train/coord3d': tf.FixedLenFeature([], tf.float32)}) # NOTE: No need to cast these features, as they are already `tf.float32` values. return features['train/coord2d'], features['train/coord3d'] filename = ["train.tfrecords"] dataset = tf.data.TFRecordDataset(filename).map(decode) iterator = dataset.make_one_shot_iterator() c2d, c3d = iterator.get_next() with tf.Session() as sess: try: while True: print(sess.run((c2d, c3d))) except tf.errors.OutOfRangeError: # Raised when we reach the end of the file. pass
type: AcceptedAnswer
downvote count: 0

windows
tags question: http://stackoverflow.com/q/47932922
tags question: http://stackoverflow.com/q/47903196
tags question: http://stackoverflow.com/q/47927475
tags question: http://stackoverflow.com/q/47886265
tags question: http://stackoverflow.com/q/47969112
tags question: http://stackoverflow.com/q/47999518
tags question: http://stackoverflow.com/q/47881478
tags question: http://stackoverflow.com/q/47945399
tags question: http://stackoverflow.com/q/47929915
tags question: http://stackoverflow.com/q/47997038
tags question: http://stackoverflow.com/q/47858129
tags question: http://stackoverflow.com/q/47928845
tags question: http://stackoverflow.com/q/47865706
tags question: http://stackoverflow.com/q/47986565
tags question: http://stackoverflow.com/q/47926026
tags question: http://stackoverflow.com/q/47940360
tags question: http://stackoverflow.com/q/48009243
tags question: http://stackoverflow.com/q/47952552
tags question: http://stackoverflow.com/q/47978171
type: Tag
tags question: http://stackoverflow.com/q/47915245
tags question: http://stackoverflow.com/q/47912438
tags question: http://stackoverflow.com/q/47978802
tags question: http://stackoverflow.com/q/47912111
tag name: windows
tags question: http://stackoverflow.com/q/47910688
tags question: http://stackoverflow.com/q/47994326
tags question: http://stackoverflow.com/q/47968578
tags question: http://stackoverflow.com/q/47957487

http://stackoverflow.com/comment/82745123
type: Comment
comment on: http://stackoverflow.com/a/47879684
has text: @YoHsiao - I added a semi-equivalent UTF-16 length example for Python.
score: 0
type: AnswerComment

http://stackoverflow.com/q/48011526
has answer: http://stackoverflow.com/a/48011720
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82991684
has body: I'm trying to create a CRM in Python as a final project to a course. And I create a dictionary to use like a "database" form my CRM. First, I tryed update the dict outside a class: index_db = {} index_db[len(index_db)] = {'name_first': 'Johnny', 'name_last': 'Quest', 'email': 'jquest@cartoonville.com', 'phone': '1 365 999999999'} index_db[len(index_db)] = {'name_first': 'Scooby', 'name_last': 'Doo', 'email': 'sdoo@cartoonville.com', 'phone': '1 365 888888888'} index_db[len(index_db)] = {'name_first': 'Homer', 'name_last': 'Simpson', 'email': 'hsimpson@cartoonville.com', 'phone': '1 365 777777777'} And it's return: { 0: { 'name_first': 'Johnny', 'name_last': 'Quest', 'email': 'jquest@cartoonville.com', 'phone': '1 365 999999999' }, 1: { 'name_first': 'Scooby', 'name_last': 'Doo', 'email': 'sdoo@cartoonville.com', 'phone': '1 365 888888888' }, 2: { 'name_first': 'Homer', 'name_last': 'Simpson', 'email': 'hsimpson@cartoonville.com', 'phone': '1 365 777777777' } } It's look great, so I created a class: class Consumer(object): index_db = {} args = {'name_first': None, 'name_last': None, 'email': None, 'phone': None} def __set__(self, var, val): self.args[var] = val def __insert__(self): self.index_db[len(self.index_db)] = self.args And insert three consumers: consumer = Consumer() consumer.__set__('name_first', 'Johnny') consumer.__set__('name_last', 'Bravo') consumer.__set__('email', 'jbravo@cartoonville.com') consumer.__set__('phone', '1 353 30316541') consumer.__insert__() consumer.__set__('name_first', 'Dexter') consumer.__set__('name_last', 'Scientist') consumer.__set__('email', 'dscientist@cartoonville.com') consumer.__set__('phone', '1 353 33256001') consumer.__insert__() consumer.__set__('name_first', 'Barney') consumer.__set__('name_last', 'Gumble') consumer.__set__('email', 'bgumble@cartoonville.com') consumer.__set__('phone', '1 353 555961533') consumer.__insert__() And it's return: { 0: { 'email': 'bgumble@cartoonville.com', 'name_first': 'Barney', 'name_last…
has comment: http://stackoverflow.com/comment/82991654
downvote count: 0
has answer: http://stackoverflow.com/a/48012248
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48011893
type: Question
upvote count: 1
tagged with: python
tagged with: dictionary
answer count: 4
has title: Updating a dictionary with a class function
has answer: http://stackoverflow.com/a/48011633

http://stackoverflow.com/comment/82912102
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47971142
has text: Do not call variables `list`, it overrides the `list` class reference.

http://stackoverflow.com/comment/82886863
type: QuestionComment
comment on: http://stackoverflow.com/q/47958126
has text: it would be so much easier doing this manually. why do you want to créate service principal in code when its a 1 time thing?
score: 0
type: Comment

http://stackoverflow.com/comment/82908640
type: QuestionComment
comment on: http://stackoverflow.com/q/47969375
has text: @Jean-FrançoisFabre, sys.arg works when I start my python script directly in CMD with the args with `python C:\myscript.py sometext`.
score: 0
type: Comment

http://stackoverflow.com/q/47978342
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/48179163
score: 1
tagged with: type-hinting
tagged with: google-cloud-dataflow
has comment: http://stackoverflow.com/comment/82958230
type: Question
answer count: 1
downvote count: 0
has title: Apache Beam - Clarifying an expected behavior of output typehint on Python SDK
has comment: http://stackoverflow.com/comment/82969588
has body: I'm trying to understand Apache Beam Python SDK internal and currently reading a typecheck part. I wrote a very simple pipeline as below: class AddZeroFn(beam.DoFn): def process(self, element): return [element + '0'] def run(argv=None): parser = argparse.ArgumentParser() known_args, pipeline_args = parser.parse_known_args(argv) pipeline_options = PipelineOptions(pipeline_args, pipeline_type_check=True) pipeline_options.view_as(SetupOptions).save_main_session = True with beam.Pipeline(options=pipeline_options) as p: numbers = p | beam.Create(['1', '2', '3']) numbers = numbers | beam.ParDo(AddZeroFn()) numbers | 'Write' &gt;&gt; WriteToText('result.txt') if __name__ == '__main__': logging.getLogger().setLevel(logging.INFO) run() Then a result is 10 20 30 Okey, then I added a type check for input, like numbers = numbers | beam.ParDo(AddZeroFn().with_input_types(str)) This is fine, and it raises an error if I change str to int as expected. apache_beam.typehints.decorators.TypeCheckError: Type hint violation for 'ParDo(AddZeroFn)': requires &lt;type 'int'&gt; but got &lt;type 'str'&gt; for element However, when I added output type check like numbers = numbers | beam.ParDo(AddZeroFn().with_output_types(float)) It just ran without any issue. No error is raised while I thought I would see the same error as input typehint. Am I misunderstanding the usage of output typehint? If so, could I ask how with_output_type is expected to behave? Also ptransform.type_check_inputs_or_outputs has lines as below if pvalue_.element_type is None: # TODO(robertwb): It's a bug that we ever get here. (typecheck) continue if hint and not typehints.is_consistent_with(pvalue_.element_type, hint): at_context = ' %s %s' % (input_or_output, context) if context else '' raise TypeCheckError( '%s type hint violation at %s%s: expected %s, got %s' % ( input_or_output.title(), self.label, at_context, hint, pvalue_.element_type)) However if I set some print statement in the first if block, I see that in ma…
has comment: http://stackoverflow.com/comment/82958572
tagged with: apache-beam
tagged with: python
favorite count: 0

http://stackoverflow.com/a/47910232
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47909457
has body: I solved in this way, just invoquing .join in the previous join but only using right table. self._join.join(rightTable,...) Complete solution for the method: def get_joins(self, first, leftTable, rightTable, leftTableColumn, rightTableColumn, outer): if first: self._join = join(leftTable, rightTable, leftTableColumn == rightTableColumn, full=outer) first = False else: self._join = self._join.join(rightTable, leftTableColumn == rightTableColumn, full=outer)
type: Answer
downvote count: 0

http://stackoverflow.com/q/47981562
favorite count: 0
has body: If I have a tuple object which stores some immutable objects (like ints), and I need to create a modified version of this tuple as efficiently/fast as possible, what is the best way to do this? Here is a simplified example of what I currently have. orig_tuple = (1, 0, 0) new_tuple = (some_function(element) for element in orig_tuple) Is this as fast as it gets? Does the list comprehension add much overhead?
type: Question
tagged with: python
tagged with: immutability
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47981612
has comment: http://stackoverflow.com/comment/82931633
answer count: 2
upvote count: 1
has title: Fastest way to make a modified copy of an immutable object in python
has answer: http://stackoverflow.com/a/47981636
possible better answer: http://stackoverflow.com/a/47981636
tagged with: python-2.7
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47981612
downvote count: 0
score: 1
tagged with: copy

http://stackoverflow.com/a/47971845
score: 0
type: Answer
has body: Whenever I have this kind of problem it is because the file I'm trying to run is not the same I am changing. I recommend using something (like cat) to check the content of the file before actually running it. So, in your case, pop up your terminal and run: $ cat hello_world.py The output should be $ cat hello_world.py print("Hello Python World!") If the output is blank, there is your problem. Try to open that exact file with sublime. Probably with $ sublime hello_world.py
answers question: http://stackoverflow.com/q/47971533

http://stackoverflow.com/comment/82796209
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47913963
has text: @bnaecker. I would like to be able to pass in the parameter when the task is called by the thread. I can't seem to get around the chicken or the egg problem here, where the thread has to exist to be able to be present in `args`.
score: 0

http://stackoverflow.com/comment/82951608
has text: Try with the updated `xpath` and `css` and let me know the status.
comment on: http://stackoverflow.com/a/47990437
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/comment/82678507
type: AnswerComment
has text: I had already tried, but it doesn't work: Warning: Already linked: /usr/local/Cellar/python/2.7.14 To relink: brew unlink python && brew link python
type: Comment
comment on: http://stackoverflow.com/a/47857096
score: 0

http://stackoverflow.com/q/47873981
has answer: http://stackoverflow.com/a/64853695
tagged with: python
tagged with: unix
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47874413
has title: Grab Docker Stats Results Using Python
type: Question
accepted answer: http://stackoverflow.com/a/47874413
has body: I am trying to build a monitoring app that constantly gets a feed from docker stats API. I quickly noticed that whenever I try to run something like docker stats 857ff7a0403b from within python, it does not gather the std out and waits for ever. The example python code is below. commands.getoutput('docker stats 857ff7a0403b') While the above code works for running commands like docker ps and docker images but it does not work for docker stats. Is there a way in python to quickly grab the results and terminate the utility so that it does not wait for ever.
tagged with: docker
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/64853695

http://stackoverflow.com/q/47858411
tagged with: apache-spark
favorite count: 0
has body: Is it possible to use LSH Spark implementation Algorithm for finding Sentence Similarity? I have approximately 16k rows in my dataset, and this is approximately 16k*16k=256000 number of different options between all rows where similarity distance has to be computed and this number is going to increase everyday. I firstly use nltk, pymorphy2, gensim libraries for some preprocessing stuff, after compute tfidf, and in the end apply idf sparse data into LSH algorithm. That's the structure of my data When I use my code, def LSH(Pred_Factors): brp = BucketedRandomProjectionLSH(inputCol="idf", outputCol="hashes", bucketLength=1.0, numHashTables=10) model = brp.fit(Pred_Factors) Hashed_Factors = model.transform(Pred_Factors) sim_table = model.approxSimilarityJoin(Hashed_Factors, Hashed_Factors, #hashes computes anyway threshold=1.2, distCol="EuclideanDistance") \ .select(col("datasetA").alias("idA"), col("datasetB").alias("idB"), col("EuclideanDistance")).cache() return sim_table sim_table = LSH(tfidf) Similarity cannot be computed because of huge size of data (sparse data is so huge to compute for LSH, but at some point of view it can but it takes 20 minutes, 95-100% CPU and 3gb Memory). I even changed amount of partitions from 200 to 1000 and it doesn't help significantly. Hopefully, I found that LSH can work with Sparse data without converting it. There is (the only one way I know that works) to do this is gently --> to compute sum of idf. ##UDF SUM sum_ = udf(lambda v: float(v.values.sum())) idf_sum = tfidf('idf_sum', sum_('idf')) and then I can use sum of idf and apply it to LSH and all is going great. May someone suggest the better way how to do it or just say that this is a normal way to compute Euclidian similarity between huge amount of text rows using LSH, I understand that cosine similarity is better for this purpose but Spark has implementation only Jaccard(Minhash) &amp; Euclidian similarities of LSH algorithm. Maybe MinHash can someway ease the computation pre…
tagged with: python
linked to: http://stackoverflow.com/q/43938672
has comment: http://stackoverflow.com/comment/99149964
answer count: 0
type: UnansweredQuestion
downvote count: 1
has title: LSH and Sentence Similarity
upvote count: 5
tagged with: pyspark
score: 4
type: Question

http://stackoverflow.com/q/48004243
tagged with: multithreading
has comment: http://stackoverflow.com/comment/82976512
tagged with: python
has body: I have a 18Gb pickle file which i need to be accessing across processes. I tried using from multiprocessing import Manager import cPickle as pkl manager = Manager() data = manager.dict(pkl.load(open("xyz.pkl","rb"))) However, I am getting the following issue: IOError: [Errno 11] Resource temporarily unavailable Someone suggested it might be because of socket timeout but it doesn't seem like it as increasing the timeout did not help. How do I go about this. Is there any other efficient way of sharing data across processes?
score: 2
linked to: http://stackoverflow.com/q/14124588
type: AnsweredQuestion
tagged with: multiprocessing
type: Question
accepted answer: http://stackoverflow.com/a/48016521
has comment: http://stackoverflow.com/comment/82976701
answer count: 1
downvote count: 0
has title: How to share large read only dictionary/list across processes in multiprocessing in python?
favorite count: 0
has answer: http://stackoverflow.com/a/48016521
upvote count: 2

http://stackoverflow.com/comment/82711738
type: QuestionComment
comment on: http://stackoverflow.com/q/47873077
score: 0
has text: Have you tried a more specific search such as conn.search('Monsters')? Also can you check the value conn and confirm that your connection is correct.
type: Comment

oauth-2.0
tags question: http://stackoverflow.com/q/47859865
tag name: oauth-2.0
tags question: http://stackoverflow.com/q/47957951
type: Tag
tags question: http://stackoverflow.com/q/47921202
tags question: http://stackoverflow.com/q/47990383

http://stackoverflow.com/comment/82965129
comment on: http://stackoverflow.com/a/47959931
has text: Yes. `PYTHONIOENCODING` is set but the error is still there.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/47905316
type: Answer
has body: docs http://flask.pocoo.org/docs/0.12/api/#flask.Request request.data Contains the incoming request data as string in case it came with a mimetype Flask does not handle. request.form: the key/value pairs in the body, from a HTML post form, or JavaScript request that isn't JSON encoded So you can try request.data if it has the correct mimetype (application json) or encode the request.form to dict with json.loads(request.form) then access uuid
answers question: http://stackoverflow.com/q/47905108
score: 0

http://stackoverflow.com/a/47913247
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47912899
answers question: http://stackoverflow.com/q/47912899
type: Answer
upvote count: 1
score: 1
has body: You can apply a groupby + count with 2 predicates - pd.Grouper with a frequency of a week score column Finally, unstack the result. df = df.groupby([pd.Grouper(freq='1w'), 'score']).count().unstack(fill_value=0) df.head() datetime score a b c d e f g h datetime 2016-12-25 0 0 1 1 0 1 0 1 2017-01-01 1 0 0 1 3 0 2 0 2017-01-08 0 3 1 1 1 0 0 1 2017-01-15 1 2 0 2 0 0 1 1 2017-01-22 0 1 2 1 1 2 0 0

http://stackoverflow.com/a/55106467
type: Answer
answers question: http://stackoverflow.com/q/47944961
upvote count: 2
has comment: http://stackoverflow.com/comment/96965230
has comment: http://stackoverflow.com/comment/96969229
score: 2
type: AcceptedAnswer
downvote count: 0
has body: Take a look at Whoosh's scoring module and use BM25F (lines 276 to 332) as a reference for building your own weighting and scoring models. You need to create a Weighting Model and a Scorer. Assuming you want to call your model Unigram, the main steps would be: Implement your own Unigram weighting model class and inherit from scoring.WeightingModel: class Unigram(WeightingModel) Implement the methods required by the base class, the main one being scorer(), which returns a reference to your Scorer class (next). This class is called when you create your searcher and defines the Weighting Model the searcher will use. Implement a UnigramScorer class and inherit from scoring.WeightLengthScorer: class UnigramScorer(WeightLengthScorer) Implement the __init__ and _score methods. __init__ takes the field name and value and is called once for each term in your query when you call searcher.search(). _score is called for each matching document in your results. It takes a weight and length and returns a score for a given field. When you create your searcher at search time, specify your custom language model using the weighting parameter: ix.searcher(weighting = Unigram)
accepted answer of: http://stackoverflow.com/q/47944961

http://stackoverflow.com/q/47910959
score: 1
has answer: http://stackoverflow.com/a/51257682
upvote count: 1
tagged with: python-requests
has body: I am trying to update a custom field in Jira, using the following code and I'm getting a 415 error code. Any help would be greatly appreciated! My code is below: import json import requests jiraSession = requests.Session() username = input("username: ") password = input("password: ") #-------------- CALL ----------------- searchAPI = 'http://ourbaseurl.jira.com/rest/api/2/issue/ISSUE-1' holder = requests.put(searchAPI, auth=(username, password), data= {"update": {"customfield_1000": { "set": { "value": "FIELD VALUE" } } }}) EDIT I've updated my code and now I'm getting a 400 status code, based on the /rest/api/2/issue/ISSUE-NAME/editmeta data = json.dumps({"fields": { "customfield_SOMEFIELD": {"value": "SOME DATA"}}}) holder = requests.put(searchAPI, json=(data) , auth=(username, password))
tagged with: jira
type: Question
has comment: http://stackoverflow.com/comment/82790273
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/82789718
has title: Updating Fields in Jira in Python using Requests
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82789454
tagged with: python
has comment: http://stackoverflow.com/comment/82789760

http://stackoverflow.com/q/47930029
has answer: http://stackoverflow.com/a/47930164
tagged with: python-2.7
answer count: 1
type: UnansweredQuestion
tagged with: datetime
tagged with: python
has title: unsupported operend type(s) for -:' str' and 'str'
has comment: http://stackoverflow.com/comment/82828724
score: 0
has body: import datetime birthday=[int(i) for i in str(20000707)] today=datetime.datetime.now() today=today.strftime('%Y-%m-%d') a=birthday[0:4] a=''.join(str(i) for i in a) a=int(a) b=birthday[4:6] b=''.join(str(i) for i in b) b=int(b) c=birthday[6:8] c=''.join(str(i) for i in c) c=int(c) dob=datetime.date(a,b,c) aged=(today-dob).days agey=aged/365 print agey It throws the following error: aged=(today-dob).days TypeError: unsupported operand type(s) for -: 'str' and 'datetime.date'
type: Question

http://stackoverflow.com/comment/82759172
comment on: http://stackoverflow.com/q/47896006
has text: Your code has two errors. You do not save the return of the function anywhere, and the return of number() has a bad indentation.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47999891
upvote count: 8
type: Answer
has comment: http://stackoverflow.com/comment/82992570
has comment: http://stackoverflow.com/comment/82997707
answers question: http://stackoverflow.com/q/47999477
has comment: http://stackoverflow.com/comment/82998097
downvote count: 0
has comment: http://stackoverflow.com/comment/82997806
has comment: http://stackoverflow.com/comment/102700781
has body: Personally I find the Anaconda environment &amp; package management to be outstanding. So if you're using the conda command to update your packages in your python environment then I recommend using the environment.yml file instead of requirements.txt. The environment.yml should looks like the following: name: root # default is root channels: - defaults dependencies: # everything under this, installed by conda - numpy==1.13.3 - scipy==1.0.0 - pip: # everything under this, installed by pip - Flask==0.12.2 - gunicorn==19.7.1 The command to install: conda env update --file environment.yml Note: Here we set name: root which is the default anaconda environment name. This is not standard practice of how to use the conda and environment.yml file. Ideally every python project should have its own environment.yml file with a project specific environment name i.e. name: project-name. Please go through https://conda.io/docs/user-guide/tasks/manage-environments.html on using Anaconda for package management.
score: 8

http://stackoverflow.com/comment/82971219
type: QuestionComment
has text: the Wireless-radar repo hasn't been updated in over a year, and has had relatively little usage. `Failed to build pybluez` and `cc -fno-strict-aliasing -fno-common - ...... osx/_osxbt.c:676:5: error: unknown type name 'IOBluetoothDeviceInquiryRef'; did you mean 'IOBluetoothDeviceRef'? IOBluetoothDeviceInquiryRef inquiry;`. indicate the package might be broken or incompatible with your configuration. suggest you contact the author of the repo
comment on: http://stackoverflow.com/q/48001202
score: 0
type: Comment

http://stackoverflow.com/comment/84648195
has text: You're most welcome. I declare it right after instantiating the engine in the constructor of a class.
type: AnswerComment
comment on: http://stackoverflow.com/a/48065082
type: Comment
score: 2

http://stackoverflow.com/comment/82769682
has text: @km786 I updated my answer with **urls.py**. The error could be coming from `return redirect('home:add-answers', id=create_question.id)` if you didn't have the `add-answers` name set in urls.py. I hope that helps, let me know if you need more clarification. thanks
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47899794
type: Comment

http://stackoverflow.com/comment/82879989
type: QuestionComment
comment on: http://stackoverflow.com/q/47954890
has text: @StefanPochmann, yep, I definitely messed up there, sorry about that. Still, that's gonna be a huge number. 229709771033.59998 seconds, or 7284.049 years, which is still a lot. Also, IPython's `%timeit` _does_ the division automatically, which is convenient, but `timeit.timeit` doesn't, which causes the confusion.
score: 0
type: Comment

http://stackoverflow.com/q/47979486
has comment: http://stackoverflow.com/comment/82927841
answer count: 1
has body: I have extracted data from a SQL database table but have been having persistent issues with trying to plot a graph between two variables. This is due to conversion issue between data types. I have first successfully converted a list to a str data type and now I want to convert it to either a float/int/ decimal type so that I can use it with matplotlib. I feel stuck at the moment since I am unable to convert the str data to any of them. Shown below is my script: import mysql.connector as mariadb import matplotlib as mpl mpl.use('Agg') import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt from matplotlib import pyplot from decimal import Decimal import pandas as pd mariadb_connection = mariadb.connect(user='user', password='password', database='mydatabase') cur = mariadb_connection.cursor() cur.execute("SELECT time, current FROM table1") current = [] time = [] for row in cur.fetchall(): current.append(int(row[1])) time.append(str(row[0])) print(type(time)) #at this point terminal shows it is a list data type time = pd.to_datetime(time) print(type(time)) #at this point terminal shows it is a &lt;class 'pandas.core.indexes.datetimes.DatetimeIndex'&gt;data type print(type(current)) #at this point, terminal shows it is a list data type current=','.join(str(v) for v in current) print(type(current)) #at this point, terminal shows it is a str data current=float(current) #at this point, I get an error stating ValueError: invalid literal for float() print(type(current)) mariadb_connection.close() plt.figure() plt.plot(time, current) plt.show() fig.savefig('plot.jpg') On running this script, I get an error stating ValueError: invalid literal for float(): 51,52,52,53,52,52,53,53,55,54,58,72,63,68,79,140,133,102,116,120,189,196,151,249,277,218,206,210,212,173,194,216,181,166,221,212,175,189,288,300,281,210,266 I then modified the line current=float(current) to current=int(current) to try converting the str data to int type and it states another error V…
has comment: http://stackoverflow.com/comment/82928065
has comment: http://stackoverflow.com/comment/82927775
tagged with: int
has answer: http://stackoverflow.com/a/47979862
has comment: http://stackoverflow.com/comment/82927872
tagged with: python
has comment: http://stackoverflow.com/comment/82927613
favorite count: 0
accepted answer: http://stackoverflow.com/a/47979862
has comment: http://stackoverflow.com/comment/82928009
downvote count: 1
has title: Difficulty converting str data to int/float/decimal for plotting with matplolib
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82928075
tagged with: matplotlib
score: -1
tagged with: mysql
type: Question
has comment: http://stackoverflow.com/comment/82927846
tagged with: decimal
upvote count: 0

http://stackoverflow.com/comment/94258498
has text: Above code working for me. But if you use subscriber.subscribe(); method it add 10 threads in default. See 'receive_messages_with_flow_control' method in [1]. [1]. https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/pubsub/cloud-client/subscriber.py
type: Comment
comment on: http://stackoverflow.com/a/48017862
type: AnswerComment
score: 0

http://stackoverflow.com/q/47986702
has title: How to add a y-axis label while using pandas.DataFrame.plot() for constructing a time series plot
answer count: 1
score: 0
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/47987179
has body: This is my code. I looked at the documentation but didn't find the answer. import pandas as pd import matplotlib.pyplot as plt from datetime import datetime avs = pd.read_csv('daily_2004_2014.csv') avs = avs.set_index(pd.DatetimeIndex(avs['Date'])) fig = plt.figure() avs.plot() plt.show() Here is the generated image
tagged with: plot
type: Question
type: AnsweredQuestion
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/47987179
tagged with: dataframe

http://stackoverflow.com/comment/82838918
comment on: http://stackoverflow.com/a/47917863
type: Comment
has text: Thanks. Finally I know how to write a Python pattern equivalent to grep's `(ab|Ab)c`.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82827872
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47906415
has text: I have converted the numpy array now like you said and parsed it to the cursor.execute like so: pic = str(frame) cursor.execute("INSERT INTO Camera (img) VALUES(%s)",(pic,)) This seems to work with no errors but when i look at the database nothing is inserted for the image

http://stackoverflow.com/q/48006466
accepted answer: http://stackoverflow.com/a/48008672
tagged with: python
type: AnsweredQuestion
has title: How refactor readChunk from SFTPFile to stop using inlineCallbacks?
type: Question
has body: I'm trying to read from file over ISFTPFile and I want to avoid using @inlinceCallbacks in this scenario? Or maybe there is a better way to read/write for ISFTPFile? @defer.inlineCallbacks def calculate_checksum(open_file): hasher = hashlib.sha256() offset = 0 try: while True: d = yield open_file.readChunk(offset, chunk_size) offset += chunk_size hasher.update(d) except EOFError: pass target_checksum = hasher.hexdigest() defer.returnValue(target_checksum) client_file = client.openFile( filename=target, flags=FXF_READ, attrs={}) checksum = yield client_file.addCallback(calculate_checksum)
tagged with: twisted
answer count: 1
has comment: http://stackoverflow.com/comment/82983719
has answer: http://stackoverflow.com/a/48008672
score: 0
tagged with: sftp

http://stackoverflow.com/q/47996516
has body: I am just playing along with python to understand the things in more depth. I learned that One of the easier ways is to use zip, but how about this: &gt;&gt;&gt; a = [[1,1,1], [2,2,2], [3,3,3]] &gt;&gt;&gt; for i in range(len(a)): ... for j in range(len(a[0])): ... a[i][j], a[j][i] = a[j][i], a[i][j] ... &gt;&gt;&gt; a [[1, 1, 1], [2, 2, 2], [3, 3, 3]] &gt;&gt;&gt; well, I was expecting the answer to be [[1, 2, 3], [1, 2, 3], [1, 2, 3]] because that is what Transpose would be ? I swapped the elements, right?? Also, this way was more natural to me. I read the documentation for zip here and it does not say anything about such "tricks". How to learn these more pythonic ways of doing the things? I am aware that asking for resources to learn goes into subjective choices and SO does not encourage such questions. But IMO, it is clearly not a matter of choice in this case, but finding any and every resource where such information is available.
has comment: http://stackoverflow.com/comment/82961418
has comment: http://stackoverflow.com/comment/82961391
type: Question
has title: Transpose of list of list
has comment: http://stackoverflow.com/comment/82961028
has answer: http://stackoverflow.com/a/47996647
accepted answer: http://stackoverflow.com/a/47996647
has comment: http://stackoverflow.com/comment/131941223
has answer: http://stackoverflow.com/a/48001091
upvote count: 2
answer count: 3
has comment: http://stackoverflow.com/comment/82961193
has comment: http://stackoverflow.com/comment/82961444
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47996742
linked to: http://stackoverflow.com/q/6473679
tagged with: python
has comment: http://stackoverflow.com/comment/82961462
has comment: http://stackoverflow.com/comment/82961260
possible better answer: http://stackoverflow.com/a/48001091
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82961148
downvote count: 0

http://stackoverflow.com/a/47894701
answers question: http://stackoverflow.com/q/47894128
has comment: http://stackoverflow.com/comment/82767892
has comment: http://stackoverflow.com/comment/82781178
has comment: http://stackoverflow.com/comment/82768066
has body: try: import Tkinter as Tk import tkFileDialog as fileDialog except ImportError: import tkinter as Tk fileDialog = Tk.filedialog import datetime # Manipulation def processText(lines): total = 0 start = None for k, line in enumerate(lines): direction, date1, time1, _, date2, time2 = line.split() if direction != "DOWN": continue if start==None: start = date1 + ' ' + time1 # 1 D1, M1, Y1 = date1.split('.') h1, m1, s1 = time1.split(':') # 2 D2, M2, Y2 = date2.split('.') h2, m2, s2 = time2.split(':') # Timestamps t1 = datetime.datetime(*map(int, [Y1, M1, D1, h1, m1, s1])).timestamp() t2 = datetime.datetime(*map(int, [Y2, M2, D2, h2, m2, s2])).timestamp() total += (t2-t1) return total, start # Opening and updating def openFile(): filename = fileDialog.askopenfilename() fileHandle = open(filename, 'r') down, start = processText(fileHandle.readlines()) txt = "Total Downtime is {0} min from {1}".format(down//60, start) textVar.set(txt) fileHandle.close() # Main root = Tk.Tk() button = Tk.Button(root, text="Open", command=openFile) button.grid(column=1, row=1) textVar = Tk.StringVar(root) label = Tk.Label(root, textvariable=textVar) label.grid(column=1, row=2) root.mainloop()
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/82771544
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47894128

http://stackoverflow.com/q/47867746
tagged with: python
has answer: http://stackoverflow.com/a/63535416
has comment: http://stackoverflow.com/comment/82700554
type: UnansweredQuestion
tagged with: django
has answer: http://stackoverflow.com/a/47868069
upvote count: 5
type: Question
has body: I have a viewset API which getting Notification of User who get authenticate with Django JWT but I got error. Please take a look! Viewset: from api.notifications.models import Notification from rest_framework.generics import ( ListAPIView ) from api.notifications.serializers import ( NotificationListSerializer ) from api.pagination import NewFeedPagination from rest_framework.permissions import AllowAny from api.permissions import IsOwnerOrReadOnly class NotificationListAPIView(ListAPIView): permission_classes = [AllowAny] serializer_class = NotificationListSerializer ordering_fields = 'date' def get_queryset(self, *args, **kwargs): queryset_list = Notification.objects.filter(to_user=self.request.user) return queryset_list When Logged in and access URL, it's successfull. But It doesn't logged in, it came to error: int() argument must be a string or a number, not 'AnonymousUser'. How can I set up with AnonymousUser, URL will come to login page: localhost:8000/admin? All Traceback Error: Traceback: File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python27\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "C:\Python27\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "C:\Python27\lib\site-packages\rest_framework\views.py" in dispatch 489. response = self.handle_exception(exc) File "C:\Python27\lib\site-packages\rest_framework\views.py" in handle_exception 449. self.raise_uncaught_exception(exc) File "C:\Python27\lib\site-packages\rest_framework\views.py" in dispatch 486. …
score: 5
answer count: 3
has answer: http://stackoverflow.com/a/75710077
downvote count: 0
tagged with: django-rest-framework
favorite count: 0
has title: Require Log in with AnonymousUser in Django Rest Framework
has comment: http://stackoverflow.com/comment/82700741

facebook-ads-api
tags question: http://stackoverflow.com/q/48004466
tag name: facebook-ads-api
type: Tag

http://stackoverflow.com/comment/82841591
comment on: http://stackoverflow.com/q/47936083
score: 1
has text: `return ('Existed')` change to `return 'Existed'`
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48000248
answer count: 1
has title: Weight initialization in tensorflow
favorite count: 0
accepted answer: http://stackoverflow.com/a/48000505
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48000505
downvote count: 0
score: 1
tagged with: tensorflow
type: Question
has body: I've a DNN using Tensorflow and it's working just fine. My question is about the weight initialization , here the part of the code where it happens: def train(numberOfFeatures,numberOFclasses): #sesssion definition sess = tf.InteractiveSession() #input Placeholder with tf.name_scope('input'): x =tf.placeholder(tf.float32,[None,numberOfFeatures],name='Features_values') y_=tf.placeholder(tf.float32,[None,numberOFclasses],name='predictions') #Weights initialization def weight_variable(shape): return tf.Variable(tf.truncated_normal(shape,stddev=0.1)) def bias_variable(shape): return tf.Variable(tf.constant(0.1,shape=shape)) # define variable summaries def variable_summaries(var): with tf.name_scope('summaries'): mean = tf.reduce_mean(var) tf.summary.scalar('mean',mean) with tf.name_scope('stddev'): stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean))) tf.summary.scalar('stddev', stddev) tf.summary.scalar('max', tf.reduce_max(var)) tf.summary.scalar('min', tf.reduce_min(var)) tf.summary.histogram('histogram', var) looking at the doc of the function tf.truncated_normal I should get values around -0.1 and +0.1, but it's not the case , as you can see bellow So my question is what I'm missing here ? thanks in advance !
upvote count: 1

http://stackoverflow.com/comment/82696334
type: Comment
comment on: http://stackoverflow.com/a/47865645
has text: Thank you! I am so dumb for overlooking something so high school level.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82823238
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47926814
type: Comment
has text: To deal with empty rows, replace `'w'` with `'wb'` in the `open` function call.

http://stackoverflow.com/comment/82712514
type: QuestionComment
comment on: http://stackoverflow.com/q/47871390
score: 0
has text: Huh... it's been solved perfectly. `describe` returns a new Series, and the `dtype` describes _that series_, and not `maturity_date` in any way.
type: Comment

http://stackoverflow.com/a/47968627
has comment: http://stackoverflow.com/comment/82907026
upvote count: 1
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82906895
has comment: http://stackoverflow.com/comment/82906905
has body: Try this to get all the events and dates you are after: import requests from bs4 import BeautifulSoup res = requests.get('http://aicd.companydirectors.com.au/events/events-calendar') soup = BeautifulSoup(res.text,"lxml") for item in soup.find_all(class_='lead'): date = item.find_previous_sibling().text.split(" |")[0] print(item.text,date)
answers question: http://stackoverflow.com/q/47968568
type: Answer

s7-1200
tags question: http://stackoverflow.com/q/47979438
type: Tag
tag name: s7-1200

http://stackoverflow.com/comment/82946118
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/47983780
has text: Thanks for your answer!
type: Comment

http://stackoverflow.com/q/47901313
has body: I trying to run some example for tensorflow but it not works since such exception. I have no idea how to solve it? Probably I need install some packages or this example is not compatible with Tensorflow 1.4. I am using Windows 10, no cuda, Python 3.6. Is it require other version Tensorflow or it is not supported on Windows 10? Traceback (most recent call last): File "C:/Users/Cezary Wagner/PycharmProjects/tf-xor/src/s02_forest_xor.py", line 32, in &lt;module&gt; forest_graph = tensor_forest.RandomForestGraphs(hparams) File "C:\root\Python36-64\lib\site-packages\tensorflow\contrib\tensor_forest\python\tensor_forest.py", line 376, in __init__ tree_variables_class=tree_variables_class) File "C:\root\Python36-64\lib\site-packages\tensorflow\contrib\tensor_forest\python\tensor_forest.py", line 350, in __init__ self.variables.append(tree_variables_class(params, i, training)) File "C:\root\Python36-64\lib\site-packages\tensorflow\contrib\tensor_forest\python\tensor_forest.py", line 318, in __init__ params, '', self.get_tree_name('stats', tree_num)) File "C:\root\Python36-64\lib\site-packages\tensorflow\contrib\tensor_forest\python\ops\stats_ops.py", line 102, in fertile_stats_variable container, shared_name=name, name=name) File "C:\root\Python36-64\lib\site-packages\tensorflow\contrib\tensor_forest\python\ops\gen_stats_ops.py", line 134, in fertile_stats_resource_handle_op shared_name=shared_name, name=name) File "C:\root\Python36-64\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 787, in _apply_op_helper op_def=op_def) File "C:\root\Python36-64\lib\site-packages\tensorflow\python\framework\ops.py", line 2958, in create_op set_shapes_for_outputs(ret) File "C:\root\Python36-64\lib\site-packages\tensorflow\python\framework\ops.py", line 2209, in set_shapes_for_outputs shapes = shape_func(op) File "C:\root\Python36-64\lib\site-packages\tensorflow\python\framework\ops.py", line 2159, in call_with_requiring return call_cpp_shape_fn(op, require_shape_fn=T…
downvote count: 0
has answer: http://stackoverflow.com/a/52852317
favorite count: 0
has title: tensorflow.python.framework.errors_impl.NotFoundError: Op type not registered 'FertileStatsResourceHandleOp'
answer count: 1
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/125012497
has text: @pabouk, the `parents` mechanism does this - copying `Action` references from the parent to the child. I don't offhand recall which method does this (probably in the Actions_container class). So even if you don't want to use `parents` you can copy ideas from this.
type: Comment
comment on: http://stackoverflow.com/a/47878812
score: 1
type: AnswerComment

http://stackoverflow.com/comment/82725315
type: Comment
score: 2
comment on: http://stackoverflow.com/a/47879192
has text: "terminal" -> "interactive interpreter"
type: AnswerComment

http://stackoverflow.com/a/47984531
answers question: http://stackoverflow.com/q/47984489
type: AcceptedAnswer
has body: It's allowed, and it does exactly what you told it to do -- it's just that that's not the same as what you want it to do. i % 5 === i % 3 === 0 is the same as (i % 5 === i % 3) === 0 (because === is left-associative). (i % 5 === i % 3) evaluates to either true or false depending on the value of i, and true === 0 and false === 0 are both false, so the condition will always be false.
accepted answer of: http://stackoverflow.com/q/47984489
type: Answer
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/82976863
score: 4

http://stackoverflow.com/comment/82685796
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47860321
type: Comment
has text: But still there are some issues. The elements for the first column for b, c and d are missing.

http://stackoverflow.com/q/47987741
has answer: http://stackoverflow.com/a/47988291
accepted answer: http://stackoverflow.com/a/47988291
has title: selecting records which meet a condition spanning multiple columns in python
type: Question
tagged with: numpy
downvote count: 0
has comment: http://stackoverflow.com/comment/82944549
favorite count: 0
tagged with: filter
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/82944996
has body: I have the below data: So each device_id can be under several services (B,G,P..) across the year and each value in the cell captures the number of months it has used a particular service. And the latest column captures the latest service it is using. This data is in a pandas dataframe. Now I need to filter out the records for whom the number of months in the latest service is >= 3. In the example given only households 1,264, 267 should be selected and the others not. The data in text format : device_id B G P S V Other Latest 1 0 0 3 0 3 0 P 2 0 0 0 0 0 12 Other 3 0 0 0 12 0 1 S 4 0 0 0 0 12 0 V 5 0 0 0 12 0 0 S 6 0 0 0 0 12 0 V 263 0 0 0 0 0 12 Other 264 5 6 0 0 0 3 Other 265 12 0 0 0 0 0 B 266 0 12 0 0 0 0 G 267 0 2 0 3 8 0 S Can someone please help me with this?
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: dataframe

http://stackoverflow.com/comment/82757268
type: QuestionComment
has text: `else overtimepay > 0:` is not valid python. Use `elif`
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47895255

http://stackoverflow.com/comment/82898208
has text: the issue with sets is undefined ordering. there's no way to associate inputs & outputs.
type: Comment
comment on: http://stackoverflow.com/a/47964272
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82692614
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47863776
has text: yes instead of manually initializing the 'pm's. I want to alternatively do it using a loop. However the loop I have shown is not working.
score: 0

http://stackoverflow.com/q/47982140
favorite count: 0
possible better answer: http://stackoverflow.com/a/47984748
tagged with: python
has body: The following code draw single random lines every merry one second. What I would like to do is to keep each line already drawn. What is the best way to do that ? I know that I need to use a QTimer to do a responsive user interface but first I need to know how to draw more and more lines... Maybe one way would be to draw all lines hidden and to show more and more lines... Or must I use a QGraphicsView ? from random import random import sys from time import sleep from PyQt5.QtWidgets import QWidget, QApplication from PyQt5.QtGui import QPainter from PyQt5.QtCore import QTimer LINES = [ (500*random(), 500*random(), 500*random(), 500*random()) for _ in range(50) ] class Interface(QWidget): def __init__(self): super().__init__() self.max = len(LINES) self.cursor = 0 self.painter = QPainter() self.setFixedSize(500, 500) self.show() def paintEvent(self, e): self.painter.begin(self) self.drawsetpbystep() self.painter.end() def drawsetpbystep(self): if self.cursor &lt; self.max: self.painter.drawLine(*LINES[self.cursor]) self.update() sleep(0.25) self.cursor += 1 if __name__ == '__main__': app = QApplication(sys.argv) interface = Interface() sys.exit(app.exec_())
has answer: http://stackoverflow.com/a/47984748
has answer: http://stackoverflow.com/a/47995280
has title: PyQT5 - Add line one by one using a pause
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82933240
tagged with: pyqt5
accepted answer: http://stackoverflow.com/a/47995280
downvote count: 1
tagged with: sleep
type: Question
has comment: http://stackoverflow.com/comment/82957073
answer count: 2
upvote count: 0
score: -1

http://stackoverflow.com/q/47891699
favorite count: 0
has answer: http://stackoverflow.com/a/47892379
has comment: http://stackoverflow.com/comment/82750523
has answer: http://stackoverflow.com/a/47891789
has title: List of tuples to dictionary not working as expected
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47891789
score: 1
has comment: http://stackoverflow.com/comment/82749889
has answer: http://stackoverflow.com/a/47892149
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/82749947
has body: For some reason my small small brain is having problems with this, I have a list of tuples list = [('name:john','age:25','location:brazil'),('name:terry','age:32','location:acme')]. Im trying to move these values into a dictionary for parsing later. I have made a few attempts, below the latest of these and im not getting all results into the dict, the dict ends up with the last value iterated (its recreating the dict each time). people = {} list = [('name:john','age:25','location:brazil'),('name:terry','age:32','location:acme')] for value in list: people = {'person': [dict(item.split(":",1) for item in value)]}
has comment: http://stackoverflow.com/comment/82749899
answer count: 3
accepted answer: http://stackoverflow.com/a/47892149
downvote count: 0

http://stackoverflow.com/comment/82949891
type: Comment
type: QuestionComment
has text: ok. Reading through it. I do hope that we have other ways. I added an image also for understanding
score: 0
comment on: http://stackoverflow.com/q/47990143

http://stackoverflow.com/comment/82698132
type: Comment
comment on: http://stackoverflow.com/q/47866437
type: QuestionComment
has text: I don't get your code : 8 lines to built "u", which is not used... plus : function comb as defined in your code is fast on my computer and can handle quite big numbers, even if it is quite a vague definition...
score: 0

http://stackoverflow.com/comment/82954391
score: 0
has text: Unfortunately for me I'm in a constrained environment where I can't easily add lots of new modules, and pylint is what I have available.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47988540

http://stackoverflow.com/comment/82995160
comment on: http://stackoverflow.com/a/48012388
type: AnswerComment
score: 0
type: Comment
has text: yeah I that might work. I think maybe the easiest approach for my application would be to just post to the same route that loads the page

http://stackoverflow.com/comment/82800331
type: QuestionComment
has text: `py -i game1.py` will drop into the Python shell after the script is finished.
type: Comment
score: 1
comment on: http://stackoverflow.com/q/47912438

http://stackoverflow.com/a/47919447
has body: you can specify dtype while reading file. pd.read_csv(file_name,dtype={col1:type})) for more details: read_csv
type: Answer
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/47919315

http://stackoverflow.com/comment/82975765
comment on: http://stackoverflow.com/q/48001418
score: 0
type: Comment
has text: Can you also add `Employee` model?
type: QuestionComment

http://stackoverflow.com/q/47896198
answer count: 1
tagged with: scikit-learn
tagged with: seed
favorite count: 0
has answer: http://stackoverflow.com/a/47904441
has body: I currently run a random forest model using the following code. I set a random_state equal to 100. from sklearn.cross_validation import train_test_split X_train_RIA_INST_PWM, X_test_RIA_INST_PWM, y_train_RIA_INST_PWM, y_test_RIA_INST_PWM = train_test_split(X_RIA_INST_PWM, Y_RIA_INST_PWM, test_size=0.3, random_state = 100) # Random Forest Regressor for RIA_INST_PWM accounts import numpy as np from sklearn.ensemble import RandomForestRegressor regressor_RIA_INST_PWM = RandomForestRegressor(n_estimators=100, min_samples_split = 10) regressor_RIA_INST_PWM.fit(X_RIA_INST_PWM, Y_RIA_INST_PWM) print ("R^2 for training set:"), print (regressor_RIA_INST_PWM.score(X_train_RIA_INST_PWM, y_train_RIA_INST_PWM)) print ('-'*50) print ("R^2 for test set:"), print (regressor_RIA_INST_PWM.score(X_test_RIA_INST_PWM, y_test_RIA_INST_PWM)) And then I use the following code to calculate the prediction values. def predict_AUM(df, features, regressor): # Reset index for later merge of predicted target values with Account IDs df.reset_index(); # Set predictor variables X_Predict = df[features] # Clean inputs X_Predict = X_Predict.replace([np.inf, -np.inf], np.nan) X_Predict = X_Predict.fillna(0) # Predict Current_AUM Y_AUM_Snapshot_1yr_Predict = regressor.predict(X_Predict) df['PREDICTED_SPAN'] = Y_AUM_Snapshot_1yr_Predict return df df_EVENT5_20 = predict_AUM(df_EVENT5_19, dfzip_features_AUM_RIA_INST_PWM, regressor_RIA_INST_PWM) Finally, I calculate the RMSE of my results: from sklearn.metrics import mean_squared_error from math import sqrt rmse = sqrt(mean_squared_error(df_EVENT5_20['SPAN_DAYS'], df_EVENT5_20['PREDICTED_SPAN'])) rmse Each time I run my code ... my RMSE changes. It has varied from 7.75 to 16.4 Why is this happening? And how can I have the same RMSE each time I run the code? Additionally, how do I optimize my model for RMSE?
has comment: http://stackoverflow.com/comment/83039220
type: UnansweredQuestion
tagged with: python
score: 2
downvote count: 0
has title: Python Dataframe: Different RMSE Score Every Time I Run Random Forest Regressor
type: Question
upvote count: 2
tagged with: modeling
tagged with: random-forest

http://stackoverflow.com/a/48001707
has body: The obvious way seems to be using fill: import turtle turtle.color('black', 'white') turtle.speed('fastest') for i in range(140, 0, -20): turtle.up() turtle.setposition(i, 160) turtle.down() turtle.setheading(90) turtle.circle(i) for i in range(160, 0, -20): turtle.up() turtle.setposition(i, 0) turtle.down() turtle.setheading(90) turtle.begin_fill() turtle.circle(i, 180) turtle.end_fill() turtle.hideturtle() turtle.mainloop() But since you indicate you don't want to use fill, another approach is to use stamping: from turtle import Turtle, Screen CURSOR_SIZE = 20 screen = Screen() turtle = Turtle('circle', visible=False) turtle.color('black', 'white') turtle.penup() turtle.sety(140) for i in range(240, 0, -40): turtle.shapesize(i / CURSOR_SIZE) turtle.stamp() turtle.sety(0) for i in range(280, 0, -40): turtle.shapesize(i / CURSOR_SIZE) turtle.stamp() turtle.sety(-10) turtle.begin_poly() turtle.circle(10, 180, 12) turtle.end_poly() screen.register_shape("semicircle", turtle.get_poly()) turtle.shape("semicircle") turtle.sety(-160) for i in range(320, 0, -40): turtle.shapesize(i / CURSOR_SIZE) turtle.stamp() screen.mainloop() But if neither of those appeals to you, you could simply draw the image by calculating where the starting point of each arc is on the circle below it to avoid the overlapping lines. I.e. do the math.
type: Answer
answers question: http://stackoverflow.com/q/47999638
score: 0

http://stackoverflow.com/q/47858885
tagged with: subtitle
has title: Having trouble Merging 2 subtitle blocks
score: 2
type: AnsweredQuestion
has body: I'm trying to merge 2 subtitle blocks for easier translation use for deepl. While the sentences can be merged and end time changed I'm having trouble changing the index numbers. The count variable is incremented but never substracted from the index. For example if we have this subtitle block: 5 00:00:23,315 --&gt; 00:00:25,108 A streetwise but soulful teen needed somewhere to live 6 00:00:25,192 --&gt; 00:00:26,610 as he waited for his Juilliard audition. 7 00:00:26,693 --&gt; 00:00:29,488 We'd support his dancing and let him stay in the guest room, right. 5 and 6 are going to be merged. The end time will that of 6. That workjs well except when it's merged it's i should get indexes of 5 and 6 but instead I get 5 and 7. Example of what i'm trying to make: 5 00:00:23,315 --&gt; 00:00:26,610 A streetwise but soulful teen needed somewhere to live as he waited for his Juilliard audition. 6 00:00:26,693 --&gt; 00:00:29,488 We'd support his dancing and let him stay in the guest room, right. This is my code. I tried adding 2 places, tried subs[sub.index].index = subs[sub.index] - count but none of that worked. import pysrt import os count = 0 # Init pysrt subs = pysrt.open(" Bojack Horseman36.srt") # Go through each subtitle for sub in subs: try: # Check if it's a sentence if not check if there is another sentence there if not nothing just remove index sentence = None if subs[sub.index].text.endswith('.') or subs[sub.index].text.endswith('?') or subs[sub.index].text.endswith('!'): subs[sub.index].index - count else: subs[sub.index].text = subs[sub.index].text + '\n' + subs[sub.index+1].text count+=1 subs[sub.index].index - count subs[sub.index].end = subs[sub.index+1].end del subs[sub.index+1] except IndexError: pass subs.save('translatedsubs.srt', encoding='utf-8') Any help is going to be appreciated thanks :D
type: Question
has comment: http://stackoverflow.com/comment/82683088
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/47859784
tagged with: python
tagged with: merge
has comment: http://stackoverflow.com/comment/82682873
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47859784
upvote count: 2

awk
tag name: awk
type: Tag
tags question: http://stackoverflow.com/q/47928211
tags question: http://stackoverflow.com/q/47893288

http://stackoverflow.com/a/47915994
has body: This code should do the trick: import os import shutil import re pattern = "^\d{4}2013$" searchDir = 'C:/Users/USER/Desktop/test/' innerDirs = os.listdir(searchDir) for dir in innerDirs: if (re.search(pattern, dir)): shutil.rmtree(searchDir + dir) The code above will remove any "date" folder that ends with '2013'.
downvote count: 0
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47915831

http://stackoverflow.com/comment/82858959
type: Comment
has text: Indeed empty __init__.py files is the way to get over the error. Python does not provide a mechanism to exclude anything from import.
comment on: http://stackoverflow.com/a/47944334
score: 1
type: AnswerComment

http://stackoverflow.com/q/47983474
has answer: http://stackoverflow.com/a/50693010
accepted answer: http://stackoverflow.com/a/50693010
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49772043
downvote count: 0
score: 9
type: Question
possible better answer: http://stackoverflow.com/a/49772043
has answer: http://stackoverflow.com/a/47983577
has answer: http://stackoverflow.com/a/47983573
answer count: 6
has answer: http://stackoverflow.com/a/50172717
tagged with: http://stackoverflow.com/tag/html
favorite count: 0
upvote count: 9
has answer: http://stackoverflow.com/a/47983571
tagged with: django
tagged with: python
has body: I've seen this error posted several times, but I can't find anyone using Django 2.0 and having the problem. The problem cropped up when I tried to nest one app inside another. The nested app (called "users") is meant to allow users to login and out. After putting that segment in, I'm getting the following error: Template error: In template C:\Users\arbit\Documents\python\learning_log\learning_logs\templates\learning_logs\base.html, error at line 6 'users' is not a registered namespace 1 : 2 : Learning Log 3 : Topics 4 : {% if user.is_authenticated %} 5 : Hello, {{ user.username }}. 6 : log out 7 : {% else %} 8 : log in 9 : {% endif %} 10 : 11 : 12 : {% block content %}{% endblock content %} 13 : Here's my root urls.py from django.urls import path, include from django.contrib import admin from . import views app_name = "learning_log" urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('users.urls')), path('', include('learning_logs.urls')), ] urlpatterns = [ # Home page path('', views.index, name='index'), # Show all topics path('topics/', views.topics, name='topics'), # Detail page for a single topic path('topics/<int:topic_id>/', views.topic, name='topic'), # Page for adding a new topic path('new_topic/', views.new_topic, name='new_topic'), # Page for adding a new entry path('new_entry/<int:topic_id>/', views.new_entry, name='new_entry'), # Page for editing an entry path('edit_entry/<int:entry_id>/', views.edit_entry, name='edit_entry'), ] ... and the app "users" url.py from django.urls import path from django.contrib.auth.views import login from . import views app_name = 'users' urlpatterns = [ # Login page. path('login/', login, {'template_name': 'users/login.html'}, name='login'), # Logout page path('logout/', views.logout_view, name='logout'), ] and the base.html from the "users" app Learning Log Topics {% if user.is_authenticated %} Hello, {{ user.username }}. log out {% else %} log in {% endif %} {% block content %}{% endblock content %} I…
has title: Django 2.0 'name' is not a registered namespace

http://stackoverflow.com/comment/82783502
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47907742
type: AnswerComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ Thanks man. I know you hate using list comprehension inplace of for loops when the end goal is not to build a list. Timings show that this method is faster.

http://stackoverflow.com/comment/82717566
has text: Not at all sarcastic. Its a failing of many posters to post incomplete information. Your post was complete with code **and** a traceback. Good question.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47875726
type: Comment

http://stackoverflow.com/comment/82959751
has text: Good, I see you added "possibly", that's enough for me to retract the downvote. Btw, when you "dismiss" the idea to convert `input_set` to a `set`, you make it sound like that might make it wrong. Do you think that? It wouldn't.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47988808

http://stackoverflow.com/comment/82695347
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47865181
type: QuestionComment
has text: @JJJ Hello, i have edited the question to make it more clear, there are no error but the output is wrong.

http://stackoverflow.com/a/47939083
downvote count: 0
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/47938864
has body: You should build your docker images by using docker-compose file. Just follow any tutorial for how to use docker-compose. and then without any manually deletion you can re-build and re-run all images by using below commands. Build all Images docker-compose build Build and run all containers docker-compose up -d I have listed some daily useful commands for docker, have a look https://rohanjmohite.wordpress.com/2017/08/04/docker-daily-useful-commands/

http://stackoverflow.com/comment/82835571
comment on: http://stackoverflow.com/q/47933194
score: 1
has text: You already cast input to an int.. why do you need to check if `type(score) == int`?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82762501
type: Comment
comment on: http://stackoverflow.com/a/47897568
type: AnswerComment
has text: ...which is to say, I don't see how following this advice would solve any problem the OP's question can be reasonably interpreted as asking about.
score: 0

http://stackoverflow.com/comment/82878190
has text: ok, when I display each item I get something like [3], [4] etc. How can I get only the number like 3,4?
score: 0
comment on: http://stackoverflow.com/q/47954431
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82810656
comment on: http://stackoverflow.com/q/47921391
score: 0
type: Comment
has text: what a difference between that two print lines?
type: QuestionComment

http://stackoverflow.com/comment/82681331
type: QuestionComment
has text: @Daniel I didn't post the whole string here...
comment on: http://stackoverflow.com/q/47857950
score: 0
type: Comment

http://stackoverflow.com/q/47897391
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47898692
accepted answer: http://stackoverflow.com/a/47898692
tagged with: exception
tagged with: python
linked to: http://stackoverflow.com/q/29548587
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/82761944
score: 1
type: Question
has body: I have a function that is supposed to generate a tuple of all built-in exceptions, (for use in the except (Exception1, Exception2, etc...) as error: form) and when I run it normally, it works just fine. def get_exceptions(): exceptionList = [] for item in dir(__builtins__): if item.find('Error') != -1: exec('exceptionList.append({})'.format(item)) return tuple(exceptionList) if __name__ == '__main__': print(get_exceptions()) and when run: (&lt;class 'ArithmeticError'&gt;, &lt;class 'AssertionError'&gt;, &lt;class 'AttributeError'&gt;, &lt;class 'BlockingIOError'&gt;, &lt;class 'BrokenPipeError'&gt;, &lt;class 'BufferError'&gt;, &lt;class 'ChildProcessError'&gt;, &lt;class 'ConnectionAbortedError'&gt;, &lt;class 'ConnectionError'&gt;, &lt;class 'ConnectionRefusedError'&gt;, &lt;class 'ConnectionResetError'&gt;, &lt;class 'EOFError'&gt;, &lt;class 'OSError'&gt;, &lt;class 'FileExistsError'&gt;, &lt;class 'FileNotFoundError'&gt;, &lt;class 'FloatingPointError'&gt;, &lt;class 'OSError'&gt;, &lt;class 'ImportError'&gt;, &lt;class 'IndentationError'&gt;, &lt;class 'IndexError'&gt;, &lt;class 'InterruptedError'&gt;, &lt;class 'IsADirectoryError'&gt;, &lt;class 'KeyError'&gt;, &lt;class 'LookupError'&gt;, &lt;class 'MemoryError'&gt;, &lt;class 'NameError'&gt;, &lt;class 'NotADirectoryError'&gt;, &lt;class 'NotImplementedError'&gt;, &lt;class 'OSError'&gt;, &lt;class 'OverflowError'&gt;, &lt;class 'PermissionError'&gt;, &lt;class 'ProcessLookupError'&gt;, &lt;class 'ReferenceError'&gt;, &lt;class 'RuntimeError'&gt;, &lt;class 'SyntaxError'&gt;, &lt;class 'SystemError'&gt;, &lt;class 'TabError'&gt;, &lt;class 'TimeoutError'&gt;, &lt;class 'TypeError'&gt;, &lt;class 'UnboundLocalError'&gt;, &lt;class 'UnicodeDecodeError'&gt;, &lt;class 'UnicodeEncodeError'&gt;, &lt;class 'UnicodeError'&gt;, &lt;class 'UnicodeTranslateError'&gt;, &lt;class 'ValueError'&gt;, &lt;class 'OSError'&gt;, &lt;class 'ZeroDivisionError'&gt;) which is just as I wanted. however, at the following, through …
has comment: http://stackoverflow.com/comment/82762093
has comment: http://stackoverflow.com/comment/82762250
has answer: http://stackoverflow.com/a/47897872
has comment: http://stackoverflow.com/comment/82762040
answer count: 2
has comment: http://stackoverflow.com/comment/82761834
has title: Simple function to find all built-in exceptions works when run directly, but fails when used as imported module, giving no traceback
upvote count: 1
possible better answer: http://stackoverflow.com/a/47897872

http://stackoverflow.com/comment/82939150
has text: you could use list or dictionary to keep all pipes' position and size and then you can use `for` loop to draw them and to check collisions. Python has even [pygame.Rect()](http://pygame.org/docs/ref/rect.html) to keep position and size - and it has method `colliderect`, `collidepoint`, etc. Currently I don't see where do you check collisions - so they doesn't work.
score: 0
comment on: http://stackoverflow.com/q/47984812
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82991479
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48011370
score: 0
has text: @Sundararaj Govindasamy I added the error, please take a look.

http://stackoverflow.com/comment/82866917
type: AnswerComment
has text: @AntonvBR List comprehensions are faster than `map` on shorter examples, however, `map` is almost always slower when using a lambda function (as in this case). I will edit the post the mention this.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47948143

api
tags question: http://stackoverflow.com/q/47995159
tags question: http://stackoverflow.com/q/47861097
tags question: http://stackoverflow.com/q/47976274
tags question: http://stackoverflow.com/q/47897996
tags question: http://stackoverflow.com/q/47940052
tags question: http://stackoverflow.com/q/47889267
tags question: http://stackoverflow.com/q/47942122
tags question: http://stackoverflow.com/q/47887547
tags question: http://stackoverflow.com/q/47953615
tags question: http://stackoverflow.com/q/47918025
tags question: http://stackoverflow.com/q/47962277
tags question: http://stackoverflow.com/q/48014240
type: Tag
tags question: http://stackoverflow.com/q/48012783
tags question: http://stackoverflow.com/q/47863300
tags question: http://stackoverflow.com/q/47958066
tags question: http://stackoverflow.com/q/47960597
tag name: api
tags question: http://stackoverflow.com/q/47995349
tags question: http://stackoverflow.com/q/47912960
tags question: http://stackoverflow.com/q/47994646
tags question: http://stackoverflow.com/q/47931233
tags question: http://stackoverflow.com/q/47867919
tags question: http://stackoverflow.com/q/47860744
tags question: http://stackoverflow.com/q/47892781
tags question: http://stackoverflow.com/q/48001159
tags question: http://stackoverflow.com/q/47991331
tags question: http://stackoverflow.com/q/47869572

http://stackoverflow.com/comment/82703286
type: Comment
comment on: http://stackoverflow.com/a/47868040
type: AnswerComment
has text: What happen when they access lock??
score: 0

keras
tags question: http://stackoverflow.com/q/47897256
tags question: http://stackoverflow.com/q/47898566
tags question: http://stackoverflow.com/q/47945512
tags question: http://stackoverflow.com/q/47980322
tags question: http://stackoverflow.com/q/47972726
tags question: http://stackoverflow.com/q/47884862
tags question: http://stackoverflow.com/q/47948160
tags question: http://stackoverflow.com/q/47979861
tags question: http://stackoverflow.com/q/47976845
tags question: http://stackoverflow.com/q/47889999
tags question: http://stackoverflow.com/q/47988817
tags question: http://stackoverflow.com/q/47990621
tags question: http://stackoverflow.com/q/48003732
tags question: http://stackoverflow.com/q/47911093
tags question: http://stackoverflow.com/q/47859532
tags question: http://stackoverflow.com/q/47988983
tags question: http://stackoverflow.com/q/47955200
tags question: http://stackoverflow.com/q/47891655
tags question: http://stackoverflow.com/q/48006574
tags question: http://stackoverflow.com/q/47907409
tags question: http://stackoverflow.com/q/47899463
tags question: http://stackoverflow.com/q/47994524
tags question: http://stackoverflow.com/q/47973267
tags question: http://stackoverflow.com/q/47909021
tags question: http://stackoverflow.com/q/47885357
tags question: http://stackoverflow.com/q/47959640
tags question: http://stackoverflow.com/q/47945175
tags question: http://stackoverflow.com/q/47935253
tags question: http://stackoverflow.com/q/47946413
tags question: http://stackoverflow.com/q/47972820
tags question: http://stackoverflow.com/q/47931014
tags question: http://stackoverflow.com/q/47860237
tags question: http://stackoverflow.com/q/47928365
tags question: http://stackoverflow.com/q/47981775
tags question: http://stackoverflow.com/q/47910449
tags question: http://stackoverflow.com/q/47923370
tags question: http://stackoverflow.com/q/47925346
tags question: http://stackoverflow.com/q/47927732
tags question: http://stackoverflow.com/q/47977497
tags question: http://stackoverflow.com/q/47926026
tags question: http://stackoverflow.com/q/47947578
tags question: http://stackoverflow.com/q/47927433
tags question: http://stackoverflow.com/q/47930176
tag name: keras
tags question: http://stackoverflow.com/q/48008048
type: Tag
tags question: http://stackoverflow.com/q/47932589
tags question: http://stackoverflow.com/q/47984976
tags question: http://stackoverflow.com/q/47934323
tags question: http://stackoverflow.com/q/47877083
tags question: http://stackoverflow.com/q/47902295
tags question: http://stackoverflow.com/q/47933858

http://stackoverflow.com/q/47862345
type: AnsweredQuestion
tagged with: sqlite
has title: Python error trying to use .execute() SQLite API query With keyword arguments
has body: I'm learning SQLite and have been trying to create a string that stores values and retrieves rows, but I get an error "execute() takes no keyword arguments." This is the way I referenced the database: import sqlite3 dbb = sqlite3.connect('finance.db') db = dbb.cursor() username = request.form.get("username") #query database for username rows = db.execute("SELECT * FROM users WHERE username = :username", \ username=username) UPDATE I misrepresented my parameters. I used the qmarks notation mentioned in the accepted answer below to reference table rows
type: Question
has answer: http://stackoverflow.com/a/47864487
tagged with: python
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/47864487
tagged with: execute
tagged with: database

http://stackoverflow.com/comment/82836020
type: Comment
type: QuestionComment
has text: @MadPhysicist Sorry, but then how to print ONLY "No projection on that date" if there's really no ANY projection on entered date? :)
comment on: http://stackoverflow.com/q/47933270
score: 0

http://stackoverflow.com/comment/82899839
has text: @CharlieParker good! It works because we put `-c pytorch` immediately after `conda install`. By this, first we're selecting the `channel` *pytorch* and then we're install the package *pytorch* and *torchvision*. This way of installation is clear to understand and will always work :) The way this installation command written in pytorch page will produce unexpected behaviour. So, I'd suggest you to follow this convention while installing any package in conda environment or in a `virtualenv`. Merry Christmas!
type: AnswerComment
comment on: http://stackoverflow.com/a/47955553
type: Comment
score: 1

http://stackoverflow.com/q/47859517
type: Question
upvote count: 0
accepted answer: http://stackoverflow.com/a/47859660
answer count: 1
favorite count: 0
has title: How to get function of median from numpy?
has comment: http://stackoverflow.com/comment/82683781
has body: What is the numpy function where it lets you use the median function(code to do that if you know) from bumpy import median alternative pls
score: -3
tagged with: python
type: AnsweredQuestion
downvote count: 3
has answer: http://stackoverflow.com/a/47859660

http://stackoverflow.com/a/48014188
answers question: http://stackoverflow.com/q/48010317
has body: Can we do something like this? import pandas as pd import numpy as np data = '''\ TimeStamp open high low close volume 2017-12-22T13:15:00 12935.00 13200.00 12508.71 12514.91 244.728611 2017-12-22T13:30:00 12514.91 12999.99 12508.71 12666.34 150.457869 2017-12-22T13:45:00 12666.33 12899.97 12094.00 12094.00 198.680014 2017-12-22T14:00:00 12094.01 12354.99 11150.00 11150.00 256.812634 2017-12-22T14:15:00 11150.01 12510.00 10400.00 12276.33 262.217127''' df = pd.read_csv(pd.compat.StringIO(data), sep='\s+', parse_dates=['TimeStamp'], index_col=['TimeStamp']) df['new_time'] = df.index[1:].tolist()+[np.NaN] # df['new_time'] = np.roll(df.index, -1) # if last is not first+15min # use boolean indexing to filter away unwanted rows df(dt2-dt1)/np.timedelta64(1, 's') == 900 for dt1,dt2 in zip(df.index.values,df.new_time.values)
score: 0
type: Answer

http://stackoverflow.com/a/47933780
has body: This would be "a" way to approach your problem. has_connections = [True, True, False] group_connections = [45, 88, 55] for h, g in zip(has_connections, group_connections): if h: print(g)
type: Answer
answers question: http://stackoverflow.com/q/47933656
score: 0

http://stackoverflow.com/q/47884174
tagged with: enigma2
has body: It was a non-compulsory exercise to build an enigma 'like' machine for schoolwork at uni. There were several steps for guidance (first I had to implement one rotating wheel, then 3 of them, after this I had to implement the reflector, then the ability to set the starting position for the wheels). Until this point everything went fine (it passed every test), but when I tried to implement the plugboard (Steckerbrett) my build fails to do the test and after searching for a mistake for hours (that i could not find) I ask you to help me. Here is my code (please note that I am still a noobie and that my code may not be the neatest): #Enigma build (everything included) class Enigma: def __init__(self, wheels, reflector, starting_position, plugs, message): self.message = message self.wheels = Wheels(wheels, starting_position) self.reflector = reflector self.plugboard = Plugboard(plugs) self.alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" self.wheels.set_starting_position() def execute(self): output = "" self.message = self.plugboard.forward(self.message) for char in self.message: if char in self.alphabet: coded_char = char if coded_char in self.plugboard.plugs_forward: coded_char = self.plugboard.plugs_forward[coded_char] coded_char = coding_forward(coded_char, self.alphabet, self.wheels.wheel1) coded_char = coding_forward(coded_char, self.alphabet, self.wheels.wheel2) coded_char = coding_forward(coded_char, self.alphabet, self.wheels.wheel3) coded_char = coding_forward(coded_char, self.alphabet, self.reflector) coded_char = coding_backward(coded_char, self.alphabet, self.wheels.wheel3) coded_char = coding_backward(coded_char, self.alphabet, self.wheels.wheel2) coded_char = coding_backward(coded_char, self.alphabet, self.wheels.wheel1) output = "".join([output, coded_char]) self.wheels.rotate() output = self.plugboard.backward(output) return output class Wheels: def __init__(self, wheels, position): self.wheel1 = wheels[0] self.wheel2 = wheels[1] self.wheel3 = wheels[2] self.positi…
favorite count: 0
has title: Problems with implementing the plugboard for an enigma build in python
has answer: http://stackoverflow.com/a/47884565
tagged with: python
accepted answer: http://stackoverflow.com/a/47884565
type: AnsweredQuestion
score: -4
type: Question
tagged with: encoding
downvote count: 4
upvote count: 0
answer count: 1

http://stackoverflow.com/comment/82922606
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47976524
type: QuestionComment
has text: maybe you can post the stacktrace as well for "pip install jira"

http://stackoverflow.com/comment/82748076
type: AnswerComment
has text: I'm not even sure dask could solve the fundamental batching problem: If a learner needs to see all the data at once to learn, then it either all needs to fit on memory somewhere or I'll have to cause a ton of page faults looking around at a memory-mapped file on disk, which will be slow. In my problem, we actually do a join of a couple of the database tables at read-time, so the hundred GB on disk explodes to TB for training.
comment on: http://stackoverflow.com/a/47890326
type: Comment
score: 0

http://stackoverflow.com/comment/82937644
score: 1
comment on: http://stackoverflow.com/a/47984221
type: AnswerComment
type: Comment
has text: @bluprince13: No, that is definitely not sth. to teach a beginner :)

http://stackoverflow.com/a/47906618
downvote count: 0
answers question: http://stackoverflow.com/q/47906065
type: Answer
score: 1
upvote count: 1
has body: I added a few Python modules to Maya with the "addsitedir-trick" explained at the end but not every python module will be playing nicely with Maya. Python on Windows is built with Visual Studio 2008 Professional. Maya uses it's own Python interpreter but Autodesk builts Maya with another Visual Studio version. This can lead to problems if you insall python modules and try to use them with Maya. Beatuifully explained here (together with a the hard solution of compiling the wanted modules yourself): http://p-nand-q.com/python/building-python-27-with-vs2010.html What you can try: Install Python 2.7 on your Windows-box, install the module you want to access in Maya (eg with pip). Now in Maya add your system SitePackages (where you just installed the module to) to your Maya-Python-Interpreter SitePackages like so: import site site.addsitedir("/path/to/your/python27/Lib/site-packages") Even cleaner solution would be to use a virtualenv instead of the global site-packages folder! (That's at least what i have done to get psycopg2 and requests play with Maya) But as mentioned in the beginning of this answer there is a possibility that this may fail (with strange errors). By the way: I highly recommend to use pyside instead of Tkinter if you want to do GUI stuff in Maya. Or the Maya-Wrappers preferably via pymel. (http://help.autodesk.com/cloudhelp/2017/ENU/Maya-Tech-Docs/PyMel/ui.html)

http://stackoverflow.com/a/47897079
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/47896877
score: 2
downvote count: 0
has body: Your final file.json example is not a valid JSON. Assuming you want to just convey the form with it you might try extending the json.JSONEncoder, but assuming you don't have nested structures in your dictionaries a quick and dirty approach would be to just construct the file manually, i.e. import json your_data = [ # lets define some test data {"key1.0": "value", "key2.0": "value"}, {"key1.1": "value", "key2.1": "value"}, {"key1.2": "value", "key2.2": "value"}, {"key1.3": "value", "key2.3": "value"}, ] with open("file.json", "w") as f: # open our file for writing f.write("[") # begin a JSON array if your_data: # a check to determine that our array is not empty for element in your_data: # now loop through your elements one by one json.dump(element, f) # JSON encode each element and write it to the file f.write(",\n") # close the element entry with a comma and a new line f.seek(-3, 1) # go back to the last separator to clear out the comma f.write("]") # end the JSON array f.truncate() # remove the rest, just in case Which will produce: [{"key1.0": "value", "key2.0": "value"}, {"key1.1": "value", "key2.1": "value"}, {"key1.2": "value", "key2.2": "value"}, {"key1.3": "value", "key2.3": "value"}]

http://stackoverflow.com/q/47911859
downvote count: 5
answer count: 1
has body: I have a login system in which students take quizzes at different difficulties. what i need to do is load the question and answers for the quiz from an external .txt file. can someone help me quickly please as i need to have this done very soon. can the coding be simple aswell and available to use on python 3.4 as i am not very good with python
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82837900
tagged with: python
has comment: http://stackoverflow.com/comment/82837695
score: -5
has title: Creating a quiz and summoning questions and answers from extrernal file
has comment: http://stackoverflow.com/comment/82895270
tagged with: authentication
has answer: http://stackoverflow.com/a/47963026
has comment: http://stackoverflow.com/comment/82791552
type: Question
has comment: http://stackoverflow.com/comment/82791539
has comment: http://stackoverflow.com/comment/82792435
upvote count: 0

http://stackoverflow.com/comment/82958214
comment on: http://stackoverflow.com/a/47985841
type: AnswerComment
score: 0
has text: For what every reason anything_but = StringVar() is not working as far as passing on what I type as a textvariable
type: Comment

http://stackoverflow.com/comment/82691846
has text: @KarthikShanmukha if it helps you can accept the answer, or if you have any confusion you can move this discussion to chat.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47861976

http://stackoverflow.com/comment/82775912
comment on: http://stackoverflow.com/q/47895053
has text: We are making progress. Take a look at wsgi.py - I’m guessing the path to your setting file is also off by one level.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82879797
comment on: http://stackoverflow.com/q/47954890
score: 0
type: QuestionComment
type: Comment
has text: @StefanPochmann, this is what `timeit.timeit("'1234567890123456'")` returns when run from the interpreter.

http://stackoverflow.com/comment/82834352
has text: How much end-to-end system profiling have you done? Are you able to diagnose where your bottlenecks are?
score: 1
comment on: http://stackoverflow.com/q/47879986
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47998569
upvote count: 2
has comment: http://stackoverflow.com/comment/82965845
has body: Using Pandas, change f to 'test.csv' to read from file: import pandas as pd data = '''\ "DSP";"Fecha";"Moneda_a_pagar_a_medio";"Impresiones";"Importe_a_pagar_a_medio";"eCPM" DSP;01/12/2017;USD;2.324;596,73;0,65''' f = pd.compat.StringIO(data) df = pd.read_csv(f, sep=";", thousands='.', decimal=',') df.to_csv('output.csv', index=False) output: DSP,Fecha,Moneda_a_pagar_a_medio,Impresiones,Importe_a_pagar_a_medio,eCPM DSP,01/12/2017,USD,2324,596.73,0.65
has comment: http://stackoverflow.com/comment/82968351
has comment: http://stackoverflow.com/comment/82968045
has comment: http://stackoverflow.com/comment/82967939
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82967971
answers question: http://stackoverflow.com/q/47998419
type: Answer
has comment: http://stackoverflow.com/comment/82967983
has comment: http://stackoverflow.com/comment/82967996

http://stackoverflow.com/q/47958281
has comment: http://stackoverflow.com/comment/82885921
has answer: http://stackoverflow.com/a/47958353
has comment: http://stackoverflow.com/comment/82885994
has body: Why am I getting ImportError: cannot import name 'BeautifulSoup' line 1, in &lt;module&gt; from bs4 import BeautifulSoup ImportError: cannot import name 'BeautifulSoup' Is it installed? pip install --upgrade --force-reinstall beautifulsoup4 Collecting beautifulsoup4 Using cached beautifulsoup4-4.6.0-py3-none-any.whl Installing collected packages: beautifulsoup4 Found existing installation: beautifulsoup4 4.6.0 Uninstalling beautifulsoup4-4.6.0: Successfully uninstalled beautifulsoup4-4.6.0 Successfully installed beautifulsoup4-4.6.0 Appears so.
has comment: http://stackoverflow.com/comment/82885928
type: Question
has title: ImportError: cannot import name 'BeautifulSoup'
score: 2
has comment: http://stackoverflow.com/comment/82885916
downvote count: 0
answer count: 1
favorite count: 0
tagged with: beautifulsoup
tagged with: python
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/82760020
type: AnswerComment
type: Comment
has text: do you import difflib from somewhere as it says name is not defined
comment on: http://stackoverflow.com/a/47896447
score: 0

http://stackoverflow.com/comment/82742589
comment on: http://stackoverflow.com/q/47869521
type: QuestionComment
score: 1
has text: Just be aware that installing packages for the system python interpreter using pip can lead to problems, specially when pip tries to update a package that is also installed by the package manager (apt) and existing packages require the older version. pip does install packages to `/usr/local/lib/` which should not interfere with apt installed packages, but if a system package suddenly finds a newer, incompatible version of a dependency it can break. Using a venv is preferred.
type: Comment

http://stackoverflow.com/comment/82947934
comment on: http://stackoverflow.com/q/47989737
score: 1
has text: how are you entering the username from the frontend?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82754322
type: AnswerComment
comment on: http://stackoverflow.com/a/47872490
score: 0
type: Comment
has text: I'm a bit new here, is there a way I can share you a dataframe to see how I'm getting the information?

http://stackoverflow.com/q/47901481
tagged with: watchdog
type: Question
tagged with: python
has title: watchdog stuck the flask web page
has comment: http://stackoverflow.com/comment/82769574
linked to: http://stackoverflow.com/q/31948285
upvote count: 1
tagged with: socket.io
answer count: 1
has comment: http://stackoverflow.com/comment/109580621
duplicate of: http://stackoverflow.com/q/31948285
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47901555
tagged with: python-watchdog
has body: I am trying to create a document monitoring script with flask and watchdog what I want to do is, if a file change in a directory it should immediately show in a web page. (if the web page is open in a browser) initially, I tried printing the file change in the console while using below script, when I routed to the localhost:5000/monitor in the browser, the browser is loading for a long time and if the file is changed it shows in the console out. I cannot understand why the browser is stuck can someone help me to understand this @webapp.route('/monitor', methods=['GET', 'POST']) def monitor(): logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S') # path = sys.argv[1] if len(sys.argv) &gt; 1 else '.' path = 'I:\\Projects\\files\\.' event_handler = LoggingEventHandler() observer = Observer() observer.schedule(event_handler, path, recursive=True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join() return 'monitor script running'
downvote count: 0
score: 1
tagged with: flask
favorite count: 0

http
tags question: http://stackoverflow.com/q/47986704
tags question: http://stackoverflow.com/q/47924370
tags question: http://stackoverflow.com/q/47978985
tags question: http://stackoverflow.com/q/47923952
tags question: http://stackoverflow.com/q/48005772
tags question: http://stackoverflow.com/q/47915107
tags question: http://stackoverflow.com/q/47974846
tag name: http
tags question: http://stackoverflow.com/q/47916884
tags question: http://stackoverflow.com/q/47963205
tags question: http://stackoverflow.com/q/47926726
tags question: http://stackoverflow.com/q/47996637
type: Tag
tags question: http://stackoverflow.com/q/47965937
tags question: http://stackoverflow.com/q/47910854
tags question: http://stackoverflow.com/q/47881270
tags question: http://stackoverflow.com/q/47983412

http://stackoverflow.com/q/47861325
has comment: http://stackoverflow.com/comment/82695478
upvote count: 1
has comment: http://stackoverflow.com/comment/82695412
favorite count: 0
has comment: http://stackoverflow.com/comment/82696447
has comment: http://stackoverflow.com/comment/82695970
has comment: http://stackoverflow.com/comment/82695734
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82698047
tagged with: python
linked to: http://stackoverflow.com/q/5414586
has title: Python: What is the most efficient way to save/read a large number of float values in a compressed file
has comment: http://stackoverflow.com/comment/82698309
has comment: http://stackoverflow.com/comment/82695828
answer count: 0
downvote count: 0
score: 1
tagged with: floating-point
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/82697736
has comment: http://stackoverflow.com/comment/82696059
has body: I need to read the RGB values from an image file (e.g. scipy.misc.imread), process/convert them and store them as float values within the range (0.0 to 255.0) in a compressed file. I have tried to use numpy.savez_compressed to save the float values into npz file and use numpy.load to read them back. However I found that numpy.load is taking a long time to read back the float values from the npz compressed file. If we use scipy.misc.imsave and scipy.misc.imread, it can save the RGB integer values in a compressed format, and read them very quickly. What is the most efficient way in terms of speed to read back the float values in a compressed file?

http://stackoverflow.com/q/47931700
has title: Python Lazy Loading Property not working for Class method
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/47931800
downvote count: 0
has comment: http://stackoverflow.com/comment/82832265
favorite count: 0
accepted answer: http://stackoverflow.com/a/47931849
has comment: http://stackoverflow.com/comment/82832390
has comment: http://stackoverflow.com/comment/82832517
has comment: http://stackoverflow.com/comment/82832298
has comment: http://stackoverflow.com/comment/82832489
has comment: http://stackoverflow.com/comment/82832361
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82832599
has body: I have a class Foo that uses lazy loading for Foo.bar. class Foo(object): @property def bar(self): if not hasattr(self, '_bar'): self._initBar() return self._bar def _initBar(self): self._bar = 'bar' foo = Foo() print(foo.bar) # prints "bar" However when i try to convert Foo to use class methods only, Foo.bar is not giving me bar, but instead giving: &lt;property object at 0x000001CA1C344728&gt; Why is it not giving me bar? class Foo(object): @property @classmethod def bar(cls): if not hasattr(cls, '_bar'): cls._initBar() return cls._bar @classmethod def _initBar(cls): cls._bar = 'bar' print(Foo.bar) # prints "&lt;property object at 0x000001CA1C344728&gt;"
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82832302
has comment: http://stackoverflow.com/comment/82832555
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47931849
score: 1
has answer: http://stackoverflow.com/a/47931800

http://stackoverflow.com/comment/82697466
score: 0
comment on: http://stackoverflow.com/q/47865277
type: Comment
type: QuestionComment
has text: @furas I tried creating instance before using prolog = Prolog() and it didn't fix the issue.

http://stackoverflow.com/comment/138250291
type: Comment
comment on: http://stackoverflow.com/a/65865696
has text: Thanks for the feedback @Tails86, I've fixed the typos (i.e. removed the plural in `build_extension`.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82706223
score: 0
comment on: http://stackoverflow.com/q/47870037
type: Comment
type: QuestionComment
has text: do you ahve the correct library? sometimes they have different names than to what you think

http://stackoverflow.com/a/47877479
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47877215
has body: pd.DataFrame({'ID': [111,111,111], 'Date': ['2007-01-01', '2017-01-03', '2007-01-02'],'Name':['Abc','xyz','rst']}) Date ID Name 0 2007-01-01 111 Abc 1 2017-01-03 111 xyz 2 2007-01-02 111 rst idx = 1 cols = [1,1,1] idx2 = 4 colAlias = ['Adam','x','Adam'] df.insert(loc=1, column='DateCount', value=cols) df.insert(loc=4, column='Alias', value=colAlias) Date DateCount ID Name Alias 0 2007-01-01 1 111 Abc x 1 2017-01-03 1 111 xyz Adam 2 2007-01-02 1 111 rst Adam
downvote count: 0
type: Answer

http://stackoverflow.com/comment/82829534
has text: `list=list.sort()`
score: 0
comment on: http://stackoverflow.com/q/47930418
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47930394
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/47930472
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82829410
downvote count: 2
has comment: http://stackoverflow.com/comment/82829416
type: Question
possible better answer: http://stackoverflow.com/a/47930432
has body: I would like to know a pythonic way to convert the following dict in python: a = {1: {'region': 'us-west' }, 2: {'region': 'us-west' } } to be in the form of: new_a = {'us-west': {1: {'data': {}, 'metadata': {} }, 2: {'data': {}, 'metadata': {} } } }
has answer: http://stackoverflow.com/a/47930432
score: -2
has answer: http://stackoverflow.com/a/47930472
answer count: 2
upvote count: 0
favorite count: 0
has title: Transform nested dict in python
tagged with: python

http://stackoverflow.com/comment/82962298
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47959931
has text: Thank you! I'd seen the post of yours before. Interesting: you write (of env variables): "they need to be set in the environment under which the initial Apache process starts up". Since my Apache server is running under systemd, what I just tried is using `Environment=` directives in a drop-in `override.conf` to set `LANG` and `LC_ALL`. No luck.
type: AnswerComment

http://stackoverflow.com/a/48001452
answers question: http://stackoverflow.com/q/48001322
accepted answer of: http://stackoverflow.com/q/48001322
has comment: http://stackoverflow.com/comment/82974883
score: 0
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/82974430
has comment: http://stackoverflow.com/comment/82974620
has comment: http://stackoverflow.com/comment/82974037
has body: The execute() method (usually) only executes a single command at a time, so the script cannot be parsed, and anyway there is no support for DELIMITER; see this comment on GitHub. Therefore, one solution is to have multiple calls: cursor6.execute(""" DROP PROCEDURE IF EXISTS schema_change """) cursor6.execute(""" CREATE PROCEDURE schema_change() BEGIN if exists (select * from information_schema.columns where table_schema = schema() and table_name = 'selectedairport' and column_name = 'GDP') then alter table selectedairport drop column GDP; NOTE: There is a syntax error here, we need to further add: END IF; Now continue as before: alter table selectedairport add column GDP DOUBLE; end """) cursor6.execute(""" CALL schema_change () """) # Or cursor6.callproc('schema_change') cursor6.execute(""" DROP PROCEDURE IF EXISTS schema_change """)
has comment: http://stackoverflow.com/comment/82975045

http://stackoverflow.com/comment/82894967
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/47962808
has text: Please, provide text version of terminal output, can't figure out, what is displayed on it

http://stackoverflow.com/comment/82855628
score: 0
type: Comment
type: QuestionComment
has text: It depends on whether ``pip`` is installed in your virtual environment - if it's missing, ``pip`` will fall back to the default one. Can you post the results of ``which python``, ``which pip``, and ``ls $(dirname $(which python))``?
comment on: http://stackoverflow.com/q/47942901

http://stackoverflow.com/q/47874864
tagged with: kivy
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: Python KIVY: how to implement recursive DropDown or recursive Spinner?
tagged with: recursion
has comment: http://stackoverflow.com/comment/82715924
score: 1
type: Question
downvote count: 0
tagged with: dropdown
has body: I am programming an application that allows a teacher to create a school year, to add several classes in a year, in which he can add several students. There are 3 types of objects: School_Year, Class, Student. All of these objects are represented by a directory in the tree that contains children objects, apart from Student. Tree architecture: School_Year / Class / Student Here is a representation of what I am trying to do: 1. There is a home menu that displays all years and allows to add/delete years. When you click on a year, it shows you all the classes of this year: 2. Imagine you click 2010-2011 year. It creates a recursive menu, and the 2012-2013 is pushed towards the bottom: 3. Imagine you click "class A" , it shows you the list of the students of this clas with another recursive menu, and the "class B" is pushed to bottom: I can't do that because I'm too newbie at kivy but I tried the first rank of recursivety: .py: # coding: utf-8 from kivy.app import App from kivy.lang import Builder from kivy.clock import Clock from kivy.uix.screenmanager import ScreenManager, Screen from kivy.uix.button import Button from kivy.uix.spinner import Spinner from functools import partial class GUI(ScreenManager): def __init__(self, **kwargs): super(GUI, self).__init__(**kwargs) class Home(Screen): def __init__(self, **kwargs): super(Home, self).__init__(**kwargs) # add a school year (parent "folder") on the home menu def add_year(self, grid, classname): # button of the year """ The values of this spinner are temporary, I don't know how to insert other child spinners inside I think I must replace the spinner by a Drop Down but I can't do it, I need some help""" left = Spinner(values = ["?", "??", "???"], text=classname.text, size = (32, 32), size_hint = (1, None)) # the delete button of this year right = Button(background_color = (1,0,0,1), text="X", size = (32, 32), size_hint = (None, None)) # equivalent of: on_press = self.del_year(grid, left, right) without NoneType error ri…
favorite count: 0
has comment: http://stackoverflow.com/comment/82715113

http://stackoverflow.com/q/47877604
has body: EDIT: here is the current issue: Traceback (most recent call last): File "figure.py", line 32, in &lt;module&gt; import Python2 File "C:\scripts\python2.py", line 12, in &lt;module&gt; shp = shape.Python1(self.size, self.length, self.breadth,self.height) NameError: name 'self' is not defined Though this question has been asked many times it hasn't solved my issue. I have two python files python1.py and python2.py In python1.py: def add(self,a): ..... def sub(self,b): .... In python2.py: import python1 def square (self,c): python1.add(a) When I try to run this, in python2.py I get AttributeError: 'module' object has no attribute 'add'. what should I do to resolve this issue?
has comment: http://stackoverflow.com/comment/82721219
favorite count: 0
has title: NameError: name 'self' is not defined - module import
type: UnansweredQuestion
tagged with: python
upvote count: 1
downvote count: 1
type: Question
score: 0
has answer: http://stackoverflow.com/a/47877695
answer count: 1

web-crawler
tags question: http://stackoverflow.com/q/47894052
tags question: http://stackoverflow.com/q/47880548
tag name: web-crawler
tags question: http://stackoverflow.com/q/47961641
tags question: http://stackoverflow.com/q/47858886
tags question: http://stackoverflow.com/q/47962083
type: Tag
tags question: http://stackoverflow.com/q/47862285
tags question: http://stackoverflow.com/q/47967639
tags question: http://stackoverflow.com/q/47880624
tags question: http://stackoverflow.com/q/47881249
tags question: http://stackoverflow.com/q/48006078

http://stackoverflow.com/comment/82898955
type: Comment
type: QuestionComment
has text: I made it clear already :) Thanks.
comment on: http://stackoverflow.com/q/47964637
score: 0

http://stackoverflow.com/q/47945648
has comment: http://stackoverflow.com/comment/82861032
tagged with: python
accepted answer: http://stackoverflow.com/a/47945873
score: 0
type: Question
has comment: http://stackoverflow.com/comment/82861068
has title: Trying to connect to twisted Server using sample code echoserver.py from twisted book. Getting error can't listen to multiple address
type: AnsweredQuestion
tagged with: network-programming
has body: Using the sample code from twisted book: echoserver.py 2-1. I keep getting this error line 980, in startListening raise CannotListenError(self.interface, self.port, le) twisted.internet.error.CannotListenError: Couldn't listen on any:8000: [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted. Code: from twisted.internet import protocol, reactor class Echo(protocol.Protocol): def dataReceived(self, data): self.transport.write(data) class EchoFactory(protocol.Factory): def buildProtocol(self, addr): return Echo() reactor.listenTCP(8000, EchoFactory()) reactor.run() Any ideas on how to fix the error or why my computer is thinking that there is more than one usage on this socket address? Totally new to networking.
has answer: http://stackoverflow.com/a/47945873
tagged with: twisted
answer count: 1

http://stackoverflow.com/comment/82682375
comment on: http://stackoverflow.com/q/47857973
type: QuestionComment
type: Comment
score: 1
has text: Generating all pairs from a set of elements has a lower-bound time complexity of O(n^2) where n is the number of elements. This lower-bound means we can never be quicker than O(n^2).

http://stackoverflow.com/comment/82879752
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47955125
has text: @ubadub When I call the `vote()` command, it always goes through the else part. Even after calling the `start()`

http://stackoverflow.com/comment/82880982
comment on: http://stackoverflow.com/q/47955785
has text: not sure, but maybe naming your venv something other than tensorflow will help..?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47932178
answer count: 1
downvote count: 0
favorite count: 0
tagged with: tf-idf
has title: TfIDf Vectorizer weights
tagged with: data-analysis
type: UnansweredQuestion
tagged with: python
tagged with: nlp
score: 1
upvote count: 1
type: Question
has body: Hi I have a lemmatized text in the format as shown by lemma. I want to get TfIdf score for each word this is the function that I wrote: import numpy as np import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer lemma=["'Ah", 'yes', u'say', 'softly', 'Harry', 'Potter', 'Our', 'new', 'celebrity', 'You', 'learn', 'subtle', 'science', 'exact', 'art', 'potion-making', u'begin', 'He', u'speak', 'barely', 'whisper', 'caught', 'every', 'word', 'like', 'Professor', 'McGonagall', 'Snape', 'gift', u'keep', 'class', 'silent', 'without', 'effort', 'As', 'little', 'foolish', 'wand-waving', 'many', 'hardly', 'believe', 'magic', 'I', 'dont', 'expect', 'really', 'understand', 'beauty'] def Tfidf_Vectorize(lemmas_name): vect = TfidfVectorizer(stop_words='english',ngram_range=(1,2)) vect_transform = vect.fit_transform(lemmas_name) # First approach of creating a dataframe of weight &amp; feature names vect_score = np.asarray(vect_transform.mean(axis=0)).ravel().tolist() vect_array = pd.DataFrame({'term': vect.get_feature_names(), 'weight': vect_score}) vect_array.sort_values(by='weight',ascending=False,inplace=True) # Second approach of getting the feature names vect_fn = np.array(vect.get_feature_names()) sorted_tfidf_index = vect_transform.max(0).toarray()[0].argsort() print('Largest Tfidf:\n{}\n'.format(vect_fn[sorted_tfidf_index[:-11:-1]])) return vect_array tf_dataframe=Tfidf_Vectorize(lemma) print(tf_dataframe.iloc[:5,:]) The output I am getting by: print('Largest Tfidf:\n{}\n'.format(vect_fn[sorted_tfidf_index[:-11:-1]])) is Largest Tfidf: [u'yes' u'fools' u'fury' u'gale' u'ghosts' u'gift' u'glory' u'glow' u'good' u'granger'] The result of tf_dataframe term weight 261 snape 0.027875 238 say 0.022648 211 potter 0.013937 181 mind 0.010453 123 harry 0.010453 60 dark 0.006969 75 dumbledore 0.006969 311 voice 0.005226 125 head 0.005226 231 ron 0.005226 Shouldn't both approaches lead to the same result of top features? I just want to calculate the tfidf scores …
tagged with: nltk
has answer: http://stackoverflow.com/a/47932469

http://stackoverflow.com/q/47936065
upvote count: 3
accepted answer: http://stackoverflow.com/a/47936124
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47936124
tagged with: python
type: AnsweredQuestion
score: 3
downvote count: 0
type: Question
has title: Why this print changing the following result?
has body: Sample code: p = map(some_logic) print(list(p)) # HERE p = filter(some_logic, p) print(list(p)) Using the above code, p generated by first line is always the same. But by adding the line commented HERE, the last print gives [] as output. Without the HERE line, the last print gives correct content of p. What's causing this?

http://stackoverflow.com/comment/82882721
type: Comment
has text: Yes, I didn't put the entire code in my previous comment because it would be too long, but I did enter each of my 50 columns just before. Is there a way to refer to the number of the column in my table ? Like for the list in python for instance: mytable[3] to get the third column
comment on: http://stackoverflow.com/a/47956442
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82756606
type: Comment
comment on: http://stackoverflow.com/q/47894748
score: 0
type: QuestionComment
has text: I am not at all a maya expert, but for what I have read on the web, the image plane is actually _calculated_, and not extracted from the image as if the image would already have the image plane object. Just willing to help. Am I getting it wrong?

http://stackoverflow.com/comment/82718152
comment on: http://stackoverflow.com/a/47874834
type: AnswerComment
score: 1
type: Comment
has text: Does it work if you try to run it like a module? `python -m some_folder_name` with a file named `__main__.py`

http://stackoverflow.com/comment/82722570
score: 0
has text: Can you actually print out `final_mage.shape, final_image.dtype`
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47878223

data-analysis
tags question: http://stackoverflow.com/q/47935872
tags question: http://stackoverflow.com/q/48010317
tags question: http://stackoverflow.com/q/47993763
type: Tag
tags question: http://stackoverflow.com/q/47858935
tags question: http://stackoverflow.com/q/47883420
tags question: http://stackoverflow.com/q/47973512
tags question: http://stackoverflow.com/q/47982568
tags question: http://stackoverflow.com/q/47932178
tags question: http://stackoverflow.com/q/47967661
tag name: data-analysis

http://stackoverflow.com/comment/129093292
type: Comment
score: 1
type: AnswerComment
has text: well , when you use env python this it's not so good idea !!!
comment on: http://stackoverflow.com/a/57670590

http://stackoverflow.com/comment/82936798
score: 0
comment on: http://stackoverflow.com/q/47983907
has text: I cannot reproduce in Python 3. Can you show the full error?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82984042
score: 0
type: AnswerComment
has text: Another way to have a list of dataframe is using `l = list(df.groupby('The_evil_column'))` to access to the `i` `df` write `l[i][1]`
comment on: http://stackoverflow.com/a/48007059
type: Comment

http://stackoverflow.com/comment/82881640
type: AnswerComment
score: 0
type: Comment
has text: Thanks for your help and explanation! :)
comment on: http://stackoverflow.com/a/47955460

http://stackoverflow.com/a/72888811
answers question: http://stackoverflow.com/q/47889693
type: Answer
has body: Esc and 'l' will remove the numbering from current cell. Esc and 'L' will remove the numbering from all the cells of notebook.
score: 1
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/82767772
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47900032
has text: Is there a better way of doing this, as I get an error for my real dataset as `error: invalid group reference 1`

http://stackoverflow.com/q/48013544
has comment: http://stackoverflow.com/comment/82996552
has comment: http://stackoverflow.com/comment/82998839
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82996966
tagged with: flask
favorite count: 0
has body: Making a simple login/register app on flask and I have encountered this issue? What am I doing wrong here? The register Form works perfectly. The login section doesn't work How can I fix it. I have to do this in order to replace flask-mysqldb with the mysql.connector for python I get this error on login submit: mysql.connector.errors.InternalError mysql.connector.errors.InternalError: Unread result found creating a new connection to the dB for the login, gives me this error builtins.TypeError TypeError: '>' not supported between instances of 'NoneType' and 'int' app.py is: from flask import Flask, render_template, flash, redirect, url_for, session, request, logging from wtforms import Form, StringField, TextAreaField, PasswordField, validators from passlib.hash import sha256_crypt import mysql.connector app = Flask(__name__) app.secret_key='secretkey' #Config MySQL cnx = mysql.connector.connect(user='jay', password='jay', host='127.0.0.1', database='usertable') #cnx.close() @app.route('/') def index(): return render_template('home.html') class RegisterForm(Form): name = StringField('Name', [validators.Length(min=1, max=50)]) username = StringField('Username', [validators.Length(min=4, max=25)]) email = StringField('Email', [validators.Length(min=6, max=50)]) password = PasswordField('Password', [ validators.DataRequired(), validators.EqualTo('confirm', message='Passwords do not match') ]) confirm = PasswordField('Confirm Password') @app.route('/register', methods=['GET','POST']) def register(): form = RegisterForm(request.form) if request.method == 'POST' and form.validate(): name = form.name.data email = form.email.data username = form.username.data password = sha256_crypt.encrypt(str(form.password.data)) #connect to db #create Cursor cur = cnx.cursor() cur.execute("INSERT INTO users(name, email, username, password) VALUES(%s, %s, %s, %s)", (name, email, username, password)) #commit 2 DB cnx.commit() #close connection cur.close() cnx.close() flash('You are now regi…
has comment: http://stackoverflow.com/comment/82996734
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82997352
has comment: http://stackoverflow.com/comment/82996581
has comment: http://stackoverflow.com/comment/82998671
tagged with: python
has answer: http://stackoverflow.com/a/48037841
score: 2
has title: Flask Mysql Connector issue
has comment: http://stackoverflow.com/comment/82998662
has comment: http://stackoverflow.com/comment/82997246
tagged with: mysql
type: Question
has comment: http://stackoverflow.com/comment/82998646
has comment: http://stackoverflow.com/comment/82997258

http://stackoverflow.com/comment/82887678
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47959076
score: 0
has text: It is a Linux x86 64. Python did have the Tkinter installed but it was not configured with my system. I am on a shared server. So in answer to your question about compiling it from source code, I am configuring it from where I installed it: ~/home2/bishopk2/python27/Python-2.7.14/./configure hopefully that clarifies things a little. Thanks for your response thus far.

http://stackoverflow.com/q/47997230
tagged with: pyqt5
upvote count: 1
downvote count: 1
type: Question
has title: How do I animate a position change with QPropertyAnimation while using a layout method?
has comment: http://stackoverflow.com/comment/82964225
score: 0
has comment: http://stackoverflow.com/comment/82962927
tagged with: pyqt
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: qt
tagged with: qpropertyanimation
answer count: 0
has body: So basically what I am trying to do is animate a widget moving, the start point being (0,0) or somewhere on the side of the parent window, and then the end point being where the widget is actually positioned on the parent window. But I am using a layout method, QGridLayout to be specific, so i cannot just change the geometry like you normally would from my understanding. Here is what a tried so far. print ("POS: ", self.Play_label.pos()) geometry_play = self.Play_label.geometry() print ("mapp: ", self.Play_label.mapToGlobal(QPoint(0,0))) print ("play geo: ", geometry_play) self.animation = QPropertyAnimation(self.Play_label, b"geometry") self.animation.setDuration(3000) self.animation.setStartValue(QRect(0,0,150,150)) self.animation.setEndValue(geometry_play) #print ("Value: ", self.animation.currentValue()) #self.animation.valueChanged.connect(self.Play_label.changeImageSize) #self.animation.setTargetObject(self.Play_label) self.animation.start() But the label that I created always has its x and y coordinates being (0,0), is this because I am using a layout method? Even if I attempt to print out the position using the .pos() method it always returns (0,0). Is there any simple way to animate this change? I understand I can change the 2nd parameter of the animation to something other than geometry but i cannot figure out what i would change it to in my case. Please any helps would be much appreciated been trying to figure this out for days now.

http://stackoverflow.com/q/47878705
type: Question
accepted answer: http://stackoverflow.com/a/47878793
has comment: http://stackoverflow.com/comment/82723602
has title: Loose yScroll when move Listbox Class to Toplevel from ROOT - in Tkinter
has comment: http://stackoverflow.com/comment/82723478
tagged with: listbox
answer count: 1
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/82723547
type: AnsweredQuestion
tagged with: tkinter
has answer: http://stackoverflow.com/a/47878793
has body: This works fine when the listbox is root, however when I move it to a Toplevel window the scrollbar no longer appears. Here is the specific code (Note the aassign query has not been applied) class App: def __init__(self): self.listb=Toplevel() self.listb.transient(root) self.listb.title=('DB View') self.vsb = Scrollbar(orient="vertical", command=self.OnVsb) self.listNum = Listbox(self.listb, yscrollcommand=self.vsb.set) self.listRoster = Listbox(self.listb, yscrollcommand=self.vsb.set) self.vsb.pack(side="right",fill="y") self.listNum.pack(side="left",fill="x", expand=True) self.listRoster.pack(side="left",fill="x", expand=True) self.listNum.bind("&lt;MouseWheel&gt;", self.OnMouseWheel) self.listRoster.bind("&lt;MouseWheel&gt;", self.OnMouseWheel) dbi = mdb.connect("localhost", port=3306, user="user", passwd="access", db="interactive_db") cursor = dbi.cursor() cursor.execute("""SELECT num FROM active_roster""") rows = cursor.fetchall() cursor.execute("""SELECT firstname, surname, assign FROM active_roster""") staff =cursor.fetchall() cursor.execute("""SELECT assign FROM active_assign""") aassign = cursor.fetchall() dbi.close() print(rows) print(aassign) print (staff) for results in rows: self.listNum.insert("end", results) for results2 in staff: self.listRoster.insert("end", results2) self.listb.mainloop() def OnVsb(self, *args): self.listNum.yview(*args) self.listRoster.yview(*args) def OnMouseWheel(self, event): self.listNum.yview("scroll", event.delta,"units") self.listRoster.yview("scroll",event.delta,"units") return "break" root = Tk() root.title("Main") root.geometry("900x600") app=App() listb = MultipleScrollingListbox() #PRE-DUAL COLUMN SYNTAX PRE-CLASS DEF numLabel=Label(root, text="Num #") numLabel.grid(row=0,column=0) assLabel=Label(root, text="Assignment") assLabel.grid(row=0,column=2) num_input=StringVar() num_input=Entry(root,textvariable=num_input) num_input.grid(row=0,column=1) ass_input=StringVar() ass_input=Entry(root,textvariable=ass_input) ass_in…

http://stackoverflow.com/q/47932922
has comment: http://stackoverflow.com/comment/82835136
linked to: http://stackoverflow.com/q/44487786
has body: Can someone explain why I obtain such strange and different times during array allocation, it turns out that it 25x times faster to allocate slightly bigger array and slice it, than to allocate the array of needed size: %timeit arr = np.zeros((360, 360)) 207 µs ± 4.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) %%timeit arr = np.zeros((362, 362)) arr = arr[:360] 8.4 µs ± 651 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) Is there something general behind that or it is some Windows related issue? While this situation is specific near (360, 360) size on my computer, I do not know if it can arise at other places. EDIT: While this question is marked as a duplicate, the answer to that question does not not fully explain the problem: %timeit -n10 -r10 arr = np.zeros((361, 361)) 243 µs ± 56.6 µs per loop (mean ± std. dev. of 10 runs, 10 loops each) %timeit -n10 -r10 arr = np.zeros((362, 362)) 6.82 µs ± 539 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) With zeros there is 25-35x regression, but with empty the story is in opposite direction with 2-5x: %timeit -n10 -r10 arr = np.empty((361, 361)) 2.49 µs ± 1.02 µs per loop (mean ± std. dev. of 10 runs, 10 loops each) %timeit -n10 -r10 arr = np.empty((362, 362)) 11.9 µs ± 1.58 µs per loop (mean ± std. dev. of 10 runs, 10 loops each) Windows 7 Python 3.6.3 numpy 1.13.3
has comment: http://stackoverflow.com/comment/82835466
downvote count: 0
has comment: http://stackoverflow.com/comment/82835401
duplicate of: http://stackoverflow.com/q/44487786
has title: Strange behavior during array allocation in numpy
favorite count: 0
tagged with: memory-management
has comment: http://stackoverflow.com/comment/82835354
type: UnansweredQuestion
tagged with: windows
tagged with: python
has comment: http://stackoverflow.com/comment/82835014
answer count: 0
has comment: http://stackoverflow.com/comment/82835263
has comment: http://stackoverflow.com/comment/82835215
has comment: http://stackoverflow.com/comment/82835705
type: Question
tagged with: numpy
score: 5
upvote count: 5
tagged with: arrays

http://stackoverflow.com/comment/82754462
score: 0
comment on: http://stackoverflow.com/q/47880164
type: Comment
type: QuestionComment
has text: could be a real chrome driver issue then. I'd get verbose chrome log (https://sites.google.com/a/chromium.org/chromedriver/logging) and submit issue to chrome developers (https://bugs.chromium.org/p/chromedriver/issues/list). They may guide you on what to check/look for

http://stackoverflow.com/q/48014006
possible better answer: http://stackoverflow.com/a/48014074
has comment: http://stackoverflow.com/comment/82997920
has comment: http://stackoverflow.com/comment/82997031
downvote count: 2
linked to: http://stackoverflow.com/q/26337003
upvote count: 1
has comment: http://stackoverflow.com/comment/82997329
has comment: http://stackoverflow.com/comment/82997003
type: Question
accepted answer: http://stackoverflow.com/a/48014072
score: -1
has body: I'm having difficulty understand this logic: &gt;&gt;&gt; text = 'ay_118724981.jpg' &gt;&gt;&gt; 'jpg' in text True &gt;&gt;&gt; 'png' in text False &gt;&gt;&gt; if 'png' not in text or 'jpg' not in text or 'jpeg' not in text: ... print('True') ... else: ... print('False') ... True &gt;&gt;&gt; I'm confused 'coz the if statement should result in False since 'jpg' is in the text. It should give me True only when none of them is in the text. Correct ?
answer count: 2
has comment: http://stackoverflow.com/comment/82996893
favorite count: 0
has comment: http://stackoverflow.com/comment/82996936
has answer: http://stackoverflow.com/a/48014072
has title: Conditions in Python
has comment: http://stackoverflow.com/comment/82996891
has answer: http://stackoverflow.com/a/48014074
has comment: http://stackoverflow.com/comment/82996917
tagged with: python
has comment: http://stackoverflow.com/comment/82996931
has comment: http://stackoverflow.com/comment/82996953
has comment: http://stackoverflow.com/comment/82996987
type: AnsweredQuestion

http://stackoverflow.com/comment/82988526
comment on: http://stackoverflow.com/a/48009997
type: Comment
score: 0
type: AnswerComment
has text: @user9115052 Still not right, `n-1 if n % 2 == 1 else n - 1`.

http://stackoverflow.com/comment/82987949
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48009764
has text: `users.User` has `abstract = True`?

http://stackoverflow.com/comment/82870041
type: QuestionComment
has text: @kshikama, sorry, but I left some code out... I am editing and adding it so you can better understand.
score: 0
comment on: http://stackoverflow.com/q/47950107
type: Comment

http://stackoverflow.com/a/47984501
score: 3
has body: I don't think that the example you show with PythonWin is easily reproducible in VS Code. The quick start guide of win32com itself (cited below) says, its only possible with a COM browser or the documentation of the product (Word in this case). The latter one is unlikely, so PythonWin is probably using a COM browser to find the properties. And because PythonWin and win32com come in the same package, its not that unlikely that PythonWin has a COM browser built in. How do I know which methods and properties are available? Good question. This is hard! You need to use the documentation with the products, or possibly a COM browser. Note however that COM browsers typically rely on these objects registering themselves in certain ways, and many objects to not do this. You are just expected to know. If you wanted the same functionality from the VS Code plugin a COM browser would have to be implemented into Jedi (IntelliSense of the VS Code plugin). Edit: I found this suggestion, on how a auto-complete, that can find these hidden attributes, could be done: These wrappers do various things that make static analysis difficult, unless we were to special case them. The general solution for such cases is to run to a breakpoint and work in the live runtime state. The auto-completer should then include the complete list of symbols because it inspects the runtime. The conversation is from an mailing list of the python IDE wingwide. Here you can see, that they implemented the above mentioned approach:
has comment: http://stackoverflow.com/comment/82969679
has comment: http://stackoverflow.com/comment/82951387
downvote count: 0
has comment: http://stackoverflow.com/comment/82951930
answers question: http://stackoverflow.com/q/47900257
type: Answer
has comment: http://stackoverflow.com/comment/82949995
upvote count: 3
has comment: http://stackoverflow.com/comment/82947189
has comment: http://stackoverflow.com/comment/83014417

http://stackoverflow.com/q/47939120
tagged with: github-api
has body: Trying to run my chatbot on LEX engine from python according to this link https://github.com/boto/boto3#quick-start . Being a starter in Github and amazon Lex i don't understand how to set these up : [default] aws_access_key_id = YOUR_KEY aws_secret_access_key = YOUR_SECRET It says to create this in ~/.aws/credentials but I'm not sure what that means. I have already set the virtual environment and ran pip install boto3 again my question is how to set that step i mentioned above and where.
has title: How can i set my credentials for `aws` in boto?
answer count: 1
has answer: http://stackoverflow.com/a/47939576
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/82847541
tagged with: python
has comment: http://stackoverflow.com/comment/82848577
has comment: http://stackoverflow.com/comment/82847703
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82847917
score: 1
accepted answer: http://stackoverflow.com/a/47939576
tagged with: amazon-lex
type: Question

http://stackoverflow.com/q/47875527
linked to: http://stackoverflow.com/q/35353934
tagged with: python
has title: How python manager.dict() locking works:
type: AnsweredQuestion
tagged with: multiprocessing-manager
accepted answer: http://stackoverflow.com/a/47875528
upvote count: 7
tagged with: multiprocessing
type: Question
tagged with: python-multiprocessing
has body: A managers.dict() allow to share a dictionary across process and perform thread-safe operation. In my case each a coordinator process create the shared dict with m elements and n worker processes read and write to/from a single dict key. Do managers.dict() have one single lock for the dict or m locks, one for every key in it? Is there an alternative way to share m elements to n workers, other than a shared dict, when the workers do not have to communicate with each other? Related python-manager-dict-is-very-slow-compared-to-regular-dict
tagged with: python-2.7
answer count: 1
downvote count: 0
score: 7
has answer: http://stackoverflow.com/a/47875528
favorite count: 0

http://stackoverflow.com/a/47872490
has comment: http://stackoverflow.com/comment/82753978
score: 1
has comment: http://stackoverflow.com/comment/82754322
answers question: http://stackoverflow.com/q/47872271
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82754023
has comment: http://stackoverflow.com/comment/82754370
has body: Compare adjacent rows with ne + shift, obtain a mask, and use this to index into df to get the required rows index into df.columns to get the required columns which change c = df.columns.intersection( ['nombre_empresa', 'perfil_cobranza', 'cuenta_bancaria'] ) i = df[c].ne(df[c].shift()) j = i.sum(1).eq(1) df = df.loc[j, ['usuario_id', 'usuario_web']] df.insert(1, 'cambio', c[i[j].values.argmax(1)]) df usuario_id cambio usuario_web 1 500199 cuenta_bancaria 3321 2 500199 perfil_cobranza 5541 3 500199 nombre_empresa 5246
accepted answer of: http://stackoverflow.com/q/47872271
type: Answer
upvote count: 1

http://stackoverflow.com/q/47965783
has comment: http://stackoverflow.com/comment/82901306
type: Question
has comment: http://stackoverflow.com/comment/82908373
tagged with: python
upvote count: 2
tagged with: machine-learning
answer count: 1
has answer: http://stackoverflow.com/a/47969543
has title: numpy - shapes error when trying to compute cost function
tagged with: numpy
score: 2
type: AnsweredQuestion
has body: I'm taking the corsera course on machine learning. I'm trying to convert the first weeks cost function into python. import numpy as np def computeCost(X, y, theta): inner = np.power(((X.dot(theta)) - y), 2) return np.sum(inner) / (2 * len(X)) It works in the beginning. However, when I start plotting it into a 3D space, the cost doesn't seem to work anymore. I run this print(computeCost(X, y, [theta0_vals[0], theta1_vals[0]])) I get "30109.7923098" However, I should get "328.0929" I tried this: inner = np.power(((X * (theta.T)) - y), 2) return np.sum(inner) / (2 * len(X)) I get a dimension error. I tried this: m = len(y) #number of training examples #X = np.array([np.ones(m), X]) #I did this beofre calling the function X = X.transpose() theta = theta.transpose() c = np.dot(X, theta) #Matrix multiplication X*theta c = c.transpose() - y J = np.sum(c**2)/(2*m) #Calculating cost return J I get the error: ValueError: shapes (2,97) and (1,2) not aligned: 97 (dim 1) != 1 (dim 0) Let me know if you need more information.
downvote count: 0
accepted answer: http://stackoverflow.com/a/47969543
favorite count: 0

http://stackoverflow.com/a/48010668
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82990375
answers question: http://stackoverflow.com/q/48010571
has body: Using Pandas, read file without headers. Add Columns names as a list. Save file to the csv. import pandas as pd df = pd.read_csv("file.csv", header=None, index_col=None) df.columns = ['Cliente', 'Fecha', 'Data', 'Numbers', 'Info', 'Numbers2', 'Analisys'] df.to_csv("file.csv", index=False)
score: 0
has comment: http://stackoverflow.com/comment/82990179
type: Answer
has comment: http://stackoverflow.com/comment/82990407

http://stackoverflow.com/q/47981500
answer count: 1
has comment: http://stackoverflow.com/comment/82932015
has body: I am using a mac with python 2.7 and pyodbc to query data from Microsoft Sql server. There is a timestamp column which shows up as datetime64[ns] in my dataframe Structure of the program - SQLCommand = (" SELECT Col1, Col2, Col3 from xyztable ") DF = pd.read_sql(SQLCommand,cnxn) # extracting Day and month by converting to dt DF['TS']=DF['TS'].dt.strftime('%d%m%') # Create labels from Categories (string type data column in SQL table), replacing each category DF['Flag']= DF['CODE'] DF.dtypes TS datetime64[ns] TIWOR object CODES object T-enc int8 TS object TS_HHMM object TS_DD int64 TS_DDMM int64 Flag object dtype: object # I am able to replace all categories but it fails at this step as u\2013 appears in the middle of string DF['Flag'].unique() array([0, 1, nan, u'Dev \u2013 Env'], dtype=object) # All attempts to find and replace are not working, some records have 'nan' values and DF.dropna does not work. Attempts to fix Various stack overflow articles have been referred but it did not help. exported Sql query output into a CSV file and loaded into Dataframe, still same issue . DF.to_csv('~/SQLoutput.csv', sep='\t', encoding='utf-8') exported sql query output into an excel file and loaded into dataframe, still same issue DF=pd.read_excel('/Users/User1/SQLoutput.xlsx',sheet_name=0,encoding='utf-8') added # -*- coding:utf-8 -*- at beginning of code, did not help Verified pyodbc settings, no problem. tsql -S sqlservername -U Username -P Password
type: UnansweredQuestion
tagged with: python
tagged with: pyodbc
has title: pandas pyodbc unicode issues u\2013
tagged with: python-unicode
type: Question
has answer: http://stackoverflow.com/a/47981783
score: 0
tagged with: pandas

http://stackoverflow.com/a/48319786
answers question: http://stackoverflow.com/q/47975499
has body: The easiest way is via Choregraphe, you can make Nao recognize objects in a few minutes. (you can download choregraphe from here)
score: 0
type: Answer

http://stackoverflow.com/comment/82708800
has text: Note switching the green and blue numbers gives a decent-looking red-blue colormap as well.
type: AnswerComment
comment on: http://stackoverflow.com/a/47871697
score: 0
type: Comment

http://stackoverflow.com/a/47987954
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/82964575
downvote count: 0
answers question: http://stackoverflow.com/q/47982261
has body: Your immediate problem is how selection() works -- it was comparing numbers to strings and have the code necessary to execute any of the subprograms. I've reworked it below to get the behavior you desire. I've also made other changes and simplifications: from tkinter import * from turtle import Pen, Screen import turtlegraphics def treeF(): order = int(orderEntry.get()) length = float(lengthEntry.get()) turtlegraphics.tree(order, length, pen) def dandelionF(): order = int(orderEntry.get()) length = float(lengthEntry.get()) turtlegraphics.tree4(order, length, pen) def flakeF(): order = int(orderEntry.get()) length = float(lengthEntry.get()) turtlegraphics.flake(order, length, pen) def gasketF(): order = int(orderEntry.get()) length = float(lengthEntry.get()) turtlegraphics.gasket(order, length, pen) def kevinF(): order = int(orderEntry.get()) length = float(lengthEntry.get()) turtlegraphics.k(order, length, pen) fractals = [('tree', treeF), ('dandelion', dandelionF), ('flake', flakeF), ('gasket', gasketF), ('kevin', kevinF)] # make a screen and a pen screen = Screen() screen.bgcolor('white') pen = Pen() pen.speed('fastest') pen.color('blue') pen.width(3) # set up the window root = Tk() root.title('turtle shapes') root.geometry('600x400+100+100') # make the interface turtleLabel = Label(root, text='Turtle Fractals Generator') turtleLabel.grid(row=0, column=1, columnspan=2) # order widgets orderLabel = Label(root, text='Order') orderLabel.grid(row=1, column=0) orderEntry = Entry(root) orderEntry.grid(row=1, column=1, columnspan=2) # length widgets lengthLabel = Label(root, text='Length') lengthLabel.grid(row=2, column=0) lengthEntry = Entry(root) lengthEntry.grid(row=2, column=1, columnspan=2) # button widgets def clearF(): # Clear the entries orderEntry.delete(0, 'end') lengthEntry.delete(0, 'end') clearButton = Button(root, text='Clear', command=clearF) clearButton.grid(row=3, column=1) # list def selection(): selections = nameList.curselection() if selections: selec…
type: Answer

http://stackoverflow.com/a/48003342
answers question: http://stackoverflow.com/q/48003241
downvote count: 0
type: Answer
upvote count: 1
score: 1
has body: You can use the raw-string r'..' construct to do that, also would be nice to use the file-open constructs within the try catch blocks and close the open file descriptor once the write is complete. try: str = r'some words\n' with open('newfile', 'a') as fd: fd.write(str) fd.close() except IOError as e: print('unable to open file newfile in append mode')

http://stackoverflow.com/comment/82685864
type: Comment
has text: @alfasin Wasnt there when I commented
comment on: http://stackoverflow.com/a/47860495
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82874391
score: 0
has text: can you please give your full file code or at least **import** part.
comment on: http://stackoverflow.com/q/47952516
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82825404
type: AnswerComment
has text: Very nice, thanks a lot for your answer! One thing I don't get is why you define functions instead of if/else rather than defining a function with if/else?
type: Comment
comment on: http://stackoverflow.com/a/47927605
score: 0

http://stackoverflow.com/q/47940731
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/58222890
has title: How do I get more decimal in clf.predict_proba(X_test)?
has comment: http://stackoverflow.com/comment/82850860
answer count: 1
downvote count: 0
tagged with: scikit-learn
has body: I have a pandas dataframe, for a binary classification case (category A, and category B). To get X_train, X_test, y_train, y_test I do 70:30 split like this: from sklearn.model_selection import train_test_split target = pd.DataFrame(data['good']) features = data.drop('good', axis=1) X_train, X_test, y_train, y_test = train_test_split(features, target, test_size = 0.3, random_state = 0) Then I did RandomForest classifier, with that this code from sklearn.ensemble import RandomForestClassifier clf = RandomForestClassifier(n_jobs=2, random_state=0) model = clf.fit(X_train, y_train) As usual you can do get the prediction by doing clf.predict(X_test). It give numpy.ndarray object like this array(['0', '0', '1', '0', '0', '1', '0', '1', '1', '1'], dtype=object) Then, I want to calculate prediction probabiblity by clf.predict_proba(X_test) and the result is array([[ 0.7 , 0.3 ], [ 0.8 , 0.2 ], [ 0.4 , 0.6 ], [ 0.8 , 0.2 ], [ 0.5 , 0.5 ], [ 0.1 , 0.9 ], [ 0.5 , 0.5 ], [ 0.3 , 0.7 ], [ 0.3 , 0.7 ], [ 0.5 , 0.5 ]]) I want to get more decimal in clf.predict_proba(X_test) output. (I am expected 3 decimals) For example, array([[ 0.712 , 0.288 ], [ 0.845 , 0.155 ... etc It would be better if the answer also convert and merge clf.predict(X_test) and clf.predict_proba(X_test) to pandas dataframe as well, because I would continue to calculate GINI index. Thanks in advance
favorite count: 0
accepted answer: http://stackoverflow.com/a/58222890
tagged with: python
has comment: http://stackoverflow.com/comment/82854109
type: AnsweredQuestion
score: 3
upvote count: 3
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/82850737

http://stackoverflow.com/comment/82897823
comment on: http://stackoverflow.com/a/47961630
has text: @bluesummers build_vocab and train are part of Word2Vec. You'll have to figure out how to turn `model` in the example above from a `KeyedVectors` to a `Word2Vec` instance.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47962314
answer count: 1
favorite count: 0
tagged with: telegram-bot
tagged with: python-telegram-bot
tagged with: telegram
has comment: http://stackoverflow.com/comment/137168086
linked to: http://stackoverflow.com/q/64196443
tagged with: python
has body: My bot is admin in a channel and I want to read channel's recent actions(like who joined the channel and etc) using python-telegram-bot. How can I achive this?
type: AnsweredQuestion
score: 1
type: Question
upvote count: 3
downvote count: 2
has answer: http://stackoverflow.com/a/47962389
accepted answer: http://stackoverflow.com/a/47962389
has title: Read channel recent actions with telegram bot

http://stackoverflow.com/q/47995188
has title: How to calculate mean and standard deviation given a PySpark DataFrame?
type: AnsweredQuestion
score: 30
has answer: http://stackoverflow.com/a/68217593
has comment: http://stackoverflow.com/comment/82958964
linked to: http://stackoverflow.com/q/49481363
has answer: http://stackoverflow.com/a/59653234
type: Question
has body: I have PySpark DataFrame (not pandas) called df that is quite large to use collect(). Therefore the below-given code is not efficient. It was working with a smaller amount of data, however now it fails. import numpy as np myList = df.collect() total = [] for product,nb in myList: for p2,score in nb: total.append(score) mean = np.mean(total) std = np.std(total) Is there any way to get mean and std as two variables by using pyspark.sql.functions or similar? from pyspark.sql.functions import mean as mean_, std as std_ I could use withColumn, however, this approach applies the calculations row by row, and it does not return a single variable. UPDATE: Sample content of df: +----------+------------------+ |product_PK| products| +----------+------------------+ | 680|[[691,1], [692,5]]| | 685|[[691,2], [692,2]]| | 684|[[691,1], [692,3]]| I should calculate mean and standard deviation of score values, e.g. the value 1 in [691,1] is one of scores.
has answer: http://stackoverflow.com/a/56509014
accepted answer: http://stackoverflow.com/a/47995478
tagged with: apache-spark-sql
tagged with: pyspark
downvote count: 0
possible better answer: http://stackoverflow.com/a/59653234
favorite count: 0
upvote count: 30
tagged with: apache-spark
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/47995478
has comment: http://stackoverflow.com/comment/82959216

http://stackoverflow.com/a/47913242
has comment: http://stackoverflow.com/comment/82794577
type: Answer
has body: children (similar to 'list_iterator') means many items so you get list not single item. It can be even list with one item or empty list but it is still a list. You have to use for loop to use get() with every item on the list or use index [0] to get only first item (if list is not empty) But in BeautifulSoup it gives all elements inside, not only tags (class Tag) but also text between tags (class NavigableString) which don't have .get() method. This code from bs4 import BeautifulSoup html = ''' ''' soup = BeautifulSoup(html, 'html.parser') mainview = soup.find(class_="mainview") for child in mainview.children: print(type(child)) gives <class 'bs4.element.NavigableString'> <class 'bs4.element.Tag'> <class 'bs4.element.NavigableString'> Better use next find() to find single element or find_all() to get list of elements. from bs4 import BeautifulSoup html = ''' ''' soup = BeautifulSoup(html, 'html.parser') mainview = soup.find(class_="mainview") child = mainview.find(class_="origianl") print(child.get('value')) EDIT: children gives only first level of subitems ( ), but not children in those subitems ( ) so you would have to use inner for loop to get which is in from bs4 import BeautifulSoup import bs4 html = ''' ''' soup = BeautifulSoup(html, 'html.parser') mainview = soup.find(class_="mainview") print('--- children ---') for child in mainview.children: print('> tag:', child.name) print('> type:', type(child)) #print('>content:', child) if isinstance(child, bs4.element.Tag): print('> value:', child.get('value')) print(' --- subchildren ---') for subchild in child.children: print(' > tag:', subchild.name) print(' > type:', type(subchild)) #print(' >content:', subchild) if isinstance(subchild, bs4.element.Tag): print(' > value:', subchild.get('value')) print(' -----------') print('-----------') Result: --- children --- > tag: None > type: <class 'bs4.element.NavigableString'> ----------- > tag: li > type: <class 'bs4.element.Tag'> > value: None --- subchildren --- > tag:…
has comment: http://stackoverflow.com/comment/82794510
has comment: http://stackoverflow.com/comment/82794690
accepted answer of: http://stackoverflow.com/q/47913140
score: 0
answers question: http://stackoverflow.com/q/47913140
type: AcceptedAnswer

http://stackoverflow.com/a/47981368
score: 2
accepted answer of: http://stackoverflow.com/q/47981067
downvote count: 0
type: AcceptedAnswer
upvote count: 2
has body: Setup - df1 Team 1 Team 2 Team1_Score Team2_Score Index 0 A B 25 56 1 B C 30 55 2 D E 35 75 df2 Team 1 Team 2 Team1_Avg Team2_Avg Index 0 A B 5 15 1 F G 25 10 2 B C 35 15 First, we'll need to sort the Team * columns, and accordingly sort the Team*_Score columns in the same way. We'll use argsort to do so. i = np.arange(len(df1))[:, None] j = np.argsort(df1'Team 1', 'Team 2', axis=1).values df1'Team 1', 'Team 2' = df1'Team 1', 'Team 2'.values[i, j] df1'Team1_Score', 'Team2_Score' = df1'Team1_Score', 'Team2_Score'.values[i, j] Now, repeat the same process for df2, with Team * and Team*_Avg. j = np.argsort(df2'Team 1', 'Team 2', axis=1).values df2'Team 1', 'Team 2' = df2'Team 1', 'Team 2'.values[i, j] df2'Team1_Avg', 'Team2_Avg' = df2'Team1_Avg', 'Team2_Avg'.values[i, j] Now, perform a left outer merge - df1.merge(df2, on=['Team 1', 'Team 2'], how='left') Team 1 Team 2 Team1_Score Team2_Score Team1_Avg Team2_Avg 0 A B 25 56 5 15 1 B C 30 55 35 15 2 D E 35 75
answers question: http://stackoverflow.com/q/47981067
type: Answer

http://stackoverflow.com/comment/83299209
has text: I had to edit the middleware a bit because it referenced my setting login_url in a weird way, but after that it works great! Thank you!
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47974092

http://stackoverflow.com/a/47996366
answers question: http://stackoverflow.com/q/47996285
type: Answer
has comment: http://stackoverflow.com/comment/82960799
score: 9
has body: First, you have to bind to the "&lt;Motion&gt;" event, which will fire every time the mouse moves. Then you need to save the previous mouse coordinates so that you have a place to draw the line from. Like this: import tkinter as tk def myfunction(event): x, y = event.x, event.y if canvas.old_coords: x1, y1 = canvas.old_coords canvas.create_line(x, y, x1, y1) canvas.old_coords = x, y root = tk.Tk() canvas = tk.Canvas(root, width=400, height=400) canvas.pack() canvas.old_coords = None root.bind('&lt;Motion&gt;', myfunction) root.mainloop()
upvote count: 9
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47996285

http://stackoverflow.com/comment/82681801
comment on: http://stackoverflow.com/a/47858519
has text: 32 bytes data is a hash... it's showing as bytes,, I want the real value from the bytes @Daniel
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/47914319
possible better answer: http://stackoverflow.com/a/47914965
has comment: http://stackoverflow.com/comment/82796828
tagged with: python
has answer: http://stackoverflow.com/a/47915157
has title: Tkinter Button Acting up
tagged with: tkinter
has comment: http://stackoverflow.com/comment/82798081
has body: I have the following python 2.7 snippet code from a much larger script. def RefreshAction(): execfile("SatTracker.py") def CloseWindow(): window.destroy() button = tk.Frame(window) button = tk.Button(text='Refresh Data', width=25,command=lambda:[CloseWindow(),RefreshAction()]) button.pack() window.mainloop() So my entire code produces a tkinter window with images, text and a button. Now the button is supposed to trigger the command to close the Tkinter window, then rerun the entire script, which it does just fine. When I click the refresh button again, something weird happens. The window doesn't close anymore, but the script still starts up, with this error though. Exception in Tkinter callback Traceback (most recent call last): File "C:\ProgramData\Anaconda3\envs\python2\lib\lib-tk\Tkinter.py", line 1541, in __call__ return self.func(*args) File "SatTracker.py", line 294, in &lt;lambda&gt; button = tk.Button(text='Refresh Data', width=25,command=lambda:[CloseWindow(),RefreshAction()]) File "C:/Users/Peter Kongstad/Dropbox/Geoscience/2. Masters/7. Semester/Delphini-1 - Software Part/GUI/Programming/SatTracker.py", line 291, in CloseWindow window.destroy() File "C:\ProgramData\Anaconda3\envs\python2\lib\lib-tk\Tkinter.py", line 1864, in destroy self.tk.call('destroy', self._w) TclError: can't invoke "destroy" command: application has been destroyed Exception in Tkinter callback Traceback (most recent call last): File "C:\ProgramData\Anaconda3\envs\python2\lib\lib-tk\Tkinter.py", line 1541, in __call__ return self.func(*args) File "C:/Users/Peter Kongstad/Dropbox/Geoscience/2. Masters/7. Semester/Delphini-1 - Software Part/GUI/Programming/SatTracker.py", line 294, in &lt;lambda&gt; button = tk.Button(text='Refresh Data', width=25,command=lambda:[CloseWindow(),RefreshAction()]) File "C:/Users/Peter Kongstad/Dropbox/Geoscience/2. Masters/7. Semester/Delphini-1 - Software Part/GUI/Programming/SatTracker.py", line 288, in RefreshAction execfile("SatTracker.py") File "SatT…
has comment: http://stackoverflow.com/comment/82797962
linked to: http://stackoverflow.com/q/1750757
linked to: http://stackoverflow.com/q/17466561
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82796706
accepted answer: http://stackoverflow.com/a/47915157
has comment: http://stackoverflow.com/comment/82799416
has comment: http://stackoverflow.com/comment/82816411
type: Question
tagged with: python-2.7
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47914965
has comment: http://stackoverflow.com/comment/82797940

http://stackoverflow.com/comment/82875750
has text: I'm sorry new to this so (coding and asking questions about it)
type: Comment
comment on: http://stackoverflow.com/q/47948225
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82682148
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47858519
has text: How to print 10 zeros from that byte as a single string ? @Daniel

http://stackoverflow.com/comment/82933263
type: Comment
has text: See also https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess for why you want to avoid `shell=True`
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47982395

http://stackoverflow.com/q/47960190
tagged with: sorting
accepted answer: http://stackoverflow.com/a/47960252
favorite count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82889489
has comment: http://stackoverflow.com/comment/82890655
tagged with: python-3.x
has body: I have a dictionary which is formed by using counter: c = collections.Counter() for y in all_years: # iterator c[y] += 1 d = dict(c.most_common()) print(d) /All years contain list of 250 year values/ The result: {1995: 9, 1957: 7, 2003: 7, 2000: 7, 2001: 6, 1975: 6, 2014: 6, 2009: 6, 1994: 5, 1999: 5, 2010: 5, 2002: 5, 1997: 5} Is it possible to sort this dictionary for the equal values by year: e.g. {1995:9,1957:7,2000:7, 2003:7, 1975:6, 2001:6, 2014:6 etc}
has comment: http://stackoverflow.com/comment/82889506
upvote count: 1
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82889508
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/82889622
has comment: http://stackoverflow.com/comment/82889505
has answer: http://stackoverflow.com/a/47960252
type: Question
has title: Sorting dictionary keys for the equal values
downvote count: 0

http://stackoverflow.com/q/47876517
has comment: http://stackoverflow.com/comment/82718720
tagged with: python
has comment: http://stackoverflow.com/comment/82718641
tagged with: oop
has comment: http://stackoverflow.com/comment/82718617
has answer: http://stackoverflow.com/a/47876552
has body: I am wondering if it makes sense in Python to use a class containing a list as if it is an in-memory database. class MyData(object): def __init__(self): self._data = ['apple', 'orange', 'banana'] @property def data(self): return self._data @classmethod def append(self, item): self._data.append(item) Here's the scenario: A first python script a.py will import this class MyData and use the data in its list. A second python script b.py continuously poll an online API in an infinite loop, imports this same class and appends more items to the list. When a.py runs another time, it should be able to read the newly added items in the list. Question: Is this a good idea, or are we better off using a real database like MySQL/redis? Update: The data does not need to be persisted to disk
type: Question
has comment: http://stackoverflow.com/comment/82719018
has comment: http://stackoverflow.com/comment/82719126
has answer: http://stackoverflow.com/a/47876855
has title: Using a Python Class to share data between Python scripts
score: 0
has comment: http://stackoverflow.com/comment/82719039
answer count: 3
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/47876789
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/31875
has comment: http://stackoverflow.com/comment/82718587
type: UnansweredQuestion

http://stackoverflow.com/a/48010810
score: 0
answers question: http://stackoverflow.com/q/48010631
type: Answer
has body: Depends on what 'f' does... Not sure if this is what you mean b = np.arange(3*4).reshape(3,4) c = np.arange(3*4).reshape(3,4)[::-1] b array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) c array([[ 8, 9, 10, 11], [ 4, 5, 6, 7], [ 0, 1, 2, 3]]) def f(b, c): """some function""" a = b + c return a a = f(b, c) a array([[ 8, 10, 12, 14], [ 8, 10, 12, 14], [ 8, 10, 12, 14]])

http://stackoverflow.com/comment/82729581
has text: Did you solve it? If not, you can paste it into stackoverflow, if the file is not to big. Probably it´s better you share it with github.com or other filesharing possibilities and i will have a look.
comment on: http://stackoverflow.com/a/47876477
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/47941113
downvote count: 0
score: 4
answer count: 3
tagged with: pandas
has title: Searching a particular value in a range among two columns python dataframe
favorite count: 0
has body: I have two csv files.Depending upon the value of a cell in csv file 1 I should be able to search that value in a column of csv file 2 and get he corresponding value from other column in csv file 2. I am sorry if this very confusing.It will probably get clear by illustration CSV file 1 Car Mileage A 8 B 6 C 10 CSV file 2 Score Mileage(Min) Mileage(Max) 1 1 3 2 4 6 3 7 9 4 10 12 5 13 15 And my desired output CSV file is something like this Car Mileage Score A 8 3 B 6 2 C 10 4 Car A is given a score of 3 depending upon its mileage 8 and then looking that mileage in csv file 2 in what range it falls and then getting corresponding score value for that range. Any help will be appreciated Thanks in advance
has answer: http://stackoverflow.com/a/47941189
possible better answer: http://stackoverflow.com/a/47941194
tagged with: python
has answer: http://stackoverflow.com/a/47941194
has answer: http://stackoverflow.com/a/47941495
tagged with: lookup
type: AnsweredQuestion
tagged with: dataframe
linked to: http://stackoverflow.com/q/46364710
accepted answer: http://stackoverflow.com/a/47941189
type: Question
upvote count: 4

http://stackoverflow.com/a/47991350
downvote count: 0
has comment: http://stackoverflow.com/comment/82957931
answers question: http://stackoverflow.com/q/47983152
has body: Assuming your model is named Room and it has properties such as length and width: from sqlalchemy import func total_area = session.query(func.sum(Room.length * Room.width)) Which is going to be translated as something like that: SELECT sum(rooms.length * rooms.width) AS sum_1 FROM rooms
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/a/48009035
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48008390
has body: I tried flattening the JSON object so all the keys sit at the same level. import json from pandas.io.json import json_normalize from collections import OrderedDict with open('data.json') as data_file: data = json.load(data_file, object_pairs_hook=OrderedDict) data=json_normalize(data) id='163' for key, value in data.items(): nested_ids = key.split('.') if (id in nested_ids): print(value) Does this get you in the right direction?

gui-testing
type: Tag
tags question: http://stackoverflow.com/q/47926274
tag name: gui-testing

http://stackoverflow.com/q/47864691
has answer: http://stackoverflow.com/a/47864737
has body: I have a pandas dataframe containing a time series (as index) of the form YYYY-MM-DD ('arrival_date') and I'd like to group by each of the weekdays (Monday to Sunday) in order to calculate for the other columns the mean, median, std etc. I should have in the end only seven rows and so far I've only found out how to group by week, which aggregates everything weekly. # Reading the data df_data = pd.read_csv('data.csv', delimiter=',') # Providing the correct format for the data df_data = pd.to_datetime(df_data['arrival_date'], format='%Y%m%d') # Converting the time series column to index df_data.index = pd.to_datetime(df_data['arrival_date'], unit='d') # Grouping by week (= ~52 rows per year) week_df = df_data.resample('W').mean() Is there a simple way to achieve my goal in pandas? I was thinking to choose every other 7th element and perform operations on the resulting array, but that seems unnecessarily complex. The head of the data frame looks like this arrival_date price 1 price_2 price_3 price_4 2 20170816 75.945298 1309.715056 71.510215 22.721958 3 20170817 68.803269 1498.639663 64.675232 22.759137 4 20170818 73.497144 1285.122022 65.620260 24.381532 5 20170819 78.556828 1377.318509 74.028607 26.882429 6 20170820 57.092189 1239.530625 51.942213 22.056378 7 20170821 76.278975 1493.385548 74.801641 27.471604 8 20170822 79.006604 1241.603185 75.360606 28.250994 9 20170823 76.097351 1243.586084 73.459963 24.500618 10 20170824 64.860259 1231.325899 63.205554 25.015120 11 20170825 70.407325 975.091107 64.180692 27.177654 12 20170826 87.742284 1351.306100 79.049023 27.860549 13 20170827 58.014005 1208.424489 51.963388 21.049374 14 20170828 65.774114 1289.341335 59.922912 24.481232
type: AnsweredQuestion
upvote count: 14
type: Question
score: 14
accepted answer: http://stackoverflow.com/a/47864737
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has title: Pandas group by weekday (M/T/W/T/F/S/S)
tagged with: python

http://stackoverflow.com/a/47924476
answers question: http://stackoverflow.com/q/47923952
has comment: http://stackoverflow.com/comment/89165748
upvote count: 20
score: 20
downvote count: 0
has body: You should just add inside your template: {% block title %}Login{% endblock %} {% block content %} Login {% if form.errors %} username or password not correct {% endif %} {% csrf_token %} {{ form.as_p }} Login {% endblock %}
has comment: http://stackoverflow.com/comment/89165778
type: Answer
has comment: http://stackoverflow.com/comment/88833017

http://stackoverflow.com/a/47943321
downvote count: 0
score: 1
has body: Well, depends on how you created the one-hot vector. But if it's sorted the same as your original DataFrame, and itself is a DataFrame, you can add the same index before joining: housing_cat_1hot.index = range(len(housing_cat_1hot)) And if it's not a DataFrame, convert it to one. This is simple, as long as both objects are sorted the same Edit: If it's not a DataFrame, then: housing_cat_1hot = pd.DataFrame(housing_cat_1hot) Already creates the proper index for you
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47942861
answers question: http://stackoverflow.com/q/47942861
type: Answer

http://stackoverflow.com/comment/82893722
type: QuestionComment
comment on: http://stackoverflow.com/q/47962044
has text: we are trying to incorporate a new peak finding algorithm to SciPy but you can still have a look and hopefully give us some feedback about it :) https://github.com/scipy/scipy/issues/8211
score: 0
type: Comment

http://stackoverflow.com/comment/82851757
type: Comment
has text: My answer would work then, try it and let me know.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47933691

http://stackoverflow.com/q/47917916
tagged with: widget
type: UnansweredQuestion
has title: Passing many variables from entry widgets to label widgets tkinter
has comment: http://stackoverflow.com/comment/82818809
has comment: http://stackoverflow.com/comment/82803806
has comment: http://stackoverflow.com/comment/82803882
type: Question
score: 0
has body: I am currently creating a program with gui that opens to a mainscreen with several buttons then quite a few cells(setup as blank label widgets) that need to be filled with data. Several of the buttons will open a new window and prompt the user to enter data into entry widgets. I want to then take this data and insert it back into the label widgets on the mainscreen. After lots of searching and attempts I have finaly determined that I can setup StringVar() variables that are set as the text variable imputs on the labels on the main page. This issue with this is that is creates a large number of variables that have to be declared as global vairables both in the parent class of the main screen as well asin the function that runs when the button is pressed on the second screen to set the data into the mainscreen labels. This code here sets up the variables in the parent class: global wgentry global woentry global dentry global tidentry global aventry global aaentry global bventry global baentry global cventry global caentry wgentry = tk.StringVar() woentry = tk.StringVar() dentry = tk.StringVar() tidentry = tk.StringVar() aventry = tk.StringVar() aaentry = tk.StringVar() bventry = tk.StringVar() baentry = tk.StringVar() cventry = tk.StringVar() caentry = tk.StringVar() wgentry.set(returnlist[0]) woentry.set(returnlist[0]) dentry.set(returnlist[0]) tidentry.set(returnlist[0]) aventry.set(returnlist[0]) aaentry.set(returnlist[0]) bventry.set(returnlist[0]) baentry.set(returnlist[0]) cventry.set(returnlist[0]) caentry.set(returnlist[0]) This code is then run in the button press function to change the values. global wgentry global woentry global dentry global tidentry global aventry global aaentry global bventry global baentry global cventry global caentry wgentry.set(workgroupentry.get()) woentry.set(workorderentry.get()) dentry.set(dateentry.get()) tidentry.set(transidentry.get()) aventry.set(avoltageentry.get()) aaentry.set(aangleentry.get()) bventry.set(bvoltageentry.ge…
has comment: http://stackoverflow.com/comment/82818780
tagged with: python
tagged with: tkinter
answer count: 0

http://stackoverflow.com/a/58178464
has comment: http://stackoverflow.com/comment/102843837
has body: You could explicitly handle it on the bash side in a script file like this: if python -c "import time; time.sleep(100)"; then echo END fi or, more aggressively, python -c "import time; time.sleep(100)" $? -ne 0 &amp;&amp; exit echo END $? is the return status code of the previous command. Where a status code of 0 means it exited fine, and anything else was an error. So, we use the short-circuit nature of &amp;&amp; to succinctly exit if the previous command fails. (See https://unix.stackexchange.com/questions/186826/parent-script-continues-when-child-exits-with-non-zero-exit-code for more info on that) Note: this will exit the bash script for any kind of python failure, not just ctrl+c, e.g. IndexError, AssertionError, etc
answers question: http://stackoverflow.com/q/47862148
score: 0
has comment: http://stackoverflow.com/comment/102910058
has comment: http://stackoverflow.com/comment/102894883
type: Answer

http://stackoverflow.com/q/47972143
type: Question
has title: Using attr with pylint
has comment: http://stackoverflow.com/comment/82924728
downvote count: 0
has body: Using the attrs package seems to cause errors with PyLint: import attr @attr.s(slots=True) class Foo: d = attr.ib(attr.Factory(dict), type=dict) f = Foo() print('bar' in f.d) print(f.d.items()) PyLint complains with the following error messages (irrelevant removed): E: 9,15: Value 'f.d' doesn't support membership test (unsupported-membership-test) E: 10, 6: Instance of '_CountingAttr' has no 'items' member (no-member) Is there a direct way how to make attrs sanely work with pylint?
favorite count: 0
tagged with: python-attrs
type: UnansweredQuestion
tagged with: pylint
has comment: http://stackoverflow.com/comment/82945326
tagged with: python
has comment: http://stackoverflow.com/comment/82932026
answer count: 0
score: 7
upvote count: 7

http://stackoverflow.com/a/47906270
type: Answer
answers question: http://stackoverflow.com/q/47906007
downvote count: 1
score: -1
has comment: http://stackoverflow.com/comment/82779375
upvote count: 0
has body: from selenium import webdriver import time from time import gmtime, strftime browser = webdriver.Chrome() filename = (strftime("%Y-%m-%d %H%M%S", gmtime())) browser.get_screenshot_as_file("C:\\parh\\screenshots\\" + filename + ".png") browser.quit() print (strftime("%Y-%m-%d %H:%M:%S", gmtime())) print (filename)

http://stackoverflow.com/comment/82852195
has text: Your second solution seems the same as @Inian answer, except it is in more detail and has more options
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47911826
type: AnswerComment

http://stackoverflow.com/comment/82794673
type: QuestionComment
comment on: http://stackoverflow.com/q/47913381
has text: Do you alter any part of the edge's information after putting it into the set? For instance, if the `source` or its id changes, the hash will change and the set will no longer work correctly.
score: 3
type: Comment

http://stackoverflow.com/comment/89165778
type: Comment
has text: @MLavrentyev And definitely agree.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47924476

http://stackoverflow.com/comment/82937704
comment on: http://stackoverflow.com/a/47984291
score: 0
type: AnswerComment
has text: I tried it and returned: TypeError: create_code() missing 1 required positional argument: 'codigo'
type: Comment

http://stackoverflow.com/comment/82999523
score: 0
comment on: http://stackoverflow.com/q/48000487
type: Comment
type: QuestionComment
has text: @C8H10N4O2 It worked! Could you please elaborate why the second one works?

http://stackoverflow.com/comment/82877967
score: 1
type: AnswerComment
has text: @Divakar, yeah, thank you for reminding of `ufunc.at()` !
comment on: http://stackoverflow.com/a/47954212
type: Comment

http://stackoverflow.com/a/47966143
has comment: http://stackoverflow.com/comment/82903910
has comment: http://stackoverflow.com/comment/82903723
has comment: http://stackoverflow.com/comment/82902038
has comment: http://stackoverflow.com/comment/82901989
type: Answer
has comment: http://stackoverflow.com/comment/82902800
answers question: http://stackoverflow.com/q/47966081
has comment: http://stackoverflow.com/comment/82903953
has comment: http://stackoverflow.com/comment/82914839
has comment: http://stackoverflow.com/comment/82902262
has body: As per documentation, you can use Dataframe.combine to Add two DataFrame objects and do not propagate NaN values. If for a (column, time) one frame is missing a value, it will default to the other frame’s value (which might be NaN as well). func is a function where you write your logic to choose the value. I think you have confusion because of lambda expression. Let me rewrite the example given in documentation without using lambda expression. def _fn(left, right): if left.sum() &lt; right.sum(): return left else return right df1 = DataFrame({'A': [0, 0], 'B': [4, 4]}) df2 = DataFrame({'A': [1, 1], 'B': [3, 3]}) df1.combine(df2, _fn) Output : A B 0 0 3 1 0 3 P.S : Since OP wants to use Dataframe.combine to replicate behavior of Dataframe.combine_first, I am pasting the source code of Dataframe.combine_first from pandas github repository. https://github.com/pandas-dev/pandas/blob/master/pandas/core/frame.py#L4153 def combine_first(self, other): import pandas.core.computation.expressions as expressions def combiner(x, y, needs_i8_conversion=False): x_values = x.values if hasattr(x, 'values') else x y_values = y.values if hasattr(y, 'values') else y if needs_i8_conversion: mask = isna(x) x_values = x_values.view('i8') y_values = y_values.view('i8') else: mask = isna(x_values) return expressions.where(mask, y_values, x_values) return self.combine(other, combiner, overwrite=False)
score: 0

http://stackoverflow.com/comment/82951693
type: QuestionComment
comment on: http://stackoverflow.com/q/47991710
has text: It's because `x` and `y` refer to the same object.
score: 0
type: Comment

http://stackoverflow.com/comment/82922726
score: 0
has text: what error do you get?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47976654

http://stackoverflow.com/q/47928523
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/47928579
tagged with: python
has title: python-daemon - running thread inside
accepted answer: http://stackoverflow.com/a/47928579
tagged with: multithreading
type: AnsweredQuestion
tagged with: python-daemon
type: Question
has body: I'm using python-daemon, but I have a thread inside the daemon to check a serial port occasionally: context = daemon.DaemonContext(pidfile=daemon.pidfile.TimeoutPIDLockFile('/var/run/gpstemp.pid'), uid = 0, gid = 4, umask = 0o002, stdout = sys.stdout, # change these for deployment stderr =sys.stderr, # change these for deployment chroot_directory= None, working_directory='/home/debian/gpstemp' app = App() with context: app.run() The thread runs this: class App(): def __init__(self, port = 5556): ... # Handle all those threading things self.__sem = Lock() self.interval = 60.0 # interval between time updates in seconds self.worker = Thread(target = self._get_datetime_worker) def run(self): self.worker.start() ... def _get_datetime_worker(self): while not self.exit.is_set(): self._get_datetime() self.exit.wait(self.interval) I'm using systemctl to start and stop it using a .service file. When I run: sudo systemctl stop myservice It waits 60 seconds before returning. How would I kill my thread in the service immediately through systemctl. I considered passing the context to the App and then redefining: context.signal_map = { signal.SIGTERM: app.shutdown, signal.SIGHUP: app.shutdown, } and then adding a shutdown method to App that does: def shutdown(self, *args): self.exit.set() self.worker.join() But, that doesn't let the context destroy the PID and doesn't exit the context right. What else should I add to the shutdown method to make things work correctly? Kurt

http://stackoverflow.com/comment/82711758
score: 1
comment on: http://stackoverflow.com/a/47869710
has text: This is clever !
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/82764065
has text: I've edited the answer to accept various other filters/flags. Not sure if your various flags are fixed or not. I'll guess other might have more to add. Good luck :)
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47898554
type: AnswerComment

http://stackoverflow.com/comment/82967087
type: Comment
type: QuestionComment
has text: You don't need any of the Studios (as long as you don't plan to code in C or C++ or C#). Scroll the page down to the bottom, the build tools are under the section `Other Tools and Frameworks` (for me, it's the last but one item in the list).
score: 0
comment on: http://stackoverflow.com/q/47872603

http://stackoverflow.com/q/47995681
tagged with: django
tagged with: python
tagged with: web-services
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/47996059
has body: i want to pass the url of the image that was selected by the user in my python function views.py because my python function will process the image that was selected by the user. this is my html command JS Bin <!--[if IE]> <![endif]--> and here is the function on my python def predict(): img = cv2.imread('C:/Users/HABITUS/Desktop/arvin files/download.jpg') #the url of the image selected must be here!! img = cv2.resize(img, (600, 600)) enhancer = Image.fromarray(img) enhancer = ImageEnhance.Contrast(enhancer) enhanced = enhancer.enhance(1.5) enhancer1 = ImageEnhance.Brightness(enhanced).enhance(1.3) convert = scipy.misc.fromimage(enhancer1) imgM = cv2.medianBlur(convert, 5) # blurring and smoothening kernel = np.ones((5, 5), np.uint8) erosion = cv2.erode(imgM, kernel, iterations=1) dilation = cv2.dilate(erosion, kernel, iterations=1) blur = cv2.GaussianBlur(convert, (15, 15), 10) grayscaled = cv2.cvtColor(imgM, cv2.COLOR_BGR2GRAY) retval2, threshold2 = cv2.threshold(grayscaled, 200, 1, cv2.THRESH_BINARY_INV) gaus = cv2.adaptiveThreshold(grayscaled, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1) retval2, otsu = cv2.threshold(grayscaled, 140, 250, cv2.THRESH_BINARY + cv2.THRESH_OTSU) backtorgb = cv2.cvtColor(threshold2, cv2.COLOR_GRAY2RGB) mult = cv2.multiply(img, backtorgb) edges = cv2.Canny(threshold2, 120, 50) the image that was selected by the user must be in cv2.imread() how can i do that? any advice or help will be appreciated thanks
tagged with: javascript
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
linked to: http://stackoverflow.com/q/5871730
linked to: http://stackoverflow.com/q/25028895
has comment: http://stackoverflow.com/comment/82961478
type: Question
has title: how to pass the url of image clicked on my html file to my python function in views.py Django

http://stackoverflow.com/comment/82916669
comment on: http://stackoverflow.com/a/47972710
score: 1
type: AnswerComment
has text: @Qiyu with multiple dtypes yes.
type: Comment

pytest-cov
tags question: http://stackoverflow.com/q/47884709
tag name: pytest-cov
type: Tag

http://stackoverflow.com/comment/82909659
has text: In addition, if you really want `dense.dot(sparse)`, you can do `sparse.T.dot(dense.T).T`
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47969531

http://stackoverflow.com/q/47857239
answer count: 1
tagged with: email
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/47857413
tagged with: python
has body: I have a data, let's say data = [ ['header_1', 'header_2'], ['row_1_!', 'row_1_2'], ['row_2_1', 'row_2_2'], ] I need to send that data as .csv file attachment to email message. I can not save it as .csv and then attach existing csv - application is working in Googpe App Engine sandbox environment. so no files can be saved. As I understand, email attachment consists of file name and file encoded as base64. I tried to make attachment body in the following way: import csv if sys.version_info &gt;= (3, 0): from io import StringIO else: from StringIO import StringIO in_memory_data = StringIO() csv.writer(inmemory_data).writerows(data) encoded = base64.b64encode(inmemory_data.getvalue()) But in result I have received by email not valid file 2 columns and 3 rows, but just one string in file (see the picture). csv_screen What I'm doing wrong?
type: Question
has title: Send data as .csv email attachmet Python
score: 0

http://stackoverflow.com/q/47867919
score: 4
tagged with: sharepoint
has title: Python Okta and Office 365/ SharePoint
favorite count: 0
has comment: http://stackoverflow.com/comment/107938699
tagged with: python
tagged with: okta
answer count: 0
has body: I would like to pick a file from SharePoint using a python script. The problem is that my company is using Okta to secure identity and I don't really know which is the right approach to connect through Okta to Office 365. Has anyone had any experience on this? Thanks guys!
type: UnansweredQuestion
type: Question
upvote count: 4
tagged with: office365
tagged with: api
downvote count: 0

memory
tags question: http://stackoverflow.com/q/47959077
tags question: http://stackoverflow.com/q/47901069
tag name: memory
tags question: http://stackoverflow.com/q/47923068
type: Tag
tags question: http://stackoverflow.com/q/47943279
tags question: http://stackoverflow.com/q/47857005

http://stackoverflow.com/comment/82962168
type: Comment
type: QuestionComment
has text: The core idea of the analysis I'm making is to go through all of the possibilities in order to find the very best one, so this is probably the only way of doing that.
comment on: http://stackoverflow.com/q/47996986
score: 0

http://stackoverflow.com/comment/83215895
comment on: http://stackoverflow.com/q/47963425
has text: Is `active_position` always a `0` or `1`?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82757854
type: Comment
has text: If nothing were being executed, spark would not have opened any files in the first place. Also, no, deleting a variable won't close intermediate files.
comment on: http://stackoverflow.com/q/47894597
score: 0
type: QuestionComment

http://stackoverflow.com/a/47939502
score: -1
has comment: http://stackoverflow.com/comment/82848087
downvote count: 1
has comment: http://stackoverflow.com/comment/82855868
type: Answer
has comment: http://stackoverflow.com/comment/82855478
has body: Try this with open("main.csv") as csvfile: tlines = [line.split(",", 2) for line in csvfile.readlines()] text = [" ".join(line) for line in tlines] print text It might help you.
upvote count: 0
has comment: http://stackoverflow.com/comment/82848129
answers question: http://stackoverflow.com/q/47939235

http://stackoverflow.com/q/47909292
downvote count: 1
accepted answer: http://stackoverflow.com/a/47910424
type: Question
tagged with: pyomo
has body: Let us consider the following set: m.sub_sit = pyomo.Set( initialize=[site], doc='site of sub problem') in this case m.sub_sit is created by create_model() function with the argument 'Mid': inst = create_model(site='Mid') what I get by calling inst.sub_sit.pprint(): In: inst.sub_sit.pprint() Out: sub_sit : site of sub problem Dim=0, Dimen=1, Size=1, Domain=None, Ordered=False, Bounds=None ['Mid'] What I really want to output is 'Mid', so that I can index other objects with 'Mid', and then I can use it in my code. e.g.: In1: PiZero In2: PiZero[inst.sub_sit[1]] In3: PiZero['Mid'] Out1: sub_sit Mid -1.0 Name: sub_costs, dtype: float64 Out2: -1.0 Out3: -1.0 Question: is there anyway to call this 'Mid' string from m.sub_sit pyomo set object, better than what I suggest? btw m.sub_sit.value gives an output, almost what I needed: {'Mid'}
upvote count: 0
has title: Pyomo calling the value of a set
score: -1
answer count: 2
has comment: http://stackoverflow.com/comment/82798227
has comment: http://stackoverflow.com/comment/82796824
has comment: http://stackoverflow.com/comment/82799359
favorite count: 0
has answer: http://stackoverflow.com/a/47910424
possible better answer: http://stackoverflow.com/a/47929389
tagged with: python
has answer: http://stackoverflow.com/a/47929389
tagged with: indexing
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82796871
has comment: http://stackoverflow.com/comment/82790673

twitter
tags question: http://stackoverflow.com/q/47896298
tags question: http://stackoverflow.com/q/47931233
tags question: http://stackoverflow.com/q/47976170
tags question: http://stackoverflow.com/q/48001159
type: Tag
tags question: http://stackoverflow.com/q/47861097
tags question: http://stackoverflow.com/q/48002981
tags question: http://stackoverflow.com/q/47892385
tag name: twitter
tags question: http://stackoverflow.com/q/47962277
tags question: http://stackoverflow.com/q/47925828
tags question: http://stackoverflow.com/q/47882039
tags question: http://stackoverflow.com/q/47943855
tags question: http://stackoverflow.com/q/47960597

http://stackoverflow.com/a/47871103
score: 3
has comment: http://stackoverflow.com/comment/82713825
has comment: http://stackoverflow.com/comment/82712565
has comment: http://stackoverflow.com/comment/82710899
has comment: http://stackoverflow.com/comment/82711039
has comment: http://stackoverflow.com/comment/82714262
has comment: http://stackoverflow.com/comment/82711252
accepted answer of: http://stackoverflow.com/q/47870621
upvote count: 3
has comment: http://stackoverflow.com/comment/82714285
answers question: http://stackoverflow.com/q/47870621
type: AcceptedAnswer
has body: I don't know if its the most elegant solution but you can use list comprehension to create a list containing the relevant columns: import pandas as pd from scipy.stats import pearsonr result = pd.DataFrame() for a1 in [column for column in df.columns if 'a1' in column]: for b1 in [column for column in df.columns if 'b1' in column]: result = result.append( pd.Series( pearsonr(df[a1],df[b1]), index=['PCC', 'p-value'], name=a1 + '__' +b1 )) PS: It would be great if you would include your imports in your next question. (So that people answering don't have to google it)
downvote count: 0
has comment: http://stackoverflow.com/comment/82710789
has comment: http://stackoverflow.com/comment/82711149
type: Answer
has comment: http://stackoverflow.com/comment/82712689
has comment: http://stackoverflow.com/comment/82713174

http://stackoverflow.com/a/62867966
score: 1
answers question: http://stackoverflow.com/q/47952552
upvote count: 1
type: Answer
has body: Another solution is (from Bitvise FAQ): How can I use SSH to start a program so it displays on the server's interactive desktop? The easiest way to do this is using the Windows Task Scheduler. First, use the Task Scheduler to configure a task that you can run by name. Then run the task from the SSH session using: schtasks /run /tn NameOfTask If the task runs a PowerShell script or batch file, you can also change the contents of the script file on demand, to correspond to what you want to run.
downvote count: 0

http://stackoverflow.com/q/47970531
tagged with: arguments
tagged with: python
has comment: http://stackoverflow.com/comment/82910458
has answer: http://stackoverflow.com/a/47970589
upvote count: 0
has body: I am confused as to why the following code is not working. My confusion lies with the returns and prints. I don't know how to make the list as the argument. Everything else seems to work fine up until that part. def while_mean(l): sum = 0 length = float(len(l)) index = 0 while index &lt; len(l): sum = l[index] + sum index = index + 1 return sum/length def for_mean(l): sum = 0 length = float(len(l)) for i in l: sum = i + sum mean = sum/length return mean def stats(): apd = ([]) nume = input("write a number:") while nume != 'n': apd.append(nume) print apd nume = input("write another number:") return sum(apd) return while_mean([apd]) print stats() print while_mean([apd]) changed def stats to: def stats(): apd = ([]) nume = raw_input("write a number:") while nume != 'n': apd.append(float(nume)) print apd nume = raw_input("write another number:") return sum(apd) print apd = ([]) print stats() print while_mean(apd)
type: Question
tagged with: function
has comment: http://stackoverflow.com/comment/82940188
score: -1
tagged with: python-2.7
answer count: 2
has title: List as argument in Python 2.7
downvote count: 1
has answer: http://stackoverflow.com/a/47970749
favorite count: 0
tagged with: return
has comment: http://stackoverflow.com/comment/82910496
type: UnansweredQuestion

http://stackoverflow.com/q/47927923
tagged with: list
downvote count: 3
type: Question
has title: list.insert(position, value) grows list indefinitely
score: -2
answer count: 1
has body: If I run the following code: data = list() length = 10 for i in range(1000): point = i % length data.insert(point, i) len(data) The output is: 1000 I was expecting the length to be 10 as I am restricting point to be in range 0-9. What I am doing wrong?
has comment: http://stackoverflow.com/comment/82824273
has answer: http://stackoverflow.com/a/47928003
favorite count: 0
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/82824173
accepted answer: http://stackoverflow.com/a/47928003
upvote count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/48383015
upvote count: 5
has comment: http://stackoverflow.com/comment/83872397
type: Answer
answers question: http://stackoverflow.com/q/47979438
downvote count: 0
has comment: http://stackoverflow.com/comment/83753155
score: 5
has body: In TIA portal, check if "optimized block access" property is off for Data block that you want to read data from. Moreover, under CPU access protection; access level must be “full” and the “connection mechanism” must allow GET/PUT. See the following link for more detail: http://snap7.sourceforge.net/snap7_client.html#1200_1500 Secondly, which data block that you want to access? You should specify that in your plc.read_area() method call. There should be a method argument that specifies "Data Block" number since you are using "0x84" data block area code.

http://stackoverflow.com/q/47893249
type: Question
tagged with: d3.js
tagged with: python
has answer: http://stackoverflow.com/a/48550052
tagged with: heatmap
has comment: http://stackoverflow.com/comment/83898406
upvote count: 1
answer count: 1
has body: I've successfully replicated this interactive dashboard map example here. I now want to input my own data. My python is more simple than the example's since all my data is already structured in the way I want it. Here's my python: # -*- coding: utf-8 -*- import pandas as pd from shapely.geometry import Point, shape from flask import Flask from flask import render_template import json data_path = './input/' def get_location(longitude, latitude, ny_json): point = Point(longitude, latitude) for record in ny_json['features']: polygon = shape(record['geometry']) if polygon.contains(point): return record['properties']['Name'] return 'other' with open(data_path + '/geojson/ny_HA.json') as data_file: ny_json = json.load(data_file) app = Flask(__name__) #route to html index @app.route("/") def index(): return render_template("index.html") #route data @app.route("/data") def get_data(): df = pd.read_csv(data_path + 'Mikes_NY_geocoded_tickets.csv', sep=';') df['location'] = df.apply(lambda row: get_location(row['longitude'], row['latitude'], ny_json), axis=1) cols_to_keep = ['timestamp', 'longitude', 'latitude', 'Violation', 'Type', 'DayOfWeek', 'location'] #remove NaN values df_clean = df[cols_to_keep].dropna() #return a json return df_clean.to_json(orient='records') if __name__ == "__main__": app.run(host='0.0.0.0',port=5000,debug=True) Here is my data geocoded_data.csv: When I run my app python app.py, No errors and when I enter the localhost into my browser my dashboard appears, but everything is empty, my cross filters and map. Here's what the browser is displaying: Here are my errors in the browser console Any ideas would be much appreciated.
tagged with: crossfilter
has title: Python & D3.js Dashboard Crossfilter Heat Map
accepted answer: http://stackoverflow.com/a/48550052
tagged with: javascript
has comment: http://stackoverflow.com/comment/84089613
has comment: http://stackoverflow.com/comment/82804030
has comment: http://stackoverflow.com/comment/83898498
has comment: http://stackoverflow.com/comment/84094949
has comment: http://stackoverflow.com/comment/84095368
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84089806

c++
tags question: http://stackoverflow.com/q/47885615
tags question: http://stackoverflow.com/q/47856074
tags question: http://stackoverflow.com/q/47949918
tags question: http://stackoverflow.com/q/47971907
tags question: http://stackoverflow.com/q/47899386
tags question: http://stackoverflow.com/q/47932685
tags question: http://stackoverflow.com/q/47919194
tags question: http://stackoverflow.com/q/47994082
tags question: http://stackoverflow.com/q/48007009
tags question: http://stackoverflow.com/q/47872981
type: Tag
tags question: http://stackoverflow.com/q/47942845
tags question: http://stackoverflow.com/q/48002776
tags question: http://stackoverflow.com/q/47938562
tags question: http://stackoverflow.com/q/47873936
tags question: http://stackoverflow.com/q/47925216
tags question: http://stackoverflow.com/q/47981651
tags question: http://stackoverflow.com/q/47907555
tags question: http://stackoverflow.com/q/47885698
tag name: c++
tags question: http://stackoverflow.com/q/47939846
tags question: http://stackoverflow.com/q/47936365
tags question: http://stackoverflow.com/q/47899493

http://stackoverflow.com/comment/82818986
comment on: http://stackoverflow.com/q/47895141
type: QuestionComment
has text: Did you try to render the page in Splash web console?
score: 0
type: Comment

http://stackoverflow.com/q/47999418
upvote count: 5
has comment: http://stackoverflow.com/comment/82967450
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/82967400
downvote count: 0
has answer: http://stackoverflow.com/a/47999513
favorite count: 0
linked to: http://stackoverflow.com/q/42920363
has answer: http://stackoverflow.com/a/47999493
score: 5
tagged with: python
duplicate of: http://stackoverflow.com/q/42920363
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/35491274
possible better answer: http://stackoverflow.com/a/47999493
has body: I accidentally closed this question with a link to the wrong duplicate. Here is the correct one: Pandas split column of lists into multiple columns. Suppose I have a dataframe of which one column is a list (of a known and identical length) or tuple, for example: df1 = pd.DataFrame( {'vals': [['a', 'b', 'c', 'd'],['e','f','g','h']]} ) ie: vals 0 [a, b, c, d] 1 [e, f, g, h] I want to extra the values in "vals" into separate named columns. I can do this clumsily by iterating through the rows: for i in range(df1.shape[0]): for j in range(0,4): df1.loc[i, 'vals_'+j] = df1.loc[i, 'vals'] [j] Result as desired: vals vals_0 vals_1 vals_2 vals_3 0 [a, b, c, d] a b c d 1 [e, f, g, h] e f g h Is there a neater (vectorised) way? I tried using [] but I get an error. for j in range (0,4) df1['vals_'+str(j)] = df1['vals'][j] gives: ValueError: Length of values does not match length of index It looks like Pandas is trying to apply the [] operator to the series/dataframe rather than the column content.
has title: How best to extract a Pandas column containing lists or tuples into multiple columns
accepted answer: http://stackoverflow.com/a/47999513
duplicate of: http://stackoverflow.com/q/35491274
type: Question

http://stackoverflow.com/q/47978929
answer count: 1
has answer: http://stackoverflow.com/a/47978988
type: Question
tagged with: python
score: 0
accepted answer: http://stackoverflow.com/a/47978988
has body: hi i want to get last specific number of data from database in python for example i get last three name of my database i try last = mpost.objects.count(3) but it gives me error Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; File "example.py", line 122, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) TypeError: count() takes 1 positional argument but 2 were given can you tell me the query that i must write thank you
has title: how get specific number of data with queryset in python
type: AnsweredQuestion

http://stackoverflow.com/a/47858668
answers question: http://stackoverflow.com/q/47856744
score: 0
type: Answer
has body: You are already using CREATE TABLE IF NOT EXISTS, but it might be easier to wrap all four creating/insertion functions into a check for the database contents: if not table_exists(conn, "family"): conn.execute("BEGIN") with conn: create_table1() create_table2() data_entry1() data_entry2() read_from_db() The column name first_name is ambiguous because it occurs in both tables. When you join using USING instead, the database will automatically remove the duplicate column: c.execute("""SELECT first_name, job FROM family JOIN jobs USING (first_name) WHERE job = 'YES'""")

http://stackoverflow.com/a/47973297
type: Answer
accepted answer of: http://stackoverflow.com/q/47973242
has comment: http://stackoverflow.com/comment/138235097
has comment: http://stackoverflow.com/comment/82916200
downvote count: 0
score: 19
has body: pass is a statement. As such it can be used everywhere a statement can be used to do nothing. None is an atom and as such an expression in its simplest form. It is also a keyword and a constant value for “nothing” (the only instance of the NoneType). Since it is an expression, it is valid in every place an expression is expected. Usually, pass is used to signify an empty function body as in the following example: def foo(): pass This function does nothing since its only statement is the no-operation statement pass. Since an expression is also a valid function body, you could also write this using None: def foo(): None While the function will behave identically, it is a bit different since the expression (while constant) will still be evaluated (although immediately discarded).
upvote count: 19
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47973242

http://stackoverflow.com/comment/82707340
has text: @COLDSPEED I tend to consider regex valid here since OP is dealing with names and it's not surprising that there are unexpected formats in a real data set. `Regex` helps validate the Name as well.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47861978

http://stackoverflow.com/comment/82920807
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47975539
has text: Sure, please see my answer below.

http://stackoverflow.com/q/47994825
score: 19
answer count: 4
has comment: http://stackoverflow.com/comment/82958668
has answer: http://stackoverflow.com/a/73368380
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84448354
has answer: http://stackoverflow.com/a/73983759
type: Question
has answer: http://stackoverflow.com/a/78260583
has comment: http://stackoverflow.com/comment/127825771
tagged with: python
has comment: http://stackoverflow.com/comment/84448812
upvote count: 19
tagged with: amazon-s3
has title: botocore.exceptions.ClientError An error occurred (SignatureDoesNotMatch) when calling the GetObject operation
tagged with: ssl
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/54903693
tagged with: boto3
tagged with: amazon-web-services
has body: While running the following code: import boto3 BUCKET = 'bwd-plfb' s3 = boto3.client('s3',use_ssl = False) resp = s3.list_objects_v2(Bucket = BUCKET ) s3.download_file(BUCKET,'20171018/OK/OK_All.zip','test.zip') I'm getting the following error: botocore.exceptions.ClientError: An error occurred (SignatureDoesNotMatch) when calling the GetObject operation: The request signature we calculated does not match the signature you provided. Check your key and signing method. What I've tried so far: Double checking Access key ID and Secret access key configured in aws cli (Running aws configure in command prompt) - They're correct. Trying to list bucket objects using boto3 - It worked successfully. The problem seems to be occuring when trying to download files. Using a chrome plugin to browse bucket contents and download files: chrome plugin It works successfully. The interesting thing is downloading works for some files but not all. I downloaded a file which previously worked before 20 times in a row to see if the error was intermittent. It worked all 20 times. I did the same thing for a file which had not previously worked and it did not download any of the 20 times. I saw some other posts on stackoverflow saying the api key &amp; access key maybe incorrect. However, I don't believe that to be the case if I was able to list objects and download files (one's which did &amp; did not work through boto3) using the Chrome S3 plugin. Does anyone have any suggestions on what might be the issue here? Thank You

http://stackoverflow.com/a/51336212
answers question: http://stackoverflow.com/q/47950571
downvote count: 0
has body: You can check this answer Media files not showing on Debug False (" The behaviour you are seeing is by design, Django doesn't serve static files in production mode. Serving many, potentially huge static files using Python will put a lot of stress on the server, while any of the common servers will handle that with ease.") Otherwise, If I'm right than you want to host your website on a server. Once you turn debug = True to False, Django no longer handle the static files by itself. Now, it's the server which handles the static files. I have this problem when I uploaded my django project to pythonanywhere. In order to solve the problem, you have to explicitly tell the server where your static files are located:
has comment: http://stackoverflow.com/comment/89647507
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/82801267
comment on: http://stackoverflow.com/a/47868393
type: AnswerComment
has text: @PaulH The conda solver is not perfect, and when it has so many packages to try and upgrade there is more likely to be a problem. In any case, even if it doesn't install the incompatible packages, if there are incompatibilities, you would end up with an error message
type: Comment
score: 2

http://stackoverflow.com/comment/82722441
comment on: http://stackoverflow.com/q/47878228
has text: Python is synchronous by default so when `func1` actually runs, it will block the main thread and not continue your program until the function is complete.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47880164
has comment: http://stackoverflow.com/comment/82751077
tagged with: selenium
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82727637
accepted answer: http://stackoverflow.com/a/55816836
has comment: http://stackoverflow.com/comment/82752566
has comment: http://stackoverflow.com/comment/82752527
has answer: http://stackoverflow.com/a/55816836
has comment: http://stackoverflow.com/comment/82754462
answer count: 1
has comment: http://stackoverflow.com/comment/82756399
score: 0
tagged with: python
has title: After drag-and-drop operations, Selenium (Python) sometimes refuses to budge
has body: After some dragging and dropping of elements into one another, the my program sometimes hangs. So I have a timeout set for it that runs the first block of code when the timer is reached. It does print the first line, but Selenium refuses to budge as driver.close() does not run after the print statement, and the rest of the code is rendered unreachable. The whole program hangs and cannot proceed. Is this a bug with Selenium or something I wrote? print("This took too long. Will run a different function.") driver.close() driver.switch_to_window(driver.window_handles[0]) sleep(2) # REST OF CODE Could it possibly be the drag-and-drop code? if elementsToMove: a1 = random.choice(elementsToMove) a2 = random.choice(elementsToMove) while a1 == a2: a2 = random.choice(elementsToMove) actions = webdriver.ActionChains(driver) actions.drag_and_drop(a1, a2) actions.perform()

http://stackoverflow.com/comment/82910545
score: 0
type: Comment
type: QuestionComment
has text: Are you looking for `df['string'].str.count(';') + 1`?
comment on: http://stackoverflow.com/q/47970561

http://stackoverflow.com/comment/82767881
has text: Something like [this](https://docs.python.org/3/library/re.html#re.findall)
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47900657
score: 0

http://stackoverflow.com/q/47880671
tagged with: python
has body: Given a dataframe like the first 2 columns (count &amp; dt) below, I'm looking to get the number of distinct dts seen in the 7-day window leading up to (but not including) each dt (e.g. what’s displayed in num_distinct_dts_prior_7_days). ix count dt num_distinct_dts_prior_7_days 0 6 2017-12-01 0 1 2 2017-12-02 1 2 2 2017-12-04 2 3 9 2017-12-05 3 4 4 2017-12-10 2 5 7 2017-12-14 1 6 2 2017-12-28 0 7 3 2017-12-29 1 This is a simplified version of the table; ultimately, my dataframe would have an additional id column, and I'd want to find the number of distinct dts seen in the 7-day window leading up to each dt, for each id. I'm happy to iterate over each id (O(tends of thousands)) if there's no solution applicable across the full dataset.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82749010
tagged with: dataframe
type: Question
has title: In python, what's the best way to get the unique count of rows in a dataframe that fall within a specific date-window relative to each row?
answer count: 1
has answer: http://stackoverflow.com/a/47880968
has comment: http://stackoverflow.com/comment/82727375
score: 0
tagged with: pandas

http://stackoverflow.com/a/47882531
downvote count: 0
answers question: http://stackoverflow.com/q/47882492
type: Answer
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/82733123
has body: import numpy as np a = [2, 4, 7, 11, 18] b = [100000, 90000, 80000, 70000, 60000] g = np.gradient(a, b)
accepted answer of: http://stackoverflow.com/q/47882492
type: AcceptedAnswer

http://stackoverflow.com/comment/83036921
has text: Actually I think that `create_date` and `write_date` fields should have miliseconds. `Datetime` fields shouldn't have because the `DEFAULT_SERVER_DATETIME_FORMAT` constant is used. So I don't know what's happening in your case
comment on: http://stackoverflow.com/q/48010835
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82752561
has text: Is this something I should report as issue?
comment on: http://stackoverflow.com/q/47892561
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82679232
type: QuestionComment
comment on: http://stackoverflow.com/q/47857428
score: 0
has text: It given file type json
type: Comment

qpushbutton
type: Tag
tags question: http://stackoverflow.com/q/47858623
tags question: http://stackoverflow.com/q/47998315
tags question: http://stackoverflow.com/q/47965618
tag name: qpushbutton

http://stackoverflow.com/comment/82687250
type: QuestionComment
has text: I'll write an answer because I think I know what you are asking now
comment on: http://stackoverflow.com/q/47860912
score: 1
type: Comment

http://stackoverflow.com/a/47911139
has body: It could be done using closure: def function_aggregator(*func_list): def aggregate(num): for func in reversed(func_list): num = func(num) return num return aggregate if __name__ == "__main__": myfunc = function_aggregator(h, m, n) print(myfunc(4)) Notes function_aggregator now takes an arbitrary number of functions Inside, it defines another function, aggregate, this is the callable you are talking about. function_aggregator returns that callable, AKA aggregate to the caller The caller then give it a name, myfunc in this case From then on, we can treat myfunc as a function which takes 1 argument and return something
answers question: http://stackoverflow.com/q/47907076
score: 0
type: Answer

http://stackoverflow.com/a/49966573
answers question: http://stackoverflow.com/q/47865082
has body: What I did for my research is take a small random sample of those tweets and manually label them as either positive or negative. You can then calculate the normalized scores using VADER or SentiWordNet and compute the confusion matrix for each which will give you your F-score etc. Although this may not be a particularly good test, as it depends on the sample of tweets you use. For example you may find that SentiWordNet classes more things as negative than VADER and thus appears to have the higher accuracy if your random sample are mostly negative.
downvote count: 0
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/82909966
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/47968306
has text: Your program fails on `[1,1,1,1]` too.
type: Comment

http://stackoverflow.com/q/47857141
has answer: http://stackoverflow.com/a/62168167
has body: (i'm on mac os 10.8.5) I'm using Python 3 (through jupyter notebook) and trying to import cv2 I did import cv2 succefully, but when I type im_g = cv2.imread("smallgray.png", 0) I get this error: --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-7-5eb2880672d2&gt; in &lt;module&gt;() ----&gt; 1 im_g = cv2.imread("smallgray.png", 0) AttributeError: module 'cv2' has no attribute 'imread' I also checked dir(cv2) and I get: ['__doc__', '__loader__', '__name__', '__package__', '__path__', '__spec__' I guess a lot of functions are missing... Is it due to a wrong opencv installation ? Actually I struggled a lot to get opencv and I guess I installed it 'too many times' and different ways via Terminal. (brew, pip) Should I uninstall opencv and start over ? How can I do this properly ? Thx in advance
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/73546015
has answer: http://stackoverflow.com/a/77374882
tagged with: python
has answer: http://stackoverflow.com/a/47859122
has answer: http://stackoverflow.com/a/76555293
tagged with: opencv
has title: AttributeError: module 'cv2' has no attribute 'imread'
linked to: http://stackoverflow.com/q/37039224
has answer: http://stackoverflow.com/a/74583416
score: 12
type: Question
has answer: http://stackoverflow.com/a/64386882
has answer: http://stackoverflow.com/a/61923390
has answer: http://stackoverflow.com/a/64668153
has answer: http://stackoverflow.com/a/64658815
has comment: http://stackoverflow.com/comment/119800405
has answer: http://stackoverflow.com/a/64586136
has answer: http://stackoverflow.com/a/71597218
has answer: http://stackoverflow.com/a/54182920
has comment: http://stackoverflow.com/comment/82678506
answer count: 18
has comment: http://stackoverflow.com/comment/82679000
has answer: http://stackoverflow.com/a/65072051
has answer: http://stackoverflow.com/a/63762064
has answer: http://stackoverflow.com/a/72649765
favorite count: 0
has answer: http://stackoverflow.com/a/79012585
upvote count: 12
has answer: http://stackoverflow.com/a/64735915

http://stackoverflow.com/q/47945122
downvote count: 0
tagged with: dask-distributed
has body: I am working on a project that involves some larger-than-memory datasets, and have been evaluating different tools for working on a cluster instead of my local machine. One project that looked particularly interesting was dask, as it has a very similar API to pandas for its DataFrame class. I would like to be taking aggregates of time-derivatives of timeseries-related data. This obviously necessitates ordering the time series data by timestamp so that you are taking meaningful differences between rows. However, dask DataFrames have no sort_values method. When working with Spark DataFrame, and using Window functions, there is out-of-the-box support for ordering within partitions. That is, you can do things like: from pyspark.sql.window import Window my_window = Window.partitionBy(df['id'], df['agg_time']).orderBy(df['timestamp']) I can then use this window function to calculate differences etc. I'm wondering if there is a way to achieve something similar in dask. I can, in principle, use Spark, but I'm in a bit of a time crunch, and my familiarity with its API is much less than with pandas.
answer count: 1
favorite count: 0
tagged with: dask
upvote count: 1
tagged with: python
type: AnsweredQuestion
has title: How to perform time derivatives in Dask without sorting
score: 1
has answer: http://stackoverflow.com/a/47945390
type: Question
accepted answer: http://stackoverflow.com/a/47945390

http://stackoverflow.com/comment/82886885
has text: Answers are getting standards. This is the sort of answers SO expects.
score: 1
comment on: http://stackoverflow.com/a/47958825
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/82713102
has text: @AlexZisman - We're trying to estimate the average difference when Model 1 underpredicts Model 2.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47872305
score: 0

http://stackoverflow.com/comment/82887835
comment on: http://stackoverflow.com/q/47959140
score: 0
type: Comment
type: QuestionComment
has text: @JohnZwinck the minEnclosing circle.

http://stackoverflow.com/comment/82773964
has text: I think I get how it works but I get following error "ValueError: invalid literal for int() with base 10:" I think it is because the first word is "REGION" which isn't a number
score: 0
comment on: http://stackoverflow.com/q/47903085
type: Comment
type: QuestionComment

tensorflow-estimator
tags question: http://stackoverflow.com/q/47867748
tag name: tensorflow-estimator
tags question: http://stackoverflow.com/q/47931602
type: Tag

http://stackoverflow.com/comment/82836121
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47933174
has text: It's working, however 'name'(not the variable) is displayed twice for each character. I'm guessing this is because of the double for loop? How can this be prevented?
score: 0

http://stackoverflow.com/comment/82744171
score: 0
type: AnswerComment
type: Comment
has text: @JeffC I think you are pretty much confused and hesitant about using [**`get_attribute`**](https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/WebElement.html) and [**`innerHTML`**](https://www.w3schools.com/jsref/prop_html_innerhtml.asp). Please go through the docs and let me know if you have any Questions.
comment on: http://stackoverflow.com/a/47880127

http://stackoverflow.com/comment/98761638
type: QuestionComment
has text: Or perhaps you can write to separate files during the processing and once all processes are finished combine these files into a single final file?
type: Comment
score: 2
comment on: http://stackoverflow.com/q/47859537

http://stackoverflow.com/comment/83329904
type: AnswerComment
comment on: http://stackoverflow.com/a/47927915
score: 0
type: Comment
has text: `3>&2` makes FD 3 be a copy of FD 2. The inverse -- `2>&3` -- would be redirecting stderr (FD 2) at an FD 3 that isn't actually open.

http://stackoverflow.com/q/47950998
answer count: 2
tagged with: python
has title: Two vectors inside a function
downvote count: 3
has body: I am new on Python. I want to create a function with two vectors inside. I tried like this def twovectors((velocity1,length1),(velocity2,length2)): but I have a message error like SyntaxError: invalid syntax. Please, need help.
has answer: http://stackoverflow.com/a/47951046
tagged with: function
accepted answer: http://stackoverflow.com/a/47951046
score: -3
possible better answer: http://stackoverflow.com/a/47951037
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/47951037
favorite count: 0
type: Question

http://stackoverflow.com/q/48000528
tagged with: list
linked to: http://stackoverflow.com/q/3459098
downvote count: 2
has body: Why does this happen? In [1]: a=[[0]*2]*2 In [2]: a Out[2]: [[0, 0], [0, 0]] In [3]: a[0][0]=1 In [4]: a Out[4]: [[1, 0], [1, 0]] Shouldn't be? In [4]: a Out[4]: [[1, 0], [0, 0]]
has answer: http://stackoverflow.com/a/48000593
type: Question
score: -2
duplicate of: http://stackoverflow.com/q/240178
upvote count: 0
has title: Changing value in list of list python. Why does it change whole row?
answer count: 1
favorite count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/240178
tagged with: python

http://stackoverflow.com/comment/82799782
type: Comment
type: QuestionComment
has text: @FlipperPA, I appreciate the help. I've updated the problem with wsgi.py
comment on: http://stackoverflow.com/q/47895053
score: 0

http://stackoverflow.com/comment/82903525
type: Comment
has text: Script doesn't ask any directory where to put downloaded data set. It just start downloading. Problem is that I had interrupted the download now script try to access that downloaded file that is missing or not completely downloaded, causing run time error and script now doesn't run. `/tmp/imagenet` where is this directory, So I can delete it and data can be re-downloaded.
type: AnswerComment
comment on: http://stackoverflow.com/a/47960873
score: 0

http://stackoverflow.com/a/47924609
type: Answer
has body: Double check whether Python2 used in this project. If so install dependencies using comment pip install -r requirements.txt If Python3+ is used. Create Virtualenv with Python3 using comment virtualenv -p python3 env and install dependencies by pip3 install -r requirements.txt
score: 0
answers question: http://stackoverflow.com/q/47922700

http://stackoverflow.com/comment/82807684
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47919998
has text: Wow, I didn't know that! Thanks! But, alas, it doesn't work with object arrays. I've upated the question.

http://stackoverflow.com/a/47983009
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/103451386
answers question: http://stackoverflow.com/q/47982894
has body: Here's one leveraging np.lib.stride_tricks.as_strided - def random_windows_per_row_strided(arr, W=3): idx = np.random.randint(0,arr.shape[1]-W+1, arr.shape[0]) strided = np.lib.stride_tricks.as_strided m,n = arr.shape s0,s1 = arr.strides windows = strided(arr, shape=(m,n-W+1,W), strides=(s0,s1,s1)) return windows[np.arange(len(idx)), idx] Runtime test on bigger array with 10,000 rows - In [469]: arr = np.random.rand(100000,100) # @Psidom's soln In [470]: %timeit select_random_windows(arr, window_size=3) 100 loops, best of 3: 7.41 ms per loop In [471]: %timeit random_windows_per_row_strided(arr, W=3) 100 loops, best of 3: 6.84 ms per loop # @Psidom's soln In [472]: %timeit select_random_windows(arr, window_size=30) 10 loops, best of 3: 26.8 ms per loop In [473]: %timeit random_windows_per_row_strided(arr, W=30) 100 loops, best of 3: 9.65 ms per loop # @Psidom's soln In [474]: %timeit select_random_windows(arr, window_size=50) 10 loops, best of 3: 41.8 ms per loop In [475]: %timeit random_windows_per_row_strided(arr, W=50) 100 loops, best of 3: 10 ms per loop
has comment: http://stackoverflow.com/comment/83115273
accepted answer of: http://stackoverflow.com/q/47982894
type: Answer
has comment: http://stackoverflow.com/comment/85114573
upvote count: 9
score: 9

http://stackoverflow.com/comment/82832361
has text: @Nyxynyx that isn't the question. The question is why create a class with only classmethods? That doesn't make much sense. Why not just a module? Why not normal methods?
comment on: http://stackoverflow.com/q/47931700
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/q/47876274
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47876554
has body: I'm trying to do a simple music player. I want ask some questions to the user while he is listening the music. In next lines, if the user doesn't want to listen again to the music, I will add a list of music and make him choose, and, in the future, I want put some commands for skip to the next music and something about that. P1 = str(input('wanna again? (Y/N)')) def DEF1(): if P1 == ('Y'): P2 = str(input('do you know what is it? (Y/N)')) if P2 == ('Y'): P3 = str(input('what is it?')) print(P3) if P2 == ('N'): print('this is a game sound!') if P1 == ('N'): print('that is it') def DEF2(): while: playsound.playsound('', True) #a music link if __name__ == '__main_': Process(target=DEF1).start() Process(target=DEF2).start() The thing is: i want to start two process (DEF1 and DEF2) at the same time , it's a 'while' and a 'if' function, DEF1 it's some questions that i want to do for the user of the program, and DEF2 it's a music that repeat if the 'while
tagged with: multiprocessing
type: Question
tagged with: if-statement
has title: multiprocess in python for two different function
tagged with: python-multiprocessing
score: 0
has answer: http://stackoverflow.com/a/47876554
answer count: 1
has comment: http://stackoverflow.com/comment/82719729
has comment: http://stackoverflow.com/comment/82718252
tagged with: while-loop
has comment: http://stackoverflow.com/comment/82748252
tagged with: python

http://stackoverflow.com/q/47892964
has comment: http://stackoverflow.com/comment/82752837
type: UnansweredQuestion
has body: I've been doing some research on this matter but could not find a proper solution. python by default is preinstalled on Mac OS. I'm currently trying to run python 3.6 and above, but when I am using Django and creating a new virtual environment, it is referencing python 2.7. I have downloaded the newest version of python, but that does not seem to overwrite python 2.7. I believe the issue has to do with the default path of python on Macs. How would I go and change that path so that when I create a virtual environment and when I use the Django framework, it will reference python 3.6 instead of python 2.7 ?
has comment: http://stackoverflow.com/comment/82752627
answer count: 0
has comment: http://stackoverflow.com/comment/82753611
type: Question
has title: Changing Default python path on Mac OS
tagged with: python
tagged with: macos
score: 0
tagged with: django

http://stackoverflow.com/comment/82757404
type: QuestionComment
has text: `a.sort()` then `a.reverse()` is dumb. Better do: `a.sort(reverse=True)`
comment on: http://stackoverflow.com/q/47895267
score: 0
type: Comment

http://stackoverflow.com/q/47858623
has comment: http://stackoverflow.com/comment/82713332
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/82702643
has title: QPushButton with transparent background
type: Question
tagged with: qpushbutton
has answer: http://stackoverflow.com/a/63441983
answer count: 2
tagged with: pyqt
downvote count: 0
has body: How to do transparent background in QPushButton? I have a background picture and I want to make the button transparent. I tried to use: reg_screen_var.new_account.setStyleSheet("QPushButton {color: #F6F6F6; background: transparent}") and: reg_screen_var.new_account.setAttribute(Qt.WA_TranslucentBackground, True) But I get this result: I'm using Ubuntu 16.04. full code: from PyQt5.QtWidgets import (QApplication, QWidget, QLabel, QLineEdit, QPushButton) from PyQt5.QtGui import (QPixmap, QFont, QMouseEvent) from PyQt5.QtCore import (Qt, QEvent, pyqtSignal, QCoreApplication, QObject) import sys app = QApplication(sys.argv) root = QWidget() class RegisterScreenVar(): def __init__(self): self.drop_logo = QLabel(root) self.drop_png = QPixmap("images/DropMeLogo.png") self.login_but = QLabel(root) self.login_but_img = QPixmap("images/Login_but.png") self.login_lab = QLabel('Login', root) self.pas_lab = QLabel('Password', root) self.login_box = QLineEdit(root) self.reg_box = QLineEdit(root) self.new_account = QPushButton("Don't have an account?", root) reg_screen_var = RegisterScreenVar() def drop_me(): def register_screen(reg_screen_var, root, app): # design of register screen root.resize(1280, 720) root.move(400, 200) root.setWindowTitle('Drop_Me') root.setStyleSheet('background-image: url(images/reg_back.png);') reg_screen_var.login_but.setPixmap(reg_screen_var.login_but_img) reg_screen_var.login_but.setAttribute(Qt.WA_TranslucentBackground, True) reg_screen_var.login_but.move(520, 500) reg_screen_var.drop_logo.setPixmap(reg_screen_var.drop_png) reg_screen_var.drop_logo.setAttribute(Qt.WA_TranslucentBackground, True) reg_screen_var.drop_logo.move(370, 0) reg_screen_var.login_lab.setFont(QFont("OpenSans-Regular", 20, QFont.Bold)) reg_screen_var.login_lab.setStyleSheet('QLabel {color: #F6F6F6}') reg_screen_var.login_lab.setAttribute(Qt.WA_TranslucentBackground, True) reg_screen_var.login_lab.move(580, 230) reg_screen_var.pas_lab.setFont(QFont("OpenSans-Regular", 20, QFont.Bo…
favorite count: 0
tagged with: transparency
has answer: http://stackoverflow.com/a/69961633
has comment: http://stackoverflow.com/comment/82713026
has comment: http://stackoverflow.com/comment/82712879
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82683310
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/82683142
has comment: http://stackoverflow.com/comment/82683446

http://stackoverflow.com/q/48010423
tagged with: python
has comment: http://stackoverflow.com/comment/82989718
has comment: http://stackoverflow.com/comment/82989347
linked to: http://stackoverflow.com/q/15559435
has title: How to create a triangle made of asterisk characters?
has body: I am trying to print a triangle made of asterisk (*) separated by spaces. If n = 4, it should look like: * * * * * * * * * * This is the code I have: n = 4 for i in range(1, n + 1): for j in range(i): print("*") This is the result I get: * * * * * * * * * * I would very appreciate what is wrong with my code...
duplicate of: http://stackoverflow.com/q/15559435
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48010507
upvote count: 0
has comment: http://stackoverflow.com/comment/82989444
score: -1
answer count: 3
has answer: http://stackoverflow.com/a/48010482
favorite count: 0
has answer: http://stackoverflow.com/a/48010478
type: UnansweredQuestion

http://stackoverflow.com/comment/82740130
type: QuestionComment
has text: @agentp well it doesn't matter what language; I don't understand what do you mean by grep NVSS file.txt>out.txt , Could you please explain more
score: 0
comment on: http://stackoverflow.com/q/47882420
type: Comment

http://stackoverflow.com/comment/82930802
has text: @DanixDanilovic In that case you could use: `df.groupby(list(df.columns),as_index=False).size().reset_index()` which is more generic.
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/47980919

http://stackoverflow.com/q/47949810
has title: Summing values in nested dictionary
has answer: http://stackoverflow.com/a/47951279
has answer: http://stackoverflow.com/a/47949868
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47949843
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82869428
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/47949863
tagged with: sum
has comment: http://stackoverflow.com/comment/82869317
has answer: http://stackoverflow.com/a/47949859
has answer: http://stackoverflow.com/a/47949945
has comment: http://stackoverflow.com/comment/82869636
has body: Sorry, I did not state my question clearly. I have a variable x that I keep iterating over and I want to include x and its corresponding sub- dictionary in a dictionary. For example, x represents bus station number. Bus station number 6 might have a distance of value1 from the bus starting station and a distance of variable2 from the bus' last station. Since I don't know what bus station I am in at any given time, I don't have all the info in a dictionary. I want to start with an empty dictionary and update the different station distance information iteratively. d1={} d1 = {1: {'a': variable1, 'b': variable2}, 2: {'a': variable3, 'b': variable4}} I want to insert a key:value pair of 'c': 'value' to d1 as shown below by adding the values in the sub dict (the sum of the values of 'a' and 'b'). d1= {1: {'a': 11, 'b': 22, 'c': 'value'}, 2: {'a': 456, 'b': 789, 'c': 'value'}} I want the value for each 'c' of the bus station to be value = variable1 + variable2 value = variable3 + variable4 I hope I have clarified my question a little better now. It's my very first question on stackoverflow and I don't think I worded my question clearly. Thank you for your responses.
downvote count: 0
answer count: 7
favorite count: 0
has answer: http://stackoverflow.com/a/47949879

http://stackoverflow.com/a/47967965
accepted answer of: http://stackoverflow.com/q/47967956
answers question: http://stackoverflow.com/q/47967956
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: In the latter the second index is over the last element. l = [1,2,3] l[0:100] =&gt; [1,2,3]
upvote count: 1
score: 1

http://stackoverflow.com/a/47864392
has comment: http://stackoverflow.com/comment/82694118
has comment: http://stackoverflow.com/comment/82693907
answers question: http://stackoverflow.com/q/47864339
accepted answer of: http://stackoverflow.com/q/47864339
has comment: http://stackoverflow.com/comment/82693788
type: AcceptedAnswer
downvote count: 0
has body: For sure its easier for line in search : if line.endswith(';\n'): print(line) And as @IMCoins noted it's better to use context manager with to close your file when you're done working: with open("Test.txt","r") as test_file: for line in test_file: if line.endswith(';\n'): print(line)
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/82693842
upvote count: 2

http://stackoverflow.com/q/47970128
tagged with: masked-array
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47970482
type: Question
answer count: 1
score: 0
has body: I am trying to select a subset of a larger grid to perform a finite element analysis to iterate over between two arrays; a masked array and an unmasked array but i have come across a problem of NaNs appearing from the mask when using np.arrays. I originally used masks here to try to avoid NaN issues including NaN == NaN (False) etc... but the mask itself seems to be creating NaNs when used with np.arrays! coordinate arrays to iterate over: array = np.array(list(np.arange(5))*5).reshape(5,5) big_array = np.array([array,array,array]) apply masks on the coordinate arrays: mask1 = np.ma.masked_array(big_array, mask = (big_array&gt;2)) mask2 = np.ma.masked_array(big_array, mask = (big_array&gt;3)) iterate over the coordinate arrays for the masked vs. unmasked comparison: for i in range(5): for j in range(5): array_group = np.array([ big_array[0,i,j], big_array[1,i,j] ]) array_group2 = np.array([ mask1[0,i,j], mask2[1,i,j] ]) print array_group ^^no NaNs from array_group but.. ^^^ print array_group2 NaNs appear for the masked array_group2 here
has answer: http://stackoverflow.com/a/47970482
tagged with: nan
has title: Python masked arrays producing NaNs with np.array
tagged with: python

http://stackoverflow.com/q/47902323
has comment: http://stackoverflow.com/comment/82771764
has comment: http://stackoverflow.com/comment/82771788
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82771733
has answer: http://stackoverflow.com/a/47903096
downvote count: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82771772
tagged with: arrays
has comment: http://stackoverflow.com/comment/82771828
score: 0
accepted answer: http://stackoverflow.com/a/47903096
has title: numpy "extend/append" ndarray
answer count: 1
tagged with: append
favorite count: 0
has body: The problem: I have a numpy array tf = numpy.full((500, 4, 1, 2), [500, 1]) tf : array([[[[ 500., 1.]], [[ 500., 1.]], [[ 500., 1.]], [[ 500., 1.]]], ..., [[[ 500., 1.]], [[ 500., 1.]], [[ 500., 1.]], [[ 500., 1.]]]]) tf.shape : (500, 4, 1, 2) Consider the first group: tf[0][0] this is : array([[ 500., 1.]]) I need to be able to append (in place) additional values say [[100, 0.33], [1, 0.34], [15, 0.33]] so that the end result looks like (this operation is carried out for each of the elements): tf : array([[[[ 500., 1.], [100., 0.33], [1., 0.34], [15., 0.33]], [[ 500., 1.]], [[ 500., 1.]], [[ 500., 1.]]], ..., [[[ 500., 1.]], [[ 500., 1.]], [[ 500., 1.]], [[ 500., 1.]]]]) I tried numpy.concatenate((tf[0][0], [[100, 0.33]]), axis = 0) this returns a new appended ndarray, but I cannot assign it back to tf[0][0] as it fails with the following error. ValueError: could not broadcast input array from shape (2,2) into shape (1,2) Is there any other way to achieve what I want using numpy? ========================================================== Inefficient list way of doing it: # initialization tf = [[[]] for i in xrange(500)] for i in xrange(500): tf[i] = [[] for a in xrange(4)] for j in xrange(4): tf[i][j].append([500, 1.0]) # usage: (for any 0 &lt; i &lt; 500; 0 &lt; j &lt; 4 ) tf[i][j].append([100, 0.33]) but this is inefficient (considering I need to do this over a million times)
has comment: http://stackoverflow.com/comment/82771855
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82772437

http://stackoverflow.com/comment/82760226
type: Comment
has text: [PEP 8 -- Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/). `import *` is not prefered because you get all functions in the same `"name space"`. if you import other module which has class/method with the same name then you override first version and you don't have access to it. For example: `tkinter has `tkinter.Button` and `tkinter.ttk.Button` - if you import `tkinter` and `ttk` using `*` then you have access only to one of this buttons.
type: AnswerComment
comment on: http://stackoverflow.com/a/47896362
score: 0

http://stackoverflow.com/q/47861726
has answer: http://stackoverflow.com/a/47862533
upvote count: 1
type: Question
tagged with: google-cloud-datalab
tagged with: google-bigquery
tagged with: sql
downvote count: 0
answer count: 1
favorite count: 0
has body: I am trying to use the Google Datalab - BigQuery magic command to insert data into a BigQuery table via the datalab notebook. When I run this code it works fine with the data appearing in the table correctly; INSERT mydataset.sampletable (word, count) VALUES('testing', 7) However, I would like to have the string 'testing' and number 7 in their own variables, which I would then insert into BQ. I have set: test = 'testing' size = 7 and then I try to run %%bq query INSERT mydataset.sampletable (word, count) VALUES (test, size) This results in an error message: "invalidQuery: Unrecognized name: test at [2:9]" How can I go about utilizing my variables within an SQL function? Thanks,
tagged with: python
accepted answer: http://stackoverflow.com/a/47862533
tagged with: jupyter-notebook
type: AnsweredQuestion
score: 1
has title: Datalab to BigQuery - Inserting variable values into SQL

http://stackoverflow.com/q/47856842
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/82685959
answer count: 0
type: UnansweredQuestion
has body: How to prevent scrapy crawler same items with different filter order like: to use only the default order
tagged with: web-scraping
tagged with: scrapy
has comment: http://stackoverflow.com/comment/82686526
type: Question
has title: How to exclude ORDER BY filter with Scrapy to prevent crawl too many pages?
has comment: http://stackoverflow.com/comment/82678091
has comment: http://stackoverflow.com/comment/82678169
tagged with: data-science

http://stackoverflow.com/a/47957159
type: Answer
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47957134
answers question: http://stackoverflow.com/q/47957134
has body: You get: &gt;&gt;&gt; 'S' and 'v' 'v' and only check for v not S. You need to check for both: if ('S' not in valuesDict.keys()) and ('v' not in valuesDict.keys()): Example: &gt;&gt;&gt; 'S' and 'v' not in 'xS' # equivalent to: 'v' not in 'xS' True &gt;&gt;&gt; ('S' not in 'xS') and ('v' not in 'xS') False

http://stackoverflow.com/q/48011393
tagged with: numpy
upvote count: 15
possible better answer: http://stackoverflow.com/a/48014372
answer count: 3
has answer: http://stackoverflow.com/a/48014372
downvote count: 0
favorite count: 0
tagged with: cx-freeze
has body: I have a complicated image processing script that runs in python with Numpy and OpenCV. I want to run this script in Android but I couldn't find a way to do it. After some research I found some frameworks that may help but I have some problems with them: Kivy only generates full APK, but what I need is an AAR or some background service so I could use it from other apps QPython only runs scripts, I didn't find a way to communicate with it from my app cxfreeze I've tried to generate executable out of my script and then running it from my app, but I couldn't find a way to compile my script to an ARM processor so Android would be able to execute it I will be happy to hear some ideas on how to run this script in Android. Is it possible to maybe root the device and install Python, Numpy and OpenCV?
has answer: http://stackoverflow.com/a/48317366
tagged with: android
tagged with: python
tagged with: kivy
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/47981791
has answer: http://stackoverflow.com/a/60173128
has title: Running python script with Numpy and OpenCV on Android
type: Question
accepted answer: http://stackoverflow.com/a/48317366
score: 15

http://stackoverflow.com/comment/82823357
score: 0
type: Comment
has text: Try defining `whichNum = None` outside all functions and then add `global whichNum` to all functions as the first line.
type: QuestionComment
comment on: http://stackoverflow.com/q/47926987

http://stackoverflow.com/a/47906996
accepted answer of: http://stackoverflow.com/q/47906792
type: Answer
has comment: http://stackoverflow.com/comment/82782274
has body: You can get num_entries from the root of your xml by: tree = ET.ElementTree(file=filename) root = tree.getroot() print(root.attrib.get('num_entries')) ^ The above method will parse all tree at once, which is no good. How about enabling start event? for event, elem in ET.iterparse(filename, events=('start', 'end')): if elem.tag == 'data' and event == 'start': print(elem.attrib['num_entries']) if elem.tag == 'item' and event == 'start': items.append(float(elem.attrib['value'])) elem.clear()
upvote count: 4
has comment: http://stackoverflow.com/comment/82781245
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47906792
score: 4

http://stackoverflow.com/comment/82921316
score: 0
type: QuestionComment
has text: https://github.com/kychanbp/HSF-Forms-Generation You can also check the original codes here. Form B.ipynb. And the tex file is inside template (Form b)
type: Comment
comment on: http://stackoverflow.com/q/47973663

http://stackoverflow.com/q/47942901
has comment: http://stackoverflow.com/comment/82855446
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/82855994
answer count: 1
has title: Module import error in virtualenv but pip list --local shows it
has comment: http://stackoverflow.com/comment/82855370
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/82857387
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47944369
score: 0
has body: I'm wondering about the following importError which I can't get ride off. I have a local virtualenv (venv) in which I've installed multiple modules: (venv) stam@stam:~$ pip list --local cryptography (1.5.2) cvxopt (1.1.9) cycler (0.10.0) Cython (0.25.1) matplotlib (1.5.3) more-itertools (2.2) ndg-httpsclient (0.4.2) numpy (1.11.2) pandas (0.19.0) paramiko (1.15.2) Pillow (2.8.1) pip (8.1.2) psycopg2 (2.6) python-apt (0.9.3.12) python-dateutil (2.5.3) python-debian (0.1.27) scipy (0.18.1) setuptools (28.6.1) simplejson (3.8.2) urllib3 (1.9.1) wheel (0.24.0) You are using pip version 8.1.2, however version 9.0.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. (venv) stam@stam:~$ now starting a python interpreter and trying to import cvxopt (note it is in the list above) gives me a importError. Why is this? I'm using the right python version, I work on the venv so everything should work out of the box. (venv) stam@stam:~$ python Python 2.7.9 (default, Aug 13 2016, 16:41:35) [GCC 4.9.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import cvxopt Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named cvxopt &gt;&gt;&gt; I'm a bit lost and don't know how exactly I can resolve this issue. It seems the right python version is started, at least the one I've attached to the virtualenv. Additional outps asked for in the comments (venv) stam@stam:~$ which python /usr/bin/python (venv) stam@stam:~$ which pip /usr/local/bin/pip
has comment: http://stackoverflow.com/comment/82855628
type: Question
accepted answer: http://stackoverflow.com/a/47944369
has comment: http://stackoverflow.com/comment/82857937
has comment: http://stackoverflow.com/comment/82858857

http://stackoverflow.com/comment/82915573
comment on: http://stackoverflow.com/q/47972832
score: 0
has text: Having said that these routines are stress tested for decades now so it's very very unlikely that they choke on this array. Can you post the np.array version of this?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47936584
has title: What does "Client failed to connect to the D-BUS daemon" mean?
score: 17
favorite count: 0
tagged with: jenkins
type: Question
has comment: http://stackoverflow.com/comment/82843861
tagged with: python
has answer: http://stackoverflow.com/a/48109518
has comment: http://stackoverflow.com/comment/82845130
has comment: http://stackoverflow.com/comment/82844551
has answer: http://stackoverflow.com/a/48089986
tagged with: selenium
has comment: http://stackoverflow.com/comment/82846481
upvote count: 17
answer count: 4
has answer: http://stackoverflow.com/a/79043620
has comment: http://stackoverflow.com/comment/83143055
accepted answer: http://stackoverflow.com/a/48109518
possible better answer: http://stackoverflow.com/a/54772878
has comment: http://stackoverflow.com/comment/82846521
has answer: http://stackoverflow.com/a/54772878
has body: I am using a very complex setup to test various non-public webpages. I use jenkins to run the python-selenium tests within a dockerimage. That way, I am completely independent of the jenkins environment and can create my own environment. In this environment I have the following software installed: Ubuntu 16.04.3 Firefox: Mozilla Firefox 57.0.1 geckodriver: 0.18.0 nosetests: 1.3.7 selenium: 3.8.0 When running the tests, which mostly succeed, I see in the geckodriver.log output messages like (firefox:55): GConf-WARNING **: Client failed to connect to the D-BUS daemon: /usr/bin/dbus-launch terminated abnormally without any error message My questions: What does this message mean? Could that be an indication of the reason why sometimes the tests are failing? If so, how to fix it?
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/46088442
downvote count: 0
has comment: http://stackoverflow.com/comment/82843595
linked to: http://stackoverflow.com/q/48079120

http://stackoverflow.com/a/47979603
type: Answer
upvote count: 12
downvote count: 0
score: 12
answers question: http://stackoverflow.com/q/47979390
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47979390
has body: After you run your init. Open the env.py file and update context.configure, add version_table='alembic_version_your_name as a kwarg.

http://stackoverflow.com/q/47970063
upvote count: 1
tagged with: python
score: 1
has title: Peewee ArrayField error
type: Question
tagged with: peewee
has answer: http://stackoverflow.com/a/48212163
answer count: 1
downvote count: 0
has body: When I create my table based on a model without an ArrayField, I get no errors. When I add: images = ArrayField(CharField) I get: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python3.6/site-packages/peewee.py", line 5037, in create_table db.create_table(cls) File "/usr/local/lib/python3.6/site-packages/peewee.py", line 3914, in create_table return self.execute_sql(*qc.create_table(model_class, safe)) File "/usr/local/lib/python3.6/site-packages/peewee.py", line 3837, in execute_sql self.commit() File "/usr/local/lib/python3.6/site-packages/peewee.py", line 3656, in __exit__ reraise(new_type, new_type(*exc_args), traceback) File "/usr/local/lib/python3.6/site-packages/peewee.py", line 135, in reraise raise value.with_traceback(tb) File "/usr/local/lib/python3.6/site-packages/peewee.py", line 3830, in execute_sql cursor.execute(sql, params or ()) peewee.OperationalError: near "[]": syntax error Can anyone point out why and provide a solution?
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/82934554
has text: Why was I able to do it on the command line then? What changed?
score: 0
comment on: http://stackoverflow.com/q/47982967
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47972619
has title: Best place to update related fields via django-import-export
accepted answer: http://stackoverflow.com/a/47972697
has body: In our project, we have to import and export complicated models in *.xls and other formats. django-import-export great tool and helped us. I wrote a lot of code for creating/editing related models vie additional meta fields (two or three levels in deep). I used import_row, import_field, before_import_row and others methods in our base ModelResource. And now I have little trouble where to place the code for simple logic. We want to update related object's field. For example: class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): author = models.OneToOneField(Author) I want to export and import (update) author__name via book resource. I tried to write Widget for this field but it wasn't a good idea. Give me an example how to export end import author__name from BookResource in right way, please.
answer count: 1
downvote count: 0
score: 1
favorite count: 0
tagged with: django-import-export
tagged with: django
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47972697
upvote count: 1
type: Question

http://stackoverflow.com/comment/139096107
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/58684066
score: 1
has text: This doesn't seem to work for me: I get `<generator object iter_modules at 0x000001CB8AD15580>`. Maybe they changed it in python 3.12?

http://stackoverflow.com/q/48001004
type: Question
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48005030
favorite count: 0
tagged with: python-2.7
tagged with: http://stackoverflow.com/tag/csv
has title: Data CSV Dashboard python
accepted answer: http://stackoverflow.com/a/48005030
tagged with: python
downvote count: 1
type: AnsweredQuestion
has body: With help from this foro I can create my Optimizator dashboard. Now, I need to make some changes. This is the code: import csv import datetime with open("prueba.csv", 'rb') as f: reader = csv.reader(f) your_list = list(reader) mydict = {} for row in your_list[1:]: date = datetime.datetime.strptime(row[0],'%d/%m/%Y') name = row[1] mydict[(date,name)] = row[2:] def convert(n): n = n.replace(",",".").replace("%","") try: return float(n) except ValueError: return 0e0 for (day, name) in mydict: previous_day = day - datetime.timedelta(days=1) if (previous_day,name) in mydict: print name, datetime.datetime.strftime(day,"%d/%m/%Y") day2_values = mydict[(day, name)] day1_values = mydict[(previous_day, name)] comparer = zip(day2_values, day1_values) for n,value in enumerate(comparer): print "item[%d]:" % (n+2,), if convert(value[1]) &lt; convert(value[0]): print value[1], "smaller than", value[0], "Incremento" else: print value[1], "bigger than", value[0], "Descenso" print &gt;&gt;&gt; Martin 18/12/2017 item[2]: 312341 smaller than 349805 Incremento item[3]: 45368 smaller than 46818 Incremento item[4]: 14.53% bigger than 13.38% Bajada item[5]: 39.35 bigger than 32.98 Bajada item[6]: 0.87 bigger than 0.70 Bajada Jose 11 03/12/2017 item[2]: 140580 smaller than 161540 Incremento item[3]: 4943 bigger than 4663 Bajada item[4]: 3.52% bigger than 2.89% Bajada item[5]: 2.04 bigger than 1.95 Bajada item[6]: 0.41 smaller than 0.42 Incremento Jorge cl 17/12/2017 item[2]: 156736 smaller than 164272 Incremento item[3]: 39295 bigger than 36921 Bajada item[4]: 25.07% bigger than 22.48% Bajada item[5]: 19.74 bigger than 19.61 Bajada item[6]: 0.50 smaller than 0.53 Incremento I need to change the returns items[2],items[3],items[4],items[5] and items[6] for the real names : [['"Fecha"', '"Cliente"', '"Subastas"', '"Impresiones_exchange"', '"Fill_rate"', '"Importe_a_pagar_a_medio"', '"ECPM_medio"'] Also, I need to save the returns in a csv file order by Cliente name. Is it possible??
score: -1

http://stackoverflow.com/q/47993418
has answer: http://stackoverflow.com/a/47993564
has comment: http://stackoverflow.com/comment/82955287
has comment: http://stackoverflow.com/comment/82955259
type: Question
tagged with: algorithm
has body: def quicksort(mas): if mas: mid = mas[0] menshe = [i for i in mas[1:] if i &lt; mid] bolshe = [i for i in mas[1:] if i &gt;= mid] return quicksort(menshe) + [mid] + quicksort(bolshe) else: return mas n = int(input()) mas = input().split() print(*quicksort(mas)) It fails on some tests, for example input: 3 8 21 22 output: 21 22 8 how to improve the code?
tagged with: sorting
has answer: http://stackoverflow.com/a/47993567
accepted answer: http://stackoverflow.com/a/47993567
answer count: 2
downvote count: 2
favorite count: 0
upvote count: 5
possible better answer: http://stackoverflow.com/a/47993564
tagged with: python
has title: Quicksort Python sorting trouble
tagged with: quicksort
type: AnsweredQuestion
score: 3

http://stackoverflow.com/a/47945517
has body: The idea is that you go through you validation set after each epoch, not after each batch. If after every batch, you had to evaluate the performances of the model on the whole validation set, you would loose a lot of time. After each epoch, you will have the corresponding losses and accuracies both for training and validation. But during one epoch, you will only have access to the training loss and accuracy.
score: 10
upvote count: 11
answers question: http://stackoverflow.com/q/47930176
has comment: http://stackoverflow.com/comment/82862624
downvote count: 1
has comment: http://stackoverflow.com/comment/82861649
type: Answer

http://stackoverflow.com/a/50285418
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47963554
score: 0
answers question: http://stackoverflow.com/q/47963554
type: Answer
has body: Kitt.ai provides 'Snowboy', a hotword detection engine which serves that purpose. You may trigger the speech recognition after the hotword is detected and it's pretty accurate too and it exactly fits this use-case. Best of all, it runs offline. You can set your code to run, after getting triggered by the hotword. Check it out: https://snowboy.kitt.ai

http://stackoverflow.com/comment/82942866
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47986319
has text: @user3599127 I don't understand your question. If your words are not separated by commas, they are implicitly treated as a single word.

http://stackoverflow.com/q/47888605
upvote count: 0
answer count: 1
has title: Python 3.x - Python Tkinter
has comment: http://stackoverflow.com/comment/82743403
favorite count: 0
tagged with: tkinter
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82749943
score: -3
has body: I'm trying to create a miner game, but it crashes everytime. Can you help me? Here is my code: def refill(event): for i in everything: c.delete(i) # This is the 'Delete' statement time.sleep(0.01) global x2 global y2 for i in range(10): # This is the 'Create' statement for i in range(10): if random.randint(1, IRON_CHANCE) != 1: stone = c.create_rectangle(x2, y2, x2 + 50, y2 + 50, fill='dim gray') everything.append(stone) y2 += 50 if random.randint(1, IRON_CHANCE) == 1: ironStone = c.create_rectangle(x2, y2, x2 + 50, y2 + 50, fill='dim gray') ironRect = c.create_rectangle(x2 + 10, y2 + 10, x2 + 40, y2 + 40, fill='ivory') irons.append(ironRect) everything.append(ironStone) everything.append(ironRect) y2 += 50 time.sleep(0.01) x2 += 50 y2 = 0 time.sleep(0.01) I think the problem is in the 'Create' state. If I delete that state, the game works smooth and fine. Can you please help me?
tagged with: python
downvote count: 3
type: Question
tagged with: crash
has comment: http://stackoverflow.com/comment/82744985
has answer: http://stackoverflow.com/a/47895548

http://stackoverflow.com/comment/82919359
has text: I've used this a couple of times before (looking at your posts), and `np.char.find` also works, I think.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/47975036
type: Comment

matplotlib-venn
tag name: matplotlib-venn
tags question: http://stackoverflow.com/q/47985623
type: Tag

http://stackoverflow.com/comment/82885886
score: 0
has text: Help me understand, whats wrong with that ?
comment on: http://stackoverflow.com/q/47957959
type: Comment
type: QuestionComment

http://stackoverflow.com/a/68247990
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47969756
downvote count: 0
has body: I believe can achieve similar results to @Federico Dorato answer without use of for loop. Return a list rather than a series and use lambda-apply + to_list() to expand results. It's cleaner code and on a random df of 10,000,000 rows performs as well or faster. Federico's code run_time = [] for i in range(0,25): df = pd.DataFrame(np.random.randint(0,10000000,size=(2, 2)), columns=list('AB')) def run_loopy(df): Cs, Ds = [], [] for _, row in df.iterrows(): c, d, = myfunc1(row['A']) Cs.append(c) Ds.append(d) return pd.Series({'C': Cs, 'D': Ds}) def myfunc1(a): c = a / 10 d = a + 50 return c, d start = time.time() df'C', 'D' = run_loopy(df) end = time.time() run_time.append(end-start) print(np.average(run_time)) # 0.001240386962890625 Using lambda and to_list run_time = [] for i in range(0,25): df = pd.DataFrame(np.random.randint(0,10000000,size=(2, 2)), columns=list('AB')) def myfunc1(a): c = a / 10 d = a + 50 return [c, d] start = time.time() df'C', 'D' = df['A'].apply(lambda x: myfunc1(x)).to_list() end = time.time() run_time.append(end-start) print(np.average(run_time)) #output 0.0009996891021728516

http://stackoverflow.com/q/47914178
favorite count: 0
has answer: http://stackoverflow.com/a/47914434
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82797942
type: AnsweredQuestion
tagged with: recursion
has title: python performing recursion on rows in df
score: 1
tagged with: rows
accepted answer: http://stackoverflow.com/a/47914434
type: Question
downvote count: 0
has body: I want to perform the following calculations with my df. I've done this in Excel but I'm not sure how to do this using Python. Here's the calculation initial| recursion begins Name | 1 | 2 | 3 | 4 ... ------------------------------------------------ A | A1 | A2 | A3 | A4 &lt;--given a | a1=0 | a2=c1*A2 | a3=c2*A3 | a4=c3*A4 &lt;--calculation (1st cell always = 0) c | c1=1 | c2=c1-a2 | c3=c2-a3 | c4=c3-a4 &lt;--calculation (1st cell always 1) Here's my example: df Name 1 2 3 4 5 ---------------------------------- A 0 .125 .286 .25 .333 B 0 0 0 .5 - the output would be: Name 1 2 3 4 5 ---------------------------------- A 0 .125 .286 .25 .333 Ax 0 .125 .25 .156 .156 Ay 1 .875 .625 .469 .313 B 0 .1 0 .25 - Bx 0 .1 0 .225 - By 1 .9 .9 .675 - Thank you!
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/82796428

http://stackoverflow.com/comment/82937717
comment on: http://stackoverflow.com/a/47984291
has text: @MiguelLuís this is a different issue now. Please accept the answer & move on with debugging the rest of your code.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/47983928
type: Answer
has body: Dictionary keys in Python do not guarantee order. You can see this SO post for more details: Python dictionary, how to keep keys/values in same order as declared?. There are ways to do it, and depending on what version of Python you are using, it might be different. If you just want to print the items in order, there is an easy way to manage it using the json library. import json ordered = {v['name']: sorted([i['name'] for i in v['cities']]) for v in locations.values()} json.dumps(ordered, sort_keys=True) This will print the following result: { "Austria": [ "Gramatneusiedl / Vienna", "Home Office", "Lenzing", "Schoerfling", "Weissenstein" ], "Belgium": [ "Antwerp", "Brussels", "Home Office", "Oostende" ] } If you want to maintain order within the dictionary, then use an OrderedDict object. OrderedDicts remember insertion order. So we can sort all of the items based on the value of the name key before creating the final dictionary. from collections import OrderedDict ordered = OrderedDict() # sort each dictionary by their name field sorted_by_country = sorted(locations.values(), key = lambda x:x['name']) for v in sorted_by_country: ordered[v['name']] = sorted([i['name'] for i in v['cities']])
upvote count: 1
has comment: http://stackoverflow.com/comment/82937484
has comment: http://stackoverflow.com/comment/82936940
answers question: http://stackoverflow.com/q/47983699
has comment: http://stackoverflow.com/comment/82936912
downvote count: 0
score: 1

http://stackoverflow.com/comment/82963824
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47973355
score: 0
has text: these are some task @task(queue='ds') def Matar_Task(vsid,vserial): killdb = Matar_Sesion() spk = killdb.mata(vsid,vserial) return None @task(queue='ds') def Correr_Task(vsid,vserial): rundb = Correr() spr = rundb.plsql(vsid,vserial) return None

http://stackoverflow.com/a/47943682
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47941965
answers question: http://stackoverflow.com/q/47941965
type: Answer
has body: If you want to show content to the user before setting up the camera screen, you need to serve the user HTML before setting up the camera screen. It looks like you're trying to accomplish this by calling temp = render(request,'pepper/picture.html') However, that line just creates HTML from the template provided at pepper/picture.html -- it doesn't actually serve that HTML to the user. Typically, you would accomplish this by writing the camera logic in javascript and embedding that javascript in picture.html. If you'd like to keep everything in django / python, then I guess you could accomplish that by splitting takePicture into two views: def picture_without_stream(request): return render(request,'pepper/picture.html') def picture_with_stream(request): camstream() return render(request,'pepper/picture.html') You could initially load picture_without_stream and when it loads, redirect to picture_with_stream. But that's pretty ugly.
score: 0

http://stackoverflow.com/comment/82712095
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47873133
has text: %%capture works like charm! Thanks for the quick answer

http://stackoverflow.com/q/47856393
has comment: http://stackoverflow.com/comment/82691461
has body: i am trying to simulate an M/M/c Queue using SimPy 3 On Python 3.6 it was easy to calculate various performance measures such as service time, waiting time... but i can't seem to find a way to calculate idle time of resources, i've looked in the documentations for SimPy but no luck, please help i've been on this for days i have a feeling i have to extend the Resource class but i just don't know enough Python to get this done arrival = prng.PRNG(50000) service = prng.PRNG(10000) simulation_time = 30.0 service_time = 10.0 arrival_time = 2.5 data = [[], [], [], [], [], [], [], []] data[3].append(0) def source(env, counter): i = 0 while True: i += 1 t = arrival.nextExponential(1.0 / arrival_time) c = customer(env, i, t, counter, service_time) env.process(c) yield env.timeout(t) def customer(env, i, t, counter, service_time): arrive = env.now data[6].append(len(counter.queue)) with counter.request() as req: data[0].append(i) data[1].append(t) data[2].append(arrive) if (len(data[2])) &gt;= 2: n = len(data[2]) - 1 p = n - 1 data[3].append(data[2][n] - data[2][p]) results = yield req wait = env.now - arrive data[5].append(wait) tib = service.nextExponential(1.0 / service_time) data[4].append(round(tib, 2)) data[7].append(wait + tib) yield env.timeout(tib) env = simpy.Environment() counter = simpy.Resource(env, capacity=5) env.process(source(env, counter)) env.run(until=simulation_time) total_wait_time = 0.0 total_time_in_system = 0.0 total_service_time = 0.0 total_interarrival_time = 0.0 print("No.\tArrival Time\tClock Time\tInterarrival Time\tService Time\tWait Time\tQueue Length\tTotal Time In System") def display(i): print() print("Average Waiting Time =&gt; %.2f Minutes" % (total_wait_time / i)) print("Average Service Time =&gt; %.2f Minutes" % (total_service_time / i)) print("Average Time Spent In System =&gt; %.2f Minutes" % (total_time_in_system / i)) print("Average Interarrival Time =&gt; %.2f Minutes" % (total_interarrival_time / i)) for i in range(0, len(data[0]))…
has title: Calculating idle time of resources using simpy?
tagged with: python
answer count: 0
type: UnansweredQuestion
type: Question
tagged with: simpy
score: 0
has comment: http://stackoverflow.com/comment/82707355
has comment: http://stackoverflow.com/comment/82691503

http://stackoverflow.com/comment/84094949
has text: @Gordon Thanks! Okay so I've revised my post. I made edits to my python to read in the data. It seems the error is coming from my `js`. For some reason its not liking that `.setMinutes(0)` is null. My timestamp data is `mm/dd/yyyy hh:mm`. Any idea why the error?
comment on: http://stackoverflow.com/q/47893249
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82871478
type: Comment
has text: `displayOptions` is (presumably) executed twice: once when the page is fetched with `GET`, and again when the user submits a `POST`. If you have code that should only execute in one of those cases, put it underneath an `if` statement checking for a specific method.
score: 1
comment on: http://stackoverflow.com/q/47950991
type: QuestionComment

http://stackoverflow.com/q/47877068
linked to: http://stackoverflow.com/q/45162021
has comment: http://stackoverflow.com/comment/82726583
favorite count: 0
has comment: http://stackoverflow.com/comment/82720004
linked to: http://stackoverflow.com/q/34362922
has comment: http://stackoverflow.com/comment/82721039
answer count: 0
has comment: http://stackoverflow.com/comment/82721829
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/82721110
has body: I am using opencv and want to stick with it. I have 5 images with some common areas in a pairwise manner. I want to merge them together in a single image. I have been successful joining two images together, as they were of the same resolution(a little tweak brought them to the same resolution without distorting the contents significantly). But now this first stage of merging gives me a highly inflated image, the resolution has gone significantly up(kind of an addition of two images). To merge the two images I had brought their resolutions to the same value and it didn't cause much distortion. But now there's this image with double the length. If I change its resolution to the level of the image next in line for stitching, it is going to highly distort the content of the first stage and hence the result from here on. How do I fix this issue given that I need to go through 5-6 iterations of stitching where the resolution is going to keep increasing? Also, if there is any text which goes into details of image processing with examples, like above. Stitcher.py # -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ # import the necessary packages import numpy as np import imutils import cv2 class Stitcher: def __init__(self): # determine if we are using OpenCV v3.X self.isv3 = imutils.is_cv3() def stitch(self, images, ratio=0.75, reprojThresh=4.0, showMatches=False): # unpack the images, then detect keypoints and extract # local invariant descriptors from them (imageB, imageA) = images #(b, g, r) = cv2.split(imageA) #imageA = cv2.merge([r,g,b]) #(b, g, r) = cv2.split(imageB) #imageB = cv2.merge([r,g,b]) (kpsA, featuresA) = self.detectAndDescribe(imageA) (kpsB, featuresB) = self.detectAndDescribe(imageB) # match features between the two images M = self.matchKeypoints(kpsA, kpsB, featuresA, featuresB, ratio, reprojThresh) # if the match is None, then there aren't enough matched # keypoints to create a panorama if M is None: return None # otherwise, a…
tagged with: opencv
score: 1
type: Question
linked to: http://stackoverflow.com/q/45315541
downvote count: 0
has comment: http://stackoverflow.com/comment/82726712
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/82721157
has title: How do I stitch multiple images in a panaroma?
tagged with: python

http://stackoverflow.com/comment/131257879
has text: I had to add `--use-pep517` in addition: ```pip install --no-cache-dir --ignore-installed --compile --install-option="--with-openssl" pycurl --use-pep517```
comment on: http://stackoverflow.com/a/70914890
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/a/47970443
has body: Since the if blocks follow the same logic, except for the source array (Zero, One, ...) and target filename (Zero.png, First.png, etc). You could record this information in a dictionary where keys are labels. For example: dict = { 0: {"source": Zero, "file": "Zero.png"}, 1: {"source": One, "file": "First.png"}, # and so on. } Then, in the loop, you just look up the label using dict.get: data = dict.get(labels[(x, y)]) if data: # data will be None (falsy) if label isn't in the dictionary data["source"][y][x] = int(255) count += 1 if count &lt;= 43: continue elif count &gt; 43: image = Image.fromarray(data["source"]) image.save(os.path.join(dirs, data["file"]), 'png')
answers question: http://stackoverflow.com/q/47969274
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/48000804
score: 4
has answer: http://stackoverflow.com/a/79522710
upvote count: 4
answer count: 2
tagged with: pandas
downvote count: 0
has title: pandas: extrapolate missing values at the tail
favorite count: 0
type: UnansweredQuestion
has body: I have a pandas dataframe df, which has GDP values alsong with yyyy-mm TimePeriod index. import numpy as np import pandas as pd import pandas_datareader.data as web gdp = web.DataReader("GDP", "fred", start, end).resample('M').mean().interpolate(method='linear').round().to_period('M') Date GDP 2015-07 16528.0 2015-08 16534.0 2015-09 16541.0 2015-10 16548.0 2015-11 16556.0 2015-12 16564.0 2016-01 16572.0 2016-02 16602.0 2016-03 16633.0 2016-04 16664.0 2016-05 16702.0 2016-06 16740.0 2016-07 16778.0 2016-08 16803.0 2016-09 16827.0 2016-10 16851.0 2016-11 16869.0 2016-12 16886.0 2017-01 16903.0 2017-02 16946.0 2017-03 16988.0 2017-04 17031.0 2017-05 17075.0 2017-06 17120.0 2017-07 17164.0 2017-08 NaN 2017-09 NaN 2017-10 NaN 2017-11 NaN 2017-12 NaN GDP is published quarterly. The latest data point is 2017 Q3. So I resampled to have monthly values and interpolated when the values were missing. How do I extrapolate to fill up the remaining of the NaN for the rest of the year by using spline or 3 month moving average etc? I have seen some examples using polynomial, but that look like overdoing stuff (pandas extrapolation of polynomial). I was wondering if there is a simpler approach. Thank you!
tagged with: python
has answer: http://stackoverflow.com/a/48000949
type: Question
linked to: http://stackoverflow.com/q/32633944

http://stackoverflow.com/comment/82944087
has text: put `print()` in methods and see which ones are executed. Why do you use `spider_opened` ? Can't you use `'open_spider'` as in [examples](https://docs.scrapy.org/en/latest/topics/item-pipeline.html) ?
comment on: http://stackoverflow.com/q/47987550
score: 0
type: QuestionComment
type: Comment

linux-mint
type: Tag
tags question: http://stackoverflow.com/q/47968370
tag name: linux-mint

http://stackoverflow.com/q/47985717
linked to: http://stackoverflow.com/q/35501137
has comment: http://stackoverflow.com/comment/82940946
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82940565
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/82940719
has comment: http://stackoverflow.com/comment/82941189
has comment: http://stackoverflow.com/comment/82940753
has comment: http://stackoverflow.com/comment/82940678
has comment: http://stackoverflow.com/comment/82940506
tagged with: python
has title: Django rest framework custom response message for different validation
has comment: http://stackoverflow.com/comment/82940597
has comment: http://stackoverflow.com/comment/82940551
favorite count: 0
has comment: http://stackoverflow.com/comment/82940594
has comment: http://stackoverflow.com/comment/82940687
has comment: http://stackoverflow.com/comment/82940835
type: UnansweredQuestion
upvote count: 1
tagged with: django
has answer: http://stackoverflow.com/a/47992965
has comment: http://stackoverflow.com/comment/82940794
has comment: http://stackoverflow.com/comment/82940603
has comment: http://stackoverflow.com/comment/82940640
score: 1
has comment: http://stackoverflow.com/comment/82940477
type: Question
tagged with: response
has body: So I want to create a custom message for the different fail based on the serializer validation. But I was only able to find how to create a standard custom response for success and fail only. Though the only response I want to create is for the failed prompt message. I found one of the posts but it's not really what I wanted for the error code source: Django Rest Framework custom response message Basically, the error message must be based on the specific validation error in serializer.py Here is my code serializer.py class UserCreate2Serializer(ModelSerializer): email = EmailField(label='Email Address') valid_time_formats = ['%H:%M', '%I:%M%p', '%I:%M %p'] birthTime = serializers.TimeField(format='%I:%M %p', input_formats=valid_time_formats, allow_null=True, required=False) class Meta: model = MyUser fields = ['username', 'password', 'email', 'first_name', 'last_name', 'gender', 'nric', 'birthday', 'birthTime', 'ethnicGroup'] extra_kwargs = {"password": {"write_only": True}} def validate(self, data): # to validate if the user have been used email = data['email'] user_queryset = MyUser.objects.filter(email=email) if user_queryset.exists(): raise ValidationError("This user has already registered.") return data # Custom create function def create(self, validated_data): username = validated_data['username'] password = validated_data['password'] email = validated_data['email'] first_name = validated_data['first_name'] last_name = validated_data['last_name'] gender = validated_data['gender'] nric = validated_data['nric'] birthday = validated_data['birthday'] birthTime = validated_data['birthTime'] ethnicGroup = validated_data['ethnicGroup'] user_obj = MyUser( username = username, email = email, first_name = first_name, last_name = last_name, gender = gender, nric = nric, birthday = birthday, birthTime = birthTime, ethnicGroup = ethnicGroup, ) user_obj.set_password(password) user_obj.save() return validated_data views.py class CreateUser2View(CreateAPIView): permission_cla…
linked to: http://stackoverflow.com/q/28197199

web-services
type: Tag
tags question: http://stackoverflow.com/q/47930324
tags question: http://stackoverflow.com/q/47867661
tag name: web-services
tags question: http://stackoverflow.com/q/47995681

http://stackoverflow.com/comment/82877273
type: AnswerComment
comment on: http://stackoverflow.com/a/47953866
type: Comment
score: 1
has text: I think `out = df1.assign(b=np.where(df2['update'].eq(''), df2['b'], df2['update']))` should be fastest

http://stackoverflow.com/comment/82915482
comment on: http://stackoverflow.com/a/47972480
has text: Your first statement is false. `obj.get()` will only work with the Entry widget (and the `*Var` classes). The other widgets that use `get()` need one or more arguments.
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/comment/82883753
comment on: http://stackoverflow.com/q/47957020
has text: Are the indices guaranteed to be in increasing order? Or even strictly increasing?
score: 0
type: Comment
type: QuestionComment

pepper
tags question: http://stackoverflow.com/q/47888476
tag name: pepper
type: Tag

http://stackoverflow.com/comment/82742835
type: QuestionComment
comment on: http://stackoverflow.com/q/47888396
has text: This is (presumably) a NP-Hard problem... good luck...
score: 0
type: Comment

http://stackoverflow.com/comment/82915144
has text: got it. Thank you very much! What if the data contains not just integer 0 but also 0.0? When I run with that data, then the error now is due to the length of 0.0 which is 3 characters. `('ord() expected a character, but string of length 3 found', 'occurred at index 3')`. I used pandas.csv_read() and the types of the data is not properly casted yet.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47972692

http://stackoverflow.com/q/47870251
downvote count: 0
has comment: http://stackoverflow.com/comment/82705524
has comment: http://stackoverflow.com/comment/82706523
favorite count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82706560
tagged with: python
tagged with: tabs
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82707006
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82705619
has title: Forming a python table with tab
upvote count: 1
has answer: http://stackoverflow.com/a/47875862
score: 1
has comment: http://stackoverflow.com/comment/82706369
has body: I have one question about Python 3.X. I'm able to create a nice "table" with .format, but the question is whether I'm able to do it with tabs to look similar to this one with formats? file = open("students.csv", "r") students= [] for i in file: i= i.rstrip() i_sublist = i.split(",") students.append(i_sublist) print("Content") print("{0:15} {1:15} {2:15}".format("Name", "Surname", "Grade")) print("{0:15} {1:15} {2:15}".format("-----", "-------", "---")) for i in students: for j in i: print("{0:15}".format(j),"",end="") print() file.close()
type: Question
has comment: http://stackoverflow.com/comment/82706282

http://stackoverflow.com/a/47856656
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/82677870
has body: It does not work because you return nothing in case the list is non-empty (you just print() ). if you do not return anything explicitly the function returns None implicitly def get_all_subsets(some_list): if len(some_list) == 1: # if len is 1 then the last element was added # previously, just add the empty list return [[]] if len(some_list) &gt; 1: # add rest of list and recurse return [some_list[1:]] + get_all_subsets(some_list[1:]) L = [1,2,3,4] print( get_all_subsets(L)) Output: [[2, 3, 4], [3, 4], [4], []]
answers question: http://stackoverflow.com/q/47856548
upvote count: 1
type: Answer

http://stackoverflow.com/comment/82948072
type: QuestionComment
comment on: http://stackoverflow.com/q/47988877
has text: By the way, an alternative method is to replace with another callback function. Such as `def justpass(*args, **kwargs):pass` and `setMouseCallback(winname, justpass)` when needed.
score: 0
type: Comment

http://stackoverflow.com/comment/82998646
has text: SOLVED. cursor.close() and creating a new connection solved the problem. Thank @mangohero1
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48013544

http://stackoverflow.com/comment/82902262
has text: When I replace `merge` with `combine_first`, it worked perfectly. So I just need to know how to make it work for `combine`.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47966143

http://stackoverflow.com/q/47980094
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82929132
has title: Number pattern with user-input lines
has answer: http://stackoverflow.com/a/47980356
has body: The program should print something like this: 1 1 1 1 1 1 1 2 2 2 2 2 2 2 3 3 3 3 3 3 3 4 4 4 4 4 4 4 (but there's no space between each line) The lines should be a user-input. lines = int(input("enter lines: ")) times = int(input("enter times: ")) for x in range(1,lines+1): for x in range(1,times+1): print(x, end=" ") print(x) The program I made doesn't print it the output, and it seems that it was reversed. and it must be derived from the program that prints asterisks which is this: lines = int(input("enter lines: ")) times = int(input("enter times: ")) for x in range(lines): for x in range(times): print("*", end=" ") print() And it asks what line of program was changed. Thank you
has comment: http://stackoverflow.com/comment/82929152
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47980415
score: 0

http://stackoverflow.com/comment/82854536
score: 0
type: AnswerComment
has text: @Aksakal So, what exactly do you need - Just the non-zero counts or do you need the X,Y indices as well?
type: Comment
comment on: http://stackoverflow.com/a/47940483

http://stackoverflow.com/comment/82920002
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47975002
has text: @GG_Python Or what exactly is the expected output from multiplying `z` and `s1`? Could you add the expected output?

http://stackoverflow.com/q/47994646
score: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/83309336
has answer: http://stackoverflow.com/a/48165254
upvote count: 4
answer count: 2
tagged with: api
possible better answer: http://stackoverflow.com/a/48026340
has comment: http://stackoverflow.com/comment/82958192
has comment: http://stackoverflow.com/comment/82959515
has answer: http://stackoverflow.com/a/48026340
accepted answer: http://stackoverflow.com/a/48165254
favorite count: 0
has comment: http://stackoverflow.com/comment/82964226
tagged with: fitbit
tagged with: python
has comment: http://stackoverflow.com/comment/82958354
tagged with: scrapy
has title: Scrapy DOWNLOAD_DELAY not working for sequential requets
has body: I am currently working with the Scrapy Python library. First I make a FormRequest call to the Fitbit's login page (https://www.fitbit.com/login) to log myself in. Then I make close to 100 requests to the Fitbit's API (https://api.fitbit.com). To not stress out the API (and to not get banned from it!), I wanted to set a delay between the requests using DOWNLOAD_DELAY in the settings.py file. However it is not working. I was testing it in the tutorials (http://scrapy.readthedocs.io/en/latest/intro/tutorial.html) and it was working properly there. What do you think? Is it because I request an API (supposed to handle those kinds of accesses)? EDIT: here is the pseudo code of my spider: class FitbitSpider: start_urls = ["https://www.fitbit.com/login"] def parse(self, response): yield scrapy.FormRequest(url,formdata,callback=after_login) def after_login(self, response): for i in range(100): yield scrapy.Request("https://api.fitbit.com/[...]") EDIT 2: here is my settings.py file: BOT_NAME = 'fitbitscraper' SPIDER_MODULES = ['fitbitscraper.spiders'] NEWSPIDER_MODULE = 'fitbitscraper.spiders' DOWNLOAD_DELAY = 20 #20 seconds of delay should be pretty noticeable
type: Question
type: AnsweredQuestion

http://stackoverflow.com/q/48009774
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I'm trying to create an unknown amount of columns with annotate: def add_daily_usage_record(query, days): for i in days: query.annotate('day_' + i + '_usage'= "doesn't matter" But it doesn't seem to work. Is there any way to give an annotation a name without writing it? or maybe if I have the name of the new column in a variable, is it possible to pass it to annotate? Thank you.
has answer: http://stackoverflow.com/a/48009847
downvote count: 0
tagged with: django
has answer: http://stackoverflow.com/a/48009835
type: Question
score: 3
has title: Django annotation in a loop
upvote count: 3
answer count: 2

http://stackoverflow.com/comment/82954845
type: AnswerComment
has text: cells = [] is a list to hold your results inside the for loop, you can accept my answer if it helped you, thanks
type: Comment
comment on: http://stackoverflow.com/a/47987022
score: 0

http://stackoverflow.com/comment/82910217
has text: then probably you have set (not per se explicitly) a variable outside of the function scope to hold data.
comment on: http://stackoverflow.com/q/47970378
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/82743921
type: QuestionComment
has text: What is `img_dir` set to? Can you show us the HDFS path content? Is Spark configured to read HDFS, not local disk?
comment on: http://stackoverflow.com/q/47874622
score: 0
type: Comment

http://stackoverflow.com/q/47906007
has answer: http://stackoverflow.com/a/47906270
has comment: http://stackoverflow.com/comment/82778691
answer count: 3
has answer: http://stackoverflow.com/a/47906171
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/82778998
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83054858
has body: I'm newbie with Python and Selenium and trying to get screenshots of specific page with time of screenshot displayed in filename, following is code snippet: from selenium import webdriver import time from time import gmtime, strftime browser = webdriver.Chrome() browser.get('https://google.com') time.sleep(3) browser.get_screenshot_as_file('C:\\path\\screenshots\\(strftime("%Y-%m-%d %H:%M:%S", gmtime())).png') browser.quit() BTW, how can I set Chrome window size when running it? And the main question: what am I doing wrong?
tagged with: python
has answer: http://stackoverflow.com/a/75819452
tagged with: screenshot
score: 1
tagged with: selenium
has title: How to save file with current time in Selenium?
has comment: http://stackoverflow.com/comment/82778859
downvote count: 1
type: Question

http://stackoverflow.com/q/47965149
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/47965286
has title: Expected 2D array, got 1D array instead, Reshape Data
has body: I'm really stuck on this problem. I'm trying to use OneHotEncoder to encode my data into a matrix after using LabelEncoder but getting this error: Expected 2D array, got 1D array instead. At the end of the error message(included below) it said to "Reshape my data" which I thought I did but it's still not working. If I understand Reshaping, is that just when you want to literally reshape some data into a different matrix size? For example, if I want to change a 3 x 2 matrix into a 4 x 6? My code is failing on these 2 lines: X = X.reshape(-1, 1) # I added this after I saw the error X[:, 0] = onehotencoder1.fit_transform(X[:, 0]).toarray() Here is the code I have so far: # Data Preprocessing # Import Libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Import Dataset dataset = pd.read_csv('Data2.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 5].values df_X = pd.DataFrame(X) df_y = pd.DataFrame(y) # Replace Missing Values from sklearn.preprocessing import Imputer imputer = Imputer(missing_values = 'NaN', strategy = 'mean', axis = 0) imputer = imputer.fit(X[:, 3:5 ]) X[:, 3:5] = imputer.transform(X[:, 3:5]) # Encoding Categorical Data "Name" from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelencoder_x = LabelEncoder() X[:, 0] = labelencoder_x.fit_transform(X[:, 0]) # Transform into a Matrix onehotencoder1 = OneHotEncoder(categorical_features = [0]) X = X.reshape(-1, 1) X[:, 0] = onehotencoder1.fit_transform(X[:, 0]).toarray() # Encoding Categorical Data "University" from sklearn.preprocessing import LabelEncoder labelencoder_x1 = LabelEncoder() X[:, 1] = labelencoder_x1.fit_transform(X[:, 1]) Here is the full error message: File "/Users/jim/anaconda3/lib/python3.6/site-packages/sklearn/preprocessing/data.py", line 1809, in _transform_selected X = check_array(X, accept_sparse='csc', copy=copy, dtype=FLOAT_DTYPES) File "/Users/jim/anaconda3/lib/python3.6/site-packages/sklearn/utils/validation.py", line 441, in check_…
has answer: http://stackoverflow.com/a/47965446
upvote count: 3
answer count: 3
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47965286
has answer: http://stackoverflow.com/a/58938283
tagged with: python
tagged with: sklearn-pandas
type: AnsweredQuestion
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/82900274
has comment: http://stackoverflow.com/comment/82900257
has comment: http://stackoverflow.com/comment/82900344
tagged with: machine-learning
accepted answer: http://stackoverflow.com/a/47965446

http://stackoverflow.com/comment/82924850
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47977787
type: Comment
has text: Please edit to include a comment explaining this code for the benefit of others.

http://stackoverflow.com/q/47893854
tagged with: math
duplicate of: http://stackoverflow.com/q/1267869
has title: Dictionary math in python - keys are there, values coming up empty
type: Question
has body: I have two dictionaries, one was populated from a dataset, the other I created manually. I was trying to do a bit of math on them, and store the results in another dictionary. It worked in an online platform, but when I run the Jupyter notebook using PyCharm, it will not return the correct results. Any idea why? Here is the creation of the two dictionaries, and the output of the two of them (i.e., the content of the dictionaries) race_counts = {} for race in race: if race not in race_counts: race_counts[race] = 1 else: race_counts[race] += 1 mapping = { 'Asian/Pacific Islander': 15159516 + 674625, 'Native American/Native Alaskan': 3739506, 'Black': 40250635, 'Hispanic': 44618105, 'White': 197318956 } race_counts dictionary: {'Native American/Native Alaskan': 917, 'Black': 23296, 'White': 66237, 'Asian/Pacific Islander': 1326, 'Hispanic': 9022} mapping dictionary: {'Native American/Native Alaskan': 3739506, 'Black': 40250635, 'White': 197318956, 'Asian/Pacific Islander': 15834141, 'Hispanic': 44618105} Here is the math I'm trying: race_per_hundredk = {} for race in race_counts: race_per_hundredk[race] = (race_counts[race] / mapping[race]) * 100000 print(race_per_hundredk) Now, the correct output I'm expecting is this: {'Asian/Pacific Islander': 8.374309664161762, 'Black': 57.8773477735196, 'Hispanic': 20.220491210910907, 'Native American/Native Alaskan': 24.521955573811088, 'White': 33.56849303419181} But, Instead I am getting this: {'Native American/Native Alaskan': 0, 'Asian/Pacific Islander': 0 'White': 0, 'Black': 0, 'Hispanic': 0} The order of the keys doesn't matter but I'm not sure why the values are being returned empty. Thanks a bunch, guys/gals. I swear I'll start answering some questions and giving back when I have an idea about what I'm doing...
score: 0
has answer: http://stackoverflow.com/a/47893887
answer count: 1
tagged with: python
tagged with: dictionary
linked to: http://stackoverflow.com/q/1267869
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47893887

http://stackoverflow.com/comment/82939915
score: 0
type: Comment
has text: Thanks. But I've checked as you wrote and the result has been added to the end of the question. It seems the problem is not related to that.
comment on: http://stackoverflow.com/a/47980557
type: AnswerComment

http://stackoverflow.com/comment/82960988
type: Comment
type: QuestionComment
has text: Should I report it?
comment on: http://stackoverflow.com/q/47996058
score: 0

http://stackoverflow.com/q/47871620
has body: Maximum Simple Cycle (product) in a graph Hello, I have constructed a directed graph G=(v,e) and I would like to find the maximum simple cycle in this graph, where edge weights are multiplied instead of added. My initial method for doing so is to construct a new graph, G=(v,e'), where e'(i,j) = 1/e(i,j)/min(e'), and then to apply Floyd-Warshall on this graph to find all shortest paths. My thoughts were that after inverting the graph, the maximum path would then become the minimum, and if we divide by the minimum value, all edge weights will be "positive" (>= 1, since we are multiplying instead of adding). However, when I run the algorithm (my Python code is below) it seems to not work, and I'm wondering if it's because my algorithm won't work at all or if it's because of an error in my code. #construct G' = (V,dist) for our modified Floyd-Warshall algorithm # edge weights are initially the inverse of w(u,v). They are then all divided # by the minimum value to ensure all are &gt;= 1 dist = {} nxt = {} minimum = float("inf") for i in e: dist[i] = {} nxt[i] = {} for j in e[i]: dist[i][j] = 1/e[i][j] nxt[i][j] = j if dist[i][j] &lt; minimum: minimum = dist[i][j] for i in dist: for j in dist[i]: dist[i][j] /= minimum # Perform Floyd-Warshall for k in v: for i in v: for j in v: try: one = dist[i][j] two = dist[i][k] three = dist[k][j] except KeyError: continue if one &gt; two * three: dist[i][j] = two * three nxt[i][j] = nxt[i][k] # Find the shortest cycle using shortest paths minimum = float("inf") for i in v: for j in v: if i == j: continue try: one = dist[i][j] two = dist[j][i] except KeyError: continue if one * two &lt; minimum: minimum = one * two pair = [i,j] def Path(u,v): if nxt[u][v] == None: return [] path = [u] while u != v: u = nxt[u][v] path.append(u) return path # Format the cycle for output p1 = Path(pair[0],pair[1]) p2 = Path(pair[1],pair[0]) p = p1 + p2[1:] print(p) # Find the total value of the cycle value = 1 for i in range(len(p)-1): value *= e[p[i]][p…
type: Question
tagged with: graph
answer count: 1
downvote count: 0
has title: Maximum Simple Cycle in Directed Graph
tagged with: python
favorite count: 0
score: 2
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47871837
tagged with: algorithm

http://stackoverflow.com/a/47865440
has body: just go for a list of tuples. this is always sorted by the first element and you can get your date value and your note separately list = [('2015-12-01', 'remember groceries') , ('2017-12-21', 'buy presents'), ('2015-12-21', 'xxx')] print(sorted(list)) print(list[0][1], list[1][1])
answers question: http://stackoverflow.com/q/47865128
score: 0
type: Answer

http://stackoverflow.com/comment/83034196
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48023315
has text: @KyleSun: I have updated the answer. Previous answer was incorrect.
score: 0

http://stackoverflow.com/comment/82782016
has text: Also, adding from the first row isn't a good idea, because you can't guarantee that it is consecutive from the first row. Furthermore, not all columns need to have the same number of NaNs.
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47907394

http://stackoverflow.com/q/47977716
tagged with: session
tagged with: facebook-messenger
score: 0
has comment: http://stackoverflow.com/comment/82924519
has comment: http://stackoverflow.com/comment/82924921
type: UnansweredQuestion
tagged with: python
has body: I have developed chatbot for messenger and deployed in heroku. When user writes(messenger sends post request) i try to set session, but after request, session is empty. With postman i have tested and everything works perfect. I want to know what is the reason? Here is how i set session: from flask import Flask, request, session @app.route('/set', methods=['POST']) def set(): session["language"] = "en" print(session) //&lt;SecureCookieSession {'language': 'en'}&gt; return "added", 200 @app.route('/get', methods=['POST']) def get(): print(session) //in messenger &lt;SecureCookieSession {}&gt; in postman &lt;SecureCookieSession {'language': 'en'}&gt; return "get"
answer count: 0
has title: Session is empty when request from messenger
type: Question
tagged with: heroku

http://stackoverflow.com/q/47887445
tagged with: http://stackoverflow.com/tag/csv
tagged with: header
has answer: http://stackoverflow.com/a/47888128
tagged with: python
type: AnsweredQuestion
has body: I am reading a csv file that has about 7-8 lines above that are a description of my file. I am getting to the first column by using the following code : list_of_files = glob.glob('C:/payment_reports/*csv') # * means all if need specific format then *.csv latest_file = max(list_of_files, key=os.path.getctime) print (latest_file) line_count = None for row in csv.reader(open(latest_file)): if row[0] == 'date/time': print (row) break else: print("{} not found".format('name')) I am getting to correct line since the row that prints is: ['date/time', 'settlement id', 'type', 'order id', 'sku', 'description', 'quantity', 'marketplace', 'fulfillment', 'order city', 'order state', 'order postal', 'product sales', 'shipping credits', 'gift wrap credits', 'promotional rebates', 'sales tax collected', 'Marketplace Facilitator Tax', 'selling fees', 'fba fees', 'other transaction fees', 'other', 'total'] Now how do I save the column + all the rows after as a new csv? I have a line_count, but before I try it with a new variable, I am sure there are functions in the csv using the index of the row that I can use to make things more simple. What do you guys suggest is the best way to do this.? Solution: thanks @bruno desthuilliers list_of_files = glob.glob('C:/payment_reports/*csv') # * means all if need specific format then *.csv latest_file = max(list_of_files, key=os.path.getctime) print (latest_file) with open(latest_file, "r") as infile: reader = csv.reader(infile) for row in reader: if row[0] == 'date/time': print (row) break else: print("{} not found".format('name')) break with open("C:/test.csv", "w") as outfile: writer = csv.writer(outfile) writer.writerow(row) # headers writer.writerows(reader) # remaining rows
has title: How can I create a new csv after finding the header row?
accepted answer: http://stackoverflow.com/a/47888128
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/47887690
score: 0
has answer: http://stackoverflow.com/a/47887690

http://stackoverflow.com/q/47904452
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/82775560
linked to: http://stackoverflow.com/q/1680528
type: Question
has comment: http://stackoverflow.com/comment/82775655
score: 0
has body: The following code, class A: pass class B: member = A() def hello(self): print(repr( type(self).member )) b1 = B() b2 = B() b1.hello() b2.hello() gives the following output: &lt;__main__.A object at 0x0000025193C03DA0&gt; &lt;__main__.A object at 0x0000025193C03DA0&gt; It seems that python only instantiate A once and uses its value for all the instances of B. Why does it happen and is there a way of instantiating different global members for all instances of B ?
has comment: http://stackoverflow.com/comment/82776013
has title: Global class members only instanciated once in python
duplicate of: http://stackoverflow.com/q/1680528
tagged with: python-3.x

http://stackoverflow.com/a/47927799
type: AcceptedAnswer
has body: You are using a square grid to perform the game of life algorithm. You then map the result onto a hexagonal grid. This means that some square grid values lie in the same cell of the hexagonal grid (adding up to its value), while some hexagonal grid cells are empty because they do not hit any sqaure grid cell. As an example, you can see that e.g. the hexagonal grid's cell centered at (0.5,2.5) does not include any position of the original square grid. Hence this cell stays empty. Since the game of life is strongly depending on the grid itself, it anyway makes no sense to use a different grid. So just stay with the square grid - or let the game of life run on a different grid, changing the complete algorithm to account for the grid in use.
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47927095
type: Answer
answers question: http://stackoverflow.com/q/47927095
has comment: http://stackoverflow.com/comment/82824544
has comment: http://stackoverflow.com/comment/82824947
has comment: http://stackoverflow.com/comment/82824784
has comment: http://stackoverflow.com/comment/82825100
score: 2
downvote count: 0

http://stackoverflow.com/q/47953294
has body: Background We have this code in our project for reading and writing from/to a row in our database @property def title_str(self) -&gt; str: return self._title_str @title_str.setter def title_str(self, i_new_title: str): self._title_str = i_new_title self._update(db.Schema.PhrasesTable.Cols.title, i_new_title) where the setter updates both the model object as well as the database Problem and Question We're concerned that if one of these statements self._title_str = i_new_title self._update(db.Schema.PhrasesTable.Cols.title, i_new_title) fail while the other one succeeds there will be an inconsistency between the value in the model object and the value in our database How can we avoid this risk? Speculation Perhaps there is a way to make two Python statements "atomic" so that if one fails the other one is reverted, or is the approach here just to store the old values and write them back if we catch an exception? Grateful for help!
has answer: http://stackoverflow.com/a/47953331
tagged with: orm
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/47953331
tagged with: setter
answer count: 1
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x
has title: Ensuring that if one of two statements fail the end result will be no change for both statements
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/82929852
type: AnswerComment
has text: The advice is good, but I am failing to understand how it relates to the OP's error..
type: Comment
comment on: http://stackoverflow.com/a/47980557
score: 1

http://stackoverflow.com/comment/82939005
has text: `while`, not `While`
comment on: http://stackoverflow.com/a/47985026
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/82966823
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47998664
has text: Thanks @MaxU. That's a much better string for testing.

http://stackoverflow.com/comment/82932566
type: QuestionComment
comment on: http://stackoverflow.com/q/47981933
has text: you should probably do `csvfile1.close()` before reading it back again (flush buffers)
score: 0
type: Comment

http://stackoverflow.com/q/47940874
answer count: 1
score: 0
has body: I would like to use LSTM unit with layer normalization implemented in tensorflow here in the following code: import tensorflow as tf import numpy as np n = 10 batch_size_series = 16 x = tf.placeholder(shape=[None, None, 1], dtype=tf.float32, name="x") layer_norm = tf.placeholder(tf.bool, name="normalize_layer") cell = tf.contrib.rnn.LayerNormBasicLSTMCell(n, layer_norm=layer_norm) initial_state = cell.zero_state(batch_size_series, dtype=tf.float32) output_state, current_state = tf.nn.dynamic_rnn(cell, inputs=x, initial_state=initial_state, dtype=tf.float32) I get the following error when the layer_norm is a Tensor: TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed. Use `if t is not None:` instead of `if t:` to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor. And the trace goes back to the dynamic_rnn: Traceback (most recent call last): File "test.py", line 19, in &lt;module&gt; output_state, current_state = tf.nn.dynamic_rnn(multi_rnn_cell, inputs=x, initial_state=initial_state, dtype=tf.float32) File "/Users/fghavamian/ve_tf2/lib/python3.6/site-packages/tensorflow/python/ops/rnn.py", line 614, in dynamic_rnn dtype=dtype) File "/Users/fghavamian/ve_tf2/lib/python3.6/site-packages/tensorflow/python/ops/rnn.py", line 777, in _dynamic_rnn_loop swap_memory=swap_memory) File "/Users/fghavamian/ve_tf2/lib/python3.6/site-packages/tensorflow/python/ops/control_flow_ops.py", line 2816, in while_loop result = loop_context.BuildLoop(cond, body, loop_vars, shape_invariants) File "/Users/fghavamian/ve_tf2/lib/python3.6/site-packages/tensorflow/python/ops/control_flow_ops.py", line 2640, in BuildLoop pred, body, original_loop_vars, loop_vars, shape_invariants) File "/Users/fghavamian/ve_tf2/lib/python3.6/site-packages/tensorflow/python/ops/control_flow_ops.py", line 2590, in _BuildLoop body_result = body(*packed_vars_for_body) File "/Users/fghavamian/ve_tf2/lib/python3.6/site-packages/ten…
tagged with: python
accepted answer: http://stackoverflow.com/a/47945143
has answer: http://stackoverflow.com/a/47945143
tagged with: tensorflow
type: AnsweredQuestion
tagged with: recurrent-neural-network
type: Question
has title: dynamic_rnn gives "`tf.Tensor` as a Python `bool`" error when layer_norm (in LayerNormBasicLSTMCell) is a Tensor

http://stackoverflow.com/comment/104226017
has text: Does this answer your question? [Mark email as read with exchangelib](https://stackoverflow.com/questions/45037322/mark-email-as-read-with-exchangelib)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47984721
score: 0

http://stackoverflow.com/comment/82809160
score: 0
type: Comment
type: QuestionComment
has text: `django`? if yes, it might be a good idea to add it in the tag list
comment on: http://stackoverflow.com/q/47920845

http://stackoverflow.com/a/47910729
type: Answer
has body: from editdistance import eval as levenshtein import pandas as pd keywords = ["foo", "foe", "bar", "baz"] groups = ["foo", "bar"] assigned_groups = [min(groups, key=lambda g: levenshtein(g, k)) for k in keywords] df = pd.DataFrame({"Keyword": keywords, "Group": assigned_groups}) # Group Keyword # 0 foo foo # 1 foo foe # 2 bar bar # 3 bar baz Using editdistance. Get it with pip install editdistance. Note that this algorithm is O(mn), where m is the length of the keywords and n the length of the groups.
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47908741
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47908741

http://stackoverflow.com/comment/82897927
score: 0
type: AnswerComment
type: Comment
has text: So, when I want to run the .py file I type `python3 file.py` in the terminal. And when I type `which python3` it outputs `/usr/local/bin/python3`. Now, in my cron job if I do `*/2 * * * * /usr/local/bin/python3 /home/pi/folder/file.py`, it still doesn't run, what else am I doing wrong (I appreciate all the help so far)?
comment on: http://stackoverflow.com/a/47964058

http://stackoverflow.com/comment/82964921
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47998276
type: AnswerComment
has text: Agreed, but I assumed OP wanted a list of values for each key and this method provides that.

http://stackoverflow.com/q/47942273
possible better answer: http://stackoverflow.com/a/47942529
tagged with: python
has body: I have a series df2 which I want to plot using pie chart Index Friday 2 Thursday 2 Wednesday 3 I have tried colors = ["#E13F29", "#D69A80", "#D63B59", "#AE5552", "#CB5C3B", "#EB8076", "#96624E"] df2.plot().pie(df2['counts'],df2.index,shadow=False,colors=colors, explode=(0, 0, 0, 0, 0.15), startangle=90,autopct='%1.1f%%', ) # View the plot drop above pyplot.axis('equal') # View the plot pyplot.tight_layout() pyplot.show() ValueError: could not convert string to float: 'Wednesday'
has comment: http://stackoverflow.com/comment/82854745
tagged with: plot
type: AnsweredQuestion
score: 2
tagged with: matplotlib
type: Question
has comment: http://stackoverflow.com/comment/82854629
has answer: http://stackoverflow.com/a/47942534
has title: plotting a series pie chart
tagged with: pie-chart
downvote count: 0
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/47942529
accepted answer: http://stackoverflow.com/a/47942534
favorite count: 0
linked to: http://stackoverflow.com/q/47935681
upvote count: 2

http://stackoverflow.com/comment/82989774
type: QuestionComment
comment on: http://stackoverflow.com/q/48008259
has text: @JonClements because that table made out of reshape function in R, which re arranged every unique cate_level1 matched into each sub_level xxxxxxxxx.
score: 0
type: Comment

http://stackoverflow.com/comment/82787246
has text: I had a similar thought, I think this is a pretty good test for that. Good catch.
comment on: http://stackoverflow.com/a/47897173
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47956156
tagged with: http://stackoverflow.com/tag/zip
accepted answer: http://stackoverflow.com/a/47956870
has body: I have lot of zipped files in my directory, I want to get number of files for each zip file. For instance, let's say for the zip file "nature.zip", I want to get following output: file_name file_format nature jpg 2, png 1 So far I managed to print the content but don't know how could I move forward from zipfile import ZipFile import os directory = r"C:\Users\Lenovo\data_2" for folder, subfolders, files in os.walk(directory): for file in files: if file.endswith(".zip"): # opening the zip file in READ mode with ZipFile(directory+ '/'+ file, 'r') as zip: # printing all the contents of the zip file zip.printdir() Thank you very much
upvote count: 2
score: 2
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/47956870
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82882259
has title: Counting number of files with different formats in zip file using Python
favorite count: 0
tagged with: python

http://stackoverflow.com/a/74583971
has body: A solution using async_tkinter_loop module (which is written by me). Internally, the approach is similar to the code from the answer of Terry Jan Reedy, but the usage is much simpler: you just need to wrap your asynchronous handlers into async_handler function calls, and use them as a command or an event handlers, and use async_mainloop(root) in place of root.mainloop(). from tkinter import * from tkinter import messagebox import asyncio import random from async_tkinter_loop import async_handler, async_mainloop def do_freezed(): """ Button-Event-Handler to see if a button on GUI works. """ messagebox.showinfo(message='Tkinter is reacting.') async def one_url(url): """ One task. """ sec = random.randint(1, 15) await asyncio.sleep(sec) return 'url: {}\tsec: {}'.format(url, sec) async def do_urls(): """ Creating and starting 10 tasks. """ tasks = [ asyncio.create_task(one_url(url)) # added create_task to remove warning "The explicit passing of coroutine objects to asyncio.wait() is deprecated since Python 3.8, and scheduled for removal in Python 3.11." for url in range(10) ] print("Started") completed, pending = await asyncio.wait(tasks) results = [task.result() for task in completed] print('\n'.join(results)) print("Finished") if __name__ == '__main__': root = Tk() # Wrap async function into async_handler to use it as a button handler or an event handler buttonT = Button(master=root, text='Asyncio Tasks', command=async_handler(do_urls)) buttonT.pack() buttonX = Button(master=root, text='Freezed???', command=do_freezed) buttonX.pack() # Use async_mainloop(root) instead of root.mainloop() async_mainloop(root)
downvote count: 0
answers question: http://stackoverflow.com/q/47895765
type: Answer
upvote count: 2
score: 2

probability
tags question: http://stackoverflow.com/q/47908749
tags question: http://stackoverflow.com/q/47919309
type: Tag
tags question: http://stackoverflow.com/q/47953098
tag name: probability
tags question: http://stackoverflow.com/q/47933019

http://stackoverflow.com/q/47891168
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47891262
has answer: http://stackoverflow.com/a/47891262
has answer: http://stackoverflow.com/a/47891242
type: Question
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/82748786
tagged with: arrays
downvote count: 0
favorite count: 0
upvote count: 8
accepted answer: http://stackoverflow.com/a/47891242
has title: Assign values to a numpy array for each row with specified columns
has comment: http://stackoverflow.com/comment/82748916
score: 8
tagged with: python
has body: I have a matrix foo with n rows and m columns. Example: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; foo = np.arange(6).reshape(3, 2) # n=3 and m=2 in our example &gt;&gt;&gt; print(foo) array([[0, 1], [2, 3], [4, 5]]) I have an array bar with n elements. Example: &gt;&gt;&gt; bar = np.array([9, 8, 7]) I have a list ind of length n that contains column indices. Example: &gt;&gt;&gt; ind = np.array([0, 0, 1], dtype='i') I would like to use the column indices ind to assign the values of bar to the matrix foo. I would like to do this per row. Assume that the function that does this is called assign_function, my output would look as follows: &gt;&gt;&gt; assign_function(ind, bar, foo) &gt;&gt;&gt; print(foo) array([[9, 1], [8, 3], [4, 7]]) Is there a pythonic way to do this?

http://stackoverflow.com/comment/82749508
has text: there is no file named path.py
type: Comment
comment on: http://stackoverflow.com/a/47891371
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82975379
comment on: http://stackoverflow.com/q/47996725
has text: Templates *should* be in `/Books/Books/templates/`. Why did you expect otherwise?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82961028
comment on: http://stackoverflow.com/q/47996516
has text: I don't get it. Is there a question here?
score: 3
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82909893
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47967633
has text: @RoadRunner hmm yes, I didn't understand the program. But then it prints `1` for `1 1 1 1` so it seems wrong in a different way.

http://stackoverflow.com/comment/82952181
score: 1
type: QuestionComment
type: Comment
has text: @MichaelButscher True, but I have to say that was what I expected from a context manager. Very much unlike my first time debugging the mysterious things that happened when I had a return in both the try and the finally block :D
comment on: http://stackoverflow.com/q/47991833

http://stackoverflow.com/comment/82737375
type: AnswerComment
comment on: http://stackoverflow.com/a/47885524
type: Comment
has text: So if I have a byte array which I fetched from the network (rss/html) with non-ascii bytes in it the function will handle them?
score: 0

http://stackoverflow.com/a/47951174
upvote count: 1
has body: An odd way that is sometimes worthwhile is from collections import defaultdict days = defaultdict(list) print(days['day1']) #prints [], Doing this you can use whatever you like for day of week keys as long as you are consistent. Like days['Monday'] or use number keys to make it look like an array.
answers question: http://stackoverflow.com/q/47950397
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/comment/82946769
comment on: http://stackoverflow.com/a/47988954
type: AnswerComment
type: Comment
has text: @moshangcheng Right, so my guess regarding the difference is that, data is loaded into pandas columns as numpy objects by default (for performance reasons). If you did `df.loc[0, 'count']` you'd see that a `int64` object is returned. Now, call `df.loc[0, 'count'].item()`, and an _int_ object is returned. My guess is that apply implicitly does something like this, passing an item to `type` inside the apply body.
score: 0

http://stackoverflow.com/comment/82771517
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47901878
has text: `from wmi import WMI` than `WMI(..............)` or `import wmi; wmi.WMI(...............)`

http://stackoverflow.com/comment/82714034
has text: What, **exactly** are you working with? Your example `input` array is *not an array*, it is a `list` object. Give us an example of your actual array. Note, you say your array is "3D", but if I use the array constructor on your `input` data it returns a one-dimensional array...
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47874298

http://stackoverflow.com/q/47963417
has comment: http://stackoverflow.com/comment/82896405
has comment: http://stackoverflow.com/comment/82923450
answer count: 1
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
has title: Cython: Speed up simple code
downvote count: 1
has comment: http://stackoverflow.com/comment/82925446
has comment: http://stackoverflow.com/comment/82896916
has comment: http://stackoverflow.com/comment/82896878
has body: I am trying to speed up the following code with Cython. Two arguments are imported from python: processing_times: List with 500 lists of 20 integers each (500x20). sequence: List with 500 integers. cimport cython @cython.boundscheck(False) @cython.wraparound(False) cpdef taillard_acceleration(sequence, processing_times, int job_inserted, int num_machines): # Static arrays - number of jobs limited to 500 jobs and 20 machines cdef int e[501][21] cdef int q[501][21] cdef int f[501][21] cdef int ms[501] # Variables cdef int sequence_length, best_makespan, best_position cdef int i, j, iq, jq, tmp # Initialize some values sequence_length = len(sequence) iq = sequence_length + 1 for i in range(1, sequence_length + 2): if i &lt; sequence_length + 1: e[i][0] = 0 # Q index I iq = iq - 1 q[iq][num_machines + 1] = 0 f[i][0] = 0 jq = num_machines + 1 for j in range(1, num_machines + 1): if i == 1: e[0][j] = 0 q[sequence_length + 1][num_machines + 1 - j] = 0 if i &lt; sequence_length + 1: # Q Index J jq = jq - 1 if e[i][j - 1] &gt; e[i - 1][j]: e[i][j] = e[i][j - 1] + processing_times[sequence[i - 1]-1][j-1] else: e[i][j] = e[i - 1][j] + processing_times[sequence[i - 1]-1][j-1] if q[iq][jq + 1] &gt; q[iq + 1][jq]: q[iq][jq] = q[iq][jq + 1] + processing_times[sequence[iq - 1]-1][jq-1] else: q[iq][jq] = q[iq + 1][jq] + processing_times[sequence[iq - 1]-1][jq-1] # f(ij) = max {f(i, j-1), e(i-1, j)} if f[i][j - 1] &gt; e[i - 1][j]: f[i][j] = f[i][j - 1] + processing_times[job_inserted-1][j-1] else: f[i][j] = e[i - 1][j] + processing_times[job_inserted-1][j-1] # Makespam - job k in position i best_makespan = 0 best_position = 0 for i in range(1, sequence_length + 2): ms[i] = 0 for j in range(1, num_machines + 1): tmp = f[i][j] + q[i][j] if tmp &gt; ms[i]: ms[i] = tmp # Check best insertion position if ms[i] &lt; best_makespan or best_makespan == 0: best_makespan = ms[i] best_position = i return best_position, best_makespan I was able to speed up the process 4x times over the original …
has answer: http://stackoverflow.com/a/47976911
score: 1
tagged with: cython
type: Question

http://stackoverflow.com/comment/82862706
type: Comment
type: QuestionComment
has text: Json error on column is the first comma because you lack the leading [ and trailing ] in your response data. Also the line breaks need commas too.
comment on: http://stackoverflow.com/q/47946297
score: 0

http://stackoverflow.com/a/47864840
score: 2
has body: The help for filter states Return those items of sequence for which function(item) is true. If function is None, return the items that are true. The boolean value of a space is True so it is not removed.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47864806
upvote count: 2

http://stackoverflow.com/comment/82997217
score: 0
type: Comment
has text: Do you just want to distinguish "delete" and "disable inbox" buttons?
type: QuestionComment
comment on: http://stackoverflow.com/q/48014031

http://stackoverflow.com/a/48294904
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47961890
score: 2
upvote count: 2
has body: Just replace shape_predictor_5_face_landmarks.dat with shape_predictor_68_face_landmarks.dat It is availbale here

http://stackoverflow.com/comment/82750338
has text: I'm going to try doing df2 = diagnostic(df)
comment on: http://stackoverflow.com/q/47891444
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47966728
has body: I have the following Gaussian equation in Python: numpy.exp((-(x-m)**2)/(2*sigma)) Provided that x is an matrix. However, the equation won't run, and I get the following error: AttributeError: 'Float' object has no attribute 'exp' How can I solve this issue? EDIT-1 Making the following edit: map(float(),np.exp((-(x-m)**2)/(2*sigma))) Raised the error: TypeError: 'float' object is not callable EDIT-2 This is a sample of the value x: [[-0.20646505 0.07763347 -0.16161097 0.370439 ] [-0.91295327 -0.73768934 -0.78909055 0.06156045] [-0.37242104 0.51828245 -1.16138222 -0.02489585] [-1.07890926 -0.29704036 -1.7888618 -0.3337744 ]] m = 5 sigma = 1 Thanks.
answer count: 3
has comment: http://stackoverflow.com/comment/82903262
has comment: http://stackoverflow.com/comment/82903453
has comment: http://stackoverflow.com/comment/82903326
has comment: http://stackoverflow.com/comment/82902940
has comment: http://stackoverflow.com/comment/82903339
accepted answer: http://stackoverflow.com/a/47966997
favorite count: 0
has comment: http://stackoverflow.com/comment/82903456
tagged with: algebra
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/82903515
has comment: http://stackoverflow.com/comment/82902980
has comment: http://stackoverflow.com/comment/82903306
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82903380
has answer: http://stackoverflow.com/a/47972741
has comment: http://stackoverflow.com/comment/82903194
upvote count: 3
tagged with: math
score: 1
has title: How to fix 'Float' object has no attribute 'exp'?
has comment: http://stackoverflow.com/comment/82903294
has comment: http://stackoverflow.com/comment/82903364
has comment: http://stackoverflow.com/comment/82903275
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/47972741
has comment: http://stackoverflow.com/comment/82903349
has answer: http://stackoverflow.com/a/47966997
has comment: http://stackoverflow.com/comment/82903059
tagged with: gaussian
has answer: http://stackoverflow.com/a/47967015
has comment: http://stackoverflow.com/comment/82903234
has comment: http://stackoverflow.com/comment/82903321

http://stackoverflow.com/q/47920475
answer count: 2
downvote count: 0
tagged with: telnetlib
has comment: http://stackoverflow.com/comment/82808520
has comment: http://stackoverflow.com/comment/82808558
has body: I have implemented a script that connects to a Cisco device and collects the show run output. The script is: import getpass import telnetlib import time HOST = "10.62.149.9" user = input("Enter your remote account: ") password = getpass.getpass("User Password: ") enable = getpass.getpass("Enable Password: ") tn = telnetlib.Telnet(HOST) tn.read_until(b"Username: ") tn.write(user.encode('ascii') + b"\n") if password: tn.read_until(b"Password: ") tn.write(password.encode('ascii') + b"\n") tn.write(b"enable\n") if enable: tn.read_until(b"Password: ") tn.write(enable.encode('ascii') + b"\n") tn.write(b"term len 0\n") tn.write(b"show run\n") time.sleep(10) s = tn.read_very_eager() print (s) tn.close() The script output is: \r\ninterface GigabitEthernet1/0/26\r\n!\r\ninterface GigabitEthernet1/0/27\r\n!\r\ninterface GigabitEthernet1/0/28\r\n!\r\ninterface GigabitEthernet1/0/29\r\n!\r\ninterface GigabitEthernet1/0/30\r\n!\r\ninterface GigabitEthernet1/0/31\r\n!\r\ninterface GigabitEthernet1/0/32\r\n!\r\ninterface GigabitEthernet1/0/33\r\n!\r\ninterface GigabitEthernet1/0/34\r\n!\r\ninterface GigabitEthernet1/0/35\r\n!\r\ninterface GigabitEthernet1/0/36\r\n!\r\ninterface GigabitEthernet1/0/37\r\n!\r\ninterface GigabitEthernet1/0/38\r\n!\r\ninterface GigabitEthernet1/0/39\r\n!\r\ninterface GigabitEthernet1/0/40\r\n!\r\ninterface GigabitEthernet1/0/41\r\n!\r\ninterface GigabitEthernet1/0/42\r\n!\r\ninterface GigabitEthernet1/0/43\r\n!\r\ninterface GigabitEthernet1/0/44\r\n!\r\ninterface GigabitEthernet1/0/45\r\n!\r\ninterface GigabitEthernet1/0/46\r\n!\r\ninterface GigabitEthernet1/0/47\r\n!\r\ninterface GigabitEthernet1/0/48\r\n no switchport\r\n ip address 10.62.149.9 255.255.255.128\r\n!\r\ninterface GigabitEthernet1/0/49\r\n!\r\ninterface GigabitEthernet1/0/50\r\n!\r\ninterface GigabitEthernet1/0/51\r\n!\r\ninterface GigabitEthernet1/0/52\r\n!\r\ninterface Vlan1\r\n no ip address\r\n shutdown\r\n!\r\ninterface Vlan10\r\n ip address 10.10.10.1 255.255.255.0\r\n!\r\ninterfac…
has answer: http://stackoverflow.com/a/47920644
accepted answer: http://stackoverflow.com/a/47920644
possible better answer: http://stackoverflow.com/a/47920579
tagged with: python
has title: How can i get telnet output printed line by line?
favorite count: 0
upvote count: 2
tagged with: cisco-ios
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/47920579
type: Question

http://stackoverflow.com/comment/83267680
type: Comment
has text: I already tried that, works fine, but It seems like it is not possible to add TWO scopes to ONE View, so i can't throttle only one view, right?
comment on: http://stackoverflow.com/a/47918901
type: AnswerComment
score: 0

http://stackoverflow.com/a/47893752
answers question: http://stackoverflow.com/q/47893393
type: AcceptedAnswer
downvote count: 0
has body: the problem is caused because the background image is going to be applied to all the widgets so the color of the button is not modified. One solution is to apply the background image only to the widget, so we use the . selector: w.setStyleSheet(".QWidget{background-image:" + "url(" + BACKGROUND_IMAGE_URL + ");" + "border:0px}")
type: Answer
accepted answer of: http://stackoverflow.com/q/47893393
score: 2
upvote count: 2

http://stackoverflow.com/q/48013190
answer count: 0
has comment: http://stackoverflow.com/comment/82996135
type: UnansweredQuestion
upvote count: 1
tagged with: python
duplicate of: http://stackoverflow.com/q/21274865
has comment: http://stackoverflow.com/comment/82995356
has comment: http://stackoverflow.com/comment/82995887
has comment: http://stackoverflow.com/comment/82995537
has comment: http://stackoverflow.com/comment/82996500
tagged with: pyqt5
has body: I started using PyQt5 for dynamic javascript scraping and already ran into trouble. When i have multiple urls to scrape, python crashes after first or second url, no matter what the domain. I can get data from the first, but not from the second page. Error logs from windows show Qt5WebEngineCore.dll as the cause of error, but I got no clue what to do. I really didnt find anything useful on it from elswhere on the web. Here's the code: import sys import requests from PyQt5.QtWidgets import QApplication from PyQt5.QtCore import QUrl from PyQt5.QtWebEngineWidgets import QWebEnginePage from bs4 import BeautifulSoup import re class Client(QWebEnginePage): def __init__(self, url): self.app = QApplication(sys.argv) QWebEnginePage.__init__(self) self.html = '' self.loadFinished.connect(self._on_load_finished) self.load(QUrl(url)) #Ignote mainFrame from PyQt4 self.app.exec_() def _on_load_finished(self): self.html = self.toHtml(self.Callable) print('Load finished') def Callable(self, html_str): self.html = html_str self.app.quit() def scrape_pyqt5(): lists = ['example1.com/a', 'example1.com/b', 'example1.com/c'] for url in lists: r = Client(url) bs = BeautifulSoup(r.html, 'html.parser') for link in bs.find_all('div', {'id': 'media-player'}): for directlink in link.find_all('iframe'): print(directlink)
type: Question
tagged with: pyqt
has comment: http://stackoverflow.com/comment/82995064
downvote count: 0
has comment: http://stackoverflow.com/comment/82995652
score: 1
has title: Python.exe crash with PyQt5
favorite count: 0
linked to: http://stackoverflow.com/q/21274865

http://stackoverflow.com/comment/82853147
type: Comment
score: 0
type: QuestionComment
has text: The suggested answers [https://stackoverflow.com/questions/8356336/how-to-capture-output-of-pythons-interpreter-and-show-in-a-text-widget](https://stackoverflow.com/questions/8356336/how-to-capture-output-of-pythons-interpreter-and-show-in-a-text-widget) and [(https://stackoverflow.com/questions/11465971/redirecting-output-in-pyqt)](https://stackoverflow.com/questions/11465971/redirecting-output-in-pyqt) are not helpful.
comment on: http://stackoverflow.com/q/47883265

http://stackoverflow.com/comment/82868016
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47890664
has text: thanks! that worked though i did need to change the shape first like u suggested

http://stackoverflow.com/q/47909021
has title: Error-to train neural net with Keras and my own csv data
tagged with: python
type: AnsweredQuestion
has body: Good day!I want to use Keras python library to train neural net I want to make 4 input neurons and 1 output neuron.I want to use my own csv file with numbers:here is it my_5_input_numbers.csv 0.3,0.5,0.6,0.7,1 0.4,0.6,0.7,0.8,0 0.5,0.7,0.8,0.9,1 I use numpy to read csv and make train matrix.Here is the code and the error import numpy as np np.set_printoptions(threshold=np.inf) from keras.datasets import boston_housing from keras.models import Sequential from keras.layers import Dense data_common=np.genfromtxt('my_5_input_numbers.csv',delimiter=',') """ data_common=array([[ 0.3, 0.5, 0.6, 0.7, 1. ], [ 0.4, 0.6, 0.7, 0.8, 0. ], [ 0.5, 0.7, 0.8, 0.9, 1. ]]) data_common.shape=(3,5) """ X_train=data_common[:,-1]#X_train.shape=(3,4) y_train=data_common[0:4,-1]#y_train.shape=(3,) y_train=y_train.reshape(3,1) model = Sequential() model.add(Dense(128,input_dim=4,activation='relu')) model.add(Dense(1,activation="softmax")) model.compile(optimizer='adam', loss='mse', metrics=['mae']) # train nn model.fit(X_train, y_train, batch_size=200, epochs=25, validation_split=0.2, verbose=2) #&lt;---Error:File "D:\NetbeansPythonProjects\testDiffrentCode\src\testKeras.py", line 16, in &lt;module&gt; # model.fit(X_train, y_train, batch_size=200, epochs=25, validation_split=0.2, verbose=2) #ValueError: #Error when checking input: #expected dense_1_input to have shape (None, 4) but got array with shape (3, 1)
type: Question
tagged with: neural-network
tagged with: keras
score: 0
has answer: http://stackoverflow.com/a/47913217
accepted answer: http://stackoverflow.com/a/47913217
answer count: 1

http://stackoverflow.com/q/48014244
has body: I'd like to split each line of a text file into two by " - ", but I keep getting this error: File "quiz.py", line 21, in Vocab questions, answers = line.split("-") ValueError: too many values to unpack (expected 2) I'm quite new to coding and could use some help. All tips are welcome as well! import hashlib testFile = "" def qSearch(): options = input ("Vocab/Grammar/or Special? (v/g/s)") if options == "v": testFile = "Vocabtest" Vocab() elif options == "g": Grammar() testFile = "Grammartest" elif options == "s": Special() testFile = "Specialtest" else: qSearch() def Vocab(): with open('Vocabtest.txt','r') as f: for line in f: questions, answers = line.split("-") ### error print (questions) qSearch() The text in my text file is formatted like so: Magandang umaga - Good Morning Magandang hapon - Good Afternoon Magandang gabi - Good evening Magandang umaga sa’yo - Good Morning to you Magandang hapon din sa’yo - Good Afternoon to you to
type: Question
answer count: 2
score: -1
has title: ValueError when splitting lines in a text file
tagged with: string
favorite count: 0
tagged with: parsing
has answer: http://stackoverflow.com/a/48014291
type: UnansweredQuestion
downvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/48014296
upvote count: 1

http://stackoverflow.com/comment/82825955
has text: Almost, just switch the order. `[[el.strip('D') for el in text] for text in texts]`
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/47928702

http://stackoverflow.com/a/47992432
has body: f1 = open('input.txt','r') for line in f1: if "&lt;div" in line: if "text-align" in line; else: f1.write(line.replace(THIS_LINE,"") Doesn't have statement after if, so it can't work. Besides you can combine two conditions: with open('input.txt','r') as f1, open('output.txt', 'w') as f_out: for line in f1: if not ("&lt;div" in line and "text-align" not in line): f2.write(line)
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/82953225
downvote count: 0
has comment: http://stackoverflow.com/comment/82953071
answers question: http://stackoverflow.com/q/47992385
upvote count: 2
has comment: http://stackoverflow.com/comment/82953139

http://stackoverflow.com/comment/87712681
score: 4
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48828449
has text: I would love to learn more about which differences between OSX and Linux are having an effect here. Could you expand your answer a bit on this topic?

http://stackoverflow.com/q/47949013
type: UnansweredQuestion
has title: Why are parentheses required for assignment of a tuple to an annotated variable?
has comment: http://stackoverflow.com/comment/82868001
has answer: http://stackoverflow.com/a/47972271
has comment: http://stackoverflow.com/comment/82868005
score: 4
type: Question
upvote count: 4
tagged with: syntax-error
answer count: 1
downvote count: 0
tagged with: iterable-unpacking
favorite count: 0
has body: When I have a line that looks like this: t: Tuple[int, int] = 0, 1 … I get a SyntaxError, but when I do this: t = 0, 1 t: Tuple[int, int] = (0, 1) … it's valid. Is this intentional? Is there an ambiguity in the parse tree with a type specifier and no parens?
has comment: http://stackoverflow.com/comment/82868010
tagged with: python
tagged with: python-typing

http://stackoverflow.com/comment/82771049
score: 0
type: QuestionComment
has text: @MarkDickinson : As you mentioned, I meant it should be classified as a JSONArray.
type: Comment
comment on: http://stackoverflow.com/q/47901728

http://stackoverflow.com/comment/82737693
type: Comment
score: 0
has text: Thanks for the help! I will use lists and iterations and the check this answer.
type: AnswerComment
comment on: http://stackoverflow.com/a/47886075

http://stackoverflow.com/a/47892835
has body: Use im.items() to convert your dict to a tupples. Then use indexes to access the elements. im = { 'Time Series (1min)': { '2017-12-19 13:01:00': { '1. open': '196.4100', '2. high': '196.5075', '3. low': '196.3800', '4. close': '196.3800', '5. volume': '4961' } } } For Python 2 print im['Time Series (1min)'].items()[0][1]['4. close'] # prints 196.3800 for Python 3, this should change as follows print(list(a['Time Series (1min)'].items())[0][1]['4. close']) # prints 196.3800 or you can loop through a['Time Series (1min)'].items() iterable
answers question: http://stackoverflow.com/q/47892781
has comment: http://stackoverflow.com/comment/82756788
has comment: http://stackoverflow.com/comment/82752221
has comment: http://stackoverflow.com/comment/82752725
score: 0
has comment: http://stackoverflow.com/comment/82755884
has comment: http://stackoverflow.com/comment/82752692
has comment: http://stackoverflow.com/comment/82752927
type: Answer
has comment: http://stackoverflow.com/comment/82752214

http://stackoverflow.com/q/47973599
tagged with: pip
has comment: http://stackoverflow.com/comment/84886082
possible better answer: http://stackoverflow.com/a/47973738
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47973792
accepted answer: http://stackoverflow.com/a/47973792
type: Question
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/84982947
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/84968351
has body: I'm running MacOS Sierra 10.12.6 By default the system came with Python 2.7.10 I installed Python 3.6.3 (with IDLE) so I can learn Python (3). I understand that this is normal as MacOS may rely on Python 2.x for some programs. Either way, Python3 runs just fine if I run python3 from the command line/terminal, or if I use IDLE (which defaults to Python 3). Now I want to install some libraries like Beautiful Soup. And I believe I can install it as follows: pip3 install beautifulsoup4 which should automatically install it. However, I read that it's recommended to use virtualenv on Mac BEFORE I run the above command. As a newbie, I don't want to mess anything up on my PC, so can anyone point me out how I can do this correctly? For example, I can follow this link: http://sourabhbajaj.com/mac-setup/Python/virtualenv.html But I just want to write here to make sure I'm following the right article/commands before I do it. Just being super careful! Also, can I make a folder with my "virtual environment" and then add sub-folders inside that for each project? Meaning, I don't need to do this everytime, I have one virtual environment and any project that I do just is a subfolder within that space so I can use any libraries that I installed. Just trying to grasp the concept. Thanks!
tagged with: python
has title: Running pip3 on MacOS Sierra (Python newbie) - do I need a virtualenv?
has answer: http://stackoverflow.com/a/47973738
has comment: http://stackoverflow.com/comment/84888914

http://stackoverflow.com/comment/90045286
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47956702
has text: I am also interested in web scrapping clinical trials website. Is this project of yours an open-source project? I'm fairly new to web scrapping and I don't know where to start. Would you be willing to share your script. I just basically want to make my own search engine for trials with specific conditions etc.

http://stackoverflow.com/comment/109753269
has text: I could see how that would be taxing for AWS to do a full table scan of its keys, but isn't that what often happens anyways when a user like OP has to scan all of the objects through a rest API and perform a text search on all the keys on the client side?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47878893
type: QuestionComment

http://stackoverflow.com/a/47860328
type: Answer
answers question: http://stackoverflow.com/q/47860107
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/82685706
has body: Anytime you think you need a loop in pandas, check your code one more time. One clue is that you have for row in df_EVENT5_18['FLT']:, but you never use row. Find indicies that match a string In this case we can simply use boolean evaluation to get the indices that we want to set: has_flt_1234 = df_EVENT5_18['FLT'].str.contains('1234') want_29 = has_flt_1234 &amp; df_EVENT5_18['AR'].str.contains('ABC1') want_25 = has_flt_1234 &amp; df_EVENT5_18['AR'].str.contains('ABC2') Setting values using boolean series Then set the appropriate rows as desired: df_EVENT5_18['MSP'][want_25] = '25' df_EVENT5_18['MSP'][want_29] = '29' Test Code: import pandas as pd df_EVENT5_18 = pd.DataFrame(dict( FLT=['1234', '1234', '1235'], AR=['ABC1', 'ABC2', 'ABC1'] )) print(df_EVENT5_18) has_flt_1234 = df_EVENT5_18['FLT'].str.contains('1234') want_29 = has_flt_1234 &amp; df_EVENT5_18['AR'].str.contains('ABC1') want_25 = has_flt_1234 &amp; df_EVENT5_18['AR'].str.contains('ABC2') # Create a new column from the list df_EVENT5_18['MSP'] = '' df_EVENT5_18['MSP'][want_25] = '25' df_EVENT5_18['MSP'][want_29] = '29' print(df_EVENT5_18) Results: AR FLT 0 ABC1 1234 1 ABC2 1234 2 ABC1 1235 AR FLT MSP 0 ABC1 1234 29 1 ABC2 1234 25 2 ABC1 1235
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47860107
has comment: http://stackoverflow.com/comment/82685651

union
type: Tag
tags question: http://stackoverflow.com/q/47899477
tag name: union
tags question: http://stackoverflow.com/q/47945540

http://stackoverflow.com/comment/82874468
comment on: http://stackoverflow.com/q/47905076
score: 0
type: Comment
type: QuestionComment
has text: Vectors will increase if the species in the reaction is more. In the above example we have 4 species - a,b,c,d and 3 reactions, so we have 3 array vectors for 4 species v1, v2, v3. Let me check if i can do something with subset sum problem. If i get something out of this, i will post here. Many thanks.

http://stackoverflow.com/q/47891829
has comment: http://stackoverflow.com/comment/82758430
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/82751396
type: Question
has body: For context, I'm making a framework for creating RSS feeds from arbitrary pages. The way it works is I have a base class with a lot of setup and want to plug in generators that describe items being returned; then I create one instance of this class. I can think of two ways to do this: 1) Make a derived class that overrides all relevant properties and methods and then create an instance of it: class Base: property = None def customizable_function(self, many, different, arguments): raise NotImplementedError() def __init__(self): non_customizable_preparation() customizable_function(1, 2, 3) class Derived: property = "useful" def customizable_function(self, many, different, arguments): do_stuff() Derived() 2) Don't create a second class, make the init function take all relevant arguments: class Base: def __init__(self, customizable_function, property): non_customizable_preparation() customizable_function(1, 2, 3) def function_that_will_be_passed(self, many, different, arguments): do_stuff() Base(function_that_will_be_passed, property="useful") The second approach seems cleaner, but in it customizable_function has to be defined outside of a class, while having its signature match what is expected. Is there some non-obvious concern which makes one of those approaches significantly better? Or is this whole thing a bad idea and I should do everything differently?
score: 0
has comment: http://stackoverflow.com/comment/82750510
has comment: http://stackoverflow.com/comment/82751123
has title: What is the best practice for modifying a part of a base class for one-time usage?

http://stackoverflow.com/comment/82797440
has text: @Nae I would agree, but the way OP starts the code in the last line prevents that.
comment on: http://stackoverflow.com/q/47914501
type: Comment
type: QuestionComment
score: 0

plot
tags question: http://stackoverflow.com/q/47998025
tags question: http://stackoverflow.com/q/47967758
tags question: http://stackoverflow.com/q/48012513
tags question: http://stackoverflow.com/q/47925087
tags question: http://stackoverflow.com/q/47972932
tags question: http://stackoverflow.com/q/47963339
tags question: http://stackoverflow.com/q/47973144
tags question: http://stackoverflow.com/q/47957314
tags question: http://stackoverflow.com/q/47872845
tags question: http://stackoverflow.com/q/48013355
tag name: plot
tags question: http://stackoverflow.com/q/47986702
tags question: http://stackoverflow.com/q/47963797
tags question: http://stackoverflow.com/q/47926332
tags question: http://stackoverflow.com/q/47942273
tags question: http://stackoverflow.com/q/47903691
tags question: http://stackoverflow.com/q/48007749
tags question: http://stackoverflow.com/q/47891531
tags question: http://stackoverflow.com/q/47907427
tags question: http://stackoverflow.com/q/47965447
type: Tag
tags question: http://stackoverflow.com/q/47929364
tags question: http://stackoverflow.com/q/47990579
tags question: http://stackoverflow.com/q/47930211
tags question: http://stackoverflow.com/q/47871398
tags question: http://stackoverflow.com/q/47859486
tags question: http://stackoverflow.com/q/47971925
tags question: http://stackoverflow.com/q/47930267
tags question: http://stackoverflow.com/q/47858545
tags question: http://stackoverflow.com/q/47930196
tags question: http://stackoverflow.com/q/48014586
tags question: http://stackoverflow.com/q/47997772
tags question: http://stackoverflow.com/q/47908749
tags question: http://stackoverflow.com/q/47913300
tags question: http://stackoverflow.com/q/47952911

http://stackoverflow.com/a/47857450
has comment: http://stackoverflow.com/comment/82679384
has body: days=[] days.append("Monday ") days.append(" Tuesday") print days[0] days[0] is the index position of your first element. (I.e, "Monday")
upvote count: 2
score: 1
downvote count: 1
answers question: http://stackoverflow.com/q/47857297
has comment: http://stackoverflow.com/comment/82679247
type: Answer

http://stackoverflow.com/comment/82706742
type: Comment
score: 1
has text: Did you try loading the graph and actually checking something went wrong? A lot of stuff gets discarded when freezing the graph (all the training-related nodes, for example), so a reduction in size is not necessarily a sign of an error
type: QuestionComment
comment on: http://stackoverflow.com/q/47870314

http://stackoverflow.com/comment/82867467
type: QuestionComment
score: 2
has text: It's very possible it has to do with which projection the map is using. The earth is round, but when we look at a map of it, it's always represented as a rectangle. This is possible using a projection like https://en.wikipedia.org/wiki/Mercator_projection. If the map is using any sort of projection, you have to keep that in mind for your math.
type: Comment
comment on: http://stackoverflow.com/q/47948674

http://stackoverflow.com/q/47863001
accepted answer: http://stackoverflow.com/a/47867513
favorite count: 0
has answer: http://stackoverflow.com/a/55297550
has body: With python lists, we can do: a = [1, 2, 3] assert a.index(2) == 1 How can a pytorch tensor find the .index() directly?
tagged with: python
has answer: http://stackoverflow.com/a/63349186
has answer: http://stackoverflow.com/a/71833292
type: AnsweredQuestion
score: 71
has answer: http://stackoverflow.com/a/67504922
has answer: http://stackoverflow.com/a/51340765
tagged with: pytorch
upvote count: 71
has comment: http://stackoverflow.com/comment/102976197
has answer: http://stackoverflow.com/a/77043122
type: Question
has title: How Pytorch Tensor get the index of specific value
has answer: http://stackoverflow.com/a/47867513
answer count: 11
has answer: http://stackoverflow.com/a/73162500
linked to: http://stackoverflow.com/q/51703981
possible better answer: http://stackoverflow.com/a/67175757
has answer: http://stackoverflow.com/a/67175757
downvote count: 0
has answer: http://stackoverflow.com/a/68411940
has answer: http://stackoverflow.com/a/55962387

http://stackoverflow.com/a/47930908
has comment: http://stackoverflow.com/comment/82833645
has comment: http://stackoverflow.com/comment/82835666
has body: When you write this: &gt;&gt;&gt; data = '\\host\printer' You end up with data containing the literal string \host\printer, because in Python \ is an escape character, and when you want a single \ you need to write \\. You can disable this behavior by using a raw string, or by escaping \ whenever you use it. So you can write: &gt;&gt;&gt; data = '\\\\host\\printer' Or you can write: &gt;&gt;&gt; data = r'\\host\printer' Since you want the literal string \\\\host\\printer, you need to replace every instance of \ with \\. Which means you can write this: &gt;&gt;&gt; newdata = data.replace('\\', '\\\\') And that gets you: &gt;&gt;&gt; print newdata \\\\host\\printer The String Literals section of the docs has some details on the above.
has comment: http://stackoverflow.com/comment/82833113
has comment: http://stackoverflow.com/comment/82858918
score: 0
type: Answer
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82855349
has comment: http://stackoverflow.com/comment/82839359
answers question: http://stackoverflow.com/q/47930283
has comment: http://stackoverflow.com/comment/82835738

http://stackoverflow.com/comment/82831777
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47929477
has text: `for line in file` should be `for line in FileName`
score: 0

http://stackoverflow.com/a/47898304
has body: http://www.rexegg.com/regex-quickstart.html is a good resource for regex the * character means find 0 or more this will find a with 0 b's the + character means find 1 or more so (ab+) will find abbb
type: Answer
answers question: http://stackoverflow.com/q/47898203
score: 0

http://stackoverflow.com/q/47875322
has title: Django TypeError using TextField bounding the form
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: django-forms
type: Question
has answer: http://stackoverflow.com/a/47875530
score: 0
answer count: 1
has body: I want to create a simple wiki page, which is comprised of several entries. But have an error TypeError at /addentry __init__() got an unexpected keyword argument 'title' The main thing here is entry model. Here is part of my models.py: class wikies(models.Model): num = models.CharField(max_length=15) title = models.CharField(max_length=150) text = models.TextField() And here is part of my forms.py: class entryform(ModelForm): class Meta: model = wikies fields = ['num', 'title', 'text'] Part of my template: &lt;form action="{% url 'addentry' %}" method="post" enctype="multipart/form-data"&gt; {% csrf_token %} &lt;p&gt; {{entryform.num}} &lt;/p&gt; &lt;p&gt; {{entryform.title}} &lt;/p&gt; &lt;p&gt; {{entryform.text}}&lt;/p&gt; &lt;p&gt;&lt;input type="submit" value="Add Entry" /&gt;&lt;/p&gt; This is part of my views.py, where I catch the error: def addentry(request): if request.method =='POST': form = entryform(num = request.POST['num'], title = request.POST['title'], text = request.POST['text'] ) I want to bound the form with values I just get, but have the following error: TypeError at /addentry init() got an unexpected keyword argument 'title' Here are POST values: num '1.2.3' text 'Water is very important resource.' title 'Importance of water' I've read the docs, I've searched through StackOverflow, but I have no idea what to do. Will appreciate any help.

http://stackoverflow.com/q/47945163
has comment: http://stackoverflow.com/comment/82860082
has body: Below is code for checking whether a given array is sorted. Tried putting in a print command at various stages to understand the code line by line, but to no avail. def sort(a): if len(a) == 1: return True return a[0] &lt;= a[1] and isSorted(a[1:]) a =[127,220,246,277,321,454,534,565,933] print(sort(a)) Firstly This is throwing an error NameError: name 'isSorted' is not defined. Second The whole code seems like a shorthand. There is no else after if, why is the isSorted only looking from index position 1. This is supposed to a recursive function, can't see one.
tagged with: arrays
tagged with: sorting
score: 0
has comment: http://stackoverflow.com/comment/82860411
has answer: http://stackoverflow.com/a/47945229
accepted answer: http://stackoverflow.com/a/47945229
possible better answer: http://stackoverflow.com/a/47945443
tagged with: python
has answer: http://stackoverflow.com/a/47945443
tagged with: recursion
type: AnsweredQuestion
type: Question
has title: Array sorted order recrusion
answer count: 2

http://stackoverflow.com/q/47904508
has comment: http://stackoverflow.com/comment/82776924
has comment: http://stackoverflow.com/comment/82777882
tagged with: azure-machine-learning-service
score: 0
has comment: http://stackoverflow.com/comment/82775737
has comment: http://stackoverflow.com/comment/82776437
tagged with: azure
answer count: 1
tagged with: scikit-learn
linked to: http://stackoverflow.com/q/44593469
has comment: http://stackoverflow.com/comment/82777736
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47905199
has body: I'm using Azure Machine Learning Studio which supports version 17.0 of scikit-learn. I would like to use newer one. You can do it as described here. But this causes name aliasing so I would have to change the name of the library which file can be found here. I don't know which parts of files I'm supposed to change so I can import scikit-learn as something else than import sklearn
has comment: http://stackoverflow.com/comment/82777358
has comment: http://stackoverflow.com/comment/82776641
type: Question
has title: Change the name of a Python library within its file

http://stackoverflow.com/a/47972198
answers question: http://stackoverflow.com/q/47972171
type: Answer
has body: There are two major errors that stand out to me immediately as I ran through your code: Variable scope issues. Attribute name overwriting issues. You are calling range on nor. I can see that you meant to call it on the variable nor that is defined inside of the function nor and not the function itself. There are two immediate solutions, either you create a variable called nor_val (or anything different from nor), in the scope above (where you defined all the other variables); and update that variable inside of your nor function and use it in the range call. The second option is to make your nor function return the nor attribute at the end of execution, and instead of calling range(nor) you would call range(nor()). In the first case, you would add a line like nor_val = 0 where you are declaring your attributes, and then replace all instances of nor where you mean the variable (not the function) with nor_val. In the second case, you would add a line like return nor at the end of your nor function, and change the range(nor) to be range(nor()). However, in both cases, your variable naming is not very intuitive. You should try to not reuse names as they could cause this type of confusion. Your nor function does not describe what the function actually does. I might call it something like get_number_rooms or something along those lines, and I would call the nor variable maybe rooms.
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/47972171
has comment: http://stackoverflow.com/comment/82936506
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82933598
downvote count: 0

http://stackoverflow.com/q/47882305
has title: Tkinter in raspberry pi bash
answer count: 1
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47882545
tagged with: tkinter
has body: I am able to import tkinter in idle3 and used it to create a simple application and in Idle3 everything works great. The problem is, if I try to start the program from bash, I get the error: ImportError: No module named 'tkinter.filedialog'; 'tkinter is not a package Why would the pi be able to run a program in idle3 but not when start with python3 program.py It seems to be that idle3 recognizes the tkinter package but my bash cannot. Any Solutions?
has comment: http://stackoverflow.com/comment/82742448
type: Question
score: 0
tagged with: bash

dialog
tag name: dialog
tags question: http://stackoverflow.com/q/47924373
type: Tag
tags question: http://stackoverflow.com/q/47904685

http://stackoverflow.com/q/47980907
has title: Count number of unique row in dataframe pandas
has answer: http://stackoverflow.com/a/47980919
answer count: 3
tagged with: pandas
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/47980919
has answer: http://stackoverflow.com/a/73034913
type: AnsweredQuestion
score: 3
tagged with: group-by
upvote count: 3
linked to: http://stackoverflow.com/q/40551335
has answer: http://stackoverflow.com/a/47981016
tagged with: dataframe
type: Question
has body: I need to count the number of unique rows in a pandas dataframe. I have tried this solution but it generates an error. This is my code: import pandas as pd df = {'x1': ['A','B','A','A','B','A','A','A'], 'x2': [1,3,2,2,3,1,2,3]} df = pd.DataFrame(df) print df.groupby(['x1','x2'], as_index=False).count() This is the error: Traceback (most recent call last): File "/home/user/workspace/project/test.py", line 9, in <module> print df.groupby(['x1','x2'], as_index=False).count() File "/usr/local/lib/python2.7/dist-packages/pandas/core/groupby.py", line 4372, in count return self._wrap_agged_blocks(data.items, list(blk)) File "/usr/local/lib/python2.7/dist-packages/pandas/core/groupby.py", line 4274, in _wrap_agged_blocks index = np.arange(blocks[0].values.shape[1]) IndexError: list index out of range What am I doing wrong?
possible better answer: http://stackoverflow.com/a/47981016
downvote count: 0

http://stackoverflow.com/a/47892724
has body: g=df.groupby('number') i=g.apply(lambda x : min(x['date'][x.type==1])) j=g.apply(lambda x : min(x['date'][x.type==2])) k=g.type.nunique()==2 df['New'] = df.number.map(~(i &gt; j) &amp; k) df Out[588]: type number date New 0 1 1 2017-10-01 True 1 2 1 2017-10-31 True 2 1 2 2017-09-01 False 3 1 2 2017-08-01 False 4 2 2 2017-06-01 False
upvote count: 2
has comment: http://stackoverflow.com/comment/82752727
answers question: http://stackoverflow.com/q/47892479
has comment: http://stackoverflow.com/comment/82752706
has comment: http://stackoverflow.com/comment/82779364
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/82772547
downvote count: 0

http://stackoverflow.com/comment/82769123
has text: Oops, I didn't really mean to close as duplicate (didn't realize this was also tagged [tag:bash]). I'll be happy to reopen if the current duplicate doesn't solve your problem, or at least look for a different duplicate.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47899453

http://stackoverflow.com/comment/135107433
type: AnswerComment
type: Comment
has text: `--install-option` is not an option for later versions of pip
score: 1
comment on: http://stackoverflow.com/a/70914890

http://stackoverflow.com/q/47983519
tagged with: python
favorite count: 0
score: 2
type: AnsweredQuestion
downvote count: 0
has body: How does H2O determine the weights for base learners? For exp. here in the example, are all the base learners equally weighted? And do I have a chance to use regularization parameters (e.g. ridge) in metalearner_algorithm? What would be the best way to avoid overfitting?
accepted answer: http://stackoverflow.com/a/47992561
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/47992561
tagged with: ensemble-learning
has title: How does H2O weigh base learners when stacking ensemble is applied?
tagged with: h2o
answer count: 1

http://stackoverflow.com/comment/82992832
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48012086
has text: Please add code and the error messages to your question

http://stackoverflow.com/q/47967774
tagged with: google-chrome-devtools
has comment: http://stackoverflow.com/comment/82905027
has title: can I access to network tab of google chrome developer tools with python?
answer count: 2
linked to: http://stackoverflow.com/q/20401264
downvote count: 0
has answer: http://stackoverflow.com/a/68363325
favorite count: 0
tagged with: python
score: 2
tagged with: selenium-chromedriver
has body: I tried to get some information in a request in some web pages and I need some information that can find it from network tab of google chrome developer tools for example when I click on followers on Instagram web, the browser sends a GET method with a parameter named "query_id", I want to find it, I can find it in network tab in google chrome dev tools but now I want to find this parameter with python, how can I do it? is there any way that I access network tab with python?
upvote count: 2
has answer: http://stackoverflow.com/a/48000749
type: UnansweredQuestion
tagged with: selenium
tagged with: google-chrome
type: Question
has comment: http://stackoverflow.com/comment/82906018

http://stackoverflow.com/comment/82805631
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47918448
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/161678/discussion-between-arun-and-exprator).
type: AnswerComment

http://stackoverflow.com/comment/82863898
score: 0
comment on: http://stackoverflow.com/q/47946897
type: Comment
type: QuestionComment
has text: @Robᵩ I'm pretty sure it's part of the string to match itself. I don't see how non-ASCII (32-127) chars would be a part of the special regex chars. I agree it's not a duplicate. but since it's part of the string to match, it's just "unclear" or sth like that.

http://stackoverflow.com/comment/82817684
has text: I found an apparently similar open issue in keras github: https://github.com/keras-team/keras/issues/8823
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47923370

http://stackoverflow.com/q/48008334
score: 9
type: Question
tagged with: pii
tagged with: anonymize
has answer: http://stackoverflow.com/a/48009472
tagged with: pandas
has body: I have loaded an s3 bucket with json files and parsed/flattened it in to a pandas dataframe. Now i have a dataframe with 175 columns with 4 columns containing personally identifiable information. I am looking for a quick solution anonymising those columns (name &amp; adress). I need to keep information for multiples so that if names or adresses of the same person occuring multiple times have the same hash. Is there existing functionality in pandas or some other package i can utilize for this?
answer count: 4
upvote count: 9
has answer: http://stackoverflow.com/a/48020208
type: UnansweredQuestion
tagged with: python
has title: Anonymize specific columns with pii in pandas dataframe python
has answer: http://stackoverflow.com/a/48009703
downvote count: 0
favorite count: 0
tagged with: privacy
has answer: http://stackoverflow.com/a/48009224

http://stackoverflow.com/comment/125440394
has text: The intel instruction says `conda install tensorflow-mkl` https://www.intel.com/content/www/us/en/developer/articles/guide/optimization-for-tensorflow-installation-guide.html
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49187554
type: Comment

http://stackoverflow.com/q/47975097
has title: google api and APscheduler
score: 0
answer count: 1
tagged with: apscheduler
accepted answer: http://stackoverflow.com/a/48016087
tagged with: python
has body: So the problem i'm having with these libraries is that when i try and compile the python script with cx_freeze if I have version 3 of APscheduler it refuses to compile error message: "ImportError: No module named 'apscheduler.executors.base_py3'" and when I try compile it with the 2.1.2 version it compiles but when run throws an error saying it cant import from apscheduler.schedulers.blocking import BlockingScheduler does anyone know a way around this or have a solution? code below: import gspread, time, requests from oauth2client.service_account import ServiceAccountCredentials from apscheduler.schedulers.blocking import BlockingScheduler def update(): print("used") scope = ['https://spreadsheets.google.com/feeds'] creds = ServiceAccountCredentials.from_json_keyfile_name('details.json', scope) client = gspread.authorize(creds) sheet = client.open('ip_display').sheet1 userip = (requests.get("http://jsonip.com/").json())["ip"] row = [userip, ] sheet.update_cell(2, 1, userip) sheet.update_cell(2, 2, time.strftime("%H:%M:%S")) scheduler = BlockingScheduler() job = scheduler.add_job(update, 'interval', hours=1) scheduler.start()
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48016087
tagged with: google-api
type: Question

http://stackoverflow.com/comment/99449510
comment on: http://stackoverflow.com/a/47931427
type: AnswerComment
score: 0
type: Comment
has text: You use `is` to compare object identities.

http://stackoverflow.com/q/47937446
tagged with: openstack
tagged with: xargs
type: Question
linked to: http://stackoverflow.com/q/11710552
upvote count: 5
answer count: 2
tagged with: bash
has answer: http://stackoverflow.com/a/47955094
score: 5
downvote count: 0
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/47937622
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47955094
has title: Parallel processing with xargs in bash
has body: I had a small script where I would source into each openstack's tenant and fetch some output with the help of python. It took too long for the reports to get generated and I was suggested to use xargs. My earlier code was like below. #!/bin/bash cd /scripts/cloud01/floating_list rm -rf ./reports/openstack_reports/ mkdir -p ./reports/openstack_reports/ source ../creds/base for tenant in A B C D E F G H I J K L M N O P Q R S T do source ../creds/$tenant python ../tools/openstack_resource_list.py &gt; ./reports/openstack_reports/$tenant.html done lftp -f ./lftp_script Now I have put xargs in the script and the script looks something like this. #!/bin/bash cd /scripts/cloud01/floating_list rm -rf ./reports/openstack_reports/ mkdir -p ./reports/openstack_reports/ source ../creds/base # Need xargs idea below cat tenants_list.txt | xargs -P 8 -I '{}' # something that takes the tenant name and source TENANT_NAME={} python ../tools/openstack_resource_list.py &gt; ./reports/openstack_reports/$tenant.html lftp -f ./lftp_script In this script how am I supposed to implement source ../creds/$tenant? Because while each tenant is dealt with, it needs to be sourced as well and I am not sure how to include that with xargs for parallel execution.
has answer: http://stackoverflow.com/a/47937622

http://stackoverflow.com/comment/82884489
type: QuestionComment
has text: This likely means your list is empty. Try printing out the length of `chain["chain"]` with `print(len(chain['chain']))`.
comment on: http://stackoverflow.com/q/47957598
score: 0
type: Comment

http://stackoverflow.com/comment/82720363
type: AnswerComment
comment on: http://stackoverflow.com/a/47864454
score: 0
type: Comment
has text: I think Python's behavior is normal. The behavior of the command running a sub-shell seems like it's the odd behavior to me. I'd expect it to run the second command regardless of what happened to the first command. Perhaps it's related to `sleep` being an shell internal command, rather than a separate program? I have no idea.

http://stackoverflow.com/comment/82824479
type: QuestionComment
has text: that's probably the easiest way. you could try reinstalling `libstdc++` like `apt-get install libstdc++`, but I don't guarantee that will work
score: 0
comment on: http://stackoverflow.com/q/47927755
type: Comment

http://stackoverflow.com/comment/82914579
score: 0
type: QuestionComment
type: Comment
has text: the order is not important here
comment on: http://stackoverflow.com/q/47957305

http://stackoverflow.com/comment/82771139
has text: I don't need to save or restore model. I only want to check values of variables after model is trained.
type: Comment
comment on: http://stackoverflow.com/a/47880150
score: 0
type: AnswerComment

http://stackoverflow.com/q/47891419
has answer: http://stackoverflow.com/a/47891738
accepted answer: http://stackoverflow.com/a/47891738
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82749409
has comment: http://stackoverflow.com/comment/82749548
type: Question
has title: Creating Python package fails because one file can't see the other
has comment: http://stackoverflow.com/comment/82749705
linked to: http://stackoverflow.com/q/14132789
answer count: 1
has body: I have 3 files in a Python module called flags. Empty __init__.py file data.py lookup.py lookup.py contains the line from data import list_of_data_items If I then try to run from flags import lookup I get ModuleNotFoundError: No module named 'data' Importing data works without issue &gt;&gt;&gt; from flags import data &gt;&gt;&gt;
has comment: http://stackoverflow.com/comment/82749653
score: 0
has comment: http://stackoverflow.com/comment/82749318
tagged with: python-module
has comment: http://stackoverflow.com/comment/82749615
has comment: http://stackoverflow.com/comment/82749589

http://stackoverflow.com/q/47971928
has body: How to save (and restore) the values of the graphical elements of the wxWidgets in Python? I want some more friendly way, maybe using a for to scrape all the elements and save the current value in a txt when I close the window and restore when I load the app. I do not want to typing 2 line of code (save and restore) to each new element that I add.
has title: wxWidgets Python save checkbox and other elements values in a text
has answer: http://stackoverflow.com/a/48043233
has comment: http://stackoverflow.com/comment/82932203
tagged with: wxwidgets
answer count: 1
has comment: http://stackoverflow.com/comment/82929671
score: 0
accepted answer: http://stackoverflow.com/a/48043233
tagged with: python
tagged with: checkbox
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82931176
type: Question

http://stackoverflow.com/comment/82746893
type: QuestionComment
has text: @Alex.S I have added my code
comment on: http://stackoverflow.com/q/47890055
score: 0
type: Comment

http://stackoverflow.com/q/47865586
has comment: http://stackoverflow.com/comment/82697631
has comment: http://stackoverflow.com/comment/82696252
type: Question
answer count: 2
downvote count: 4
has comment: http://stackoverflow.com/comment/82696837
score: -2
has answer: http://stackoverflow.com/a/49208156
favorite count: 0
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/87597214
tagged with: python
has body: I want to perform integration of an equation with one variable and few constants in the form of symblos namely, A,k,p whose values I have planned to enter after integration. Integrating equation with only one variable but with no other symbol(containing some constant value) is simple and direct, but for the case in which symbols are present, integration using quad from scipy.integrate gives an error. Actually quad() requires the values of all symbols to be pre-defined. I want a solution where I don't have to enter the values for symbols beforehand but take an input and substitue them afterwards. To make the problem even more clear, I want to integrate a wave equation A * sin(kx + wt) , where A is amplitude, w is angular velocity, t is time and x is position (x is only variable ) quad() requires to define the values for A, k and p before integrating but what I want to do is first integrate A * sin(kx + wt) and then substitue the values for A, k and p in the result by taking user input . Please suggest a method to do so :)
has title: Integration in python containing some parameter
has answer: http://stackoverflow.com/a/47866140
accepted answer: http://stackoverflow.com/a/49208156
upvote count: 2
possible better answer: http://stackoverflow.com/a/47866140
has comment: http://stackoverflow.com/comment/82696269
type: AnsweredQuestion

http://stackoverflow.com/comment/82941378
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47986231
has text: This is perfect! Do you think this would work faster then using loops? I am trying to minimize the run time

http://stackoverflow.com/q/48002785
has answer: http://stackoverflow.com/a/48002828
downvote count: 0
has answer: http://stackoverflow.com/a/64292642
linked to: http://stackoverflow.com/q/62962387
has body: I haven't been able to find a solution to this problem elsewhere, even though it seems it should be a common one. import logging logging.basicConfig(filename='logs.log', level=logging.INFO) logging.info('something happened') I want to create and write to the log file, but instead it displays the messages in the notebook output cell.
has answer: http://stackoverflow.com/a/48005958
has answer: http://stackoverflow.com/a/54828178
tagged with: jupyter
has title: Cannot get jupyter notebook to log to a file
favorite count: 0
answer count: 5
score: 6
tagged with: python
upvote count: 6
tagged with: logging
accepted answer: http://stackoverflow.com/a/48005958
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48003099
linked to: http://stackoverflow.com/q/18786912
has answer: http://stackoverflow.com/a/48003099
type: Question

http://stackoverflow.com/q/47870797
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82706879
accepted answer: http://stackoverflow.com/a/47887985
favorite count: 0
has body: I have a list of items and I would like to return the one with the greatest severity i.e. The input could be "Rainy|Icy|Windy" and the list of possible inputs could be (in order of severity): sunny, cloudy, windy, rainy, icy. With the above input I would like to output only Icy as it is the most sever. I have tried something like: dictionary1 = {'sunny': 0, 'cloudy': 1, 'windy': 1, 'rainy': 2, 'icy': 3} with open(Conditions_csv, 'wb') as fw: writer = csv.writer(fw, delimiter=',') header = ['Date','latitude','longitude','Condition'] writer.writerow(header) for row in cur.fetchall(): conditions = row[3].split("|") for item in sorted(dictionary1.keys(),reverse= True): name = dictionary1[item] if name in conditions: print row print name writer.writerow(row + name) db.close() my output for the above will be: (18/12/2017,45,-85, Rainy|Icy|Windy) Icy (18/12/2017,45,-85, Rainy|Icy|Windy) Rainy (18/12/2017,45,-85, Rainy|Icy|Windy) Windy (18/12/2017,47,-88, Rainy|Windy) Rainy (18/12/2017,47,-88, Rainy|Windy) Windy (18/12/2017,40,-84, Icy|Windy) Icy (18/12/2017,40,-84, Icy|Windy) Windy all I want to reuturn is: (18/12/2017,45,-85, Rainy|Icy|Windy) Icy (18/12/2017,47,-88, Rainy|Windy) Rainy (18/12/2017,40,-84, Icy|Windy) Icy
upvote count: 2
tagged with: python
possible better answer: http://stackoverflow.com/a/47870885
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47870885
has comment: http://stackoverflow.com/comment/82706992
has title: Lookup text against a list to find largest value in python
has answer: http://stackoverflow.com/a/47887985
type: Question

http://stackoverflow.com/comment/82751637
type: QuestionComment
has text: Your indentation is broken, whether or not the posted code occurs in a loop.
score: 2
comment on: http://stackoverflow.com/q/47892500
type: Comment

http://stackoverflow.com/comment/82872822
score: 0
comment on: http://stackoverflow.com/a/47951526
type: AnswerComment
has text: `find_elements_by_css_selector` doesn't raise `NoSuchElementException` unless you've defined an implicit wait. Make sure that the targeted elements are not in frame. Other than that you should get some elements since it matches the HTML you've provided.
type: Comment

http://stackoverflow.com/a/47927385
downvote count: 0
has body: The error int object is not iterable is not because list expects an iterable, but sum expected an iterable. The following code: map(sum , [1,2,3,4]) Is somewhat equivalent to: [sum(x) for x in [1,2,3,4]] Executing the last expression yields the same error.
type: Answer
score: 2
answers question: http://stackoverflow.com/q/47927234
upvote count: 2

http://stackoverflow.com/comment/82912415
comment on: http://stackoverflow.com/q/47971235
score: 0
type: Comment
has text: @georgexsh please check my edit. My function now is larger and it could make more sense to try and build something a bit more Pythonic.
type: QuestionComment

http://stackoverflow.com/a/47919891
type: Answer
has comment: http://stackoverflow.com/comment/82807507
has comment: http://stackoverflow.com/comment/82807580
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47919877
has body: Update: In OpenCV 3.4 , cv2.findContours returns image, contours, hierarchy cv2.findContours(image, mode, method[, contours[, hierarchy[, offset]]]) -&gt; image, contours, hierarchy In OpenCV 4.0, cv2.findContours returns contours, hierarchy cv2.findContours(image, mode, method[, contours[, hierarchy[, offset]]]) -&gt; contours, hierarchy So to find contours in a threshed binary image, and calculate the areas, use: cnts= cv.findContours(threshed, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)[-2] for cnt in cnts: area = cv2.contourArea(cnt) print(area)
downvote count: 0

http://stackoverflow.com/comment/82789381
has text: I suspect that you copied the table entirely into the first column of your excel spreadsheet. Then, when you saved the file as CSV, it saved it as a single-column CSV, hence the `"`s around each line. Do either of these: 1) don't use Excel. Instead, copy-paste the CSV from the web into Notepad++. Save the CSV file from Notepad++, or 2) don't copy-paste. Instead, save the .xls from the web. Open it in Excel and Save-As CSV from there.
score: 0
comment on: http://stackoverflow.com/q/47895825
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47996051
type: UnansweredQuestion
has title: memory error using scipy.integrate.simps on big-ish (500MB) array on a 64bit machine with enough memory
tagged with: simpsons-rule
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/82963993
has comment: http://stackoverflow.com/comment/82960225
has comment: http://stackoverflow.com/comment/82960578
has body: I am using the scipy simpsons rule in a vectorized way for performance. (I am calculting integrals on a rolling window on a timeseries.) For some reason I am getting a memory error when using simps on an 500MB array of floats on a 64bit machine which has 4GB of memory available. Here's some example code: import numpy as np from scipy.integrate import simps import psutil print(psutil.virtual_memory().percent) #gives 40% # in the followinging, the number of rows can be increased up until 190'000 without issues. # The memory usage during execution of the whole script grows linearly with the size of the input array # I don't observe any exponential behaviour in Memory-usage a = np.random.rand(195000, 150, 2) print(psutil.virtual_memory().percent) #gives 51% print(a.nbytes/1024/1024, "MB") #gives 446MB print(a[:,:,0].nbytes/1024/1024, "MB") #gives 223 MB I = simps(a[:,:,0], a[:,:,1]) #MemoryError print(psutil.virtual_memory().percent) I can see the virtual memory of my machine going up until 2GB are used and then I get a MemoryError even though not all of my free memory is used. So I am confused: Why am I getting a MemoryError even though there is still about 2GB of unused Memory available? Can this be worked around? I am using Winddows Server 2012 R2. Edit: To illustrate the more or less linear scaling of memory usage vs. input size, I performed the following little experiment: def test(rows): a = np.random.rand(rows, 150, 2) I = simps(a[:,:,0], a[:,:,1]) print(I.shape) for numRows in [r for r in range(10000,190000,10000)]: test(numRows) Which gives a rising memory consumption in the windows ressource monitor as well as in other tools like mprof:
score: 0
tagged with: out-of-memory
tagged with: python
has comment: http://stackoverflow.com/comment/82967256
answer count: 0

http://stackoverflow.com/comment/82914905
comment on: http://stackoverflow.com/q/47972289
has text: I added the html recieve with my script and the uninterpreted html
score: 0
type: Comment
type: QuestionComment

amazon-elastic-beanstalk
tag name: amazon-elastic-beanstalk
type: Tag
tags question: http://stackoverflow.com/q/47986073
tags question: http://stackoverflow.com/q/47972522
tags question: http://stackoverflow.com/q/47900138

http://stackoverflow.com/q/47980278
has comment: http://stackoverflow.com/comment/82929046
type: Question
has comment: http://stackoverflow.com/comment/82929926
upvote count: 0
score: -1
tagged with: python-2.7
has body: I have the follow string, which I'm trying to load using python 2.7 json.loads. { u'Status': { u'display_name': u'Status', u'is_updatable': True, u'type': u'TEXT', u'val': u'Paying', u'source': u'API' }, u'Create Date': { u'display_name': u'Create Date', u'is_updatable': True, u'type': u'DATE', u'val': u'2017-09-20', u'source': u'API' }, u'Total # of Projects': { u'display_name': u'Total # of Projects', u'is_updatable': True, u'type': u'TEXT', u'val': u'53', u'source': u'Pixel' } } I'm getting the error: ValueError: Expecting property name: line 1 column 2 (char 1) Any ideas?
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82929053
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82931576
linked to: http://stackoverflow.com/q/25707558
has answer: http://stackoverflow.com/a/47981503
has title: Load json using python 2.7
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/82929057
duplicate of: http://stackoverflow.com/q/25707558
has comment: http://stackoverflow.com/comment/82929043
downvote count: 1

http://stackoverflow.com/q/47884910
type: Question
tagged with: curve-fitting
tagged with: python
has answer: http://stackoverflow.com/a/47917872
has title: Fixing fit parameters in curve_fit
accepted answer: http://stackoverflow.com/a/47894763
answer count: 3
has answer: http://stackoverflow.com/a/73951825
upvote count: 1
possible better answer: http://stackoverflow.com/a/47917872
has body: I have a function Imaginary which describes a physics process and I want to fit this to a dataset x_interpolate, y_interpolate. The function is a form of a Lorentzian peak function and I have some initial values that are user given, except for f_peak (the peak location) which I find using a peak finding algorithm. All of the fit parameters, except for the offset, are expected to be positive and thus I have set bounds_I accordingly. def Imaginary(freq, alpha, res, Ms, off): numerator = (2*alpha*freq*res**2) denominator = (4*(alpha*res*freq)**2) + (res**2 - freq**2)**2 Im = Ms*(numerator/denominator) + off return Im pI = np.array([alpha_init, f_peak, Ms_init, 0]) bounds_I = ([0,0,0,0, -np.inf], [np.inf,np.inf,np.inf, np.inf]) poptI, pcovI = curve_fit(Imaginary, x_interpolate, y_interpolate, pI, bounds=bounds_I) In some situations I want to keep the parameter f_peak fixed during the fitting process. I tried an easy solution by changing bounds_I to: bounds_I = ([0,f_peak+0.001,0,0, -np.inf], [np.inf,f_peak-0.001,np.inf, np.inf]) This is for many reasons not an optimal way of doing this so I was wondering if there is a more Pythonic way of doing this? Thank you for your help
tagged with: scipy
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/47894763
favorite count: 0

http://stackoverflow.com/comment/82744597
type: AnswerComment
comment on: http://stackoverflow.com/a/47889275
score: 0
has text: so basically it will look like with open('stats.csv', 'a') as new_file:
type: Comment

http://stackoverflow.com/comment/82678188
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47856882
has text: im getting this jsons from url's
score: 0

http://stackoverflow.com/a/47860495
type: Answer
has comment: http://stackoverflow.com/comment/82685839
score: 7
upvote count: 7
answers question: http://stackoverflow.com/q/47860473
has comment: http://stackoverflow.com/comment/82685864
has body: length = 6 for x in range(1, length+1): print(x * '*' + (length - x) * '#') # integer * (string), concatenate the string integer times
downvote count: 0
has comment: http://stackoverflow.com/comment/82685763

http://stackoverflow.com/comment/82897995
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47964058
has text: Can you post the source of your file? Also, have you tried logging some messages to see if the file is executing. It is possible that you have a logic problem that might not be showing up until you try to run it via cron.

http://stackoverflow.com/q/47865695
tagged with: deep-learning
has body: When preparing train set for neural network training, I find two possible way. The traditional way: calculate the mean on whole training set， and minus this fixed mean value per image before sending to network. Processing standard deviation in the similar way. I find tensorflow provides a function tf.image.per_image_standardization that do normalization on single image. I wonder which way is more appropriate？
answer count: 1
favorite count: 0
upvote count: 2
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47893204
score: 1
has title: Which is the correct way to do image normalization?
downvote count: 1
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/47893204
tagged with: neural-network
tagged with: data-science

http://stackoverflow.com/q/47914378
has comment: http://stackoverflow.com/comment/82797469
linked to: http://stackoverflow.com/q/47893838
upvote count: 0
answer count: 1
has title: How to show a webpage in Qmainwindow?
has answer: http://stackoverflow.com/a/47924843
favorite count: 0
has comment: http://stackoverflow.com/comment/82797489
tagged with: python
type: AnsweredQuestion
has body: I have searched entire web to find a way to do this. All the answers are about PyQt4, Pyside, Qwebview, Qt4, or Qt5(C++), therefore they do not work on PyQt5. the other answer is QtWebEngineView: unknown for PyQt5 (at least mine). I have the latest version of Python, Pycharm and PyQt5.
accepted answer: http://stackoverflow.com/a/47924843
tagged with: pyqt5
downvote count: 1
type: Question
score: -1
has comment: http://stackoverflow.com/comment/82797559

http://stackoverflow.com/q/47978702
score: 0
answer count: 2
has title: How fetch latest tag response in selenium?
tagged with: beautifulsoup
tagged with: xpath
has body: So this is my bot : https://www.pandorabots.com/pandora/talk?botid=b3a17e933e345861 And I am trying to fetch current human vs thanos response so I tried: from selenium import webdriver import time driver=webdriver.Chrome() browser=driver.get('https://www.pandorabots.com/pandora/talk?botid=b3a17e933e345861') ask=driver.find_element_by_xpath('/html/body/form/table/tbody/tr[1]/td[1]/input') inpu_1='ask thanos ' ask.send_keys(inpu_1) time.sleep(2) But now I am stuck and not able to find a way to fetch current human and thanos response because there are many tag and if I try with xpath it looks like this: /html/body/b[2] So if I am trying this: print(" thanos: {} ".format(driver.find_element_by_css_selector("b:contains('thanos:')"))) then it's not giving anything and returning blank How to fetch latest reply of thanos?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47979615
tagged with: web-scraping
tagged with: python
has answer: http://stackoverflow.com/a/47978882
tagged with: selenium
type: Question

http://stackoverflow.com/comment/83578933
comment on: http://stackoverflow.com/q/47966461
has text: Your `ip a` output is missing the important bits, i.e. the interface `lo`. Please add this information.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82928719
type: Comment
type: QuestionComment
has text: Did you forget the brackets?
score: 0
comment on: http://stackoverflow.com/q/47979988

http://stackoverflow.com/comment/82678631
comment on: http://stackoverflow.com/q/47856273
score: 0
type: Comment
type: QuestionComment
has text: The URL you are trying to create for page no. 1 onwards doesn't seem to be working...

http://stackoverflow.com/a/47953506
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47952846
has body: Adding; pyplot.switch_backend('backend') where backend is either TkAgg or Qt4Agg solved my problem. Thank you to ImportanceOfBeingErnest for solving this for me!

http://stackoverflow.com/q/47946187
answer count: 1
has body: I am using PyCharm community version 2017.3.1, and Python 2.7.1. I tried installing opencv through PyCharm but it kept giving me an error. File "C:/Users/user/PycharmProjects/cameratest/cameratest.py", line 2, in import cv2 ImportError: DLL load failed: %1 is not a valid Win32 application. I downloaded the opencv executable file and tried moving it to my Python 2.7 file but it would still not work, and I tried following the answer here but to no avail.
favorite count: 0
linked to: http://stackoverflow.com/q/32660114
tagged with: pycharm
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82863158
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82863259
tagged with: opencv
has answer: http://stackoverflow.com/a/49615782
score: 1
has title: OpenCV won't import in PyCharm
has comment: http://stackoverflow.com/comment/82862244
type: Question
downvote count: 0
linked to: http://stackoverflow.com/q/19019720

http://stackoverflow.com/q/47873861
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82713322
tagged with: python
tagged with: nlp
answer count: 0
score: 1
upvote count: 1
type: Question
has title: Cosine similarity - ValueError: too many values to unpack (expected 2)
has body: I've read through a handful of similar posts, but haven't found an exact duplicate for my issue. I'm working on calculating cosine similarity for tfidf values, and am getting ValueError: too many values to unpack (expected 2) I understand that this is basically saying that 2 values were expected and there are more than 2 values being fed through, resulting in an error. But I'm not sure how to move forward from here. Here's the full code from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import linear_kernel def find_similar(tfidf_matrix, index, top_n = 5): cosine_similarities = linear_kernel(tfidf_matrix[index:index+1], tfidf_matrix).flatten() related_docs_indices = [i for i in cosine_similarities.argsort()[::-1] if i != index] return [(index, cosine_similarities[index]) for index in related_docs_indices][0:top_n] corpus = [] for doc in nlp.pipe(df['TIP_all_txt'].astype('unicode').values, batch_size=9845, n_threads=3): if doc.is_parsed: corpus.append([n.text for n in doc if not n.is_punct and not n.is_stop and not n.is_space]) else: corpus.append(None) tf = TfidfVectorizer(analyzer='word', ngram_range=(1,3), min_df = 0, stop_words = 'english') tfidf_matrix = tf.fit_transform([content for doc, doc in corpus]) for me_index, item in enumerate(corpus): similar_documents = [(corpus[index], score) for index, score in find_similar(tfidf_matrix, me_index)] me = corpus[me_index] document_id = me[0].split("/")[1].split(".")[0] for ((raw_similar_document_id, title), score) in similar_documents: similar_document_id = raw_similar_document_id.split("/")[1].split(".")[0] writer.writerow([document_id, me[1], similar_document_id, title, score]) and error message: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-75-8522d91e96f8&gt; in &lt;module&gt;() 8 9 tf = TfidfVectorizer(analyzer='word', ngram_range=(1,3), min_df = 0, stop_words = 'english') ---&gt; 10…
has comment: http://stackoverflow.com/comment/82713687
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/82681011
type: Comment
comment on: http://stackoverflow.com/q/47858275
score: 1
has text: https://pyformat.info/#number_padding
type: QuestionComment

http://stackoverflow.com/comment/82960100
type: Comment
type: QuestionComment
has text: you could use `open('input.txt').readlines()`, it will return the file lines as a list. if that doesn't help, please provide a sample of the data file you need to loop through and the expected output.
score: 1
comment on: http://stackoverflow.com/q/47995991

http://stackoverflow.com/q/47976084
has comment: http://stackoverflow.com/comment/82921398
has body: I have created a basic web app using python-flask. A user can upload a file for some analysis and some functions run at the back-end. When the job is done a file containing the results,is automatically sent to the user. However if the process runs so long, and the user tries to stop the operation, python functions still works at the back-end. I have to stop whole web app and re-run it to terminate python processes. These are the processes on port 5000 when I run the web app. $ lsof -i:5000 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME python 5306 akinyilmaz 6u IPv4 104621 0t0 TCP *:5000 (LISTEN) python 5309 akinyilmaz 6u IPv4 104621 0t0 TCP *:5000 (LISTEN) python 5309 akinyilmaz 8u IPv4 104621 0t0 TCP *:5000 (LISTEN) When a client uploads a file and starts analyzing I get the following. $ lsof -i:5000 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME firefox 4276 akinyilmaz 106u IPv4 145274 0t0 TCP akin_yilmaz.corp.airties.com:34274-&gt;akin_yilmaz.corp.airties.com:5000 (ESTABLISHED) python 5306 akinyilmaz 6u IPv4 110021 0t0 TCP *:5000 (LISTEN) python 5309 akinyilmaz 6u IPv4 110021 0t0 TCP *:5000 (LISTEN) python 5309 akinyilmaz 8u IPv4 110021 0t0 TCP *:5000 (LISTEN) python 5309 akinyilmaz 9u IPv4 146944 0t0 TCP akin_yilmaz.corp.airties.com:5000-&gt;akin_yilmaz.corp.airties.com:34274 (ESTABLISHED) I tried to get PIDs and kill difference (which is 4276 in this case) but it actually did not work and python functions did not stop. What can I do to kill only python functions running, but not to terminate whole web app?
answer count: 0
type: UnansweredQuestion
tagged with: tcp
has comment: http://stackoverflow.com/comment/82921299
has title: Flask, terminate running python function but do not terminate whole web server
type: Question
tagged with: flask
score: 0
tagged with: python

http://stackoverflow.com/a/47975228
type: Answer
upvote count: 1
has body: Adapt a path-finding algorithm, such as Dijkstra's or A*, or alternatively adapt the breadth-first or depth-first search of a graph. Start at any point in the set of unvisited points, and proceed with whichever algorithm you've picked with the caveat that a point is considered to be connected only to all points to which its distance is less than the threshhold. When you've finished off with one class (i.e. when you can discover no more new nodes), pick any node from the set of unvisited nodes and repeat.
has comment: http://stackoverflow.com/comment/82920286
downvote count: 1
has comment: http://stackoverflow.com/comment/82920523
has comment: http://stackoverflow.com/comment/82920389
has comment: http://stackoverflow.com/comment/82920187
answers question: http://stackoverflow.com/q/47974874
has comment: http://stackoverflow.com/comment/82920368
has comment: http://stackoverflow.com/comment/82920412
has comment: http://stackoverflow.com/comment/82920388
score: 0
has comment: http://stackoverflow.com/comment/82920370

http://stackoverflow.com/q/47963425
linked to: http://stackoverflow.com/q/24870953
has comment: http://stackoverflow.com/comment/82940229
tagged with: financial
has body: I am working on a pandas Financial series dataframe and iterating through the rows to test stops and targets. With a large dataset this takes way too long. The main problem that I have is the that the data['Signal']fires only when the boundary condition exists. IT would be nice to 'latch' the signal to remain 1( via forward fill) while the target and the stop have not been touched. Currently I an checking every row and filling in the position value to perform my calculation. update with data: Date Time Open High Low Close boundry1 boundry2 L1 S1 Signal exit_type exit_price Sreturn position 578 20120831 10:56:00 1272.50 1274.00 1272.50 1274.00 1274.5 1271.25 1277.75 1268.0 0 NaN NaN 0 0 579 20120831 10:57:00 1274.00 1275.25 1274.00 1274.25 1274.5 1271.25 1277.75 1268.0 0 NaN NaN 0 0 580 20120831 10:59:00 1274.25 1274.75 1274.25 1274.75 1274.5 1271.25 1277.75 1268.0 1 NaN NaN 0 0 581 20120831 11:00:00 1274.75 1274.75 1274.75 1274.75 1274.5 1271.25 1277.75 1268.0 0 NaN NaN 0 0 582 20120831 11:01:00 1275.00 1275.00 1275.00 1275.00 1274.5 1271.25 1277.75 1268.0 0 NaN NaN 0 0 583 20120831 11:02:00 1275.75 1275.75 1275.25 1275.25 1274.5 1271.25 1277.75 1268.0 0 NaN NaN 0 0 584 20120831 11:03:00 1276.25 1276.25 1276.25 1276.25 1274.5 1271.25 1277.75 1268.0 0 NaN NaN 0 0 585 20120831 11:04:00 1277.00 1277.00 1277.00 1277.00 1274.5 1271.25 1277.75 1268.0 0 NaN NaN 0 0 586 20120831 11:05:00 1275.75 1275.75 1274.75 1274.75 1274.5 1271.25 1277.75 1268.0 0 NaN NaN 0 0 587 20120831 11:06:00 1275.50 1275.50 1275.25 1275.25 1274.5 1271.25 1277.75 1268.0 0 NaN NaN 0 0 588 20120831 11:07:00 1275.25 1275.25 1274.75 1274.75 1274.5 1271.25 1277.75 1268.0 0 NaN NaN 0 0 589 20120831 11:09:00 1274.75 1275.00 1274.75 1275.00 1274.5 1271.25 1277.75 1268.0 0 NaN NaN 0 0 590 20120831 11:10:00 1275.25 1275.25 1275.25 1275.25 1274.5 1271.25 1277.75 1268.0 0 NaN NaN 0 0 591 20120831 11:11:00 1275.50 1275.50 1275.50 1275.50 1274.5 1271.25 1277.75 1268.0 0 NaN NaN 0 0 592 20120831 11:12:00 1275.00 1…
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/83185162
favorite count: 0
has comment: http://stackoverflow.com/comment/82896350
has comment: http://stackoverflow.com/comment/83231417
tagged with: python
tagged with: vectorization
has comment: http://stackoverflow.com/comment/83214386
has comment: http://stackoverflow.com/comment/83215895
score: 2
answer count: 0
upvote count: 2
linked to: http://stackoverflow.com/q/20109391
type: UnansweredQuestion
has title: Pandas more efficient looping financial data
type: Question

http://stackoverflow.com/q/47886132
tagged with: python
has comment: http://stackoverflow.com/comment/82748669
answer count: 0
has body: We have a Cassandra server that ran out of disk space, after that we upgraded the disk space. But since then it has not been possible to connect with cqlsh. I am trying to connect to cassandra locally on the server but i just get the following error. It seems like it just uses the default connect timeout of 5 seconds and ignores my connect-timeout parameter.. Any ideas what could be wrong? python cqlsh 10.0.12.10 --connect-timeout 3600 --debug Using CQL driver: &lt;module 'cassandra' from '/usr/share/cassandra/lib/cassandra-driver-internal-only-3.0.0-6af642d.zip/cassandra-driver-3.0.0-6af642d/cassandra/__init__.py'&gt; Using connect timeout: 3600 seconds Connection error: ('Unable to connect to any servers', {'10.0.12.10': OperationTimedOut('errors=None, last_host=None',)})
tagged with: cqlsh
type: Question
tagged with: cassandra
score: 0
has comment: http://stackoverflow.com/comment/82789511
has title: cqlsh OperationTimedOut when connecting
type: UnansweredQuestion

http://stackoverflow.com/q/47871328
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python
has title: Concatenating DataFrames with similar and disjoint columns
has body: Problem is simplified for ease of discussion. Take 3 dataframes with similar and disjoint columns, but the same column values. How does one concatenate them in such a way that there are no repeated columns, all unique columns are retained (i.e. not doing an inner join), and new rows are not created if column values are the same? Individual dataframes: df1: a b c 0 1 2 3 1 11 22 33 df2: b c d 0 2 3 4 1 22 33 44 df3: c d e 0 3 4 5 1 33 44 55 Desired output: a b c d e 0 1 2 3 4 5 1 11 22 33 44 55 However, simply using pd.concat([df1, df2, df3], axis=1) includes duplicate columns.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47871343
accepted answer: http://stackoverflow.com/a/47871343
tagged with: join
score: 1
tagged with: dataframe
type: Question
tagged with: concatenation
downvote count: 0

http://stackoverflow.com/q/47951915
upvote count: 2
has answer: http://stackoverflow.com/a/47951979
tagged with: primary-key
type: Question
has answer: http://stackoverflow.com/a/47951968
has body: Here is my model: class InvitationCode(models.Model): code = models.CharField(max_length=6, primary_key=True) group = models.OneToOneField(Group, on_delete=models.PROTECT) According to doc, primary_key=True implies null=False and unique=True. However this is not what I see: &gt;&gt;&gt; from app.models import InvitationCode &gt;&gt;&gt; c = InvitationCode(group_id=1) &gt;&gt;&gt; c.save() &gt;&gt;&gt; c.pk '' &gt;&gt;&gt; c1 = InvitationCode(group_id=1) &gt;&gt;&gt; c1.save() &gt;&gt;&gt; InvitationCode.objects.all() &lt;QuerySet [&lt;InvitationCode: InvitationCode object ()&gt;]&gt; Why Django allowed me to have primary key as empty string? Why uniqueness constrain didn't work?
answer count: 2
downvote count: 0
has title: Custom primary key in Django model
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82873526
score: 2

http://stackoverflow.com/a/48025787
has comment: http://stackoverflow.com/comment/83021146
has comment: http://stackoverflow.com/comment/83035825
answers question: http://stackoverflow.com/q/47968136
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/47968136
has body: I'm not overly happy about using GL_TRIANGLE_FAN because it's caused a lot of odd shapes when using batched rendering. So consider moving over to GL_TRIANGLES instead and simply add all the points to the object rather than leaning on GL to close the shape for you. That way, you can easily move over to doing batched rendering: import pyglet from pyglet.gl import * from collections import OrderedDict from time import time, sleep from math import * from random import randint key = pyglet.window.key class CustomGroup(pyglet.graphics.Group): def set_state(self): #pyglet.gl.glLineWidth(5) #glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) #glColor4f(1, 0, 0, 1) #FFFFFF #glLineWidth(1) #glEnable(texture.target) #glBindTexture(texture.target, texture.id) pass def unset_state(self): glLineWidth(1) #glDisable(texture.target) class Particle(): def __init__(self, x, y, batch, particles): self.batch = batch self.particles = particles self.group = CustomGroup() self.add_point(x, y) def add_point(self, x, y): colors = ()#255,0,0 sides = 50 radius = 25 deg = 360/sides points = ()#x, y # Starting point is x, y? prev = None for i in range(sides): n = ((deg*i)/180)*pi # Convert degrees to radians point = int(radius * cos(n)) + x, int(radius * sin(n)) + y if prev: points += x, y points += prev points += point colors += (255, i*int(255/sides), 0)*3 # Add a color pair for each point (r,g,b) * points[3 points added] prev = point points += x, y points += prev points += points[2:4] colors += (255, 0, 255)*3 self.particles[len(self.particles)] = self.batch.add(int(len(points)/2), pyglet.gl.GL_TRIANGLES, self.group, ('v2i/stream', points), ('c3B', colors)) class main(pyglet.window.Window): def __init__ (self, demo=False): super(main, self).__init__(800, 600, fullscreen = False, vsync = True) #print(self.context.config.sample_buffers) self.x, self.y = 0, 0 self.sprites = OrderedDict() self.batches = OrderedDict() self.batches['default'] = pyglet.graphics.Batch() self.active_batch = 'default' for i in …
score: 6

http://stackoverflow.com/comment/82955529
score: 0
has text: "What kind of error?" It's not really an error, but it doesn't follow the condition I originally thought of. If the column `last_name` only contains the element `Miller`, that should be ok. The above `.issubset()` will throw an error though, as one must include 'Jones', 'Miller', 'Ali', 'Milner', and 'Cooze'
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47903570

imagenet
tags question: http://stackoverflow.com/q/47912485
type: Tag
tag name: imagenet

http://stackoverflow.com/a/48015361
has comment: http://stackoverflow.com/comment/83023023
type: Answer
has comment: http://stackoverflow.com/comment/83022392
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83030767
has body: What you are trying to do is much simpler than how you tried doing it. You can first melt portfolios to flip it and collect all the date columns as rows in a single column, then join it with returns, and finally pivot to get the desired result. This is basically what @djk47463 did in one compound line, and my edited answer serves as a step-by-step breakdown of his. Let's create your DataFrames to make the answer reproducible. import pandas as pd import sys if sys.version_info[0] &lt; 3: from StringIO import StringIO else: from io import StringIO # Create df rawText = StringIO(""" PERMNO FROMDATE MORET 0 93044 20131231 -0.022304 1 79702 20131231 0.012283 2 85751 20131231 -0.016453 3 85576 20131231 0.038766 4 93044 20131010 -0.02 5 79702 20131010 0.01 6 85751 20131010 -0.01 7 85576 20131010 0.03 """) returns = pd.read_csv(rawText, sep = "\s+") portfolios = pd.DataFrame({'20131010':[93044, 85751], '20131231':[85576, 79702]}) Notice, the FROMDATE column of returns consists of numbers, but in portfolios the date columns are strings. We must make them consistent: df.FROMDATE = df.FROMDATE.astype(str) Let's start the solution by melting (i.e. unpivot) portfolios: portfolios = portfolios.melt(var_name=['FROMDATE'],value_name='PERMNO') # portfolios: FROMDATE PERMNO 0 20131010 93044 1 20131010 85751 2 20131231 85576 3 20131231 79702 Now you want to hold this pm constant, and merge returns to its lines whenever their PERMNOs and FROMDATEs match: merged = pm.merge(df, how='left', on=['PERMNO', 'FROMDATE']) # merged: FROMDATE PERMNO MORET 0 20131010 93044 -0.020000 1 20131010 85751 -0.010000 2 20131231 85576 0.038766 3 20131231 79702 0.012283 Remember we had melted (unpivoted) the portfolios at the beginning? We should pivot this result to give it the shape of portfolios: final = merged.pivot(index='PERMNO', columns='FROMDATE', values='MORET').reset_index() # final: FROMDATE PERMNO 20131010 20131231 0 79702 NaN 0.012283 1 85576 NaN 0.038766 2 85751 -0.01 NaN 3 93044 -0.02 NaN
has comment: http://stackoverflow.com/comment/83022492
has comment: http://stackoverflow.com/comment/83021001
answers question: http://stackoverflow.com/q/48014529
downvote count: 0

http://stackoverflow.com/comment/82726934
type: AnswerComment
has text: Am i missing something easy like the chrome webdriver executable needs to be in the same directory as the .py file? Or does the .py file need to be ran from the command line?
comment on: http://stackoverflow.com/a/47879839
score: 0
type: Comment

http://stackoverflow.com/a/67774304
downvote count: 0
has comment: http://stackoverflow.com/comment/134732808
type: Answer
answers question: http://stackoverflow.com/q/47955548
score: 10
has body: I like Harald's solution. However, as of 2021, my environment needed some modifications. Docker version 20.10.5, build 55c4c88 I changed the Dockerfile as follows. FROM selenium/standalone-chrome USER root RUN apt-get update &amp;&amp; apt-get install python3-distutils -y RUN wget https://bootstrap.pypa.io/get-pip.py RUN python3 get-pip.py RUN python3 -m pip install selenium
upvote count: 10

http://stackoverflow.com/q/47878060
has comment: http://stackoverflow.com/comment/82722744
tagged with: archlinux
has comment: http://stackoverflow.com/comment/82723615
tagged with: python
has comment: http://stackoverflow.com/comment/82723461
upvote count: 4
has comment: http://stackoverflow.com/comment/82723714
has comment: http://stackoverflow.com/comment/82722833
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/82723616
has body: How is it possible that a core module is importing a non-existent name from another core module? Specifically, the re module importing enum.IntFlag Ways to Reproduce It can be reproduced by launching an interpreter and attempting the import, running a program that depends on enum.IntFlag such as pip, viewing the interpreter settings page in Eclipse, using the text editor, running the interactive console in PyDev, ... Directly importing from enum import IntFlag Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: cannot import name 'IntFlag' Run a dependant program (pip) Traceback (most recent call last): File "/usr/bin/pip", line 4, in &lt;module&gt; import re File "/usr/lib/python3.6/re.py", line 142, in &lt;module&gt; class RegexFlag(enum.IntFlag): AttributeError: module 'enum' has no attribute 'IntFlag' Viewing the Python Interpreter settings in Eclipse also produces the above traceback (in the window the interpreter settings would be in). Preferences =:&gt; PyDev =:&gt; Interpreters =:&gt; Python Interpreter Also the text editor doesn't recognise a print statement. Also, when I run the console interpreter (eg: Ctrl+Alt+Enter, eclipse fails with a popup showing this: 'Create Interactive Console' has encountered a problem. Error initializing console. Error Details Click the Error Details button: Error initializing console. Unexpected error connecting to console. Failed to recive suitable Hello response from pydevconsole. Last msg received: Console already exited with value: 1 while waiting for an answer. Command Line used: /usr/bin/python3.6 -u /usr/lib/eclipse/../../../home/scott/.eclipse/org.eclipse.platform_4.7.1_155965261_linux_gtk_x86_64/plugins/org.python.pydev_6.2.0.201711281614/pysrc/pydevconsole.py 44633 43575 44633 43575 Environment: PATH=/usr/local/sbin:/usr/local/bin:/usr/bin:/opt/cuda/bin:/usr/lib/jvm/default/bin:/opt/jython/bin/:/usr/bin/site_perl:/usr/bin/vendor_perl:/usr/bin/core_perl XAUTHORITY=/tmp/xauth…
has comment: http://stackoverflow.com/comment/82723644
type: Question
has comment: http://stackoverflow.com/comment/82722932
tagged with: pydev
has comment: http://stackoverflow.com/comment/82723340
has title: Why is the re module trying to import enum.IntFlag?
has comment: http://stackoverflow.com/comment/82723545
tagged with: development-environment
has comment: http://stackoverflow.com/comment/82722831
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82723064
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82723224
has comment: http://stackoverflow.com/comment/82723094
has answer: http://stackoverflow.com/a/47878910
accepted answer: http://stackoverflow.com/a/47878910
has comment: http://stackoverflow.com/comment/82723378

http://stackoverflow.com/comment/83092821
type: AnswerComment
comment on: http://stackoverflow.com/a/47881272
score: 0
type: Comment
has text: Sorry for being late reply. You gave me the right answer to solve it, after tried several times finally it works. Thank you very much.

http://stackoverflow.com/q/47891867
upvote count: 4
downvote count: 0
has answer: http://stackoverflow.com/a/47925735
type: Question
has answer: http://stackoverflow.com/a/47926835
score: 4
tagged with: python-2.7
answer count: 2
has title: Bloomberg API in Python: How to Get Historical Reference Data
has body: I'm trying to figure out how to get historical reference data through bloomberg api in python. Essentially, I am attempting to reproduce the following excel BDH in python: =BDH("IBM US EQUITY","3MTH_IMPVOL_100.0%MNY_DF","2015-01-01","2016-01-01") None of the python packages I've found seem to offer this functionality. For instance, while I can get reference data through tia: from tia.bbg import LocalTerminal resp = LocalTerminal.get_reference_data('SPX Index','3MTH_IMPVOL_100.0%MNY_DF') I can't figure out how to pull the historical time series of implied vol as opposed to the single datapoint. Has anyone done this before?
favorite count: 0
tagged with: bloomberg
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/69172363
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47941954
has body: You can parse thumbnail images using content-type: image/png query parameter. Note that it will scrape only 20 images. If set to more, it will throw an error. Learn more about MIME types. import requests from bs4 import BeautifulSoup params = { "q": "dog", "tbm": "isch", "content-type": "image/png", } html = requests.get("https://www.google.com/search", params=params) soup = BeautifulSoup(html.text, 'html.parser') for img in soup.select("img"): print(img["src"]) ------ ''' https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQq4fZiRGnMloOFKfYsBu91lbGkvT5RcLoa-ExEwbe6LDP3jl7zfZORPaprKA&s https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQAxU74QyJ8jn8Qq0ZK3ur_GkxjICcvmiC30DWnk03DEsi7YUgS8XXksdyybXY&s ... ''' If you want to scrape original resolution image URLs, you need to use regex and in order to extract URLs from the tags to match, extract and decode them. It will be a much-much faster scraping time compare to selenium. Find all script tags: soup.select('script') Secondly, to match the desired pattern using regex: # one of the regex patterns to find original size URL re.findall(r"(?:'|,),\[\"(https:|http.*?)\",\d+,\d+\]", SOME_VARIABLE) Thirdly, iterate over matches, extract and decode each URL one by one: for SOME_VARIABLE in SOME_VARIABLE: # it needs to be decoded twice. # otherwise Unicode characters will be still present after the first decode. # yes, it is stupid. original_size_img_not_fixed = bytes(fixed_full_res_image, 'ascii').decode('unicode-escape') original_size_img = bytes(original_size_img_not_fixed, 'ascii').decode('unicode-escape') Code and full example in the online IDE that also downloads images: import requests, lxml, re, json, urllib.request from bs4 import BeautifulSoup headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582" } params = { "q": "dog", # query "tbm": "isch", # img results "hl": "en", # language "ijn": "0", # batch of 100 imgae…

http://stackoverflow.com/comment/82688475
type: QuestionComment
has text: To get all the values for the `name` column in a list: `[entry['name'].encode('ascii', 'ignore') for entry in df['data']]`, then you have to do something like `ALTER TABLE ADD column_name datatype` and then insert your values
score: 0
comment on: http://stackoverflow.com/q/47861688
type: Comment

http://stackoverflow.com/a/47961168
has body: Create an env file, import it into settings, eg: assume settings.py and your env file is settings_top_Secret.py In settings.py from . import /PATH_TO/settings_top_Secret SECRET_KEY = settings_top_Secret.SECRET_KEY and in your settings_top_Secret.py SECRET_KEY = '7984)0_beumt0)wuvk*y%))0_beumt0)wuvk*y%(vss-x-7z_' And always, refrain from uploading settings_top_Secret to accessible path in live server, or in case of git, include it in gitignore.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47958956

http://stackoverflow.com/comment/82956917
score: 1
has text: @touchingtwist: Why do you think a regex is better than a much simpler text search using `.includes()` or `.indexOf()`? It'll be slower and can break depending on what characters are valid for your user names.
comment on: http://stackoverflow.com/a/47993718
type: AnswerComment
type: Comment

http://stackoverflow.com/a/48000262
answers question: http://stackoverflow.com/q/48000111
has body: Here's what I use for multiple vertical-only axes: f, axes = plt.subplots(nrows=3, ncols=1, figsize=(12,5)) try: iter(axes) # Check if axes can be iterated over except TypeError: axes = [axes] # If not, then make it into a list for ax in axes: ax.plot(x, y) ax.set_ylabel('AVG') Usually I even change the figure size depending on how many rows I have. Doing this gets a little complicated if you have ncols &gt; 1. Therefore this is for vertical-only plots.
downvote count: 0
score: 1
upvote count: 1
type: Answer

http://stackoverflow.com/a/47900958
type: Answer
has comment: http://stackoverflow.com/comment/82769528
downvote count: 0
has body: Split the text into single words and check whether a word in written in lower case is "something". If yes, then change the case to lower if word.lower() == "something": text = text.replace(word, "something") To know how to split a text into words, see this question. Another way is to iterate through single letters and check whether a letter is the first letter of "something": text = "Many words: SoMeThInG, SOMEthING, someTHing" for n in range(len(text)-8): if text[n:n+9].lower() == "something": # check whether "something" is here text = text.replace(text[n:n+9], "something") print text
score: 1
answers question: http://stackoverflow.com/q/47899565
has comment: http://stackoverflow.com/comment/82769592
upvote count: 1

http://stackoverflow.com/comment/82740984
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47886673
has text: @eyllanesc sorry for late response. Thats pretty much it
score: 0

http://stackoverflow.com/comment/82919364
has text: @timgeb I tried my best to clarify all uncertainties. If you have any constructive suggestion on how to reformulate the problem, I'm happy to do so. Even if I phrased it wrong, so far all you said is "It's not well defined that way". Edit: I rethought and you're right, it does not satisfy the definition of an equivalence relation. I'll try again differently: I want to throw points of coordinates together into containers. Given a container, I want to throw an element into there if it is close to one or more of the current elements.
type: Comment
comment on: http://stackoverflow.com/q/47974874
score: 1
type: QuestionComment

http://stackoverflow.com/a/47986604
answers question: http://stackoverflow.com/q/47986565
accepted answer of: http://stackoverflow.com/q/47986565
type: AcceptedAnswer
score: 0
has comment: http://stackoverflow.com/comment/82942209
has comment: http://stackoverflow.com/comment/82942559
type: Answer
has comment: http://stackoverflow.com/comment/82943503
has body: For windows try following command from command prompt: pip install Pillow or python -m pip install Pillow Pillow is a fork of PIL, the Python Imaging Library, which is no longer maintained. However, to maintain backwards compatibility, the old module name is used. For sdl2 try following(windows): python -m pip install kivy.deps.sdl2 python -m pip install kivy.deps.glew or try: python -m pip install docutils pygments pypiwin32 kivy.deps.sdl2 kivy.deps.glew
has comment: http://stackoverflow.com/comment/82943434

http://stackoverflow.com/comment/82716936
comment on: http://stackoverflow.com/q/47873366
has text: How can "the first feature, X[0], has 6 possible values 0, 1, 2, 3, 4, 5" while all your features are categorical?? Please post a sample of your data, otherwise your question is completely unclear...
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47858996
score: 16
has comment: http://stackoverflow.com/comment/82682861
has comment: http://stackoverflow.com/comment/82682915
type: Question
has body: When I generate an image and then generate a numpy array from it, the original .npy file differs from the new one. I thought new-array.npy would be exactly the same as original-array.npy since they are coming from the same image. For an example, I used this little image with 4*4 pixels: original-image.png Here is a larger version (not the one I'm working with): The last part of the code is the one that converts the .png to .npy. I think the problem is in here somewhere. import numpy as np from PIL import Image from matplotlib import pyplot as plt filename = 'image-test' img = Image.open( filename + '.png' ) data = np.array( img, dtype='uint8' ) np.save( filename + '.npy', data) # visually testing our output img_array = np.load(filename + '.npy') plt.imshow(img_array) My simple algorithm: Generate random rgb array and save it as .npy Save a .png file from that numpy array. Load that .png file and save it back to .npy import numpy as np from matplotlib import pyplot as plt import matplotlib from PIL import Image ####create a matrix of random colors filename = "original-array" matrix=np.random.random((4,4,3)) nx,ny,nz=np.shape(matrix) CXY=np.zeros([ny, nx]) for i in range(ny): for j in range(nx): CXY[i,j]=np.max(matrix[j,i,:]) #Save binary data np.save(filename + '.npy', CXY) print(filename + " was saved") #Load npy img_array = np.load(filename + '.npy') plt.imshow(img_array) ####Save npy as png filename = "original-image" img_name = filename +".png" matplotlib.image.imsave(img_name, img_array) print(filename + " was saved") #### Convert that png back to numpy array img = Image.open( filename + '.png' ) data = np.array( img, dtype='uint8' ) #Convert the new npy file to png filename = "new-array" np.save( filename + '.npy', data) print(filename + " was saved") #Load npy img_array = np.load(filename + '.npy') filename = "new-image" #Save as png img_name = filename +".png" matplotlib.image.imsave(img_name, img_array) print(filename + " was saved") Here is the result : Whe…
tagged with: image-processing
has comment: http://stackoverflow.com/comment/101555506
has answer: http://stackoverflow.com/a/60422785
has comment: http://stackoverflow.com/comment/82683043
tagged with: numpy
has comment: http://stackoverflow.com/comment/82684111
has comment: http://stackoverflow.com/comment/82683918
tagged with: arrays
answer count: 1
upvote count: 16
has title: Properly convert png to npy numpy array (Image to Array)
favorite count: 0
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/82761030
tagged with: python
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/82921172
type: Comment
has text: I was thinking about inheritance as well, but the thing that I don't like is that I'll end up with `Users.things` rather than `Users.users` - in other words, the name of the list does not really describe what it contains. That can probably be inferred by the name of the class inheriting the base class; but still not ideal. Both are better solutions than what I've written so far, though.
comment on: http://stackoverflow.com/a/47975326
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82885994
type: Comment
type: QuestionComment
has text: You should mark you question as answered by clicking the green tick below burhan khalid's answer.
comment on: http://stackoverflow.com/q/47958281
score: 0

http://stackoverflow.com/comment/82938455
comment on: http://stackoverflow.com/q/47984318
has text: At the _very least_ we need to be able to reproduce your error with the uploaded code. My guess though we'll eventually get to a point where you'll [need to use a global reference to your image](https://stackoverflow.com/q/3359717/7032856).
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48165254
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 6
upvote count: 6
answers question: http://stackoverflow.com/q/47994646
accepted answer of: http://stackoverflow.com/q/47994646
has body: Alright, I just found the answer to my problem. It came from the creation of a CrawlerProcess in the main.py file I was running. It did not load the settings in the settings.py file. Beforehand I was doing the following: process = CrawlerProcess({ 'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)' }) process.crawl(fitbit_spider.FitbitSpider) process.start() Now if I change the CrawlerProcess into: process = CrawlerProcess({ 'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)', 'DOWNLOAD_DELAY': 20 }) I do get the wanted delay ! Note: using get_project_settings() to create the CrawlerProcess is not working either.

http://stackoverflow.com/comment/126407360
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/71517136
type: Comment
has text: As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

http://stackoverflow.com/comment/82842059
type: AnswerComment
comment on: http://stackoverflow.com/a/47936061
score: 0
has text: The point I'm trying to make is that, within the constraints you have around messing around with the path system, modules/packages must be resolved from `.`: this is where Python will try to resolve imports from (in addition to, obviously, the environment's lib folders and whatever else is already on `$PYTHONPATH` or `sys.path`)
type: Comment

http://stackoverflow.com/q/47946713
favorite count: 0
score: 0
tagged with: python
has title: Open new frame from Menu (new window in already opened window)
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82863523
tagged with: tkinter
has comment: http://stackoverflow.com/comment/82863651
type: UnansweredQuestion
upvote count: 1
downvote count: 1
type: Question
has body: I am using a part of code to open different pages inside one window and it works fine. When I am trying to open a window from menu (file > New Test), it opens a new window instead of the same window. I am really confused with this and have a couple of questions. How to open Window from Menu in the same Window. Why menubar is visible in a page1 (NewTestWindow) if it is defined in the MainPage. Is it a correct way to make a separate class for menubar or it is better to insert it in the class MainWindow. import tkinter as tk from tkinter import font as tkfont class MenuBar(tk.Menu): def __init__(self, parent, controller): tk.Menu.__init__(self, controller) self.controller = controller fileMenu = tk.Menu(self, tearoff=0) self.add_cascade(label="File", underline=0, menu=fileMenu) fileMenu.add_command(label="New Test", underline=1, command=lambda: SampleApp().show_frame("NewTestWindow")) fileMenu.add_separator() fileMenu.add_command(label="Exit", underline=2, command=self.onexit) def onexit(self): quit() class SampleApp(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic") container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (MainWindow, NewTestWindow): 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("MainWindow") def show_frame(self, page_name): '''Show a frame for the given page name''' frame = self.frames[page_name] frame.tkraise() class MainWindow(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.menubar = MenuBar(self, parent) self.controller.config(menu=self.menubar) label = tk.Label(self, text="This is the main page", font=controller.title…
has answer: http://stackoverflow.com/a/58226529
has comment: http://stackoverflow.com/comment/82863553
answer count: 1

http://stackoverflow.com/comment/82700192
comment on: http://stackoverflow.com/q/47867589
has text: Please provide us with the error code, it's unclear what is failng.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48003185
type: AnsweredQuestion
score: 7
has comment: http://stackoverflow.com/comment/82975078
tagged with: machine-learning
upvote count: 7
tagged with: signal-processing
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48006709
has body: I am trying to use KNN to correctly classify .wav files into two groups, group 0 and group 1. I extracted the data, created the model, fit the model, however when I try and use the .predict() method I get the following error: Traceback (most recent call last): File "/..../....../KNN.py", line 20, in <module> classifier.fit(X_train, y_train) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sklearn/neighbors/base.py", line 761, in fit X, y = check_X_y(X, y, "csr", multi_output=True) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sklearn/utils/validation.py", line 521, in check_X_y ensure_min_features, warn_on_dtype, estimator) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sklearn/utils/validation.py", line 405, in check_array % (array.ndim, estimator_name)) ValueError: Found array with dim 3. Estimator expected <= 2. I have found these two stackoverflow posts which describe similar issues: sklearn Logistic Regression "ValueError: Found array with dim 3. Estimator expected <= 2." Error: Found array with dim 3. Estimator expected <= 2 And, correct me if I'm wrong, but it appears that scikit-learn can only accept 2-dimensional data. My training data has shape (3240, 20, 5255) Which consists of: 3240 .wav files in this dataset (this is index 0 of the training data) For For each .wav file there is a (20, 5255) numpy array which represents the MFCC coefficients (MFCC coefficients try and represent the sound in a numeric way). My testing data has shape (3240,) #category is 0 or 1 What code can I use to manipulated my training and testing data to convert it into a form that is usable by scikit-learn? Also, how can I ensure that data is not lost when I go down from 3 dimensions to 2 dimensions?
answer count: 1
downvote count: 0
has title: sklearn dimensionality issues "Found array with dim 3. Estimator expected <= 2"
tagged with: scikit-learn
favorite count: 0
accepted answer: http://stackoverflow.com/a/48006709
linked to: http://stackoverflow.com/q/34866548
tagged with: python
linked to: http://stackoverflow.com/q/34972142
has comment: http://stackoverflow.com/comment/82975052

http://stackoverflow.com/a/47971841
has comment: http://stackoverflow.com/comment/82913538
has comment: http://stackoverflow.com/comment/82913450
has comment: http://stackoverflow.com/comment/82913425
type: Answer
accepted answer of: http://stackoverflow.com/q/47971794
has comment: http://stackoverflow.com/comment/82913465
has body: You can achieve it with cumsum name_index = df'col_2', 'col_3'\ .apply(pd.to_numeric, errors='coerce')\ .ge(10)\ .any(axis=1)\ .cumsum() df['name'] = df['name'].astype(str) + '_' + name_index.astype(str) print(df) A col_2 col_3 name 0 1.0 2 11 hello_1 1 1.0 2 1 hello_1 2 1.0 12 3 hello_2 3 1.0 NaN NaN hello_2
answers question: http://stackoverflow.com/q/47971794
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/47929265
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47929323
has title: How to remove sprites out of group, outside of the class: Pygame
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/47929323
tagged with: python
tagged with: pygame
score: 2
has body: #Importing Modules import pygame as pg import sys import random #All pygame stuff under here pg.init() #Font definitions backFont = pg.font.SysFont("monospace",40) titleFont = pg.font.SysFont("garamond", 100) cipherFont = pg.font.SysFont("garamond", 50) buttonFont = pg.font.SysFont("garamond", 25) bigFont = pg.font.SysFont("garamond",100) Font = pg.font.SysFont(None,32) inputFont = pg.font.SysFont('consola', 35) errorFont = pg.font.SysFont('tahoma',20) diagramFont = pg.font.SysFont('courier new',25) #Colour definitions BackGray = pg.Color('gray60') screenGray = pg.Color('gray80') buttonGray2 = pg.Color('gray50') textColour = pg.Color('navy') #Screen size set screen = pg.display.set_mode((400, 400)) clock = pg.time.Clock() class Button(pg.sprite.Sprite): def __init__(self, text, x, y, width, height, colour, enabled): super().__init__() self.image = pg.Surface((width, height)) self.image.fill(colour) self.rect = self.image.get_rect() txt = buttonFont.render(text, True, textColour) txtRect = txt.get_rect(center = self.rect.center) self.image.blit(txt, txtRect) self.rect.topleft = x, y self.enabled = enabled def isPressed(self, event): if self.enabled == True: if event.type == pg.MOUSEBUTTONDOWN: if self.rect.collidepoint(event.pos): return True return False def Function(): background = pg.Surface(screen.get_size()) background.fill(screenGray) Button1 = Button('Encrypt',100,100,125,50,buttonGray2,True) Button2 = Button('Decrypt',100,200,125,50,buttonGray2,True) buttonsGroup = pg.sprite.Group(Button1,Button2) ACTIONPRINT = False Active1 = False while True: for event in pg.event.get(): if event.type == pg.QUIT: pg.quit() sys.exit() elif Button1.isPressed(event): print("1") Active1 = True elif Button2.isPressed(event): print("2") if Active1 == True: ACTIONPRINT = True buttonsGroup = pg.sprite.Sprite.remove(Button2) screen.blit(background,(0,0)) buttonsGroup.draw(screen) pg.display.flip() clock.tick(60) Function() Above is the code for the class of Buttons, and a simple fun…
upvote count: 2
tagged with: sprite
type: Question

http://stackoverflow.com/comment/82801673
type: QuestionComment
has text: `blosc` doesn't have wheels, so `pip` internally compiles the library for you. If you want to involve yourself in the process, then you should expect problems, especially if you're unfamiliar with the code.
comment on: http://stackoverflow.com/q/47916452
score: 0
type: Comment

http://stackoverflow.com/q/47955736
type: Question
downvote count: 0
tagged with: websocket
tagged with: javascript
tagged with: python-2.7
has title: Error "Invalid frame header" when send data from client to server - Python websocket
score: 1
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: I have an issue when send data from client to server - Python websocket. Here my client code: &lt;script type="text/javascript"&gt; var s = new WebSocket('ws://127.0.0.1:8999'); s.onopen = function (e) { console.log("Socket opened."); }; s.onclose = function (e) { console.log("Socket closed."); }; s.onmessage = function(t){alert(t)}; function onSubmit() { s.send("Hello from client"); } &lt;/script&gt; And server - Python code: import socket import re from base64 import b64encode from hashlib import sha1 websocket_answer = ( 'HTTP/1.1 101 Switching Protocols', 'Upgrade: websocket', 'Connection: Upgrade', 'Sec-WebSocket-Accept: {key} \r\n\r\n', ) GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('127.0.0.1', 8999)) s.listen(10) client, address = s.accept() text = client.recv(1024) print "Get data text from client and send back this data: " print text key = (re.search('Sec-WebSocket-Key:\s+(.*?)[\n\r\r\n]+', text) .groups()[0] .strip()) response_key = b64encode(sha1(key + GUID).digest()) response = '\r\n'.join(websocket_answer).format(key=response_key) client.send(response) clientData = client.recv(4096) client.send("Hello from server") When run Python Socket Server, I can connect from client, it mean "console.log("Socket opened.");" is working. But when I send data from client to server by running function onSubmit() data, I get the error "Invalid frame header" in console log of Chrome develop tool. And when I debug data from client sent to server (clientData variable in Python file), I got an crack string: "��Ϭ����Ջ��ߕ������܉�". Anybody can help me to resolve this problem?
answer count: 0

http://stackoverflow.com/q/47973512
has title: How to convert or decode the Unicode characters in pandas DataFrame?
tagged with: unicode
has body: I was reading some data from an excel file using pandas and did some row traversal to make a python dictionary which i then put into a json file . The problem is that I am getting Unicode characters in the json file itself : "C V M College of Fine Arts,\u00a0 Vallabh Vidyanagar" As shown above I don't want the Unicode '\u00a0' and instead want the decoded character representation of it in my json file. Is there any way I can do this conversion (or filtering or whatever its called) while reading the excel file from the pandas itself ? or is there any way to do this while writing to json file using json.dump()?
favorite count: 0
tagged with: data-analysis
tagged with: python
has answer: http://stackoverflow.com/a/47973602
has comment: http://stackoverflow.com/comment/82916710
upvote count: 1
tagged with: excel
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/47973602
type: Question
tagged with: pandas
answer count: 1
downvote count: 0

http://stackoverflow.com/q/47861390
favorite count: 0
has answer: http://stackoverflow.com/a/47861497
tagged with: python
type: AnsweredQuestion
has body: Im trying to graph a list of tuples using matplotlib.pyplot package &amp; Python 3 in Spyder IDE. Below is the relevant snippet of my code: import matplotlib.pyplot as plt def plot_test(item): xdata = [] ydata = [] for item in list_of_epoch_total_time_tuples: xdata = item[0] ydata = item[3] plt.plot(xdata,ydata) plt.ylabel('epoch_counter') plt.xlabel('square_error') plt.show() Here is my output: I cant see the line plot. The graph is empty? 1) How can i draw this properly 2) how can I provide plot range, so there is no negative values? Thanks
upvote count: 1
type: Question
has title: Python, matplotlib.pyplot cant see line plot
accepted answer: http://stackoverflow.com/a/47861497
score: 1
tagged with: matplotlib
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/133382600
has text: A few years later, `pd.lookup` is deprecated and this is the recommended way: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#looking-up-values-by-index-column-labels
comment on: http://stackoverflow.com/a/47997669
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/82716687
score: 1
has text: We mean , the Quarter 0 only have one value , why in your dataframe b , Data , it showing 0 rather than NaN
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47875483

http://stackoverflow.com/q/47922657
has body: I'm working with Odoo v8 and I've created a server action which is working OK, but to manage that I had to write it in old API, after a lot of attempts of doing it in new API. This is my code, the one in old API, which is working now: Python def open_action_alt_picking_type_views(self, cr, uid, ids, context=None): res = { 'view_type': 'form', 'view_mode': 'kanban', 'res_model': 'stock.picking.type', 'type': 'ir.actions.act_window', 'target': 'current', } return res XML Picking types True ir.actions.server code action = self.open_action_alt_picking_type_views(cr, uid, context.get('active_ids', []), context=context) And this is one of the attempts in new API which is not working: Python @api.model def open_action_alt_picking_type_views(self): res = { 'view_type': 'form', 'view_mode': 'kanban', 'res_model': 'stock.picking.type', 'type': 'ir.actions.act_window', 'target': 'current', } return res XML Picking types True ir.actions.server code action = self.open_action_alt_picking_type_views() I tried with @api.multi, with no decorators, adding a return before de method call in the XML code field, etc. Does anyone know how to achieve this?
tagged with: http://stackoverflow.com/tag/xml
favorite count: 0
has comment: http://stackoverflow.com/comment/82825673
upvote count: 2
tagged with: python
has title: How to move server action code from old API to new API?
accepted answer: http://stackoverflow.com/a/47928568
score: 2
type: AnsweredQuestion
tagged with: odoo
tagged with: odoo-8
type: Question
has answer: http://stackoverflow.com/a/47928568
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/82826046
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/82891134
type: AnswerComment
has text: Also, your final bit of code states "if len(oldname) < 70" which works. This is not intuitive, as it says that it will only process names with less than 70 characters, which includes problematic names like rename.py and "." If I switch it to "> 70", the script fails again. Why?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47960843

http://stackoverflow.com/comment/82995725
score: 1
type: Comment
type: QuestionComment
has text: I'm using python 3.6 64-bit cpython and getting the desired result rather than what's above
comment on: http://stackoverflow.com/q/48013457

http://stackoverflow.com/a/58773976
downvote count: 0
type: Answer
score: 1
answers question: http://stackoverflow.com/q/47862363
upvote count: 1
has body: This seems to be related to virtual environments having the same name See https://intellij-support.jetbrains.com/hc/en-us/community/posts/115000792670--solved-Project-Interpreter-Error-Please-Specify-a-different-SDK-Name
has comment: http://stackoverflow.com/comment/103853141

http://stackoverflow.com/comment/82944606
score: 0
type: Comment
has text: Thanks Ashish. This indeed looks interesting. Not quite what I was looking for, but it may be of help.
type: AnswerComment
comment on: http://stackoverflow.com/a/47887914

http://stackoverflow.com/comment/82889338
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47957611
has text: I suspected that I need to do %s but would this invite SQL injections?

http://stackoverflow.com/q/47925828
possible better answer: http://stackoverflow.com/a/59400220
answer count: 3
linked to: http://stackoverflow.com/q/47612822
favorite count: 0
has comment: http://stackoverflow.com/comment/82857195
has comment: http://stackoverflow.com/comment/82859212
score: 6
tagged with: python
has answer: http://stackoverflow.com/a/72787939
has answer: http://stackoverflow.com/a/47945335
tagged with: tweepy
upvote count: 6
type: AnsweredQuestion
has body: In Python 3 I made program to extract posts and likes in Twitter: import tweepy import pandas as pd consumer_key = '' consumer_secret = '' access_token = '' access_token_secret = '' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) This function receives the didactic classification of profiles (only for database organization) and the name of the profile. It creates a list with dictionaries, which is then returned: def linhadotempo(posicao, valor): tela = api.user_timeline(valor) bolha = [] for status in tela: dicionario = {"nome": valor, "posicionamento": posicao, "posts_links": status.text, "curtidas": status.favorite_count} bolha.append(dicionario) return bolha List of names of Twitter profiles and their didactic ratings. Then transformed into a dataframe: data = { 'nome': ['jeanwyllys_real', 'lucianagenro', 'jairbolsonaro', 'MBLivre'], 'posicionamento': ['esquerda', 'esquerda', 'direita', 'direita'] } perfis = pd.DataFrame(data, columns=['nome','posicionamento']) perfis.reset_index() index nome posicionamento 0 0 jeanwyllys_real esquerda 1 1 lucianagenro esquerda 2 2 jairbolsonaro direita 3 3 MBLivre direita I create a final list to put together the lists created in the function. I do an iteration in the dataframe of the profiles to activate the function bolhas = [] for num, row in perfis.iterrows(): bolha = linhadotempo(row['posicionamento'], row['nome']) bolhas.append(bolha) My intention later was to create a final dataframe with this, but it did not work out. My intention was to have the columns "curtidas", "nome", "posicionamento" and "posts_links" bolhas_final = pd.DataFrame(bolhas) bolhas_final.reset_index() index 0 1 2 3 4 5 6 7 8 ... 10 11 12 13 14 15 16 17 18 19 0 0 {'nome': 'jeanwyllys_real', 'posicionamento': ... {'nome': 'jeanwyllys_real', 'posicionamento': ... {'nome': 'jeanwyllys_real', 'posicionamento': ... {'nome': 'jeanwyllys_real', 'posicionamento': ... {'nom…
tagged with: list
has comment: http://stackoverflow.com/comment/82859191
has title: How to create a pandas dataframe using Tweepy?
tagged with: twitter
type: Question
has answer: http://stackoverflow.com/a/59400220
accepted answer: http://stackoverflow.com/a/47945335
downvote count: 0

http://stackoverflow.com/a/47944382
type: Answer
has body: As Pierre de Buyl said, minimize(self.obj, np.array(a), args=(b,c,d), ... results in 5 positional arguments passed to obj: self, a, b, c, d. The minimize method does not pack all the arguments into x. Since the method obj was declared with two arguments, def obj (self, x), there is an error. It would be consistent to write def obj (self, x, b, c, d): which I think also eliminates the need for the list unpacking that your obj is doing now; so the obj loses its purpose and can be replaced with fitn.
score: 0
answers question: http://stackoverflow.com/q/47941226

http://stackoverflow.com/comment/82993710
type: Comment
comment on: http://stackoverflow.com/q/48012370
score: 0
has text: You *already* split it into lines: `info.split("\n")`.
type: QuestionComment

http://stackoverflow.com/q/47957712
has answer: http://stackoverflow.com/a/47957723
tagged with: python-2.7
answer count: 3
has answer: http://stackoverflow.com/a/47957839
accepted answer: http://stackoverflow.com/a/47957839
downvote count: 0
has body: I am learning python 3. I imported dataset from sklearn. When I print it, it looks weird. What command should I use in order to see data clearly organized: column, rows. import statsmodels.api as sm from sklearn import datasets data = datasets.load_boston() print(data)
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/47957719
has title: how to print data in nice clean way
tagged with: python
linked to: http://stackoverflow.com/q/9535954
has answer: http://stackoverflow.com/a/47957719
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/a/48007624
upvote count: 1
has body: You have not used lines read from usernames.txt file in your code for searching the username in it. So, modify your code as: usernames = [] passwords = [] usernames.append(username) passwords.append(password) usernamesFile = open("usernames.txt","a") for usernames in usernames: usernamesFile.write("%s\n" % usernames) usernamesFile.close() passwordsFile = open("passwords.txt", "a") for passwords in passwords: passwordsFile.write("%s\n" % passwords) passwordsFile.close() while True: loginUsername = raw_input("Enter your username: ") usernamesFile = open("usernames.txt", "r") lines = usernamesFile.readlines() if loginUsername in lines: index = lines.index(username) break else: print "Username not found" continue
downvote count: 0
answers question: http://stackoverflow.com/q/48007411
type: Answer
score: 1

http://stackoverflow.com/comment/82899846
comment on: http://stackoverflow.com/a/47963868
has text: I got another error after making the changes: `Traceback (most recent call last): File "plot_script.py", line 23, in <module> data.append(int(row[1])) TypeError: int() argument must be a string or a number, not 'NoneType' `
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/82793143
score: 0
type: Comment
has text: I meant mouse click not keyboard enter
type: AnswerComment
comment on: http://stackoverflow.com/a/47912227

http://stackoverflow.com/comment/82811971
comment on: http://stackoverflow.com/q/47921673
score: 0
type: QuestionComment
has text: Thanks a lot Muthuraj , it solved the problem!
type: Comment

http://stackoverflow.com/a/47957525
type: Answer
upvote count: 1
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47957499
accepted answer of: http://stackoverflow.com/q/47957499
downvote count: 0
has body: Very simple - just put them all together in one filter() with commas: if ReleaseDate.objects.filter(game=game.id, platform=release_date_object['platform'], region=release_date_object['region']).exists(): Sometimes more complicated queries require Q objects but for a simple multiple-field query just put them all in one filter().

http://stackoverflow.com/comment/82967521
has text: As a side note, checking the modification time of a file isn't sufficient to find out if it's been modified. Moving or renaming a file doesn't change its modification time, so if you delete the original file and then move/rename a different file to that location, it won't trigger your build script.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47998787
score: 0

http://stackoverflow.com/a/47869161
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47861343
has comment: http://stackoverflow.com/comment/82709985
has body: Below example produces a simple image viewer tested with path of C:\Users\Public\Pictures\Sample Pictures, let me know if anything's unclear: import tkinter as tk from PIL import Image, ImageTk #required for getting files in a path import os class ImageViewer(tk.Label): def __init__(self, master, path): super().__init__(master) self.path = path self.image_index = 0 self.list_image_files() self.show_image() self.bind('&lt;Button-1&gt;', self.show_next_image) def list_files(self): (_, _, filenames) = next(os.walk(self.path)) return filenames def list_image_files(self): self.image_files = list() for a_file in self.list_files(): if a_file.lower().endswith(('.jpg', '.png', '.jpeg')): self.image_files.append(a_file) def show_image(self): img = Image.open(self.path + "\\" + self.image_files[self.image_index]) self.img = ImageTk.PhotoImage(img) self['image'] = self.img def show_next_image(self, *args): self.image_index = (self.image_index + 1) % len(self.image_files) self.show_image() root = tk.Tk() mypath = r"C:\Users\Public\Pictures\Sample Pictures" a = ImageViewer(root, mypath) a.pack() root.mainloop()

http://stackoverflow.com/comment/82756830
has text: Why are you using a nested loop? You should be `zip`ping them together.
comment on: http://stackoverflow.com/q/47895049
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47915570
has comment: http://stackoverflow.com/comment/82831286
type: UnansweredQuestion
has body: I am trying to make a post request to mailchimp's api. It works perfectly fine when I am doing it in my local machine but somehow when I push it into the cloud. This error appears and I thought it was because of the python version since it's the only differences between local and the cloud. In cloud it's python 2.7.6 local I am using 2.7.12 I have searched up but a few issues only talks about other lib that's causing the error. I didn't have new requirements installed at all. I can calling a post request by using something like requests.post(MAILCHAMP_API, payload, headers=headers).json() Then I get an error of cannot make memory view because object does not have the buffer interface Exception Location: /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/contrib/pyopenssl.py in sendall, line 216
has title: TypeError: cannot make memory view because object does not have the buffer - django
tagged with: django
has comment: http://stackoverflow.com/comment/82805090
tagged with: python
tagged with: request
answer count: 0
downvote count: 0
score: 1
type: Question
tagged with: post
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/82968739
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47998787
type: QuestionComment
has text: If ext4, the lag in modification times may be related to this: https://stackoverflow.com/questions/14392975/timestamp-accuracy-on-ext4-sub-millsecond

http://stackoverflow.com/comment/82824504
has text: @deceze what is curious is that the program stops at a random page and i had checked on that page if that div is there and it is.So I guess i need to implement a function that retries to get that url and parse it again until it finds the div.Can you help me with my second error too?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47925511

http://stackoverflow.com/q/47896240
accepted answer: http://stackoverflow.com/a/47896300
tagged with: filter
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/82759659
answer count: 4
has body: I'm trying to select a subset of a subset of a dataframe, selecting only some columns, and filtering on the rows. df.loc[df.a.isin(['Apple', 'Pear', 'Mango']), ['a', 'b', 'f', 'g']] However, I'm getting the error: Passing list-likes to .loc or [] with any missing label will raise KeyError in the future, you can use .reindex() as an alternative. What 's the correct way to slice and filter now?
favorite count: 0
score: 41
has answer: http://stackoverflow.com/a/47896405
upvote count: 41
has comment: http://stackoverflow.com/comment/82759475
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/54983671
has answer: http://stackoverflow.com/a/54983671
has answer: http://stackoverflow.com/a/47896300
has answer: http://stackoverflow.com/a/65146867
tagged with: slice
linked to: http://stackoverflow.com/q/50229942
type: Question
has title: Pandas slicing FutureWarning with 0.21.0
has comment: http://stackoverflow.com/comment/82759641
downvote count: 0

http://stackoverflow.com/comment/82885663
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47958147
type: Comment
has text: Tried with `test_feats = [res.get() for res in test_feats]`. Having `TypeError: 'numpy.ndarray' object is not callable` , I will take my time to debug it

http://stackoverflow.com/comment/82937246
score: 0
comment on: http://stackoverflow.com/a/47983993
type: AnswerComment
has text: Thanks! Being able to use a dictionary rather than a db will be much simpler so I’m glad you eased my mind of possible effiency issues
type: Comment

http://stackoverflow.com/a/48000986
has body: states = [ 'Oregon': 'OR', 'Florida': 'FL', 'California': 'CA', 'New York': 'NY', 'Michigan': 'MI' ] Using square brackets, this is an attempt to define a list, and list items must be separated with commas. However, it seems that you want to create a dictionary here (i.e. a collection of key: value pairs), and for that braces (curly brackets) must be used: states = { 'Oregon': 'OR', 'Florida': 'FL', 'California': 'CA', 'New York': 'NY', 'Michigan': 'MI' }
has comment: http://stackoverflow.com/comment/82970538
type: Answer
answers question: http://stackoverflow.com/q/48000927
upvote count: 2
score: 1
downvote count: 1

http://stackoverflow.com/comment/82985996
comment on: http://stackoverflow.com/a/47944461
has text: Absolutely! Not the way to handle imports, unless there are constraints where one is not allowed to change the Python path, sys.path, etc. In the end, as I mentioned in the 1st paragraph above, the way to handle this is to set FLASK_APP, and run both the app & unittest as packages.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/47921216
has body: Approach #1 : Here's one approach - def label_based_on_shifts(a): # Detect starts of each label(element is non-zero and is different # from the previous element) mask = np.r_[a[0]!=0,(a[1:] != a[:-1]) &amp; (a[1:] !=0)] # Setup id array, which when cumulatively summed would lead us to # labelled islands out = mask.astype(np.uint64).cumsum() # Set the islands that are zeros in input array to be zeros in o/p too out[a==0] = 0 return out Sample run - In [53]: a Out[53]: array([0, 0, 1, 1, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 0, 0]) In [54]: label_based_on_shifts(a) Out[54]: array([0, 0, 1, 1, 0, 0, 2, 2, 3, 3, 4, 4, 5, 5, 0, 0]) Approach #2 : Another one to replace np.cumsum with np.repeat - def label_based_on_shifts_v2(a): mask = np.r_[True,(a[1:] != a[:-1]),True] idx = np.flatnonzero(mask) valid_idx_mask = a[idx[:-1]]!=0 starts = idx[:-1][valid_idx_mask] stops = idx[1:][valid_idx_mask] lens = stops-starts out = np.zeros(len(a), dtype=int) out[a!=0] = np.repeat(np.arange(1,len(starts)+1), lens) return out
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47921101
answers question: http://stackoverflow.com/q/47921101
type: Answer

http://stackoverflow.com/a/50824279
accepted answer of: http://stackoverflow.com/q/47983289
has body: It definitely means Redshift is not good for real-time loading and reporting. Redshift is a columnar based database, so writes to it are (relatively) expensive whereas reads are lightning fast compared to a row based database (like MySQL). What this means is that Redshift is ideal for queries that need to read a large amount of data, but you should load to Redshift in batches. I have used Redshift many times for something like your use case. The production data is cloned into Redshift multiple times per day (say every 30 minutes, incrementally. There are many vendors that could do this for you). Whenever a report is needed, the query hits Redshift instead of a production database. Not only will the query run faster, it won't lock up your production db. Additionally, if the query return times are still not fast enough for your liking. You can set up data pipelines to create summary tables. Instead of querying raw transaction data for every report, you could hit these summary tables eg SELECT date(transaction_date) as day, count(1) as transactions FROM transactions GROUP BY day ORDER BY day could just become SELECT day, transactions FROM transactions_summary_by_day The tradeoff is latency. Since you are not writing to Redshift constantly, any report pulled from Redshift will only have data as the most recent write batch. Maybe that's 30 minutes, maybe that's 1 day, it depends what you set up. Data pipelines will increase this latency, as reports built off of them use only data since they last ran, which relies on Redshift data that was loaded at that time. If your users need true "real-time" reporting this might be a dealbreaker. But if they work in terms of days or weeks, having an hour or so of latency is worth it to get quick-loading reports.
type: Answer
has comment: http://stackoverflow.com/comment/88653707
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88653877
upvote count: 1
answers question: http://stackoverflow.com/q/47983289
type: AcceptedAnswer

http://stackoverflow.com/a/48451655
has body: I would look into pandas (http://pandas.pydata.org/pandas-docs/stable/) and statsmodels (http://www.statsmodels.org/dev/index.html). Pandas is good for reading data into dataframes in python, and then you can run statistical models with statsmodels. I am not well-versed in statsmodels, so you may have to look into the documentation yourself. Here is an example, to try and go along with what you showed in your question: import pandas as pd import statsmodels.formula.api as sm df = pd.read_csv("data.csv", sep=",") df.dropna(axis=0, how='any') results = sm.ols(formula="v3~v2", data=df).fit() t_test = results.t_test('v2=0') if (t_test.pvalue*2) &gt; 0.01: print("notsig") print(t_test.pvalue*2) if (t_test.pvalue*2) &lt;= 0.01: print("sig") print(t_test.pvalue*2) I took the pvalue*2 in this example, because I believe that it only gives the one-tail p-value, but you should check the documentation to make sure.
answers question: http://stackoverflow.com/q/47896641
upvote count: 1
has comment: http://stackoverflow.com/comment/86419614
has comment: http://stackoverflow.com/comment/83899454
type: Answer
has comment: http://stackoverflow.com/comment/83945970
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/86528000

http://stackoverflow.com/a/47988808
has comment: http://stackoverflow.com/comment/82959477
has comment: http://stackoverflow.com/comment/82949534
score: 1
has comment: http://stackoverflow.com/comment/82959203
has comment: http://stackoverflow.com/comment/82959789
upvote count: 1
has comment: http://stackoverflow.com/comment/82958913
answers question: http://stackoverflow.com/q/47987707
has comment: http://stackoverflow.com/comment/82948912
has comment: http://stackoverflow.com/comment/82948579
has body: Another Posssible Approach: One way to possibly speed up the search time for checking if a value exists in input_set is to use binary search, which is O(logn). Here is some example code which also uses the convienient collections.defaultdict: from collections import defaultdict master = { "KeyA": ['Aron', 'Ranom Value', 'Abhishek'], "KeyB": ['Ball', 'Foo', 'Bar', 'Badge', 'Dog'], "KeyZ": ['Random Value', 'Foo', 'Bar'] } input_set = ['Foo', 'Bar', 'Dog', 'Aron'] sorted_list = sorted(input_set) d = defaultdict(list) for key, value in master.items(): for v in value: if binary_search(sorted_list, v): d[key].append(v) print(d) Which Outputs: defaultdict(&lt;class 'list'&gt;, {'KeyA': ['Aron'], 'KeyB': ['Foo', 'Bar', 'Dog'], 'KeyZ': ['Foo', 'Bar']}) Where binary_search() is defined below: def binary_search(item_list,item): first = 0 last = len(item_list)-1 while first &lt;= last: mid = (first + last)//2 if item_list[mid] == item : return True elif item &lt; item_list[mid]: last = mid - 1 else: first = mid + 1 return False The above code does seem like reinventing the wheel. You can have a look at the bisect module which provides some ways to call binary search without having to write your own function. Note: In order to use binary search, you also need to sort the values before hand, which is O(nlogn). I'm not entirely sure how much impact this will have, you'd have to run some tests with another approach to see the difference. Additionally, as @SuperSaiyan posted, converting input_set to a set is the most efficient approach, because set lookup O(1) in the best case, and O(n) in the worst case(rare).
has comment: http://stackoverflow.com/comment/82948514
has comment: http://stackoverflow.com/comment/82959751
downvote count: 0
has comment: http://stackoverflow.com/comment/82948208
has comment: http://stackoverflow.com/comment/82959338
has comment: http://stackoverflow.com/comment/82957655
has comment: http://stackoverflow.com/comment/82956964
type: Answer

http://stackoverflow.com/a/47871343
has comment: http://stackoverflow.com/comment/82708066
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47871328
accepted answer of: http://stackoverflow.com/q/47871328
has comment: http://stackoverflow.com/comment/82708097
has body: Option 1 Using concat + groupby - pd.concat([df1, df2, df3], 1).groupby(axis=1, level=0).first() a b c d e 0 1 2 3 4 5 1 11 22 33 44 55 Option 2 merge - df1.merge(df2).merge(df3) a b c d e 0 1 2 3 4 5 1 11 22 33 44 55 In general, for n dataframes, if you have a list of them, you can perform an n-way merge with a loop - df_list = [df1, df2, df3] df = df_list[0] for d in df_list[1:]: df = df.merge(d) df a b c d e 0 1 2 3 4 5 1 11 22 33 44 55
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/82676410
type: QuestionComment
comment on: http://stackoverflow.com/q/47856142
score: 0
type: Comment
has text: Simply `import time` should work fine.

http://stackoverflow.com/q/47857270
answer count: 1
tagged with: pyscripter
tagged with: execjs
tagged with: javascript
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48856987
has body: I am trying to insert an image generated by Matplot into a Google Sheet from Python from PyScripter using Python 2.7. This is the starting data from the csv: x Date orcl 0 10/17/2016 37.685646 20 11/14/2016 38.679703 40 12/13/2016 40.116657 60 1/12/2017 38.732384 80 2/10/2017 40.303417 100 3/13/2017 42.072063 120 4/10/2017 43.662434 140 5/9/2017 45.131077 160 6/7/2017 45.051693 180 7/6/2017 48.47522 200 8/3/2017 50.032654 220 8/31/2017 50.132263 240 9/29/2017 48.160038 260 10/27/2017 50.880001 280 11/27/2017 48.880001 Here are the imports: import pandas as pd import statsmodels.api as sm import numpy as np import matplotlib.pyplot as plt import matplotlib matplotlib.style.use('ggplot') Get the data from the file and genereate the plots: file = pd.read_csv('orcl.csv') x = file.iloc[ :, -3] y = file.iloc[ :, -1] m, b = np.polyfit(x, y, 1) results = sm.OLS(y,x).fit() print ('results are: ', (results)) fig, ax = plt.subplots() plt.plot(x, y, '.', label = None) plt.plot(x, m*x + b, '-',label='Regression Line') ax.scatter(x, y) ax.set_xlabel(r'days_from_start', fontsize=15) ax.set_ylabel(r'stock_price', fontsize=15) ax.grid(True) fig.tight_layout() plt.legend() plt.savefig("orcl.png", bbox_inches='tight') plt.show() Pyscripter hangs up in a debug session, even though I have debug turned off in > Tools > Options > IDE Options > Postmortem on exception until I close the plot window. This code dose not close the plot: plt.close() I am having trouble with the ExecJS: import execjs # execjs from here: https://pypi.python.org/pypi/PyExecJS # javascript from here: https://stackoverflow.com/questions/ #43664483/insert-image-into-google-sheets-cell-using-google-sheets-api ctx = execjs.compile( """ { var ss=SpreadsheetApp.getActiveSpreadsheet() var formulaSheet = ss.getSheetByName("orcl"); '''tab 'orcl' is present. var formulaCell = formulaSheet.getRange("B5"); formulaCell.setFormula('=IMAGE("orcl.png",4,100,200)') } #http://finviz.com/fut_chart.ashx?t=ES&amp;p&amp;p=m5&amp;s=m """…
downvote count: 0
score: 1
has title: Insert image in Google Sheets from python, PyExecJS, and JavaScript using PyScripter
favorite count: 0
type: Question
tagged with: python
upvote count: 1

http://stackoverflow.com/q/47935303
score: 0
answer count: 3
has body: I am trying to make a two person game where each person moves an object but if one person is moving their object the other can't. Here is my code. running = True while running: if event.type == pygame.KEYDOWN: if (event.key == 276): bat2.rect.x -= 2 if (event.key == 275): bat2.rect.x += 2 if (event.key == 97): bat1.rect.x -= 1 if (event.key == 100): bat1.rect.x += 1 Each bat is a different object. Is there a way?
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: pygame
has comment: http://stackoverflow.com/comment/82840600
has answer: http://stackoverflow.com/a/47935422
has comment: http://stackoverflow.com/comment/82840646
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82840557
type: Question
has answer: http://stackoverflow.com/a/47935602
has answer: http://stackoverflow.com/a/47935652
has title: Press multiple keys at once

http://stackoverflow.com/comment/82971797
type: Comment
type: AnswerComment
has text: This would work if i was not using regex. But argv in this case could be a regex to allow for greater flexibility in the search.
comment on: http://stackoverflow.com/a/48001617
score: 0

http://stackoverflow.com/q/47911683
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47911899
has answer: http://stackoverflow.com/a/47911922
type: Question
has title: Adding user inputted numbers within a function
has answer: http://stackoverflow.com/a/47911873
has comment: http://stackoverflow.com/comment/82796948
has answer: http://stackoverflow.com/a/47911818
score: 0
has answer: http://stackoverflow.com/a/47911912
has body: I am new to creating user-defined functions in python and I was wondering what is going wrong here, I am basically trying to get the user to input a number which is the amount of numbers they wish to add together. The program will then ask them to enter a number for the amount of times the previously entered number states. For instance, if the user entered 3, the program would ask them to enter three different numbers. Then program will then utilise the function I created to add those numbers together. def add_multi(x): z = 0 for i in range(y): z = z + x return z y = int(input("Enter amount of numbers you wish to add: ")) for i in range(y): x = int(input("Enter number: ")) print(add_multi(x)) I go to input 2 for the amount numbers I wish to add together, and I then choose the numbers 2 and 1 to add together. Usually this would output 3 but it somehow outputs the number 2 and I have no idea why. If anyone can help it would be greatly appreciated as I am completely stuck.
possible better answer: http://stackoverflow.com/a/47911818
answer count: 5
tagged with: python
accepted answer: http://stackoverflow.com/a/47911912

http://stackoverflow.com/comment/82905553
score: 0
type: AnswerComment
type: Comment
has text: Well, try to create a string which has shown structure, instead of passing a dictionary with needed values. One thing to figure out yourself is where does this 11-digit number comes from (I suppose this is some sort of anti-bot protection).
comment on: http://stackoverflow.com/a/47967953

http://stackoverflow.com/a/48001768
has body: Why doesn't a simple import statement in the original code do the job? Like so: import first # # The rest of the program. # Then from the command line, you only need to run python test.py As long as test.py and first.py are in the same directory, this approach is effectively "including" first.py in test.py. Please include more information about why you want to pass first.py as a command line argument. It seems to me, since you already know what your program will be doing with first.py, and you have to write your code under the assumption that first.py will be imported anyway, you might as well just do it at the beginning of test.py.
has comment: http://stackoverflow.com/comment/82972114
type: Answer
answers question: http://stackoverflow.com/q/48001691
has comment: http://stackoverflow.com/comment/82972082
score: 0

http://stackoverflow.com/q/47856390
upvote count: 1
has comment: http://stackoverflow.com/comment/82677476
has comment: http://stackoverflow.com/comment/82676981
downvote count: 0
has answer: http://stackoverflow.com/a/70766151
has comment: http://stackoverflow.com/comment/82677364
favorite count: 0
tagged with: pygame
has comment: http://stackoverflow.com/comment/82677417
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47856729
has title: How do I blit a background only once in pygame?
tagged with: python
tagged with: blit
score: 1
has body: I am making a platformer and I've run into a problem wwhen blitting the background. In my current code, the game loop draws the background on the game window every frame, which makes the game really laggy when I want to use any background that isn't just a solid color. My question is how do I blit the background only once (if it's possible) so that the game wouldn't slow down so much. Here are some parts of my Game class that lead to blitting the image: class Game: def __init__(self): pg.init() pg.mixer.init() self.bg = pg.image.load("background.jpg") self.screen = pg.display.set_mode((WIDTH, HEIGHT)) pg.display.set_caption(TITLE) self.clock = pg.time.Clock() self.running = True self.font_name = pg.font.match_font(FONT_NAME) self.pillarhp = 100 def new(self): self.run() def run(self): self.clock.tick(FPS) self.playing = True while self.playing: self.clock.tick(FPS) self.events() self.update() self.draw() def draw(self): now = pg.time.get_ticks() self.screen.blit(self.bg, [0, 0]) self.screen.blit(self.island, [0,0]) self.all_sprites.draw(self.screen) self.draw_text("Score: " + str(self.score), 20, BLACK, 40, 20) self.draw_text("Pillar HP: " + str(self.pillarhp), 20, BLACK, 40, 50) pg.display.flip()
has comment: http://stackoverflow.com/comment/82677440
tagged with: background
type: Question
answer count: 2

http://stackoverflow.com/q/48010776
has answer: http://stackoverflow.com/a/48010831
duplicate of: http://stackoverflow.com/q/9202224
type: Question
answer count: 2
has title: How to make the output of input function look like a * symbol?
downvote count: 0
linked to: http://stackoverflow.com/q/27631629
has answer: http://stackoverflow.com/a/48010830
has comment: http://stackoverflow.com/comment/82990365
has comment: http://stackoverflow.com/comment/82990059
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/82990054
upvote count: 2
type: UnansweredQuestion
has body: I'm making a program where the user needs to enter a password. I'm using the input function for this. How would I make it so that the user sees *** symbols instead of the actual letters for their password?
has comment: http://stackoverflow.com/comment/82991452
score: 2

peewee
tag name: peewee
tags question: http://stackoverflow.com/q/47896615
tags question: http://stackoverflow.com/q/47880166
type: Tag
tags question: http://stackoverflow.com/q/47976768
tags question: http://stackoverflow.com/q/47970063
tags question: http://stackoverflow.com/q/47995101

http://stackoverflow.com/comment/83024265
comment on: http://stackoverflow.com/a/48012748
type: AnswerComment
score: 0
type: Comment
has text: Didn't know about sys.displayhook existence. Thank you.

http://stackoverflow.com/comment/82843179
comment on: http://stackoverflow.com/q/47936474
has text: Does this [thread](https://stackoverflow.com/questions/31464345/fitting-a-closed-curve-to-a-set-of-points) helps ?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47931000
upvote count: 2
has comment: http://stackoverflow.com/comment/82832284
type: Answer
score: 2
has body: Setup - df1 = df1.set_index('Name') df2 = df2.set_index('Name2') df1 1 2 3 Name xy-yz 1 1 2 xa-ab 2 2 2 yz-ijk 3 1 2 zb-ijk 4 2 2 df2 1 2 3 Name2 x 0 1 5 y 1 2 5 z 2 3 5 a 3 4 6 Retrieve relevant rows from df2 based on the first letter of df1. i = df2.loc[df1.index.str[0]] i 1 2 3 Name2 x 0 1 5 x 0 1 5 y 1 2 5 z 2 3 5 Perform divison and reset the index. j = (df1.set_index(i.index) / i).set_index(df1.index) j 1 2 3 Name xy-yz inf 1.000000 0.4 xa-ab inf 2.000000 0.4 yz-ijk 3.000000 0.500000 0.4 zb-ijk 2.000000 0.666667 0.4 Concatenate the result. pd.concat([df1, i, j]) 1 2 3 xy-yz 1.000000 1.000000 2.0 xa-ab 2.000000 2.000000 2.0 yz-ijk 3.000000 1.000000 2.0 zb-ijk 4.000000 2.000000 2.0 x 0.000000 1.000000 5.0 x 0.000000 1.000000 5.0 y 1.000000 2.000000 5.0 z 2.000000 3.000000 5.0 xy-yz inf 1.000000 0.4 xa-ab inf 2.000000 0.4 yz-ijk 3.000000 0.500000 0.4 zb-ijk 2.000000 0.666667 0.4 Here, once again, use np.isfinite on j if you want to mask non-real numeric values - j = j[np.isfinite(j)].fillna('') j 1 2 3 Name xy-yz 1.000000 0.4 xa-ab 2.000000 0.4 yz-ijk 3 0.500000 0.4 zb-ijk 2 0.666667 0.4 Use this j as the argument to concatenation afterwards.
has comment: http://stackoverflow.com/comment/82832401
has comment: http://stackoverflow.com/comment/82831532
has comment: http://stackoverflow.com/comment/82831991
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82832160
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47930647
has comment: http://stackoverflow.com/comment/82832167
answers question: http://stackoverflow.com/q/47930647

http://stackoverflow.com/a/47891410
type: AcceptedAnswer
has body: set() takes the values from an iterable and adds each value separately. You passed in a tuple, which is an iterable with two values. If you wanted to add the tuple itself, you need to wrap that in an iterable, like a list: set([("1111","test1")]) In Python 3, you can instead use a set display to create a new set: {("1111","test1")} A set display takes elements separated by commas, and ("1111", "test1") is one tuple element here. In the other post, the set was created with a set display (so {tuple1, tuple2, etc.}) and the answers used either an itertools function or a generator expression to produce the sequence of tuples for the set() function to process; a both produce an iterable type.
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47891372
score: 6
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/47891372

http://stackoverflow.com/q/47957020
tagged with: python
tagged with: insert
answer count: 4
has body: Given original = 'Has two optional arguments which must be specified.' and strings = [{'index': 3, 'string': 'foo'}, {'index': 7, 'string': 'bar'}, {'index': 12, 'string': 'abc'}] what would be an efficient way (ideally by only iterating once over original) to insert all of the strings in strings to original at their specified index? The function, in this case would return 'Hasfoo twobar optiabconal arguments which must be specified.'. For example, here is an inefficient implementation I just wrote: def add_strings(original, strings): added_length = 0 for i in strings: insertion_index = i['index'] + added_length original = original[:insertion_index] + i['string'] + original[insertion_index:] added_length += len(i['string']) return original
favorite count: 0
has answer: http://stackoverflow.com/a/47957032
accepted answer: http://stackoverflow.com/a/47957283
has answer: http://stackoverflow.com/a/47966947
has comment: http://stackoverflow.com/comment/82884170
upvote count: 1
possible better answer: http://stackoverflow.com/a/47957696
has comment: http://stackoverflow.com/comment/82883421
downvote count: 1
has answer: http://stackoverflow.com/a/47957696
type: AnsweredQuestion
tagged with: list
has title: Insert several strings into one string (Python)
has comment: http://stackoverflow.com/comment/82883704
type: Question
has comment: http://stackoverflow.com/comment/82883753
has answer: http://stackoverflow.com/a/47957283
tagged with: string
score: 0

http://stackoverflow.com/q/48008048
upvote count: 4
has comment: http://stackoverflow.com/comment/82986318
answer count: 1
has answer: http://stackoverflow.com/a/48008098
tagged with: keras
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has body: I have the following code from keras.preprocessing import image test_image = image.load_img('roi.jpg', target_size = (64, 64),grayscale=True) test_image = image.img_to_array(test_image) test_image = np.expand_dims(test_image, axis = 0) The roi.jpg is an image which saved in the same directory. After execution I got the following error test_image = image.load_img('roi.jpg', target_size = (64, 64),grayscale=True) File "C:\ProgramData\Anaconda3\lib\site-packages\keras\preprocessing\image.py", line 345, in load_img raise ImportError('Could not import PIL.Image. ') ImportError: Could not import PIL.Image. The use of `array_to_img` requires PIL. Please help me to solve this error. I have used windows 10 and python version : Python 3.6.3 :: Anaconda custom (64-bit)
has comment: http://stackoverflow.com/comment/82985254
has title: image.load_img error in python, Keras
downvote count: 1
type: Question
score: 3
tagged with: anaconda
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/82990106

http://stackoverflow.com/q/47980075
has answer: http://stackoverflow.com/a/47980206
score: 0
answer count: 1
tagged with: oop
accepted answer: http://stackoverflow.com/a/47980206
type: AnsweredQuestion
has title: How to make a variable behave like a reference or a value hook?
has body: To specific, here is a class A, which has a member var storing some intermediate result. What I want to do is trying to make a wrapper which have an instance of A() as a member, but still accessing var without changing other part of code. Pseudo-Code: Class A: def __init__(self): self.var=0 .... Class B: def __init__(self): self.submod=A() instance_b = B() and make instance_b.var refers to instance_b.submod.var as it changes while running.
tagged with: python-3.x
type: Question
tagged with: python

http://stackoverflow.com/q/47863796
tagged with: base64
has title: Type Error encountered while working on custom encode in python 3.6
score: 0
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47864056
type: Question
has body: I wrote a custom encoding code snippet. When i run it on pyton 3.6 i got type error. I couldn't figure it out exactly. The code snippet is working fine with python 2.7. import os import sys import base64 def encode(key, clear): """encode custom """ enc = [] for i in range(len(clear)): key_c = key[i % len(key)] enc_c = chr((ord(clear[i]) + ord(key_c)) % 256) #change the int or str enc.append(enc_c) return base64.urlsafe_b64encode("".join(enc)) clear = "ABCDEFGH" encode_var = encode("crumbs", clear) Error Log : (py3) C:\Dev\crumbles&gt;python s1.py Traceback (most recent call last): File "s1.py", line 45, in &lt;module&gt; encode_var = encode("crumbs", clear) File "s1.py", line 42, in encode return base64.urlsafe_b64encode("".join(enc)) File "C:\Users\Cookie1\Anaconda3\envs\py3\lib\base64.py", line 118, in urlsafe _b64encode return b64encode(s).translate(_urlsafe_encode_translation) File "C:\Users\Cookie1\Anaconda3\envs\py3\lib\base64.py", line 58, in b64encod e encoded = binascii.b2a_base64(s, newline=False) TypeError: a bytes-like object is required, not 'str'
accepted answer: http://stackoverflow.com/a/47864056
answer count: 1

http://stackoverflow.com/a/48028861
type: Answer
has body: This answer shows some examples of how to use db2cli.exe to configure db2dsdriver.cfg Remember that you do not need to use DSNs in python to connect to Db2 databases, you can use the long form of the connect to specify all the details of the connection. Using a DSN is useful when the DSN is used by multiple different local applications(so the config is only in one place), or when your python scripts need to run on multiple environments which may use different DSN details without code changes and where the DSNs are under control of a different group, or when DSN-parameters are environment specific. So choose the best approach to suit your enterprise. If you must use DSNs, choose either user-dsn's or system-dsn as appropriate for your environment and requirements. Choose which format of configuration file to use for the Db2 client. The db2cli.ini is an old legacy format Windows style INI file with x=y tuples and [section] blocks in plain text. You can manipulate its contents either with a text editor or with command line commands of Db2 . This old format has enough online documentation and has been around for decades, so I won't expand on this. The db2dsdriver.cfg file is a more recent format. It is an XML file. You can edit it with Db2 commands (db2cli.exe on Windows) or via a text editor (or XML editor). I would use this format for new environments with currently supported Db2 clients. As its XML, there is a validation step (db2cli validate ...). The online Db2 Knowledge centre has all this information although you do need to spend time studying many pages and rehearse and test carefully. Here are some sample lines of batch file script, which you can run in an ADMINISTRATOR db2cmd.exe window on MS-windows, which show how to use the db2cli.exe tool to populate db2dsdriver.cfg. You have to have at least local-admin rights to run these commands. First set some variables to match your specific environment, port-number, hostname of Db2 server, credentials and DSN and rem…
answers question: http://stackoverflow.com/q/48013391
upvote count: 1
has comment: http://stackoverflow.com/comment/107861099
has comment: http://stackoverflow.com/comment/83109608
score: 1
has comment: http://stackoverflow.com/comment/107872390
has comment: http://stackoverflow.com/comment/107854615
accepted answer of: http://stackoverflow.com/q/48013391
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/82868058
comment on: http://stackoverflow.com/q/47949044
score: 0
type: Comment
type: QuestionComment
has text: You want to avoid shadowing. i.e. using `NAMES` inside `clean_names`. Unless it is passed as a parameter.

http://stackoverflow.com/a/75938191
has body: pip install openpyxl The above command worked for me.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47975866
has comment: http://stackoverflow.com/comment/133996350

http://stackoverflow.com/comment/82916134
type: Comment
has text: always put full error message (Traceback) in question (as text, not screenshot). There are other useful informations.
type: QuestionComment
comment on: http://stackoverflow.com/q/47973248
score: 1

http://stackoverflow.com/q/48012513
accepted answer: http://stackoverflow.com/a/48176746
has body: I have a user choose 4 directories using tkinter in "loadingfiles." From there, it loads all of the files from each directory. how would I be able to save all of the subplots into a PDF. I know I have to do it from the main function, but how would I go about this? def loadingfiles(): #loads all of the files from each directory #returns Files def initialize_and_Calculate(Files=[],*args): fig = plt.figure() fig.set_size_inches(9,5,forward=True) gs1=gridspec.GridSpec(1,2) ax0=fig.add_subplot(gs1[0,0]) ax1=fig.add_subplot(gs1[0,1]) #treat x and y as a parameter within a file in a directory. Can be any numbers ax0.plot(x,y,'-') ax1.plot(x1,y1,'-') fig.tight_layout() def main(): Files=loadingfiles() #this loads the files in directory L=len(Files) for c in range (0,L): #this for loops runs the initialize_and_Calc. function per directory. initialize_and_Calculate(Files[c]) #'File[0]' is directory 1. 'File[1]' is directory 2...and so on plt.show() if __name__=="__main__": main() If this doesn't make any sense, then how can I pass a 'fig' in a function. Say if I were to make a figure in my main function, how can I pass 'fig' to a function?
tagged with: plot
type: Question
tagged with: matplotlib
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/48176746
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
has title: Saving multiple subplots into one pdf using different functions

http://stackoverflow.com/q/47892066
has title: SGD Classifier partial fit learning with different dimensional input data
has comment: http://stackoverflow.com/comment/82751452
tagged with: python
tagged with: classification
type: UnansweredQuestion
tagged with: machine-learning
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/82751398
has answer: http://stackoverflow.com/a/47892538
type: Question
linked to: http://stackoverflow.com/q/48074462
answer count: 1
downvote count: 0
tagged with: scikit-learn
has body: I am trying to perform a SGD classification for one hot encoded data. I did a fit on my training example and want to perform partial_fit on fewer data at later time. I understand the error getting thrown because of dimension change between fit data and partial_fit data. I also understand I need to perform data transform on my hot_new_df but I am unsure how. IN[29] -- is where i am doing a fit() IN[32] -- is where i am doing a partial_fit() I have just presented a hypothetical example here... My actual data is over shape of 40K rows and ~200 columns Jupyter QtConsole 4.3.1 Python 3.6.2 |Anaconda custom (64-bit)| (default, Sep 21 2017, 18:29:43) Type 'copyright', 'credits' or 'license' for more information IPython 6.1.0 -- An enhanced Interactive Python. Type '?' for help. In [27]: import pandas as pd ...: ...: input_df = pd.DataFrame(dict(fruit=['Apple', 'Orange', 'Pine'], ...: color=['Red', 'Orange','Green'], ...: is_sweet = [0,0,1], ...: country=['USA','India','Asia'], ...: is_valid = ['Valid', 'Valid', 'Invalid'])) ...: input_df Out[27]: color country fruit is_sweet is_valid 0 Red USA Apple 0 Valid 1 Orange India Orange 0 Valid 2 Green Asia Pine 1 Invalid In [28]: hot_df = pd.get_dummies(input_df, columns=['fruit','color','country']) ...: hot_df Out[28]: is_sweet is_valid fruit_Apple fruit_Orange fruit_Pine color_Green \ 0 0 Valid 1 0 0 0 1 0 Valid 0 1 0 0 2 1 Invalid 0 0 1 1 color_Orange color_Red country_Asia country_India country_USA 0 0 1 0 0 1 1 1 0 0 1 0 2 0 0 1 0 0 In [29]: from sklearn.linear_model import SGDClassifier ...: from sklearn.model_selection import train_test_split ...: ...: X_train, X_test, y_train, y_test = train_test_split(hot_df.drop(['is_valid'], axis=1), ...: hot_df['is_valid'], ...: test_size=0.1) ...: clf = SGDClassifier(loss="log", penalty="l2") ...: clf.fit(X_train, y_train) ...: clf /Users/praj3/anaconda3/lib/python3.6/site-packages/sklearn/linear_model/stochastic_gradient.py:84: FutureWarning: max_iter and tol parameters have been ad…
favorite count: 0

http://stackoverflow.com/comment/82774620
has text: @StevenBENET I collect the data from sql but process on python and I use zeppelin so I guess python 3
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47903700
type: Comment

http://stackoverflow.com/q/47886981
type: Question
upvote count: 2
answer count: 1
has body: I want to be able to set a variable in the django admin panel, which will be passed to the template as template variable, similar to placeholder in cms. (For example when I save this variable in admin panel it will be rendered to the template) Added. Let's say I have a site page with text area, this text area I can replace by template variable in view with template tags {{ text }}. But I want to do it in the django admin panel, what i did was creating the model with text field, registering it in admin panel and replacing only one row in this table and geting this text variable in view that I want to pass in to the template as text_home = Text_home_page.objects.all()[0].text. I think that creating whole table to modify only one template variable is not a good idea. I found a similar question but i dont know how to implement it.
favorite count: 0
has answer: http://stackoverflow.com/a/47911455
downvote count: 5
type: UnansweredQuestion
has title: Django, how to pass a variable from the Django admin to a template?
score: -3
tagged with: python
linked to: http://stackoverflow.com/q/9220042
tagged with: django-templates
tagged with: django

http://stackoverflow.com/a/47968928
type: Answer
answers question: http://stackoverflow.com/q/47968824
has body: Try this: class P: limit = 8 def __init__(self, x=0, y=0, p=None): self.x = x self.y = y self.parents = p def __str__(self): s = '' for p in self.parents: s += '({},{}-&gt;)'.format(p.x, p.y) s += '({},{}-&gt;)'.format(self.x, self.y) return s + '\n' def next_move(self): def valid(x): return 0 &lt;= x &lt; P.limit x, y = self.x, self.y a = [-1, 1] b = [-2, 2] ls = [(x + i, y + j) for i in a for j in b if valid(x + i) and valid(y + j)] ls += [(x + i, y + j) for i in b for j in a if valid(x + i) and valid(y + j)] to_return = [] for i in range(len(ls)): to_return.append(P(ls[i][0], ls[i][1], self)) return to_return p = P() print(p.next_move()) See changes in Line 27 Because to_return is a list, so we can't use + operator. We can use append function for list.
score: 0

http://stackoverflow.com/comment/82896411
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47963198
has text: There should be two buttons displayed, but there is nothing displayed. Changing Test.kv to test.kv is not working.
score: 0

http://stackoverflow.com/a/47912114
accepted answer of: http://stackoverflow.com/q/47911773
answers question: http://stackoverflow.com/q/47911773
has comment: http://stackoverflow.com/comment/82793518
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82793674
has comment: http://stackoverflow.com/comment/82800533
has comment: http://stackoverflow.com/comment/82792378
type: Answer
has comment: http://stackoverflow.com/comment/82794912
has comment: http://stackoverflow.com/comment/82797508
has comment: http://stackoverflow.com/comment/82795539
downvote count: 0
has comment: http://stackoverflow.com/comment/82797114
score: 1
has body: Removing duplicates Before #Sort movie name list movielist.sort() Add the line movielist = list(set(movielist)) A set is like a list, except you're not allowed to have duplicates in a set, so converting your list to a set and back will remove all duplicates. The CSV Output csvwriter.writerow takes a list of lists. The outer lists are for each of the rows and the inner list is for each column in that row. Right now the outer list only has one item in it -- [movielist]. And everything inside of movielist is the data for the various columns. What you're going to want to do is instead of passing writerows.rows data that is in the form [ ["title1", "title2", "title3", "etc."] ] You're going to want to pass it something more like this [ ["title1"], ["title2"], ["title3"], ["etc."] ] Edit 2: This can be done like so: movielist2 = [] for movie in movielist: movielist2.append([movie]) writer.writerows(movielist2) Edit 3: Instead of doing the above, you could also change the line #Add movie name to list movielist.append(movienames) to #Add movie name to list movielist.append([movienames]) And that should work as well. You just have to make sure that the movielist that gets passed into the writer.writerows() function is a list of lists, instead of a list.
has comment: http://stackoverflow.com/comment/82792348
has comment: http://stackoverflow.com/comment/82795878
has comment: http://stackoverflow.com/comment/82800072
has comment: http://stackoverflow.com/comment/82800231
has comment: http://stackoverflow.com/comment/82798327
has comment: http://stackoverflow.com/comment/82799021
has comment: http://stackoverflow.com/comment/82792908

http://stackoverflow.com/comment/82780783
has text: Actually, it isn't working quite the way it should still. Instead of returning the appropriate state name from the function, it is returning a "None" value. When I initially said it worked, I was looking at aggregate counts of the "" (blank) value that went to zero; turns out it simply returned None. It's not the function either because the function returns the correct value when testing on a single cell! Any other ideas?
type: AnswerComment
comment on: http://stackoverflow.com/a/47897508
score: 0
type: Comment

http://stackoverflow.com/q/47925610
tagged with: python
downvote count: 6
tagged with: list
has answer: http://stackoverflow.com/a/47925695
has answer: http://stackoverflow.com/a/47925706
type: Question
linked to: http://stackoverflow.com/q/30216000
score: -4
has comment: http://stackoverflow.com/comment/82819937
answer count: 2
has title: What is the difference between implementation of list() and [] in py3.x?
favorite count: 0
has body: Here is the sample code1 and its result. d ={ "name":"looser", "roll":6666, "profile" : "developer" } print("list formatted dict is {}".format([d])) for k,v in [d.items()]: if d[k] is "developer": d.pop(k) else: print(k) result: list formatted dict is [{'name': 'looser', 'roll': 6666, 'profile': 'developer'}] Traceback (most recent call last): File "/Users/rough/try.py", line 18, in &lt;module&gt; for k,v in [d.items()]: ValueError: too many values to unpack (expected 2) Process finished with exit code 1 Here is the sample code2 with modified form. d ={ "name":"looser", "roll":6666, "profile" : "developer" } print("list formatted dict is {}".format([d])) for k,v in list(d.items()): if d[k] is "developer": d.pop(k) else: print(k) result: list formatted dict is [{'name': 'looser', 'roll': 6666, 'profile': 'developer'}] name roll Process finished with exit code 0 On many places people tell me there is no difference, is it true there is no difference.If there is no difference then why such result. Because one is solving my problem of **RuntimeError: dictionary changed size during iteration **
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82818834
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/82772854
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47903089
has text: You misspelled `argv` as `agrv` on line 7.

http://stackoverflow.com/q/47914237
upvote count: 2
has title: FFMPEG command from Python 3.5 does not actually create audio file
score: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/82797900
has body: I have a Django web application that accepts user uploaded videos/audio and saves them into a folder '../WebAppDirectory/media/recordings'. I am then using a speech to text API to get a rough transcription of the audio. This is working fine for .wav and .mp4 files, but the web app also accepts videos (.MOV) that I would like to first convert to .wav, then pass off to the API. Using ffmpeg from my command line like this ffmpeg -i C:\Users\Nathan\Desktop\MeetingRecorderWebAPP\media\recordings\upload_sample.MOV -ab 160k -ac 2 -ar 44100 -vn upload_sample.wav Correctly creates the .wav file from the original .MOV. However, when I run this from python with subprocess.check_call(command, shell=True) ffmpeg responds with File 'upload_sample.wav' already exists. Overwrite ? [y/N] While Python tells me FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\Nathan\Desktop\MeetingRecorderWebAPP\media\recordings\upload_sample.wav' It is also worth noting that I do not see a 'upload_sample.wav' file in the media/recordings/ directory. This leads me to believe that maybe Python and ffmpeg are looking in different folders, but I am not sure where I am going wrong. When I print the command from the subprocess.check_call and copy/paste it into cmd, the file is created as expected. Hoping someone with some experience with ffmpeg/Python subprocess can help shed some light! Here are the files I am working with: Folder Structure DjangoWebApp |---media |---|---imgs |---|---recordings |---|---|---upload_sample.MOV |---uploaded_audio_to_text.py uploaded_audio_to_text.py import speech_recognition as sr from os import path import os import subprocess def speech_to_text(file_name): AUDIO_FILE = path.join(path.dirname(path.realpath(__file__)), 'media','recordings', file_name) print("Looking at path: ",AUDIO_FILE) # get extension AUDIO_FILE_EXT = os.path.splitext(AUDIO_FILE)[1] if(AUDIO_FILE_EXT == '.MOV'): print("File is not .wav: ", AUDIO_FILE_EXT, "found. Converting...") # We will …
answer count: 1
has answer: http://stackoverflow.com/a/47914998
favorite count: 0
tagged with: ffmpeg
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82797705
tagged with: python
tagged with: audio

http://stackoverflow.com/q/47917926
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47918007
upvote count: 3
linked to: http://stackoverflow.com/q/28896237
type: Question
possible better answer: http://stackoverflow.com/a/49868947
has title: Custom the `on_delete` param function in Django model fields
score: 3
has answer: http://stackoverflow.com/a/49868947
downvote count: 0
has body: I have a IPv4Manage model, in it I have a vlanedipv4network field: class IPv4Manage(models.Model): ... vlanedipv4network = models.ForeignKey( to=VlanedIPv4Network, related_name="ipv4s", on_delete=models.xxx, null=True) As we know, on the on_delete param, we general fill the models.xxx, such as models.CASCADE. Is it possible to custom a function, to fill there? I want to do other logic things there.
favorite count: 0
has answer: http://stackoverflow.com/a/47917990
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47917965
accepted answer: http://stackoverflow.com/a/47917990
answer count: 4

http://stackoverflow.com/comment/82923891
comment on: http://stackoverflow.com/q/47976853
score: 0
type: Comment
type: QuestionComment
has text: @VeltzerDoron I tried 'n_estimators': [5, 10, 15, 20], 'max_depth': [2, 3, 4, 6], 'min_samples_leaf': [30, 40, 50], Best Params: {'n_estimators': 5, 'max_depth': 4, 'min_samples_leaf': 30} roc_auc_score_train:0.95137440923 roc_auc_score_validation:0.491039110868

http://stackoverflow.com/q/47874523
type: Question
has answer: http://stackoverflow.com/a/47912455
has body: I'm trying to use CNTK in Python/VS2017. I'm experienced in VS but new to Python and CNTK. I've installed CNTK into Anaconda 4.1.1 and I've created a custom Anaconda environment pointing to C:\local\Anaconda3-4.1.1-Windows-x86_64\envs\cntk-py35. If I open an Interactive Window from the "Python Environments" list in VS2017, I can import CNTK. However, if I create an empty Python project in VS2017, then open an Interactive Window from the same Anaconda environment shown in the project "Python Environments" list, I get a "module not found". Any help is appreciated, Bill Traceback (most recent call last): File "C:\local\Anaconda3-4.1.1-Windows-x86_64\envs\cntk-py35\lib\site-packages\cntk\cntk_py.py", line 18, in swig_import_helper return importlib.import_module(mname) File "C:\local\Anaconda3-4.1.1-Windows-x86_64\envs\cntk-py35\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 986, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 956, in _find_and_load_unlocked ImportError: No module named 'cntk._cntk_py'
accepted answer: http://stackoverflow.com/a/47912455
tagged with: visual-studio-2017
downvote count: 0
answer count: 1
score: 1
favorite count: 0
tagged with: python
has title: import cntk works in VS2017 "python environment" but not in "python project"
type: AnsweredQuestion
tagged with: cntk
upvote count: 1

http://stackoverflow.com/comment/82730928
type: AnswerComment
has text: Maybe I am missing something, but changing `j` and `l` still doesn't mean you have to implement the `for` loop yourself but can still use Numpy vectorization.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47867754

http://stackoverflow.com/a/47949888
upvote count: 1
has comment: http://stackoverflow.com/comment/82880272
downvote count: 1
has body: You can use apply method to trim text in each row. Also to not get SettingWithCopyWarning: warning you have to use .loc and copy() s = s.copy() s.loc[:,"A"] = s.A.apply(lambda x : x[0]) print(s) A B 0 S 1 1 S 2 2 E 3 3 P 4
score: 0
has comment: http://stackoverflow.com/comment/82880093
type: Answer
answers question: http://stackoverflow.com/q/47949871

http://stackoverflow.com/q/47871344
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/47871345
has body: I am creating contours for a series of plots. I store the contour objects in a list and then later I create a new plot. How can I re-use the stored plots in the new plot? import numpy as np import matplotlib.pylab as plt # Used for calculating z: A = [0.9, 1.0] # Contour values we will use: values = [0.7, 0.8] # Create points for data: x = np.linspace(0.0, np.pi, 1000) y = np.linspace(0.0, np.pi, 1000) # Grid the data: xi, yi = np.meshgrid(x, y) # Lists for storing contours: CS0 = [] CS1 = [] for a in A: # Calculate z for this value of A: z = a * (np.cos(xi)**2 + np.sin(yi)**2) print np.max(z) print np.min(z) # Plot for this iteration: plt.figure() plt.contourf(xi, yi, z, 101) # Create contours for different values: solid = plt.contour(xi, yi, z, levels=[values[0]]) dashed = plt.contour(xi, yi, z, levels=[values[1]], linestyles='dashed') plt.show() # Store chosen contours or a comparative plot later: CS0.append(solid) CS1.append(dashed) These two figures are generated for the different values of A: Now continue by attempting to re-use the stored QuadContourSet objects: colours = ['red', 'orange'] plt.close() plt.figure() for c0, c1, color, a in zip(CS0, CS1, colours, A): print type(c0), type(c1) # Re-use c0 and c1 in this new plot...???.... plt.? = c0 # ??? plt.? = c1 # ??? plt.show() The normal way to create a new plot doesn't work because I simply want to reuse the ones I stored earlier.
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has title: Add existing plot to figure in matplotlib pylab
tagged with: matplotlib
has answer: http://stackoverflow.com/a/47871345
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/82676780
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/47856349
has text: Looks like Python-2.x versus Python-3.x since in Python-2.x `x/y` is integer division in case the operands are integers.
type: Comment

http://stackoverflow.com/q/47956242
tagged with: python
linked to: http://stackoverflow.com/q/2462248
tagged with: xpath
has comment: http://stackoverflow.com/comment/82882483
accepted answer: http://stackoverflow.com/a/47956569
upvote count: 2
has title: Can't parse data from `th` tag along with `td` tag from different tables
tagged with: web-scraping
has body: I've written a script in python using xpath to parse tabular data from a webpage. Upon execution, it is able to parse the data from tables flawlessly. The only thing that I can't fix is parse the table header that means th tag. If I would do the same using css selector, i could have used .cssselect("th,td") but in case of xpath I got stuck. Any help as to how I could parse the data from th tag also will be highly appreciated. Here is the script which is able to fetch everything from different tables except for the data within th tag: import requests from lxml.html import fromstring response = requests.get("https://fantasy.premierleague.com/player-list/") tree = fromstring(response.text) for row in tree.xpath("//*[@class='ism-table']//tr"): tab_d = row.xpath('.//td/text()') print(tab_d)
has answer: http://stackoverflow.com/a/47957135
tagged with: lxml
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/47956569
downvote count: 0
possible better answer: http://stackoverflow.com/a/47957135
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82886138
type: Question
answer count: 2

text-segmentation
tags question: http://stackoverflow.com/q/47874306
tags question: http://stackoverflow.com/q/47991814
tag name: text-segmentation
type: Tag

http://stackoverflow.com/a/47926814
upvote count: 2
has comment: http://stackoverflow.com/comment/82821610
has comment: http://stackoverflow.com/comment/82822109
has comment: http://stackoverflow.com/comment/82823238
has body: What you want to do is straight forward, it is just the syntax and how you organize the code. Here is my approach to your problem: import csv def merge(list1, list2): lookup = {row[0]: row for row in list1} for row2 in list2: value = row2[-1] if value in lookup: row1 = lookup[value] yield 'Yes', row1[1], row1[2], row2[1], row2[2], row1[0] else: yield 'No', 'N/A', 'N/A', row2[1], row2[2], row2[3] if __name__ == '__main__': list1 = [ ['10001', 'Jason', 'University of Utah School of Medicine'], ['10007', 'Zhang', 'Duke'], ['10016', 'Som', 'Dana-Farber']] list2 = [ ['Som', 'mrcc', 'Wed Dec 20 18:36:28 +0000 2017', '10016'], ['David', 'mrcc', 'Wed Dec 20 18:36:38 +0000 2017', '10013'], ['Kristen', 'mrcc gro', 'Wed Dec 20 18:37:24 +0000 2017', '10045'], ['Zhang', 'wan mrcc', 'Wed Dec 20 18:38:44 +0000 2017', '10007']] rows = merge(list1, list2) with open('merge_lists.csv', 'wb') as outfile: writer = csv.writer(outfile) writer.writerow(['User ID Present?', 'User Name', 'Center Name', 'Text', 'Date', 'User ID']) writer.writerows(rows) Notes The procedure you describe is in function merge. To make looking up easier, I created a dictionary called lookup where the user IDs are the keys, and the rows are the values. By writing to excel file, I guess you meant the CSV file format Update My original answer outputs to a CSV file, which I think the easiest to deal with. You can open that file in Excel without any difficulty. However, I have a feeling that you are insisting on writing to Excel format, so I spent some time to learn xlwt enough to use it. Here is my updated solution. Please note that this module deals with an older .xls file format, not the newer .xlsx format. If you save to .xlsx, Excel will not be able to open it. import xlwt def merge(list1, list2): lookup = {row[0]: row for row in list1} for row2 in list2: value = row2[-1] if value in lookup: row1 = lookup[value] yield 'Yes', row1[1], row1[2], row2[1], row2[2], row1[0] else: yield 'No', 'N/A', 'N/A', row2[1], row2…
accepted answer of: http://stackoverflow.com/q/47925894
score: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82835851
answers question: http://stackoverflow.com/q/47925894
type: Answer

http://stackoverflow.com/comment/82973923
type: Comment
type: QuestionComment
has text: my guess is that one dicts element has 84 terms and another has 83. Make sure you understand the source.
comment on: http://stackoverflow.com/q/48002267
score: 0

slice
tags question: http://stackoverflow.com/q/47963060
tags question: http://stackoverflow.com/q/47968232
tags question: http://stackoverflow.com/q/47904544
type: Tag
tags question: http://stackoverflow.com/q/47924407
tags question: http://stackoverflow.com/q/47932493
tags question: http://stackoverflow.com/q/47982894
tags question: http://stackoverflow.com/q/47966085
tags question: http://stackoverflow.com/q/47957475
tags question: http://stackoverflow.com/q/47947148
tag name: slice
tags question: http://stackoverflow.com/q/47857372
tags question: http://stackoverflow.com/q/47896240
tags question: http://stackoverflow.com/q/47959029
tags question: http://stackoverflow.com/q/47947279

http://stackoverflow.com/q/47867163
type: UnansweredQuestion
has title: how to access bug data from bugzilla using python
tagged with: python
type: Question
score: 0
has answer: http://stackoverflow.com/a/47869231
answer count: 1
tagged with: bugzilla
has body: i need to access bugzilla (server) data using python. what ways can use to do this. Is we can use XML-RPC or need layer by layer of understanding

libvirt
tag name: libvirt
tags question: http://stackoverflow.com/q/47926832
type: Tag

http://stackoverflow.com/q/47981720
has title: Unhashable type: 'list' error when running python script in mininet
type: UnansweredQuestion
tagged with: network-programming
has comment: http://stackoverflow.com/comment/82931874
type: Question
downvote count: 2
tagged with: mininet
score: -2
favorite count: 0
has answer: http://stackoverflow.com/a/47981851
answer count: 1
has body: #!/usr/bin/python from mininet.topo import Topo from mininet.net import Mininet from mininet.link import Link from mininet.log import setLogLevel, info from mininet.cli import CLI class myNetwork(Topo): "three users connected to cloud" def build(self, **_opts): #create switch s1 = \ [ self.addSwitch for s in 's1' ] #create hosts h1, h2, h3 = \ [ self.addHosts for h in 'h1', 'h2', 'h3' ] #create links [for h,s in [(h1,s1), (h2,s1), (h3,s1)]: self.addLink(h,s) def run(): topo = myNetwork() net = Mininet(topo=topo) net.start() CLI(net) net.stop() if __name__=='__main__': setLogLevel('info') run() When I try to run my python script in mininet, I get the error: Unhashable type: 'list' I tried to research this, and I understand what the error means but I'm not sure why exactly I'm getting this error when I run my python script.
tagged with: python
upvote count: 0

http://stackoverflow.com/comment/82973380
type: Comment
comment on: http://stackoverflow.com/q/48002016
has text: I'm voting to close this question as off-topic because it belongs on https://codere iew.stackexchange.com
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82836951
type: Comment
has text: i got this using the code: AttributeError: 'DataFrame' object has no attribute 'to_datetime'
comment on: http://stackoverflow.com/a/47933731
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82776641
comment on: http://stackoverflow.com/q/47904508
type: Comment
type: QuestionComment
score: 0
has text: I don't understand. You want to use a newer version of sklearn within the code of an older version of sklearn?

http://stackoverflow.com/comment/82848348
type: AnswerComment
has text: On LInux, can you adjust accordingly(this answer is for windows)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47939576

http://stackoverflow.com/a/70979967
score: 2
answers question: http://stackoverflow.com/q/47879608
upvote count: 2
has body: cdlane has an awesome idea here of using ontimer and a set of currently-pressed keys, but I thought I'd try to extend and refine it a bit. The problem with a secondary loop with ontimer is that it seems to fight the main turtle loop, both in terms of computation and also in terms of thread safety/interleaving, where you can begin iterating the key pressed set and find that a handler has pulled a key out during iteration, raising an error. The (seemingly poorly-named) tracer(0) function lets you disable turtle's loop so you can call it manually from within the hand-rolled ontimer loop using update(). This reduces some of the choppiness of the competing loops, although I imagine the timer resolution on rolling your own loop with repeated calls to ontimer is less precise than the built-in loop. But I haven't really looked at the source yet -- feel free to leave a comment if you have any insight. Here's the proof of concept: from turtle import Screen, Turtle def tick(): for action in list(keys_pressed): actions[action]() win.update() win.ontimer(tick, frame_delay_ms) t = Turtle() win = Screen() win.tracer(0) frame_delay_ms = 1000 // 30 step_speed = 10 actions = dict( Left=lambda: t.left(step_speed), Right=lambda: t.right(step_speed), Up=lambda: t.forward(step_speed), ) keys_pressed = set() def bind(key): win.onkeypress(lambda: keys_pressed.add(key), key) win.onkeyrelease(lambda: keys_pressed.remove(key), key) for key in actions: bind(key) win.listen() tick() win.exitonclick() Ultimately, though, if you want to go much further into realtime graphics and games, Pygame is better equipped. cdlane has a few good posts on tracer: 1, 2, 3.
downvote count: 0
type: Answer

http://stackoverflow.com/comment/82867720
score: 0
type: Comment
has text: I see your point people path if I don't need the power of regex else re_path.
comment on: http://stackoverflow.com/a/47944941
type: AnswerComment

http://stackoverflow.com/a/47891789
has body: You can try this: l = [('name:john','age:25','location:brazil'),('person:terry','age:32','location:acme')] people = [{c:d for c, d in [i.split(':') for i in a]} for a in l] Output: [{'name': 'john', 'age': '25', 'location': 'brazil'}, {'person': 'terry', 'age': '32', 'location': 'acme'}]
has comment: http://stackoverflow.com/comment/82750068
answers question: http://stackoverflow.com/q/47891699
score: 0
type: Answer

http://stackoverflow.com/q/47979438
tagged with: plc
upvote count: 3
tagged with: siemens
type: Question
accepted answer: http://stackoverflow.com/a/47979493
possible better answer: http://stackoverflow.com/a/48383015
score: 3
has answer: http://stackoverflow.com/a/48383015
has title: S7-1200, Snap7: Exception: CLI : function refused by CPU (Unknown error)
answer count: 2
has body: Running below snap7 client script for python using Siemens S7-1200 PLC shows the below common CLI refusal error. What is here the common problem and how to solve it? Script: import snap7 from snap7.util import * import struct import snap7.client from snap7.snap7types import S7AreaDB plc=snap7.client.Client() plc.connect('192.168.0.69',0,1) area = 0x84 start = 0 length = 1 bit = 0 byte= plc.read_area(area,0,start,length) Traceback error: No handlers could be found for logger "snap7.common" Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.7/dist-packages/snap7/client.py", line 242, in read_area check_error(result, context="client") File "/usr/local/lib/python2.7/dist-packages/snap7/common.py", line 69, in check_error raise Snap7Exception(error) snap7.snap7exceptions.Snap7Exception: CLI : function refused by CPU (Unknown error)
tagged with: tia-portal
downvote count: 0
tagged with: s7-1200
favorite count: 0
has answer: http://stackoverflow.com/a/47979493
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/82911820
comment on: http://stackoverflow.com/q/47970683
score: 0
type: Comment
type: QuestionComment
has text: @CrazyIvan oh, that was another mistake, you answered correctly, but I did not ask the question I intended. Sorry about that. (I have revised the question; the for loop is still the same one that should be vectorized).

http://stackoverflow.com/a/47955306
upvote count: 9
has body: From the PEP specification: A class decorator is provided which inspects a class definition for variables with type annotations as defined in PEP 526, "Syntax for Variable Annotations". In this document, such variables are called fields. Using these fields, the decorator adds generated method definitions to the class to support instance initialization, a repr, comparison methods, and optionally other methods as described in the Specification section. Such a class is called a Data Class, but there's really nothing special about the class: the decorator adds generated methods to the class and returns the same class it was given. The @dataclass generator adds methods to the class that you'd otherwise have to define yourself like __repr__, __init__, __lt__, and __gt__.
type: Answer
score: 8
downvote count: 1
answers question: http://stackoverflow.com/q/47955263

http://stackoverflow.com/q/47857428
has comment: http://stackoverflow.com/comment/82680046
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/json
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/82679232
has body: Try to solve example given in this link But It give error. Parsing values from a JSON file? a.json { "maps": [ { "id": "blabla", "iscategorical": "0" }, { "id": "blabla", "iscategorical": "0" } ], "masks": { "id": "valore" }, "om_points": "value", "parameters": { "id": "valore" } } Python file import json from pprint import pprint data = json.load(open('a.json')) pprint(data) ERRORS data = json.load(open('a.json')) File "C:\Users\Almaas\AppData\Local\Programs\Python\Python36-32\lib\json\__init__.py", line 299, in load parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw) File "C:\Users\Almaas\AppData\Local\Programs\Python\Python36-32\lib\json\__init__.py", line 354, in loads return _default_decoder.decode(s) File "C:\Users\Almaas\AppData\Local\Programs\Python\Python36-32\lib\json\decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\Almaas\AppData\Local\Programs\Python\Python36-32\lib\json\decoder.py", line 355, in raw_decode obj, end = self.scan_once(s, idx) json.decoder.JSONDecodeError: Expecting ',' delimiter: line 2 column 1 (char 740)
has comment: http://stackoverflow.com/comment/82679185
has title: Issue in JSON load in python
linked to: http://stackoverflow.com/q/2835559
score: 0
favorite count: 0

http://stackoverflow.com/comment/82962635
comment on: http://stackoverflow.com/q/47996637
has text: I guess I know why. Are you writing `curl ...` right after the flask log? If you run `curl` in a new terminal tab/window, I think it will be fine.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47989670
has answer: http://stackoverflow.com/a/47989771
score: -4
has answer: http://stackoverflow.com/a/47989823
tagged with: python
has title: What is wrong with this while loop code in python?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82947876
has comment: http://stackoverflow.com/comment/82947957
has answer: http://stackoverflow.com/a/47989709
accepted answer: http://stackoverflow.com/a/47989709
tagged with: loops
has comment: http://stackoverflow.com/comment/82947799
has answer: http://stackoverflow.com/a/47990704
type: Question
possible better answer: http://stackoverflow.com/a/47989770
tagged with: infinite-loop
has answer: http://stackoverflow.com/a/47989770
has answer: http://stackoverflow.com/a/47989943
answer count: 6
has comment: http://stackoverflow.com/comment/82948002
tagged with: while-loop
has body: def nearest_square(limit): key=0 while key&lt;=limit: i=0 key=i*i i+=1 return key test1 = nearest_square(40) print("expected result: 36, actual result: {}".format(test1)) will this loop be running for infinite time?
has comment: http://stackoverflow.com/comment/82947967
downvote count: 4
favorite count: 0
upvote count: 0
has comment: http://stackoverflow.com/comment/82947889

http://stackoverflow.com/comment/82894348
has text: If it works for you, and if the only thing you did differently from the question is the way you initialised you `grocery_history`, then it follows that the issue lies with the initialisation of that data structure. Writing an answer proclaiming that OP's code works, rather than getting to the root cause, isn't helping OP.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47962557

http://stackoverflow.com/comment/82820471
has text: Yet another dupe. Sir you taught me this answer long ago.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47926342
type: AnswerComment

http://stackoverflow.com/comment/82919727
comment on: http://stackoverflow.com/q/47973355
has text: Wait, are you using `python manage.py runserver` in production?
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/a/47923312
type: Answer
answers question: http://stackoverflow.com/q/47923233
has body: You can replace all instances of newline followed by space by newline: puzzle = puzzle.replace('\n ','')
score: 0

http://stackoverflow.com/q/47984251
tagged with: tkinter
upvote count: 1
has comment: http://stackoverflow.com/comment/82937789
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82938106
has comment: http://stackoverflow.com/comment/82937802
score: 1
has answer: http://stackoverflow.com/a/47984929
has title: tkinter canvas not opening when while loop is used
has comment: http://stackoverflow.com/comment/82937688
has comment: http://stackoverflow.com/comment/82937757
type: Question
has comment: http://stackoverflow.com/comment/82949247
accepted answer: http://stackoverflow.com/a/47984929
answer count: 1
tagged with: tkinter-canvas
downvote count: 0
has body: I was experimenting with tkinter and was using the following code as a tester: import keyboard from time import sleep from tkinter import * tk = Tk() canvas = Canvas(tk, width=400, height=400) canvas.pack() a = 0 if keyboard.is_pressed('q'): a = 1 if a == 1: canvas.create_line(0,0,400,400) tk.mainloop() No canvas appears when I run this code. I have tried using a debug message instead of creating a line, as well as shifting "tk.mainloop" but the canvas does not show up. However, when I do not use a while loop but a for loop the canvas appears. The program that I plan on making needs an infinite loop. Is there a way to do this in a way that works with tkinter? Thanks in advance and my apologies for a question that is probably down to some simple error of mine.
tagged with: python
favorite count: 0

http://stackoverflow.com/q/47873305
tagged with: wordsearch
type: Question
has answer: http://stackoverflow.com/a/47875987
accepted answer: http://stackoverflow.com/a/47875987
answer count: 1
score: 0
tagged with: string
has title: Word Searcher from Words.list
tagged with: python
type: AnsweredQuestion
tagged with: list
has body: I was helping my mom with this word search app earlier while taking a break from some python tutorials and I realized -- what a perfect example of something interesting for me to work on/learn from. Here's what I came up with, and while it works, I have to do some extra steps to figure out the words. It seems that my double characters don't register as two, and one of them gets replaced with a non-relevant letter. I've tried a lot of different things -- popping, removing. for character in words and not in myletters (to subtract out the difference). A lot of what I found involving this stuff were grids, and directionals, but I'm really just interested in a split list of words from my character input. Any help is appreciated. Sidenote - I am very new to coding, so idk if this was the appropriate route. This x was x * 10 simpler than any example I could find. (Maybe why it doesn't work the way I want it to? ;p) wordlist = open("PossibleWords.txt", "r").read().split() myletters = input("Letters?: ").lower() s = list() sorted = str(myletters) for word in wordlist: if len(word) == len(myletters) and all(letter in word for letter in sorted): s.append(word) for length in s[:100]: print(length)
has comment: http://stackoverflow.com/comment/82712208

http://stackoverflow.com/comment/82806501
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47918665
has text: `from 32Bit import 64Bit as tk` always `tk is None` [here](https://stackoverflow.com/questions/8724729/importerror-dll-load-failed-importing-tkinter)

http://stackoverflow.com/comment/82815829
has text: would writing as a png instead of a jpg do this?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47923884

http://stackoverflow.com/comment/82826543
type: QuestionComment
comment on: http://stackoverflow.com/q/47928839
has text: @GrantGarrison Oh ok then if an answer can provide a way to implement a so called 'hill climbing' algorithm, that will be enough for me, thanks!
score: 0
type: Comment

http://stackoverflow.com/q/47971291
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82912146
type: Question
has comment: http://stackoverflow.com/comment/82912168
upvote count: 2
has comment: http://stackoverflow.com/comment/82912941
answer count: 1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/55749837
has body: I'm trying to port a Python2 script (which works perfectly) to Python3, but I have a problem. This is my code: def encode_script(duck_text, duck_lang, bunny=None): lang_dir = os.path.join(os.path.dirname(__file__), 'languages') language_dict = os.path.join(lang_dir, '{0}.json'.format(duck_lang)) lang_file = json.load(open(language_dict)) encoded_file = parse_text(duck_text, lang_file, bunny) if encoded_file and not bunny: if 'Not in Language' in encoded_file: return encoded_file else: try: encoded_file = "".join(encoded_file) duck_blob = io.StringIO() duck_blob.write(encoded_file.decode('hex')) duck_bin = duck_blob.getvalue() duck_blob.close() return duck_bin except Exception as e: print ("Error creating inject.bin: {0}".format(e)) return False and this is the error: D:\encdec\Encoders-decoders\DuckToolkit-master&gt;python ducktools.py -e -l us test.txt ducky.bin [+] Reading Input file. [-] Encoding File Traceback (most recent call last): File "ducktools.py", line 58, in &lt;module&gt; duck_bin = encoder.encode_script(duck_text, language) File "D:\encdec\Encoders-decoders\DuckToolkit-master\ducktoolkit\encoder.py", line 160, in encode_script encoded_file = parse_text(duck_text, lang_file, bunny).decode() File "D:\encdec\Encoders-decoders\DuckToolkit-master\ducktoolkit\encoder.py", line 24, in parse_text duck_text = duck_text.replace("\r", "") TypeError: expected bytes, bytearray or buffer compatible object The script works perfect on Python2. What should I do?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82913200
has title: TypeError: expected bytes, bytearray or buffer compatible object

http://stackoverflow.com/comment/82804798
comment on: http://stackoverflow.com/q/47918443
score: 0
type: QuestionComment
has text: @briancaffey it returns `statsmodels==0.8.0`
type: Comment

http://stackoverflow.com/a/47871782
downvote count: 0
has body: If you're looking for a way to move the directory, you're already importing shutil. It has a move function which applies to directories as well: https://docs.python.org/3.5/library/shutil.html#shutil.move
has comment: http://stackoverflow.com/comment/82709228
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/82709254
upvote count: 2
answers question: http://stackoverflow.com/q/47871737
has comment: http://stackoverflow.com/comment/82715553
has comment: http://stackoverflow.com/comment/82709062
has comment: http://stackoverflow.com/comment/82708961
has comment: http://stackoverflow.com/comment/82709194

http://stackoverflow.com/a/47871845
downvote count: 0
score: 37
has comment: http://stackoverflow.com/comment/82726133
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47870003
upvote count: 37
answers question: http://stackoverflow.com/q/47870003
type: Answer
has body: You're looking for torch.mv(a,b) Note that for the future, you may also find torch.matmul() useful. torch.matmul() infers the dimensionality of your arguments and accordingly performs either dot products between vectors, matrix-vector or vector-matrix multiplication, matrix multiplication or batch matrix multiplication for higher order tensors.

http://stackoverflow.com/a/58686209
answers question: http://stackoverflow.com/q/47881339
has body: Spent some hours to figure out how to do it with subprocess. So enjoy: import getpass import subprocess sudo_password = getpass.getpass(prompt='sudo password: ') p = subprocess.Popen(['sudo', '-S', 'ls'], stderr=subprocess.PIPE, stdout=subprocess.PIPE, stdin=subprocess.PIPE) try: out, err = p.communicate(input=(sudo_password+'\n').encode(),timeout=5) except subprocess.TimeoutExpired: p.kill()
type: Answer
score: 6
upvote count: 6
downvote count: 0

http://stackoverflow.com/comment/82804651
comment on: http://stackoverflow.com/a/47918371
type: AnswerComment
score: 0
type: Comment
has text: check the data type. In case of any miss match you wont get the desired result

http://stackoverflow.com/comment/82835969
type: Comment
has text: Nevermind, it appears that I need to use another port after all. Thanks for your help, I've accepted your answer.
type: QuestionComment
comment on: http://stackoverflow.com/q/47931241
score: 0

http://stackoverflow.com/q/47963283
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: esky
has answer: http://stackoverflow.com/a/47981989
score: 1
has answer: http://stackoverflow.com/a/52498738
type: Question
answer count: 2
downvote count: 0
has body: I'm trying to create auto-update zip using esky, I was able to create msi but when I try to make the auto-update zip i get an error referring that 'Freezer' object has no attribute 'createLibraryZip' I'm developing this on a Windows 10 machine using python 3.5 from git bash. I created my setup script based on this tutorial https://fernandofreitasalves.com/how-to-create-an-application-with-auto-update-using-python-and-esky/ python setup.py bdist_esky ... copying C:\c\Users\Ezequiel\.virtualenvs\appcon\lib\site-packages\win32\win32wnet.pyd -&gt; dist\appcon-1.1.0.win32\appcon-1.1.0.win32\lib\win32wnet.pyd copying logging.ini -&gt; dist\appcon-1.1.0.win32\appcon-1.1.0.win32 copying config.ini -&gt; dist\appcon-1.1.0.win32\appcon-1.1.0.win32 copying icon.png -&gt; dist\appcon-1.1.0.win32\appcon-1.1.0.win32 Traceback (most recent call last): File "setup.py", line 40, in &lt;module&gt; base=base, File "C:\c\Users\Ezequiel\.virtualenvs\appcon\lib\site-packages\cx_Freeze\dist.py", line 349, in setup distutils.core.setup(**attrs) File "c:\users\ezequiel\appdata\local\programs\python\python35-32\Lib\distutils\core.py", line 148, in setup dist.run_commands() File "c:\users\ezequiel\appdata\local\programs\python\python35-32\Lib\distutils\dist.py", line 955, in run_commands self.run_command(cmd) File "c:\users\ezequiel\appdata\local\programs\python\python35-32\Lib\distutils\dist.py", line 974, in run_command cmd_obj.run() File "C:\c\Users\Ezequiel\.virtualenvs\appcon\lib\site-packages\esky\bdist_esky\__init__.py", line 312, in run self._run() File "C:\c\Users\Ezequiel\.virtualenvs\appcon\lib\site-packages\esky\bdist_esky\__init__.py", line 320, in _run self._run_freeze_scripts() File "C:\c\Users\Ezequiel\.virtualenvs\appcon\lib\site-packages\esky\bdist_esky\__init__.py", line 345, in _run_freeze_scripts self.freezer_module.freeze(self) File "C:\c\Users\Ezequiel\.virtualenvs\appcon\lib\site-packages\esky\bdist_esky\f_cxfreeze.py", line 81, in freeze if f.createLibraryZip: Attribu…
favorite count: 0
tagged with: cx-freeze
has comment: http://stackoverflow.com/comment/126970991
has title: Error making auto-update zip cx_freeze and esky 'Freezer' object has no attribute 'createLibraryZip'
has comment: http://stackoverflow.com/comment/126971098

http://stackoverflow.com/a/47999254
upvote count: 1
answers question: http://stackoverflow.com/q/47998930
score: 1
has body: One thing to realize is that the strings we use when creating symbols have nothing to do with names of those symbols. You can have a = Symbol('b') and now a is a symbol whose string representation is 'b'. In your code, this symbol is referred to as a, not as b. In particular, creating Funct = [Function('m'), Function('n')] and then assigning m = x**2 does nothing for the functions you created: there is no connection between m and Function('m'). Also, SymPy does not really differentiate functions, it differentiates expressions (functions in which something is plugged in). The following creates a double list of derivatives, given expressions and variables: variables = symbols("x y z") expressions = [x**2, y**2, x*y] print([[diff(e, v) for v in variables] for e in expressions]) Output: [[2*x, 0, 0], [0, 2*y, 0], [y, x, 0]]
downvote count: 0
type: Answer

http://stackoverflow.com/comment/82708848
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47871691
has text: @cᴏʟᴅsᴘᴇᴇᴅ Thanks, first one works. Feel free to post as an answer if you want to include some explanation with it.
score: 0

http://stackoverflow.com/comment/82839331
comment on: http://stackoverflow.com/a/47934915
type: AnswerComment
score: 0
type: Comment
has text: I can write scheduled task.But now,I was asked to implement it with bat.

http://stackoverflow.com/comment/82916119
comment on: http://stackoverflow.com/a/47973253
score: 2
type: AnswerComment
type: Comment
has text: In the presence of a JIT all bets are off. You should have put that relevant information in your question in the first place: both that you had tried this and what platform you are using.

cpython
tags question: http://stackoverflow.com/q/47904296
tags question: http://stackoverflow.com/q/47990890
tags question: http://stackoverflow.com/q/47907032
type: Tag
tag name: cpython
tags question: http://stackoverflow.com/q/47990512
tags question: http://stackoverflow.com/q/47898526

http://stackoverflow.com/q/47967809
linked to: http://stackoverflow.com/q/4432208
score: 0
has answer: http://stackoverflow.com/a/47969950
answer count: 3
tagged with: string
has comment: http://stackoverflow.com/comment/82905154
has comment: http://stackoverflow.com/comment/82905577
has answer: http://stackoverflow.com/a/47968765
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82905209
has body: The goal of this program is to encrypt a string. The rule is that every vowel in the string should be swapped to the third vowel after the original. If the vowel is beyond the length, return to the first one and keep counting. As for the consonants, it's similar to the first rule, except that it will be swapped to the second consonant after the original one. If there's a blank space, leave it blank. I've encountered a problem that the string index is out of range, and I can't find where the problem is. Also, is it possible that the program is able to escape the loop automatically after text[x] can no longer find any elements? empty='' UA="AEIOU" UC="BCDFGHJKLMNPQRSTVWXYZ" text=str(input()) Flag=True x=0 while Flag: if ord(text[x])==32: r=' ' empty=empty+r elif 41&lt;=ord(text[x])&lt;=90: if (ord(text[x])==65 and ord(text[x])==69 and ord(text[x])==73 and ord(text[x])==79 and ord(text[x])==85): r=0 while (ord(text[x])!=ord(UA[r])): r=r+1 if r+3&gt;=len(UA): r=r-2 else: r=r+3 empty=empty+UA[r] x=x+1 else: r=0 while (ord(text[x])!=ord(UC[r])): r=r+1 if r+2&gt;=len(UC): r=r-19 else: r=r+2 empty=empty+UC[r] x=x+1 elif ord(text[x])==None: Flag=False print(empty)
type: Question
has title: Python- the index of the string is out of range
has answer: http://stackoverflow.com/a/47968120
has comment: http://stackoverflow.com/comment/82905372

http://stackoverflow.com/comment/82803212
has text: @felixc, I tried this way that will set vars for all hosts(it is useful, thanks). for my case, I only want to set vars for `windows` group.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47902832

http://stackoverflow.com/comment/82764666
comment on: http://stackoverflow.com/a/47898858
score: 1
has text: @sudonym `pandas` objects are typed like `numpy`, they can contain either arrays of primitive types, e.g. `numpy.int64`, or, `dtype=object`, in which case, they can contain *any* python object. Note, that usually comes at the expense of efficiency.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82719911
type: Comment
comment on: http://stackoverflow.com/a/47877002
type: AnswerComment
has text: (Not that you *couldn't* do it in Python... it just seems orthogonal to the problem you're trying to solve.)
score: 0

http://stackoverflow.com/a/47998541
answers question: http://stackoverflow.com/q/47998454
has body: By using str.split + agg df['B']=np.where(df['B'].str.split('-',expand=True)[0]!='1',df['B'].str.split('-',expand=True)[0],df['B']) df.groupby(['index','A','B']).agg({'Count':'sum','Value':'mean'}).reset_index() Out[1628]: index A B Count Value 0 x abc 1-a 1 1 1 x abc 2 3 3 2 x xyz 3 5 1 3 y abc 1-b 1 5 4 y abc 1-c 0 3 5 y ijk 2 1 2 6 y ijk 3 2 1 For your case df.groupby(['index','A','B']).agg(lambda x : x.mean() if x.name.startswith('Value') else x.sum()).reset_index()
accepted answer of: http://stackoverflow.com/q/47998454
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82965589
type: Answer
has comment: http://stackoverflow.com/comment/82965730
score: 2
downvote count: 0

http://stackoverflow.com/a/47880181
answers question: http://stackoverflow.com/q/47879356
score: 3
downvote count: 0
upvote count: 3
has body: Below example produces a Text widget that has elided text in it, using tags: import tkinter as tk root = tk.Tk() text = tk.Text(root) text.pack() text.tag_config('mytag', elide=True) text.insert('end', "This text is non-elided.") text.tag_add('mytag', '1.13', '1.17') def toggle_elision(): # cget returns string "1" or "0" if int(text.tag_cget('mytag', 'elide')): text.tag_config('mytag', elide=False) else: text.tag_config('mytag', elide=True) tk.Button(root, text="Toggle", command=toggle_elision).pack() root.mainloop()
type: Answer

http://stackoverflow.com/comment/82853610
has text: Is there any way i can have this return something other than a bool, like, say, a list of bools?
comment on: http://stackoverflow.com/a/47941814
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47885839
accepted answer: http://stackoverflow.com/a/47885915
has comment: http://stackoverflow.com/comment/82737248
tagged with: python
has body: I have below inputs, inp = 'Sample' n = 5 I would like to generate a list of tuples of n elements packing input with index. So that my output is, [('Sample', 0), ('Sample', 1), ('Sample', 2), ('Sample', 3), ('Sample', 4)] Below snippet does the work neat, output = zip([inp]*n, range(n)) Just curious about alternate approaches to solve the same?
score: 2
type: AnsweredQuestion
tagged with: alternate
has comment: http://stackoverflow.com/comment/82737290
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47885915
possible better answer: http://stackoverflow.com/a/47961444
has title: Alternate ways in place of zip
has answer: http://stackoverflow.com/a/47961444
downvote count: 0
favorite count: 0
tagged with: http://stackoverflow.com/tag/zip
tagged with: tuples
upvote count: 2

http://stackoverflow.com/q/47910458
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/47912354
tagged with: pip
upvote count: 1
has body: I added fork of library (sqlalchemy) and another library (alembic), depended on fork source, to requirements.txt. During installation fork and source have installed. Why does it happens? Can fork be installed as dependency? Here is installation process and its results: ➜ ~ mkdir test_reqs ➜ ~ cd test_reqs ➜ test_reqs echo "alembic==0.9.3 -e git+https://github.com/aCLr/sqlalchemy.git#egg=rel_1_bind_url_as_key" &gt; reqs.txt ➜ test_reqs virtualenv2 venv New python executable in /home/anton/test_reqs/venv/bin/python2 Also creating executable in /home/anton/test_reqs/venv/bin/python Installing setuptools, pip, wheel...done. ➜ test_reqs source venv/bin/activate (venv) ➜ test_reqs pip install -r reqs.txt Collecting alembic==0.9.3 (from -r reqs.txt (line 1)) Obtaining rel_1_bind_url_as_key from git+https://github.com/aCLr/sqlalchemy.git#egg=rel_1_bind_url_as_key (from -r reqs.txt (line 2)) Cloning https://github.com/aCLr/sqlalchemy.git to ./venv/src/rel-1-bind-url-as-key Running setup.py (path:/home/anton/test_reqs/venv/src/rel-1-bind-url-as-key/setup.py) egg_info for package rel-1-bind-url-as-key produced metadata for project name sqlalchemy. Fix your #egg=rel-1-bind-url-as-key fragments. Collecting SQLAlchemy&gt;=0.7.6 (from alembic==0.9.3-&gt;-r reqs.txt (line 1)) Collecting Mako (from alembic==0.9.3-&gt;-r reqs.txt (line 1)) Collecting python-editor&gt;=0.3 (from alembic==0.9.3-&gt;-r reqs.txt (line 1)) Collecting python-dateutil (from alembic==0.9.3-&gt;-r reqs.txt (line 1)) Using cached python_dateutil-2.6.1-py2.py3-none-any.whl Collecting MarkupSafe&gt;=0.9.2 (from Mako-&gt;alembic==0.9.3-&gt;-r reqs.txt (line 1)) Collecting six&gt;=1.5 (from python-dateutil-&gt;alembic==0.9.3-&gt;-r reqs.txt (line 1)) Using cached six-1.11.0-py2.py3-none-any.whl Installing collected packages: SQLAlchemy, MarkupSafe, Mako, python-editor, six, python-dateutil, alembic, sqlalchemy Running setup.py develop for sqlalchemy Successfully installed Mako-1.0.7 MarkupSafe-1.0 SQLAlchemy-1.1.1…
type: Question
accepted answer: http://stackoverflow.com/a/47912354
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
has title: pip install from requirements ignores library fork

http://stackoverflow.com/a/47907515
answers question: http://stackoverflow.com/q/47907268
downvote count: 0
has body: The idea is to dynamically pass to the class creation a pair of attribute name and value, to do that, create a dictionary using the name/value attribute and pass it along using dictionary unpacking: def create_act(user, verb, name, value): attrs = {name: value} action = Action(user=user, verb=verb, **attrs) action.save() return action
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/a/47971408
accepted answer of: http://stackoverflow.com/q/47971275
answers question: http://stackoverflow.com/q/47971275
type: AcceptedAnswer
score: 27
has body: This line of code: item = QTableWidgetItem(scraped_age).setTextAlignment(Qt.AlignHCenter) will not work properly, because it throws away the item it creates before assigning it to the variable. The variable will in fact be set to None, which is the return value of setTextAlignment(). Instead, you must do this: item = QTableWidgetItem(scraped_age) # create the item item.setTextAlignment(Qt.AlignHCenter) # change the alignment
type: Answer
upvote count: 27
has comment: http://stackoverflow.com/comment/116146918
downvote count: 0

http://stackoverflow.com/q/47972594
type: Question
tagged with: plpython
tagged with: python
possible better answer: http://stackoverflow.com/a/47972771
answer count: 2
tagged with: error-handling
upvote count: 1
has answer: http://stackoverflow.com/a/47972771
has body: The qustion's in the (albeit long) title. I have code in this fashion: -- create the tables for models CREATE TABLE invoice( id SERIAL PRIMARY KEY, value VARCHAR(8) CONSTRAINT valid_money CHECK(validate_invoice_money(value)) ); with this procedure: CREATE OR REPLACE FUNCTION validate_invoice_money(test VARCHAR) RETURNS BOOLEAN AS $$ import plpy import re if (re.match("^[0-9]+\\.[0-9]{2}$", test) == None): return False return True $$ LANGUAGE plpython3u IMMUTABLE; (the specifics of this example are not important, I know there's better ways to validate a value than this, such as using the MONEY type.) When an insert is attempted that fails this check, I get the following error: ERROR : new row for relation "invoice" violates check constraint "valid_model" DETAIL : Failing row contains (1, "notvalid"). (the error/detail descriptors are my own code, but a PostgreSQL error has an error and a detail field provided.) Is there any way for me to change the "detail" portion of this error from my Python procedure?
tagged with: stored-procedures
has answer: http://stackoverflow.com/a/47972916
type: AnsweredQuestion
downvote count: 0
has title: In a PostgreSQL CHECK constraint using a boolean stored procedure written in PL/Python, can the detail of the error message be updated?
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/47972916
tagged with: postgresql

http://stackoverflow.com/q/47990553
type: Question
has title: Can't start anaconda-navigator and other: ImportError: /usr/lib/x86_64-linux-gnu/libXxf86vm.so.1: undefined symbol: _XEatDataWords
answer count: 0
type: UnansweredQuestion
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/82975689
has comment: http://stackoverflow.com/comment/82949722
tagged with: anaconda
has body: this is my first question on stackoverflow. Sorry for any customs violations ;) I am running python3.6 on an Ubuntu 16.04 system. Whenever I try to start anaconda-navigator or spyder on the terminal I get the following error: from PyQt5.QtGui import * ImportError: /usr/lib/x86_64-linux-gnu/libXxf86vm.so.1: undefined symbol: _XEatDataWords The same happens when I try to: import matplotlib.pyplot as plt in my python script. I reinstalled anaconda navigator in different versions for different python versions and the ubuntu package libxxf86vm1_1.1.4-1_amd64.deb, but with no success. Ist there someone with experience in this matter? Best regards.
tagged with: matplotlib
tagged with: ubuntu-16.04

http://stackoverflow.com/q/47956327
upvote count: 3
has comment: http://stackoverflow.com/comment/82882206
tagged with: python
has body: I have the following tree: myDjangoSite/ ... myApp/ ... static/ ... myApp/ myData.json And I have this view.py file: import json from django.shortcuts import render from django.contrib.staticfiles.templatetags.staticfiles import static url = static('myApp/myData.json') json_data = open(url) def helloWorld(request): return render(request, 'myApp/index.html') ...and when I access to the webpage, the browsers shows this message: IOError at / [Errno 2] No such file or directory: '/static/myApp/myData.json' I don't understand why it says "no such file or directory", if the file DOES exist and how to solve it.
has comment: http://stackoverflow.com/comment/82882609
downvote count: 0
has answer: http://stackoverflow.com/a/47956376
accepted answer: http://stackoverflow.com/a/47956376
has title: Can't parse a static JSON file in Django 1.8
tagged with: django
type: Question
type: AnsweredQuestion
score: 3
tagged with: django-views
has comment: http://stackoverflow.com/comment/82882698
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/82882177
answer count: 1
has comment: http://stackoverflow.com/comment/82882338
tagged with: django-staticfiles
favorite count: 0

http://stackoverflow.com/comment/82919595
comment on: http://stackoverflow.com/a/47973755
score: 1
type: AnswerComment
has text: keep asking,one day you will :)
type: Comment

http://stackoverflow.com/comment/82910144
comment on: http://stackoverflow.com/q/47970163
type: Comment
has text: did you remove correct `after()` - before `mainloop()`. If you still have problem then maybe you use different code than you show in question - ie. you may have `()` in `command=read_data()`
score: 1
type: QuestionComment

http://stackoverflow.com/q/47982331
downvote count: 0
has answer: http://stackoverflow.com/a/47982648
tagged with: string
has answer: http://stackoverflow.com/a/47982758
tagged with: http://stackoverflow.com/tag/xml
favorite count: 0
has title: Parsing broken XML with numbers as tag names
linked to: http://stackoverflow.com/q/2352840
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/82933564
has body: I have lots of xml files that have keys that are in digit format i.e &lt;12345&gt;Golly&lt;/12345&gt; When parsing using ElementTree I get an error not well-formed (invalid token). I am assuming this because the keys are in digit format and not words. When I try to change/replace the keys into string by adding double quotes using regex xmlstr = re.sub('&lt;([\d]+)&gt;','&lt;"' + str(re.search('&lt;([\d]+)&gt;', xmlstr).group(1))+ '"&gt;',xmlstr) xmlstr = re.sub('&lt;/([\d]+)&gt;','&lt;/"' + str(re.search('&lt;/([\d]+)&gt;', xmlstr).group(1))+ '"&gt;',xmlstr) All other keys are replace using the first found key.(all keys end up being the same. whereas the keys themselves in the original file are unique in each document.) I guess the files were converted from json to xml directly. The keys should represent id number and the values are the names associated with the id number I was wondering if there is a way to work with digits as keys, or if there is a way I can replace the keys one by one and not replacing all matches with one found string. .group(1) returns the first occurrence which causes the problem. Please Help.
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47982648
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/82933226
answer count: 2
tagged with: xml-parsing
possible better answer: http://stackoverflow.com/a/47982758

http://stackoverflow.com/comment/107199576
comment on: http://stackoverflow.com/a/53196099
has text: I also found pandas slow, but for one project I solved it using a different approach. I had the data in multiple files (13 columns), but 1 million rows in total. Instead I used MySQL INFILE with the files stored locally. Calling it from python, using threading. I was able to import 1 million rows in ~20 seconds.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/82732254
has text: If you can compute intersections then you can use [inclusion-exclusion](https://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle)
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47883034

http://stackoverflow.com/a/47937593
downvote count: 0
type: Answer
has body: The reason why the performance differs is because numpy first tends to search for pandas implementation of the function using getattr than doing the same in builtin numpy functions when a pandas object is passed. Its not the numpy over the pandas object that is slow, its the pandas version. When you do np.clip(pd.Series([1,2,3,4,5]),a_min=None,amax=1) _wrapfunc is being called : # Code from source def _wrapfunc(obj, method, *args, **kwds): try: return getattr(obj, method)(*args, **kwds) Due to _wrapfunc's getattr method : getattr(pd.Series([1,2,3,4,5]),'clip')(None, 1) # Equivalent to `pd.Series([1,2,3,4,5]).clip(lower=None,upper=1)` # 0 1 # 1 1 # 2 1 # 3 1 # 4 1 # dtype: int64 If you go through the pandas implementation there is a lot of pre checking work that is done. Its the reason why the functions which has the pandas implementation done via numpy has such difference in speed. Not only clip, functions like cumsum,cumprod,reshape,searchsorted,transpose and much more uses pandas version of them than numpy when you pass them a pandas object. It might appear numpy is doing the work over those objects but under the hood its the pandas function.
score: 5
answers question: http://stackoverflow.com/q/47893677
upvote count: 5

http://stackoverflow.com/comment/82707792
type: QuestionComment
has text: I'm not sure I understand. In your example you would use `mat_bigger[bs_[off_min:off_max]] = ...`
comment on: http://stackoverflow.com/q/47870663
score: 0
type: Comment

http://stackoverflow.com/a/47942104
downvote count: 0
answers question: http://stackoverflow.com/q/47940331
has comment: http://stackoverflow.com/comment/82871936
type: Answer
accepted answer of: http://stackoverflow.com/q/47940331
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/82865807
has body: Q1: I think it is not necessary to first make an np.array and then create the dataframe. This works perfectly fine, for example: rd = lambda: datetime.date(randint(2005,2025), randint(1,12),randint(1,28)) df = pd.DataFrame([(rd(), rd()) for x in range(100)]) Added later: df = pd.DataFrame((x.value() for x in listOfThings), index=(pd.to_datetime(x.time()) for x in listOfThings)) Q2: I noticed that pd.to_datetime('some date') almost always gets it right. Even without specifying the format. Perhaps this helps. In [115]: pd.to_datetime('2008-09-22T13:57:31.2311892-04:00') Out[115]: Timestamp('2008-09-22 17:57:31.231189200')
type: AcceptedAnswer

http://stackoverflow.com/comment/109747624
comment on: http://stackoverflow.com/q/47878893
type: QuestionComment
type: Comment
has text: @Michael-sqlbot Is that feature limitation still the case 3 years later? I also would like to search through keys, but my string of interest is in the middle, not the end.
score: 0

conda
tags question: http://stackoverflow.com/q/47915166
tags question: http://stackoverflow.com/q/47934881
tags question: http://stackoverflow.com/q/47928898
tags question: http://stackoverflow.com/q/47897270
tags question: http://stackoverflow.com/q/48012811
tags question: http://stackoverflow.com/q/48000496
tags question: http://stackoverflow.com/q/47909851
tag name: conda
tags question: http://stackoverflow.com/q/47955200
tags question: http://stackoverflow.com/q/47898252
tags question: http://stackoverflow.com/q/47996247
tags question: http://stackoverflow.com/q/47861087
type: Tag
tags question: http://stackoverflow.com/q/48003486
tags question: http://stackoverflow.com/q/47943081
tags question: http://stackoverflow.com/q/48009091

http://stackoverflow.com/a/47998793
score: 2
answers question: http://stackoverflow.com/q/47982858
upvote count: 2
has body: Since it's not completely clear what Image.save() does in this context, could you try doing it this way? def get_image(request): image_data = open('oh_noes_cat.png', mode='r').read() return HttpResponse(image_data, content_type="image/png")
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47982858
type: Answer

http://stackoverflow.com/tag/xml
tags question: http://stackoverflow.com/q/47892790
tags question: http://stackoverflow.com/q/48001711
tags question: http://stackoverflow.com/q/47929216
tags question: http://stackoverflow.com/q/47922657
tags question: http://stackoverflow.com/q/48009547
type: Tag
tags question: http://stackoverflow.com/q/47993061
tags question: http://stackoverflow.com/q/47963080
tags question: http://stackoverflow.com/q/47893915
tags question: http://stackoverflow.com/q/47984543
tags question: http://stackoverflow.com/q/47986569
tags question: http://stackoverflow.com/q/47876577
tags question: http://stackoverflow.com/q/47883390
tags question: http://stackoverflow.com/q/47996099
tags question: http://stackoverflow.com/q/47889929
tags question: http://stackoverflow.com/q/47891089
tags question: http://stackoverflow.com/q/47917787
tags question: http://stackoverflow.com/q/47856050
tags question: http://stackoverflow.com/q/47906792
tags question: http://stackoverflow.com/q/47884348
tags question: http://stackoverflow.com/q/47982331
tag name: xml
tags question: http://stackoverflow.com/q/47998961
tags question: http://stackoverflow.com/q/47885730
tags question: http://stackoverflow.com/q/47938834
tags question: http://stackoverflow.com/q/47970378
tags question: http://stackoverflow.com/q/47935300
tags question: http://stackoverflow.com/q/47910644
tags question: http://stackoverflow.com/q/47874196
tags question: http://stackoverflow.com/q/47910752
tags question: http://stackoverflow.com/q/47936003
tags question: http://stackoverflow.com/q/48011386
tags question: http://stackoverflow.com/q/48007230
tags question: http://stackoverflow.com/q/47919194
tags question: http://stackoverflow.com/q/47943619
tags question: http://stackoverflow.com/q/47989270
tags question: http://stackoverflow.com/q/47938134
tags question: http://stackoverflow.com/q/47888784

http://stackoverflow.com/q/47901931
has answer: http://stackoverflow.com/a/47902048
tagged with: python
tagged with: match
has answer: http://stackoverflow.com/a/47902010
type: AnsweredQuestion
has title: Python DataFrame: replacing values from DataFrame to other DataFrame with same index and columns
has body: I have two dataframes. "df" is my original dataframe with 100000+ values and "df_result" is another that contains only certain columns with certain indexes of df. I have changed the values in "df_result" columns and want to apply back to my original dataframe "df". I have mapped the column names and index of "df_index" to match the right index of "df" but it does not contain every index of "df". (ex, df.index() output is [0,1,2,.....,92808,92809] and df_result.index() output is [23429,23430,32349,42099,45232,.....,91324,91423]). Is there efficient way to put every value in "df_result" to the original "df" which is corespond to same index and columns?. Thank you!
type: Question
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/47902010
accepted answer: http://stackoverflow.com/a/47902048
tagged with: replace
score: 0
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/82770552

http://stackoverflow.com/q/47987550
answer count: 1
has body: I am using scrapy to parse a table containing links and save it in json. The links from table contain additional detail and they will be fetched and stored into another json. (following this example: https://docs.scrapy.org/en/latest/topics/exporters.html) To achieve this I am using a pipeline to check item type and store result in appropriate json. However, I am stuck in some weird error. Please refer below: from scrapy import signals from scrapy.exporters import JsonItemExporter from for_icu import items class ListPipeline(object): def __init__(self): self.files = {} @classmethod def from_crawler(cls, crawler): pipeline = cls() crawler.signals.connect(pipeline.spider_opened, signals.spider_opened) crawler.signals.connect(pipeline.spider_closed, signals.spider_closed) return pipeline def spider_opened(self, spider): print("spider_opened") file_table = open('%s_table.json' % spider.name, 'w+b') self.files[spider].append(file_table) self.exporter1 = JsonItemExporter(file_table) self.exporter1.start_exporting() file_detail = open('%s_detail.json' % spider.name, 'w+b') self.files[spider].append(file_detail) self.exporter2 = JsonItemExporter(file_detail) self.exporter2.start_exporting() def spider_closed(self, spider): print("spider_closed") self.exporter1.finish_exporting() self.exporter2.finish_exporting() for file in self.files.pop(spider): file.close() def process_item(self, item, spider): print("process_item") if isinstance(item, items.UniListItem): self.exporter1.export_item(item) return item elif isinstance(item, items.UniDetail): self.exporter22.export_item(item) return item Error: 2017-12-27 11:41:15 [scrapy.core.scraper] ERROR: Error processing {'country': ('Finland',), 'country_code': ('fi ',), 'u_link': ('http://www.xxxxxxx.xxx/xxxxxxx/xxxx.htm',), 'u': (' pisto',)} Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/twisted/internet/defer.py", line 653, in _runCallbacks current.result = callback(current.result, *args, **kw) File …
has answer: http://stackoverflow.com/a/47989367
has comment: http://stackoverflow.com/comment/82951766
has title: scrapy pipeline exporter object is not getting instantiated
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82945008
has comment: http://stackoverflow.com/comment/82944087
has comment: http://stackoverflow.com/comment/82945503
tagged with: http://stackoverflow.com/tag/json
tagged with: scrapy
has comment: http://stackoverflow.com/comment/82945795
type: Question
has comment: http://stackoverflow.com/comment/82944366
score: 0
has comment: http://stackoverflow.com/comment/82945185

http://stackoverflow.com/a/47900171
answers question: http://stackoverflow.com/q/47897434
downvote count: 0
has comment: http://stackoverflow.com/comment/82793748
has comment: http://stackoverflow.com/comment/82793803
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/82796672
score: 1
has body: To print the element texts TEXT, Active: and GAME you can use the following code blocks : To print TEXT : print(b.find_element_by_xpath("//div[@class='details']//span[@class='bold']").get_attribute("innerHTML")) To print Active: : fullsting = b.find_element_by_xpath("//div[@class='details']").get_attribute("innerHTML") part_word = fullsting.split(")") words = part_word[1].split("G") print(words[0]) To print GAME : print(b.find_element_by_xpath("//div[@class='details']//a[@class='game']").get_attribute("innerHTML"))
has comment: http://stackoverflow.com/comment/91621192

http://stackoverflow.com/comment/82774766
comment on: http://stackoverflow.com/a/47903922
has text: you don't need to change url config, just go by old way to list with prefix
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/82700925
type: AnswerComment
score: 0
type: Comment
has text: how will save multiple choice in single field like postgres array and i need to save correct answer also
comment on: http://stackoverflow.com/a/47867939

http://stackoverflow.com/a/76555293
has body: This happened to me once when I copied the file via save as. As soon as I deleted the second file, the problem resolved itself.
answers question: http://stackoverflow.com/q/47857141
score: 0
type: Answer

http://stackoverflow.com/comment/82678506
comment on: http://stackoverflow.com/q/47857141
score: 4
has text: Do you have another file named `cv2.py`?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83088895
type: Comment
has text: I have edited the question.. Please check.. If yu could help me out
type: QuestionComment
comment on: http://stackoverflow.com/q/48004556
score: 0

http://stackoverflow.com/comment/82694227
type: QuestionComment
comment on: http://stackoverflow.com/q/47864053
score: 0
has text: @tripleee That makes sense, because the IPv4 object have many property for imitate IPv6 object.
type: Comment

http://stackoverflow.com/a/48007208
type: Answer
has body: One thing to mention is that pylint currently has limited capabilities for type-checking, as those seen in mypy. It relies more on inferring values and types without type hints, although the intent is to have support for PEP-484 typing at some point. Now regarding the question, I see that you are using a module extender, while in fact you should use a class transform, as in: astroid.MANAGER.register_transform(astroid.ClassDef, _class_transform, optional_transform_predicate)
score: 0
answers question: http://stackoverflow.com/q/47988540

http://stackoverflow.com/q/47953638
favorite count: 0
has comment: http://stackoverflow.com/comment/82877156
type: Question
tagged with: python
has title: Button Click Event on IronPython + Wpf
tagged with: wpf
tagged with: visual-studio
accepted answer: http://stackoverflow.com/a/47953695
has comment: http://stackoverflow.com/comment/82876958
has body: Im new to python and VS and im trying to make a simple GUI with a button. Once I click the button I want it to print(5). The code looks as following but when I click "run" it exits without any action: import wpf from System.Windows import Application, Window class MyWindow(Window): def __init__(self): wpf.LoadComponent(self, 'WpfApplication1.xaml') BUTTON.Click += self.Button_Click print(5) def Button_Click(self, sender, e): pass if __name__ == '__main__': Application().Run(MyWindow()) XAML: Thank you.
upvote count: 1
tagged with: ironpython
answer count: 1
has comment: http://stackoverflow.com/comment/82878568
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47953695
downvote count: 0
score: 1

http://stackoverflow.com/q/47989368
type: UnansweredQuestion
has body: I have a dataset of eye gluacoma with predefined ground truths of optic disc and optic cup, but the image size in the dataset is way too large, they are around 2045x1752 so the GT cordinates are also as per that cordinate ratio, but am looking to resize the image to lower aspect ratio say 450x400, and relocate the GT cordinates according to a new aspect ratio, but am bit confused with that, so any approch towards this problem would be appreciated. Note: Here the GT cordinates are in seperate csv file, it's not already labled in the dataset image itself.
tagged with: python
tagged with: opencv
answer count: 0
score: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82947981
has comment: http://stackoverflow.com/comment/82948200
has title: Opencv map predefined GT cordinates to different aspect ratio

http://stackoverflow.com/comment/82750612
has text: how about [pygame.mixer.music.stop](http://pygame.org/docs/ref/music.html#pygame.mixer.music.stop), [pygame.mixer.stop](http://pygame.org/docs/ref/mixer.html#pygame.mixer.stop) and [pygame.mixer.quit](http://pygame.org/docs/ref/mixer.html#pygame.mixer.quit)
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47888545
type: Comment

http://stackoverflow.com/a/47971435
has comment: http://stackoverflow.com/comment/84444341
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/47971334
answers question: http://stackoverflow.com/q/47971334
has comment: http://stackoverflow.com/comment/82912457
upvote count: 1
type: AcceptedAnswer
has body: It is telling you that chromedriver.exe doesn't have the executable bit set. But I don't think that matters since you are trying to run a Windows program (.exe) on an Linux machine which is what Heroku is.
type: Answer
has comment: http://stackoverflow.com/comment/82912380

http://stackoverflow.com/q/47903241
upvote count: 2
downvote count: 2
accepted answer: http://stackoverflow.com/a/47903382
type: Question
has body: Have array of dictionaries: a = [{'id': 1, 'k': 1}, {'id': 2, 'k': 2}, {'id': 3, 'k': 3}] How to return value of id key and value of k if any k matches condition? Trying like: return [i['id'], i['k'] if any(i['k'] == 2 for i in a) else fail('fail')]
possible better answer: http://stackoverflow.com/a/47903429
has answer: http://stackoverflow.com/a/47903429
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/82773278
has answer: http://stackoverflow.com/a/47903382
has title: Return multiple values from list comprehension if any value matches condition
favorite count: 0
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/47884601
has comment: http://stackoverflow.com/comment/82734934
has comment: http://stackoverflow.com/comment/82735967
tagged with: django-rest-framework
tagged with: postman
has body: I am using Django Restframework for apis. I am working on a POST api where I need to send an array of objects in form-data. When I tried it in raw data it is working perfectly. But when I use form-data in postman and placing the value in array, It is causing problem. The key value pair i am using in raw data is { "services": [ { "category_image": "", "category_name": "construction", "budget_min": "0-1000", "budget_max": "0-1000", "distance_min": "200", "distance_max": "500", "projects": [ { "category_image": "", "category_name": "residential", "sub_category": [ { "project_name": "single family", "project_image": "", "parent_id": "1" }, { "project_name": "multi family", "project_image": "", "parent_id": "1" }, { "project_name": "big family", "project_image": "", "parent_id": "1" } ] }, { "category_image": "", "category_name": "hospitality", "sub_category": [ { "project_name": "health care", "project_image": "", "parent_id": "5" }, { "project_name": "hotels", "project_image": "", "parent_id": "5" } ] } ], "sub_category": [ { "service_name": "wall", "service_image": "", "parent_id": "1" }, { "service_name": "kitchen", "service_image": "", "parent_id": "1" }, { "service_name": "outdoor", "service_image": "", "parent_id": "1" } ] }, { "category_image": "", "category_name": "driving", "sub_category": [ { "service_name": "car", "service_image": "", "parent_id": "5" }, { "service_name": "bike", "service_image": "", "parent_id": "5" } ] } ] } In form-data I am using services as the key and the array as value. My code to retrieve value is : data = request.data.get['services'] While using raw data i am getting it properly but not in form-data. I printed the request , it is coming perfect in raw data but in form-data it takes everything inside a string . The response looks like - "[\n {\n \"min_price\":\"5\",\n \"max_price\":\"50\",\n \"category_image\":\"\",\n \"service_name\":\"plumb\",\n \"projects\":[\n {\n \"category_image\":\"\",\n \"project_name\":\"personal\",\n \"sub_c…
has title: Posting array of objects in request in form-data in django api
score: 0
has comment: http://stackoverflow.com/comment/82735640
has comment: http://stackoverflow.com/comment/82735715
has comment: http://stackoverflow.com/comment/82736526
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82734883
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82736679
type: Question

http://stackoverflow.com/q/47953973
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82879007
has answer: http://stackoverflow.com/a/47955904
tagged with: django
upvote count: 1
tagged with: python
has title: Django: how to send form data from one page to the next?
has comment: http://stackoverflow.com/comment/82880264
score: 1
tagged with: django-forms
type: Question
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82878315
favorite count: 0
has comment: http://stackoverflow.com/comment/82877811
has body: The basic problem is that I can not find out a way of taking the form data to pass on to the next page? Extra information: I read somewhere that I should use session, which seems sensible, however, serialization appears not to work with forms without a model, however, I could be wrong. When I click submit the error is AttributeError: 'BoundField' object has no attribute '_meta'. Form class ItemCounterForm(Form): item = CharField(max_length=30) counter = IntegerFeild(min_value=1, max_value=1000) def __init__(self, *args, **kwargs): super(ItemCounterForm, self).__init__(*args, **kwargs) View class ItemCounterView(View): FormSet = formset_factory(ItemCounterForm) def get(self, request, *args, **kwargs): context = { 'form': self.FormSet() } return render(request, 'app:template', context) def post(self, request, *args, **kwargs): form = self.FormSet(self.request.POST or None) if form.is_valid(): for single_form in form: data_form = serializers.serialize('json', single_form) request.session['form'] = data_form return HttpResponseRedirect(reverse_lazy('app:next_page')) else: context = { 'form': self.FormSet() } return render(request, 'app:template', context) Thank you for your time.

http://stackoverflow.com/a/47881354
downvote count: 0
type: Answer
has body: A loc based solution - i = df1.set_index('id') j = df2.set_index('id') i.loc[j.index, 'value'] = j['value'] df2 = i.reset_index() df2 id value 0 1 100 1 2 50 2 3 100 3 4 100 4 5 30
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47881124

http://stackoverflow.com/comment/82725417
has text: This is a great answer.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47879432
type: AnswerComment

http://stackoverflow.com/q/47970686
has comment: http://stackoverflow.com/comment/82911015
has comment: http://stackoverflow.com/comment/82910929
type: UnansweredQuestion
tagged with: python
has body: please help to find the issue with cookies. Angular is getting needed data and looks like everything is working, but if I adding needed for Angular fields (Access-Control-Allow-Origin and Access-Control-Allow-Headers) the cookies is stopping work and browser is not saving them.. why? HTTP response is generating by my Python server with the next text (ex) : HTTP/1.1 200 OK Content-Type: application/json Set-Cookie: session=127578629; Domain=host1.com; expires=Mon, 25-Dec-2017 17:41:16 GMT Access-Control-Allow-Origin: * Access-Control-Allow-Methods: POST, GET, OPTIONS Access-Control-Allow-Headers: Content-Type, * Access-Control-Allow-Credentials: true "{logged:True}" And Angular correctly gets this json also... Thank you everyone for any tips... because i'm out of ideas... P.S. Without CORS fields cookies is working wel... Angular code (if required) : @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { public apiURL:string = 'http://host1.com:9999/'; public logged: boolean; response: any; constructor(private elementRef:ElementRef, private http:Http) { this.logged = this.elementRef.nativeElement.getAttribute('auth'); } ngOnInit() { this.checkLogin() } checkLogin() { this.response = this.http.post(this.apiURL, {"search": "search"}).map(res =&gt; res.json()).subscribe(data =&gt; {console.log(data);}); } }
has title: Trouble with saving of cookies with CORS fields on response
answer count: 0
tagged with: cookies
tagged with: angular5
has comment: http://stackoverflow.com/comment/82910904
type: Question
has comment: http://stackoverflow.com/comment/82911036
tagged with: javascript
has comment: http://stackoverflow.com/comment/82911094
score: 0

http://stackoverflow.com/a/47978931
answers question: http://stackoverflow.com/q/47974846
score: 4
type: AcceptedAnswer
type: Answer
has body: The issue here is that b64encode returns bytes, but those can be easily converted to a proper unicode string. It won't make a difference with your server. &gt;&gt;&gt; b64 = base64.b64encode(b'...') &gt;&gt;&gt; type(b64) &lt;class 'bytes'&gt; &gt;&gt;&gt; b64 = base64.b64encode(b'...').decode('utf8') &gt;&gt;&gt; type(b64) &lt;class 'str'&gt;
upvote count: 4
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47974846

http://stackoverflow.com/comment/82944996
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47987741
has text: `number of months in the latest service is >= 3` You mean `== 3`? Because almost everything is >= 3.
type: Comment

http://stackoverflow.com/comment/82799418
type: QuestionComment
score: 4
has text: Please include code as text and not as image.
comment on: http://stackoverflow.com/q/47915676
type: Comment

http://stackoverflow.com/comment/82754680
has text: I am trying the most basic code as below: Open Browser https://xxxxxx.xxxxxx.com:19100/web/login.jsp ie Click Element id=overridelink where do i append --port and switch. Sorry , i m very new to this.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47893341
type: Comment

http://stackoverflow.com/comment/82811305
type: Comment
comment on: http://stackoverflow.com/a/47893712
score: 0
type: AnswerComment
has text: That explains it. Consider accepting your answer because it will help other peers to identify the problem more easy.

http://stackoverflow.com/a/47992052
upvote count: 1
has body: You need to read the data as a string, and when split it by a comma and newline character: # Open file with open("example.txt", "r") as f: # read the contents and replace "\n" characters by commas thedata = f.read().replace("\n", ",") # split it by "," creating an array array = thedata.split(",") # if it's needed, remove empty elements and trim spaces: array = [item.strip() for item in array if item.strip() != ""] # Printing result: print(array)
score: 1
has comment: http://stackoverflow.com/comment/82952337
answers question: http://stackoverflow.com/q/47992019
has comment: http://stackoverflow.com/comment/82952839
has comment: http://stackoverflow.com/comment/82952655
downvote count: 0
has comment: http://stackoverflow.com/comment/82952277
has comment: http://stackoverflow.com/comment/82952376
type: Answer

http://stackoverflow.com/q/47908363
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82784984
has comment: http://stackoverflow.com/comment/82784771
type: Question
has title: List indices must be integers or slices not str- HMM forward algorithm
score: 0
has comment: http://stackoverflow.com/comment/82784767
accepted answer: http://stackoverflow.com/a/47908467
has comment: http://stackoverflow.com/comment/82785138
answer count: 1
has comment: http://stackoverflow.com/comment/82784582
has comment: http://stackoverflow.com/comment/82784269
has answer: http://stackoverflow.com/a/47908467
has comment: http://stackoverflow.com/comment/82784168
has comment: http://stackoverflow.com/comment/82784352
tagged with: python
tagged with: nlp
has body: i am trying to implement forward algorithm in order to calculate HMM. I am doing step by step and debug on every step but i am getting an error. Anyone can tell me what error is? My code is: states = ('Fever','Healthy') end = 'F' observation =('3','1','1','2','2','3','1','3') start = {'Fever': 0.5, 'Healthy': 0.5} trans_prob = { 'Fever' : {'Fever': 0.8, 'Healthy': 0.1, 'F': 0.1}, 'Healthy' : {'Fever': 0.1, 'Healthy': 0.8, 'F': 0.1}, } em_prob = { 'Fever' : {'1': 0.1, '2': 0.2, '3': 0.7}, 'Healthy' : {'1': 0.7, '2': 0.2, '3': 0.1}, } #lent = len(observation) prev = [] for i, obs_i in enumerate(observation): curr = [] for st in states: if i==0: prev_sum =start[st]*em_prob[st][obs_i] else: for i in trans_prob.keys(): prev_sum = sum(prev[k]*transition_probability[i][st] for k in states) print (prev_sum) It is giving me this error: TypeError Traceback (most recent call last) in () 20 else: 21 for i in trans_prob.keys(): ---> 22 prev_sum = sum(prev[k]*transition_probability[i][st] for k in states) 23 print (prev_sum) in (.0) 20 else: 21 for i in trans_prob.keys(): ---> 22 prev_sum = sum(prev[k]*transition_probability[i][st] for k in states) 23 print (prev_sum) TypeError: list indices must be integers or slices, not str

http://stackoverflow.com/comment/82880946
type: Comment
score: 1
type: QuestionComment
has text: you've defined your model such that only one file can be mapped to one user. that's what a one to one field does. If you want otherwise, make it a foreign key.
comment on: http://stackoverflow.com/q/47955762

http://stackoverflow.com/a/47969969
upvote count: 6
accepted answer of: http://stackoverflow.com/q/47969587
answers question: http://stackoverflow.com/q/47969587
type: AcceptedAnswer
downvote count: 0
has body: As far as i know it is possible that DNG files can be compressed (even though it is lossless format), so you will need to decode your dng image first. https://www.libraw.org/ is capable of doing that. There is python wrapper for that library (https://pypi.python.org/pypi/rawpy) import rawpy import imageio path = 'image.dng' with rawpy.imread(path) as raw: rgb = raw.postprocess()
score: 6
type: Answer

http://stackoverflow.com/a/63762064
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47857141
downvote count: 0
has body: This might happen if you have named one of your files as 'cv2.py'. So when you 'import cv2', the system accesses your file instead of the actual library. So try renaming cv2.py' to any other name and your code should work fine.

http://stackoverflow.com/q/47977177
has comment: http://stackoverflow.com/comment/83020290
upvote count: 1
type: Question
has title: clear interactive python session when re-running script from emacs
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: emacs
tagged with: python
has body: I've got the following python script: import numpy as np import matplotlib.pyplot as plt x = np.linspace(1, 20, 10) y = np.linspace(1, 10, 10) plt.plot(x, y) plt.figure() plt.plot(x**2, y) plt.ion() plt.show() To run it from an emacs buffer, I execute the following: C-c C-p # a new buffer appears with an interactive ipython session C-c C-c # run the script I then make a small change to the code in emacs (say multiply the x vector by some constant), and run it again with C-c C-c, the following error appears: TypeError: unbound method trigger_manager_draw() must be called with _BackendMac instance as first argument (got FigureManagerMac instance instead) Since it always works the first time around, how can I run the code in a clear/fresh Python session each time I execute C-c C-c? Also is C-c C-p necessary? Is there a way to simply achieve both steps with only C-c C-c?
answer count: 0
score: 1

http://stackoverflow.com/a/47892573
upvote count: 1
has body: continue is allowed only in for or while loops. Looks like it's redundant here. In case this is part of a loop, please post that part of your code as well.
type: Answer
answers question: http://stackoverflow.com/q/47892500
downvote count: 0
score: 1

http://stackoverflow.com/a/79230406
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47975866
has body: Try running your code editor as an administrator, that worked for me

http://stackoverflow.com/comment/82983443
type: Comment
has text: It's all about javascript coding conventions. You can refer [this](https://stackoverflow.com/questions/846585/can-someone-explain-the-dollar-sign-in-javascript)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48007391

http://stackoverflow.com/q/47971410
type: AnsweredQuestion
tagged with: django-models
answer count: 1
downvote count: 0
favorite count: 0
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/47971433
has title: Django - Getting AttributeError 'User' object has no attribute 'cleaned_data' while cleaning form data
has body: I was trying to make a user registration page in Django. everything went fine. but when I submit the form data I get this below error AttributeError 'User' object has no attribute 'cleaned_data' Image of that AttributeError I searched on stackoverflow and found that the object.cleanded_data should be placed after object.is_valid() else one should face the AttributeError. But I placed that after checking is_valid() still getting error. my codes: views.py class UserFormView(View): form_class = UserForm template_name = "music/registration_form.html" def get(self, request): form = self.form_class(None) return render(request, self.template_name, {"form": form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) username = user.cleaned_data["username"] password = user.cleaned_data["password"] user.set_password(password) user.username = username user.save() user = authenticate(username= username, password= password) if user is not None: if user.is_active: login(request, user) return redirect("music:index") return render(request, self.template_name, {"form": form}) forms.py from django.contrib.auth.models import User from django import forms class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ["username", "email", "password"] I cant find where I made mistake.
tagged with: django-views
score: 1
upvote count: 1
tagged with: django-forms
has answer: http://stackoverflow.com/a/47971433
type: Question

http://stackoverflow.com/comment/82770596
comment on: http://stackoverflow.com/q/47901771
type: Comment
type: QuestionComment
score: 2
has text: @Ev.Kounis some countries use `,` as a decimal separator instead of `.`, not everyone is from the US

http://stackoverflow.com/a/47972005
answers question: http://stackoverflow.com/q/47971968
has body: One option would be to have each instance buffer the output in an internal buffer. then output it at the end. You could have the main thread go and save each started process in an array. then wait on all three to finish and finally go and grab the internal buffer from each process in the array and print them serially.
has comment: http://stackoverflow.com/comment/82913727
accepted answer of: http://stackoverflow.com/q/47971968
type: Answer
has comment: http://stackoverflow.com/comment/82913654
has comment: http://stackoverflow.com/comment/82914750
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/82918242
has comment: http://stackoverflow.com/comment/82913675
has comment: http://stackoverflow.com/comment/82914806
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82914802

http://stackoverflow.com/a/68948768
upvote count: 1
has comment: http://stackoverflow.com/comment/121901217
has body: You have to construct a ssh command like this ['ssh', '-T', 'host_user_name@host_address'] then follow below code. Code: from subprocess import Popen, PIPE ssh_conn = ['ssh', '-T', 'host_user_name@host_address'] # if you have to add port then ssh_conn should be as following # ssh_conn = ['ssh', '-T', 'host_user_name@host_address', '-p', 'port'] commands = &quot;&quot;&quot; cd Documents/ ls -l cat test.txt &quot;&quot;&quot; with Popen(ssh_conn, stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True) as p: output, error = p.communicate(commands) print(output) print(error) print(p.returncode) # or can do following things p.stdin.write('command_1') # add as many command as you want p.stdin.write('command_n') Terminal Output: Please let me know if you need further explanations. N.B: You can add command in commands string as many as you want.
has comment: http://stackoverflow.com/comment/121945195
has comment: http://stackoverflow.com/comment/121902323
has comment: http://stackoverflow.com/comment/121878163
has comment: http://stackoverflow.com/comment/121880687
has comment: http://stackoverflow.com/comment/121902723
answers question: http://stackoverflow.com/q/47887790
has comment: http://stackoverflow.com/comment/121878442
has comment: http://stackoverflow.com/comment/121901267
downvote count: 0
has comment: http://stackoverflow.com/comment/121878467
type: Answer
has comment: http://stackoverflow.com/comment/121880024
score: 1

http://stackoverflow.com/q/47890465
type: Question
upvote count: 4
answer count: 1
downvote count: 0
favorite count: 0
tagged with: pandas
tagged with: rolling-computation
tagged with: python
has title: understanding rolling correlation in pandas
tagged with: correlation
has body: I am trying to understand how pandas.rolling_corr actually calculates rolling correlations. So far I have always been doing it with numpy. I prefer to use pandas due to the speed and the ease of use, but I cannot get the rolling correlation as it used to do. I start with two numy arrays: c = np.array([1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1]) d = np.array([8,9,8]) now I want to calculate the cross-correlation for which length-3-window of my array c. I define a rolling window function: def rolling_window(a, window): shape = a.shape[:-1] + (a.shape[-1] - window + 1, window) strides = a.strides + (a.strides[-1],) return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides) and calculate the correlation between each of my generated windows and the second original dataset. This approach works just fine: for win in rolling_window(c, len(d)): print(np.correlate(win, d)) Outputs: [50] [75] [100] [125] [150] [175] [200] [209] [200] [175] [150] [125] [100] [75] [50] If I attempt to solve it with pandas: a = pd.DataFrame([1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1]) b = pd.DataFrame([8,9,8]) no matter if I use DataFrame rolling_corr: a.rolling(window=3, center=True).corr(b) or Pandas rolling_corr: pd.rolling_corr(a, b, window=1, center=True) I just get a bunch of NaNs: 0 0 NaN 1 0.0 2 NaN 3 NaN 4 NaN 5 NaN 6 NaN 7 NaN 8 NaN 9 NaN 10 NaN 11 NaN 12 NaN 13 NaN 14 NaN 15 NaN 16 NaN Can someone give me a hand? I am able to solve the problem with numpy by flattening the numpy array obtained from converting the pandas DataFrame a.values.ravel() However, I would like to solve the calculation entirely with pandas. I have searched the documentation but haven't found the answer I am looking for. What am I missing or not undrstanding? Thank you very much in advance. D.
has answer: http://stackoverflow.com/a/48610617
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48610617
score: 4

http://stackoverflow.com/q/47962601
has body: Line 26 of this code is giving me error and I haven't been able to fix it. Please help me figure it out. This is the line: path[road]['distance_from_start'] = path.get(road, {}).get('distance_from_start') + path.get(road, {}).get('distance_to_neighbor') What it is supposed to find is the shortest path between a starting point and destination goal in a map with multiple intermediary stops in between. import math def my_function(M, start, goal): frontier = set([start]) expanded = set() chosen = start chosen_coordinates = M.intersections[chosen] goal_coordinates = M.intersections[goal] roads_to_choose = M.roads[chosen] path = {} while frontier != set(): if chosen != goal: for road in roads_to_choose: if road not in expanded: frontier.add(road) path[road] = {} path[road]['coordinate'] = {} path[road]['roads'] = {} path[road]['distance_to_goal'] = {} path[road]['distance_to_neighbor'] = {} path[road]['distance_from_start'] = {} path[road]['g_plus_h'] = {} path[road]['path_list'] = {} path[road]['coordinate'] = M.intersections[road] path[road]['roads'] = M.roads[road] path[road]['distance_to_neighbor'] = math.sqrt(((M.intersections[road][0]-chosen_coordinates[0])**2) + ((M.intersections[road][1]-chosen_coordinates[1])**2)) path[road]['distance_from_start'] = path.get(road, {}).get('distance_from_start') + path.get(road, {}).get('distance_to_neighbor') path[road]['distance_to_goal'] = math.sqrt(((goal_coordinates[0]-M.intersections[road][0])**2) + ((goal_coordinates[1]-M.intersections[road][1])**2)) path[road]['g_plus_h'] = path[road]['distance_from_start'] + path[road]['distance_to_goal'] path[road]['path_list'] = path[chosen]['path_list'].append(road) frontier.remove(chosen) expanded.add(chosen) if x not in expanded: chosen = min(path.keys(), key=lambda x:path[x]['g_plus_h']) path[road]['distance_from_start'] = path.get(chosen, {}).get('distance_from_start') else: print("Short path called") return path[goal]['path_list']
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82894504
has title: TypeError: unsupported operand type(s) for +: 'dict' and 'float'
has comment: http://stackoverflow.com/comment/82894477
has comment: http://stackoverflow.com/comment/82894671
type: Question
has comment: http://stackoverflow.com/comment/82894450
accepted answer: http://stackoverflow.com/a/47962698
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/47962698
tagged with: python
tagged with: dictionary

http://stackoverflow.com/comment/82967228
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47999119
score: 0
has text: yes I want from each file. i.e compare lines containing values of bb and select the highest value of bb. Then write out each line with the max value of bb into the output text after comparison. i.e compare lines 1 file 1 with line 1 file 2 with line 1 file 3 etc and whichever line has the highest value of bb gets written to output, then go to line 2 etc

http://stackoverflow.com/q/47924237
tagged with: matplotlib
has body: I would like to spread my boxplots equally over the x-axis. The following code generates a figure where the two boxplots are close with plenty of space on either side. In generate I want the code to spread the boxplots out evenly regardless of the number of boxplots (in this example there are only two, but in general there will be many). import matplotlib.pyplot as plt statistic_dict = {0.40000000000000002: [0.36003616645322273, 0.40526649416305677, 0.46522159350924536], 0.20000000000000001: [0.11932912803730165, 0.23235825966896217, 0.12380728472472625]} def draw_boxplot(y_values, x_values, edge_color, fill_color): bp = plt.boxplot(y_values, patch_artist=True, positions=x_values) for element in ['boxes', 'whiskers', 'fliers', 'medians', 'caps']: plt.setp(bp[element], color=edge_color) plt.xlabel("x label ") plt.ylabel("y label ") plt.title("Title") for patch in bp['boxes']: patch.set(facecolor=fill_color) y_values = statistic_dict.values() x_values = statistic_dict.keys() draw_boxplot(y_values, x_values, "skyblue", "white") plt.savefig('fileName.png', bbox_inches='tight') plt.close()
answer count: 1
has answer: http://stackoverflow.com/a/47926303
tagged with: boxplot
tagged with: python
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47926303
type: Question
has title: Boxplots equally spread out

http://stackoverflow.com/a/47994424
has comment: http://stackoverflow.com/comment/82969735
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47994397
has body: You need to escape your brackets so Python can tell the difference between a format parameter and a character that needs to be printed out, to do that you can just duplicate the brackets as follows: print('{{"_id":ObjectId("{}")}}'.format('5a43ae09e2bae06ddd400dfc')) Here is more info: https://docs.python.org/3/library/string.html#formatstrings
answers question: http://stackoverflow.com/q/47994397
type: Answer
upvote count: 3
score: 3

http://stackoverflow.com/comment/82769200
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47901157
has text: The error is at if condition when i am comparing the score of home team and away team.What I want to do is to add a column to the csv file which lists the win or loss of a team,win being 1 and loss being zero so that i can add the win of a particular team in a season and calculate their probability of winning and predict the probability of winning in the next season.

http://stackoverflow.com/comment/82854109
type: QuestionComment
has text: Just append the results to the dataframe using column names. Something like `data['prob_0']=output[:,0]` and `data['prob_1']=output[:,1]`, where `output = clf.predict_proba(X_test)`
score: 0
comment on: http://stackoverflow.com/q/47940731
type: Comment

http://stackoverflow.com/a/48164720
has comment: http://stackoverflow.com/comment/83540209
has comment: http://stackoverflow.com/comment/83543437
has comment: http://stackoverflow.com/comment/83363285
has comment: http://stackoverflow.com/comment/83622753
has comment: http://stackoverflow.com/comment/83623376
has comment: http://stackoverflow.com/comment/83351455
has comment: http://stackoverflow.com/comment/83363418
answers question: http://stackoverflow.com/q/48009243
score: 0
has body: I used this distribution and it worked fine for me (Windows 7 and 10 64bit, 2x Intel Xeon E5-2637 v3) https://github.com/fo40225/tensorflow-windows-wheel
type: Answer

http://stackoverflow.com/q/47960368
has comment: http://stackoverflow.com/comment/82890197
downvote count: 0
tagged with: qt-designer
answer count: 1
linked to: http://stackoverflow.com/q/28204043
tagged with: keyboard-shortcuts
favorite count: 0
has body: I have a form designed in Qt Designer (with PyQt5). I use a line-edit there for entering some input. What I want is to add the ability to use a keyboard combo (something like Ctrl+B or one of the function keys) in the line-edit. Once that combo or function key is pressed, I am going to run a function/method that will paste the clipboard contents in a "special" way (meaning it will filter and adjust the value from the clipboard). It seems all easy, and a lot of people must have been doing this kind of stuff before. But I wasn't able to find a single, simple, understandable way of doing what I want. Here is the kind of solution I am looking for. The following is under a class that holds the MainForm code: self.ui.my_lineedit.keyboard_key_pressed.connect(self.my_func, ctrl+b) def my_func(self): pass I made up the keyboard_key_pressed part (and others) for you to understand what I'm going for. Is there a straightforward way of doing what I want like the example above?
has answer: http://stackoverflow.com/a/47963560
linked to: http://stackoverflow.com/q/45308101
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/82890366
tagged with: qlineedit
score: 2
type: AnsweredQuestion
tagged with: pyqt5
accepted answer: http://stackoverflow.com/a/47963560
type: Question
has title: Assign keyboard shortcut to QLineEdit from Qt Designer

http://stackoverflow.com/comment/82878940
score: 0
type: Comment
has text: Let say I have a button and a textbox in my GUI and I had like to see text appears when I clicked the button. It is possible to see?
type: QuestionComment
comment on: http://stackoverflow.com/q/47954644

http://stackoverflow.com/comment/82865423
has text: it's not really a csv / at least not using `csv` module at all but rather text processing. can the characters be in the middle of the string?
comment on: http://stackoverflow.com/q/47947737
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/47859225
upvote count: 18
has comment: http://stackoverflow.com/comment/82683281
has comment: http://stackoverflow.com/comment/82683170
has body: There is no need to use a lambda expression here, you can pass a reference to te function directly: list(map(add, list1, list2)) In case you want to use list comprehension, you can use zip: [add(x, y) for x, y in zip(list1, list2)] zip takes n iterables, and generate n-tuples where the i-th tuple contains the i-th element of every iterable. In case you want to add a default value to some parameters, you can use partial from functools. For instance if you define a: def add (x, y, a, b): return x + y + a + b from functools import partial list(map(partial(add, a=3, b=4), list1, list2)) Here x and y are thus called as unnamed parameters, and a and b are by partial added as named parameters. Or with list comprehension: [add(x, y, 3, 4) for x, y in zip(list1, list2)]
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82683206
accepted answer of: http://stackoverflow.com/q/47859209
type: Answer
has comment: http://stackoverflow.com/comment/82683243
answers question: http://stackoverflow.com/q/47859209
score: 18

http://stackoverflow.com/comment/120849714
score: 0
comment on: http://stackoverflow.com/a/55093287
type: Comment
has text: Which OS are you using? can you guess what would be the log file location if I'm using geckodriver on Spring (deployed on tomcat)
type: AnswerComment

http://stackoverflow.com/a/47861692
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/47861508
answers question: http://stackoverflow.com/q/47861508
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: You can use subprocess.check_output() instead of subprocess.call(): import subprocess print("The top five memory consumers on the system are:") cmd = "ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | head -n 6" result = subprocess.check_output(cmd, shell=True).decode() lines = result.split("\n") for line in lines: print(line) Also note that the result of check_output() is a bytes-like object, so you must call .decode() on it if you want to work with it as a string.

http://stackoverflow.com/tag/json
tags question: http://stackoverflow.com/q/47986743
tags question: http://stackoverflow.com/q/47897996
tags question: http://stackoverflow.com/q/47866945
tags question: http://stackoverflow.com/q/48004543
tags question: http://stackoverflow.com/q/47971226
tags question: http://stackoverflow.com/q/47861688
tags question: http://stackoverflow.com/q/47968470
tags question: http://stackoverflow.com/q/47955454
tags question: http://stackoverflow.com/q/47929046
tags question: http://stackoverflow.com/q/47889267
tags question: http://stackoverflow.com/q/47993087
tags question: http://stackoverflow.com/q/48002339
tags question: http://stackoverflow.com/q/47913709
tags question: http://stackoverflow.com/q/47991145
tags question: http://stackoverflow.com/q/47962660
tags question: http://stackoverflow.com/q/47882829
tags question: http://stackoverflow.com/q/48004577
tags question: http://stackoverflow.com/q/47919440
tags question: http://stackoverflow.com/q/47931538
tags question: http://stackoverflow.com/q/47870487
tags question: http://stackoverflow.com/q/48004556
tags question: http://stackoverflow.com/q/47936640
tags question: http://stackoverflow.com/q/48012370
tags question: http://stackoverflow.com/q/47898531
tags question: http://stackoverflow.com/q/47948690
tags question: http://stackoverflow.com/q/48009171
tags question: http://stackoverflow.com/q/47986878
tags question: http://stackoverflow.com/q/47963287
tags question: http://stackoverflow.com/q/47896877
tags question: http://stackoverflow.com/q/47871352
tags question: http://stackoverflow.com/q/47953069
tags question: http://stackoverflow.com/q/47889565
tags question: http://stackoverflow.com/q/47903593
type: Tag
tags question: http://stackoverflow.com/q/47865048
tags question: http://stackoverflow.com/q/47912051
tags question: http://stackoverflow.com/q/47980278
tags question: http://stackoverflow.com/q/48008390
tags question: http://stackoverflow.com/q/47987550
tags question: http://stackoverflow.com/q/47878260
tags question: http://stackoverflow.com/q/47946297
tags question: http://stackoverflow.com/q/47893309
tags question: http://stackoverflow.com/q/47957480
tags question: http://stackoverflow.com/q/47933565
tags question: http://stackoverflow.com/q/47910374
tags question: http://stackoverflow.com/q/47858802
tags question: http://stackoverflow.com/q/47857428
tags question: http://stackoverflow.com/q/47981652
tags question: http://stackoverflow.com/q/48012911
tags question: http://stackoverflow.com/q/47856882
tags question: http://stackoverflow.com/q/47950212
tags question: http://stackoverflow.com/q/47995840
tags question: http://stackoverflow.com/q/47912706
tags question: http://stackoverflow.com/q/47880389
tags question: http://stackoverflow.com/q/47886058
tags question: http://stackoverflow.com/q/47967661
tags question: http://stackoverflow.com/q/47931356
tag name: json
tags question: http://stackoverflow.com/q/47919423
tags question: http://stackoverflow.com/q/47981693
tags question: http://stackoverflow.com/q/47878199
tags question: http://stackoverflow.com/q/47979088
tags question: http://stackoverflow.com/q/47932921
tags question: http://stackoverflow.com/q/47910547
tags question: http://stackoverflow.com/q/47978178
tags question: http://stackoverflow.com/q/47977440
tags question: http://stackoverflow.com/q/48012197
tags question: http://stackoverflow.com/q/47917468
tags question: http://stackoverflow.com/q/47889499
tags question: http://stackoverflow.com/q/47979647
tags question: http://stackoverflow.com/q/47970625
tags question: http://stackoverflow.com/q/47892781
tags question: http://stackoverflow.com/q/47976077
tags question: http://stackoverflow.com/q/47857154
tags question: http://stackoverflow.com/q/47901728
tags question: http://stackoverflow.com/q/47863768
tags question: http://stackoverflow.com/q/47991331
tags question: http://stackoverflow.com/q/47878367
tags question: http://stackoverflow.com/q/47998634
tags question: http://stackoverflow.com/q/47880332

http://stackoverflow.com/comment/82906853
type: AnswerComment
comment on: http://stackoverflow.com/a/47968548
type: Comment
score: 1
has text: Despite its higher time complexity, I guess mine is simpler and more concise and performance won't be an issue even for very long lists (as log(n) doesn't grow that fast). Add to that that list concatenation is `O(M+N)` which is unnecessary and that users tend to trust rep without proper checking ;)

http://stackoverflow.com/comment/82723742
type: Comment
type: QuestionComment
has text: IMO there is nothing really wrong with the list and loop
comment on: http://stackoverflow.com/q/47878838
score: 0

http://stackoverflow.com/q/47994698
downvote count: 0
accepted answer: http://stackoverflow.com/a/47996459
has body: So I am trying to modify a user in my active directory. As of now I can log in as an AD-user but when I try to edit my profile, it does not implement in the AD. I use django-auth-ldap for AD backend. I made a connection with a user that has reading and writing permissions. AUTH_LDAP_SERVER_URI = "ldap://192.168.1.12" AUTH_LDAP_BIND_DN = "user" AUTH_LDAP_BIND_PASSWORD = "password" AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_DEBUG_LEVEL: 1, ldap.OPT_REFERRALS: 0 } AUTH_LDAP_USER_SEARCH = LDAPSearch("DC=sb,DC=ch", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)") # Set up the basic group parameters. AUTH_LDAP_GROUP_SEARCH = LDAPSearch("DC=sb,DC=ch", ldap.SCOPE_SUBTREE, "(objectClass=group)") AUTH_LDAP_GROUP_TYPE = NestedActiveDirectoryGroupType() # What to do once the user is authenticated AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail" } AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_active": "CN=ipa-users,cn=users,DC=sb,DC=ch", "is_staff": "CN=ipa-users,cn=users,DC=sb,DC=ch", "is_superuser": "CN=ipa-users,cn=users,DC=sb,DC=ch" } # This is the default, but be explicit. AUTH_LDAP_ALWAYS_UPDATE_USER = True # Use LDAP group membership to calculate group permissions. AUTH_LDAP_FIND_GROUP_PERMS = True # Cache settings AUTH_LDAP_CACHE_GROUPS = True AUTH_LDAP_GROUP_CACHE_TIMEOUT = 3600 AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) So what and where do I have to set or get anything? This is my edit_profile.html: {% csrf_token %} Vorname Nachname E-Mail Bestätigen
tagged with: ldap
tagged with: user-profile
tagged with: python
favorite count: 0
score: 2
has answer: http://stackoverflow.com/a/52270893
upvote count: 2
tagged with: django
possible better answer: http://stackoverflow.com/a/52270893
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47996459
tagged with: active-directory
has title: Modify an Active Directory User in Django
type: Question
answer count: 2

http://stackoverflow.com/comment/83899454
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48451655
has text: tvalues and pvalues for testing that parameter is zero are directly available in the results instance, t_test is more general and provides the same results.

http://stackoverflow.com/comment/82820857
score: 0
type: Comment
has text: @TheGman, what is happening if you changed to `EC.element_to_be_clickable`?
comment on: http://stackoverflow.com/a/47925369
type: AnswerComment

http://stackoverflow.com/q/48001370
has title: Kill a background process using command
type: Question
tagged with: kill
score: 0
has comment: http://stackoverflow.com/comment/82971835
answer count: 1
tagged with: shell
has body: I am trying to kill a process which I ran in back ground not I want to cancel it using a command line. Below is the command I am using but I am getting error "Operation not permitted". ps -aef | grep gs_roach | grep -v grep | awk '{print $2}' | xargs kill -2
tagged with: python
tagged with: unix
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48001444

http://stackoverflow.com/comment/82688883
has text: What I'm asking is do I have to collapse the image dimensions to rnn dims or do I feed the images as they are read?
comment on: http://stackoverflow.com/a/47861934
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47904685
tagged with: python
type: AnsweredQuestion
upvote count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/47911931
has body: I have problem with the results of my pop-up window. Below I have shown part of my code to understand the problem. It's a kind of pop-up window where the user makes some choice in the GUI. After this it should show a window where there will be the question "Are you sure?", and two buttons "Yes" and "No". The problem is that when I test the code below (before and after the msg.show()), I have the same value set as False. Why doesnt it work like this: Before function -> False Show my window and wait to click the button If I clicked button "Yes", then give True, else False How I can handle this properly? Is there another approach? from PyQt4 import QtCore, QtGui from Message import Ui_Message import sys class MessageBox(QtGui.QDialog): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent=None) self.msg = Ui_Message() self.msg.setupUi(self) self.confirmed=False self.declined=False QtCore.QObject.connect(self.msg.NoButton, QtCore.SIGNAL(("clicked()")), self.Declined) QtCore.QObject.connect(self.msg.YesButton, QtCore.SIGNAL(("clicked()")), self.Confirmed) def Confirmed(self): self.confirmed = True MessageBox.close(self) return True def Declined(self): self.declined = True MessageBox.close(self) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) msg = MessageBox() print('Befor show window',msg.confirmed) msg.show() print('After show window', msg.confirmed) sys.exit(app.exec_())
type: Question
tagged with: dialog
tagged with: pyqt4
score: 0
has title: How to get result from corfirmation dialog
tagged with: pyqt
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47911931

http://stackoverflow.com/q/47892431
has comment: http://stackoverflow.com/comment/82751409
has answer: http://stackoverflow.com/a/47892883
upvote count: 1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82751945
score: 1
type: Question
has comment: http://stackoverflow.com/comment/82751379
accepted answer: http://stackoverflow.com/a/47892883
has comment: http://stackoverflow.com/comment/82751504
answer count: 1
downvote count: 0
tagged with: python-2.7
has body: I define a function as below, EmiCtry, percapita, and year are global parameters. I would like to see the effect of choosing different shreshold and ramprate. def annual_emi_scale(shreshold, ramprate): tmp = EmiCtry for i in range(177): for j in range(91): if percapita[i,j] &gt;= shreshold and year[j] &gt;= 2020: tmp[i,j] = tmp[i,j] * (1.-ramprate) adj1 = cdutil.averager(tmp, axis=0,weights='equal',action='sum') adj2 = cdutil.averager(adj1,axis=0,weights='equal',action='sum') return adj1, adj2 Then I do a loop with the defined function: emi = np.zeros([25, 91]) cum = np.zeros([5,5]) for ii in range(5): shre = (ii + 1) * 20 for jj in range(5): ramp = jj * 0.02 emi[ii*5+jj],cum[ii,jj] = annual_emi_scale(shre, ramp) The outputs are strange for ii > 0 and it seems after each loop tmp = EmiCtry does not work at all. That is, for ii = 3, tmp = EmiCtry will use the value of tmp when ii = 2. However, when I do tmp1, tmp2 = annual_emi_scale(80, 0.00) before the loop, the results are correct. But when I put it after the loop, the same thing happen again. EmiCtry is calculated from other data and is an numpy.array() with float type values: co2EmiCtry = original_data.astype(np.float)
has title: Python, looping with defined function, but output strange values
has comment: http://stackoverflow.com/comment/82752090
favorite count: 0

http://stackoverflow.com/a/47973454
type: Answer
upvote count: 1
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/47973360
has body: You first need to make flat list out of list1 and list2, make an extended list which contains both elements of list1 and list2 and cast the resulting list to set to remove duplicate elements. Solution i am giving is little less verbose and involve less number of lines #Flatten list function flatten=lambda l: sum(map(flatten,l),[]) if isinstance(l,list) else [l] list1 = flatten(list1) #[1, 1, 1, 2, 2, 1, 2, 3, 6, 3, 4, 5] list2 = flatten(list2) #[1, 1, 6, 7, 7, 14, 8, 9] list1.extend(list2) #[1, 1, 1, 2, 2, 1, 2, 3, 6, 3, 4, 5, 1, 1, 6, 7, 7, 14, 8, 9] list(set(list1)) #[1, 2, 3, 4, 5, 6, 7, 8, 9, 14]

http://stackoverflow.com/a/48042420
accepted answer of: http://stackoverflow.com/q/47983165
answers question: http://stackoverflow.com/q/47983165
upvote count: 5
has body: By default, the STDOUT of many programs (including perl) is line-buffered (flushed on newline) when the STDOUT is connected to a terminal, and block-buffered (flushed when the file's buffer is full) otherwise (e.g. when it's connected to a pipe). You can fool such programs into using line-buffering by using a pseudo-tty (ptty) instead of a pipe. To that end, unbuffer is your friend. On Ubuntu, this is part of the expect package (sudo apt install expect). From the docs: unbuffer disables the output buffering that occurs when program output is redirected from non-interactive programs. For example, suppose you are watching the output from a fifo by running it through od and then more. od -c /tmp/fifo | more You will not see anything until a full page of output has been produced. You can disable this automatic buffering as follows: unbuffer od -c /tmp/fifo | more I tried your example code and got the same result as you describe (thanks to your Minimal, Complete, and Verifiable example!). I then changed run_demo(['sudo', '-b', 'prove', '-v', os.path.join(os.getcwd(), 'job.t')], timeout_sec, signal.SIGINT) to run_demo(['sudo', '-b', 'unbuffer', 'prove', '-v', os.path.join(os.getcwd(), 'job.t')], timeout_sec, signal.SIGINT) That is: I simply prepended unbuffer to the prove command. The output then was: DEMO: sudo -b python job.py KILLED! Got our/err: 1..20 ok 1 ok 2 ok 3 ok 4 ok 5 ok 6 Traceback (most recent call last): File "job.py", line 8, in &lt;module&gt; time.sleep(1) KeyboardInterrupt DEMO: sudo -b unbuffer prove -v /home/dirk/w/sam/p/job.t KILLED! Got our/err: /home/dirk/w/sam/p/job.t .. 1..20 ok 1 ok 2 ok 3 ok 4 ok 5
type: Answer
downvote count: 0
score: 5
type: AcceptedAnswer

http://stackoverflow.com/q/47971235
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47971490
type: AnsweredQuestion
score: 1
tagged with: formatting
type: Question
has body: I have written this piece of code: @staticmethod def __ver_upload_url(document_type, document_subtype=None): verification_base = 'verification/{0}/'.format(document_type) verification_base += '{0}/'.format(document_subtype) if document_subtype is not None else '' I was wondering if there was a cleaner, more Pythonic way of formatting the URL path in just one line. I initially had: verification_base = 'verification/{0}/{1}'.format(document_type, document_subtype) \ if document_subtype is not None else 'verification/{0}/'.format(document_type) I think it is cleaner and more readable now, but maybe there is still a better way. Note: I am trying to generate a path for a Django file that must be uploaded, and files have always types, but not always subtypes (as in categories and subcategories). I want to add a subdirectory to specify the subtype only if the file has a subtype, and if not leave it inside the folder named as the type. Edit I had to escalate my function and now it looks something like: def verification_url(document_type, document_subtype=None, company=False, company_administrator=False): verification_base = 'verification/' verification_base += 'companies/' if company or company_administrator else '' verification_base += 'admins/' if company_administrator else '' verification_base += '{0}/'.format(document_type) verification_base += '{0}/'.format(document_subtype) if document_subtype is not None else '' def function(instance, filename): id = instance.id if company else instance.user.id return verification_base + '{user_id}/{filename}'.format(id=id, filename=filename) I was wondering that maybe I could write a URL builder that depends upon a list of elements that will be inserted into a string limited by slashes, to reduce the length of my code, or make it reusable at least. What are your suggestions to improve the efficiency / scalability of the code?
has title: More efficient way of formatting optional text string
has answer: http://stackoverflow.com/a/47971490
has comment: http://stackoverflow.com/comment/82912348
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82912415

pyusb
tags question: http://stackoverflow.com/q/47970964
type: Tag
tag name: pyusb
tags question: http://stackoverflow.com/q/47973496

http://stackoverflow.com/comment/82846854
type: Comment
comment on: http://stackoverflow.com/q/47938834
type: QuestionComment
has text: you can always you standard `if` to check something in Python.
score: 0

http://stackoverflow.com/q/47981651
has answer: http://stackoverflow.com/a/47982109
type: Question
tagged with: firebase
score: 0
answer count: 1
tagged with: python
has title: C++ Firebase wrapper?
has body: I'm trying to create an app that runs from a raspberry PI and connects to a firebase database. I have written this app in C++ and I was wondering if there was a simple way to do that. I did it in Python with the module Pyrebase: import pyrebase def firbaseLogIn(): directory = os.getcwd() serviceAccount = directory + "xxx.json" config = { "apiKey": "xxx", "authDomain": "xxxx", "databaseURL": "https://example.com", "projectId": "xxxx", "storageBucket": "xx.example.com", "serviceAccount": serviceAccount } firebase = pyrebase.initialize_app(config) # Log the user in email = "xxx@gmail.com" password = "xxx" auth = firebase.auth() user = auth.sign_in_with_email_and_password(email, password) # Get a reference to the database service db = firebase.database() # Pass the user's idToken to the push method userInfo = db.child("users").child(user['localId']).get() print(userInfo.val()) return; and it works fine. However when I try to do something similar with the c++ SDK and by following the doc the app just doesn't work. I don't know if it's because it only works with and IOS game (it actually says that you need Xcode) or because I'm just unable to follow the documentation correctly. The code does not throw any error. It prints that I have signed in correctly but the user information in not correct. For example the UID is the email and the phone number is 1-888-897-5309 which is clearly not correct. This is what I've tried in c++: #include "firebase/app.h" firebase::App* configureFirebaseApp(std::string appcwd){ std::string stringAppID = appcwd + "xxx.json"; const char* appID = &amp;stringAppID[0]; firebase::AppOptions appOptions = firebase::AppOptions(); appOptions.set_api_key("xxx"); appOptions.set_database_url("https://xxx.xxx.com"); appOptions.set_project_id("xxx"); appOptions.set_storage_bucket("xxxxx.xxxx.com"); appOptions.set_app_id(appID); return firebase::App::Create(appOptions); } #include "firebase/auth.h" void FirebaseLogIn(std::string appcwd){ const char email[] = …
tagged with: c++
type: UnansweredQuestion
tagged with: firebase-realtime-database

http://stackoverflow.com/a/47957854
downvote count: 0
type: Answer
upvote count: 12
has comment: http://stackoverflow.com/comment/102414742
answers question: http://stackoverflow.com/q/47957813
has body: Since you need to dynamically change the return values, you need to use side_effect and not the return_value. You may map the desired return values to the expected inputs and use the .get function of this mapping/dictionary as a side effect: return_values = {1: 10, 2: 20} o.foo.side_effect = return_values.get Demo: In [1]: from unittest import mock In [2]: m = mock.MagicMock() In [3]: return_values = {1: 10, 2: 20} In [4]: m.foo.side_effect = return_values.get In [5]: m.foo(1) Out[5]: 10 In [6]: m.foo(2) Out[6]: 20
accepted answer of: http://stackoverflow.com/q/47957813
score: 12
type: AcceptedAnswer

http://stackoverflow.com/a/47924945
has comment: http://stackoverflow.com/comment/82817663
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82818663
accepted answer of: http://stackoverflow.com/q/47924382
type: Answer
answers question: http://stackoverflow.com/q/47924382
has body: I guess you mixed up the arguments to contour and contourf. Applying the reverse colormap to contour works fine. import numpy as np import matplotlib.pyplot as plt from matplotlib import mlab delta = 0.025 x = np.arange(1.0, 3.0, delta) y = np.arange(1.0, 2.0, delta) X, Y = np.meshgrid(x, y) Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) # difference of Gaussians Z = 10.0 * (Z2 - Z1) plt.figure() CS2 = plt.contourf(X, Y, Z, cmap=plt.cm.YlGn_r) CS = plt.contour(X, Y, Z, cmap=plt.cm.YlGn) plt.clabel(CS, fontsize=10) plt.title('Simplest default with labels') plt.show() To use the same colormap for the lines as for the fills, but then use a different colormap for the labels, you need to define the colors manually. But the use of the existing levels helps you do that quite efficiently. CS2 = plt.contourf(X, Y, Z, cmap=plt.cm.YlGn_r) CS = plt.contour(CS2, cmap=plt.cm.YlGn_r) plt.clabel(CS, fontsize=10, colors=plt.cm.Reds(CS.norm(CS.levels)))

dialogflow-es
tag name: dialogflow-es
type: Tag
tags question: http://stackoverflow.com/q/47929433

http://stackoverflow.com/a/48019592
has comment: http://stackoverflow.com/comment/133202081
score: 25
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47968861
upvote count: 25
has body: It is not safe to write to a single file from multiple processes. According to https://docs.python.org/3/howto/logging-cookbook.html#logging-to-a-single-file-from-multiple-processes Although logging is thread-safe, and logging to a single file from multiple threads in a single process is supported, logging to a single file from multiple processes is not supported, because there is no standard way to serialize access to a single file across multiple processes in Python. One possible solution would be to have each process write to its own file. You can achieve this by writing your own handler that adds process pid to the end of the file: import logging.handlers import os class PIDFileHandler(logging.handlers.WatchedFileHandler): def __init__(self, filename, mode='a', encoding=None, delay=0): filename = self._append_pid_to_filename(filename) super(PIDFileHandler, self).__init__(filename, mode, encoding, delay) def _append_pid_to_filename(self, filename): pid = os.getpid() path, extension = os.path.splitext(filename) return '{0}-{1}{2}'.format(path, pid, extension) Then you just need to call addHandler: logger = logging.getLogger('foo') fh = PIDFileHandler('bar.log') logger.addHandler(fh)

http://stackoverflow.com/a/47916044
answers question: http://stackoverflow.com/q/47915933
type: AcceptedAnswer
has body: Your a and b variables are local. You can only use these variables in the method scope. If you want a class attribute (shared with all the class) you have to set the like self.a = ... and self.b = .... In python is not necessary create a constructor method __init__ neither initialize these attributes. But in your example if you call functions2 before function1 it will crash because you are using one attribute that doen't exist. Then is recommended initialize the attributes. You can initialize the attributes like this: class Project: a = '' b = '' def function1(self): self.a='hello world,' def function2(self): self.b=self.a + ' I am alive' More things to keep in mind: 1. The variables are in lower case and snake case: project1 = Project() 2. Your prints won't print anything because your functions don't return anything. You have to return something like: def function1(): return 'hello world,' or if you need to set a and print: def function1(): self.a = 'hello world,' return self.a
upvote count: 1
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47915933
score: 1

http://stackoverflow.com/a/47944084
type: Answer
has comment: http://stackoverflow.com/comment/82960727
answers question: http://stackoverflow.com/q/47942875
has body: What you want to do is use the from_json method to convert the string into an array and then explode: from pyspark.sql.functions import * from pyspark.sql.types import * phone_schema = ArrayType(StructType([StructField("phone", StringType())])) converted = inputDF\ .withColumn("areaCode", get_json_object("phones", "$[*].areaCode"))\ .withColumn("phones", explode(from_json("phones", phone_schema)))\ .withColumn("phone", col("phones.phone"))\ .drop("phones")\ .filter(~isnull("phone")) converted.show()
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47942875
upvote count: 8
type: AcceptedAnswer
score: 8

http://stackoverflow.com/comment/82789785
comment on: http://stackoverflow.com/a/47910633
score: 1
has text: No problem, Tensorflow isn't trivial. Don't hesitate to ask further questions when you get confused by something
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47918524
tagged with: boto3
has comment: http://stackoverflow.com/comment/82819130
tagged with: amazon-systems-manager
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/82804828
possible better answer: http://stackoverflow.com/a/52437107
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/82804897
has title: AWS Run Command : Python Not Found
tagged with: python
has comment: http://stackoverflow.com/comment/82817057
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52437107
type: Question
has comment: http://stackoverflow.com/comment/82806586
has answer: http://stackoverflow.com/a/47930400
has answer: http://stackoverflow.com/a/47931019
accepted answer: http://stackoverflow.com/a/47931019
has body: I am using Boto3 SSM to run commands in my instance. When I run simple command such as echo hello world or mkdir abc it works fine and gives me expected output. but when I am trying to run python -V or any other python command. The output is python not found. But python is in my EC2 Instance which is running Ubuntu. When I manually check it works fine. Code: ssm = boto3.client('ssm' ) commands = ['python -V'] ssm.send_command(DocumentName="AWS-RunShellScript", Parameters={'commands': commands}, InstanceIds=['i-xxxxxxxxxxx'])

http://stackoverflow.com/q/47919009
has answer: http://stackoverflow.com/a/47919556
has comment: http://stackoverflow.com/comment/82830677
downvote count: 0
has title: Simplest Way to Remotely Interact With Python Script
score: 1
has answer: http://stackoverflow.com/a/47919934
type: Question
has answer: http://stackoverflow.com/a/47963630
has comment: http://stackoverflow.com/comment/82810891
possible better answer: http://stackoverflow.com/a/47919934
has body: I am setting up a Raspberri Pi on a network, which runs a Python script to control GPIO pins. I need to change a variable in this script from another computer on the network, via GUI, or command line. What is the simplest way possible to accoplish this (I am new to this)? Maybe a simple webpage hosted on the Pi somehow with buttons that control the variables? Thanks EDIT: Sorry, I was trying to keep it simple. The script will be started at boot and run continuously, monitoring a temperature, and cycling a heater on/off (via GPIO pins) to maintain the temperature stored in a "set_point" variable.
has comment: http://stackoverflow.com/comment/82806616
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/82810768
upvote count: 1
has answer: http://stackoverflow.com/a/47919530
favorite count: 0
has comment: http://stackoverflow.com/comment/82811140
has comment: http://stackoverflow.com/comment/82831280
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47944827
answer count: 5
tagged with: remote-access
tagged with: python
has answer: http://stackoverflow.com/a/47944827
type: AnsweredQuestion

http://stackoverflow.com/q/47990143
has comment: http://stackoverflow.com/comment/82949489
downvote count: 0
has comment: http://stackoverflow.com/comment/82949618
favorite count: 0
has body: I have below models.py and admin.py files in Django. I wanted to do 2 things Merge specs field of Environment and ItemObject and store into specs of Environment which I managed to do because I was able to figure out where to place the logic. (class AddEnvironmentDetailsInlineForm(forms.ModelForm)) I need to do the same for Estimate. I need to fetch the Environment.specs and Estimate.specs, merge the two and save in Estimate.specs The merge is like ItemObject -> Environment -> Estimate The challenge is that I cannot figure out where to put that logic for Estimate and Environment. Do I need to create a ModelForm for Estimate to achieve a merge? I am not clear on the logic here for the files (I am still learning the concepts in Django). If anyone could make me understand, it would be great. models.py class Estimate(CommonModel): ... class Environment(CommonModel): estimate = models.ForeignKey(Estimate,related_name='environments') logic = PythonCodeField(blank=True, null=True) ... class Item(CommonModel): ... class ItemTemplate(Item): pass class ItemObject(Item): pass class EnvironmentDetail(models.Model): environment = models.ForeignKey(Environment) item_name = models.CharField(max_length=200,blank=True) qty = models.FloatField('Qty') ... admin.py class CommonAdmin(admin.ModelAdmin): ... class EnvironmentInlineAdmin (admin.TabularInline): model = Environment ... formfield_overrides = { JSONField:{ 'widget':JSONEditor }, } ... def save_model(self, request, obj, *kwargs): if request.user.is_superuser or request.user==obj.author: obj.author.id=request.user.id super(EnvironmentInlineAdmin,self).save_model(request, obj, *kwargs) else: raise ValidationError("author must be you") class EstimateAdmin (CommonAdmin): inlines = [ EnvironmentInlineAdmin ] list_display = ('title', 'gp_code', 'otc_price','annual_price') admin.site.register(Estimate,EstimateAdmin) class EnvironmentDetailsInlineForm(forms.ModelForm): class Meta: model = EnvironmentDetail fields = ['item_name','qty'] s…
has title: Need to save estimate model in Django
tagged with: python
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: django
score: 2
has comment: http://stackoverflow.com/comment/82949261
has comment: http://stackoverflow.com/comment/82949891
has comment: http://stackoverflow.com/comment/82949545
has comment: http://stackoverflow.com/comment/82951132
type: Question
has comment: http://stackoverflow.com/comment/82949006

http://stackoverflow.com/comment/82730865
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47882307
has text: @ pschill @ Adrian Grzywaczewski Good!!! it works.

http://stackoverflow.com/comment/82713474
comment on: http://stackoverflow.com/q/47873828
score: 0
type: Comment
type: QuestionComment
has text: @MartijnPieters: If it's implemented as a namespace package then it can be sitting in the filesystem waiting for the install to happen.

http://stackoverflow.com/comment/82871997
comment on: http://stackoverflow.com/q/47948989
has text: You do not show a [mcve] of the issue. Hence nobody has any idea how you created this graph. You're thereby wasting the time of people trying to answer.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/47970467
type: Answer
has comment: http://stackoverflow.com/comment/82921199
accepted answer of: http://stackoverflow.com/q/47967872
answers question: http://stackoverflow.com/q/47967872
score: 0
type: AcceptedAnswer
has body: This error code is for Bad Request. you are trying to get three elements(comments, rating and recipe_id), but they are not present in the form, so flask throws a 400 error. what you could do is using hidden inputs to send that kind of information. Give your comment 1 2 3 4 5 but, you should design your code differently, so that the recipe_id is set based on the recipe you want to add comment's for. you can achieve that in numerous ways, but since that's not in the context of this question, i will leave that part alone. another way to do is, using a JS code(jquery post or AJAX) to post the data, and that way, you could have make a variable with the data you want, and then post it.

size
type: Tag
tag name: size
tags question: http://stackoverflow.com/q/47858950

http://stackoverflow.com/q/47990797
downvote count: 0
has answer: http://stackoverflow.com/a/47991449
possible better answer: http://stackoverflow.com/a/47991840
type: Question
tagged with: math
has comment: http://stackoverflow.com/comment/82953375
upvote count: 3
has comment: http://stackoverflow.com/comment/82953276
answer count: 3
tagged with: pandas
has title: pandas - cumulative median
has answer: http://stackoverflow.com/a/47991840
tagged with: accumulate
favorite count: 0
has comment: http://stackoverflow.com/comment/82951953
has comment: http://stackoverflow.com/comment/82952295
has answer: http://stackoverflow.com/a/47990817
accepted answer: http://stackoverflow.com/a/47990817
tagged with: python
type: AnsweredQuestion
score: 3
has body: I was wondering if there is any pandas equivalent to cumsum() or cummax() etc. for median: e.g. cummedian(). So that if I have, for example this dataframe: a 1 5 2 7 3 6 4 4 what I want is something like: df['a'].cummedian() which should output: 5 6 6 5.5
has comment: http://stackoverflow.com/comment/82952068

http://stackoverflow.com/a/47907139
has comment: http://stackoverflow.com/comment/82781641
downvote count: 1
score: 10
answers question: http://stackoverflow.com/q/47907032
has body: After id(300) is executed, no more references to 300 exist, so the id is freed. When you execute id(6), it gets that same chunk of memory and stores 6 instead. When you do -300 is 6, -300 and 6 are both referenced at the same time, so they won't have the same address anymore. If you keep references to both -300 and 6, this happens: &gt;&gt;&gt; a, b = -300, 6 &gt;&gt;&gt; id(a) some number &gt;&gt;&gt; id(b) some different number; 6 is still in the other memory address. Note: In CPython, numbers from -5 to 256 (I think) are cached, and will always have the same address, so this will not happen.
has comment: http://stackoverflow.com/comment/82781355
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47907032
type: Answer
upvote count: 11
has comment: http://stackoverflow.com/comment/82781360

http://stackoverflow.com/a/47930400
type: Answer
has comment: http://stackoverflow.com/comment/82830659
has body: boto3.ssm is not mean to be used as your quick shell injection tools. You need to install ssm-agent to your linux instance to perform more advanced triggering, vice-versa to windows.
answers question: http://stackoverflow.com/q/47918524
score: 0

http://stackoverflow.com/q/47998646
has comment: http://stackoverflow.com/comment/82965701
score: 0
has comment: http://stackoverflow.com/comment/82966460
has comment: http://stackoverflow.com/comment/82965644
has comment: http://stackoverflow.com/comment/82966103
answer count: 1
has comment: http://stackoverflow.com/comment/82965938
has body: I'm trying to connect to my mysql container but whenever I try to run mysql -uroot -p I always get bash: mysql: command not found but mysql is already installed in the docker container when I try to run pip3 freeze I get this result alembic==0.9.6 appdirs==1.4.3 bcrypt==3.1.4 certifi==2017.11.5 cffi==1.11.2 chardet==3.0.4 click==6.7 elasticsearch==5.5.1 flasgger==0.8.0 Flask==0.12.2 Flask-Cors==3.0.3 gevent==1.2.2 greenlet==0.4.12 idna==2.6 iso3166==0.8 itsdangerous==0.24 Jinja2==2.10 jsonschema==2.6.0 Mako==1.0.7 MarkupSafe==1.0 mistune==0.8.3 mock==2.0.0 mysqlclient==1.3.12 packaging==16.8 pbr==3.1.1 pybuilder==0.11.12 pycparser==2.18 pycrypto==2.6.1 pyparsing==2.2.0 python-dateutil==2.6.1 python-editor==1.0.3 PyYAML==3.12 redis==2.10.6 requests==2.18.4 six==1.11.0 SQLAlchemy==1.2.0 tblib==1.3.2 ujson==1.35 urllib3==1.21.1 validate-email==1.3 Werkzeug==0.13 As you can see mysqlclient is installed. If I try to check if mysql container is accessible inside my docker using ping. It's working properly and I was able to get a response. How do I connect now since it says bash: mysql: command not found -- UPDATE -- After running docker run I connected inside the docker container and run pip install --no-cache-dir -r requirements.txt and below is the output Now it says requirement already satisfied. I'm not sure but does this mean it already installed the package? Below is my dockerfile FROM python:3.5.2 ADD deployment /root/.ssh RUN chmod 700 /root/.ssh/id_rsa RUN ssh-keyscan -t rsa bitbucket.org &gt; /root/.ssh/known_hosts RUN mkdir -p /app ADD . /app WORKDIR /app RUN pip install --no-cache-dir -r requirements.txt WORKDIR /app/myproject CMD ["python", "./init.py", "-c", "config/config.yaml"]
has comment: http://stackoverflow.com/comment/82965731
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82965654
tagged with: python
has comment: http://stackoverflow.com/comment/82966551
has comment: http://stackoverflow.com/comment/82965711
has comment: http://stackoverflow.com/comment/82965868
tagged with: mysql
has answer: http://stackoverflow.com/a/48000168
has comment: http://stackoverflow.com/comment/82966315
type: Question
has comment: http://stackoverflow.com/comment/82965884
has comment: http://stackoverflow.com/comment/82965929
has comment: http://stackoverflow.com/comment/82965963
has comment: http://stackoverflow.com/comment/82966222
has comment: http://stackoverflow.com/comment/82966803
has comment: http://stackoverflow.com/comment/82965749
has title: Can't connect from docker using mysqlclient
has comment: http://stackoverflow.com/comment/82966175
has comment: http://stackoverflow.com/comment/82966814
tagged with: docker

http://stackoverflow.com/comment/83448981
type: Comment
comment on: http://stackoverflow.com/a/48159986
score: 0
type: AnswerComment
has text: You fix the aspect ratio using CALIB_FIX_ASPECT_RATIO. Also make sure you are not calibrating any distortion terms. The reason why is that you would get an unstable calibration because you can't calibrate distortion and K reliably with a single image.

http://stackoverflow.com/comment/82907316
comment on: http://stackoverflow.com/a/47964884
score: 0
type: AnswerComment
has text: Hi bunya, I've tried this but still no luck. My current code: `{% for value, text in form.area.field.choices %} {{ text }} {% endfor %}` and here is my CSS `.area_text{ font-family: 'Roboto', sans-serif; } #area_input{ border-radius: 0px; }` I can style the label (area_text) fine but I just cant manage to style the input checkboxes at all! Any help would be great!
type: Comment

http://stackoverflow.com/q/48012669
answer count: 1
has body: I'm building a DNN for a pattern recognition problem using TFLearn in Python 3.5. My input is shaped as a [50, 300], so roughly speaking my training set is a list of arrays each composed of 50 elements which are an array of 300 elements. All arrays I'm building are NumPy arrays. Here the code I'm using: training = np.array(training) # create train and test lists train_x = list(training[:,0]) print(train_x[0]) train_y = list(training[:,1]) # reset underlying graph data tf.reset_default_graph() mean = int(len(train_x[0])/len(train_y[0])) net = tflearn.input_data(shape=[None, 50, 300]) net = tflearn.fully_connected(net, mean) net = tflearn.fully_connected(net, mean) net = tflearn.fully_connected(net, len(train_y[0]), activation='softmax') net = tflearn.regression(net) # Define model and setup tensorboard model = tflearn.DNN(net, tensorboard_dir='tflearn_logs') # Start training (apply gradient descent algorithm) model.fit(train_x, train_y, show_metric=True) But the error I'm getting is the following: Traceback (most recent call last): File "/Users/Foo/Bar/test.py", line 82, in &lt;module&gt; model.fit(train_x, train_y, show_metric=True) File "/usr/local/lib/python3.5/site-packages/tflearn/models/dnn.py", line 215, in fit callbacks=callbacks) File "/usr/local/lib/python3.5/site-packages/tflearn/helpers/trainer.py", line 336, in fit show_metric) File "/usr/local/lib/python3.5/site-packages/tflearn/helpers/trainer.py", line 777, in _train feed_batch) File "/usr/local/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 778, in run run_metadata_ptr) File "/usr/local/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 954, in _run np_val = np.asarray(subfeed_val, dtype=subfeed_dtype) File "/usr/local/lib/python3.5/site-packages/numpy/core/numeric.py", line 531, in asarray return array(a, dtype, copy=False, order=order) ValueError: setting an array element with a sequence. Probably I'm not well defining shapes of the Network. How may I fix…
tagged with: tflearn
has title: TFLearn: Define correct dimension of DNN
score: 0
accepted answer: http://stackoverflow.com/a/48324421
tagged with: python
tagged with: tensorflow
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48324421
type: Question
tagged with: numpy

http://stackoverflow.com/comment/82878654
has text: Thank you, that was helpful.
score: 0
comment on: http://stackoverflow.com/q/47954324
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47999293
answer count: 1
has answer: http://stackoverflow.com/a/47999368
accepted answer: http://stackoverflow.com/a/47999368
score: 0
tagged with: pandas-groupby
tagged with: pandas
has comment: http://stackoverflow.com/comment/82967081
has title: Python PANDAS: Groupby Transform First Occurrence of Condition
has comment: http://stackoverflow.com/comment/82967275
tagged with: python
has body: I have dataframe in the following general format: customer_id,transaction_dt,product,price,units 1,2004-01-02 00:00:00,thing1,25,47 1,2004-01-17 00:00:00,thing2,150,8 2,2004-01-29 00:00:00,thing2,150,25 3,2017-07-15 00:00:00,thing3,55,17 3,2016-05-12 00:00:00,thing3,55,47 4,2012-02-23 00:00:00,thing2,150,22 4,2009-10-10 00:00:00,thing1,25,12 4,2014-04-04 00:00:00,thing2,150,2 5,2008-07-09 00:00:00,thing2,150,43 5,2004-01-30 00:00:00,thing1,25,40 5,2004-01-31 00:00:00,thing1,25,22 5,2004-02-01 00:00:00,thing1,25,2 I have it sorted by the relevant fields in ascending order. Now what I am trying to figure out how to check for a criteria inside a group and create a new indicator flag for only first time it occurs. As a toy example, I am trying to figure out something like this to start: conditions = ((df['units'] &gt; 20) | (df['price] &gt; 50) df['flag'] = df[conditions].groupby(['customer_id']).transform() Any help on how best to formulate this properly would be most welcome!
type: AnsweredQuestion
type: Question

http://stackoverflow.com/comment/82741396
has text: Use it like `^(?!.*myserver\.com)127\.0\.0\.1\s+\S*`
score: 0
comment on: http://stackoverflow.com/q/47887769
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47949093
answers question: http://stackoverflow.com/q/47949071
score: 3
has body: I found myself asking a similar question not too long ago. I had used PM2 for NodeJS apps and found Supervisor to more general and very similar. Very clean web interface to monitor process statuses remotely and the events API is very helpful for automatic notifications if processes fail.
upvote count: 3
has comment: http://stackoverflow.com/comment/82868286
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/82868184

http://stackoverflow.com/a/47952105
type: Answer
has comment: http://stackoverflow.com/comment/82874233
answers question: http://stackoverflow.com/q/47951956
has body: You can use figure. For example: plt.figure(figsize=(1, 1)) Creates an inch-by-inch image, which will be 80-by-80 pixels unless you also give a different dpi argument. You can change dpi with two possible ways Way 1: Passing it as an argument to the figure as the following:(i.e 300) plt.figure(figsize=(1, 1),dpi=300) Way 2:Passing it to savefig() plt.savefig("foo.png", dpi=300) Perfect Example
accepted answer of: http://stackoverflow.com/q/47951956
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/82874143

http://stackoverflow.com/q/47956930
has comment: http://stackoverflow.com/comment/82883259
type: UnansweredQuestion
score: -4
has title: Subset a list based on specific strings
has body: I'm reading in a file and assigning it the variable "input_kws". input_kws = open('words.txt','r') Contents of "input_kws" are: baseball basketball football tennis boxing volleyball I simply want to create a new list containing only words containing "ball".
type: Question
answer count: 2
downvote count: 4
upvote count: 0
has answer: http://stackoverflow.com/a/47956957
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/47956977
tagged with: python
tagged with: regex
tagged with: text

http://stackoverflow.com/q/47899122
tagged with: export
linked to: http://stackoverflow.com/q/5666056
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82765304
favorite count: 0
has answer: http://stackoverflow.com/a/47910115
has comment: http://stackoverflow.com/comment/82765463
has comment: http://stackoverflow.com/comment/82766273
tagged with: equivalent
has comment: http://stackoverflow.com/comment/82765160
tagged with: python
tagged with: wolfram-mathematica
has comment: http://stackoverflow.com/comment/82766665
has comment: http://stackoverflow.com/comment/82764861
has comment: http://stackoverflow.com/comment/82765066
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82766132
has body: My Professor sent me a Mathematica Notebook, where he plots a 2d contour and then extracts the contour as lines (i.e. a list of lists of coordinate-tuples). The specific code segment looks like this: xdiv = 0.05 zt = 1. lis = Table[SomeFunction[x, y, zt], {y, -xmax, xmax, xdiv}, {x, -xmax, xmax, xdiv}]; plot = ListContourPlot[lis, PlotLegends -&gt; Automatic, Contours -&gt; {0}, ContourShading -&gt; None]; lines = Cases[Normal@plot, Line[pts_, ___] :&gt; xdiv*pts, Infinity]; I do not fully understand how exactly the code does what it does and an I'm seeking help for an explanation. I want to write a similar code in python and understand how. Also I want to know if I can extract the lines without using the ContourPlot function. I am not particularly interested in plotting the contours, I only need a list of its lines. Edit: Rephrased the question. Also: matplotlib - extracting data from contour lines seems to explain how to achieve my goal in python. However, I don't really understand how it does what it does and judge if there is a better way, in terms of performance, to achieve it (I am dealing with very large lists, so this contour extraction seems like quite the bottleneck). I was looking for something more of an explanation to understand what exactly happens. The provided answer does really well at explaining the Mathematica code. I will read more into the matplotlib methods.
upvote count: 2
has comment: http://stackoverflow.com/comment/82787910
has title: Understanding Mathematica contour lines extraction
accepted answer: http://stackoverflow.com/a/47910115
type: Question
has comment: http://stackoverflow.com/comment/82783941

http://stackoverflow.com/comment/82800533
comment on: http://stackoverflow.com/a/47912114
score: 0
type: AnswerComment
type: Comment
has text: No problem. I'm glad it worked, and sorry for having given you some bad code.

http://stackoverflow.com/comment/82808257
score: 0
has text: No the lines only span a function so that's why they are disconnected. The minus sign pops up on indent for python. It has nothing to do with errors.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47919704

http://stackoverflow.com/q/47981691
type: Question
has title: REST API interacting with Spark
upvote count: 2
tagged with: hadoop
tagged with: apache-spark
answer count: 1
favorite count: 0
tagged with: rest
tagged with: python
tagged with: node.js
score: 2
has body: I am trying to connect my Spark context with REST API. So my flow is this, i send request from my UI- nodejs to REST API which need to interact with the spark context ( Spark job works above hive tables ) which contains the needed response and send it back to UI for display. Is there any way to achieve this ? UI &lt;->REST API&lt;-> Spark (HDFS)
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47981811

http://stackoverflow.com/q/47998420
has answer: http://stackoverflow.com/a/47998732
upvote count: 3
downvote count: 1
possible better answer: http://stackoverflow.com/a/47998732
has answer: http://stackoverflow.com/a/47998737
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82965256
has comment: http://stackoverflow.com/comment/82965627
has answer: http://stackoverflow.com/a/47998813
accepted answer: http://stackoverflow.com/a/47998737
has body: I'm pretty sure the answer to this lies in regular expressions but I'm not getting it right. I have a list of text. Within that text I'm parsing out a bunch of different things but I'm scratching my head in particular at telling certain numbers from one another. I have client numbers that are sequential but have gaps (1, 2, 4, 5.. 1900, 1901, 1905), I have year numbers (2001, 2015, 2016), and finally I have billed amounts (0.00, 43.24, 1,925.00, 10,324.95). I need to be able to tell the billed amounts, which include commas when the amount is $1,000 or more and always include two numbers to the right of the decimal, from year numbers, which don't use any commas and don't have a decimal point. The client numbers I can detect just by where they are located. I've been trying to do it by testing for a regular expression of: currency_matcher = re.compile('\d*[,]*\d*\d[.]\d*') if currency_matcher.search(line) != None: #assume currency I haven't specifically tried looking for the years yet but assumed I'd do a similar thing like: year_matcher = re.compile('\d\d\d\d') I've also considered using try and except but am just beginning that experimentation as I type this. Any help or suggestions are appreciated. EDIT: trying to add some clarity I have a text document that is broken into a python list like this: [ "1", "Alice Alwen", "12345 Oak Street", "Anytown, US 12345", "0.00", "123.45", "2007", "Pontiac", "2", "Bob Bobberson", "1919 Elm Road", "Metropolis, US 11111", "123.45", "0.00", "2016", "Sherman Tank", "2105", "Bradley Fighting Vehicle", "5", "Carl Carlson", "9854 Willow Way #1", "Gotham City, GA 34567", "1,001.00", "2,300.00", "2015", "Batmobile - used" ] I can always tell when the client ID is because it's the first thing. After the personal info there are two "currencies" in my example (there are four in my dataset but same idea). I'd like to be able to ID these and extract them. Towards the end of the row you will also see a year number associated with a vehicle. I …
has comment: http://stackoverflow.com/comment/82965728
type: Question
score: 2
has title: trying to use Python to tell numbers apart
favorite count: 0
answer count: 3
has comment: http://stackoverflow.com/comment/82965199
tagged with: python
tagged with: regex

http://stackoverflow.com/comment/82682687
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47858808
score: 0
has text: @Viviane, how do you check the written CSV?

http://stackoverflow.com/q/47917657
tagged with: python-3.x
has body: Why do I get in Python2 &gt;&gt;&gt; map(max,[1,2],[3,1]) [3, 2] and in Python3 &gt;&gt;&gt; map(max,[1,2],[3,1]) &lt;map object at 0x10c2235f8&gt; ? What should replace map(max,[1,2],[3,1]) in Python3 ? I read that one should use list comprehension in Python3 but &gt;&gt;&gt; [max(i,j) for i in [1,2] for j in [3,1]] [3, 1, 3, 2] does not give the desired result and neither do the variations that came to mind.
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/1303347
score: 1
has title: map a binary function over pairs of lists in Python 3
upvote count: 3
downvote count: 2
duplicate of: http://stackoverflow.com/q/1303347
type: Question
has answer: http://stackoverflow.com/a/47917686
has comment: http://stackoverflow.com/comment/82803427
answer count: 1
has comment: http://stackoverflow.com/comment/82831308
has comment: http://stackoverflow.com/comment/82803370
favorite count: 0
has comment: http://stackoverflow.com/comment/82811008

http://stackoverflow.com/q/47998156
has comment: http://stackoverflow.com/comment/82964663
has body: I wrote a program to list all the prime numbers less than a number the user inputs. When I run the program in PyCharm, the output is very nice: each number is properly situated on the line and no numbers are spread across two lines. However, when I run the program from the command line, the formatting gets weird, with numbers at the end of a row sometimes getting cut off. Here is my code: import prime_functions as pf number = int(input("Find primes up to what number? ")) # Save primes to a list. primes = pf.list_primes(number) for prime in primes[0:len(primes)-1]: print(prime, end=', ') print(primes[len(primes)-1]) # Print length of primes. print(f'Number of primes less than {number}: {len(primes)}') # Pause before exiting. input() The list_primes function simply checks whether each odd number from three to the user's number is prime and returns a list of all the primes it finds. What I would like to do ideally is print a small slice of the primes list on each line (say, five elements per line), but I can't think of how to do that without abandoning the generality of the program and using a bunch of for-loops. Are there any Python tricks out there that will help me?
tagged with: python
accepted answer: http://stackoverflow.com/a/47998481
answer count: 4
type: AnsweredQuestion
tagged with: formatting
tagged with: output
type: Question
has answer: http://stackoverflow.com/a/47998894
has answer: http://stackoverflow.com/a/47998874
score: 4
has answer: http://stackoverflow.com/a/47998481
possible better answer: http://stackoverflow.com/a/47998894
upvote count: 4
has comment: http://stackoverflow.com/comment/82964942
downvote count: 0
has answer: http://stackoverflow.com/a/47998645
favorite count: 0
has title: Python - Format a list so elements are not split between lines

http://stackoverflow.com/a/47890398
upvote count: 1
answers question: http://stackoverflow.com/q/47890071
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/82766095
has comment: http://stackoverflow.com/comment/82748305
has comment: http://stackoverflow.com/comment/82750790
score: 1
has comment: http://stackoverflow.com/comment/82750179
has body: the variable div is going to be completely empty. That's because your error handler assigned it the empty string. Please don't use subscripts, conditionals, and handlers in that way. It would be more natural to iterate over the results of select() with for, building up a result list (or string). Also, you should create soup = BeautifulSoup(html) just once, as that can be a fairly expensive operation, since it carefully parses a potentially long web page. With that, you could build up a list of HTML fragments with: images = [image for image in soup.select('div.large-image')] Or if for some reason you're not fond list comprehensions, you could equivalently write: images = [] for image in soup.select('div.large-image'): images.append(image) and then get the required html with div = '\n'.join(images).

http://stackoverflow.com/q/48014537
has comment: http://stackoverflow.com/comment/83000728
favorite count: 0
tagged with: python-3.x
type: Question
answer count: 2
tagged with: python
has body: There has been some back and forth between myself and the IT department of a company I recently began working regarding the installation of Python / Anaconda suite on my work PC. The IT department is making claims of security risks (with Anaconda) but I suspect it’s more of a matter of them not wanting to give me access. My suspicion is based, not on my IT knowledge, but due to the fact that I’ve used Anaconda at my last job with no issues. I’m hoping for some insight of enterprise risks (if any) associated with installation of Anaconda. To summarize the situation/my knowledge: • I am not a developer, nor do I come from an IT/enterprise risk background. I’ve used Python for analytics, data cleansing and report automation • Current and past companies are within the finance industry, i.e. confidential information lives on the network • I’m requesting Anaconda as opposed Anaconda Enterprise • I’m requesting Python version 3.6.4 I’m not trying to write-off IT’s concerns. What I’m trying to do is better understand the situation, educate myself and either alleviate their concerns or propose an alternative all parties can work with. So my questions are: Are their security threats associated with leveraging Anaconda? If so, what specifically? If the risk is too great, what are alternatives to simply installing the Anaconda Suite? Thanks
upvote count: 3
has answer: http://stackoverflow.com/a/48022958
downvote count: 1
tagged with: anaconda
possible better answer: http://stackoverflow.com/a/48015112
has answer: http://stackoverflow.com/a/48015112
tagged with: security
has title: Security Issues with Anaconda?
has comment: http://stackoverflow.com/comment/83000768
accepted answer: http://stackoverflow.com/a/48022958
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/82871572
score: 0
has text: Have a look at different questions on here like this [one](https://stackoverflow.com/a/42445265/6028443) and experiment different methods of getting the data you require. Extract that part away from your code and try to figure out that in isolation before bring it back in.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47950044

http://stackoverflow.com/q/47918564
has body: I have a bunch of Python objects, all defined independently. They can all be parent/children of one another. This relationship is materialized via the "children" property that each object has. It is a list, potentially empty. If I want to know the children of an object, i just have to do MyObject.children. Now I want to retrieve the parent: is there an elegant way of doing that? The only thing I can think of is to iterate over all my objects and check whether one contains MyObject in his children list.
type: UnansweredQuestion
tagged with: python
has title: Parents of python object
answer count: 0
has comment: http://stackoverflow.com/comment/82804930
type: Question
tagged with: parent-child
score: 0
has comment: http://stackoverflow.com/comment/82804983
has comment: http://stackoverflow.com/comment/82806101
has comment: http://stackoverflow.com/comment/82804938

http://stackoverflow.com/q/47964719
has answer: http://stackoverflow.com/a/47965430
score: -1
duplicate of: http://stackoverflow.com/q/5383623
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/82900729
favorite count: 0
tagged with: beautifulsoup
accepted answer: http://stackoverflow.com/a/47965430
has comment: http://stackoverflow.com/comment/82899233
answer count: 1
tagged with: python
has body: I am trying to get the value of a hidden input type. Even though it is empty now the value is generated later. I get the error "TypeError: 'NoneType' object is not subscriptable" when I run my code. This is the code on the website: &lt; input type="hidden" id="bb_device_id" name="bb_device_id" value="" &gt; I am using the following code to try and get the value: deviceId = soup.find('input', {'id': 'bb_device_id'})['value']
has comment: http://stackoverflow.com/comment/82900704
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82899498
has title: How do I get a value with a hidden input type using python 3?
downvote count: 1
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/5383623
has comment: http://stackoverflow.com/comment/82899361

http://stackoverflow.com/a/48017558
type: Answer
has comment: http://stackoverflow.com/comment/136105081
answers question: http://stackoverflow.com/q/48013449
downvote count: 0
score: 1
has body: The only alternative to using shapes.txt would be to use the stops along the route to define shapes. The laziest way would be to pick a single trip for that route, get the set of stops from stop_times.txt, and then get the corresponding stop locations from stops.txt. If you wanted or needed to, you could get a more complete picture by finding the unique ordered sets of stops among all of the trips on that route, and define a shape for each ordered set in the same way. Of course, these shapes would only be rough estimates because you don't have any information about the path taken by the vehicles between stops.
upvote count: 1

http://stackoverflow.com/q/47988810
downvote count: 0
tagged with: facebook-chatbot
has title: Use ngrok url as callback url for facebook webhook, but is recognized "not whitelisted"
accepted answer: http://stackoverflow.com/a/48566633
favorite count: 0
tagged with: pycharm
type: Question
has answer: http://stackoverflow.com/a/71156164
possible better answer: http://stackoverflow.com/a/48264998
tagged with: webhooks
has answer: http://stackoverflow.com/a/75842585
tagged with: python
has answer: http://stackoverflow.com/a/48264998
has comment: http://stackoverflow.com/comment/82946424
has body: My IDE is Pycharm. I want to test my app locally, so I run my service locally and use ngrok to expose my app to Internet. The url showed by ngrok is https://436cb7e9.ngrok.io But when I want to verify the facebook webhook callback url use this url above, it shows ERROR 2017-12-27 08:16:37,407 wsgi_server.py:329] Request Host 436cb7e9.ngrok.io not whitelisted. Enabled hosts are set(['localhost']) I ran the app well before, but I don't know why this time it shows an error. Could somebody gives me suggestion?
upvote count: 3
has answer: http://stackoverflow.com/a/48566633
answer count: 4
has comment: http://stackoverflow.com/comment/82970112
tagged with: facebook-webhooks
type: AnsweredQuestion
score: 3

http://stackoverflow.com/comment/82761309
score: 1
has text: No, that functionality is not part of Python format strings.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47897235

http://stackoverflow.com/a/47984382
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/47976765
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47976765
has body: I solved it with 3 steps: First, I created unique compound index: tasks.create_index([("start_time", pymongo.ASCENDING,), ("task_proxy", pymongo.ASCENDING)], unique=True) Then, I adjusted query to search only in index fields (covered query): all_tasks = tasks.find({ "$and": [{ "start_time": { "$gte": plan_date.astimezone(pytz.UTC), "$lt": plan_date.astimezone(pytz.UTC) + timedelta(hours=1) } }, { "task_proxy": px }] }, {"_id": 0, "start_time": 1, "task_proxy": 1}) Last (same code above), I increased the size of time queries from 1 minute to 1 hour, so I can do 1 database operation instead of 60. I can operate with most of the data inside Python script, so load on the database is much lower :) UPD: Rewrited 80% of code: I used 1 query for every order, now I use 1 query for every hour, find free time periods there, and pack orders in free cells (or move to another collection if not enough cells). Still using compound index and covered query, script exception time went from 15-17 seconds to 0.6.

http://stackoverflow.com/q/47906135
answer count: 1
has title: Calculate sum of overlapping timestamp differences and duplicate time
has comment: http://stackoverflow.com/comment/82780441
type: UnansweredQuestion
tagged with: python
tagged with: timestamp
type: Question
has body: I have a dataframe with two columns containing start and end timestamp of a session: 1 2017-12-04 05:26:15 2017-12-04 05:28:39 2 2017-12-04 05:26:31 2017-12-04 05:34:36 3 2017-12-04 05:28:44 2017-12-04 05:28:54 4 2017-12-04 05:29:05 2017-12-04 05:30:57 5 2017-12-04 05:31:04 2017-12-04 05:31:13 6 2017-12-04 05:31:06 2017-12-04 05:31:13 7 2017-12-04 05:31:26 2017-12-04 05:43:18 8 2017-12-04 05:33:31 2017-12-04 05:35:54 9 2017-12-04 05:34:12 2017-12-04 05:35:24 I need to calculate the sum of the differences (i.e. durations) of these sessions excluding duplicate time and duplicate time For example: consider sessions 7,8,9. Start at 05:31:26 (session 7) and end at 05:43:18 (session 7). But in between there are multiple sessions open. The result for 7,8,9 would be: Duration excluding duplicate time: 11 minutes 52 seconds Duplicate time: 2 minutes 23 seconds (session 8) + 1 minute 12 seconds (session 9) = 3 minutes 35 seconds How to achieve this in python?
score: 0
has comment: http://stackoverflow.com/comment/82779180
has answer: http://stackoverflow.com/a/47909514
has comment: http://stackoverflow.com/comment/82779974
tagged with: pandas

http://stackoverflow.com/q/47969852
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/47969896
type: UnansweredQuestion
has body: I have a Series : 350 0 254 1 490 0 688 0 393 1 30 1 and a dataframe : 0 outcome 0 350 1 1 254 1 2 490 0 3 688 0 4 393 0 5 30 1 The below code to count the total number of matches between the Series and the outcome column in the dataframe is what was intended. Is there any other better way besides the below? i=0 match=0 for pred in results['outcome']: if test.values[i] == pred: match+=1 i+=1 print match I tried using results['Survived'].eq(labels_test).sum() but the answer is wrong. And using lambda but the syntax is wrong.
tagged with: python
has answer: http://stackoverflow.com/a/47969895
type: Question
has title: Totalling the matching values of a dataframe column with Series values
tagged with: dataframe
score: 4
upvote count: 4

counter
tags question: http://stackoverflow.com/q/47951514
tag name: counter
tags question: http://stackoverflow.com/q/47993554
type: Tag

http://stackoverflow.com/comment/82935638
comment on: http://stackoverflow.com/a/47972023
has text: @Virureddy I'm sure you need to review what you are doing or your hive port and access.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/82767370
type: Comment
comment on: http://stackoverflow.com/a/47898840
score: 1
type: AnswerComment
has text: Neat, but it doesn't cope with duplicate items in `data_1`.

http://stackoverflow.com/comment/82829491
type: Comment
type: QuestionComment
has text: Can you show your code as it is difficult to work out what the problem is without seeing it.
comment on: http://stackoverflow.com/q/47930431
score: 0

http://stackoverflow.com/comment/82721876
has text: From the command line (not powershell) path to your virtualenv. Then try typing `Scripts\python.exe -m pip install appJar`. What happens?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47877726
score: 0

http://stackoverflow.com/comment/82947876
score: 0
type: Comment
type: QuestionComment
has text: now the question is correct, i forgot to write "=0" after key
comment on: http://stackoverflow.com/q/47989670

http://stackoverflow.com/q/48012349
has body: i am trying to convert the below pandas dataframe, pd.DataFrame({'PE': [115.45, 8], 'PE FY1': [11, 12], 'EV/Sales':[0.4, 1.9], 'EV/EBIT':[16, 9.8], 'EV/EBITDA': [10.8, 7.5]}) to an np.array but within multiple square brackets - as below - but have so far been unsuccesful. I am unsure of the correct name of this structure but need it in this for scikit learn. I the below works for what i am trying to do, just a matter of getting there. q = np.array([[[115.45,11.00,0.40,16.00,10.80]], [[8.00,12.00,1.90, 9.80,7.50]]]) whatever i try i either end up with normal brackets in the wrong place or IndexError: tuple index out of range as i run it through the regressor and tree interpretor - as below Latest_feature_values = pd.DataFrame({'PE': [115.45, 8], 'PE FY1': [11, 12], 'EV/Sales':[0.4, 1.9], 'EV/EBIT':[16, 9.8], 'EV/EBITDA': [10.8, 7.5]}) Latest_feature_values = np.array(Latest_feature_values.values)
upvote count: 2
tagged with: pandas
downvote count: 1
answer count: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48012543
accepted answer: http://stackoverflow.com/a/48012543
type: AnsweredQuestion
score: 1
type: Question
tagged with: numpy
has title: dataframe to np.array - IndexError: tuple index out of range

http://stackoverflow.com/q/47859999
has title: Sending data from a html non-input to Flask
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has answer: http://stackoverflow.com/a/47860099
type: AnsweredQuestion
tagged with: request.form
downvote count: 2
upvote count: 1
type: Question
tagged with: javascript
score: -1
tagged with: flask
accepted answer: http://stackoverflow.com/a/47860099
answer count: 1
favorite count: 0
has body: how can i send non-input data (like lists) from html to Flask. Data that i want to receive 1 Data that i want to receive 2 Data that i want to receive 3 with request.from i only receive the button informations in python, but i want the data from the list. What i have to do, that i can get the list-data?

http://stackoverflow.com/a/48011094
has comment: http://stackoverflow.com/comment/83016226
upvote count: 1
answers question: http://stackoverflow.com/q/48010839
downvote count: 0
has comment: http://stackoverflow.com/comment/83018224
type: Answer
score: 1
has body: With BeautifulSoup.select() method: ... for el in soup.select('li[data-vc-node-id="10"] a'): print(el) The output:

http://stackoverflow.com/q/47982949
has answer: http://stackoverflow.com/a/47984221
upvote count: 33
has comment: http://stackoverflow.com/comment/83376067
possible better answer: http://stackoverflow.com/a/47984334
has answer: http://stackoverflow.com/a/48089563
has answer: http://stackoverflow.com/a/47984334
has body: I'm looking for a simple way of parsing complex text files into a pandas DataFrame. Below is a sample file, what I want the result to look like after parsing, and my current method. Is there any way to make it more concise/faster/more pythonic/more readable? I've also put this question on Code Review. I eventually wrote a blog article to explain this to beginners. Here is a sample file: Sample text A selection of students from Riverdale High and Hogwarts took part in a quiz. This is a record of their scores. School = Riverdale High Grade = 1 Student number, Name 0, Phoebe 1, Rachel Student number, Score 0, 3 1, 7 Grade = 2 Student number, Name 0, Angela 1, Tristan 2, Aurora Student number, Score 0, 6 1, 3 2, 9 School = Hogwarts Grade = 1 Student number, Name 0, Ginny 1, Luna Student number, Score 0, 8 1, 7 Grade = 2 Student number, Name 0, Harry 1, Hermione Student number, Score 0, 5 1, 10 Grade = 3 Student number, Name 0, Fred 1, George Student number, Score 0, 0 1, 0 Here is what I want the result to look like after parsing: Name Score School Grade Student number Hogwarts 1 0 Ginny 8 1 Luna 7 2 0 Harry 5 1 Hermione 10 3 0 Fred 0 1 George 0 Riverdale High 1 0 Phoebe 3 1 Rachel 7 2 0 Angela 6 1 Tristan 3 2 Aurora 9 Here is how I currently parse it: import re import pandas as pd def parse(filepath): """ Parse text at given filepath Parameters ---------- filepath : str Filepath for file to be parsed Returns ------- data : pd.DataFrame Parsed data """ data = [] with open(filepath, 'r') as file: line = file.readline() while line: reg_match = _RegExLib(line) if reg_match.school: school = reg_match.school.group(1) if reg_match.grade: grade = reg_match.grade.group(1) grade = int(grade) if reg_match.name_score: value_type = reg_match.name_score.group(1) line = file.readline() while line.strip(): number, value = line.strip().split(',') value = value.strip() dict_of_data = { 'School': school, 'Grade': grade, 'Student number': number, value_type: value } data.append(dict_of_da…
tagged with: pandas
has title: How to parse complex text files using Python?
favorite count: 0
accepted answer: http://stackoverflow.com/a/47984221
answer count: 5
tagged with: python
tagged with: regex
tagged with: parsing
type: AnsweredQuestion
score: 32
has answer: http://stackoverflow.com/a/75462027
downvote count: 1
has answer: http://stackoverflow.com/a/47992112
type: Question

http://stackoverflow.com/q/47978366
has body: I am having below python code which will save the slider value in to the text file. Actually my intention is to get the value from kivy file and have to save it in the text-file. But unfortunately i am not getting exactly how to do it. Separate file for kivy from that value must be sent to python file. In python file those values have to saved. Below is the link of code for the python. https://docs.google.com/document/d/1VPTcXyWU1w9LbKypZ95Db3PkhDwvqDSNp6iUE19WWFo/edit?usp=sharing
downvote count: 2
type: Question
has title: How to make separate kivy file for the following python code
upvote count: 0
score: -2
has answer: http://stackoverflow.com/a/47993140
answer count: 1
has comment: http://stackoverflow.com/comment/82954431
favorite count: 0
type: UnansweredQuestion
tagged with: slider
tagged with: python
tagged with: kivy
has comment: http://stackoverflow.com/comment/82943706
has comment: http://stackoverflow.com/comment/82939076

http://stackoverflow.com/a/47882783
score: 3
downvote count: 1
has body: Yes i got the answer. This error occurred because i didn't installed django-wkhtmltopdf. installed >> `pip install django-wkhtmltopdf I hope this answer will help to resolve the similar error.
answers question: http://stackoverflow.com/q/47882242
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/86360268

http://stackoverflow.com/q/47934119
answer count: 1
has title: Python: performance of finding divisors
tagged with: python
has body: Benchmarking these functions: def divisors_optimized(number): square_root = int(math.sqrt(number)) for divisor in range(1, square_root): if number % divisor == 0: yield divisor yield number / divisor if square_root ** 2 == number: yield square_root def number_of_divisors_optimized(number): count = 0 square_root = int(math.sqrt(number)) for divisor in range(1, square_root): if number % divisor == 0: count += 2 if square_root ** 2 == number: count += 1 return count You can see that the basic structure is identical in both. Benchmark code: number = 9999999 for i in range(10): print(f"iteration {i}:") start = time.time() result = list(utils.divisors_optimized(number)) end = time.time() print(f'len(divisors_optimized) took {end - start} seconds and found {len(result)} divisors.') start = time.time() result = utils.number_of_divisors_optimized(number) end = time.time() print(f'number_of_divisors_optimized took {end - start} seconds and found {result} divisors.') print() Output: iteration 0: len(divisors_optimized) took 0.00019598007202148438 seconds and found 12 divisors. number_of_divisors_optimized took 0.0001919269561767578 seconds and found 12 divisors. iteration 1: len(divisors_optimized) took 0.00019121170043945312 seconds and found 12 divisors. number_of_divisors_optimized took 0.00020599365234375 seconds and found 12 divisors. iteration 2: len(divisors_optimized) took 0.000179290771484375 seconds and found 12 divisors. number_of_divisors_optimized took 0.00019049644470214844 seconds and found 12 divisors. iteration 3: len(divisors_optimized) took 0.00019025802612304688 seconds and found 12 divisors. number_of_divisors_optimized took 0.00020170211791992188 seconds and found 12 divisors. iteration 4: len(divisors_optimized) took 0.0001785755157470703 seconds and found 12 divisors. number_of_divisors_optimized took 0.00017905235290527344 seconds and found 12 divisors. iteration 5: len(divisors_optimized) took 0.00022721290588378906 seconds and found 12 divisors. numb…
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47934239
has comment: http://stackoverflow.com/comment/82837691
score: 0
has comment: http://stackoverflow.com/comment/82837577
tagged with: execution-time
type: Question
tagged with: python-3.6
accepted answer: http://stackoverflow.com/a/47934239
tagged with: performance-testing

http://stackoverflow.com/comment/82813288
score: 1
has text: Add please your HTML.
type: QuestionComment
comment on: http://stackoverflow.com/q/47919975
type: Comment

http://stackoverflow.com/q/47863031
score: 1
favorite count: 0
tagged with: beautifulsoup
type: Question
answer count: 2
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82691363
has comment: http://stackoverflow.com/comment/82691700
accepted answer: http://stackoverflow.com/a/47893174
has title: How to extract from multiple tags and group the data together using BS4?
has comment: http://stackoverflow.com/comment/82691280
downvote count: 0
has comment: http://stackoverflow.com/comment/82690984
possible better answer: http://stackoverflow.com/a/47864326
has answer: http://stackoverflow.com/a/47893174
has body: I have extracted data between span tags based on its class, from a webpage. But at times, the webpage splits a line into multiple fragments and stores it in consecutive tags. All the children span tags have the same class name. Following is the HTML snippet: &lt;p class="Paragraph SCX"&gt; &lt;span class="TextRun SCX"&gt; &lt;span class="NormalTextRun SCX"&gt; This week &lt;/span&gt; &lt;/span&gt; &lt;span class="TextRun SCX"&gt; &lt;span class="NormalTextRun SCX"&gt; &amp;nbsp;(12/ &lt;/span&gt; &lt;/span&gt; &lt;span class="TextRun SCX"&gt; &lt;span class="NormalTextRun SCX"&gt; 11 &lt;/span&gt; &lt;/span&gt; &lt;span class="TextRun SCX"&gt; &lt;span class="NormalTextRun SCX"&gt; &amp;nbsp;- 12/1 &lt;/span&gt; &lt;/span&gt; &lt;span class="TextRun SCX"&gt; &lt;span class="NormalTextRun SCX"&gt; 7 &lt;/span&gt; &lt;/span&gt; &lt;span class="TextRun SCX"&gt; &lt;span class="NormalTextRun SCX"&gt; ): &lt;/span&gt; &lt;/span&gt; &lt;span class="EOP SCX"&gt; &amp;nbsp; &lt;/span&gt; &lt;/p&gt; From the above HTML snippet, I need to extract only the innermost span data. Python code to extract data using BS4: for data in elem.find_all('span', class_="TextRun"): a = data.find('span').contents[0] a = a.string.replace(u'\xa0', '') print (a) events_parsed_thisweek.append(a) This code results in each data being separately printed as separate entity. Required Output: This Week ((12/11 - 12/17): Any idea how to combine these span tag data together? Thanks!
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47864326
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/comment/82980132
has text: May I unpack the nightly package over my 5.10.0 installation? And at which server the IRC channel is?
comment on: http://stackoverflow.com/a/48002867
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/82690677
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47862859
has text: i've been tried this. but the result is single word. And i want to join one person name. If i try to join this, i cant specify the other names
type: Comment

http://stackoverflow.com/q/47874623
tagged with: timeit
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47874810
has body: In the future I'll write multiple small scripts in Python 3 which I want to time. One way would be to write every script like this: # functions definitions go here if __name__ == '__main__': import time start = time.time() # my code end = time.time() print("This script took {} seconds to execute".format(end - start)) But I would have to write this into every single of these scripts. What would be the best way to time my script without including this code every single time (without losing accuracy - I'm aware of time ./script.py)?
upvote count: 3
has title: Time multiple python3 scripts
type: Question
score: 3
has comment: http://stackoverflow.com/comment/82714667
has answer: http://stackoverflow.com/a/47874969
possible better answer: http://stackoverflow.com/a/47874969
answer count: 2
has answer: http://stackoverflow.com/a/47874810
downvote count: 0
linked to: http://stackoverflow.com/q/20308567
favorite count: 0
tagged with: python-3.x
tagged with: time
linked to: http://stackoverflow.com/q/30306099
has comment: http://stackoverflow.com/comment/82714601
tagged with: python
has comment: http://stackoverflow.com/comment/82714687

http://stackoverflow.com/comment/82967027
score: 0
type: Comment
type: QuestionComment
has text: Yeah I was downloading the Microsoft Visual C++ Redistributable for Visual Studio 2017, my bad. I understand what the difference is now :) So when I go to this link (https://www.visualstudio.com/downloads/#build-tools-for-visual-studio-2017) would I download Free Visual Studio (on the top right corner of the page) or Visual Studio Community 2017 since it has the IDE? They all come under the Build Tools Title so I wasn't sure. Or is it a different download?
comment on: http://stackoverflow.com/q/47872603

http://stackoverflow.com/q/47861189
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/47861842
has comment: http://stackoverflow.com/comment/82688695
has title: pandas grouping data frame - python
tagged with: python
has body: I have this dataset, PRODUCT_ID SALE_DATE SALE_PRICE PROVIDER 1 01/02/16 25 1 1 02/10/16 60 1 1 01/11/16 63 2 1 09/10/16 65 3 2 11/11/15 54 1 2 13/01/16 34 2 3 19/05/14 45 1 3 15/10/15 38 1 3 16/06/14 53 2 3 18/10/15 58 2 This is a combined dataset, data provided by different providers, there is no common identifier for each sale. The issue here is each data provider will have slightly different date and price for each sale. So I am trying to group them together as single sale with a group id. So the business logic here is data provider 1 is the first to get sale data, so for a product id, if the sale date from provider 2 or 3 is within 1 month time and the price is within 10$ difference (more or less), we consider them as same sale, else it will be considered as different sale. So, the output should look like, PRODUCT_ID SALE_DATE SALE_PRICE PROVIDER SALE_GROUP_ID 1 01/02/16 25 1 1 1 02/10/16 60 1 2 1 01/11/16 63 2 2 1 09/10/16 65 3 2 2 11/11/15 54 1 3 2 13/01/16 34 2 4 3 19/05/14 45 1 5 3 15/10/15 38 1 6 3 16/06/14 53 2 5 3 18/10/15 58 2 7 How do I achieve this in pandas, can someone help please? Thanks.
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/82688398
has comment: http://stackoverflow.com/comment/82688418
has comment: http://stackoverflow.com/comment/82688670
upvote count: 1
type: Question
tagged with: pandas-groupby
tagged with: pandas
has answer: http://stackoverflow.com/a/47861842

http://stackoverflow.com/q/47942861
has body: Let's consider the dataset of House prices from this example. I have the entire dataset stored in the housing variable: housing.shape (20640, 10) I also have done a OneHotEncoder encoding of one dimensions and get housing_cat_1hot, so housing_cat_1hot.toarray().shape (20640, 5) My target is to join the two variables and store everything in just one dataset. I have tried the Join with index tutorial but the problem is that the second matrix haven't any index. How can I do a JOIN between housing and housing_cat_1hot? &gt;&gt;&gt; left=housing &gt;&gt;&gt; right=housing_cat_1hot.toarray() &gt;&gt;&gt; result = left.join(right) Traceback (most recent call last): File "", line 1, in result = left.join(right) File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/pandas/core/frame.py", line 5293, in join rsuffix=rsuffix, sort=sort) File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/pandas/core/frame.py", line 5323, in _join_compat can_concat = all(df.index.is_unique for df in frames) File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/pandas/core/frame.py", line 5323, in can_concat = all(df.index.is_unique for df in frames) AttributeError: 'numpy.ndarray' object has no attribute 'index'
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/47943321
has comment: http://stackoverflow.com/comment/82855402
answer count: 3
has title: Join one dataset and the result of OneHotEncoder in Pandas
tagged with: pandas
possible better answer: http://stackoverflow.com/a/47943762
accepted answer: http://stackoverflow.com/a/47943321
tagged with: python
has answer: http://stackoverflow.com/a/47943762
favorite count: 0
tagged with: one-hot-encoding
upvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47945232
tagged with: join
score: 1

http://stackoverflow.com/comment/129937787
comment on: http://stackoverflow.com/q/47998552
has text: I've done three strange things: add `/` in the end of the `[core] dags_folder = ...` settings in the `airflow.cfg`. Also, I've done `chmod 777` to the `__init__.py` file in the `dags` folder. And reboot the system. After these three steps airflow starts working IDK why. Maybe the thing was only in rebooting.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82965728
comment on: http://stackoverflow.com/q/47998420
type: QuestionComment
type: Comment
has text: @Tai That's is correct. I need to be able to tell the "1,111.11" and "11.11" from the "1111".
score: 0

http://stackoverflow.com/comment/82923609
type: Comment
comment on: http://stackoverflow.com/q/47977251
score: 0
type: QuestionComment
has text: Please read https://www.python.org/dev/peps/pep-0484/ to see what's the whole purpose of the type hinting in python. All you're doing seems to be in a contradict with the aforementioned PEP. Also, note that you can simply define your custom types in a separate module and just import them in current module and use them as type hints.

http://stackoverflow.com/q/47975115
has comment: http://stackoverflow.com/comment/82923074
has comment: http://stackoverflow.com/comment/82927945
type: UnansweredQuestion
tagged with: python
tagged with: opencv
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83004921
has comment: http://stackoverflow.com/comment/82944935
has answer: http://stackoverflow.com/a/47976941
has title: Morphing Operation in OpenCV Python
has comment: http://stackoverflow.com/comment/82926390
type: Question
upvote count: 2
tagged with: numpy
linked to: http://stackoverflow.com/q/47667238
linked to: http://stackoverflow.com/q/47973238
answer count: 1
linked to: http://stackoverflow.com/q/41149763
has body: I have the following image bearing handwritten text and lines of the page. I want to extract to remove the lines from the image, so that only the handwritten text is left. I tried implementing it, using opencv in Python. But, I don't get the best results. Please help! import numpy as np import cv2 image = cv2.imread('image.jpg') gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) (gray,50,150,apertureSize = 3) cv2.imwrite('edges-50-150.jpg',edges) minLineLength=100 lines = cv2.HoughLinesP(image=edges,rho=1,theta=np.pi/180, threshold=100,lines=np.array([]), minLineLength=minLineLength,maxLineGap=80) a,b,c = lines.shape for i in range(a): x = lines[i][0][0] - lines [i][0][2] y = lines[i][0][1] - lines [i][0][3] if x!= 0: if abs(y/x) &lt;1: cv2.line(gray, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (255, 255, 255), 1, cv2.LINE_AA) se = cv2.getStructuringElement(cv2.MORPH_ELLIPSE , (3,3)) gray = cv2.morphologyEx(gray, cv2.MORPH_CLOSE, se) cv2.imwrite('houghlines.jpg', gray) cv2.imwrite('another.png', gray)
favorite count: 0

http://stackoverflow.com/comment/82958096
type: AnswerComment
comment on: http://stackoverflow.com/a/47993208
type: Comment
has text: Thanks, it seems that I reduced the code too much. Please consider the edited version of my question.
score: 0

http://stackoverflow.com/comment/82905179
score: 0
comment on: http://stackoverflow.com/q/47967872
type: Comment
type: QuestionComment
has text: The problem will be with the server side code.

http://stackoverflow.com/q/47861616
favorite count: 0
tagged with: django
tagged with: python
has title: What is a clean way of mocking multiple methods on a class in python?
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/82688399
tagged with: unit-testing
type: Question
has answer: http://stackoverflow.com/a/47862302
has comment: http://stackoverflow.com/comment/82688445
accepted answer: http://stackoverflow.com/a/47862302
tagged with: mocking
score: 2
answer count: 1
has body: When writing tests I am often faced with the needed to mock several class methods. Currently I am doing this by nesting with statements contain the mock references e.g. from ... import A def test_sample(self) instance = A() with mock(A, 'function_1', return_value=1): with mock(A, 'function_2', return_value=2): with mock(A, 'function_3', return_value=3): assert A.function_4, 10 Is there a neater / recommended way of doing this? It would be nice to be able to remove several nested calls! During this process there may or may not be other methods on the class that are not mocked.
downvote count: 0

http://stackoverflow.com/a/47876477
has comment: http://stackoverflow.com/comment/82760736
type: Answer
has body: Could we see the gpx file, where the errors occurs? I tried the file https://github.com/tkrajina/gpxpy/blob/master/test_files/cerknicko-jezero-no-creator.gpx with your codesnippet import gpxpy def parsegpx(): points2 = list() with open('cerknicko-jezero-no-creator.gpx','r') as gpxfile: gpx = gpxpy.parse(gpxfile) for track in gpx.tracks: for segment in track.segments: for point in segment.points: dict = {'Timestamp': point.time, 'Latitude': point.latitude, 'Longitude': point.longitude, 'Elevation': point.elevation } points2.append(dict) print(points2) if __name__ == '__main__': parsegpx() and get correct results: [{'Timestamp': datetime.datetime(2010, 8, 5, 14, 23, 59), 'Elevation': 542.320923, 'Latitude': 45.772175035, 'Longitude': 14.357659249}, {'Timestamp': datetime.datetime(2010, 8, 5, 14, 25, 8), 'Elevation': 550.972656, 'Latitude': 45.772089791, 'Longitude': 14.357567383}, {'Timestamp': datetime.datetime(2010, 8, 5, 14, 26, 36), 'Elevation': 553.856689, 'Latitude': 45.772063639, 'Longitude': 14.357461184}, {'Timestamp': datetime.datetime(2010, 8, 5, 14, 26, 46), 'Elevation': 555.779297, 'Latitude': 45.772002535, 'Longitude': 14.357343167}, {'Timestamp': datetime.datetime(2010, 8, 5, 14, 26, 56), 'Elevation': 555.779297, 'Latitude': 45.771906478, 'Longitude': 14.357355237}, {'Timestamp': datetime.datetime(2010, 8, 5, 14, 27, 5), 'Elevation': 555.298584, 'Latitude': 45.771813104, 'Longitude': 14.357374264}, {'Timestamp': datetime.datetime(2010, 8, 5, 14, 27, 14), 'Elevation': 553.856689, 'Latitude': 45.771737499, 'Longitude': 14.357434446}, {'Timestamp': datetime.datetime(2010, 8, 5, 14, 27, 28), 'Elevation': 552.414551, 'Latitude': 45.77164907, 'Longitude': 14.357447689}, {'Timestamp': datetime.datetime(2010, 8, 5, 14, 27, 46), 'Elevation': 551.934082, 'Latitude': 45.771551002, 'Longitude': 14.35746965}, {'Timestamp': datetime.datetime(2010, 8, 5, 14, 27, 55), 'Elevation': 552.895264, 'Latitude': 45.771471541, 'Longitude': 14.357517259}, {'Timestamp': datetime.…
has comment: http://stackoverflow.com/comment/82719638
has comment: http://stackoverflow.com/comment/82719797
has comment: http://stackoverflow.com/comment/82729581
answers question: http://stackoverflow.com/q/47875819
score: 0

http://stackoverflow.com/comment/82832390
type: QuestionComment
has text: @kindall: Descriptor `__get__` methods are invoked when the descriptor is accessed through the class, but `property.__get__` doesn't invoke the getter in that case.
score: 1
comment on: http://stackoverflow.com/q/47931700
type: Comment

http://stackoverflow.com/q/47940753
downvote count: 3
upvote count: 1
tagged with: coordinates
has comment: http://stackoverflow.com/comment/82850868
type: Question
accepted answer: http://stackoverflow.com/a/47941880
has comment: http://stackoverflow.com/comment/82850807
has comment: http://stackoverflow.com/comment/82850759
has body: I need to find the co-ordinates (lat/long) nearer to some other co-ordinate by some percentage of the distance between those two co-ordinates. Example: location1 = (32.7991094663, -117.234719251) location2 = (32.7094778234, -117.136413578) # find a new location closer by 60% from location1 than location2 find_closer_location(location1, location2, 60) for calculating distance i am using below algo from math import radians, cos, sin, asin, sqrt def haversine(lon1, lat1, lon2, lat2): # convert decimal degrees to radians lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2 c = 2 * asin(sqrt(a)) km = 6371 * c return km
has comment: http://stackoverflow.com/comment/82850693
tagged with: python-2.7
has title: Generate lat long along a line
answer count: 2
has answer: http://stackoverflow.com/a/47940840
favorite count: 0
possible better answer: http://stackoverflow.com/a/47940840
has answer: http://stackoverflow.com/a/47941880
has comment: http://stackoverflow.com/comment/82850831
tagged with: python
score: -2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82850963

http://stackoverflow.com/q/47980322
has body: I am working on deep learning. I am using Keras with tensorflow backend, and I have 36980 images to train. I want to use VGG16, so I resized all of them to (224*224) size. So the size of the train array is around 22GB (36980*224*224*3*4 bytes). When I try to load this amount data into a numpy array, python shows MemoryError. I have thought of splitting the training set into 10 pieces and train my model on only one of such piece at a time. Is there any better approach to solve this problem? I am using Python 3 (64 bit version). N.B. To get a good accuracy, I need as large image as possible, so I can't resize them to a smaller size. Moreover, it's necessary to use RGB images here. No fit_generator() solution please. A model trained using fit_generator() behaves abnormally while predicting, at least as far as I have seen.
has comment: http://stackoverflow.com/comment/82941814
answer count: 0
tagged with: out-of-memory
linked to: http://stackoverflow.com/q/47979861
has comment: http://stackoverflow.com/comment/82933407
type: UnansweredQuestion
has title: Any better approach to solve MemoryError?
tagged with: python
has comment: http://stackoverflow.com/comment/82932117
has comment: http://stackoverflow.com/comment/82933874
has comment: http://stackoverflow.com/comment/82932923
tagged with: tensorflow
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82929541
tagged with: keras
score: 0

http://stackoverflow.com/a/47924582
upvote count: 1
downvote count: 0
has body: You can use dict comprehension: rsId = [v for item in op['key2']['skey2']['sskey1'] for k, v in item.items() if k == 'sid']
answers question: http://stackoverflow.com/q/47924481
type: Answer
score: 1

http://stackoverflow.com/q/47892561
has comment: http://stackoverflow.com/comment/82751736
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82754851
tagged with: python
linked to: http://stackoverflow.com/q/12413649
has comment: http://stackoverflow.com/comment/82755788
answer count: 0
upvote count: 3
has comment: http://stackoverflow.com/comment/82752561
has comment: http://stackoverflow.com/comment/82751602
has comment: http://stackoverflow.com/comment/82752659
has title: PIL.Image Closing error using Matplotlib imread()
type: Question
score: 3
tagged with: python-imaging-library
tagged with: matplotlib
has body: I'm using imread() from the matplotlib.pyplot library because I want to plot my scatter plots on top of an image: import matplotlib.pyplot as plt import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) model_image = plt.imread('data/img1.jpg') Everything works fine. However, when I use the logger of the standard python lib, it prints a DEBUG error: DEBUG:PIL.Image:Error closing: 'NoneType' object has no attribute 'close' This bothers me. Am I doing something wrong, our is it matplotlib fault? FYI matplotlib version: 2.1.0
downvote count: 0
has comment: http://stackoverflow.com/comment/82756006

http://stackoverflow.com/q/48002981
tagged with: sentiment-analysis
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/82974146
has comment: http://stackoverflow.com/comment/82974184
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82974191
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/82974458
has title: How to print words and their frequency in a csv file?
tagged with: twitter
has body: I have a code which creates a bag of words from tweets and forms matrix of their frequency. I want to create a csv file which will have each word in my dictionary as column header and the rows will be the frequency of the word in each tweet. Something like this: Word1 Word2 ..... Wordn Tweet1 1 0 ..... 0 Tweet2 0 0 ..... 1 Tweetn 0 1 ..... 0 But this format is not being achieved by my code, it is still giving me only the dictionary format. I am building a training dataset for svm. code : import operator from collections import defaultdict from collections import Counter from sklearn.feature_extraction.text import CountVectorizer import pandas as pd import json with open('Twidb13.txt', 'w') as file: file.write(json.dumps(sorted_words)) file.write(count_vect.fit_transform(df.Text).todense()) I have words in sorted form as this [["all", 0], ["cats", 1], ["in", 2], ["my", 3], ["row", 4], ["zzzpositive", 5]] and their frequencies as separately in a matrix format like this [[1 1 1 1 1 1]]. I want to combine these two.
type: Question
score: 0

http://stackoverflow.com/a/47898298
upvote count: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47897997
has body: You can use np.einsum to do this operation. An example with random values: a = np.arange(4096.).reshape(4,4,256) b = np.arange(32768.).reshape(128,256) c = np.einsum('ijk,lk-&gt;ijl',a,b) print(c.shape) Here, the subscripts argument is: ijk,lk-&gt;ijl From your requirement, i=4, j=4, k=256, l=128 The comma separates the subscripts for two operands, and the subscripts state that the multiplication should be performed over the last subscript in each tensor (the subscript k which is common to both the tensors). The tensor subscript after the -&gt; states that the resultant tensor should have the shape (i,j,l). Now depending on the type of operation you are performing, you might have to retain this subscript or change this subscript to jil, but the rest of the subscripts remains the same.
answers question: http://stackoverflow.com/q/47897997
downvote count: 0
score: 1

http://stackoverflow.com/comment/82785877
has text: Sorry @Zinki I misunderstood the question at first. I just rewrote my answer from scratch. Hopefully it's more useful for you now.
comment on: http://stackoverflow.com/a/47909086
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/82826261
score: 0
type: QuestionComment
type: Comment
has text: have you looked at pandas dataframes in python?
comment on: http://stackoverflow.com/q/47928754

http://stackoverflow.com/comment/82994685
score: 0
type: Comment
type: QuestionComment
has text: @nicoguaro Can you give me some link where I can find how to do it??
comment on: http://stackoverflow.com/q/47963797

http://stackoverflow.com/q/47930345
has comment: http://stackoverflow.com/comment/82829435
has comment: http://stackoverflow.com/comment/82829324
has body: I'm a bit of noob with pandas and I'm trying to perform some calculations and modifications on parts of a masked dataframe using apply. The part I want to operate on is defined by my mask and I don't want to modify any non-masked values. The thing is that I have no idea what is the proper way to put the result of the apply call on the masked dataframe back where it belongs in the original dataframe (or a copy of it, doesn't matter). Here is a toy example of what I'm struggling with, I will try to make all values in the A column negative using a mask and apply: import pandas as pd import numpy as np def make_df(): np.random.seed(4) df = pd.DataFrame(np.random.randn(5, 2),columns=["A","B"]) return df df = make_df() mask = (df["A"]&gt;0) print(df) A B 0 0.050562 0.499951 1 -0.995909 0.693599 2 -0.418302 -1.584577 3 -0.647707 0.598575 4 0.332250 -1.147477 The expected result is this : A B 0 -0.050562 0.499951 1 -0.995909 0.693599 2 -0.418302 -1.584577 3 -0.647707 0.598575 4 -0.332250 -1.147477 What I hoped would work was this : df = make_df() df[mask]["A"] = df[mask]["A"].apply(lambda v: -v) print(df) A B 0 0.050562 0.499951 1 -0.995909 0.693599 2 -0.418302 -1.584577 3 -0.647707 0.598575 4 0.332250 -1.147477 But it fails with pandas warning me that df[mask]["A"] is a copy not a view so modifications on it do not affect df.
accepted answer: http://stackoverflow.com/a/47930367
possible better answer: http://stackoverflow.com/a/47930434
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47930434
has comment: http://stackoverflow.com/comment/82829329
has title: Inplace operation on masked dataframe
type: AnsweredQuestion
score: 1
tagged with: dataframe
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47930367
downvote count: 0
favorite count: 0
tagged with: pandas

atomic
type: Tag
tag name: atomic
tags question: http://stackoverflow.com/q/47946202

http://stackoverflow.com/a/47922488
answers question: http://stackoverflow.com/q/47922235
has body: A simple for loop solution would be A = [{"name":"john","age":40}, {"name":"john","age":45}, {"name":"sam","age":10}, {"name":"sam","age":11}, {"name":"mark","age":50}] res = {} for i in A: if i['name'] not in res: res[i['name']] = i['age'] else: if res[i['name']] &lt; i['age']: res[i['name']] = i['age'] print res Result: {'john': 45, 'sam': 11, 'mark': 50}
type: Answer
has comment: http://stackoverflow.com/comment/82812642
has comment: http://stackoverflow.com/comment/82813009
score: 2
downvote count: 1
has comment: http://stackoverflow.com/comment/82814241
upvote count: 3

http://stackoverflow.com/comment/82790738
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47904669
has text: Sorry,completely confused. Actually both row.get("C") & row.get('C') are giving me same thing.Kindly post your code below this post.My requirement is if it's matching with column C I will able to print Hello & if not matching it won't print anything. Or if you want then I can create a separate thread
type: AnswerComment

http://stackoverflow.com/a/47938516
has body: bs4 stores tag attributes in a dictionary so you can select them by name. for kvart in kvarts[0].find_all('option'): print kvart['data-url-alias'], kvart['value'] As mentioned by Evyatar Meged in the comments this will raise a KeyError if a key doesn't exist, so if you're not sure about it use the .get method. for kvart in kvarts[0].find_all('option'): print kvart.get('data-url-alias'), kvart.get('value') dict.get returns None if a key doesn't exist (or you can set a default value)
has comment: http://stackoverflow.com/comment/102100610
has comment: http://stackoverflow.com/comment/82846035
upvote count: 6
has comment: http://stackoverflow.com/comment/82846081
type: Answer
has comment: http://stackoverflow.com/comment/102100703
score: 6
answers question: http://stackoverflow.com/q/47938299
downvote count: 0

http://stackoverflow.com/comment/82886693
comment on: http://stackoverflow.com/a/47958689
type: Comment
has text: @coldspeed if you can help me find a more efficient way or better. I would greatly appreciate. I don't really need itertools. All i need is a way to "bruteforce" a binary string
type: AnswerComment
score: 0

http://stackoverflow.com/q/47964266
tagged with: python
has comment: http://stackoverflow.com/comment/82899428
has comment: http://stackoverflow.com/comment/82898548
has comment: http://stackoverflow.com/comment/82899071
has body: I have question about my Python Code. I have this code that is trying to find changes on a webpage by making a json file and comparing to see if there any changes every 5 seconds but I am getting this error. I think everything else in the code should work.. How do I fix this? Traceback (most recent call last): File "C:\Users\Admin\Desktop\binance-getmarketsalert-master\test.py", line 28, in &lt;module&gt; before_set = set([market['symbol'] for market in before['result']]) TypeError: list indices must be integers or slices, not str The code is this: import time from smtplib import SMTPException def build_pair_string(pairs): pair_string = "" for pair in pairs: pair_string += pair + "\n" return pair_string while True: try: with open('markets.json', 'r') as current_markets: before = json.loads(current_markets.read()) except IOError: before = requests.get('').json() with open('markets.json', 'w') as current_markets: current_markets.write(json.dumps(before)) print("First run... Getting initial market data.") after = requests.get('').json() new_set = after_set - before_set if not new_set: print('No changes.. Waiting 5 seconds') time.sleep(5) if new_set: with open('markets.json', 'w') as current_markets: duration = 500 # millisecond freq = 440 # Hz winsound.Beep(freq, duration) print('Binance has added the following pairs:') new_list = [] for pair in new_set: new_list.append(pair) # = [item for item in pair] print(new_list) sender = 'sender@gmail.com' receivers = ['receiver@gmail.com'] message = """ Binance added {} """.format(build_pair_string(new_list)) try: smtpObj = smtplib.SMTP_SSL('smtp.gmail.com:465') smtpObj.login('example@gmail.com','password') print("\nSuccessfully sent email") except SMTPException as e: print(e) print("\nError: unable to send email") logging.critical('Waiting 5 seconds. New coin was listed') time.sleep(5)
has title: Error with Python - trying to find changes on a webpage
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/82898268
tagged with: http://stackoverflow.com/tag/html
tagged with: monitor
answer count: 0
score: 0

http://stackoverflow.com/a/47991412
upvote count: 2
has body: You could simply use in: forbidden = ['admin', 'master', 'owner'] username = request.POST['username'] match = [nm for nm in forbidden if nm in username] if match: # part of the username is in the forbidden list. Example in IPython: In [1]: forbidden = ['admin', 'master', 'owner'] In [2]: username = 'owner123' In [3]: match = [nm for nm in forbidden if nm in username] In [4]: match Out[4]: ['owner']
type: Answer
accepted answer of: http://stackoverflow.com/q/47989737
score: 2
answers question: http://stackoverflow.com/q/47989737
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82951125
downvote count: 0

http://stackoverflow.com/comment/82921078
type: Comment
type: QuestionComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ, cold speed. btw, do you want to post your answer? I can accept it as the final answer.
comment on: http://stackoverflow.com/q/47975309
score: 0

jsonparser
tags question: http://stackoverflow.com/q/48008390
type: Tag
tag name: jsonparser

http://stackoverflow.com/comment/82965851
score: 0
comment on: http://stackoverflow.com/q/47998664
type: Comment
type: QuestionComment
has text: @user2357112 Good catch. It was meant to be `arr_unicode` which won't change anything

http://stackoverflow.com/comment/82846200
comment on: http://stackoverflow.com/q/47937905
score: 0
type: QuestionComment
type: Comment
has text: What do you mean by "making '/getab 030' a link" ?

http://stackoverflow.com/comment/82895742
has text: did my post answer your question?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47909126

http://stackoverflow.com/a/47868127
upvote count: 5
downvote count: 0
has body: size: it is declared but when initialized it uses self.env.grid_size[0]. How env can have an attribute grid_size that it was not defined or initialized? In the line before, self.env is set as the first positional argument the user supplies to the initializer when creating an instance of Simulator. It is up to the user to supply an object which has an attribute grid_size. (This should probably be mentioned by a doc-string or a type hint.) road_with: Why it is not mentioned in the parentheses? I would have just put road_with in the parentheses with the default value 44 Only let the user know what he must know about the inner workings of an object. It's the principle of information hiding. If every instance of our object should carry the attribute road_width with the value 44, why bother the user with another optional argument where it's not clear what calling the initializer with other values for road_width would even do? bg_color: Why it is not defined in the parentheses? Why quit, start_time, current_time are not defined in the parentheses? see above I don't understand your last two questions.
type: Answer
score: 5
answers question: http://stackoverflow.com/q/47868009

http://stackoverflow.com/comment/82793313
has text: Well you can't click Enter, you can't use ActionChains and you won't switch from Safari, good luck
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47912227

http://stackoverflow.com/comment/82990369
score: 0
comment on: http://stackoverflow.com/q/47925731
type: QuestionComment
type: Comment
has text: Okay, but with a little bit thinkin you would see, that the Name itself is not the problem und you could just overthink the names, but i changed it though, Maybe You could now help with the problem, not with the typography

http://stackoverflow.com/q/47928371
downvote count: 0
answer count: 1
tagged with: ubuntu
favorite count: 0
has body: I am new to tensorflow and I am working on shared linux (Ubuntu 16.04), it means I don't have root access. Cuda 8.0 and Cudnn 8 are already installed by admin as root. I have installed python 3.5 using anaconda and then installed tensorflow using pip. I have added the cuda-8.0/bin and cuda-8.0/lib64 to PATH and LD_PATH_LIBRARY using following exports. export PATH="$PATH:/usr/local/cuda-8.0/bin" export LD_LIBRARY_PATH="/usr/local/cuda-8.0/lib64" But when I try to run the program it gives the following error. ImportError: libcublas.so.8.0: cannot open shared object file: No such file or directory However these files exist in LD_LIBRARY_PATH, and nvcc -V is also working. Is it even possible to refer to the system installed Cuda and CuDnn ? If yes, can you help to clear the above error. Thanks in advance.
tagged with: python
tagged with: cublas
upvote count: 3
type: UnansweredQuestion
tagged with: tensorflow
type: Question
score: 3
has title: ImportError: libcublas.so.8.0: cannot open shared object file: No such file or directory (Shared Linux)
has answer: http://stackoverflow.com/a/47928522

http://stackoverflow.com/q/48007100
favorite count: 0
upvote count: 11
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/53402511
has answer: http://stackoverflow.com/a/57068272
tagged with: pyqt5
score: 11
type: Question
has comment: http://stackoverflow.com/comment/87908138
has body: I am trying to bundle a PyQt project using Pyinstaller. I tried creating package using command pyinstaller --onedir Hello.py. This creates dist folder and has Hello.exe. On running it gets the error: This application failed to start because it could not find or load the Qt platform plugin "windows"in "". Reinstalling the application may fix this problem. I solved the issue in my PC by setting environment variable QT_QPA_PLATFORM_PLUGIN_PATH or by Copying dist\Hello\PyQt5\Qt\plugins\platform folder to where Hello.exe exists. But this issue exists when I bundle to a single file using command --onefile, and run on any other machine, where QT_QPA_PLATFORM_PLUGIN_PATH is not set. Can someone help to figure out the issue.
has answer: http://stackoverflow.com/a/68102147
has answer: http://stackoverflow.com/a/63115852
linked to: http://stackoverflow.com/q/122327
has title: Error: Could not find or load the Qt platform plugin "windows" - PyQt + Pyinstaller
downvote count: 0
tagged with: pyinstaller
tagged with: python
answer count: 4

http://stackoverflow.com/q/47861188
has comment: http://stackoverflow.com/comment/82687512
score: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: pip
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82687300
downvote count: 1
tagged with: anaconda
has answer: http://stackoverflow.com/a/47877881
tagged with: matplotlib
has body: I'm having trouble trying to do Chapter 2 of "Doing Math with Python". I have Anaconda and Python 3.6.3 on Mac (10.13). I attempt to run one of the programs from Chapter 2, and I get a message saying, "No module named 'matplotlib'". How do I get past this?
has title: Graphs in Python with "Doing Math with Python"
type: Question

http://stackoverflow.com/comment/126924722
type: Comment
comment on: http://stackoverflow.com/a/47896975
has text: swdmnd: Of course it does, a fact @buhtz never acknowledged after I posted the complete *working* code.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82864064
type: QuestionComment
has text: Dictionaries must have unique keys. You can't have multiple `3` keys. From your title, are you trying to have a list of words stored against that key? The expected output in your question does not match what I understand from the question title.
score: 4
comment on: http://stackoverflow.com/q/47947082
type: Comment

http://stackoverflow.com/a/48005804
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48005688
has body: The argument to insertafter is a regular expression, so you need to escape brackets with backslashes. insertafter: "\\[server\\]" In a vast majority of cases, you should use Ansible template module and specify the desired contents, instead of relying on the current state of the target machine.
has comment: http://stackoverflow.com/comment/82982104

http://stackoverflow.com/comment/137295076
has text: On a mac M1 with a recent version of pip, I used the following successfully: `pip install --compile --config-settings="--build-option=--with-openssl --openssl-dir=/opt/homebrew/opt/openssl@3/" pycurl `
comment on: http://stackoverflow.com/a/47888872
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/q/48009112
tagged with: python-docx
has comment: http://stackoverflow.com/comment/83018769
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82989272
answer count: 0
has title: list out of range error when python-docx reads a table of which the border's not aligned
type: Question
has comment: http://stackoverflow.com/comment/82986798
has body: I am parsing a table (which looks like the image below) in Word docx file by using python-docx. But when it reads the table below it throws an error. I've noticed that there is a tiny "crack" at the right-end border of the table as I circled red in the picture. If I manually align the right-end border, my code will be fine. But isn't there a clever way to solve it? from docx import Document document = Document(u'D:\\1.docx') tables = document.tables print(tables[0].rows[0].cells[0].text) The error is: Traceback (most recent call last): File "C:\Users\lenovo\Anaconda2\envs\py3\lib\site-packages\IPython\core\interactiveshell.py", line 2862, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "&lt;ipython-input-168-61cbbaa7e1a8&gt;", line 1, in &lt;module&gt; tables[0].rows[0].cells[0].text File "C:\Users\lenovo\Anaconda2\envs\py3\lib\site-packages\docx\table.py", line 384, in cells return tuple(self.table.row_cells(self._index)) File "C:\Users\lenovo\Anaconda2\envs\py3\lib\site-packages\docx\table.py", line 106, in row_cells return self._cells[start:end] File "C:\Users\lenovo\Anaconda2\envs\py3\lib\site-packages\docx\table.py", line 173, in _cells cells.append(cells[-col_count]) IndexError: list index out of range During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\lenovo\Anaconda2\envs\py3\lib\site-packages\IPython\core\interactiveshell.py", line 2808, in run_ast_nodes if self.run_code(code, result): File "C:\Users\lenovo\Anaconda2\envs\py3\lib\site-packages\IPython\core\interactiveshell.py", line 2879, in run_code self.showtraceback(running_compiled_code=True) TypeError: showtraceback() got an unexpected keyword argument 'running_compiled_code' Can someone help me?
has comment: http://stackoverflow.com/comment/82992229
score: 0

http://stackoverflow.com/q/47977238
linked to: http://stackoverflow.com/q/42092774
tagged with: multidimensional-array
answer count: 3
has answer: http://stackoverflow.com/a/52817923
has body: While implementing a Kronecker-product for pedagogical reasons (without using the obvious and readily available np.kron()), I obtained a 4 dimensional array as an intermediate result, which I've to reshape to get the final result. But, I still can't wrap my head around reshaping these high dimensional arrays. I have this 4D array: array([[[[ 0, 0], [ 0, 0]], [[ 5, 10], [15, 20]]], [[[ 6, 12], [18, 24]], [[ 7, 14], [21, 28]]]]) This is of shape (2, 2, 2, 2) and I'd like to reshape it to (4,4). One might think that this is obvious to do with np.reshape(my4darr, (4,4)) But, the above reshape does not give me the expected result which is: array([[ 0, 5, 0, 10], [ 6, 7, 12, 14], [ 0, 15, 0, 20], [18, 21, 24, 28]]) As you can see, all the elements in the expected result are present in the 4D array. I just can't get the hang of doing the reshape correctly as needed. In addition to the answer, some explanation of how to do the reshape for such high dimensional arrays would be really helpful. Thanks!
tagged with: reshape
tagged with: python
score: 25
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/42812918
upvote count: 25
linked to: http://stackoverflow.com/q/32525345
linked to: http://stackoverflow.com/q/36943700
linked to: http://stackoverflow.com/q/39429900
linked to: http://stackoverflow.com/q/38499475
linked to: http://stackoverflow.com/q/34606602
linked to: http://stackoverflow.com/q/43547453
linked to: http://stackoverflow.com/q/41510395
accepted answer: http://stackoverflow.com/a/47978032
linked to: http://stackoverflow.com/q/38929531
type: Question
linked to: http://stackoverflow.com/q/38718234
has title: Intuition and idea behind reshaping 4D array to 2D array in NumPy
linked to: http://stackoverflow.com/q/35513420
linked to: http://stackoverflow.com/q/43166662
linked to: http://stackoverflow.com/q/40234839
linked to: http://stackoverflow.com/q/42892382
linked to: http://stackoverflow.com/q/33211988
linked to: http://stackoverflow.com/q/37719889
linked to: http://stackoverflow.com/q/47477945
tagged with: numpy
linked to: http://stackoverflow.com/q/42562853
tagged with: arrays
downvote count: 0
linked to: http://stackoverflow.com/q/46388237
linked to: http://stackoverflow.com/q/42652082
possible better answer: http://stackoverflow.com/a/47977299
favorite count: 0
has answer: http://stackoverflow.com/a/47978032
has answer: http://stackoverflow.com/a/47977299

http://stackoverflow.com/comment/89819296
type: Comment
has text: it can, but this doesn't solve the issue where `account.id` comes in as an ordered dict as well, not as a field. the `account` table is a sub table that is related to the opportunity table. The dictionary in Stephen's answer is how to solve for that. But thanks!
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/51418021

http://stackoverflow.com/comment/82984084
type: Comment
has text: still, you can check your desired condition before the rest of the code and break out of the loop
type: AnswerComment
comment on: http://stackoverflow.com/a/48007811
score: 0

http://stackoverflow.com/comment/82708626
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47871398
score: 0
has text: I added it, but the script doesn't print 'hello'

http://stackoverflow.com/q/47942845
has comment: http://stackoverflow.com/comment/82855476
downvote count: 1
type: Question
type: AnsweredQuestion
score: 3
linked to: http://stackoverflow.com/q/35116437
has comment: http://stackoverflow.com/comment/82876692
has body: I need to call a pipeline realized as a Python (3.6) function from my C++ project under the Windows platform. Function “function_name” from file "experiment_test.py" takes text string as input parameter and return another text string as the result. I try the code below but it doesn’t work properly – python functions from libraries shutil, codecs, makedirs, etc doesn’t work. C++ code (reduced): std::string Text,Result; PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pValue; Py_Initialize(); pName = PyUnicode_FromString("experiment_test"); pModule = PyImport_Import(pName); pDict = PyModule_GetDict(pModule); pFunc = PyDict_GetItemString(pDict, "function_name"); pArgs = PyTuple_New(1); pValue = PyUnicode_FromString(Text.c_str()); PyTuple_SetItem(pArgs, 0, pValue); if (PyCallable_Check(pFunc)) { pValue = PyObject_CallObject(pFunc, pArgs); if (pValue != NULL) { Result = PyUnicode_AsUTF8(pValue); Py_DECREF(pValue); } else return false; } // ... Py_Finalize(); Python code (reduced): #!/usr/local/bin/python3 import shutil import codecs from os import makedirs from os import path from os import unlink from subprocess import call def function_name(): name = 'working_files/current_text' if not path.exists('working_files'): makedirs('working_files') if path.exists('result.txt'): unlink('result.txt') with codecs.open(name + '.txt', 'w', encoding='utf-8') as f: f.write(text) # ... return result So no new files will be generated by Python. I tried to import Python modules in C++ by calling PyRun_SimpleString("import shutil"); etc after Py_Initialize(); but it doesn’t help. What do I do wrong?
has answer: http://stackoverflow.com/a/47972756
accepted answer: http://stackoverflow.com/a/47972756
answer count: 1
linked to: http://stackoverflow.com/q/34748913
favorite count: 0
tagged with: python
has title: Calling Python function with parameters from C++ project (Visual Studio)
linked to: http://stackoverflow.com/q/39539089
upvote count: 4
linked to: http://stackoverflow.com/q/8528437
tagged with: c++

http://stackoverflow.com/q/47952935
linked to: http://stackoverflow.com/q/45498049
has body: I configured eclipse with pyspark i am using latest version of SPARK and PYTHON. when i try to code something and run. i get below error. java.io.IOException: Cannot run program "python": CreateProcess error=2, The system cannot find the file specified code i have written is below ''' Created on 23-Dec-2017 @author: lenovo ''' from pyspark import SparkContext,SparkConf from builtins import int #from org.spark.com.PySparkDemo import data from pyspark.sql import Row from pyspark.sql.context import SQLContext conf = SparkConf().setAppName("FileSystem").setMaster("local") sc=SparkContext(conf=conf) sqlContext=SQLContext(sc) a = sc.textFile("C:/Users/lenovo/Desktop/file.txt") b = a.map(lambda x:x.split(",")).map(lambda x:Row(id=int(x[0]),name=x[1],marks=int(x[2]))) c = sqlContext.createDataFrame(b) c.show() please suggest
has title: java.io.IOException: Cannot run program "python": CreateProcess error=2, The system cannot find the file specified
type: Question
type: AnsweredQuestion
tagged with: apache-spark-sql
tagged with: pyspark
tagged with: eclipse
possible better answer: http://stackoverflow.com/a/67180174
upvote count: 2
downvote count: 2
answer count: 2
duplicate of: http://stackoverflow.com/q/45498049
favorite count: 0
score: 0
tagged with: apache-spark
tagged with: python
has answer: http://stackoverflow.com/a/47953300
accepted answer: http://stackoverflow.com/a/47953300
has answer: http://stackoverflow.com/a/67180174

http://stackoverflow.com/q/47984690
tagged with: django
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48016359
type: AnsweredQuestion
downvote count: 1
has body: code sample corrected December 27, 2017 I'm using Django 1.11 and Python 2.7.13. I'm deploying on Google App Engine using Cloud SQL (MySQL 5.7) but the error happens in my local development environment. I have a very simple app with 1 form that collects some data and tries to save it as a new record in the database. It works fine if I use the default form and CreateView like this: # views.py class SubjectCreate(CreateView): model = Subject fields = '__all__' success_url = reverse_lazy('subapp:index') However, I want to customize the form (move fields around, use check boxes, etc.) To do this from what I can tell I can't use the default CreateView, etc. but have to write my own. So here's what I've done: # models.py class Subject(models.Model): subject_date = models.DateTimeField(default=timezone.now) subject_field2 = models.CharField(max_length=20) ... whole bunch of other fields ... def __str__(self): return self.subject_date.strftime('%Y-%m-%d %H:%M') + self.subject_field2[:35] + "..." #views.py def createnewsubject(request): if request.method == 'POST': subject_form = NewSubjectForm(request.POST) if subject_form.is_valid(): subject_data = Subject(request.POST) subject_data.save() return HttpResponseRedirect('/') else: subject_form = NewSubjectForm() return render(request, 'subapp/subject_form.html', {'form': subject_form}) # forms.py class NewSubjectForm(forms.ModelForm): class Meta: model = Subject fields = "__all__" When the code hits subject_data.save() I get TypeError at /new/ int() argument must be a string or a number, not 'QueryDict' When I look through the trace I see self &lt;django.db.models.fields.AutoField: id&gt; value &lt;QueryDict: { ... dict with all my app data ... }&gt; So it sounds like Django is trying to use my form data as the primary key of the new record. But the primary key should be auto-generated. I've beaten my head on this for weeks using Django doc, Stack Overflow posts, and Google. I'm getting nowhere. Please help?
type: Question
accepted answer: http://stackoverflow.com/a/48016359
has answer: http://stackoverflow.com/a/47985290
has comment: http://stackoverflow.com/comment/82938390
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/47985290
has comment: http://stackoverflow.com/comment/83001958
favorite count: 0
has comment: http://stackoverflow.com/comment/82938677
has title: Django Saving new record, int() argument must be a string or a number, not 'QueryDict'

http://stackoverflow.com/a/47920368
has comment: http://stackoverflow.com/comment/82808650
answers question: http://stackoverflow.com/q/47919846
has body: Use pycountry.countries.lookup &gt;&gt;&gt; pycountry.countries.lookup('Bolivia') Country(alpha_2='BO', alpha_3='BOL', common_name='Bolivia', name='Bolivia, Plurinational State of', numeric='068', official_name='Plurinational State of Bolivia')
upvote count: 4
has comment: http://stackoverflow.com/comment/82808816
downvote count: 0
type: Answer
score: 4

http://stackoverflow.com/comment/82691489
score: 0
comment on: http://stackoverflow.com/q/47863243
type: Comment
type: QuestionComment
has text: Is it possible for you to use `numpy`?

http://stackoverflow.com/comment/82850360
has text: Note that [`re.match("/(\d+(\.\d+)?)/", value) != False`](https://docs.python.org/3/library/re.html#re.regex.match) is going to be True always, since `re.match()` returns either a match object or None.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47931787

http://stackoverflow.com/comment/82990112
type: QuestionComment
has text: Why don't you want to use the ternary operator? The Python conditional expression is quite efficient.
score: 0
comment on: http://stackoverflow.com/q/48009830
type: Comment

http://stackoverflow.com/a/47933205
type: Answer
upvote count: 14
answers question: http://stackoverflow.com/q/47928608
score: 14
has comment: http://stackoverflow.com/comment/135852513
accepted answer of: http://stackoverflow.com/q/47928608
has comment: http://stackoverflow.com/comment/135924803
type: AcceptedAnswer
has body: EDIT (2023.09): I added headers because it stoped working. It needs User-Agent from real web browser. It can't be short 'Mozilla/5.0'. You can check your User-Agent using pages like httpbin.org/user-agent Your url doesn't work for me. But with https://google.com/search?q= I get results. import urllib from bs4 import BeautifulSoup import requests import webbrowser headers = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/117.0' } text = 'hello world' text = urllib.parse.quote_plus(text) url = 'https://google.com/search?q=' + text response = requests.get(url, headers=headers) #with open('output.html', 'wb') as f: # f.write(response.content) #webbrowser.open('output.html') soup = BeautifulSoup(response.text, 'lxml') for g in soup.find_all(class_='g'): print(g.text) print('-----') Read Beautiful Soup Documentation
downvote count: 0

http://stackoverflow.com/comment/82979273
type: QuestionComment
comment on: http://stackoverflow.com/q/48005152
has text: Yes it is a 2D mAtrix, same length each time, no longer no shorter
score: 0
type: Comment

http://stackoverflow.com/q/47937240
has comment: http://stackoverflow.com/comment/82844184
has comment: http://stackoverflow.com/comment/82847039
type: Question
has answer: http://stackoverflow.com/a/47938315
has comment: http://stackoverflow.com/comment/82844242
has comment: http://stackoverflow.com/comment/82844003
has title: Classes in Linked List not working
has comment: http://stackoverflow.com/comment/82843901
has comment: http://stackoverflow.com/comment/82844550
tagged with: class
score: 0
answer count: 2
has body: Got a schoolwork to do showroom with 2 classes: Car &amp; Node, while Node data contain Car class with its data. Then I have to make a Linked list, should be doubly, but I think a simple should work as well, with Nodes containing Cars. The only function in Linked list is inserting a new Node with new Car. It should be sorted by price of cars upwardly. Tried this, but it keeps telling me TypeError: '&lt;' not supported between instances of 'NoneType' and 'NoneType' class Car: def __init__(self, id = None, name = None, brand = None, price = None, active = None): self.id = id self.name = name self.brand = brand self.price = price self.active = active class Node: def __init__(self, data): self.next = None self.data = Car() class LinkedList: def __init__(self): self.head = Node(None) def insertNode(self, car): newNode = Node(car) curNode = self.head if self.head.data is None: self.head = newNode if newNode.data.price &lt; curNode.data.price: newNode.next = curNode self.head = newNode else: while curNode.next is not None and curNode.next.data.price &lt;= newNode.data.price: curNode = curNode.next newNode.next = curNode.next curNode.next = newNode db = LinkedList() def init(cars): for car in cars: db.insertNode(car) def add(car): db.insertNode(car) Did I miss something, 'cause I think it should be working.
has answer: http://stackoverflow.com/a/47937827
has comment: http://stackoverflow.com/comment/82844093
tagged with: python
has comment: http://stackoverflow.com/comment/82844009
has comment: http://stackoverflow.com/comment/82844169
has comment: http://stackoverflow.com/comment/82844111
tagged with: linked-list
type: UnansweredQuestion

http://stackoverflow.com/comment/82834700
type: Comment
comment on: http://stackoverflow.com/a/47920690
type: AnswerComment
has text: The error is not in your snippet. Show us the full code
score: 0

http://stackoverflow.com/comment/82972644
has text: @FatihAkici It is because the new value of randomarray[x] may exceed the next value of the array when I sum it with '+ 1'. For example; randomarray[x]= '39' and 'randomarray[x+1]='40'. When I sum it +1, and the condition is not provided again, it can be upgraded randomarray[x]='41'or more.
comment on: http://stackoverflow.com/q/48000786
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/47943640
has comment: http://stackoverflow.com/comment/82856863
has answer: http://stackoverflow.com/a/47943853
type: Question
score: -2
has title: How can I average several inputs?
has comment: http://stackoverflow.com/comment/82856908
has answer: http://stackoverflow.com/a/47943950
has body: I'm trying to code a calculator with several options, just for the leraning experience, and one of these options is 'average', I want the user to be able to input as many values as he wants to, but it's not working yet, what should I change? This is my code for the average so far: elif ui1 == subop1_2: 1 = [input("Input your values, separate with a comma").split(',')] result = sum(1) / float(len(1)) print("The average is {}".format(result)) time.sleep(10)
upvote count: 0
has answer: http://stackoverflow.com/a/47943728
accepted answer: http://stackoverflow.com/a/47945164
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/47943728
tagged with: python
has comment: http://stackoverflow.com/comment/82856868
has comment: http://stackoverflow.com/comment/82856815
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82856843
downvote count: 2
has answer: http://stackoverflow.com/a/47945164

http://stackoverflow.com/q/47927980
has answer: http://stackoverflow.com/a/47928204
upvote count: 4
answer count: 2
downvote count: 0
favorite count: 0
has body: How can I modify the following line of code (which reads the names of parameters in config_file): re.findall('Parameter.*', config_file) so as to ignore lines containing a comment symbol (%) to the left? i.e. in the following example, Parameter: A %Parameter: B % Parameter: C Parameter: D %the best parameter only A and D match?
has answer: http://stackoverflow.com/a/47928122
tagged with: python
tagged with: regex
accepted answer: http://stackoverflow.com/a/47928204
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82824326
possible better answer: http://stackoverflow.com/a/47928122
linked to: http://stackoverflow.com/q/2973436
has comment: http://stackoverflow.com/comment/82824956
type: Question
has comment: http://stackoverflow.com/comment/82824795
has title: Ignore comments with whitespace in regex
has comment: http://stackoverflow.com/comment/82824970
score: 4
has comment: http://stackoverflow.com/comment/82824329

http://stackoverflow.com/comment/83061984
comment on: http://stackoverflow.com/a/48006525
type: AnswerComment
has text: I updated the answer, although I admit that this solution is not very elegant. I hope it solves your problem though.
score: 0
type: Comment

http://stackoverflow.com/comment/82927613
has text: Split your string using with `,` character, and convert each number to an int. Right now, you are trying to tell the machine "Hey, I have got a string and I want it to be an integer. Can you tell me which integer '51,52,52,53,52(...)' is ?". Nah. You gotta divide your sentence into all the detached numbers. And then, you will tell the machine : "Hey, I got a list of numbers, but they are in the form a strings. Can you convert them to actual numbers ?".
score: 1
comment on: http://stackoverflow.com/q/47979486
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82723590
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/47876128
type: Comment
has text: You should be able to use a simple `join` to merge the two grouped dataframes. Since they are both the result of grouping by CLIENT, they will have the same index (at least, before calling `reset_index`).

http://stackoverflow.com/q/47946317
possible better answer: http://stackoverflow.com/a/47946359
score: 0
answer count: 2
tagged with: function
duplicate of: http://stackoverflow.com/q/44564414
has answer: http://stackoverflow.com/a/47946360
duplicate of: http://stackoverflow.com/q/7129285
tagged with: string
linked to: http://stackoverflow.com/q/750136
accepted answer: http://stackoverflow.com/a/47946360
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47946359
has title: Python use function as string
has body: I want to use a function as a String, i have this function: def getCoins(user): ##Get the Coins from a user.## try: with open(pathToUser + user + ".txt") as f: for line in f: print(user + " has " + line +" coins!") except: print("Error!") Now it just print the coins, but i want to use it in other codes like this: client.send_msg(m.text.split(' ')[2] + "has" + coinapi.getCoins('User') + "coins") How do it do that? So that i can use it like a string, the message in Twitchchat should be: "USERXYZ has 100 coins"
type: Question

http://stackoverflow.com/comment/82756455
comment on: http://stackoverflow.com/q/47894673
type: QuestionComment
type: Comment
has text: what i want is to access the matrix on the position of the blob and eliminate it. Should i not be imagining images as matrices?
score: 1

http://stackoverflow.com/comment/82729402
score: 1
type: QuestionComment
type: Comment
has text: Sounds like maybe a job for pandas with a `DatetimeIndex`... do you know the start and end times?
comment on: http://stackoverflow.com/q/47881799

http://stackoverflow.com/q/47856519
tagged with: mysql
has title: How to dynamically generate mysql ON DUPLICATE UPDATE in python
has body: I am trying to dynamically generate MySQL insert/update queries given a csv file. I have a csv file hobbies.csv: id,name,hobby "1","rick","coding" "2","mike","programming" "3","tim","debugging" I then have 2 functions: 1 to generate the queries, 1 to update the database: generate_sql.py from connect_to_database import read_db_config from config_parser import read_csv_files from update_db import insert_records import csv def generate_mysql_queries(): csv_file_list, table_list, temp_val, temp_key, temp_table, reader, header, data, data_list = ([] for i in range(9)) val_param = '%s' query = '' total_queries = 0 db = read_db_config(filename='config.ini', section='mysql') csv_file_dict = read_csv_files(filename='config.ini', section='data') for key, value in csv_file_dict.items(): temp_val = [value] temp_key = [key] csv_file_list.append(temp_val) table_list.append(temp_key) for index, files in enumerate(csv_file_list): with open("".join(files), 'r') as f: reader = csv.reader(f) header.append(next(reader)) data.append([row for row in reader]) for d in range(len(data[index])): val_param_subs = ','.join((val_param,) * len(data[index][d])) total_queries += 1 query = """INSERT INTO """ + str(db['database']) + """.""" + """""".join('{0}'.format(t) for t in table_list[index]) + \ """(""" + """, """.join('{0}'.format(h) for h in header[index]) + """) VALUES (%s)""" % val_param_subs + \ """ ON DUPLICATE KEY UPDATE """ + """=%s, """.join(header[index]) + """=%s""" data_list.append(data[index][d]) insert_records(query, data_list) I then pass the query and data to insert_records() in update_db.py: from mysql.connector import MySQLConnection, Error from connect_to_database import read_db_config def insert_records(query, data): query_string = query data_tuple = tuple(data) try: db_config = read_db_config(filename='config.ini', section='mysql') conn = MySQLConnection(**db_config) cursor = conn.cursor() cursor.executemany(query, data_tuple) print("\tExecuted!") conn.commit() except Erro…
type: Question
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/47858739
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/q/47952756
score: 0
tagged with: python
has body: The following lambda returns empty "" for filenames without a slash (e.g. "local.txt"): lambda filename: os.path.dirname(filename) I would like to ensure (in very concise syntax) that the lambda always returns a proper directory name, i.e. "." instead of "". Is there more concise way for doing this than the following: lambda filename: os.path.dirname(filename) if os.path.dirname(filename) != "" else "." IMO it would be nice if os.path.dirname would not have to be specified (perhaps even evaluated) twice. A conditional expression with one branch instead of two (if such a construct exists) could support come in handy.
has comment: http://stackoverflow.com/comment/82874888
accepted answer: http://stackoverflow.com/a/47952783
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47952783
has title: Python conditional expression with one branch instead of two
type: Question
answer count: 1
tagged with: python-3.6

http://stackoverflow.com/comment/82914413
has text: @ClementAttlee to be clear, you should *not* try to modify a list or its elements as you iterate through it. instead create a new list
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47972392

http://stackoverflow.com/q/47863640
answer count: 1
has body: I'm making onefile executables with pyinstaller on windows 10. I'm including data files (pickle files) by editing the .spec file... How can I store changes made to these files during run time? My understanding is that the data files are copied to a temp directory during execution. I can read from the files using the path I get from sys._MEIPASS but the changes I write are lost after restarting the program. Is there a way to write to pickle files stored inside the exe?
favorite count: 0
has title: how to change bundled data file pyinstaller on execute
type: UnansweredQuestion
tagged with: pyinstaller
tagged with: python
has answer: http://stackoverflow.com/a/61203249
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82695482
type: Question
has comment: http://stackoverflow.com/comment/82698008
score: 0

http://stackoverflow.com/q/47949918
score: 1
has body: I need to pass a list of complex numbers from python to C++ to initialize a vector and after some operations, I need to pass the vector of complex double back to python. Here is my try: example.i %module example %{ #define SWIG_FILE_WITH_INIT #include "example.h" %} %include "std_vector.i" %include &lt;complex.i&gt; %include &lt;std_complex.i&gt; namespace std { %template(DoubleVector) vector&lt;double&gt;; %template(ComplexVector) vector&lt;std::complex&lt;double&gt; &gt;; } %include "example.h" example.cpp #include "example.h" void my_class::set_value(Complex a, std::vector&lt;Complex&gt; v) { com1 = {1,2}; comV = v; } void my_class::print_value() { std::cout &lt;&lt; com1&lt;&lt; std::endl; for (int i=0; i&lt;comV.size(); i++) std::cout&lt;&lt;comV[i]&lt;&lt;std::endl; } example.h #include &lt;iostream&gt; #include &lt;cstdio&gt; #include &lt;vector&gt; #include &lt;omp.h&gt; #include &lt;complex&gt; typedef std::complex&lt;double&gt; Complex; class my_class { private: Complex com1; std::vector&lt;Complex&gt; comV; public: my_class(){ } void set_value(Complex a, std::vector&lt;Complex&gt; v); void print_value(); }; I compiled and give me the following error when I try to test it: import example c = example.my_class() c.set_value(complex(1.0,3.5), [complex(1,1.2), complex(2.0,4.2)]) c.print_value() return _example.my_class_set_value(self, a, v) TypeError: in method 'my_class_set_value', argument 3 of type 'std::vector&lt; Complex,std::allocator&lt; Complex &gt; &gt;' I don't know Where I made a mistake?
type: Question
has title: SWIG: How to pass a vector of complex numbers from C++ to python
tagged with: vector
answer count: 1
downvote count: 0
tagged with: python
favorite count: 0
tagged with: c++
accepted answer: http://stackoverflow.com/a/47949992
upvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47949992
tagged with: swig

http://stackoverflow.com/q/47949330
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/47949694
has answer: http://stackoverflow.com/a/47949694
favorite count: 0
has answer: http://stackoverflow.com/a/47950163
has title: Python import function from package
tagged with: python-3.x
tagged with: package
tagged with: python
type: AnsweredQuestion
score: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/47950163
type: Question
tagged with: python-import
has body: (Python 3.6) I have this folder structure: package/ start.py subpackage/ __init__.py submodule.py submodule.py: def subfunc(): print("This is submodule") __ init __.py: from subpackage.submodule import subfunc start.py: import subpackage subpackage.subfunc() subpackage.submodule.subfunc() I understand how and why subpackage.subfunc() works. But I don't understand why: subpackage.submodule.subfunc() also works, if I have not done: from subpackage import submodule Nor: import subpackage.submodule Neither in __ init __.py nor in start.py Thank you very much if anyone may clear my doubt.

http://stackoverflow.com/comment/82900491
type: Comment
has text: @Sam that seems easy to modify- since a product can only be created is there was an order, and an order only created if there is a user, at each of the `if` checks, delete all dependent objects. The other option is, instead of a general except, you can check for specific exceptions, since difference exceptions are thrown by `save` and the constructors.
comment on: http://stackoverflow.com/a/47955054
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82992658
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47995901
has text: Thanks @errantlinguist, dully noted.

http://stackoverflow.com/comment/82928284
score: 0
comment on: http://stackoverflow.com/a/47979820
type: AnswerComment
type: Comment
has text: apprectiate, all it took was to change a string to a list. big thanks!

http://stackoverflow.com/q/47969034
type: Question
has body: I am running a Python script using subprocess and willing to save output to a file as well as show live logs on terminal. I have written below code and its saving logs in file but not showing live script execution logs on terminal. TCID = sys.argv[1] if TCID == "5_2_5_3": output = subprocess.check_output([sys.executable, './script.py']) with open('scriptout.log', 'wb') as outfile: outfile.write(output)
has comment: http://stackoverflow.com/comment/82908921
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/47969333
tagged with: python-3.x
tagged with: python
accepted answer: http://stackoverflow.com/a/47969333
has comment: http://stackoverflow.com/comment/82907703
tagged with: logging
has comment: http://stackoverflow.com/comment/82907631
type: AnsweredQuestion
tagged with: subprocess
score: 1
has comment: http://stackoverflow.com/comment/82908888
has title: Python subprocess display logs on terminal and save in file
upvote count: 1

http://stackoverflow.com/q/47964380
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/63924307
downvote count: 0
accepted answer: http://stackoverflow.com/a/47965006
favorite count: 0
has answer: http://stackoverflow.com/a/67611915
possible better answer: http://stackoverflow.com/a/63924307
type: Question
score: 31
tagged with: pandas
has title: Pandas DataFrame column naming conventions
tagged with: python
has body: Is there any commonly used Pandas DataFrame column naming convention? Is PEP8 recommended here (ex. instance variables)? Concious that lots of data is loaded from external sources with headers but I'm curious what is the correct approach when I have to name/rename the columns on my own?
upvote count: 31
answer count: 3
has answer: http://stackoverflow.com/a/47965006

http://stackoverflow.com/comment/82985198
type: QuestionComment
comment on: http://stackoverflow.com/q/48008390
has text: I edited, the question, is my question question clearer?
score: 0
type: Comment

http://stackoverflow.com/a/47925802
has comment: http://stackoverflow.com/comment/82819828
score: 0
has comment: http://stackoverflow.com/comment/82819559
has comment: http://stackoverflow.com/comment/82820269
has comment: http://stackoverflow.com/comment/82820232
has comment: http://stackoverflow.com/comment/82819589
has body: Python isn't making a copy of ints or floats every time you assign them to a different variable. The thing is that they're not mutable; there's nothing you could do to an int that would change it, so however many variables you assign it to, you won't ever get any surprising behaviour. With obj2.1st_att = 5, you're explicitly modifying an attribute of an object. There's no analog operation to that for an int. It is expected that this operation modifies the object, and that this change will be visible to anyone else who holds a reference to that object. You should not try to work around that behaviour in any way, as that would break a lot of expectations and cause bugs or surprising behaviour in itself. It is good that making a copy of an object is an explicit action you need to take. Get used to it.
type: Answer
has comment: http://stackoverflow.com/comment/82819971
has comment: http://stackoverflow.com/comment/82819768
has comment: http://stackoverflow.com/comment/82820030
answers question: http://stackoverflow.com/q/47925677
has comment: http://stackoverflow.com/comment/82819660

http://stackoverflow.com/comment/82829482
score: 1
comment on: http://stackoverflow.com/q/47928608
type: Comment
type: QuestionComment
has text: you might be struggling with this as Google renders a lot of its page with Javascript, so the markup you see if not present in the downloaded data. Have you checked in the actual data that the markup you want is there? You may want to consider using the Google custom search API https://developers.google.com/custom-search/json-api/v1/overview since I hear that Google routinely changes the markup on its search results pages.

http://stackoverflow.com/a/47873645
downvote count: 0
type: Answer
has body: No it doesn't. In neither of those cases is the type equal to the string "str". It's equal to the type str. In any case, to check if something is a string, you should use isinstance, again with the actual type object. if isinstance(var, str): print("it is str")
answers question: http://stackoverflow.com/q/47873616
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/82737567

http://stackoverflow.com/q/47889919
linked to: http://stackoverflow.com/q/17443354
has comment: http://stackoverflow.com/comment/82746126
has comment: http://stackoverflow.com/comment/82746389
tagged with: python
has answer: http://stackoverflow.com/a/47890033
tagged with: jupyter
has answer: http://stackoverflow.com/a/62878684
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/82746870
has comment: http://stackoverflow.com/comment/82746813
upvote count: 3
type: UnansweredQuestion
score: 1
downvote count: 2
type: Question
tagged with: numpy
has body: First bear with me as I am relatively new to coding. I am trying to import numpy to Jupyter (localhost, webbased) using Python 3 and getting an error. import numpy as np ModuleNotFoundError Traceback (most recent call last) &lt;ipython-input-7-0aa0b027fcb6&gt; in &lt;module&gt;() ----&gt; 1 import numpy as np ModuleNotFoundError: No module named 'numpy' What should I do? Many thanks.
has comment: http://stackoverflow.com/comment/82746781
answer count: 2
has title: Failing to import numpy in Jupyter
favorite count: 0
has comment: http://stackoverflow.com/comment/82746998
has comment: http://stackoverflow.com/comment/82746465

http://stackoverflow.com/q/48007984
has body: I am new to tensorflow and Machine Learning. Recently I am working on a model. My model is like below, Character level Embedding Vector -> Embedding lookup -> LSTM1 Word level Embedding Vector->Embedding lookup -> LSTM2 [LSTM1+LSTM2] -> single layer MLP-> softmax layer [LSTM1+LSTM2] -> Single layer MLP-> WGAN discriminator Code of he rnn model while I'm working on this model I got the following error. I thought My batch is too big. Thus I tried to reduce the batch size from 20 to 10 but it doesn't work. ResourceExhaustedError (see above for traceback): OOM when allocating tensor with shape[24760,100] [[Node: chars/bidirectional_rnn/bw/bw/while/bw/lstm_cell/split = Split[T=DT_FLOAT, num_split=4, _device="/job:localhost/replica:0/task:0/device:GPU:0"](gradients_2/Add_3/y, chars/bidirectional_rnn/bw/bw/while/bw/lstm_cell/BiasAdd)]] Node: bi-lstm/bidirectional_rnn/bw/bw/stack/_167 = _Recvclient_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_636_bi-lstm/bidirectional_rnn/bw/bw/stack", tensor_type=DT_INT32, _device="/job:localhost/replica:0/task:0/device:CPU:0" tensor with shape[24760,100] means 2476000*32/8*1024*1024 = 9.44519043 MB memory. I am running the code on a titan X(11 GB) GPU. What could go wrong? Why this type of error occurred? * Extra info *: the size of the LSTM1 is 100. for bidirectional LSTM it becomes 200. The size of the LSTM2 is 300. For Bidirectional LSTM it becomes 600. *Note *: The error occurred after 32 epoch. My question is why after 32 epoch there is an error. Why not at the initial epoch.
tagged with: batch-processing
downvote count: 0
has answer: http://stackoverflow.com/a/48096611
has title: Training broke with ResourceExausted error
has answer: http://stackoverflow.com/a/48066085
favorite count: 0
possible better answer: http://stackoverflow.com/a/48066085
tagged with: python
upvote count: 16
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83300062
accepted answer: http://stackoverflow.com/a/48096611
score: 16
has answer: http://stackoverflow.com/a/75273345
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/83299465
linked to: http://stackoverflow.com/q/39076388
answer count: 3

http://stackoverflow.com/comment/82782480
has text: @kabanus that solution gives out a list of tuples, I need a 2D array
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47905529

http://stackoverflow.com/a/47961455
answers question: http://stackoverflow.com/q/47961210
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82892565
type: Answer
accepted answer of: http://stackoverflow.com/q/47961210
has body: To answer your question: To do this for just abc, you'd have to write a regex that says: "start with ", then whatever; eventually a, then whatever, eventually b, then whatever, eventually c, then whatever, and finally "; or b, then whatever, eventually a, then whatever, eventually c, then whatever..." - and so on, for all 3! = 6 permutations. # declarative regex = '^".*(a.*b.*c|a.*c.*b|b.*a.*c|b.*c.*a|c.*a.*b|c.*b.*a).*"$' # generative import itertools regex = '^".*(' regex += '|'.join('.*'.join(p) for p in itertools.permutations('abc')) regex += ').*"$' However, if you try to do that for all printable characters, you'll probably run out of memory, as there are (126-32)! = 108736615665674308027365285256786601004186803580182872307497374434045199869417927630229109214583415458560865651202385340530688000000000000000000000 permutations. So... To solve your problem: printables = {chr(i) for i in range(32, 127)} def f(s): return s.startswith('"') and s.endswith('"') and printables &lt; set(s)
downvote count: 0
score: 1

http://stackoverflow.com/q/47967167
has body: I am a novice in python. I am trying to use the Sellmeier Equation to calculate a refractive index. The coefficients of this equation are decimals to a large number of sig figs ( i.e B1 = 1.03961212, B2 = 0.231792344, C1 = 6.00069867×10−3 ... and so on) in the sellmeier formula there is a lot of fractions, multiplication and squaring of these numbers. I originally state them as floats. However such a process apparently cannot be done with floats like these. What do i do? Please need help!
type: UnansweredQuestion
score: -3
downvote count: 3
type: Question
has answer: http://stackoverflow.com/a/47967250
linked to: http://stackoverflow.com/q/11522933
duplicate of: http://stackoverflow.com/q/11522933
upvote count: 0
answer count: 1
has title: HOW TO USE LONG DECIMAL NUMBERS IN PYTHON
favorite count: 0
has comment: http://stackoverflow.com/comment/82905424
tagged with: physics
tagged with: python

http://stackoverflow.com/q/47952516
has comment: http://stackoverflow.com/comment/82874391
tagged with: numpy
has comment: http://stackoverflow.com/comment/82874390
has comment: http://stackoverflow.com/comment/82874406
tagged with: python-2.7
has body: I have a code that might have been developed for Python 3, but my Centos is running Python 2.7: def generateWeights(self, name_list): n = len(name_list) weights = np.flip(np.arange(1, n), axis=0) return weights / np.sum(weights) I get for this part of the code: AttributeError: 'module' object has no attribute 'flip' Is there anything I should install/update, or an alternative code that will work? Import part: import requests import urllib import logging import argparse from lxml import objectify import time import pandas as pd import numpy as np import re
accepted answer: http://stackoverflow.com/a/47952540
linked to: http://stackoverflow.com/q/45706896
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82874404
favorite count: 0
has title: AttributeError: 'module' object has no attribute 'flip', python 2.7
tagged with: python
score: -1
type: AnsweredQuestion
downvote count: 1
has comment: http://stackoverflow.com/comment/82874640
type: Question
has comment: http://stackoverflow.com/comment/82874363
linked to: http://stackoverflow.com/q/7416170
has answer: http://stackoverflow.com/a/47952540

http://stackoverflow.com/q/47988625
has comment: http://stackoverflow.com/comment/133813543
has comment: http://stackoverflow.com/comment/83353795
accepted answer: http://stackoverflow.com/a/49286807
score: 2
type: AnsweredQuestion
downvote count: 0
tagged with: textbox
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50528811
type: Question
has body: In my GUI I create a ttk.notebook and then put Text widgets into each tab and dump logs/info into these Text widgets. If the process is restarted with a new set of log files I .forget() the old tabs and then create the new ones. I've noticed that the ram used from the original Text widgets is not cleared when I do this. How can I free this ram? Example: from tkinter import * from tkinter.ttk import Notebook main = Tk() def maker(): nb = Notebook(main, name='nbook') nb.grid(row=0, column=0, columnspan=2) frame1 = Frame(name='frame1') txt = Text(frame1, wrap=NONE) txt.grid() nb.add(frame1, text='textwindow') txt.insert('end', 'hello\n' * 1000000) def remover(): print(main.winfo_children()) for tab in main.children['nbook'].tabs(): main.children['nbook'].forget(tab) print(main.winfo_children()) b1 = Button(main, text='Insert', command=maker) b1.grid(row=1, column=0) b2 = Button(main, text='Clear tabs', command=remover) b2.grid(row=1, column=1) main.mainloop() In the example, when you click "Insert" it creates the widget and dumps a bunch of text into it. If you call remover with the "Clear tabs" button it forgets all tabs but the ram used by that text is never free. Even if you destroy the text widget the ram is not released. How can I free this up?
tagged with: python
has answer: http://stackoverflow.com/a/47988908
possible better answer: http://stackoverflow.com/a/50528811
tagged with: tkinter
upvote count: 2
answer count: 3
has answer: http://stackoverflow.com/a/49286807
has title: Clear used RAM for Tkinter TEXT widget

http://stackoverflow.com/q/48001164
tagged with: python
has answer: http://stackoverflow.com/a/63079765
answer count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48001184
has body: I got an error TypeError: unsupported operand type(s) for +: 'PosixPath' and 'str' My code is the following import os import cv2 import random from pathlib import Path path = Path(__file__).parent path = "../img_folder" for f in path.iterdir(): print(f) f = str(f) img=cv2.imread(f) line = random.randint(0, 50) img[3, 3, :] = line cv2.imwrite(path + "/" + "photo.png", img) Traceback says a code of cv2.imwrite~ is wrong. I really cannot understand why this is wrong. Is this type of path error? Or am I wrong to use this method? How should I fix this?
score: 40
downvote count: 1
type: Question
has title: TypeError: unsupported operand type(s) for +: 'PosixPath' and 'str'
has comment: http://stackoverflow.com/comment/82970859
tagged with: opencv
has answer: http://stackoverflow.com/a/48596264
has comment: http://stackoverflow.com/comment/82970812
has answer: http://stackoverflow.com/a/66229328
possible better answer: http://stackoverflow.com/a/48596264
has answer: http://stackoverflow.com/a/48001184
favorite count: 0
upvote count: 41

http://stackoverflow.com/comment/82813701
comment on: http://stackoverflow.com/q/47918761
has text: Possible duplicate of [fatal error: Python.h: No such file or directory](https://stackoverflow.com/questions/21530577/fatal-error-python-h-no-such-file-or-directory)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47858886
has comment: http://stackoverflow.com/comment/82683096
upvote count: 4
has comment: http://stackoverflow.com/comment/82683524
type: AnsweredQuestion
has body: I've written a scraper in python to get different category names from a webpage but it is unable to fetch anything from that page. I'm seriously confused not to be able to figure out where i'm going wrong. Any help would be vastly appreciated. Here is the link to the webpage: URL Here is what I've tried so far: from bs4 import BeautifulSoup import requests res = requests.get("replace_with_above_url",headers={"User-Agent":"Mozilla/5.0"}) soup = BeautifulSoup(res.text,"lxml") for items in soup.select('.slide_container .h3.standardTitle'): print(items.text) Elements within which one such category names I'm after: Furniture Offers #This is the name I'm after
downvote count: 0
has comment: http://stackoverflow.com/comment/82683166
tagged with: web-scraping
tagged with: web-crawler
has title: Can't scrape category titles from a webpage
type: Question
has answer: http://stackoverflow.com/a/47904795
answer count: 2
has comment: http://stackoverflow.com/comment/82683251
accepted answer: http://stackoverflow.com/a/47904795
score: 4
has answer: http://stackoverflow.com/a/47859011
has comment: http://stackoverflow.com/comment/82683027
has comment: http://stackoverflow.com/comment/82683356
possible better answer: http://stackoverflow.com/a/47859011
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82682541
tagged with: python

http://stackoverflow.com/a/47986013
type: Answer
has comment: http://stackoverflow.com/comment/82942353
has comment: http://stackoverflow.com/comment/82941372
upvote count: 1
has body: One way is import sys sentence = input("Enter a sentence:") sentenceLower = sentence.lower() sentenceListLength = len(sentenceLower) for i in range(sentenceListLength) : c = sentenceLower[i] if ( ("a" &lt;= c) and (c &lt;= "z") ) : sys.stdout.write(":regional_indicator_"+c+":") else : # Do your stuff pass You could as well traverse characters with for c in sentenceLower : instead of for i in range(sentenceListLength) : c = sentenceLower[i] (and it would be usually regarded as more pythonic). Using an integer index is sometimes more flexible/versatile (it is up to your case).
score: 1
answers question: http://stackoverflow.com/q/47985695
downvote count: 0
has comment: http://stackoverflow.com/comment/82941100

http://stackoverflow.com/comment/82784899
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47908767
score: 0
has text: Please, tag Python too.

http://stackoverflow.com/a/48755637
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/112057303
upvote count: 2
score: 2
has body: Check out this in the config options # lines of code to run at IPython startup. # c.InteractiveShellApp.exec_lines = [] It allows you to run specific commands on startup. You can also put in scripts in ~/.ipython/profile_default/startup, but depending on your spawner these can require a bit of setup to make sure they get loaded.
answers question: http://stackoverflow.com/q/47978586

image-scanner
tag name: image-scanner
type: Tag
tags question: http://stackoverflow.com/q/47870037

video
tags question: http://stackoverflow.com/q/47879986
type: Tag
tags question: http://stackoverflow.com/q/47902535
tags question: http://stackoverflow.com/q/47979490
tags question: http://stackoverflow.com/q/47999030
tags question: http://stackoverflow.com/q/47968668
tag name: video
tags question: http://stackoverflow.com/q/47949404
tags question: http://stackoverflow.com/q/47912225

http://stackoverflow.com/comment/82872105
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47951270
has text: its true its expecting GET method and you are using POST so find proper method

http://stackoverflow.com/comment/83004076
has text: @DebanjanB I tried with the code: ChromeOptions options = new ChromeOptions(); options.addArguments("allow-file-access-from-files"); options.addArguments("use-fake-device-for-media-stream"); options.addArguments("use-fake-ui-for-media-stream"); WebDriver driver = new ChromeDriver(options); But it is opening new window and that allow camera method getting passed and failed to the next method.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48007699
score: 0

http://stackoverflow.com/q/47885927
score: 6
tagged with: python
upvote count: 6
linked to: http://stackoverflow.com/q/41648103
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/108671014
has title: Is it possible to add new jobs dynamically using concurrent.futures.ThreadPoolExecutor?
downvote count: 0
has comment: http://stackoverflow.com/comment/133326212
tagged with: concurrent.futures
favorite count: 0
has body: The use case I have in mind is as follows: I would like to start a range of jobs with ThreadPoolExecutor and then when a job completes, I would like to add a new job to the queue. I would also like to know when the next job finishes and repeat the procedure above. After I have had the opportunity to observe a predefined number of results, I would like to terminate everything properly. For instance, consider the following code, where the commented out bits in the run_con method show what I would like to achieve. import numpy as np import time from concurrent import futures MAX_WORKERS = 20 seed = 1234 np.random.seed(seed) MSG = "Wall time: {:.2f}s" def expensive_function(x): time.sleep(x) return x def run_con(func, ts): t0 = time.time() workers = min(MAX_WORKERS, len(ts)) with futures.ThreadPoolExecutor(workers) as executor: jobs = [] for t in ts: jobs.append(executor.submit(func, t)) done = futures.as_completed(jobs) for future in done: print("Job complete: ", future.result()) # depending on some condition, add new job to jobs, e.g. # jobs.append(func, np.random.random()) # update done generator # if a threshold on total jobs is reached, close every thing down sensibly. print(MSG.format(time.time()-t0)) ts = np.random.random(10)*5 print("Sleep times: ", ts) run_con(expensive_function, ts) Is this achievable with concurrent.futures? If not, what are the alternatives?
type: UnansweredQuestion

http://stackoverflow.com/comment/82946190
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47986441
type: AnswerComment
has text: Maybe we use different version of Python.

http://stackoverflow.com/q/47871887
type: Question
has comment: http://stackoverflow.com/comment/82846931
has body: Having a query with many eagerloads (and so many LEFT OUTER JOIN), I'm a currently trying to figure out a way to disable MySQL query cache on a per-query basis. So far I have been unable to find any hint on how I might to that in the documentation. Simplest example (without joins): result = session.query(MyTable).filter(Object.id == 42) will generate something like: SELECT MyTable.id AS mytable_id, MyTable.stuff as mytable_stuff, … FROM MyTable WHERE MyTable.id = 42; I'm looking to generate the following statement instead so it won't try to use or fill the query cache: SELECT SQL_NO_CACHE MyTable.id AS mytable_id, MyTable.stuff as mytable_stuff, … FROM MyTable WHERE MyTable.id = 42; Is it actually possible?
tagged with: sqlalchemy
has title: Is there a way to use SQL_NO_CACHE MySQL option in SQLAlchemy?
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/82709813
type: UnansweredQuestion
score: 3
tagged with: python
answer count: 0
upvote count: 3
tagged with: mysql

http://stackoverflow.com/comment/82962935
type: Comment
has text: running `brew reinstall openssl` was required on an upgraded macOS 10.13 machine
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47888872

http://stackoverflow.com/comment/82871044
type: QuestionComment
has text: It's generally poor design to have separate lists for related data like this, this isn't Fortran. Use lists of dictionaries so that you keep all the related information together as named items in each dictionary.
score: 1
comment on: http://stackoverflow.com/q/47950697
type: Comment

http://stackoverflow.com/comment/82972351
type: Comment
has text: Dont have current code however tried different modules which dont work so well in ironpython since its little problematic to import packages in it. Used html in one project as well but looking for pure python option that might require very basic modules
comment on: http://stackoverflow.com/q/48001911
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82763396
has text: Take input from the file and create a data frame. Then follow: https://www.datacamp.com/community/tutorials/python-excel-tutorial
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47898294

http://stackoverflow.com/q/47944401
tagged with: phantomjs
has title: Execute PhantomJS on a Flask Web App on IIS
score: 0
has answer: http://stackoverflow.com/a/48113963
answer count: 1
tagged with: flask
favorite count: 0
has body: I developed a python web app in flask and I'm trying to deploy it correctly on IIS. Before i launch the app to production server I'm testing it on a VM. All the steps i did: Install IIS with CGI With IIS installed, I download the web platform installer I installed the WFastCGI for Python 3 (my version) I configured the Handler Mappings and the CGI Settings to deploy my app, and is all fine. The Website is all working, except one part. One of the functions of the website require execute a webdriver, in this case PhantomJS, with selenium python module. The PhantomJS executable is on the root folder of the website: PhantomJSPath = 'phantomjs/bin/phantomjs.exe' But when i try to use declare the variable to select the webdriver his just don't run on IIS (when i open that specific page of that function it gives me a 500 ERROR, all the other pages work perfectly). The stupid thing is, when i execute by Flask development mode on port 5000 it just works perfectly. browser = webdriver.PhantomJS(PhantomJSPath) I tried a lot of stuff already like give all permissions to everyone on the web app folder and stuff like that. I think the problem is with IIS configuration or security settings. I hope you can help me and all of the other people with the same issue ;) TY
type: UnansweredQuestion
tagged with: python
tagged with: iis
tagged with: selenium
upvote count: 1
downvote count: 1
type: Question

http://stackoverflow.com/comment/83010976
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48011347
has text: I modified my question, please take a look again.

http://stackoverflow.com/comment/82779713
score: 1
type: QuestionComment
has text: @OliverBestwalter : understood, I tried to describe my problem in the edit.
comment on: http://stackoverflow.com/q/47905078
type: Comment

http://stackoverflow.com/comment/82715553
has text: no it did not change , I just tried to make you a point for improve your answer :)
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47871782

http://stackoverflow.com/comment/112683704
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48012758
has text: Office365 app passwords work for me in order to get around two-factor authentication. Creating them is a bit hidden in the settings: https://learn.microsoft.com/en-gb/azure/active-directory/user-help/multi-factor-authentication-end-user-app-passwords Besides, consider using the `shareplum` library instead of using Sharepoint's REST API directly. Most common operations like listing and updating files will be much simpler this way. https://shareplum.readthedocs.io/en/latest/tutorial.html#office-365-authentication

http://stackoverflow.com/q/47942417
favorite count: 0
has body: I have a dataset df_train and some labels for it df_train_labels. print(df_train.shape) print(df_train_labels.shape) outputs: (1460, 6) (1460,) and print(df_train[0:4]) print(df_train_labels[0:4]) outputs OverallQual GrLivArea GarageCars TotalBsmtSF FullBath YearBuilt 0 1 0.000000 1 1 1 1 1 1 0.000000 0 1 0 1 2 0 0.693147 0 2 0 2 3 0 1.098612 1 3 1 3 0 2.505338 1 2.493950 2 2.510994 3 2.472277 Name: SalePrice, dtype: float64 I am trying to fit a model on this data: from sklearn.ensemble import RandomForestClassifier clf = RandomForestClassifier(n_estimators=10) clf = clf.fit(df_train, df_train_labels) However, the last line fails with this error: raise ValueError("Unknown label type: %r" % y_type) ValueError: Unknown label type: 'continuous' I looked here and here but I didn't see any information relevant to my problem. Any idea what could be wrong?
tagged with: pandas
tagged with: python
upvote count: 2
type: UnansweredQuestion
downvote count: 1
type: Question
tagged with: dataframe
has comment: http://stackoverflow.com/comment/82854463
has answer: http://stackoverflow.com/a/47942883
has title: ValueError: Unknown label type: 'continuous' when applying Random Forrest
answer count: 2
linked to: http://stackoverflow.com/q/45645716
score: 1
tagged with: scikit-learn
linked to: http://stackoverflow.com/q/45645043
has answer: http://stackoverflow.com/a/61303961

http://stackoverflow.com/comment/82998662
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48013544
score: 0
has text: glad I could help! Best of luck. feel free to self-answer and I will gladly upvote it

http://stackoverflow.com/q/47991624
score: 4
tagged with: pymssql
upvote count: 4
answer count: 1
downvote count: 0
has body: I have a procedure in sql server that returns multiple tables: create procedure newtest as begin select 1 as a select 2 as b end In python, cursor.description just returns first column name: a I want to get every column name in each table. How can I do that? This is my code: cur.execute(com) num_tables=0 while True: print(cur.description) ret=cur.fetchall() if len(ret)&gt;0: ret_list.append(ret) num_tables+=1 print(ret) else: break
favorite count: 0
has comment: http://stackoverflow.com/comment/82951848
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48208861
type: Question
has title: Can't get column names after first table return from Stored procedure in pymssql

http://stackoverflow.com/a/47931440
accepted answer of: http://stackoverflow.com/q/47931356
type: Answer
has comment: http://stackoverflow.com/comment/82831800
has comment: http://stackoverflow.com/comment/82831731
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/47931356
type: AcceptedAnswer
has body: The way this is normally done is: JSON_PATH_SRC = "src" JSON_PATH_DST = "dst" JSON_URL_SRC = "src" JSON_URL_DST = "dst" pathPacket[JSON_PATH_SRC] = "/tmp" pathPacket[JSON_PATH_DST] = "/home/user/out" urlPacket[JSON_URL_SRC] = "localhost" urlPacket[JSON_URL_SRC] = "contoso" Upper-case to denote "constants" is the way it goes. You'll see this in the standard library, and it's even recommended in PEP8: Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include MAX_OVERFLOW and TOTAL. Python doesn't have true constants, and it seems to have survived without them. If it makes you feel more comfortable wrapping this in a class that uses ABCmeta with properties, go ahead. Indeed, I'm pretty sure abc.ABCmeta doesn't not prevent object initialization. Indeed, if it did, your use of property would not work! property objects belong to the class, but are meant to be accessed from an instance. To me, it just looks like a lot of rigamarole for very little gain.
downvote count: 0
has comment: http://stackoverflow.com/comment/82831680

http://stackoverflow.com/comment/82750228
score: 0
comment on: http://stackoverflow.com/q/47891623
type: Comment
type: QuestionComment
has text: Set is not serializable...

http://stackoverflow.com/q/47951268
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/82872058
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82872074
downvote count: 1
has answer: http://stackoverflow.com/a/47951453
has title: Copy Django App to a New Project but Model Data is Lost
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82872107
type: Question
has body: I made a development django project on my pc, and I added a bunch of data for one of the apps "things" by logging in the ADMIN panel. When I copy and paste this app folder into a new project on Ubuntu, add this app in setting, then I find all the data in the model is gone. I used "makemigrations, migrate". Still nothing. What should I do to have those data in this new project?
has comment: http://stackoverflow.com/comment/82872215
answer count: 1
accepted answer: http://stackoverflow.com/a/47951453

http://stackoverflow.com/comment/82736995
comment on: http://stackoverflow.com/q/47885008
score: 0
type: Comment
type: QuestionComment
has text: ^ true, comment will be removed in 3, 2, 1 GO. (this one will be deleted soon too)

http://stackoverflow.com/comment/82933594
type: Comment
comment on: http://stackoverflow.com/a/47982176
has text: @MartinBouhier When I tried running this code with `['archivo1.xlsx', 'archivo2.xlsx', 'archivo.xlsx']`, it worked perfectly for me. Can you please check and make sure that the structure of `archivo3` is the same as the rest of them??
type: AnswerComment
score: 0

http://stackoverflow.com/q/47960004
answer count: 1
has body: I have been trying to use Stanford Core NLP over a data set but it stops at certain indexes which I am unable to find. The data set is available on Kaggle: https://www.kaggle.com/PromptCloudHQ/amazon-reviews-unlocked-mobile-phones/data This is a function that outputs the sentiment of a paragraph by taking the mean sentiment value of individual sentences. import json def funcSENT(paragraph): all_scores = [] output = nlp.annotate(paragraph, properties={ "annotators": "tokenize,ssplit,parse,sentiment", "outputFormat": "json", # Only split the sentence at End Of Line. We assume that this method only takes in one single sentence. #"ssplit.eolonly": "true", # Setting enforceRequirements to skip some annotators and make the process faster "enforceRequirements": "false" }) all_scores = [] for i in range(0,len(output['sentences'])): all_scores.append((int(json.loads(output['sentences'][i]['sentimentValue']))+1)) final_score = sum(all_scores)/len(all_scores) return round(final_score) Now I run this code for every review in the 'Reviews' column using this code. import pandas as pd data_file = 'C:\\Users\\SONY\\Downloads\\Amazon_Unlocked_Mobile.csv' data = pd.read_csv( data_file) from pandas import * i = 0 my_reviews = data['Reviews'].tolist() senti = [] while(i&lt;data.shape[0]): senti.append(funcSENT(my_reviews[i])) i=i+1 But somehow I get this error and I am not able to find the problem. Its been many hours now, kindly help. [1]: https://i.sstatic.net/qFbCl.jpg How to avoid this error?
downvote count: 0
favorite count: 0
tagged with: keyerror
has title: Unable to run Stanford Core NLP annotator over whole data set
type: UnansweredQuestion
tagged with: python
score: 1
upvote count: 1
type: Question
tagged with: stanford-nlp
linked to: http://stackoverflow.com/q/46678204
tagged with: typeerror
has answer: http://stackoverflow.com/a/47963585
tagged with: sentiment-analysis

http://stackoverflow.com/q/47871084
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/47871526
tagged with: tkinter
upvote count: 1
answer count: 1
has body: I'm facing some trouble aligning tkinter widgets when located in different frames, as shown I have 3 frames: main_frame - colored in blue, containing 3 subframes: buttons_frame,timers_frame,switches_frame, which all centered to main_frame, one on top of other. Design requires: all widgets in all subframes will be centered inside its frame. As shown in attached pic, and code - middle sub-frame, timers_frame is streched OK to max size using tk.E+tk.w, BUT widgets inside positioned at row=0, column=0 and not aligning to center of streched frame. Using tk.E+tk.W didn't solve it. Solving it without using sub-frames, works OK. Relevant portion of code: class CoreButton(ttk.Frame): def __init__(self, master, nickname='CoreBut.inc', hw_in=[], hw_out=[], ip_in='', \ ip_out='', sched_vector=[], num_buts=1): ttk.Frame.__init__(self, master) # Styles self.style = ttk.Style() self.style.configure("Azure.TFrame", background='azure4') self.style.configure("Blue.TFrame", background='blue') self.style.configure("Blue2.TFrame", background='light steel blue') self.style.configure("Red.TButton", foreground='red') # Frames # Buttons&amp;Indicators py, px = 4, 4 self.main_frame = ttk.Frame(self, style="Blue2.TFrame", relief=tk.RIDGE) self.main_frame.grid() self.buttons_frame = ttk.Frame(self.main_frame, relief=tk.RIDGE, style="Azure.TFrame") self.buttons_frame.grid(row=0, column=0, pady=py, padx=px) # Counters self.timers_frame = ttk.Frame(self.main_frame, relief=tk.RIDGE, border=5, style="Azure.TFrame") self.timers_frame.grid(row=1, column=0, pady=py, padx=px, sticky=tk.E+tk.W) # Extra GUI self.switches_frame = ttk.Frame(self.main_frame, relief=tk.RIDGE, border=5, style="Azure.TFrame") self.switches_frame.grid(row=2, column=0, pady=py) # Run Gui # self.build_gui() self.extras_gui() def extras_gui(self): ck1 = tk.Checkbutton(self.switches_frame, text='On/Off', variable=self.on_off_var, \ indicatoron=1, command=self.disable_but) ck1.grid(row=0, column=0) ck2 = tk.Checkbutton(self.switches…
accepted answer: http://stackoverflow.com/a/47871526
tagged with: grid-layout
has title: Python - Widget alignment when using multiple frames
type: AnsweredQuestion

http://stackoverflow.com/comment/82903922
has text: @guillermo chamorro, I checked using unicodeDammit it gave me: [windows-1252], [iso-8859-1], [iso-8859-2]. I thought about using BitesI0, but all my sorting is based on strings match
comment on: http://stackoverflow.com/q/47942623
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47930367
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/47930345
downvote count: 0
has body: Try to use loc[]: In [11]: df.loc[mask, 'A'] *= -1 In [12]: df Out[12]: A B 0 -0.050562 0.499951 1 -0.995909 0.693599 2 -0.418302 -1.584577 3 -0.647707 0.598575 4 -0.332250 -1.147477
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47930345
upvote count: 2

http://stackoverflow.com/comment/82811446
comment on: http://stackoverflow.com/a/47921600
score: 0
type: Comment
type: AnswerComment
has text: i think your iteration code in template has a problem. try changing `{% for person in context.team %}` to `{% for key, person in context.items %}`

http://stackoverflow.com/comment/120234643
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/66964977
has text: i haven't programmed in python in like a year and a half. i have no idea if this is correct or not because the script was abandoned/replaced and i don't even work there anymore.
type: Comment

http://stackoverflow.com/comment/82916108
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47973244
type: Comment
has text: You seem to use a virtual environment already. It might be best to learn to use them properly. A good tutorial can be found at http://docs.python-guide.org/en/latest/dev/virtualenvs/

http://stackoverflow.com/q/47867748
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50822269
linked to: http://stackoverflow.com/q/46423956
has title: Transfer learning with tf.estimator.Estimator framework
tagged with: tensorflow
has answer: http://stackoverflow.com/a/47883472
upvote count: 17
type: Question
has comment: http://stackoverflow.com/comment/82723236
score: 17
tagged with: tensorflow-estimator
answer count: 2
possible better answer: http://stackoverflow.com/a/50822269
has comment: http://stackoverflow.com/comment/82722752
has body: I'm trying to do transfer learning of an Inception-resnet v2 model pretrained on imagenet, using my own dataset and classes. My original codebase was a modification of a tf.slim sample which I can't find anymore and now I'm trying to rewrite the same code using the tf.estimator.* framework. I am running, however, into the problem of loading only some of the weights from the pretrained checkpoint, initializing the remaining layers with their default initializers. Researching the problem, I found this GitHub issue and this question, both mentioning the need to use tf.train.init_from_checkpoint in my model_fn. I tried, but given the lack of examples in both, I guess I got something wrong. This is my minimal example: import sys import os os.environ['CUDA_VISIBLE_DEVICES'] = '-1' import tensorflow as tf import numpy as np import inception_resnet_v2 NUM_CLASSES = 900 IMAGE_SIZE = 299 def input_fn(mode, num_classes, batch_size=1): # some code that loads images, reshapes them to 299x299x3 and batches them return tf.constant(np.zeros([batch_size, 299, 299, 3], np.float32)), tf.one_hot(tf.constant(np.zeros([batch_size], np.int32)), NUM_CLASSES) def model_fn(images, labels, num_classes, mode): with tf.contrib.slim.arg_scope(inception_resnet_v2.inception_resnet_v2_arg_scope()): logits, end_points = inception_resnet_v2.inception_resnet_v2(images, num_classes, is_training=(mode==tf.estimator.ModeKeys.TRAIN)) predictions = { 'classes': tf.argmax(input=logits, axis=1), 'probabilities': tf.nn.softmax(logits, name='softmax_tensor') } if mode == tf.estimator.ModeKeys.PREDICT: return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions) exclude = ['InceptionResnetV2/Logits', 'InceptionResnetV2/AuxLogits'] variables_to_restore = tf.contrib.slim.get_variables_to_restore(exclude=exclude) scopes = { os.path.dirname(v.name) for v in variables_to_restore } tf.train.init_from_checkpoint('inception_resnet_v2_2016_08_30.ckpt', {s+'/':s+'/' for s in scopes}) tf.losses.softmax_cross_entr…
downvote count: 0
has comment: http://stackoverflow.com/comment/82722418
has comment: http://stackoverflow.com/comment/82731665
favorite count: 0
has comment: http://stackoverflow.com/comment/88557068
tagged with: python
accepted answer: http://stackoverflow.com/a/47883472

http://stackoverflow.com/comment/82978604
comment on: http://stackoverflow.com/q/47989741
type: Comment
type: QuestionComment
has text: @ShpielMeister, I have edited the post to include the stacktrace - thank you for the help!
score: 0

http://stackoverflow.com/q/47972499
has answer: http://stackoverflow.com/a/47972545
tagged with: python
has answer: http://stackoverflow.com/a/47980048
accepted answer: http://stackoverflow.com/a/47980048
type: AnsweredQuestion
has title: How can I convert a list of strings into sympy variables?
possible better answer: http://stackoverflow.com/a/47972545
type: Question
upvote count: 4
answer count: 2
tagged with: sympy
downvote count: 0
score: 4
favorite count: 0
has body: I have a list of strings, e.g., var = ['x', 'y', 'z']. I want to use these strings as sympy 'symbols'. I am trying to do this: for i in var: i = symbols('i') it's not working of course. Can someone help me with this?

http://stackoverflow.com/q/47886582
has body: I have a python project where I want to log multiple events across different modules in a single rotating file. I am using logzero for this. For example: If I need logging from init.py and main.py, how can I using only a single log file to log both the events?
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82738999
favorite count: 0
tagged with: python
tagged with: logging
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47886771
has title: Logging to a single file across different modules in python
accepted answer: http://stackoverflow.com/a/47886771
downvote count: 0
score: 1
type: Question

http://stackoverflow.com/comment/82895864
has text: When nothing references it anymore. As a side note, it's better to use Python 3.
comment on: http://stackoverflow.com/q/47963275
score: 4
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47909316
score: 1
has body: Using join (to join list elements) and map(str,myList) to convert all integers inside list to strings ','.join(map(str,myList[:-1])) + ' and ' + str(myList[-1]) #'1,2,3 and 4'
upvote count: 1
answers question: http://stackoverflow.com/q/47908919
type: Answer
downvote count: 0

http://stackoverflow.com/comment/82874021
comment on: http://stackoverflow.com/a/47951968
type: AnswerComment
has text: In admin UI yes, but not in the shell.
score: 0
type: Comment

http://stackoverflow.com/q/47973496
favorite count: 0
has comment: http://stackoverflow.com/comment/121717901
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82925259
tagged with: python
has comment: http://stackoverflow.com/comment/82916696
has title: Can't Find Device with PyUSB
has body: I found my device's VID and PID in the properties for the device on windows, which are 256 for the VID and 006 for the PID. I can't seem to get pyusb to find it. From what I've seen, most people put the VID and PID in hex, which I tried and it still doesn't work. Here's my code: import usb.core import usb.util VID = 256 PID = 6 dev = usb.core.find(idVendor=VID, idProduct=PID) dev is always None. Any clue what I did wrong? EDIT: I just tested with another device with a VID of 0x046D and a PID of 0xC21D and it still returns None. EDIT 2: I have libusb installed and I've tried running the script in both Python 3.4 and Python 2.7. It always returns None.
score: 1
upvote count: 1
tagged with: pyusb
has comment: http://stackoverflow.com/comment/82917937
type: Question
has comment: http://stackoverflow.com/comment/82916717
has comment: http://stackoverflow.com/comment/82924801
has comment: http://stackoverflow.com/comment/82916736
has comment: http://stackoverflow.com/comment/82916683
has answer: http://stackoverflow.com/a/47978345
has comment: http://stackoverflow.com/comment/82916654
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82916647

http://stackoverflow.com/a/59559649
answers question: http://stackoverflow.com/q/47969493
score: 0
type: Answer
has body: The below bubble sort code works on tensorflow with eager execution enabled. Should work without eager execution too :) import tensorflow as tf import tensorflow.contrib.eager as tfe tfe.enable_eager_execution() n1= tf.contrib.eager.Variable([1,3,7,5,2]) n1_len= n1.get_shape()[0] print (n1_len) for i in range(n1.get_shape()[0]): for j in range (n1.get_shape()[0]): if tf.math.less(n1[i],n1[j]): temp=n1[i] tf.scatter_update(n1,i,n1[j]) tf.scatter_update(n1,j,temp) print (n1) Output: &lt;tf.Variable 'Variable:0' shape=(5,) dtype=int32, numpy=array([3, 1, 7, 5, 2], dtype=int32)&gt; &lt;tf.Variable 'Variable:0' shape=(5,) dtype=int32, numpy=array([7, 1, 3, 5, 2], dtype=int32)&gt; &lt;tf.Variable 'Variable:0' shape=(5,) dtype=int32, numpy=array([1, 7, 3, 5, 2], dtype=int32)&gt; &lt;tf.Variable 'Variable:0' shape=(5,) dtype=int32, numpy=array([1, 3, 7, 5, 2], dtype=int32)&gt; &lt;tf.Variable 'Variable:0' shape=(5,) dtype=int32, numpy=array([1, 3, 5, 7, 2], dtype=int32)&gt; &lt;tf.Variable 'Variable:0' shape=(5,) dtype=int32, numpy=array([1, 2, 5, 7, 3], dtype=int32)&gt; &lt;tf.Variable 'Variable:0' shape=(5,) dtype=int32, numpy=array([1, 2, 3, 7, 5], dtype=int32)&gt; &lt;tf.Variable 'Variable:0' shape=(5,) dtype=int32, numpy=array([1, 2, 3, 5, 7], dtype=int32)&gt;

http://stackoverflow.com/a/68728834
answers question: http://stackoverflow.com/q/47967490
has body: If you're using an old version of pudb that doesn't support pudb.forked.set_trace(), you can use pudb.remote.set_trace to debug multiprocessing code. This post has a nice overview of how to do this: https://auro-227.medium.com/use-pudb-to-debug-python-multiprocessing-code-c0c5551d010c
type: Answer
score: 0

http://stackoverflow.com/comment/82693524
comment on: http://stackoverflow.com/q/47864235
score: 0
type: Comment
type: QuestionComment
has text: Could you provide the output of: `import sys; print(sys.path)` for us?

http://stackoverflow.com/q/47926257
has answer: http://stackoverflow.com/a/48457449
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/48457449
possible better answer: http://stackoverflow.com/a/47927407
downvote count: 0
has answer: http://stackoverflow.com/a/47927407
tagged with: pymodbus3
tagged with: minimalmodbus
has comment: http://stackoverflow.com/comment/82877423
favorite count: 0
tagged with: modbus
has body: I am working on a slave computer and want to save the data transmitted from the master via Modbus RS485, into a text file. The master computer constantly send writing and reading request to the slave computer I am working on, below is a picture captured by serial port monitor. I just found with minimalmodbus you can read registers. But it seems to only work if you are a master device. Can I do something similar but on a slave computer? http://minimalmodbus.readthedocs.io/en/master/usage.html #!/usr/bin/env python import minimalmodbus instrument = minimalmodbus.Instrument('/dev/ttyUSB1', 1) # port name, slave #address (in decimal) ## Read temperature (PV = ProcessValue) ## temperature = instrument.read_register(289, 1) # Registernumber, number of #decimals print temperature ## Change temperature setpoint (SP) ## NEW_TEMPERATURE = 95 instrument.write_register(24, NEW_TEMPERATURE, 1) # Registernumber, value, #number of decimals for storage
upvote count: 1
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/48708648
has title: Can I read Modbus RS485 data received on a slave computer with Python?
tagged with: rs485
score: 1

http://stackoverflow.com/comment/82758593
type: Comment
has text: No it requires authentication to access this page. However if you have a suspicion that some other element might be blocking this from working, I would be happy to try that out.
type: QuestionComment
comment on: http://stackoverflow.com/q/47893201
score: 0

http://stackoverflow.com/comment/83374185
score: 0
type: Comment
type: QuestionComment
has text: Hi @DrSokoban - just the suggestion above (to replace it with an empty function).
comment on: http://stackoverflow.com/q/47988877

http://stackoverflow.com/a/48016056
score: 1
answers question: http://stackoverflow.com/q/48005171
type: Answer
has body: Event KEYDOWN has event.unicode, event.key, event.mod You can compare if event.type == pygame.KEYDOWN: if event.unicode == "a": or even if event.type == pygame.KEYDOWN: if event.unicode.lower() == "a": to check "a" and "A" To check char in word if event.type == pygame.KEYDOWN: if event.unicode.lower() in your_word.lower(): Example code use event.unicode to render text with pressed keys. BTW: It is not some Entry widget so it doesn't delete char when you press backspace. import pygame # --- constants --- BLACK = ( 0, 0, 0) WHITE = (255, 255, 255) BLUE = ( 0, 0, 255) GREEN = ( 0, 255, 0) RED = (255, 0, 0) SCREEN_WIDTH = 300 SCREEN_HEIGHT = 200 FPS = 5 # `FPS = 25` is enough for human eye to see animation. # If your program don't use animation # then `FPS = 5` or even `FPS = 1` can be enough # --- main --- # - init - pygame.init() screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT)) screen_rect = screen.get_rect() # - objects - font = pygame.font.SysFont(None, 30) text = "" text_image = font.render(text, True, GREEN) text_rect = text_image.get_rect() # get current size text_rect.center = screen_rect.center # center on screen # - mainloop - clock = pygame.time.Clock() done = False while not done: # - events - for event in pygame.event.get(): if event.type == pygame.QUIT: done = True elif event.type == pygame.KEYDOWN: text += event.unicode text_image = font.render(text, True, GREEN) text_rect = text_image.get_rect() # get current size text_rect.center = screen_rect.center # center on screen # - draws - screen.fill(BLACK) screen.blit(text_image, text_rect) pygame.display.flip() clock.tick(FPS) # - end - pygame.quit() # &lt;-- quit(), not init()
upvote count: 1
downvote count: 0

http://stackoverflow.com/q/47894281
linked to: http://stackoverflow.com/q/5019209
has comment: http://stackoverflow.com/comment/82756627
has title: Implement an optional context manager in Python
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: with-statement
has comment: http://stackoverflow.com/comment/82756465
has comment: http://stackoverflow.com/comment/82755650
has body: We have a codebase with the following use pattern: factory = DataFactory(args) dataset = factory.download_and_cache_big_dataset(key) metadata = dataset.get_some_metadata() Currently, download_and_cache_big_dataset fetches a very large file from S3 and puts it somewhere. Among other things, it does filename = get_s3_key(key) filepath = os.path.join(get_tmp_dir(), filename) s3.download_file(key, filepath) return BigFileClass(filepath) # gets stored in a class somewhere However, this file doesn't get deleted. This is fine when this function is called sparingly and relies on file caching, but bad when it is called repeatedly and we don't want to fill up the disk. Is there a way to refactor the code with a context manager such that we can use it as factory = DataFactory(args) with factory.download_and_cache_big_dataset(key) as dataset: metadata = dataset.get_some_metadata() # do something with metadata # file gets automatically deleted But critically, without breaking the existing usage, so that the other code works as is? Or will there need to be a different method that returns the context manager?
upvote count: 1
has answer: http://stackoverflow.com/a/47894995
type: Question
has comment: http://stackoverflow.com/comment/82756630
tagged with: contextmanager
score: 1
tagged with: temporary-files
has comment: http://stackoverflow.com/comment/82759285

http://stackoverflow.com/a/47876792
upvote count: 1
answers question: http://stackoverflow.com/q/47876248
has body: IIUC what your issue is, I changed your data frame's time column name, df.rename(columns={0:'Time'}, inplace= True) df Time 1 2 3 4 5 6 7 23:10:50 all 28.36 0.00 0.38 0.25 0.00 71.02 23:10:51 all 22.77 0.00 0.84 0.12 0.00 76.27 23:10:52 all 32.06 0.00 0.86 0.00 0.00 67.08 23:10:53 all 31.38 0.00 0.61 0.00 0.00 68.01... Now I can change your Time column into timedelta64[ns] df.Time = pd.to_timedelta(df.Time) df When I type df.dtypes, I get this, Time timedelta64[ns] 1 object 2 float64 3 float64 4 float64 5 float64 6 float64 7 float64 dtype: object So, you have to convert your column into timedelta, your seaborn plot should work.
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/a/48008856
answers question: http://stackoverflow.com/q/48008612
downvote count: 0
has body: Since dicts are inherently unordered, you would have to order its items first. Given your example data, you want to skip the first and last by key: for k in sorted(capitals)[1:-1]: print(capitals[k])
type: Answer
upvote count: 3
score: 3

http://stackoverflow.com/a/48008488
type: Answer
answers question: http://stackoverflow.com/q/48007936
score: 0
has body: Creating a list of dictionaries for the groups: groups = [{'G1': 12}, {'G2': 15}, {'G1': 9}, {'G3': 18}, {'G2': 17}, {'G3': 6}, {'G1': 20}] Getting values into their groups: result = dict() for d in groups: for k, v in d.items(): if k in result: result[k].append(v) else: result[k] = [v] Calculating averages group-wise: averages = [] for d in result: averages.append((d, sum(result[d]) / len(result[d]))) print(averages) [('G1', 13.666666666666666), ('G2', 16.0), ('G3', 12.0)] &gt;&gt;&gt;

http://stackoverflow.com/comment/82965978
type: AnswerComment
has text: if I add points of the hundreds then it will no match to existing rules and there will be problem to edit it later - it would need more work. You would have to convert it back to version without points when you focus in or change all rules.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/47990190

eclipse
tag name: eclipse
tags question: http://stackoverflow.com/q/47875459
tags question: http://stackoverflow.com/q/47892879
tags question: http://stackoverflow.com/q/47952935
tags question: http://stackoverflow.com/q/47990769
tags question: http://stackoverflow.com/q/47856447
tags question: http://stackoverflow.com/q/47996308
type: Tag

http://stackoverflow.com/a/47883951
has comment: http://stackoverflow.com/comment/82733694
accepted answer of: http://stackoverflow.com/q/47883821
answers question: http://stackoverflow.com/q/47883821
score: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82733984
upvote count: 3
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/82733822
has body: Iterate over all buttons in the list, and check if button is event.widget: def Function(event): for button in listOfButtons: if button is event.widget: print(button['text']) return As @tobias_k mentioned - it's overcomlicated. You already has a button as event.widget. So solution is simple as print(event.widget['text']). However, if Function can be called not only from the button click or there're several lists with buttons/with whatever - it's a must to check! In other side, button can be pressed not only by the Left-mouse click, hence command option is better! import tkinter root = tkinter.Tk() def Function(button): print(button['text']) ... Button = tkinter.Button(root, text="Button 1") Button.configure(command=lambda button=Button: Function(button)) ... Button = tkinter.Button(root, text="Button 2") Button.configure(command=lambda button=Button: Function(button)) ... root.mainloop()

http://stackoverflow.com/q/47953523
type: Question
has comment: http://stackoverflow.com/comment/82880220
has body: I got the following list called "phonenumbers". I struggle to remove the elements which contain '\n\t\t\t' and '\n\t\t\t\t'. I tried "try and except"-methode and remove('\n\t\t\t\t') but couldnt make it work. Any tips? ['(02271) 6 79', ' 70', '\n\t\t\t', '(02271) 6 79', '\n\t\t\t\t', ' 70', '\n\t\t\t', '\n\t\t\t', '(02181) 27 0', '\n\t\t\t\t', '3-0', '\n\t\t\t', '\n\t\t\t', '(02181) 27 0', '\n\t\t\t\t', '3-0', '\n\t\t\t', '\n\t\t\t', '(02161) 24 19', '\n\t\t\t\t', ' 40', '\n\t\t\t', '\n\t\t\t', '(02161) 24 19', '\n\t\t\t\t', ' 40', '\n\t\t\t', '\n\t\t\t', '(02131) 66 67', '\n\t\t\t\t', ' 10', '\n\t\t\t', '\n\t\t\t', '(02131) 66 67', '\n\t\t\t\t', ' 10', '\n\t\t\t', '\n\t\t\t', '(02103) 39 00', '\n\t\t\t\t', ' 93', '\n\t\t\t', '\n\t\t\t', '(02103) 39 00', '\n\t\t\t\t', ' 93', '\n\t\t\t', '\n\t\t\t', '(02173) 2 04 7', '\n\t\t\t\t', '3-0', '\n\t\t\t', '\n\t\t\t', '(02173) 2 04 7', '\n\t\t\t\t', '3-0', '\n\t\t\t', '\n\t\t\t', '(02235) 9 23 04', '\n\t\t\t\t', ' 30', '\n\t\t\t', '\n\t\t\t', '(02235) 9 23 04', '\n\t\t\t\t', ' 30', '\n\t\t\t', '\n\t\t\t', '\n\t\t\t\t', '(0221) 3 46 79 40', '\n\t\t\t', '\n\t\t\t', '\n\t\t\t\t', '(0221) 3 46 79 40', '\n\t\t\t', '\n\t\t\t', '(02232) 4 23', '\n\t\t\t\t', ' 05', '\n\t\t\t', '\n\t\t\t', '(02232) 4 23', '\n\t\t\t\t', ' 05', '\n\t\t\t', '\n\t\t\t', '(0157) 86 85 74', '\n\t\t\t\t', ' 43', '\n\t\t\t', '\n\t\t\t', '(0157) 86 85 74', '\n\t\t\t\t', ' 43', '\n\t\t\t', '\n\t\t\t', '(02181) 2 78 11', '\n\t\t\t\t', ' 47', '\n\t\t\t', '\n\t\t\t', '(02181) 2 78 11', '\n\t\t\t\t', ' 47', '\n\t\t\t', '\n\t\t\t', '(02181) 47 49 0', '\n\t\t\t\t', '0-0', '\n\t\t\t', '\n\t\t\t', '(02181) 47 49 0', '\n\t\t\t\t', '0-0', '\n\t\t\t', '\n\t\t\t', '(02202) 1 88', '\n\t\t\t\t', ' 60', '\n\t\t\t', '\n\t\t\t', '(02202) 1 88', '\n\t\t\t\t', ' 60', '\n\t\t\t', '\n\t\t\t', '(0211) 23 80', '\n\t\t\t\t', ' 70', '\n\t\t\t', '\n\t\t\t', '(0211) 23 80', '\n\t\t\t\t', ' 70', '\n\t\t\t', '\n\t\t\t', '(02235) 9 23 0', '\n\t\t\t\t', '4-0', '\n\t\t\t', '\n\t\t\t', '(022…
has comment: http://stackoverflow.com/comment/82877163
answer count: 3
has answer: http://stackoverflow.com/a/47953542
tagged with: python
score: -2
tagged with: regex
has answer: http://stackoverflow.com/a/47953653
favorite count: 0
has answer: http://stackoverflow.com/a/47953543
has title: Remove an '\\n\\t\\t\\t'-element from list
has comment: http://stackoverflow.com/comment/82876333
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82876294
upvote count: 3
has comment: http://stackoverflow.com/comment/82876411
downvote count: 5

http://stackoverflow.com/q/47890820
answer count: 0
tagged with: process
type: Question
tagged with: kernel32
has title: UnicodeEncodeError: trying to print win32_process (wmi module)
tagged with: wmi
score: 0
has body: i'm trying to print all the process ( like task mannager), so i used this code : from ctypes import * import wmi c = wmi.WMI() kernel32 = windll.kernel32 i = 0 txt = "" for process in c.Win32_Process(): try: txt = txt + str(process) except: print process most of the process (about 144/146) pass the try and then i print all together but there are about 2 process that fail the try, and the except and raise this error while i'm trying to print them: UnicodeEncodeError: 'ascii' codec can't encode characters in position 178-181: ordinal not in range(128) someone know what to do?
has comment: http://stackoverflow.com/comment/82748384
type: UnansweredQuestion
tagged with: win32-process
tagged with: python
has comment: http://stackoverflow.com/comment/82752197

http://stackoverflow.com/a/47909906
upvote count: 4
answers question: http://stackoverflow.com/q/47909595
downvote count: 0
has comment: http://stackoverflow.com/comment/82789598
has body: You can try this .. df.hits.shift().rolling(3,min_periods=1).mean().fillna(df.hits) Out[692]: 0 14225.000000 1 14225.000000 2 14395.000000 3 14456.666667 4 14457.333333 5 14458.333333 6 14459.000000 7 14454.666667 Name: hits, dtype: float64 Update df['new']=df.groupby('site').hits.apply(lambda x : x.shift().rolling(3,min_periods=1).mean().fillna(x)) df Out[712]: date site iso id hits new 0 2017-08-25 google 1 7012 14225.0 14225.000000 1 2017-08-26 google 1 7012 14565.0 14225.000000 2 2017-08-27 google 1 7012 14580.0 14395.000000 3 2017-08-28 google 1 7012 14227.0 14456.666667 4 2017-08-29 google 1 7012 14568.0 14457.333333 5 2017-08-30 google 1 7012 14582.0 14458.333333 6 2017-08-31 google 1 7012 14214.0 14459.000000 7 2017-09-01 google 1 7012 14053.0 14454.666667 8 2017-08-25 facebook 2 7019 21225.0 21225.000000 9 2017-08-26 facebook 2 7019 21565.0 21225.000000 10 2017-08-27 facebook 2 7019 31580.0 21395.000000 11 2017-08-28 facebook 2 7019 13227.0 24790.000000 12 2017-08-29 facebook 2 7019 22568.0 22124.000000 13 2017-08-30 facebook 2 7019 44582.0 22458.333333 14 2017-08-31 facebook 2 7019 32214.0 26792.333333 15 2017-09-01 facebook 2 7019 44053.0 33121.333333
has comment: http://stackoverflow.com/comment/82790360
has comment: http://stackoverflow.com/comment/82791582
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82789146
has comment: http://stackoverflow.com/comment/82788939
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/82789673
accepted answer of: http://stackoverflow.com/q/47909595

communication
tag name: communication
type: Tag
tags question: http://stackoverflow.com/q/47894191

http://stackoverflow.com/a/47902269
type: Answer
downvote count: 0
has body: Assuming your list contains strings such as "-0.744342 dog", and my_word_list is a list of strings, how about this: worddict = dict(map(lambda x: (x, True), my_word_list)) import re for item in my_list: parts = re.split("\s+", item) if len(parts) != 2: raise ValueError("Wrong data format") logvalue, word = float(parts[0]), parts[1] if logvalue &gt; TRESHHOLD and word in worddict: print("Hurrah, a match!") Note the first line, which makes a dictionary out of your list of words. If you don't do this, you'll waste a lot of time doing linear searches through your word list, causing your algorithm to have a time complexity of O(n*m), while the solution I propose is much closer to O(n+m), n being the number of lines in my_list, m being the number of words in my_word_list.
answers question: http://stackoverflow.com/q/47901771
score: 1
upvote count: 1

http://stackoverflow.com/q/47991331
tagged with: python
has comment: http://stackoverflow.com/comment/82950933
has comment: http://stackoverflow.com/comment/82951572
has comment: http://stackoverflow.com/comment/82951333
tagged with: http://stackoverflow.com/tag/json
tagged with: virus
type: Question
tagged with: api
score: 0
has comment: http://stackoverflow.com/comment/82951210
has body: I am currently working on a virus scanner and I am using VirusTotal API to scan but it returns an error here is the code: def Send_File(file): params = {'API Key': API_KEY} files = {'file': ('check.py', open('check.py', 'rb'))} response=requests.post('https://www.virustotal.com/vtapi/v2/file/scan', files=files, params=params) json_response = response.json()
answer count: 0
has title: VirusTotal api No JSON object could be decoded
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82951019

http://stackoverflow.com/comment/82919520
has text: whatever you do, `Users` should almost certainly not be an iterator, either define you own class or make `__iter__` a generator function. Or looking at your `__iter__` and `__next__` implementations, just do `def __iter__(self): return iter(self.users)`
type: Comment
comment on: http://stackoverflow.com/q/47974960
type: QuestionComment
score: 1

http://stackoverflow.com/q/48010839
type: Question
has title: get all links from one node in HTML
has comment: http://stackoverflow.com/comment/82990499
answer count: 1
has answer: http://stackoverflow.com/a/48011094
tagged with: beautifulsoup
score: 0
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/82990122
type: UnansweredQuestion
tagged with: python
has body: I'm trying to get all the links that are linked to one node, having a structure like: <a href "C"> I would like all the links from "data-vc-node-id="10"" and I'm trying to get them doing something like: for tag in soup.findAll('data-vc-node-id="10"',href=True): print tag But of course, I'm getting nothing from that :/ How can I get them? Thanks!
tagged with: href

http://stackoverflow.com/comment/82837721
comment on: http://stackoverflow.com/q/47933169
score: 0
type: QuestionComment
type: Comment
has text: Since 72 does not evenly divide 684-32 = 652, it is guaranteed that the marker can go pass the boundary. Hence the suggestion by @furas. You could avoid pixel issues by using gridded labels with images.

http://stackoverflow.com/a/47966997
has comment: http://stackoverflow.com/comment/82903572
has comment: http://stackoverflow.com/comment/82903574
downvote count: 0
score: 9
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82903532
has comment: http://stackoverflow.com/comment/82903562
has comment: http://stackoverflow.com/comment/82903553
type: Answer
upvote count: 9
accepted answer of: http://stackoverflow.com/q/47966728
answers question: http://stackoverflow.com/q/47966728
has body: It maybe because you have your array's dtype as object so convert it to float i.e x = np.array([[-0.20646505, 0.07763347, -0.16161097, 0.370439 ], [-0.91295327,-0.73768934, -0.78909055, 0.06156045], [-0.37242104, 0.51828245, -1.16138222, -0.02489585], [-1.07890926, -0.29704036, -1.7888618, -0.3337744 ]],dtype=object) m = 5 sigma = 1 np.exp((-(x-m)**2)/(2*sigma)) This will lead to : AttributeError: 'float' object has no attribute 'exp' Convert it to float i.e: np.exp((-(x.astype(float)-m)**2)/(2*sigma)) array([[ 1.29935943e-06, 5.47758566e-06, 1.63950875e-06, 2.21778276e-05], [ 2.55786406e-08, 7.10033001e-08, 5.27984133e-08, 5.06026050e-06], [ 5.40131118e-07, 4.34936286e-05, 5.70846640e-09, 3.28945338e-06], [ 9.45644899e-09, 8.07503629e-07, 9.81698210e-11, 6.64271640e-07]]) This also depends on the numpy version you are using. You should also try updating numpy, so many bugs have been fixed.

http://stackoverflow.com/q/47991138
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: Question
has answer: http://stackoverflow.com/a/47991540
has comment: http://stackoverflow.com/comment/82951141
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/82950652
answer count: 1
has comment: http://stackoverflow.com/comment/82950851
accepted answer: http://stackoverflow.com/a/47991540
has body: I have a bit of code which currently looks like this: if os.path.isfile('D:\\df_1'): df_1 = pd.read_pickle('D:\\df_1') else: df_1 = pd.DataFrame(columns = ['Date', 'Location', 'Product']) if os.path.isfile('D:\\df_2'): df_2 = pd.read_pickle('D:\\df_2') else: df_2 = pd.DataFrame(columns = ['Date', 'Location', 'Product']) [...] if os.path.isfile('D:\\df_20'): df_20 = pd.read_pickle('D:\\df_20') else: df_20 = pd.DataFrame(columns = ['Date', 'Location', 'Product']) Basically what I'm doing is checking if the Dataframe already exists, if it does load it, otherwise create an empty dataframe. I need this because then the code will try to append new data to each of the dataframe. So I will have something like: [retrieve new data and clean it] df_1 = pd.concat([df_1, df_1_new_data]) Do this for all the 20 dataframes I have (they contain different things, so I want to keep them separate), and then save them in order to retrieve them again the day after and add new data to them: df_1.to_pickle('D:\\df_1') df_2.to_pickle('D:\\df_2') [...] df_20.to_pickle('D:\\df_20') Now, it's already quite heavy to do it with 20 dataframes, but I will probably need to add some more! Is there a way to read the different dataframes, and then write them to pickle in a for loop or something like this? So to reduce the lines of code for the many I have now to a simple 2 lines for loop? Thank you!
upvote count: 4
has title: Elegant way to work with multiple dataframes in Pandas

http://stackoverflow.com/comment/82685490
comment on: http://stackoverflow.com/a/47860321
type: Comment
has text: Thanks for the answer, but the results are not the same as the desired ones.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82741723
comment on: http://stackoverflow.com/q/47887942
score: 0
type: Comment
has text: You mean city by city?
type: QuestionComment

http://stackoverflow.com/comment/82933405
type: Comment
score: 0
has text: Thank you. So is this what the above function is doing? -> https://wikimedia.org/api/rest_v1/media/math/render/svg/c92d581fd7b8a66308bde64d64dcd8d71cc66ce0
type: AnswerComment
comment on: http://stackoverflow.com/a/47973199

http://stackoverflow.com/q/47891051
has title: Python sum elements in 2d list with the same first value
has comment: http://stackoverflow.com/comment/82748575
has body: I'm trying to find an efficient way to do the following: I have this sample: sample = [['no',2, 6], ['ja',5,7], ['no',4,9], ['ja',10,11], ['ap',7,12]] and would need res = [['no', 6, 15], ['ja', 15, 18], ['ap',7,12]] i.e. sum the corresponding values of the sublists where the first element is the same. Thanks a lot My code is: codes = list(set([element[0] for element in sample])) res=[] for code in codes: aux=[code] res01 = 0 res02 = 0 for element in sample: if element[0] == code: res01 += element[1] res02 += element[2] aux += [res01, res02] res.append(aux)
type: Question
answer count: 2
tagged with: sum
has comment: http://stackoverflow.com/comment/82748546
score: -1
possible better answer: http://stackoverflow.com/a/47891543
downvote count: 2
has answer: http://stackoverflow.com/a/47891543
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82748539
tagged with: python
has answer: http://stackoverflow.com/a/47891137
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47891137
has comment: http://stackoverflow.com/comment/82748560

http://stackoverflow.com/comment/82716962
type: Comment
type: QuestionComment
has text: You should probably add a tag for the language you're using.
comment on: http://stackoverflow.com/q/47875765
score: 0

http://stackoverflow.com/q/47873465
has body: I've created complex linestring as follows: from shapely.geometry import LineString complex_line = LineString([(-1, -1), (1, 1), (1, 0), (-1, 0)]) The line is valid but it is not simple. How can I get the crossing point (here [0,0])?
type: UnansweredQuestion
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/47878614
score: 1
has title: Shapely - get coordinates of crossings from complex linestring
downvote count: 0
answer count: 1
favorite count: 0
tagged with: shapely
tagged with: python

http://stackoverflow.com/a/47874374
has body: As recommended in the comments, vstack or concatenate: In [320]: alist Out[320]: [[[1, 2, 3]], [[4, 5, 6], [7, 8, 9]], [[1, 2, 3], [4, 5, 6], [7, 8, 9]]] In [321]: len(alist) Out[321]: 3 Trying to make an array from the list just creates a 1d array of lists. Not much help. reshape won't work. In [322]: np.array(alist) Out[322]: array([list([[1, 2, 3]]), list([[4, 5, 6], [7, 8, 9]]), list([[1, 2, 3], [4, 5, 6], [7, 8, 9]])], dtype=object) But concatenate works with a list of arrays (or array like objects): In [323]: np.concatenate(alist, axis=0) Out[323]: array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 2, 3], [4, 5, 6], [7, 8, 9]]) concatenate will also work with Out[322] because it treats its input as a list even it is an array. vstack is the same thing except it makes sure the subarrays are all 2d, which in this case they already are.
score: 1
accepted answer of: http://stackoverflow.com/q/47874298
has comment: http://stackoverflow.com/comment/82714360
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47874298
type: Answer
has comment: http://stackoverflow.com/comment/82715148
upvote count: 1

http://stackoverflow.com/q/47874287
has title: How to enable python loop in pymol command line?
downvote count: 0
score: 1
favorite count: 0
tagged with: pymol
has answer: http://stackoverflow.com/a/47877050
has body: Here said the script should be used within the pymol commandline. I would like to output many distances using a loop after reading this. But I got error message: File "&lt;string&gt;", line 1 for i in range(resi_total_n): ^ SyntaxError: unexpected EOF while parsing My code is: from pymol import cmd mol_name='name' resi=10 # the target residue number resi_total_n=500 # the total residue number f=open('dist.txt','w') resi_n=0 for i in range(resi_total_n): resi_n += 1 dst=cmd.distance('tmp',mol_name+'///'+str(resi)+'/ca',mol_name+'///'+str(resi_n)+'/ca') #the alpha carbon f.write("%8.3f\n"%dst) f.close()
tagged with: python
possible better answer: http://stackoverflow.com/a/57238146
has answer: http://stackoverflow.com/a/57238146
upvote count: 1
accepted answer: http://stackoverflow.com/a/47877050
type: AnsweredQuestion
type: Question
answer count: 2

http://stackoverflow.com/q/48002748
answer count: 1
has answer: http://stackoverflow.com/a/48002980
has body: In the following code, one rectangle is made when the "Paint" button is clicked. It contains also a "Move" button. By clicking the "Move" button I want to move the rectangle 1px in both x and y directions. But I failed here. I can understand the question is about how to transfer variable values wenn a button is clicked. To a beginner it is very difficult for me. Any help will be highly appreciated! # -*- coding: utf-8 -*- from PyQt5.QtWidgets import QWidget, QApplication, QPushButton, QHBoxLayout, QDoubleSpinBox from PyQt5.QtGui import QPainter, QColor, QBrush import sys class Example(QWidget): def __init__(self): super(Example, self).__init__() self.initUI() self.flag = False def initUI(self): self.setFixedSize(400, 400) self.setWindowTitle('Colours') self.btnPaint = QPushButton("Paint", self) self.btnMove = QPushButton("Move x+1 y+1", self) self.deltax = 0 # original value self.deltay = 0 # original value self.btnPaint.clicked.connect(self.onPaint) self.btnMove.clicked.connect(self.onMove) self.hlayout = QHBoxLayout() self.hlayout.addWidget(self.btnPaint) self.hlayout.addWidget(self.btnMove) self.hlayout.addStretch(1) self.setLayout(self.hlayout) self.show() def onPaint(self): self.flag = True self.update() def onMove(self): self.deltax = self.deltax + 1 # button clicked, value +1 self.deltay = self.deltay + 1 # button clicked, value +1 self.flag_move = True self.update() def paintEvent(self, e): if self.flag: qp = QPainter() qp.begin(self) self.drawRectangles(qp) qp.end() if self.flag_move: qp = QPainter() qp.begin(self) self.drawRectangles(qp) qp.end() def drawRectangles(self, qp): x1 = 10 y1 = 15 x2 = 90 y2 = 60 col = QColor(0, 0, 0) col.setNamedColor('#d4d4d4') qp.setPen(col) qp.setBrush(QColor(200, 0, 0)) qp.drawRect(x1+self.deltax, y1+self.deltay, x2+self.deltax, y2+self.deltay) if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())
tagged with: qt5
score: 0
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48002980
tagged with: pyqt5
type: Question
tagged with: pyqt
has title: PyQt5: How to click a button to move the paint?

http://stackoverflow.com/comment/82758428
comment on: http://stackoverflow.com/q/47895699
type: Comment
type: QuestionComment
score: 3
has text: You must decide whether you want Property to be a list subclass or have a list as an attribute. Don't make it both. If instances are a list, initialize self, not self.data. If instances have a list as 'data', you must write the Property methods that call data methods yourself.

http://stackoverflow.com/comment/82862067
has text: Chek this answer, it may be what you need https://stackoverflow.com/a/47945317/6005145
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47942623

http://stackoverflow.com/comment/82923824
type: QuestionComment
has text: @v Thx 4 heads up! I am following Badder on twitter . Here is my program now: https://math.stackexchange.com/a/2574424/432081
type: Comment
comment on: http://stackoverflow.com/q/47909793
score: 0

http://stackoverflow.com/comment/83001424
comment on: http://stackoverflow.com/q/48014298
type: QuestionComment
type: Comment
has text: I do believe that it's possible to wrap SpaCy into some sort of API request that it's curl-able but that'll take a significant work to make sure that all functionalities are API accessible.
score: 0

http://stackoverflow.com/comment/82875749
type: Comment
comment on: http://stackoverflow.com/q/47952609
score: 1
type: QuestionComment
has text: I managed to solve it. There is option replace_existing=True. That will modify defined job. @register_job(scheduler, "interval", seconds=300, id="test_job", replace_existing=True)

tcp
type: Tag
tags question: http://stackoverflow.com/q/47971907
tags question: http://stackoverflow.com/q/47858503
tags question: http://stackoverflow.com/q/47966461
tags question: http://stackoverflow.com/q/48005482
tags question: http://stackoverflow.com/q/47860238
tags question: http://stackoverflow.com/q/47876945
tags question: http://stackoverflow.com/q/47979490
tags question: http://stackoverflow.com/q/47903031
tags question: http://stackoverflow.com/q/47976084
tag name: tcp

http://stackoverflow.com/a/47990433
upvote count: 1
has comment: http://stackoverflow.com/comment/82971182
has comment: http://stackoverflow.com/comment/82961067
has body: There seems to already be both server/client for Excel 2002. pyrtd Looking at that source, once you create a dispatch object, then it seems to be cast to IRtdServer. Extract related parts, it becomes below. from win32com import client, universal from win32com.server.util import wrap def __init__(self, classid): self._classid = classid self._rtd = None def connect(self, event_driven=True): dispatch = client.Dispatch(self._classid) self._rtd = client.CastTo(dispatch, 'IRtdServer') if event_driven: self._rtd.ServerStart(wrap(self)) else: self._rtd.ServerStart(None) Please refer to client.py and examples/rtdtime.py of the following sources. pyrtd - default pyrtd/rtd/client.py pyrtd/examples/rtdtime.py
has comment: http://stackoverflow.com/comment/82970187
type: Answer
has comment: http://stackoverflow.com/comment/82964063
downvote count: 0
has comment: http://stackoverflow.com/comment/82971325
has comment: http://stackoverflow.com/comment/82968220
score: 1
answers question: http://stackoverflow.com/q/47985956

http://stackoverflow.com/q/48002016
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82973380
tagged with: python
tagged with: regex
has title: How to get the whole line in which a regex is matched?
has answer: http://stackoverflow.com/a/48002523
score: 1
has comment: http://stackoverflow.com/comment/82974594
has body: So in the book Automate the Boring Stuff with Python, there is this homework project: Write a program that opens all .txt files in a folder and searches for any line that matches a user-supplied regular expression. The results should be printed to the screen. Below is my code. I have two questions: Is there a shorter version for the program? It seems that there is something wrong with the line regex (I want a regex to match the whole line in which the user-specified regex appeared) because it's not showing any results under lineReg. I tried removing the parentheses around the leading and trailing part of the regex. import os, re # Dir Location print('Enter a directory location: (in which txt files are located)') direct= input() os.chdir(direct) # Regexes print("Enter the text you'd like to search for: (or a regex)") givenReg= input() soloReg= re.compile(givenReg) lineReg= re.compile((r'^\n.*')+givenReg+(r'.*\n$')) txtFileReg= re.compile(r'.*\.txt') # Texts in Dir txtFiles= os.listdir(direct) # Finding line through Regex for i in range(len(txtFiles)): if txtFileReg.search(txtFiles[i]) != None: file= open(txtFiles[i]) read= file.read() outcomeSolo= soloReg.findall(read) outcomeLine= lineReg.findall(read) print('In ' + txtFiles[i] + ', found these matches:') print(outcomeLine) print('In ' + txtFiles[i] + ', the lines for these matches were:') print(outcomeSolo) print('\n') file.close()
type: Question
upvote count: 1
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82974588
favorite count: 0
has comment: http://stackoverflow.com/comment/82974437
has comment: http://stackoverflow.com/comment/82972509

http://stackoverflow.com/comment/82819768
type: Comment
comment on: http://stackoverflow.com/a/47925802
type: AnswerComment
has text: I just want it to automatically make a new copy when object is referenced, I dont want to block changes to attributes
score: 0

http://stackoverflow.com/a/48075686
score: 7
upvote count: 7
answers question: http://stackoverflow.com/q/47954063
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: I got no answer for some time, so i did not find any better solution than below. Maybe someome will find it useful. Ok, the trick is - to have {{form.DELETE}} for any form in your formset in template. It renders as a checkbox (i made it invisible) and i made JS to make it "checked" whenever user press "delete" button. After user press "submit" button, every form, marked for deletion, will NOT be validated by the view during filled_formset.is_valid(). This lets you delete object from database with ajax behind the scene. The problem was that an ERROR was raised during formset validation. Caused by the form of an object, which was already deleted from database with ajax. So there are all components: views.py def show_cart(request): OrderItemFormSet = inlineformset_factory(Order, OrderItem, form=OrderItemForm, extra=0, can_delete=True) order = Order.objects.get(pk=request.session['order']) if request.method == 'GET': formset = OrderItemFormSet(instance=order) return render(request, 'ordersys/cart.html', {'formset': formset}) elif request.method == 'POST': filled_formset = OrderItemFormSet(request.POST, instance=order) if filled_formset.is_valid(): filled_formset.save() return redirect('catalog:index') else: return render(request, 'ordersys/cart.html', {'formset': filled_formset}) cart.html {{ formset.management_form }} {% for form in formset %} {{ form.id }} # custom filter {{ form.quantity.label_tag }} {{ form.quantity }} {{ form.errors }} Delete {% endfor %} Submit Next, if user press 'DELETE' button, my JavaScript 1. hides form with $(item).css('display', 'none'); 2. makes checked form.DELETE checkbox with ItemDelCheckbox.prop('checked', true); 3. sends ajax request to delete item from database (otherwise if user refreshes the page, the item still in the cart) views.py def delete_order_item(request): # meets the ajax request item_id = int(request.POST['item_id']) order = get_object_or_404(Order, pk=int(request.POST['order_i…
accepted answer of: http://stackoverflow.com/q/47954063

http://stackoverflow.com/q/47951097
answer count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 1
score: 2
tagged with: odoo
upvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/82871729
has title: Virtual Keyboard in Odoo
tagged with: javascript
tagged with: python-2.7
tagged with: odoo-10
has body: I need to enable Virtual keyboard in Odoo and I made it almost. But the thing is when I click to a particular letter it comes on all the fields like below. I have to resolve this.The entire code is just below including xml,javascript. hotel.xml <?xml version="1.0" encoding="utf-8"?> <t t-name="HotelRegistrationMenu"> Welcome to Hotel California We serve for your happiness Book Now </t> <t t-name="HotelRegistrationKeys"> Customer Name Phone Number Number Of Persons Required Date Required Time <t t-foreach="['A','B','C','D','E','F','G','H','I','J','K','L','M', 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z','1','2', '3','4','5','6','7','8','9','0','-','OK','Del']" t-as="btn_name"> <t t-esc="btn_name"/> </t> </t> Javascript file registration.js odoo.define('bi_hotel.registration', function (require) { "use strict"; // var BarcodeHandlerMixin = require('barcodes.BarcodeHandlerMixin'); var core = require('web.core'); var Widget = require('web.Widget'); var QWeb = core.qweb; var _t = core._t; var registration = Widget.extend({ template:'HotelRegistrationKeys', events: { "click .o_bi_hotel_button_registration": function(){ var self = this; self.$el.html(QWeb.render('HotelRegistrationKeys', {widget: self}));}, 'click .o_hr_attendance_pin_pad_button_A': function() { this.$('.o_hr_attendance_PINbox').val(this.$('.o_hr_attendance_PINbox').val() + 'A'); }, 'click .o_hr_attendance_pin_pad_button_B': function() { this.$('.o_hr_attendance_PINbox').val(this.$('.o_hr_attendance_PINbox').val() + 'B'); }, 'click .o_hr_attendance_pin_pad_button_C': function() { this.$('.o_hr_attendance_PINbox').val(this.$('.o_hr_attendance_PINbox').val() + 'C'); }, 'click .o_hr_attendance_pin_pad_button_D': function() { this.$('.o_hr_attendance_PINbox').val(this.$('.o_hr_attendance_PINbox').val() + 'D'); }, 'click .o_hr_attendance_pin_pad_button_E': function() { this.$('.o_hr_attendance_PINbox').val(this.$('.o_hr_attendance_PINbox').val() + 'E'); }, 'click .o_hr_attendance_pin_pad_button_F': functi…
favorite count: 0

http://stackoverflow.com/comment/82825636
has text: Unable to access `https://www.willhaben.at/iad/myprofile/adadministration/showlist?page=6` without logging in through credentials :)
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47925805

http://stackoverflow.com/comment/82875675
type: Comment
comment on: http://stackoverflow.com/a/47953130
has text: That code sample can only produce `TypeError: list indices`. May be wrongly pasted the sample. It's might a tuple like `dict = ({...},{...},)`.
score: 0
type: AnswerComment

mininet
tag name: mininet
tags question: http://stackoverflow.com/q/47944124
tags question: http://stackoverflow.com/q/47981720
type: Tag

http://stackoverflow.com/q/47984835
tagged with: gradient-descent
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82958024
answer count: 0
tagged with: backpropagation
score: 1
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/82980445
type: Question
has comment: http://stackoverflow.com/comment/82956106
has comment: http://stackoverflow.com/comment/82990312
has title: I am having trouble training a simple neural network
upvote count: 3
downvote count: 2
has body: I am learning to make neural network and I have derived the following equations for backpropagation. Is something wrong with this because I can't seem to get the neural network training. I am coding in python and the accuracy I get is around 10 (I get this even when I don't train my network). However, the error is decreasing for each iteration. Also, I'm currently identifying matrix by size to perform dot product, Hadamard product and transposition, kind of like hit and trial. Is there a better way to do this? According to my understanding, we try to find the right weights such that the cost is minimized. So, to do that we take partial derivative which gives us a measure of how much a small change in a component will affect the overall cost of the system. So following that I derived this but I don't get why the network is not training. Please help... Its a 3 layer neural network (input layer, 1 hidden layer, output layer). First I feed the input forward through the neural network, then calculate cost and finally use back-propagation to update the weights. Here, x is the input data, w is the weight (w1 for layer 1 and w2 for layer 2), z(a,w) is the transfer of data from left layer to right layer, g(z) is the activation function (Sigmoid function used), a(z) is the output of the layer, and E(a,y) is the cost function (squared mean error used). This is my feed forward equation of the neural network: This is the derivation of back-propagation gradients for weights w1, w1b(bias for layer 1), w2 and w2b(bias for layer 2). My python code: (I have used p as a list to transfer weights between functions in sequence w1,w1b,w2,w2b. Also, I added the regularization terms later on so is not included in the derivation. But it follows the same principle of partial derivative. The code was written in Jupyter Notebook and every function has its own block.) alpha=0.12 lmda=1 def feedForward(p,x): a1=x z2=np.dot(a1,p[0])+p[1] a2=g(z2) z3=np.dot(a2,p[2])+p[3] a3=g(z3) return [a1,a2,a3],…
tagged with: neural-network
favorite count: 0
has comment: http://stackoverflow.com/comment/82980421

http://stackoverflow.com/comment/82867012
has text: Is the following statement correct? You want to make all the series in dataset have exactly the same timestamps by adding them if necessary to each one (with y values of 0).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47944250
score: 0

http://stackoverflow.com/comment/82743851
type: QuestionComment
has text: I will check it out! I am very new to working with shapefiles and python. Thank you
score: 0
comment on: http://stackoverflow.com/q/47888887
type: Comment

http://stackoverflow.com/comment/82770301
has text: @mohyaboulaydegaga Yes, you have to `import difflib`, or if that's not possible, install it, e.g. using `pip` or `pip3`, or implement your own edit distance algorithm, which is a good exercise on its own.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47896447

qgis
tags question: http://stackoverflow.com/q/47888887
type: Tag
tag name: qgis

http://stackoverflow.com/q/47875878
has title: pygame moving square goes out of bounderies
upvote count: 1
answer count: 1
tagged with: pygame
favorite count: 0
tagged with: python-3.x
tagged with: python
has body: I am currently programming a moving square. I want to control it with my keys, and for it to not move out of bounds. However, I cannot get it to not move out of the boundaries ( the side of the window ). Here is my code: import sys, pygame pygame.init() width, height = 700, 700 screen = pygame.display.set_mode((width, height), pygame.RESIZABLE) clock = pygame.time.Clock() FPS = 120 x1 = 0 y1 = 0 xmb1 = False xmf1 = False ymb1 = False ymf1 = False squareh = 50 squarew = 50 squares = 3 BLACK = (0,0,0) WHITE = (255,255,255) while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.display.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: xmb1 = True if event.key == pygame.K_RIGHT: xmf1 = True if event.key == pygame.K_UP: ymb1 = True if event.key == pygame.K_DOWN: ymf1 = True elif event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: xmb1 = False if event.key == pygame.K_RIGHT: xmf1 = False if event.key == pygame.K_UP: ymb1 = False if event.key == pygame.K_DOWN: ymf1 = False if x1 == 0: xmb1 = False if y1 == 0: ymb1 = False if x1 == width - squarew: xmfl = False if y1 == height - squareh: ymf1 == False if xmb1: x1 -= squares if xmf1: x1 += squares if ymb1: y1 -= squares if ymf1: y1 += squares screen.fill(BLACK) pygame.draw.rect(screen, WHITE, (x1, y1, squareh, squarew), 0) pygame.display.flip() clock.tick(FPS) Does anybody know how to fix this? I have just recently learnt pygame(last night!)
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
has answer: http://stackoverflow.com/a/47876063
accepted answer: http://stackoverflow.com/a/47876063

http://stackoverflow.com/q/47974841
linked to: http://stackoverflow.com/q/423379
answer count: 1
has body: I am using windows10 and python 2.7.14. Running the python scripts in command prompt. I want to read some lines in text file and compare with some text, if it matches it should be stored in array. And also I want the array should be global. But In my script the I am not able to store the contents in array. How do I achieve this. #This method is to reading logfile and saving the different datas in different lists def Readlogs(Filename): datafile = file(Filename) for line in datafile: if "login = " in line: print(line) trial=line s2 = "= " ArrayLogin = trial[trial.index(s2) + len(s2):] print(ArrayLogin) print(ArrayLogin) if "Overlay = " in line: print(line) trial2=line s2 = "= " arrayOverlay = trial2[trial2.index(s2) + len(s2):] print(arrayOverlay) Readlogs(WriteFileName)
has comment: http://stackoverflow.com/comment/82919019
score: 0
tagged with: global-variables
tagged with: arrays
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47974885
tagged with: scope
has title: How do I assign values in text file to an array inside python function and use it as global?
type: Question
tagged with: python

http://stackoverflow.com/comment/82957392
has text: Since different *Python* versions come with different compilers, pick one. Since *bjoem* is for *Py3*, the *Py27* attempt makes no sense. Second, *Py34* is compiled using *VStudio10*.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47994082

http://stackoverflow.com/comment/82704865
comment on: http://stackoverflow.com/a/47869578
score: 0
type: AnswerComment
has text: Ok, I agree. And I am pretty sure that if I had in my question two lines of code then possibly I would have not any downvotes. The whole phylosophy tend to be wrong and especially from certain users. Anyway, thank you for your answer and for your time.
type: Comment

http://stackoverflow.com/a/47902214
answers question: http://stackoverflow.com/q/47900084
type: Answer
upvote count: 1
score: 1
has body: from pyspark.sql.functions import col,split import re #r = re.compile(r"(?=\s\w+=)") adsample = sc.textFile("hdfs://hostname/user/hdfs/sample/Log18Dec.txt") splitted_sample = adsample.flatMap(lambda (x): ((v) for v in re.split('\s+(?=\w+=)',x))) for m in splitted_sample.collect(): print(m)
downvote count: 0

http://stackoverflow.com/comment/82970588
has text: @Zenvega this is what I get base on your gdp dataset
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48000949

http://stackoverflow.com/q/47982785
has comment: http://stackoverflow.com/comment/82936281
has comment: http://stackoverflow.com/comment/82936428
has title: Python: performing FFT on music file
has comment: http://stackoverflow.com/comment/82934254
downvote count: 0
possible better answer: http://stackoverflow.com/a/76723099
has answer: http://stackoverflow.com/a/48015264
accepted answer: http://stackoverflow.com/a/48015264
score: 8
favorite count: 0
tagged with: fft
linked to: http://stackoverflow.com/q/35701407
upvote count: 8
has comment: http://stackoverflow.com/comment/82935631
has comment: http://stackoverflow.com/comment/82934217
tagged with: python
has comment: http://stackoverflow.com/comment/82934357
linked to: http://stackoverflow.com/q/19276295
has comment: http://stackoverflow.com/comment/82999372
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82934224
has comment: http://stackoverflow.com/comment/82936533
has answer: http://stackoverflow.com/a/76723099
has body: I am trying to perform a FFT on a song (audio file in wav format, about 3 minutes long) which I created as follows, just in case it is relevant. ffmpeg -i "$1" -vn -ab 128k -ar 44100 -y -ac 1 "${1%.webm}.wav" Where $1 is the name of a webm file. This is the code which is supposed to display a FFT of the given file: import numpy as np import matplotlib.pyplot as plt # presume file already converted to wav. file = os.path.join(temp_folder, file_name) rate, aud_data = scipy.io.wavfile.read(file) # wav file is mono. channel_1 = aud_data[:] fourier = np.fft.fft(channel_1) plt.figure(1) plt.plot(fourier) plt.xlabel('n') plt.ylabel('amplitude') plt.show() The problem is, it takes for ever. It takes so long that I cannot even show the output, since I've had plenty of time to research and write this post and it still has not finished. I presume that the file is too long, since print (aud_data.shape) outputs (9218368,), but this looks like a real world problem, so I hope there is a way to obtain an FFT of an audio file somehow. What am I doing wrong? Thank you. edit A better formulation of the question would be: is the FFT of any good in music processing? For example similarity of 2 pieces. As pointed out in the comments, my plain approach is way too slow. Thank you.
tagged with: scipy
linked to: http://stackoverflow.com/q/47954034
tagged with: signal-processing
type: Question
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/82934915

http://stackoverflow.com/comment/82858747
comment on: http://stackoverflow.com/q/47944526
type: Comment
has text: You want to write into a new file the content you wish ?
score: 0
type: QuestionComment

http://stackoverflow.com/a/47956434
has comment: http://stackoverflow.com/comment/82938429
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47956236
upvote count: 2
has body: You could patch the decorator with a new decorator which you could control: import functools def patch(parent, obj_name, switch_reg, switch_name): def gen_switcher(): def wrapper(func): ori_wrapped = ori_decorator(func) @functools.wraps(func) def _(*args, **kwargs): if switch_reg.get(switch_name, False): func_to_call = func else: func_to_call = ori_wrapped print(func_to_call) return func_to_call(*args, **kwargs) return _ return wrapper ori_decorator = getattr(parent, obj_name) setattr(parent, obj_name, gen_switcher()) with: # have to patch the decorator before applying it import numba switchs = {} patch(numba, 'jit', switchs, 'DISABLE_NUMBA_JIT') @numba.jit def f(a, b): return a + b f(1, 2) yields: CPUDispatcher(&lt;function f at 0x10a5f90d0&gt;) then with: # this part could be rewrited as a context manager switchs['DISABLE_NUMBA_JIT'] = True f(1, 2) get: &lt;function f at 0x10a5f90d0&gt;
has comment: http://stackoverflow.com/comment/82943363
type: Answer

flask-restplus
tag name: flask-restplus
type: Tag
tags question: http://stackoverflow.com/q/47917385

http://stackoverflow.com/comment/82820590
has text: `t` has length `j`, while `te[i]` is a single number. For `j != 1` (which is mostly the case), it does not make sense to plot a list of `j` values versus a single number. This is what the error tells you.
type: QuestionComment
comment on: http://stackoverflow.com/q/47926317
score: 1
type: Comment

http://stackoverflow.com/comment/82743355
comment on: http://stackoverflow.com/q/47884976
score: 0
type: Comment
has text: being the storage choice of professional photographers next to .RAW files for example
type: QuestionComment

http://stackoverflow.com/q/47986344
score: 1
tagged with: data-structures
has comment: http://stackoverflow.com/comment/82946587
accepted answer: http://stackoverflow.com/a/47986375
favorite count: 0
has comment: http://stackoverflow.com/comment/82941609
type: Question
has comment: http://stackoverflow.com/comment/82941567
has body: for example, I have this Set object: a = {0,1,2,3,4,5} how to randomly remove fixed number of elements from this set?
tagged with: python
has comment: http://stackoverflow.com/comment/82941599
has comment: http://stackoverflow.com/comment/82942842
answer count: 2
tagged with: set
upvote count: 1
has answer: http://stackoverflow.com/a/47986375
has comment: http://stackoverflow.com/comment/82942762
linked to: http://stackoverflow.com/q/10048069
has answer: http://stackoverflow.com/a/47986376
has title: How to randomly discard a number of elements in a set using Python?
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47986376
downvote count: 0

output
tags question: http://stackoverflow.com/q/47998156
tags question: http://stackoverflow.com/q/47858869
tag name: output
tags question: http://stackoverflow.com/q/47930144
type: Tag
tags question: http://stackoverflow.com/q/47985695
tags question: http://stackoverflow.com/q/47883265
tags question: http://stackoverflow.com/q/47878710
tags question: http://stackoverflow.com/q/47972171

http://stackoverflow.com/q/47872609
upvote count: 2
has comment: http://stackoverflow.com/comment/82710735
has comment: http://stackoverflow.com/comment/82710650
has title: Scrapy error: 'Pipeline' object has no attribute 'exporter'
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82713782
tagged with: python
tagged with: scrapy
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/72123287
type: Question
has body: I made a scraper and am using this tutorial to export using a pipeline. When I run scrapy crawl [myspider] I see the objects flashing by in my terminal, but after each it gives the error 'PostPipeline' object has no attribute 'exporter'. My Spider class FokSpider1(CrawlSpider): name = 'fok' allowed_domains = ['fok.nl'] start_urls = ['http://forum.fok.nl/?token=77c1f767bc31859fee1ffe041343fa48&amp;allowcookies=ACCEPTEER+ALLE+COOKIES'] rules = ( # My rules, leave out to save space ) def __init__(self, *args, **kwargs): self.driver = webdriver.Chrome() super(FokSpider1, self).__init__(*args, **kwargs) def parse_topic(self, response): posts = response.xpath("//div[contains(@class, 'post userid')]") for i, post in enumerate(posts): l = ItemLoader(selector=post, item=ForumTopic(), response=response) l.add_xpath('subforum_title',"//*[@id='pageWrapper']/div[4]/div/h2/a/text()") l.add_xpath('topic_title',"//*[@id='pageWrapper']/div[4]/h1/span/text()") l.add_xpath('unique_post_id', ".//@data-postid") l.add_xpath('post_rank', ".//@data-teller") l.add_xpath('author', ".//@data-member") l.add_xpath('timestamp', ".//span[contains(@class, 'post_time')]/a[1]/text()") l.add_xpath('content', ".//div[contains(@id, '_bot')]/div[contains(@class, 'postmain_right')]/text()") yield l.load_item() settings.py ITEM_PIPELINES = { 'scrapy_spider.pipelines.PostPipeline': 300, } I don't think the rest of settings.py is relevant? pipelines.py from scrapy.exceptions import DropItem from scrapy import signals from scrapy.exporters import XmlItemExporter class PostPipeline(object): def __init__(self): self.ids_seen = set() self.files = {} @classmethod def from_crawler(cls, crawler): pipeline = cls() crawler.signals.connect(pipeline.spider_opened, signals.spider_opened) crawler.signals.connect(pipeline.spider_closed, signals.spider_closed) return pipeline def spider_opened(self, spider): file = open('fokSpider1.xml' % spider.name, 'w+b') self.files[spider] = file self.exporter = XmlItemExporter(file) …
answer count: 2
has answer: http://stackoverflow.com/a/47937006
tagged with: scrapy-pipeline

http://stackoverflow.com/q/47863300
favorite count: 0
has answer: http://stackoverflow.com/a/47863460
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
has comment: http://stackoverflow.com/comment/82703647
type: Question
has title: Getting status code 102 from coinnest.co.kr
tagged with: api
has comment: http://stackoverflow.com/comment/82691522
has comment: http://stackoverflow.com/comment/82693055
tagged with: rest
has body: I'm trying to write a Python wrapper for a cryptocurrency exchange. #!/usr/bin/python2.7 import hashlib import hmac import time base_url = 'https://api.coinnest.co.kr' class Coinnest(): def __init__(self, key, secret): self.key = key self.secret = secret def get_balance(self): url = base_url + '/api/account/balance' nonce = str(int(time.time())*1000) key = hashlib.md5(self.secret).hexdigest() message = 'key={}&amp;nonce={}'.format(self.key, nonce) signature = hmac.new(key, message, hashlib.sha256).hexdigest() payload = {'key': key, 'nonce': nonce, 'signature': signature} r = requests.post(url, data=payload) return r.json() coinnest = Coinnest('','') print coinnest.get_order_history() Response: u'status': 102, u'msg': u'', u'data': u'' According to the API response description: Code 102 means Parameter error. Required parameters are missing or in wrong format. I believe I have all the required parameters of key nonce signature. Am I delivering the payload in the wrong location or in the wrong format? Unfortunately, their documentation is not very clear and I am a beginner. Thank you.
downvote count: 0
answer count: 1

http://stackoverflow.com/a/47867499
has comment: http://stackoverflow.com/comment/82703922
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47866783
downvote count: 0
has comment: http://stackoverflow.com/comment/82699969
answers question: http://stackoverflow.com/q/47866783
type: Answer
score: 2
upvote count: 2
has body: I just tried overwriting sys.stdout.write and it worked (with a few quirks). Someone will correct me if I'm wrong, but I think it's not gonna get much better than this. In [1]: import sys In [2]: tmp = sys.stdout.write In [3]: sys.stdout.write = lambda text: tmp(text + '!') In [4]: 5 + 5 !Out[4]: 10! !! !!In [5]: EDIT: I've gotten this far. Haven't figured out where that 1 extra ! comes from. In [5]: sys.stdout.write = lambda text: tmp(text if text.endswith('\n') else text + '!\r') In [6]: 5+5 Out[6]: 10! ! In [7]:
has comment: http://stackoverflow.com/comment/82705872

http://stackoverflow.com/comment/82997156
type: AnswerComment
has text: I thought I understand simple logic such as this but apparently I need review it. Embarrassing, really.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48014074

http://stackoverflow.com/comment/82901559
has text: right good move
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47962043
type: QuestionComment

http://stackoverflow.com/q/47912045
tagged with: python
has title: Word2Vector ValueError: scatter requires x column to be numeric
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48039103
score: 1
has body: I am a beginner in machine learning, there might be silly mistake, any help would be appreciated. I am getting error while execution of below code snippet: def plot_region(x_bounds, y_bounds): slice = points[ (x_bounds[0] &lt;= points.x) &amp; (points.x &lt;= x_bounds[1]) &amp; (y_bounds[0] &lt;= points.y) &amp; (points.y &lt;= y_bounds[1]) ] ax = slice.plot.scatter("x", "y", s=35, figsize=(10, 8)) for i, point in slice.iterrows(): ax.text(point.x + 0.005, point.y + 0.005, point.word, fontsize=11) plot_region(x_bounds=(4.0,4.2),y_bounds=(-0.5,-0.1)) plot_region(x_bounds=(0, 1), y_bounds=(4, 4.5)) ValueError: scatter requires x column to be numeric
upvote count: 1
tagged with: machine-learning
type: Question
possible better answer: http://stackoverflow.com/a/51572687
has answer: http://stackoverflow.com/a/51572687
has comment: http://stackoverflow.com/comment/82805952
answer count: 2
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/48039103
favorite count: 0
has comment: http://stackoverflow.com/comment/82902275

http://stackoverflow.com/comment/82732438
score: 0
type: AnswerComment
has text: OK. Thanks for your carefully comments.
type: Comment
comment on: http://stackoverflow.com/a/47883292

http://stackoverflow.com/comment/82825884
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47925805
type: Comment
has text: Without credentials we can't access `https://www.willhaben.at/iad/myprofile/adadministration/show‌​list?page=6` to get the `WebElement` **"xpath","selector":"//input[@class='btn icon-icon_bearbeiten status-expired'][@type='button']"**

http://stackoverflow.com/comment/82863027
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47946297
has text: thats the data i get from the api its not something in my control (unless I didnt understand you)

http://stackoverflow.com/q/47878587
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47878620
type: Question
has title: Python, accessing widget items from outside of a class
tagged with: listbox
score: 0
has body: I have an auto generated code which generates a GUI that has various widgets in it. One of the widget is a ScrolledListBox. A part of the code is shown below: class New_Toplevel_1: def __init__(self, top=None): self.Scrolledlistbox4.configure(background="white") self.Scrolledlistbox4.configure(font="TkFixedFont") self.Scrolledlistbox4.configure(highlightcolor="#d9d9d9") self.Scrolledlistbox4.configure(selectbackground="#c4c4c4") self.Scrolledlistbox4.configure(width=10) I want to access the Scrolledlistbox4 from outside this class. So for example, I would like to write to write a function that updates the ScrolledListBox whenever I call it. I am relatively new to python and would like to know how can I accomplish this.
answer count: 1
tagged with: python
tagged with: tkinter
has answer: http://stackoverflow.com/a/47878620

http://stackoverflow.com/a/47950797
has comment: http://stackoverflow.com/comment/82871181
type: Answer
has comment: http://stackoverflow.com/comment/82871280
has comment: http://stackoverflow.com/comment/82871366
answers question: http://stackoverflow.com/q/47950467
has comment: http://stackoverflow.com/comment/82871402
has body: You can just save the header as a list and then split it later:- with open(description.txt) as desc_file: Heading1 = "keep reading until you get 2 blank lines in a row" Heading2 = "keep reading until you get 2 blank lines in a row" . . Last_ Heading = ditto Now you can map those headers to your table columns. EDIT:- With open you might want to specify what kind of encoding file has, it defers from system to system.
score: 0
has comment: http://stackoverflow.com/comment/82871087

http://stackoverflow.com/q/47922078
tagged with: selenium
has answer: http://stackoverflow.com/a/47922426
accepted answer: http://stackoverflow.com/a/47922426
tagged with: selenium-webdriver
type: AnsweredQuestion
type: Question
has body: I am trying to run a code and every time, I am getting an error of "StaleElementReferenceException", and it makes my life a living hell. The code is as follow: import time import unittest import DropDownAddresses import re from selenium import webdriver from selenium.common.exceptions import * from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.remote.webelement import WebElement from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.select import Select from selenium.webdriver.support.ui import WebDriverWait from selenium.common.exceptions import * UserEmail = "testinguser90@gmail.com" UserPassword = '12345678' SubcategoryName = input("Enter Name of Sub category: ") def dropDown(self, Category): driver = self.driver actions = ActionChains ( driver ) actions.move_to_element ( Category ).perform ( ) SelectedCategory = driver.find_element_by_partial_link_text ( SubcategoryName ) self.NameofSelectedCategory = print ( SelectedCategory.text ) time.sleep ( 2 ) actions.move_to_element ( SelectedCategory ).click ( ).perform ( ) time.sleep ( 2 ) def headings(self): driver= self.driver Pageheading = driver.find_element_by_tag_name ( "h1" ).text headingName = re.sub ( "[^a-zA-Z]", "", Pageheading ) # Mainheading = int(Pageheading.text[:-4]) offerCount = re.findall ( '\d+', Pageheading ) NumberofOffers = (offerCount[0]) if headingName == self.NameofSelectedCategory: print ( "Heading is correct i.e. " + headingName ) else: print ( "Heading was not correct" ) if NumberofOffers == 1: print ( "Number of Offers in this section is " + str ( NumberofOffers ) ) else: print ( "Number of offers in this section are " + str ( NumberofOffers ) ) class Categories(unittest.TestCase): def setUp(self): DropDownAddresses.browserCalling(self) def test_Test1(self): DropDownAddresses.openBrowser(self) driver = self.driver MoveSliderAhead = driver.find_element_by_xpath("//*[@id=…
has comment: http://stackoverflow.com/comment/82813448
has comment: http://stackoverflow.com/comment/82812377
score: 0
answer count: 1
tagged with: python
has title: StaleElementReferenceException on Selenium + Python

http://stackoverflow.com/q/47890915
tagged with: python
has answer: http://stackoverflow.com/a/47890973
tagged with: lambda
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47891045
accepted answer: http://stackoverflow.com/a/47890973
has answer: http://stackoverflow.com/a/47891045
upvote count: 4
has comment: http://stackoverflow.com/comment/82748594
answer count: 2
downvote count: 0
has title: Conditional statements on Panda Dataframes using Lambdas
score: 4
favorite count: 0
has body: I'm getting stuck on a simple point. I'm trying to establish a column within a Panda dataframe, which only pulls up the age for males (0), but for some reason I cannot iterate over the Dataframe (it only repeats the first result, which is 22). Here is my code: new_tab['menage'] = new_tab.Gender.apply( lambda x: new_tab.iloc[:,1] if x==0 else 0) Original Age Gender menage 0 22.0 0 22.0 1 38.0 1 0.0 2 26.0 1 0.0 3 35.0 1 0.0 4 35.0 0 22.0 I'm specifically trying to do this for lambda, whilst recognising there are other alternatives available. I'm sure it's something really straightforward, but being new to coding, is beyond me at present. Any help would be brilliant. Thanks
tagged with: pandas

http://stackoverflow.com/a/47954497
has comment: http://stackoverflow.com/comment/106291345
has comment: http://stackoverflow.com/comment/82878613
score: 6
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/82880866
has comment: http://stackoverflow.com/comment/82880838
has comment: http://stackoverflow.com/comment/82878336
answers question: http://stackoverflow.com/q/47954401
has comment: http://stackoverflow.com/comment/82878486
accepted answer of: http://stackoverflow.com/q/47954401
type: AcceptedAnswer
downvote count: 0
has body: Approach #1 : With np.einsum - np.einsum('ij,ik,i-&gt;jk',p,p,w) Approach #2 : With broadcasting + np.tensordot - np.tensordot(p[...,None]*p[:,None], w, axes=((0),(0))) Approach #3 : With np.einsum + np.dot - np.einsum('ij,i-&gt;ji',p,w).dot(p) Runtime test Set #1 : In [653]: p = np.random.rand(50,30) In [654]: w = np.random.rand(50) In [655]: %timeit np.einsum('ij,ik,i-&gt;jk',p,p,w) 10000 loops, best of 3: 101 µs per loop In [656]: %timeit np.tensordot(p[...,None]*p[:,None], w, axes=((0),(0))) 10000 loops, best of 3: 124 µs per loop In [657]: %timeit np.einsum('ij,i-&gt;ji',p,w).dot(p) 100000 loops, best of 3: 9.07 µs per loop Set #2 : In [658]: p = np.random.rand(500,300) In [659]: w = np.random.rand(500) In [660]: %timeit np.einsum('ij,ik,i-&gt;jk',p,p,w) 10 loops, best of 3: 139 ms per loop In [661]: %timeit np.einsum('ij,i-&gt;ji',p,w).dot(p) 1000 loops, best of 3: 1.01 ms per loop The third approach just blew everything else! Why Approach #3 is 10x-130x faster than Approach #1? np.einsum is implemented in C. In the first approach, with those three strings there i,j,k in its string-notation, we would have three nested loops (in C of course). That's a lot of memory overhead there. With the third approach, we are only getting into two strings i, j, hence two nested loops (in C again) and also leveraging BLAS based matrix-multiplication with that np.dot. These two factors are responsible for the amazing speedup with this one.

http://stackoverflow.com/a/47959185
has comment: http://stackoverflow.com/comment/82896224
accepted answer of: http://stackoverflow.com/q/47959054
type: Answer
answers question: http://stackoverflow.com/q/47959054
has comment: http://stackoverflow.com/comment/82896014
has body: This is easily do-able with a zero-width negative lookahead to ensure that Item does not appear next: In [19]: s1=' abdjjc eoafl japoge ' In [20]: s2=' abdjjc Item ljapoge ' In [21]: re.sub(r'^ (?!.*Item).* ', 'FOO', s1) Out[21]: 'FOO' In [22]: re.sub(r'^ (?!.*Item).* ', 'FOO', s2) Out[22]: ' abdjjc Item ljapoge ' Here the mentioned negative lookahead pattern is (?!.*Item), coming after to ensure that Item does not occur in the string anytime later.
has comment: http://stackoverflow.com/comment/82896367
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82896091

troposphere
type: Tag
tags question: http://stackoverflow.com/q/47915147
tag name: troposphere

http://stackoverflow.com/comment/82855630
score: 0
type: Comment
type: QuestionComment
has text: Isn't both `enter username` and `insert password` are invalid anyway according to the no space rule? So why bother?
comment on: http://stackoverflow.com/q/47942973

http://stackoverflow.com/q/47858515
tagged with: python
has title: Restricted integer partitions in Python
answer count: 0
upvote count: 2
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/82681841
tagged with: integer-partition
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/82681590
favorite count: 0
has body: I want to find out how many ways there are to make 500 using only 1, 2, 5, 10, 20, 50, 100, and 200. I understand that there exist greedy algorithms etc that can solve this type of question, but I want to be able to do it the following way: The number of integer partitions of a given number, n, using only numbers from some set T, can be obtained from the coefficient of the xn term in the product of all (1-xt)-1, where t is in T. To do this, note that the Taylor expansion of (1-xt)-1 equals (1+xt+x2t+...). Here is the code I've written so far: ################################# # First, define a function that returns the product of two # polynomials. A list here # represents a polynomial with the entry in a list corresponding to # the coefficient of the power of x associated to that position, e.g. # [1,2,3] = 1 + 2x + 3x^2. ################################# def p(a,v): """(list,list) -&gt; list""" prodav = [0]*(len(a)+len(v)-1) for n in range(len(a)): for m in range(len(v)): prodav[n+m] += v[m]*a[n] return prodav ################################# # Now, let a,b,c,...,h represent the first 501 terms in the Taylor # expansion of 1/(1-x^n), where n gives the coin value, i.e # 1,2,5,10,20,50,100,200 in pence. See the generating function # section in https://en.wikipedia.org/wiki/Partition_(number_theory). # Our function, p, multiplies all these polynomials together # (when applied iteratively). As per the Wiki entry, the coefficient # of x^t is equal to the number of possible ways t can be made, # using only the denominations of change available, a so called # 'restricted integer partition'. Note that it isn't necessary to # consider the entire Taylor expansion since we only need the # 500th power. ################################# a = ( [1] ) * 501 # 1 b = ( [1] + [0] ) * 250 + [1] # 2 c = ( [1] + [0]*4 ) * 100 + [1] # 5 d = ( [1] + [0]*9 ) * 50 + [1] # 10 e = ( [1] + [0]*19 ) * 25 + [1] # 20 f = ( [1] + [0]*49 ) * 10 + [1] # 50 g = ( [1] + [0]*99 ) * 5 + [1] # 100 h = (…

http://stackoverflow.com/a/49241786
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/94189957
has comment: http://stackoverflow.com/comment/85519857
downvote count: 0
has body: I would recommend to use tesserocr. It supports Tesseract 4 and is a true wrapper around the C++ API in contrast to pytesseract which just calls tesseract CLI. Training is a whole different story and you should follow the guide provided by the developers.
type: Answer
answers question: http://stackoverflow.com/q/47977703

http://stackoverflow.com/comment/82714685
has text: if you use IPython or Jupyter, use ??add_student
type: Comment
comment on: http://stackoverflow.com/q/47874585
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82947794
comment on: http://stackoverflow.com/q/47988849
has text: dbscan clustering of sklearn over the coordinates is an option here. http://scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.html. Example usage on data: http://scikit-learn.org/stable/auto_examples/cluster/plot_dbscan.html#sphx-glr-auto-examples-cluster-plot-dbscan-py
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47943642
answers question: http://stackoverflow.com/q/47943458
type: Answer
score: 0
has body: Use a negative character set: import re s = "John Smith &lt;jsmith@email.com&gt;" email = re.findall('&lt;([^&gt;])&gt;', s)[0] That matches anything thats not a &gt; character, so everything thats in the angular brackets.

http://stackoverflow.com/a/59365142
answers question: http://stackoverflow.com/q/47877530
score: 0
type: Answer
has body: If you have 2 each 1-dimensional arrays, x and y, you can convert the arrays into matrices with repeating columns, transpose, and apply the distance formula. This assumes that x and y are coordinated pairs. The result is a symmetrical distance matrix. x = [1, 2, 3] y = [4, 5, 6] xx = np.repeat(x,3,axis = 0).reshape(3,3) yy = np.repeat(y,3,axis = 0).reshape(3,3) dist = np.sqrt((xx-xx.T)**2 + (yy-yy.T)**2) dist Out[135]: array([[0. , 1.41421356, 2.82842712], [1.41421356, 0. , 1.41421356], [2.82842712, 1.41421356, 0. ]])

http://stackoverflow.com/comment/83007695
comment on: http://stackoverflow.com/q/48011093
has text: Check this: https://stackoverflow.com/questions/11704221/using-a-rotation-matrix-opencv
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82908808
type: Comment
type: QuestionComment
has text: @Nijan Could you describe why you need this functionality? Checking for types in Python is generally considered an anti-pattern. The IDE is likely doing meta-analysis by reading your source code.
score: 0
comment on: http://stackoverflow.com/q/47968098

http://stackoverflow.com/comment/82745345
type: QuestionComment
score: 1
has text: While we are speaking of style guidelines, it improves readability to add one or two newlines in between functions, like in furas's answer.
comment on: http://stackoverflow.com/q/47889011
type: Comment

http://stackoverflow.com/comment/82892284
comment on: http://stackoverflow.com/q/47961348
type: QuestionComment
type: Comment
has text: You can simplify with `r'[A-Z]{3,5}'`.
score: 1

http://stackoverflow.com/comment/82976903
comment on: http://stackoverflow.com/a/47992680
score: 0
type: AnswerComment
has text: B can be anything ,need not be all ones.Does this work for any B?
type: Comment

http://stackoverflow.com/comment/82841575
comment on: http://stackoverflow.com/q/47936083
has text: Update Issues, @Ykh
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82905372
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47967809
has text: Difficult without an exact error message and I can't reproduce the error - the last `elif` is not connected to any `if`. But many `index out of range` errors arise, because people forget that the index starts at `0`, not at `1`.
score: 0

http://stackoverflow.com/comment/82919333
score: 1
comment on: http://stackoverflow.com/a/47972708
type: AnswerComment
has text: `_is_view` is a really good functionality, i didn't know about this. Thanks
type: Comment

http://stackoverflow.com/comment/82940620
score: 1
type: QuestionComment
has text: Can you post a minimal example of `im`?
type: Comment
comment on: http://stackoverflow.com/q/47985739

http://stackoverflow.com/q/47881124
tagged with: dataframe
tagged with: pandas
has body: i have a dataframe df1 id value 1 100 2 100 3 100 4 100 5 100 i have another dataframe df2 id value 2 50 5 30 i want to replace these values for id's in df2 with the values in df1. final modified df1: id value 1 100 2 50 3 100 4 100 5 30 i will be running this in a loop. i'e df2, will change time to time (df1, outside loop) what would be the best way to change the values?
favorite count: 0
has title: change value of one dataframe by value from other dataframe pandas
has answer: http://stackoverflow.com/a/47881134
has answer: http://stackoverflow.com/a/47881354
upvote count: 2
tagged with: python
possible better answer: http://stackoverflow.com/a/47881354
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47881134
type: Question
answer count: 2
score: 2
downvote count: 0

http://stackoverflow.com/comment/82722246
comment on: http://stackoverflow.com/a/47877774
type: AnswerComment
score: 0
type: Comment
has text: Thanks for the reply. In my data set, there can be multiple products. How can i use above logic in that scenario Thanks again

http://stackoverflow.com/q/47908310
has answer: http://stackoverflow.com/a/47908436
upvote count: 1
has body: For our python project we have to solve multiple questions. We are however stuck at this one: "Write a function that, given a FASTA file name, returns a dictionary with the sequence IDs as keys, and a tuple as value. The value denotes the minimum and maximum molecular weight for the sequence (sequences can be ambiguous)." import collections from Bio import Seq from itertools import product def ListMW(file_name): seq_records = SeqIO.parse(file_name, 'fasta',alphabet=generic_dna) for record in seq_records: dictionary = Seq.IUPAC.IUPACData.ambiguous_dna_values result = [] for i in product(*[dictionary[j] for j in record]): result.append("".join(i)) molw = [] for sequence in result: molw.append(SeqUtils.molecular_weight(sequence)) tuple= (min(molw),max(molw)) if min(molw)==max(molw): dict={record.id:molw} else: dict={record.id:(min(molw), max(molw))} print(dict) Using this code we manage to get this output: {'seq_7009': (6236.9764, 6367.049999999999)} {'seq_418': (3716.3642000000004, 3796.4124000000006)} {'seq_9143_unamb': [4631.958999999999]} {'seq_2888': (5219.3359, 5365.4089)} {'seq_1101': (4287.7417, 4422.8254)} {'seq_107': (5825.695099999999, 5972.8073)} {'seq_6946': (5179.3118, 5364.420900000001)} {'seq_6162': (5531.503199999999, 5645.577399999999)} {'seq_504': (4556.920899999999, 4631.959)} {'seq_3535': (3396.1715999999997, 3446.1969999999997)} {'seq_4077': (4551.9108, 4754.0073)} {'seq_1626_unamb': [3724.3894999999998]} As you can see this is not one dictionary but multiple dictionaries under each other. So is there anyway we can change our code or type an extra command to get it in this format: {'seq_7009': (6236.9764, 6367.049999999999), 'seq_418': (3716.3642000000004, 3796.4124000000006), 'seq_9143_unamb': (4631.958999999999), 'seq_2888': (5219.3359, 5365.4089), 'seq_1101': (4287.7417, 4422.8254), 'seq_107': (5825.695099999999, 5972.8073), 'seq_6946': (5179.3118, 5364.420900000001), 'seq_6162': (5531.503199999999, 5645.577399999999), 'seq_504': (4556.92089999…
has title: How can I combine separate dictionary outputs from a function in one dictionary?
accepted answer: http://stackoverflow.com/a/47908432
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/82783926
tagged with: python
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/47908436
has answer: http://stackoverflow.com/a/47908432

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

http://stackoverflow.com/q/47999477
score: 8
type: AnsweredQuestion
downvote count: 0
tagged with: pip
upvote count: 8
type: Question
accepted answer: http://stackoverflow.com/a/48014252
tagged with: anaconda
has body: When installing a requirements.txt file for a Django app on a linux server I can run: conda install --yes --file requirements.txt This will crash if any of the packages are not available through Conda (PackageNotFoundError). This bash one liner is a cool way to go through the requirements.txt file one line at a time source: while read requirement; do conda install --yes $requirement; done &lt; requirements.txt This installs all of the packages that are available through Conda without crashing on the first missing package. However, what I would like to is track the packages that fail by capturing the output from Conda and if there is a PackageNotFoundError then run pip install on the package. I'm not great with bash, so hoping someone can suggest a hack. Another solution could be to just write out a new text file called pip-requirements.txt with the requirements that fail.
has answer: http://stackoverflow.com/a/47999512
possible better answer: http://stackoverflow.com/a/47999891
has answer: http://stackoverflow.com/a/47999891
has answer: http://stackoverflow.com/a/48014252
tagged with: bash
answer count: 3
has title: Bash Script to Conda Install requirements.txt with PIP follow-up
favorite count: 0
tagged with: python

http://stackoverflow.com/a/47856236
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/47856208
type: Answer
upvote count: 1
has body: all(len(lst) == 1 for lst in lists)

http://stackoverflow.com/comment/82792143
has text: They can't .. the code I posted will only get called if a role is also passed. This is more of a learning exercise as to the best /safest way to approach this.
comment on: http://stackoverflow.com/q/47911968
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47894254
type: Question
tagged with: torch
has body: I am trying to install fb-python library -a bridge between Lua and Python: https://github.com/facebookarchive/fblualib/tree/master/fblualib/python on my Linux machine using the command cd fblualib/fblualib/python luarocks make rockspec/fbpython-0.1-1.rockspec however all my attempts are encountering the error below: cmake -E make_directory build &amp;&amp; cd build &amp;&amp; cmake -DROCKS_PREFIX=/home/current_user/torch/install/lib/luarocks/rocks/fbpython/0.1-1 \ -DROCKS_LUADIR=/home/current_user/torch/install/lib/luarocks/rocks/fbpython/0.1-1/lua \ -DROCKS_LIBDIR=/home/current_user/torch/install/lib/luarocks/rocks/fbpython/0.1-1/lib \ .. &amp;&amp; make CMake Error at /usr/share/cmake-2.8/Modules/FindPackageHandleStandardArgs.cmake:108 (message): REQUIRED_ARGS (missing: GLOG_INCLUDE_DIR GLOG_LIBRARY) Call Stack (most recent call first): /usr/share/cmake-2.8/Modules/FindPackageHandleStandardArgs.cmake:315 (_FPHSA_FAILURE_MESSAGE) cmake/FindGlog.cmake:21 (FIND_PACKAGE_HANDLE_STANDARD_ARGS) CMakeLists.txt:27 (FIND_PACKAGE) -- Configuring incomplete, errors occurred! The file throwing the error is this: https://github.com/facebookarchive/fblualib/blob/master/fblualib/cmake/FindGlog.cmake However, I have installed the Glog library https://github.com/google/glog/releases: given that I don't have sudo access to the machine, I set ./configure to a custom location that I probably need to specify now for the GLOG_INCLUDE_DIR and GLOG_LIBRARY flags. How to do this? Any suggestion is appreciated. Thank you!
upvote count: 2
has title: Install fb-python on Linux machine
favorite count: 0
type: UnansweredQuestion
tagged with: glog
tagged with: python
tagged with: lua
score: 2
downvote count: 0
answer count: 0

http://stackoverflow.com/comment/82812138
has text: but I get :KeyError: 'The grouper name df.index is not found'
comment on: http://stackoverflow.com/a/47919274
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47977110
linked to: http://stackoverflow.com/q/41474150
type: Question
has title: Change the template option based on the condition
accepted answer: http://stackoverflow.com/a/47978100
answer count: 1
has body: How to change the template tag based on another template tag. task_count = {1 :3, 2: 0, 3: 1} --- i manually created task_type = {1:rebuild,2:upgrade,3:provisioning} ---- this from table I want to get the task count for ex: if the task id 1 then "Rebuild:3". I tried the below code it's not working {% for task in TaskTypeTag %} {{task_count.{{task.id}}}}
tagged with: django
tagged with: python
type: AnsweredQuestion
tagged with: django-templates
score: 0
has answer: http://stackoverflow.com/a/47978100

http://stackoverflow.com/q/47965879
tagged with: python
tagged with: phantomjs
tagged with: screen-scraping
tagged with: selenium
type: Question
has comment: http://stackoverflow.com/comment/82901551
has title: How can a website detect and block PhantomJS with Mozilla user agent-tag?
linked to: http://stackoverflow.com/q/47708260
has comment: http://stackoverflow.com/comment/82964597
duplicate of: http://stackoverflow.com/q/47708260
score: 0
has body: I am scraping a pool of URLs in a python selenium framework using PhantomJS. First, I specify the user agent. dcap = dict(DesiredCapabilities.PHANTOMJS) dcap["phantomjs.page.settings.userAgent"] = ( "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/53 " "(KHTML, like Gecko) Chrome/15.0.87") Next, I create the PhantomJS instance. def create_phantomJS(): driver = webdriver.PhantomJS("phantomjs.exe", desired_capabilities=dcap) return driver Then, I get all visible text from the website (quick &amp; dirty): def use_driver(driver, URL): website = driver.get(URL) # this line is needed, the highlighting is a bug in html = WebDriverWait(driver, 1).until(EC.presence_of_element_located((By.XPATH, ".//html"))) text = (str(html.text.encode("utf-8",'ignore'))) return text When setting the URL to "https://www.whoishostingthis.com/tools/user-agent/", the output contains the following information: Your User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/53 (KHTML, like Gecko) Chrome/15.0.87 This confirms that the setup is working. However, my website of interest returns: Access Denied You don't have permission to access "URL" on this server. In contrast, this works with geckodriver which I don't understand. In addition, using BeautifulSoup or requests just returns robots.txt content, which means that something at the DOM side is able to specifically detect PhantomJS Q1: How can PhantomJS be detected despite different user agent? Q2: What does Geckodriver different in order to overcome this check? Q3: Can this check be circumvented theoretically? Please note that I am interested in understanding the difference of both driver instances rather than doing something fishy.
has comment: http://stackoverflow.com/comment/82901570
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/82905543
type: Comment
has text: They don't. Yes, you can.
comment on: http://stackoverflow.com/a/47968003
score: 0
type: AnswerComment

http://stackoverflow.com/a/47920702
has comment: http://stackoverflow.com/comment/82809062
has comment: http://stackoverflow.com/comment/82808886
answers question: http://stackoverflow.com/q/47920624
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 6
score: 6
has body: For me working: d = {l: df.xs(l)['clump_thickness'].to_dict() for l in df.index.levels[0]} Another solution similar like DataFrame with MultiIndex to dict , but is necessary filter column for Series: d = df.groupby(level=0).apply(lambda df: df.xs(df.name).clump_thickness.to_dict()).to_dict() print (d) {0: {0: 274.0, 1: 19.0}, 1: {0: 67.0, 1: 12.0}, 2: {0: 83.0, 1: 45.0}, 3: {0: 16.0, 1: 40.0}, 4: {0: 4.0, 1: 54.0}, 5: {0: 0.0, 1: 69.0}, 6: {0: 0.0, 1: 0.0}, 7: {0: 0.0, 1: 0.0}, 8: {0: 0.0, 1: 0.0}, 9: {0: 0.0, 1: 0.0}}
has comment: http://stackoverflow.com/comment/104021598
has comment: http://stackoverflow.com/comment/104021696
accepted answer of: http://stackoverflow.com/q/47920624

http://stackoverflow.com/a/47968634
has comment: http://stackoverflow.com/comment/82906855
has comment: http://stackoverflow.com/comment/82907284
has comment: http://stackoverflow.com/comment/82907155
has body: Why do you need to restore the function and what does that even mean? If you need to use a model, you have to restore the corresponding graph. What your function does is defining nodes of the graph. You may use your function to build or rebuild that graph again and then load weights stored somewhere using Saver() or you may restore graph from the protobuf file. In order to rebuild the graph, try to invoke invoke your function somewhere output_layer=generator(keep_prob, z, out_channel_dim, alphag1, is_train=True) and than use Saver class as usual to restore weights. Your function does not compute, it defines a part or whole of the graph. All computations are performed by the graph. In the last case you will find useful the following thread. Usually, you will need to know names of the input and output layers. That can be obtained by the code: [n.name for n in tf.get_default_graph().as_graph_def().node]
has comment: http://stackoverflow.com/comment/82906999
score: 0
has comment: http://stackoverflow.com/comment/82906995
has comment: http://stackoverflow.com/comment/82907058
has comment: http://stackoverflow.com/comment/82907114
type: Answer
has comment: http://stackoverflow.com/comment/82906962
has comment: http://stackoverflow.com/comment/82907142
has comment: http://stackoverflow.com/comment/82906901
has comment: http://stackoverflow.com/comment/82907119
answers question: http://stackoverflow.com/q/47968556
has comment: http://stackoverflow.com/comment/82907011
has comment: http://stackoverflow.com/comment/82907089
has comment: http://stackoverflow.com/comment/82906988

http://stackoverflow.com/comment/82873327
score: 0
comment on: http://stackoverflow.com/a/47951615
type: Comment
type: AnswerComment
has text: Can you explain this line: punc_count[3] -= punc_count[2] * 3 I don't understand [2] is it the number of index?

http://stackoverflow.com/a/47903947
score: 0
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/47903089
has body: There is a misspelling agrv. After reading the file, you are not closing it. Try this: import sys def cat(filename): f = open(filename) text = f.read() f.close() print(text) def main(): cat(sys.argv[1]) if __name__ == '__main__': main() I would rewrite the cat() function using with statement as it takes care of closing the file. def cat(filename): with open(filename) as f: text = f.read() print(text) Python Tutorial says: It is good practice to use the with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point.
accepted answer of: http://stackoverflow.com/q/47903089

http://stackoverflow.com/a/47974910
type: Answer
upvote count: 2
score: 2
has body: Option 1 Inplace with update df.update( df.myValues.loc[ lambda x: ~x.str.contains(':') ].str.replace('\s+is\s+', ':')) myValues 0 One:1 1 Two:2 2 Three:3 3 Four is IV:4 Option 2 Inline and using map f = lambda x: x if ':' in x else x.replace(' is ', ':') df.assign(myValues=list(map(f, v))) myValues 0 One:1 1 Two:2 2 Three:3 3 Four is IV:4
answers question: http://stackoverflow.com/q/47973172
downvote count: 0

http://stackoverflow.com/comment/82949971
type: Comment
comment on: http://stackoverflow.com/q/47990482
score: 1
has text: In CBC mode the output of block *i* depends from the output of block *i-1*... It's normal that you don't get the same result by encrypting again the same data, it's exactly the kind of problem that CBC was designed to solve.
type: QuestionComment

http://stackoverflow.com/comment/82955472
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47993317
has text: @Daniel I added some extra information.

http://stackoverflow.com/comment/82967146
type: Comment
type: QuestionComment
has text: @DanMašek Maybe, I will try it. Screenshots have lower resolution than video frames so I thought that using the smaller resolution will make calculation of SSIM faster.
comment on: http://stackoverflow.com/q/47999030
score: 0

http://stackoverflow.com/comment/82869532
comment on: http://stackoverflow.com/q/47949808
type: Comment
type: QuestionComment
has text: Please give a more detailed problem description! How long? Any output? Python and pip versions?
score: 0

http://stackoverflow.com/a/47878489
has body: Would this work? In this solution, I used x.name to get the row index. df['Cumulative Total'] = df.apply(lambda x: x['Total'] if x.name == 0 else x.shift()['Cumulative Total']-(x.shift()['Total']*(x.shift()['Annualized Rate']/1200)),axis=1)
answers question: http://stackoverflow.com/q/47878410
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/82723240

http://stackoverflow.com/a/47968262
has body: Try range(len(current_ins[1])): or range(int(current_ins[1])):. It depends on what is inside current_ins[1].
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/82906181
answers question: http://stackoverflow.com/q/47968210

http://stackoverflow.com/comment/82836946
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47933806
score: 0
has text: I'm confused, so you don't add this into models.py?

http://stackoverflow.com/comment/82910010
has text: I think you need to think in detail about what you want: according to your github you have one function that ignores both its parameters and returns nothing - this doesn't look like it can meaningfully be wrapped in Cython. You've also got a main program which accepts some file names as command line arguments and calls opencv - which again isn't really a good candidate to wrap in Cython. You've also put the code off-site so it isn't a self-contained question here. Finally there already is an opencv wrapper for Python? Why not use that?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47969835

http://stackoverflow.com/comment/82749394
has text: But you are adding list to string aint that incorrect , where u did this, output = output + list2
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47891367
type: AnswerComment

http://stackoverflow.com/q/47861361
tagged with: python
possible better answer: http://stackoverflow.com/a/47861404
has answer: http://stackoverflow.com/a/47861404
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47861408
type: Question
tagged with: object
score: 0
accepted answer: http://stackoverflow.com/a/47861408
has answer: http://stackoverflow.com/a/47861416
has title: NameError: name 'myname' is not defined in Python
answer count: 3
has body: I'm getting this error quite often so I'd like to give an example: class Me(): def __init__(self,name): self.name=name def call(): myname=Me("Alex") printIt() def printIt(): print(myname.name) call() Why am I getting this error instead of printing "Alex"? Thanks in advance

http://stackoverflow.com/comment/82911827
type: QuestionComment
has text: Very nice. What is not working?
score: 1
comment on: http://stackoverflow.com/q/47971142
type: Comment

http://stackoverflow.com/q/47881249
tagged with: python
has comment: http://stackoverflow.com/comment/82822172
linked to: http://stackoverflow.com/q/54459701
tagged with: selenium-chromedriver
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82729172
score: 1
linked to: http://stackoverflow.com/q/52782684
tagged with: selenium
upvote count: 1
tagged with: web-crawler
linked to: http://stackoverflow.com/q/49775502
linked to: http://stackoverflow.com/q/45672693
type: Question
has title: Python Selenium ChromeDriver not waiting for pages to load
linked to: http://stackoverflow.com/q/53240157
has answer: http://stackoverflow.com/a/47882636
linked to: http://stackoverflow.com/q/50168663
linked to: http://stackoverflow.com/q/59909654
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/48079120
linked to: http://stackoverflow.com/q/53588966
linked to: http://stackoverflow.com/q/47770144
linked to: http://stackoverflow.com/q/52603847
favorite count: 0
has comment: http://stackoverflow.com/comment/82728446
accepted answer: http://stackoverflow.com/a/47882636
linked to: http://stackoverflow.com/q/59130200
has body: I have a set of Web scrapers designed to run in Python 3.6 using Selenium ChromeDriver. All of them ran simply perfect. This week I updated Selenium to v2.8 and ChromeDriver to v2.34. Immediately, the scrapers failed to work normally and crash at some early point of the crawling. I have a little implementation of sys.stdout that outputs both to a .txt and the console, so I started noticing the errors are like this: Message: no such frame (Session info: chrome=63.0.3239.108) (Driver info: chromedriver=2.34.522940 (1a76f96f66e3ca7b8e57d503b4dd3bccfba87af1),platform=Windows NT 10.0.15063 x86_64) or Message: no such element: Unable to locate element: {"method":"name","selector":"txtClave"} (Session info: chrome=63.0.3239.108) (Driver info: chromedriver=2.34.522940 (1a76f96f66e3ca7b8e57d503b4dd3bccfba87af1),platform=Windows NT 10.0.15063 x86_64) Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="ctl00_cp_wz_ddlTarjetas"]/option[2]"} (Session info: chrome=63.0.3239.108) (Driver info: chromedriver=2.34.522940 (1a76f96f66e3ca7b8e57d503b4dd3bccfba87af1),platform=Windows NT 10.0.15063 x86_64) Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="ctl00_cp_wz_ddlTarjetas"]/option[3]"} (Session info: chrome=63.0.3239.108) (Driver info: chromedriver=2.34.522940 (1a76f96f66e3ca7b8e57d503b4dd3bccfba87af1),platform=Windows NT 10.0.15063 x86_64) Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="ctl00_cp_wz_ddlTarjetas"]/option[4]"} (Session info: chrome=63.0.3239.108) (Driver info: chromedriver=2.34.522940 (1a76f96f66e3ca7b8e57d503b4dd3bccfba87af1),platform=Windows NT 10.0.15063 x86_64) These are often followed by a ChromeDriver crash Windows message that was not there ever before: chromedriver.exe has stopped working. While looking at the Chrome window, and by debugging, I suspect the error is caused at lines that should make the spider wait for a page to load, but i…

http://stackoverflow.com/comment/82917937
has text: `VID=0x01 and PID =0x00` ? Remove all drivers for your USB device. You are an Administrator ?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47973496
type: QuestionComment

http://stackoverflow.com/a/47863008
has body: A little roundabout, but this can be done by applying a groupby operation on each row, and then using np.where to selectively apply your values to the original. def f(x): return x.groupby(x.ne(x.shift()).cumsum()).cumcount() + 1 i = df.apply(pd.to_numeric, errors='coerce') j = 'inactive_' + i.apply(f, axis=1).astype(str) df[:] = np.where(i.ne(0), df.values, j) df 2017-04-03 2017-04-04 2017-04-05 2017-04-06 id 0 inactive_1 active inactive_1 inactive_2 1 inactive_1 active inactive_1 active 2 inactive_1 inactive_2 inactive_3 inactive_4
score: 3
answers question: http://stackoverflow.com/q/47862796
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47862796
type: Answer

http://stackoverflow.com/a/47893468
type: Answer
upvote count: 1
has body: Another alternative for extracting the prices without knowledge of the time would be to use the urllib.request package with the json package and a bit of looping: import json import urllib.request def extract_json(f): json_decode = json.load(f) time_series = json_decode['Time Series (1min)'] for data in time_series: print(time_series[data]['3. low']) opener = urllib.request.FancyURLopener({}) url = "http://localhost:8092/sample_json.json" f = opener.open(url) extract_json(f) If the input on the server is: { "Time Series (1min)": { "2017-12-19 13:01:00": { "1. open": "196.4100", "2. high": "196.5075", "3. low": "196.3800", "4. close": "196.3800", "5. volume": "4961" } } } The result of running the script is: 196.3800 Tried on this version: 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)]
downvote count: 1
score: 0
answers question: http://stackoverflow.com/q/47892781

http://stackoverflow.com/a/47871526
score: 1
has body: You have to give the column your timers are in weight! self.timers_frame.columnconfigure(0, weight=1) Otherwise the column has exactly the width of your timers and not the width of your timers_frame.
answers question: http://stackoverflow.com/q/47871084
accepted answer of: http://stackoverflow.com/q/47871084
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0

http://stackoverflow.com/comment/82813687
type: Comment
score: 1
comment on: http://stackoverflow.com/a/47922933
has text: The OP is using a Mac, and `python2` works for me on a Mac.
type: AnswerComment

flask-sqlalchemy
tags question: http://stackoverflow.com/q/47998500
tags question: http://stackoverflow.com/q/47857173
tags question: http://stackoverflow.com/q/47909457
type: Tag
tags question: http://stackoverflow.com/q/47912520
tags question: http://stackoverflow.com/q/47931787
tags question: http://stackoverflow.com/q/48006939
tags question: http://stackoverflow.com/q/47888579
tags question: http://stackoverflow.com/q/47949900
tags question: http://stackoverflow.com/q/47865981
tag name: flask-sqlalchemy
tags question: http://stackoverflow.com/q/47904931
tags question: http://stackoverflow.com/q/47995784
tags question: http://stackoverflow.com/q/47893496

http://stackoverflow.com/comment/82977891
type: Comment
type: QuestionComment
score: 0
has text: @PM2Ring - True. OP does not specify version, then the caveat.
comment on: http://stackoverflow.com/q/48004691

http://stackoverflow.com/a/47973280
upvote count: 1
type: Answer
has body: That's absolute difference between pass and None The pass (without upper case P): Because python be the indent base language, so if you define a new method, you should have some code after that. def method_a(): some_thing = 1 # Have to do some thing If not, an exception should be raised so you could use the pass keyword for hacks this problem. def method_a(): pass # Do nothing The None: So very different, the None keyword has a little bit same to the null keywords from another language like Java or C. That may be the empty data or not assign data like that. [] == None null == None () == None ...
answers question: http://stackoverflow.com/q/47973242
downvote count: 0
score: 1

http://stackoverflow.com/q/47940331
has title: Constructing pandas dataframe from a list of objects
score: 1
upvote count: 1
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/47942104
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has body: Let me start off by saying that I'm fairly new to numpy and pandas. I'm trying to construct a pandas dataframe but I'm not sure that I'm doing things in an appropriate way. My setting is that I have a large list of .Net objects (that I have very little control over) and I want to build a time series from this using pandas dataframe. I have an example where I have replaced the .Net class with a simplified placeholder class just for demonstration. The listOfthings in the code is basically what I get from .Net and I want to convert that into a pandas dataframe. My questions are: I construct the dataframe by first constructing a numpy array. Is this necessary? Also, this array doesn't have the size 1000x2 as I expect. Is there a better way to use numpy here? This code doesn't work because I doesn't seem to be able to cast the string to a datetime64. This confuses me since the string is in ISO format and it works when I try to parse it like this: np.datetime64(str(np.datetime64('now','us'))). Code sample: import numpy as np import pandas as pd class PlaceholderClass: def time(self): return str(np.datetime64('now', 'us')) def value(self): return 100*np.random.random_sample() listOfThings = [PlaceholderClass() for i in range(1000)] arr = np.array([(x.time(), x.value()) for x in listOfThings], dtype=[('time', np.datetime64), ('value', np.float)]) dataframe = pd.DataFrame(data=arr['value'], index=arr['time']) Thanks in advance
has answer: http://stackoverflow.com/a/47942104
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/82856305
has text: `--enable-R-shlib --enable-R-static-lib ` seems wrong. Pick one.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47943336

http://stackoverflow.com/comment/82762081
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47897568
has text: This is good advice in general, but `os.system()` blocks too.
score: 0

http://stackoverflow.com/a/47981501
has body: A high level approach involves modifying the df_summary (alias df2) to get our output. We'll need to set_index operation on the days_max column on df2. We'll also change the name to days (which will help later on) groupby to group on person apply a reindex operation on the index (days, so we get rows for each day leading upto the last day) fillna to fill NaNs in the convert column generated as a result of the reindex assign to create a dummy column for emailed that we'll set later. Next, index into the result of the previous operation using df_emailed. We'll use those values to set the corresponding emailed cells to 1. This is done by MultiIndexing with loc. Finally, use reset_index to bring the index out as columns. def f(x): return x.reindex(np.arange(1, x.index.max() + 1)) df = df2.set_index('days_max')\ .rename_axis('day')\ .groupby('person')['convert']\ .apply(f)\ .fillna(0)\ .astype(int)\ .to_frame()\ .assign(emailed=0) df.loc[df1'person', 'day'.apply(tuple, 1).values, 'emailed'] = 1 df.reset_index() person day convert emailed 0 A 1 0 0 1 A 2 0 1 2 A 3 0 0 3 A 4 0 1 4 A 5 0 0 5 A 6 0 0 6 A 7 0 0 7 A 8 0 1 8 A 9 0 1 9 A 10 1 0 10 B 1 0 1 11 B 2 0 1 12 B 3 0 0 13 B 4 0 0 14 B 5 0 1 Where df1 = df_emailed and, df2 = df_summary
has comment: http://stackoverflow.com/comment/82941963
has comment: http://stackoverflow.com/comment/82942479
downvote count: 0
has comment: http://stackoverflow.com/comment/82937039
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47981341
has comment: http://stackoverflow.com/comment/82933450
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/82933442
answers question: http://stackoverflow.com/q/47981341
score: 1

http://stackoverflow.com/comment/82682321
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/47858828
has text: Thanks :-) , I did not notice that require join, when I saw your answer, thank you my friend :-)

http://stackoverflow.com/comment/82764814
type: QuestionComment
has text: Is there any reason you can't use the vendors `pytineye` client? [Their examples](https://api.tineye.com/python/docs/) seems to cover exactly what you need.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47896933

http://stackoverflow.com/q/47979623
favorite count: 0
type: Question
upvote count: 2
answer count: 2
accepted answer: http://stackoverflow.com/a/47979820
tagged with: python
has title: word frequencies in text file in python
has body: I want to find frequencies for the certain words in wanted, and while it finds me the frequecies, the displayed result contains lots of unnecessary data. Code: from collections import Counter import re wanted = "whereby also thus" cnt = Counter() words = re.findall('\w+', open('C:/Users/user/desktop/text.txt').read().lower()) for word in words: if word in wanted: cnt[word] += 1 print (cnt) Results: Counter({'e': 131, 'a': 119, 'by': 38, 'where': 16, 's': 14, 'also': 13, 'he': 4, 'whereby': 2, 'al': 2, 'b': 2, 'o': 1, 't': 1}) Questions: How do i omit all those 'e', 'a' 'by', 'where', etc.? If I then wanted to sum up the frequencies of words (also, thus, whereby) and divide them by total number of words in text, would that be possible? disclaimer: this is not school assignment. i jut got lots of free time at work now and since i spend a lot of time with reading texts i decided to do this little project of mine to remind myself a bit of what i've been taught couple years ago. Thanks in advance for any help.
downvote count: 1
has answer: http://stackoverflow.com/a/47979820
has comment: http://stackoverflow.com/comment/82928111
has comment: http://stackoverflow.com/comment/82927911
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47991286
has comment: http://stackoverflow.com/comment/82927815
score: 1
has answer: http://stackoverflow.com/a/47991286

http://stackoverflow.com/q/47941831
type: AnsweredQuestion
upvote count: 2
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/47942146
tagged with: evaluation
has title: How to evaluate Tensorflow model on a full validation example
has body: I am using Tensorflow's tf.estimator.DNNClassifier.evaluate function to evaluate my network. I am using Tensorflow's Iris data located here. Upon some further investigation and maths, I have determined that no matter the evaluation set size, 128 examples are evaluated. For instance, the iris_training.csv has only 120 examples, and 128 are evaluated (presumably 8 are evaluated twice). I also have some validation sets with 1k examples, but only 128 examples are evaluated in this case as well. I figured this out by dividing the total loss by the average loss to get the number of examples evaluated. I would like to be able to vary this arbitrarily, especially when working with larger validation sets. How can this be accomplished? I have tried with the evaluation function's steps argument = 1, 2, 10, 120, etc... which results in the the same, 128 examples being evaluated, and steps = None which results in the function never returning. I can't understand from where this 128 metric is originating, even after having scoured the API located here. I also looked into using the similar tf.contrib.learn.DNNClassifier's estimator located here, but the API states that the function is deprecated and will be removed, so I figured that wasn't the best option. I am assuming that the steps argument isn't what I'm looking for after locating another SO page here. So, how can I use Tensorflow to evaluate an arbitrary number of validation examples?
score: 2
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/39985025
tagged with: tensorflow-datasets
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47942146
tagged with: python

http://stackoverflow.com/comment/82748539
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47891051
has text: I'm using for loops and if conditions
type: Comment

http://stackoverflow.com/q/47856472
has comment: http://stackoverflow.com/comment/82677108
tagged with: python
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has title: How can I sort historical data in a list in order to calculate monthly averages
upvote count: 1
type: Question
has body: I am a python beginner and I am struggling with sorting a list which is an output of stock historical data of a company.so far I have retrieved the file from the url given and I have printed the data into a one long list with date, open, close,volume etc.how can I get about sorting it out and be able to calculate the average prices. please help import httplib2 GOOGLE_URL = "https://www.dropbox.com/s/qr7cu2kui654kgz/googlePrices.csvdl=1" h = httplib2.Http(".cache") headers, prices = h.request(GOOGLE_URL) dataList = prices.decode().strip('\n').split(',') dataList = dataList[1:] print (dataList)
has comment: http://stackoverflow.com/comment/82677315
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82677253

http://stackoverflow.com/comment/82940551
has text: You want you error response like `{promptmsg:xxx}`? I must remind you,if you do like this,you will never know which field in model cause the error!
type: Comment
comment on: http://stackoverflow.com/q/47985717
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82913530
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47971619
has text: By the way, thank you again SO MUCH for your help so far. I honestly got stuck on this for hours and you just solved it in a couple of minutes. THANK YOU

http://stackoverflow.com/q/47896617
has title: How do you delete rows with a certain object in pandas, python?
has answer: http://stackoverflow.com/a/47896745
favorite count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/82760823
has comment: http://stackoverflow.com/comment/82760233
tagged with: python
tagged with: jupyter-notebook
score: -1
has answer: http://stackoverflow.com/a/47916098
has body: I have a column in my data that contains these kind of values 2 2 yes 2 yes In python pandas how would I identify the entire row containing a string of letters and then delete or drop the entire row? Thanks
type: UnansweredQuestion
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/82760636
type: Question
has comment: http://stackoverflow.com/comment/82761490
answer count: 2

http://stackoverflow.com/a/47990888
has body: Here is my one-liner, using frozensets and and: len(set(map(frozenset, qlist)) and set(map(frozenset, reflist))) I understand you are new to Python, hence I will answer your question using your own method, just for the sake of recording the basic straightforward answer for future reference. First of all, your code shouldn't run at all. It must error out, because both each and reflist[i] are lists, and you are applying a string method of split(",") on them. Therefore you are getting the initial value of count = 0. You must check in the first place whether your code is even touching all the elements of qlist and reflist. This is not Code Review, hence I will leave it to you to run this and see the answer: i = 0 count = 0 for each in qlist: while i &lt; len(qlist): print i print each print reflist[i] i = i + 1 Keep in mind: You don't have to iterate on index! You can just loop over the elements of iterables directly! This is the answer you are looking for: match = [] # Optional, to see all the matching elements count = 0 for q in qlist: for r in reflist: if set(q) == set(r): print q, r match.append(q) count += 1 print match print count, len(match)
score: 0
answers question: http://stackoverflow.com/q/47988583
type: Answer

http://stackoverflow.com/comment/82925772
score: 0
type: Comment
type: QuestionComment
has text: @DeepSpace , Actually I am looking for a generic way so that if in case any new attribute gets added to input string then I don't have to modify regex. Only adding attribute in python object should work.
comment on: http://stackoverflow.com/q/47978454

http://stackoverflow.com/comment/82872107
has text: Copy your database
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47951268

http://stackoverflow.com/q/48003723
score: 1
has body: Because of large data, I have to use pyspark to combine dataframe values (a list) in different rows. The dataframe like this: x = sqlContext.createDataFrame([("A", ['1','2','3']),("B", ['4','2','5','6']),("C", ['2','4','9','10']),("D", ['11','12','15','16'])],["index", "num_group"]) +-----+----------------+ |index| num_group| +-----+----------------+ | A| [1, 2, 3]| | B| [4, 2, 5, 6]| | C| [2, 4, 9, 10]| | D|[11, 12, 15, 16]| +-----+----------------+ And I want to merge num_group by list which have the same element like this: (index is a meaningless value or string) +-------------------------+ | num_group| +-------------------------+ |[1, 2, 3, 4, 5, 6, 9, 10]| | [11, 12, 15, 16]| +-------------------------+ I think i can use graphframes GraphX to find the connection and merge two or more rows based on equal values in different rows. Is it possible? I'm not really understanding the example of the documents. Any help would be greatly appreciated.
type: Question
tagged with: pyspark
has title: pyspark: Merge two or more rows if column have equal values in different rows
tagged with: python-2.7
tagged with: spark-graphx
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
downvote count: 0
has answer: http://stackoverflow.com/a/48017873

http://stackoverflow.com/comment/82750628
type: AnswerComment
type: Comment
score: 0
has text: Fixed, can you please upvote me @OdayHajYehia ? It's very important to me and I think I did a good job.
comment on: http://stackoverflow.com/a/47891367

http://stackoverflow.com/comment/82811788
comment on: http://stackoverflow.com/q/47918946
has text: Could you please elaborate what you're trying to achieve. Include a concrete sample of the result you're after. The sample query you've displayed does not reflect "I am trying to get all Contacts that **are related to certain** Classification."
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82816066
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47923884
has text: `os.rename("fred.jpg", "tmp_image.jpg")`
type: Comment

http://stackoverflow.com/comment/82873820
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47923801
type: Comment
has text: I still don't know, what your exact problem is, can you include your error message or your wrong output? If it is urgent, you should check out the program `gscan2pdf`.

http://stackoverflow.com/comment/124156959
type: Comment
has text: @hieko, look at [Amit's answer](https://stackoverflow.com/a/47992113/14062356). you should use either `list2 = list1[:]` or `list2 list1.copy()`. I'd recommend the second since it is clearer.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47986258

http://stackoverflow.com/comment/82995167
type: Comment
comment on: http://stackoverflow.com/q/48013114
type: QuestionComment
score: 1
has text: So, are you looking for `hstack` or something of the sort?

http://stackoverflow.com/comment/82975211
comment on: http://stackoverflow.com/q/48003270
has text: what is the source of the code you supplied? and what is your objective?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47970096
upvote count: 3
type: AcceptedAnswer
has body: With X and Y as the 2D and 3D inputs respectively, we can use tf.einsum - tf.einsum('ij,ikj-&gt;ik',X,Y) The output would have a shape of (?, 15).
has comment: http://stackoverflow.com/comment/82909552
has comment: http://stackoverflow.com/comment/82909539
type: Answer
score: 3
accepted answer of: http://stackoverflow.com/q/47970040
downvote count: 0
answers question: http://stackoverflow.com/q/47970040

http://stackoverflow.com/comment/82682259
comment on: http://stackoverflow.com/q/47858529
type: Comment
type: QuestionComment
has text: Use a set, not a list.
score: 0

http://stackoverflow.com/comment/82683515
type: Comment
type: QuestionComment
has text: you've got a redundancy here: `for k in range(i+1,100):` would be better
score: 1
comment on: http://stackoverflow.com/q/47859384

http://stackoverflow.com/q/47870531
linked to: http://stackoverflow.com/q/6224052
has comment: http://stackoverflow.com/comment/82710146
has body: I wrote the following Python 3 script: from sys import argv from os.path import exists script, from_file, to_file = argv print(f"Copying from {from_file} to {to_file}") in_file = open(from_file) indata = in_file.read() print(f"The input file is {len(indata)} bytes long") print(f"Does the output file exist? {exists(to_file)}") print("Ready, hit RETURN to continue, CTRL-C to abort.") input() out_file = open(to_file, 'w') out_file.write(indata) print("Alright, all done.") out_file.close() in_file.close() Apparently the output of len(indata) should be: The input file is 21 bytes long But I get: The input file is 46 bytes long The from_file is a file called test.txt which contains the text "This is a test file." I double-checked the text inside test.txt. I thought that the difference may be on the computer since I'm using Windows and the teacher doesn't. Expected output of the exercise according to Zed This is my first post here and I already tried to find something about this issue. Although I found some questions about exercise 17, I found nothing about the bytes difference.
has answer: http://stackoverflow.com/a/47871742
accepted answer: http://stackoverflow.com/a/47871742
has comment: http://stackoverflow.com/comment/82707766
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82707591
has comment: http://stackoverflow.com/comment/82709547
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82730911
linked to: http://stackoverflow.com/q/6769311
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82707489
has comment: http://stackoverflow.com/comment/82706610
has comment: http://stackoverflow.com/comment/82706427
has comment: http://stackoverflow.com/comment/82707202
favorite count: 0
has comment: http://stackoverflow.com/comment/82708191
has comment: http://stackoverflow.com/comment/82708650
has comment: http://stackoverflow.com/comment/82707508
has comment: http://stackoverflow.com/comment/82707570
has comment: http://stackoverflow.com/comment/82707156
linked to: http://stackoverflow.com/q/13590749
tagged with: python
tagged with: python-3.x
has title: LPTHW Exercise 17. Why the output from len() is not what the exercise says?

http://stackoverflow.com/q/47916639
score: 0
tagged with: matrix
has comment: http://stackoverflow.com/comment/82801551
has comment: http://stackoverflow.com/comment/82802674
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82802599
downvote count: 1
has comment: http://stackoverflow.com/comment/82802478
has body: Sample Code: https://pastebin.com/L8qV1eWQ Link to PDF/Image of the code: https://imgur.com/tiPcB8M import numpy as np from scipy.optimize import minimize import math as m import random #Inputs: ## X = A 100x6 array of 600 organized variables. def func(X): x = 0 for i in range(0,100): for j in range(0,6): x = x = X[i][j] return -1.0*x #Inputs: ## a = the A matrix constructed below ## d = the d array constructed below #Outputs: # res - result of optimization def Optimize(a,c,d): ###Constraints### cons = list() for i in range(0,100): cons.append( {'type' : 'ineq', 'fun' : lambda X : np.array([ X[i][0]+X[i][1]+ X[i][2]+X[i][3]+X[i][4]+X[i][5]-d ]), 'jac' : lambda X : np.ones(6) }) for j in range(0,6): cons.append( {'type' : 'ineq', 'fun' : lambda X : np.array([ X[0][j]+ X[1][j]+ X[2][j]+ X[3][j]+ X[4][j]+ X[5][j]+ X[6][j]+ X[7][j]+ X[8][j]+ X[9][j]+ X[10][j]+X[11][j]+X[12][j]+X[13][j]+X[14][j]+X[15][j]+ X[16][j]+X[17][j]+X[18][j]+X[19][j]+ X[20][j]+X[21][j]+X[22][j]+X[23][j]+X[24][j]+X[25][j]+ X[26][j]+X[27][j]+X[28][j]+X[29][j]+ X[30][j]+X[31][j]+X[32][j]+X[33][j]+X[34][j]+X[35][j]+ X[36][j]+X[37][j]+X[38][j]+X[39][j]+ X[40][j]+X[41][j]+X[42][j]+X[43][j]+X[44][j]+X[45][j]+ X[46][j]+X[47][j]+X[48][j]+X[49][j]+ X[50][j]+X[51][j]+X[52][j]+X[53][j]+X[54][j]+X[55][j]+ X[56][j]+X[57][j]+X[58][j]+X[59][j]+ X[60][j]+X[61][j]+X[62][j]+X[63][j]+X[64][j]+X[65][j]+ X[66][j]+X[67][j]+X[68][j]+X[69][j]+ X[70][j]+X[71][j]+X[72][j]+X[73][j]+X[74][j]+X[75][j]+ X[76][j]+X[77][j]+X[78][j]+X[79][j]+ X[80][j]+X[81][j]+X[82][j]+X[83][j]+X[84][j]+X[85][j]+ X[86][j]+X[87][j]+X[88][j]+X[89][j]+ X[90][j]+X[91][j]+X[92][j]+X[93][j]+X[94][j]+X[95][j]+ X[96][j]+X[97][j]+X[98][j]+X[99][j] -c]), 'jac' : lambda X : np.ones(100)}) bnds = list() for i in range(0,100): for j in range(0,6): bnds.append((0,A[i][j])) res = minimize(func, np.zeros(shape=(100,6)), jac=np.ones(600), bounds = bnds, constraints=cons, method='SLSQP', options={'disp': True}) return res ##Create sample matrix and arrays of values…
tagged with: scipy
has comment: http://stackoverflow.com/comment/82801443
has title: scipy.optimize.minimize "ValueError:The truth value of an array with more than one element is ambiguous
type: Question
has comment: http://stackoverflow.com/comment/82801986
favorite count: 0
tagged with: optimization

http://stackoverflow.com/a/47914046
accepted answer of: http://stackoverflow.com/q/47913881
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: pd.to_numeric + sort_values + loc - df.loc[pd.to_numeric(df.col0, errors='coerce').sort_values().index] col0 col1 col2 col4 3 34 865665 296 0 4 56 865700 297 0 5 100 865628 292 5 1 '1ZE7999' 865545 20 20 2 'R022428' 865584 297 0 Details pd.to_numeric coerces non-integral values to NaN - i = pd.to_numeric(df.col0, errors='coerce') i 1 NaN 2 NaN 3 34.0 4 56.0 5 100.0 Name: col0, dtype: float64 sort_values sorts the column, ignoring NaNs. j = i.sort_values() j 3 34.0 4 56.0 5 100.0 1 NaN 2 NaN Name: col0, dtype: float64 Observe the index. All you need to do is use the index to reindex the dataframe. Either loc or reindex will do it. df.loc[j.index] col0 col1 col2 col4 3 34 865665 296 0 4 56 865700 297 0 5 100 865628 292 5 1 '1ZE7999' 865545 20 20 2 'R022428' 865584 297 0 df.reindex(index=j.index) col0 col1 col2 col4 3 34 865665 296 0 4 56 865700 297 0 5 100 865628 292 5 1 '1ZE7999' 865545 20 20 2 'R022428' 865584 297 0 If you need to reset the index, that's easily done. df.loc[j.index].reset_index(drop=True) col0 col1 col2 col4 0 34 865665 296 0 1 56 865700 297 0 2 100 865628 292 5 3 '1ZE7999' 865545 20 20 4 'R022428' 865584 297 0
answers question: http://stackoverflow.com/q/47913881
score: 10
upvote count: 10

http://stackoverflow.com/comment/85085156
type: Comment
comment on: http://stackoverflow.com/a/49034527
type: AnswerComment
has text: thank you for the feedback. I know it works. What I'd like to know is if there's a more efficient way of doing it. Did you get a goo speed up? How much?
score: 0

http://stackoverflow.com/comment/82865482
type: Comment
comment on: http://stackoverflow.com/q/47936097
score: 0
has text: Also, thank you for showing me the docs, I tried the with open(...) in my code and replacing newline= ' ' with 'b' flag for python 2:https://docs.python.org/2/library/csv.html#csv.writer yet still encountering the same 'not all parameters..' error. Unsure on how to proceed, any guidance or suggestions would be very helpful.
type: QuestionComment

performance
tags question: http://stackoverflow.com/q/47993569
tags question: http://stackoverflow.com/q/47886509
tags question: http://stackoverflow.com/q/47895267
tags question: http://stackoverflow.com/q/48002130
tags question: http://stackoverflow.com/q/47974874
tags question: http://stackoverflow.com/q/47987412
tags question: http://stackoverflow.com/q/47976142
tags question: http://stackoverflow.com/q/47969149
tags question: http://stackoverflow.com/q/47971431
tags question: http://stackoverflow.com/q/47898526
tags question: http://stackoverflow.com/q/47961104
tags question: http://stackoverflow.com/q/47882038
tags question: http://stackoverflow.com/q/47968183
tags question: http://stackoverflow.com/q/48007580
tags question: http://stackoverflow.com/q/47986269
tags question: http://stackoverflow.com/q/47883715
tags question: http://stackoverflow.com/q/47859316
tags question: http://stackoverflow.com/q/47954315
tags question: http://stackoverflow.com/q/47859236
tag name: performance
tags question: http://stackoverflow.com/q/47862083
tags question: http://stackoverflow.com/q/47948728
tags question: http://stackoverflow.com/q/47968136
type: Tag
tags question: http://stackoverflow.com/q/47998759
tags question: http://stackoverflow.com/q/47893677
tags question: http://stackoverflow.com/q/47859482

http://stackoverflow.com/comment/82934300
type: Comment
has text: Does this solution help? "Ok, so the easiest way for you to fix this up is to run `python3 -m pip install pyopenssl pyasn1 ndg-httpsclient`. That should fix your problem, but if it doesn't we can pursue more aggressive options." from https://github.com/requests/requests/issues/3006#issuecomment-226784234
type: QuestionComment
comment on: http://stackoverflow.com/q/47982858
score: 0

http://stackoverflow.com/comment/82916166
has text: Have you tried `cpdef`? That's supposed to make a function available to the importing `py` module. But even with that you might not be able to modify its value or use within the compiled code.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47973162
score: 0

http://stackoverflow.com/comment/82713937
comment on: http://stackoverflow.com/q/47874052
has text: @MartijnPieters: I think there's a valid question about use of super here, beyond the misspelled `__init__` method.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82749109
type: QuestionComment
comment on: http://stackoverflow.com/q/47891291
score: 1
has text: You already have all combinations, now put them into the Excel sheet. I think, copy-paste would work.
type: Comment

http://stackoverflow.com/comment/82851829
type: QuestionComment
comment on: http://stackoverflow.com/q/47941253
has text: this is really trivial. Try a few things out. You will get it on your own. I would recreate the dictionary with a dict-comprehension
score: 1
type: Comment

http://stackoverflow.com/q/47897003
has answer: http://stackoverflow.com/a/47897067
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82761672
type: Question
tagged with: pandas
accepted answer: http://stackoverflow.com/a/47897067
has body: Here is pandas data frame format of the data source cinema kiwi restaurant sushi 0 [2, 2, 2] [5, 5, 5] [2, 2, 2] [14, 14, 14] 1 [2, 2, 2] [2, 2, 2] [2, 2, 2] [2, 2, 2] 2 [1, 1, 1] [1, 1, 1] [10, 10, 10] [1, 1, 1] I would like to transform it as follow by choosing only the first value of the array cinema kiwi restaurant sushi 0 2 5 2 14 1 2 2 2 2 2 1 1 10 1 Is there any function to do that ? I was thinking about using the "apply" method but I am not sure if it the best/most straightforward way. Thank you by advance for your comments.
has title: How to extract a value from a cell containing an array in pandas Dataframe?
tagged with: python
linked to: http://stackoverflow.com/q/41708059
answer count: 1
score: 0
tagged with: dataframe

http://stackoverflow.com/comment/82770195
comment on: http://stackoverflow.com/q/47901163
type: QuestionComment
has text: Did you bother reading the official doc for your Django version before posting ?
score: 0
type: Comment

http://stackoverflow.com/comment/82964685
score: 0
type: Comment
has text: See my edit to the question that reflects your advice. Can you confirm that the arrow line is still solid on your system? It still shows solid on mine.
type: AnswerComment
comment on: http://stackoverflow.com/a/47997896

http://stackoverflow.com/comment/82722510
score: 0
has text: That is what it basically looks like. All I want to do is add to that dataframe if df#2 has matching student ids in it as does df#1. Then I have a collection of a whole group of certain students with the grades. Because they are allowed multiple submissions.
comment on: http://stackoverflow.com/q/47878204
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83009565
score: 0
type: Comment
has text: @micheal sir i also need help in showing popup. I have edited my post
comment on: http://stackoverflow.com/a/48010564
type: AnswerComment

http://stackoverflow.com/comment/82803371
score: 0
has text: @newcoder you still haven't pasted the error message fully. I recreated your case and ran it to see the full error message. Please see my answer.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47917286

http://stackoverflow.com/a/48004276
downvote count: 0
score: 3
accepted answer of: http://stackoverflow.com/q/48004089
answers question: http://stackoverflow.com/q/48004089
upvote count: 3
type: AcceptedAnswer
has body: It is a very simple way: set_results = [] for r in results: for sub_r in r: if not sub_r in set_results: set_results.append(sub_r) Output: [{'a': 1, 'b': [1, 2, 3]}, {'a': 10, 'b': [7, 8, 9]}, {'a': 100, 'b': [100, 200, 300]}, {'a': 123, 'b': [9, 5, 2]}]
type: Answer

http://stackoverflow.com/comment/82734873
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47884565
has text: I was thinking about this but every setting (including the plugboard) was given in the exercise and I have already triple checked whether it is the same for me :(

http://stackoverflow.com/a/47954408
score: 9
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/47954034
upvote count: 9
accepted answer of: http://stackoverflow.com/q/47954034
has comment: http://stackoverflow.com/comment/82897364
downvote count: 0
has comment: http://stackoverflow.com/comment/82892317
has comment: http://stackoverflow.com/comment/111225541
has body: There are numerous ways to do so. The easiest is to check out the methods proposed in Kernels on Kaggle competition TensorFlow Speech Recognition Challenge (just sort by most voted). This one is particularly clear and simple and contains the following function. The input is a numeric vector of samples extracted from the wav file, the sample rate, the size of the frame in milliseconds, the step (stride or skip) size in milliseconds and a small offset. from scipy.io import wavfile from scipy import signal import numpy as np sample_rate, audio = wavfile.read(path_to_wav_file) def log_specgram(audio, sample_rate, window_size=20, step_size=10, eps=1e-10): nperseg = int(round(window_size * sample_rate / 1e3)) noverlap = int(round(step_size * sample_rate / 1e3)) freqs, times, spec = signal.spectrogram(audio, fs=sample_rate, window='hann', nperseg=nperseg, noverlap=noverlap, detrend=False) return freqs, times, np.log(spec.T.astype(np.float32) + eps) Outputs are defined in the SciPy manual, with an exception that the spectrogram is rescaled with a monotonic function (Log()), which depresses larger values much more than smaller values, while leaving the larger values still larger than the smaller values. This way no extreme value in spec will dominate the computation. Alternatively, one can cap the values at some quantile, but log (or even square root) are preferred. There are many other ways to normalize the heights of the spectrogram, i.e. to prevent extreme values from "bullying" the output :) freq (f) : ndarray, Array of sample frequencies. times (t) : ndarray, Array of segment times. spec (Sxx) : ndarray, Spectrogram of x. By default, the last axis of Sxx corresponds to the segment times. Alternatively, you can check the train.py and models.py code on github repo from the Tensorflow example on audio recognition. Here is another thread that explains and gives code on building spectrograms in Python.

http://stackoverflow.com/comment/82867391
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47948691
has text: Another option would be to use the IUS packages for Python, however IUS does not ship Ruby so you would have similar problems there with either using SCL or being stuck with the 2.0 distro package.
type: Comment

spacy
tags question: http://stackoverflow.com/q/47899616
tags question: http://stackoverflow.com/q/47956625
tags question: http://stackoverflow.com/q/47856247
tags question: http://stackoverflow.com/q/47874306
tag name: spacy
tags question: http://stackoverflow.com/q/48002970
type: Tag
tags question: http://stackoverflow.com/q/48014298
tags question: http://stackoverflow.com/q/47862971
tags question: http://stackoverflow.com/q/47983900

http://stackoverflow.com/q/47907967
favorite count: 0
tagged with: datetime
tagged with: python
accepted answer: http://stackoverflow.com/a/47908146
type: AnsweredQuestion
upvote count: 2
score: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/47908146
tagged with: python-2.7
tagged with: pandas
answer count: 1
tagged with: timedelta
has title: Pandas Timedelta is negative where it should be positive, how to overcome the limitations
has body: I want to calculate difference between the day smth was mentioned and the day it was published. So I have the next DataFrame df_test= pd.DataFrame([{'Mention Date': pd.Timestamp('2015-09-17 12:47:06'), 'Publication Date': pd.Timestamp('1684-01-01 00:00:00')}, {'Mention Date': pd.Timestamp('2015-09-17 12:47:06'), 'Publication Date': pd.Timestamp('2013-01-01 00:00:00')}, {'Mention Date': pd.Timestamp('2015-09-17 12:47:06'), 'Publication Date': pd.Timestamp('1724-01-01 00:00:00')}, {'Mention Date': pd.Timestamp('2015-01-01'), 'Publication Date': pd.Timestamp('1722-09-22 00:12:43.1453')}, {'Mention Date': pd.Timestamp('2015-01-01'), 'Publication Date': pd.Timestamp('1722-09-22 00:00:00')}]) Now I want to calculate the difference between "Mention Date" and "Publication Date". print df_test["Mention Date"] - df_test["Publication Date"] 0 -92350 days +13:12:32.290448 1 989 days 12:47:06 2 106545 days 12:47:06 3 106751 days 23:47:16.854700 4 -106752 days +00:25:26.290448 dtype: timedelta64[ns] As you can see, the response is wrong for row 0 and 4. The difference should be positive everywhere. If I do difference only value by value then the response is positive. See the code below. print df_test.loc[0]["Mention Date"] - df_test.loc[0]["Publication Date"] print df_test.loc[3]["Mention Date"] - df_test.loc[3]["Publication Date"] print type(df_test.loc[0]["Mention Date"] - df_test.loc[0]["Publication Date"]) 121154 days, 12:47:06 106751 days 23:47:16.854700 &lt;type 'datetime.timedelta'&gt; But the result is then of different type. However, limit is Timestamp('1677-09-21 00:12:43.145225') according to https://pandas.pydata.org/pandas-docs/stable/timeseries.html#timestamp-limitations, it should not be my case. I have 2 questions: How to overcome the "wrong" behavior? Should this be considered a bug in the pandas pd.Timedelta? Or is this rather some 'normal' behavior? Update: I found the limitation for pd.Timedelta https://pandas.pydata.org/pandas-docs/stable/timedeltas.html#time…

http://stackoverflow.com/a/47867618
answers question: http://stackoverflow.com/q/47867468
has comment: http://stackoverflow.com/comment/82700400
score: 0
has body: Assuming that your keys all are single words with the first letter captial: x = userInput.lower() y = x.title() print myDict[y]
has comment: http://stackoverflow.com/comment/82700163
type: Answer
has comment: http://stackoverflow.com/comment/82700427
has comment: http://stackoverflow.com/comment/82700944

http://stackoverflow.com/comment/82813556
comment on: http://stackoverflow.com/q/47919975
score: 0
has text: @RatmirAsanov added
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47940356
accepted answer: http://stackoverflow.com/a/47941118
has body: I met with strange python behavior with this code: #!/usr/bin/python import multiprocessing import time import sys class worker(multiprocessing.Process): def __init__(self, val): super(worker,self).__init__() self.val = val def update_val(self,val): self.val = val print("self.val now is %s" %(self.val)) def run(self): while True: print("Worker report: val is %s" % (self.val)) time.sleep(self.val) subproc = worker(10) subproc.start() while True: new_val = sys.stdin.readline().rstrip() if new_val: subproc.update_val(new_val) print("Main report: val is %s" % (subproc.val)) I desired, that variable val in object subproc was be changed by update_val function. But I was surprised, because that variable was changed only for queries from main process. Function run was still use old value: $ ./test.py Worker report: val is 10 Worker report: val is 10 5 self.val now is 5 Main report: val is 5 Main report: val is 5 Worker report: val is 10 Worker report: val is 10 What can be a problem cause? This code works similar in Python2.7 and Python3.6. Thanks in advance!
tagged with: class
possible better answer: http://stackoverflow.com/a/47940516
score: 0
has answer: http://stackoverflow.com/a/47941118
answer count: 3
has answer: http://stackoverflow.com/a/47940516
has answer: http://stackoverflow.com/a/47958939
has title: python multiprocessing class
tagged with: python
type: AnsweredQuestion
tagged with: python-multiprocessing
type: Question

http://stackoverflow.com/a/47952562
downvote count: 0
has comment: http://stackoverflow.com/comment/82878180
type: Answer
has body: I suggest you to use a grammar check before you post the question. Cool. So, as we can see the code, it is a very small scraping code. You need to follow this before running the code. There are three libraries you need to run the code. Selenium pip install -U selenium. BeautifulSoup pip install -U bs4 Lxml pip install -U lxml Then download the chrome driver from https://sites.google.com/a/chromium.org/chromedriver/ Then run the code by python code.py P.S. I hope you have Python in your system.
answers question: http://stackoverflow.com/q/47952518
score: 1
upvote count: 1

http://stackoverflow.com/comment/82978581
comment on: http://stackoverflow.com/a/47992680
score: 0
has text: Its not working when B=[[1,2,1],[2,1,2],[1,1,3]],when elements of B are different from each other.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82705814
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47859784
has text: Thanks a lot @MartinEvans couldn't done it without you! :D
type: AnswerComment

http://stackoverflow.com/comment/82688603
score: 0
type: Comment
type: QuestionComment
has text: You code does not work like this. `data` is not defined.
comment on: http://stackoverflow.com/q/47861821

http://stackoverflow.com/comment/82970382
has text: I don't know what to do tbh. I used the code you wrote but it gives back the same error than before.
comment on: http://stackoverflow.com/a/48000737
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/47939588
answer count: 0
type: UnansweredQuestion
score: 0
has title: Iterate through colors with cycle for each new line which gets plotted
has comment: http://stackoverflow.com/comment/82848911
tagged with: matplotlib
duplicate of: http://stackoverflow.com/q/4805048
type: Question
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/82848892
has body: I have the following code: filenames=sorted((glob.glob('G*_5.csv'))) cycol=cycle('bgrcmky').next for fname in ((glob.glob('G*_5.csv'))): data=np.loadtxt(fname, delimiter=",") X=data[:,1] Y=data[:,0] n=fname.split('_') plt.plot(X,Y, c=cycol(), linestyle='--', label=n[0], linewidth=3.0 ) plt.title("Damage Patterns 5'") plt.xlabel("Base") plt.ylabel("%") plt.legend(loc='upper right') plt.xticks([1, 2, 3, 4, 5]) plt.ylim((0,50)) plt.show() Which gives the following output: which is fine but I have one problem with the colors since in the cycle('bgrcmky') I only specified seven colors. But I need ten different ones or more. I landed on this site matplotlib colors where different ways are stated to specify the color. So I tried some of those methods like: cycol=cycle(["(0.1, 0.2, 0.5)", "(0.1, 0.2, 0.5, 0.3)"]).next or cycol=cycle(["xkcd:sky blue", "xkcd:orange"]).next but these are not working. So is there any way to upgrade the method I used with the cycle to get more then seven colors? Thanks in advance :)
has comment: http://stackoverflow.com/comment/82848879
tagged with: python
has comment: http://stackoverflow.com/comment/82848580

http://stackoverflow.com/a/47969892
type: Answer
score: 2
has body: The other 2 answers explained what happens. Although I want to offer you another representation that will help you have a better understanding. I took a snapshot from this documentation page about heapq. First of all, you can see that PriorityQueue uses a heappop here Now, to the image. heappop In this image, when you pop the first item 0 (job1), 1 ('job2') will take its place, and then, 3 (job4) will take 1 (job2) place. We should conclude by saying this is a normal behaviour.
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/47969623

http://stackoverflow.com/a/47859818
type: Answer
answers question: http://stackoverflow.com/q/47859723
upvote count: 3
score: 3
has body: Is that what you want? In [236]: x = corr.dropna() In [237]: x.loc[pd.IndexSlice[x.index[0][0], :], :] Out[237]: bar A B foo bar 2016-01-12 A 1.000000 0.158424 B 0.158424 1.000000
downvote count: 0

http://stackoverflow.com/q/47894191
has answer: http://stackoverflow.com/a/48828449
score: 27
upvote count: 27
answer count: 2
tagged with: communication
downvote count: 0
has comment: http://stackoverflow.com/comment/82820231
has comment: http://stackoverflow.com/comment/82775487
has title: Performance discrepancy between OSX and Linux for communication using Python multiprocessing
favorite count: 0
has comment: http://stackoverflow.com/comment/83556104
tagged with: linux
possible better answer: http://stackoverflow.com/a/48828449
tagged with: python
linked to: http://stackoverflow.com/q/44747145
has body: I have been trying to learn more about Python's multiprocessing module and to evaluate different techniques for communication between processes. I wrote a benchmark that compares the performance of Pipe, Queue, and Array (all from multiprocessing) for transferring numpy arrays between processes. The full benchmark can be found here. Here's a snippet of the test for Queue: def process_with_queue(input_queue, output_queue): source = input_queue.get() dest = source**2 output_queue.put(dest) def test_with_queue(size): source = np.random.random(size) input_queue = Queue() output_queue = Queue() p = Process(target=process_with_queue, args=(input_queue, output_queue)) start = timer() p.start() input_queue.put(source) result = output_queue.get() end = timer() np.testing.assert_allclose(source**2, result) return end - start I ran this test on my Linux laptop and got the following results for an array size of 1000000: Using mp.Array: time for 20 iters: total=2.4869s, avg=0.12435s Using mp.Queue: time for 20 iters: total=0.6583s, avg=0.032915s Using mp.Pipe: time for 20 iters: total=0.63691s, avg=0.031845s I was a little surprised to see Array perform so poorly since it uses shared memory and presumably doesn't require pickling, but I assume there must be some copying in numpy that I can't control. However, I ran the same test (again for array size 1000000) on a Macbook, and got the following results: Using mp.Array: time for 20 iters: total=1.6917s, avg=0.084587s Using mp.Queue: time for 20 iters: total=2.3478s, avg=0.11739s Using mp.Pipe: time for 20 iters: total=8.7709s, avg=0.43855s The real timing differences aren't that surprising since of course different systems would exhibit different performance. What is so surprising are the differences in relative timing. What could account for this? This is a pretty surprising result to me. I wouldn't be surprised to see such stark differences between Linux and Windows, or OSX and Windows, but I sort of assumed that these things w…
tagged with: macos
accepted answer: http://stackoverflow.com/a/53249844
has comment: http://stackoverflow.com/comment/83580558
has comment: http://stackoverflow.com/comment/84390069
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82783119
has answer: http://stackoverflow.com/a/53249844
tagged with: multiprocessing
type: Question
linked to: http://stackoverflow.com/q/1289813
has comment: http://stackoverflow.com/comment/83090868
has comment: http://stackoverflow.com/comment/83556045

http://stackoverflow.com/comment/83003135
has text: Ah, yes `'Reindexing only valid with uniquely'`. Only works for unique indices.
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48005487

http://stackoverflow.com/q/47933565
has comment: http://stackoverflow.com/comment/82836485
tagged with: python
has comment: http://stackoverflow.com/comment/82836533
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47933777
type: Question
has comment: http://stackoverflow.com/comment/82836483
has comment: http://stackoverflow.com/comment/82836605
upvote count: 5
tagged with: http://stackoverflow.com/tag/json
tagged with: boto3
has body: In my project i have to create a py that call a lambda function passing body parameters, i write this code: import boto3 import json import base64 client = boto3.client(‘lambda’) d = {'calID': '92dqiss5bg87etcqeeamlmob2g@group.calendar.google.com', 'datada': '2017-12-22T16:40:00+01:00', 'dataa': '2017-12-22T17:55:00+01:00', 'email': 'example@hotmail.com'} s = json.dump(d) s64 = base64.b64encode(s.encode('utf-8')) response = client.invoke( FunctionName='arn:aws:lambda:eu-west-1:13737373737:function:test', InvocationType='RequestResponse', LogType='None', ClientContext='None', Payload=s64 ) but when response run this error is generated: InvalidRequestContentException: An error occurred (InvalidRequestContentException) when calling the Invoke operation: Could not parse request body into json: Unrecognized token '[binary]': was expecting ('true', 'false' or 'null') at [Source: [B@4587098d; line: 1, column: 481] what this mean? Many thanks in advance
score: 5
has title: Python call my AWS lambda from code with boto3 error
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/47933777
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/82836427
tagged with: aws-lambda
favorite count: 0
has comment: http://stackoverflow.com/comment/82836589
has comment: http://stackoverflow.com/comment/82836458

http://stackoverflow.com/comment/82816902
has text: This sounds like it might be a buffering issue. Does adding `sys.stdout.flush()` as the very last line of `example.py` make a difference? I was able to mock up something that reproduced this behaviour with named pipes in Linux, and flushing solved the problem.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47910189
score: 0

http://stackoverflow.com/comment/82681181
has text: _a simple chat application_: you have not exactly over-specified your application.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47858129
type: QuestionComment

http://stackoverflow.com/a/47989128
has comment: http://stackoverflow.com/comment/82946824
has comment: http://stackoverflow.com/comment/82973583
answers question: http://stackoverflow.com/q/47989021
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/82947028
has comment: http://stackoverflow.com/comment/82974241
has comment: http://stackoverflow.com/comment/82946838
downvote count: 0
score: 1
has body: Try this sudo yum install python26 or sudo yum --enablerepo=epel install python26 or see this stackover post

http://stackoverflow.com/a/48013322
score: 2
answers question: http://stackoverflow.com/q/48013114
upvote count: 2
has body: Sounds like your list, when turned into an array, doesn't have the right number of dimensions. Let me illustrate: In [323]: arr = np.arange(12).reshape(3,4) In [324]: alist = list(range(3)) In [325]: np.concatenate((arr,alist)) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-325-9b72583c40de&gt; in &lt;module&gt;() ----&gt; 1 np.concatenate((arr,alist)) ValueError: all the input arrays must have same number of dimensions In [326]: arr.shape Out[326]: (3, 4) concatenate turns any list inputs into arrays: In [327]: np.array(alist).shape Out[327]: (3,) arr is 2d, so this array needs to be 2d as well: In [328]: np.array(alist)[:,None].shape Out[328]: (3, 1) In [329]: np.concatenate((arr, np.array(alist)[:,None]), axis=1) Out[329]: array([[ 0, 1, 2, 3, 0], [ 4, 5, 6, 7, 1], [ 8, 9, 10, 11, 2]]) It is easy to concatenate a (3,4) array with a (3,1) array on the last dimension. I get the impression that a lot of people are jumping into machine learning code (tensorflow, keras, sklearn) without understanding some of the basics of numpy arrays, such as shape and dimensions.
has comment: http://stackoverflow.com/comment/84351085
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48013114

http://stackoverflow.com/q/47969616
has answer: http://stackoverflow.com/a/47970058
favorite count: 0
has answer: http://stackoverflow.com/a/47969726
tagged with: python
accepted answer: http://stackoverflow.com/a/47969726
answer count: 4
type: AnsweredQuestion
tagged with: list
has body: I have a list of lists like this:- x=[['A','B','C','D'],['E','F','G','H']] I am trying to add an index to the list like this:- y=[[0,'A','B','C','D'],[1,'E','F','G','H']] Is there any way to achieve this?
upvote count: 2
has title: Adding an index to a list of a lists in python
possible better answer: http://stackoverflow.com/a/47969621
has answer: http://stackoverflow.com/a/47969621
type: Question
has answer: http://stackoverflow.com/a/47969664
score: 2
downvote count: 0

http://stackoverflow.com/a/69670473
upvote count: 5
has body: Your problem is not in code or anything is that the Selenium community stopped supporting PhantomJS in the new version, so every time you try to pull the PhatomJs lib it doesn't exist. In the documentation it says that they currently support https://www.selenium.dev/selenium/docs/api/py/api.html
score: 4
type: Answer
answers question: http://stackoverflow.com/q/47980410
downvote count: 1

setup.py
tags question: http://stackoverflow.com/q/47941418
tag name: setup.py
type: Tag

http://stackoverflow.com/comment/82777766
type: QuestionComment
type: Comment
has text: @IMCoins can you suggest any librabry apart from openpyxl, xlwtwriter
comment on: http://stackoverflow.com/q/47905053
score: 0

http://stackoverflow.com/q/47905078
has comment: http://stackoverflow.com/comment/82776960
has title: python3 list comprehension using a dictionary doesn't always return the same list
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47908824
type: Question
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/82776946
has comment: http://stackoverflow.com/comment/82777030
has comment: http://stackoverflow.com/comment/82779713
has comment: http://stackoverflow.com/comment/82777023
has body: EDIT: As requested, here is the problem I am trying to solve: I have files in a directory that do not have extensions. Based on the output of the "file" command I want to assign the corresponding extension. So my dictionary is assigning strings that can be in this output, to the extensions (eg "ASCII": "txt") but can't know if it will be the exact output. For example : $ file my_file myfile: ASCII text # I want to change the extension of myfile to myfile.txt That is what the code I wrote was designed to do, but maybe there are better solutions I have a dictionnary of strings with keys that have common strings : MY_D = { "first_k": "first_v", "sec_k": "sec_v", "some_key_name_that_includes_others": "value1", "some_other_key": "value2", ... "last_k": "last_v" } Sometimes, I have to fetch a value, if the search word is within the key. I use this code: key_I_am_looking_for = "some" value = list(v for k, v in MY_D.items() if value_I_am_looking_for in k)[-1] But when the key I am looking for appears in multiple possible keys, the value I get is not always the same, in this example it can be either "value1" or "value2". I noticed the list returned, is not always ordered the same way. Is there a way I can make this return always the value that corresponds to the longest key matched (here would be "value1")?
answer count: 2
has answer: http://stackoverflow.com/a/47907524
favorite count: 0
upvote count: 3
downvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82778284
has comment: http://stackoverflow.com/comment/82777002
has comment: http://stackoverflow.com/comment/82777020
score: 2
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82778403

http://stackoverflow.com/comment/98760346
type: Comment
comment on: http://stackoverflow.com/a/50484745
score: 5
type: AnswerComment
has text: `validation_split` doesn't exist as a parameter with `fit_generator`.

http://stackoverflow.com/q/47972522
has answer: http://stackoverflow.com/a/47978083
upvote count: 2
tagged with: google-app-engine
tagged with: pip
tagged with: python
accepted answer: http://stackoverflow.com/a/49845803
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/16584552
has comment: http://stackoverflow.com/comment/82914732
has title: How to use a Python library with no pip install on AWS Elastic Beanstalk or Google App Engine?
type: Question
has body: I have a Flask web service using a Python library PyDDE, which is distributed on PyPI but somehow can't be pip installed. I can install this library on my local environment using pip install git+https://github.com/hensing/PyDDE.git or clone and install setup.py. But when I tried to upload and build the project on either AWS Elastic Beanstalk or Google App Engine Flexible Environment, this becomes an issue that they can't find a matching distribution of this library. Is there any workaround to solve this issue? Here is the error message from GAE Flexible: Step #1: Could not find a version that satisfies the requirement PyDDE (from -r requirements.txt (li ne 7)) (from versions: ) Step #1: No matching distribution found for PyDDE (from -r requirements.txt (line 7)) Step #1: The command '/bin/sh -c pip install -r requirements.txt' returned a non-zero code: 1 Finished Step #1 ERROR ERROR: build step "gcr.io/cloud-builders/docker@sha256:331786b295647a4560ed004a46761ee91409e754df7ffa7 54a67000bd020729a" failed: exit status 1 Step #1: ------------------------------------------------------------------------------------------------------ ERROR: (gcloud.app.deploy) Cloud build failed. Check logs at https://console.cloud.google.com/gcr/buil ds/6ace1019-8bf5-434b-b916-5c6cae84de9f?project=project-190120 Failure status: UNKNOWN: Err or Response: [2] Build failed; check build logs for details And here is my requirements.txt: Flask==0.12.2 Werkzeug==0.12.2 gunicorn==19.7.1 pandas&gt;0.20.0 numpy&gt;1.13.0 scipy&gt;0.19.0 PyDDE google-api-python-client UPDATE: I added this line in requirements.txt: -e git+git://github.com/hensing/PyDDE.git#egg=PyDDE And it works for GAE. Thank you @hansaplast !! However, AWS Elastic Beanstalk doesn't accept this requirements.txt. It throws this error: INFO: Created CloudWatch alarm named: awseb-e-3tu2ajdxug-stack-AWSEBCloudwatchAlarmLow-8NOPISSRAAEH ERROR: Your requirements.txt is invalid. Snapshot your logs for details. ERROR: [Instance: i-03e92fa3…
downvote count: 0
has comment: http://stackoverflow.com/comment/82914868
tagged with: amazon-web-services
favorite count: 0
has comment: http://stackoverflow.com/comment/82914878
answer count: 3
has answer: http://stackoverflow.com/a/47972654
tagged with: amazon-elastic-beanstalk
possible better answer: http://stackoverflow.com/a/47972654
has answer: http://stackoverflow.com/a/49845803

http://stackoverflow.com/q/47978213
has answer: http://stackoverflow.com/a/47978607
upvote count: 1
tagged with: python
has title: Unable to extract a desired portion of text and discard the rest out of some elements
type: AnsweredQuestion
score: 1
type: Question
accepted answer: http://stackoverflow.com/a/47978607
downvote count: 0
answer count: 1
has body: I've used a selector within my python code to get Soccer: Next To Play out of some html elements. It works fine when I use a for loop and .extract() the unwanted portion. However, is there any better way to get the aforesaid text out of the elements other than what I have done below or at least to do the same with a one-liner expression. from bs4 import BeautifulSoup content=''' Soccer: Next To Play RACE R ''' soup = BeautifulSoup(content,"lxml") for item in soup.select(".page-title-new h1"): for elem in item.select("span"):elem.extract() print(item.text.strip()) # items = [item.text for item in soup.select(".page-title-new h1")] #what to do to finish it as a one-liner # print(items) With the loop what I get (this is what I wish to get without a loop or a one-liner code): Soccer: Next To Play Without the loop what I get: Soccer: Next To Play RACE R
tagged with: css-selectors
favorite count: 0
tagged with: beautifulsoup
tagged with: python-3.x

pyspark
tags question: http://stackoverflow.com/q/47953320
tags question: http://stackoverflow.com/q/47996396
tags question: http://stackoverflow.com/q/47899604
tags question: http://stackoverflow.com/q/47903905
tags question: http://stackoverflow.com/q/47955449
tags question: http://stackoverflow.com/q/47895143
tags question: http://stackoverflow.com/q/47946449
tags question: http://stackoverflow.com/q/48005176
tags question: http://stackoverflow.com/q/47993060
tags question: http://stackoverflow.com/q/47926966
type: Tag
tags question: http://stackoverflow.com/q/47978962
tags question: http://stackoverflow.com/q/47874622
tags question: http://stackoverflow.com/q/47952935
tags question: http://stackoverflow.com/q/47964679
tags question: http://stackoverflow.com/q/47897238
tags question: http://stackoverflow.com/q/47959037
tags question: http://stackoverflow.com/q/47896528
tags question: http://stackoverflow.com/q/47975534
tags question: http://stackoverflow.com/q/48005089
tags question: http://stackoverflow.com/q/47912338
tags question: http://stackoverflow.com/q/47989779
tags question: http://stackoverflow.com/q/47946874
tags question: http://stackoverflow.com/q/48011891
tags question: http://stackoverflow.com/q/47995188
tags question: http://stackoverflow.com/q/47922435
tags question: http://stackoverflow.com/q/47897050
tags question: http://stackoverflow.com/q/48007130
tags question: http://stackoverflow.com/q/48004584
tags question: http://stackoverflow.com/q/47978384
tags question: http://stackoverflow.com/q/47906697
tags question: http://stackoverflow.com/q/47919022
tags question: http://stackoverflow.com/q/47858411
tags question: http://stackoverflow.com/q/47882092
tags question: http://stackoverflow.com/q/47933705
tags question: http://stackoverflow.com/q/48003723
tag name: pyspark
tags question: http://stackoverflow.com/q/47945809
tags question: http://stackoverflow.com/q/47921842
tags question: http://stackoverflow.com/q/47894597
tags question: http://stackoverflow.com/q/47900084
tags question: http://stackoverflow.com/q/47905546
tags question: http://stackoverflow.com/q/47942875
tags question: http://stackoverflow.com/q/47874444

c++11
tags question: http://stackoverflow.com/q/47933692
tags question: http://stackoverflow.com/q/47938772
type: Tag
tag name: c++11

http://stackoverflow.com/q/47892954
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: django
has answer: http://stackoverflow.com/a/47893041
tagged with: python
has title: Django tell if last item with certain attribute in dual ordering (order_by)
has body: In a Django queryset how can I tell if the list item I'm on (when iterating) is the list item that has a certain attribute. Example: I order a queryset by: MyModel.objects.all().order_by('-featured', '-created_at') So, all objects which are featured first by their appropriate time and then all non-featured items sorted by time properly as well. When iterating in the template I want to be able to tell if I've hit the last "featured" item in the dual-ordering (such that featured = True). Example usage: If last item -> display banner separating featured / non-featured -> continue iterating displaying non-featured after banner. {% for object in object_list %} # display object {% if last item with attribute %} # display banner {% endif %} {% endfor %} I know I can do another queryset to get the count, but that's an extra query I'd like to avoid.
type: AnsweredQuestion
tagged with: django-templates
score: 1
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/47893041
tagged with: django-models

http://stackoverflow.com/a/47862289
has body: Maybe you're supposed to brute force the API docs? &gt;&gt;&gt; secret1 = 'qwer-qewr-qwer-qwer' &gt;&gt;&gt; secret2 = 'qwer-qwer-qwer-qwer' &gt;&gt;&gt; message_template = 'key=asdf-asdf-asdf-asdf&amp;nonce={}&amp;coin=btc&amp;id=3' &gt;&gt;&gt; target = '66b2935f3ba82a4a17074d439adab1043a63df4a177af68fe76a3f4f350ef55d' &gt;&gt;&gt; keys = [hashlib.md5(secret1).hexdigest(), hashlib.md5(secret1).digest(), hashlib.md5(secret2).hexdigest(), hashlib.md5(secret2).digest()] &gt;&gt;&gt; &gt;&gt;&gt; for i in range(1505000000, 1506000000): ... msg = message_template.format(i) ... for key in keys: ... if hmac.new(key, msg, hashlib.sha256).hexdigest() == target: ... print 'FOUND hmac', key, msg ... if hashlib.sha256(key + msg).hexdigest() == target: ... print 'FOUND sha256', key, msg ... FOUND hmac fecfe400baa3ae47fe8c42f9c087ec90 key=asdf-asdf-asdf-asdf&amp;nonce=1505209413&amp;coin=btc&amp;id=3 Which corresponds to: &gt;&gt;&gt; keys.index('fecfe400baa3ae47fe8c42f9c087ec90') 0 So the following should work: &gt;&gt;&gt; hmac.new(hashlib.md5('qwer-qewr-qwer-qwer').hexdigest(), 'key=asdf-asdf-asdf-asdf&amp;nonce=1505209413&amp;coin=btc&amp;id=3', hashlib.sha256).hexdigest() '66b2935f3ba82a4a17074d439adab1043a63df4a177af68fe76a3f4f350ef55d' Looks like you were doing the right thing, but their nonce changed, and the qwer-qewr-qwer-qwer private key is correct.
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47861874
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47861874

http://stackoverflow.com/a/47931123
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/47896378
upvote count: 1
answers question: http://stackoverflow.com/q/47896378
has body: I'm not sure I see much practical difference. In either case the local counters are created in the parameter service device scope, so they'll live on the parameter server. In Version 1 each worker's graph contains only its local counter, whereas each worker's graph contains all of the local counters in Version 2 (but the workers still only interact with their own counters, and the variables themselves still live on the parameter server). So to answer explicitly, yes you can store variables which don't exist in the parameter server's graph on the parameter server. Basically there's a hash table on the parameter server (the ResourceMgr) which can store arbitrary variable names/values. To automatically put variables on parameter server(s), tf.train.replica_device_setter can help reduce boilerplate.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82872021

http://stackoverflow.com/comment/82680953
has text: Why didn't you just kill the program? Anyway, you're basically asking to do something fairly compute- and memory- intensive. Yes, it can make your computer unhappy but shouldn't crash anything.
score: 1
comment on: http://stackoverflow.com/q/47858187
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82737452
score: 0
comment on: http://stackoverflow.com/q/47873616
type: QuestionComment
type: Comment
has text: Big thanks to all of you, guys, for a clarification.

http://stackoverflow.com/comment/82993726
has text: @DylanF I added a second way to enable accessing the keys/attributes both through `dir()` and `vars()`.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48001538

http://stackoverflow.com/q/47919423
tagged with: python
has comment: http://stackoverflow.com/comment/82807116
score: 1
tagged with: http://stackoverflow.com/tag/json
upvote count: 1
type: Question
tagged with: numpy
tagged with: hadoop
has body: I have a big 17 GB JSON file placed in hdfs . I need to read that file and convert into nummy array which is then passed into K-Means clustering algorithm. I tried many ways but system slows down and getting a memory error or kernel dies. the code i tried is from hdfs3 import HDFileSystem import pandas as pd import numpy as nm import json hdfs = HDFileSystem(host='hostname', port=8020) with hdfs.open('/user/iot_all_valid.json/') as f: for line in f: data = json.loads(line) df = pd.DataFrame(data) dataset= nm.array(df) I tried using ijson but still not sure which is the right way to do this in faster way.
has answer: http://stackoverflow.com/a/47919575
has answer: http://stackoverflow.com/a/47926530
has answer: http://stackoverflow.com/a/47919680
answer count: 3
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/82806504
has comment: http://stackoverflow.com/comment/82806433
has comment: http://stackoverflow.com/comment/82807204
favorite count: 0
type: UnansweredQuestion
has title: Convert 17GB JSON file to a numpy array

http://stackoverflow.com/q/48004691
has title: how to sort a csv file by two columns in python?
tagged with: python
answer count: 4
favorite count: 0
upvote count: 5
downvote count: 0
has body: I have a csv file that contains 6 columns. I want to sort it by col #2 and then by col #3. My current code is creating a blank file: import csv with open('original.csv', mode='rt') as f, open('sorted.csv', 'w') as final: writer = csv.writer(final, delimiter='\t') reader = csv.reader(f, delimiter=',') _ = next(reader) sorted1 = sorted(reader, key=lambda row: int(row[1])) sorted2 = sorted(reader, key=lambda row: int(row[2])) for row in sorted2: writer.writerow(row) What am I doing wrong?
has answer: http://stackoverflow.com/a/48004801
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48004886
has answer: http://stackoverflow.com/a/48004929
accepted answer: http://stackoverflow.com/a/48004929
type: Question
has answer: http://stackoverflow.com/a/48004853
score: 5
has comment: http://stackoverflow.com/comment/82977891
possible better answer: http://stackoverflow.com/a/48004801
has comment: http://stackoverflow.com/comment/82977932
has comment: http://stackoverflow.com/comment/82977811
has comment: http://stackoverflow.com/comment/82977863

http://stackoverflow.com/comment/82930846
type: QuestionComment
comment on: http://stackoverflow.com/q/47981207
score: 1
has text: use try except?
type: Comment

http://stackoverflow.com/comment/82832497
type: QuestionComment
comment on: http://stackoverflow.com/q/47931534
score: 0
has text: @kjhughes question updated
type: Comment

http://stackoverflow.com/q/47966082
tagged with: web-applications
tagged with: video-embedding
type: Question
has answer: http://stackoverflow.com/a/47966113
answer count: 2
score: 0
has body: I have a Django site that I want to add videos. Currently users can upload their photos and I want each user to be able to add their videos as well. I am not sure how to do this, since I am a beginner programmer. Can you please direct me to right way?
has title: Video embedding
possible better answer: http://stackoverflow.com/a/47966113
has answer: http://stackoverflow.com/a/47990584
accepted answer: http://stackoverflow.com/a/47990584
tagged with: django
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/47970983
has title: how to enable memory profiler only when testing in python?
tagged with: python
has answer: http://stackoverflow.com/a/47971072
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
tagged with: memory-profiling
tagged with: testing
has body: I am using memory_profiler in python and profiling some piece of code. But I only want that to enable when testing is happening, like the function is being invoked from a test-suite. I don't want the profiler being enabled when code is running in production. Is there any way to do that? I am open to generic suggestion like "how to enable decorators only when the testing is happening?". Example code - from memory_profiler import profile @profile(precision=4) def my_func(): a = [1] * (10 ** 6) b = [2] * (2 * 10 ** 7) del b return a
upvote count: 1
answer count: 1
tagged with: decorator
favorite count: 0
accepted answer: http://stackoverflow.com/a/47971072
tagged with: python-3.x

http://stackoverflow.com/a/74622968
type: Answer
score: 2
downvote count: 0
has body: I'm a bit late to the party, but nowadays there a number of out of the box options for setting up SpaCy as an API, as described by alvas which do the trick rather nicely. eg. https://github.com/microsoft/cookiecutter-spacy-fastapi
upvote count: 2
answers question: http://stackoverflow.com/q/48014298

http://stackoverflow.com/a/47891137
type: AcceptedAnswer
downvote count: 0
has body: Using defaultdict: &gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; d = defaultdict(lambda: [0,0], list()) &gt;&gt;&gt; for a,b,c in sample: d[a][0]+=b d[a][1]+=c #driver values : IN : sample = [['no',2, 6], ['ja',5,7], ['no',4,9], ['ja',10,11], ['ap',7,12]] OUT : d = defaultdict(&lt;function &lt;lambda&gt; at 0x7f4349f17620&gt;, {'no': [6, 15], 'ja': [15, 18], 'ap': [7, 12]}) Since the output is structured as such, I would suggest you utilise the dict type for storing your output as future processing with it will be easier. In case you still want the output as a list, just map the dict, as follows: &gt;&gt;&gt; [ [key]+ele for key,ele in d.items()] =&gt; [['no', 6, 15], ['ja', 15, 18], ['ap', 7, 12]]
type: Answer
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/47891051
answers question: http://stackoverflow.com/q/47891051

http://stackoverflow.com/comment/82778859
type: QuestionComment
has text: I expect the resulted file name to look like 2017-12-20 12:26:55.png
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47906007

http://stackoverflow.com/a/47867849
answers question: http://stackoverflow.com/q/47867758
has body: &lt;tr&gt; {% for val in response_data %} &lt;td&gt;{{val.name}}&lt;/td&gt; {% endfor %} &lt;/tr&gt; This is a simple way to loop the data and display it in table
score: 0
type: Answer

http://stackoverflow.com/a/47876761
has comment: http://stackoverflow.com/comment/94016690
has comment: http://stackoverflow.com/comment/94019044
has comment: http://stackoverflow.com/comment/125603257
score: 13
has comment: http://stackoverflow.com/comment/93994194
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47876663
has comment: http://stackoverflow.com/comment/125615335
has comment: http://stackoverflow.com/comment/93995454
type: Answer
answers question: http://stackoverflow.com/q/47876663
upvote count: 13
has body: You could do it like this using transform to get sum with like indexes of oringal dataframe then use div with Pandas intrinsic data alignment: df.div(df.groupby(['foo','bar']).transform('sum')) Output: value foo bar baz 1 A C 0.750000 D 0.250000 B D 0.600000 F 0.400000 2 B C 0.416667 F 0.583333

http://stackoverflow.com/comment/82951176
comment on: http://stackoverflow.com/q/47990341
has text: Do you have frames on your page?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47910907
tagged with: django
tagged with: unit-testing
type: AnsweredQuestion
has title: Unit test in Django: using self.assertIn() to find text in key/value pair
type: Question
upvote count: 2
has body: I'm trying to write a unit test for my Django app using self.assertIn() This is my unit test: def test_user_get_apps_meta(self): myuser = User.objects.get(email='theemail@gmail.com') tagline = 'the text' self.assertIn(tagline, myuser.get_apps()) The result of myuser.get_apps() is a list of dictionaries. In one of those dictionaries is indeed the tagline text I'm looking for: 'the text' But I'm getting an error when I run the test: self.assertIn(tagline, myuser.get_apps()) AssertionError: 'the text' not found in [{'logo_app_alt': 'the text', '...},{},{}] Am I not using self.assertIn() correctly? Is there a way to check if certain text is the value of a key/value pair in a dictionary?
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/47911166
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/47911166
score: 2
downvote count: 0

http://stackoverflow.com/a/47992085
has body: you can use transform method: In [23]: df['diff'] = df.groupby('customer_id') \ ['action_date'] \ .transform(lambda x: (x.max()-x.min()).days) In [24]: df Out[24]: action_date customer_id diff 0 2017-08-15 1 18 1 2017-08-21 1 18 2 2017-08-21 1 18 3 2017-09-02 1 18 4 2017-08-28 2 32 5 2017-09-29 2 32 6 2017-10-15 3 51 7 2017-10-30 3 51 8 2017-12-05 3 51
score: 16
accepted answer of: http://stackoverflow.com/q/47991907
has comment: http://stackoverflow.com/comment/121755186
answers question: http://stackoverflow.com/q/47991907
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/115444819
has comment: http://stackoverflow.com/comment/82953039
type: Answer
upvote count: 16

http://stackoverflow.com/comment/82773508
type: Comment
type: QuestionComment
has text: Thanks Furas , your assessment is correct.
score: 0
comment on: http://stackoverflow.com/q/47888559

http://stackoverflow.com/a/47867270
score: 1
has body: That is awfully inefficient: you build the initial list one element at a time when a list comprehension would do it in one single operation: cupcake = i for i in range(1, 101) or even cupcake = list(range(1, 101)) you use the anti-pattern remove + insert to change the value of an element of the list: cupcake[0] = 0 and later in the code cupcake[k] = 0 you loop from the begining for j and k, when the second loop could start at j+1 you (wrongly) use division when you should use modulo And your real problem is that in Python 3, the division of two integers is always a float whether one is or is not a multiple of the other: &gt;&gt;&gt; 4 / 2 2.0 &gt;&gt;&gt; type(4/2) float So your code could become: def main(): cupcake = list(range(1, 101)) cupcake[0] = 0 for j in range(len(cupcake)): if cupcake[j] &gt; 0: for k in range(j+1, len(cupcake)): if cupcake[k] &gt; 0: if cupcake[k] % cupcake[j] == 0: cupcake[k] = 0 print(cupcake) Anyway, the correct algo is to remove multiples instead of consistently testing divisibility: def main(): cupcake = list(range(1, 101)) cupcake[0] = 0 for j in range(len(cupcake)): if cupcake[j] &gt; 0: for k in range(j + cupcake[j], len(cupcake), cupcake[j]): cupcake[k] = 0 print(cupcake)
upvote count: 1
answers question: http://stackoverflow.com/q/47866737
has comment: http://stackoverflow.com/comment/82699992
type: Answer
downvote count: 0

http://stackoverflow.com/comment/82771888
type: QuestionComment
has text: I've added the requests part that is rather obvious. But something is amiss. Something about the custom boundary.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47896933

http://stackoverflow.com/comment/82938842
type: QuestionComment
comment on: http://stackoverflow.com/q/47984934
has text: What are your exact errors?
score: 0
type: Comment

http://stackoverflow.com/comment/82843955
comment on: http://stackoverflow.com/q/47932656
type: QuestionComment
has text: @Blender yeah, thats what im doing right now. like i said before, i'm just curious actually
score: 0
type: Comment

http://stackoverflow.com/q/47968706
type: AnsweredQuestion
score: 1
tagged with: bokeh
has body: I have a figure with multiple plots on it. I would like to make the rectangles on it links. The docs of something similar makes all the plots links, however i would just like the rectangles to be links. I tried a lot of thinks with js_on_event, costum_js_on_tap etc... Example try: ... plot.line([1, seq_len], [-0.2, -0.2], color="black") callback = OpenURL(url="google.com") a = plot.rect(1, 1, 100, 1) a.js_on_event('tap', callback) ...
has answer: http://stackoverflow.com/a/48034376
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/48034376
has title: Python Bokeh make part of the plot a link
tagged with: python-3.x
upvote count: 1
type: Question

http://stackoverflow.com/q/47902702
score: -2
has title: How to copy certain strings from txt file to Word doc using Python?
has comment: http://stackoverflow.com/comment/82772706
downvote count: 3
upvote count: 1
answer count: 1
tagged with: ms-word
favorite count: 0
has answer: http://stackoverflow.com/a/47903200
accepted answer: http://stackoverflow.com/a/47903200
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82772175
has body: I want to copy a word or string from txt file to word file at a certain block of table! can someone guide me how to do it? Best Regards, Usman
type: Question

http://stackoverflow.com/q/47955427
has title: Removing '\n' character from print statement
accepted answer: http://stackoverflow.com/a/47955439
type: Question
score: 0
answer count: 2
tagged with: file-io
tagged with: python
has body: I have the following code when writing to a text file: def writequiz(quizname,grade,perscore,score,username): details=[quizname,username,grade,perscore,score] with open('quizdb','a') as userquiz: print(details,file=userquiz) Now the code is doing what I want it to (writing to a new line every time), however if I wanted to write every list to the same line in the text file how would I do this using the print method as used above? I know I could use file.write, but how do I remove the newline character in the print statement? Slightly hypothetical but it was bugging me.
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47955439
possible better answer: http://stackoverflow.com/a/47955458
has answer: http://stackoverflow.com/a/47955458

http://stackoverflow.com/q/47999547
has comment: http://stackoverflow.com/comment/82967806
tagged with: recursion
type: AnsweredQuestion
tagged with: list
linked to: http://stackoverflow.com/q/18713321
has title: Recursive formula inside a for loop
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/47999690
upvote count: 0
has comment: http://stackoverflow.com/comment/82967668
has comment: http://stackoverflow.com/comment/82967787
score: -1
answer count: 1
has body: I need to implement a recursive formula in my code block which is bayesian_prices = [] for i in range(10): q = dayqvalue(i, grid, fullData) w = compute_dayweights(q) option_data, index_prices, initial_date = get_samedated_opt(fullData, i, 1) callput, tmt, ex, mkt = orderdata(option_data) baypr = compute_bayesian_prices(w, grid, callput, tmt, ex, index_prices) bayesian_prices.append(baypr) What I need to do regards the computation of "q". Everytime I need to compute the q as sum of the old value and the new value obtained from the function "dayqvalue". In other words, when i=0 the first list of q values is computed. Then with i=1 I should have a list which is the sum of q computed at 0 and q computed at 1 and so on. The last time that the for loop runs, I should have a list of q which is the sum of all the precedeing lists plus the new one. Is there a simple way to implement it? The list q contains about a thousand elements. EDIT q is a list of 1000 elements. Everytime I should add entry by entry a new list of 1000 elements to the previous one. For instance, assume to have qcomputed when i=0 and when i=1. I would obtain newq = [q_0[0] + q_1[0] , q_0[1] + q_1[1]] in the first 2 entry. The list newq should be of the same lenght of q_0 and q_1. It should contain the sum of their values entry by entry.
favorite count: 0
has comment: http://stackoverflow.com/comment/82967635
has answer: http://stackoverflow.com/a/47999690
has comment: http://stackoverflow.com/comment/82967619
tagged with: python

http://stackoverflow.com/comment/82922979
type: QuestionComment
has text: It would be safe to use python 3.0
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47976524

http://stackoverflow.com/comment/82891960
score: 0
type: Comment
type: QuestionComment
has text: Does `obj.nucleotide` implicitly use standard output? Otherwise, it's not clear how `fout` gets used at all.
comment on: http://stackoverflow.com/q/47961341

http://stackoverflow.com/comment/82816741
has text: I've added further clarification in response to your helpful expressions of bafflement.
comment on: http://stackoverflow.com/q/47922274
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/82741303
type: QuestionComment
comment on: http://stackoverflow.com/q/47884199
score: 2
has text: Do you mind to share you pc specs, the output of `df.npartitions` and `df.known_divisions` I ran your same code in dask using `from dask.multiprocessing import get` and writing `.compute(get=get)` for a similar dataframe (just a 30gb one instead of 100gb) and the elapsed time was 5 minutes.
type: Comment

http://stackoverflow.com/a/47983993
has comment: http://stackoverflow.com/comment/82937255
has comment: http://stackoverflow.com/comment/82937320
has comment: http://stackoverflow.com/comment/82937246
has comment: http://stackoverflow.com/comment/82937165
type: Answer
has comment: http://stackoverflow.com/comment/82937082
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/82937365
has comment: http://stackoverflow.com/comment/82937190
answers question: http://stackoverflow.com/q/47983734
has body: Okay so you have 500.000 items where a number maps to a five-digit string: Let's put that to the test def five(i): """turns a number into an at least five-digit string""" s = hex(s).replace('0x', '') return '0' * (5 - len(s)) + s # 500k items, no duplication d = {} for i in range(500000): d[i] = five(i) # see https://code.activestate.com/recipes/577504/ total_size(d, verbose=False) / 1024 / 1024 # =&gt; 33.8720645904541 (megabytes) That's nothing, really. Use a dict.
upvote count: 3
accepted answer of: http://stackoverflow.com/q/47983734
type: AcceptedAnswer

http://stackoverflow.com/comment/82935097
has text: That seems to be exactly what I needed! Thanks!
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47981089

http://stackoverflow.com/q/47905139
score: 0
has body: I am planning to classify emails. I am using tfidf vectorizer and logistic regression algorithm to do this. I took very small training and testing sets. My training set consists of 150 emails( 3 classes, 50 emails/class) and testing set consists of 6 emails. Now my classifier is predicting 4 out of 6 correctly. Now my doubt is, can I tell the classifier that this document belongs to class X not class Y? If yes, What is this process called? Thank you.
has title: text classification using logistic regression
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88737628
has answer: http://stackoverflow.com/a/50867759
tagged with: text-classification
type: Question
answer count: 1

http://stackoverflow.com/a/47975265
answers question: http://stackoverflow.com/q/47974903
score: 0
has body: Your original regex: [0-9a-f]{4}\-[0-9a-f]{4}\-[0-9a-f]{4}\- can be simplified in ([0-9a-f]{4}\-){3} or (([0-9a-f]{4}\-){3}) depending on the fact that you want to use the whole match as a whole or not (e.g. backreference,...). Tested on regex101: https://regex101.com/r/gLSu92/1 https://regex101.com/r/gLSu92/2
type: Answer

http://stackoverflow.com/a/47903200
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47902702
score: 1
has body: If your question is how to write a word (.docx) file. There is a library called docx. Simply installed using pip: pip install python-docx Here is a short example that writes a docx file for you. from docx import Document document = Document() document.add_heading('Document Title', 0) p = document.add_paragraph('A plain paragraph having some text') document.save('demo.docx') Here is a script that that will read a text file and add lines that match a condition to a word file. I would change the matches_my_condition function to your own needs. from docx import Document def matches_my_condition(line): """ Returns true or false if the given line should be added to the document """ # Which will return true if the word cake appears in the line return 'cake' in line # Prepare document document = Document() with open('my_text_file.txt', 'r') as textfile: for line in textfile.readlines(): if matches_my_condition(line): document.add_paragraph(line) document.save('my_cake_file.docx')
answers question: http://stackoverflow.com/q/47902702

http://stackoverflow.com/comment/82719567
comment on: http://stackoverflow.com/q/47876712
has text: @user3245256: if you care about leap seconds, the `time` module is not going to do any better. `time` and `datetime` use the same underlying system time information.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82848482
has text: on Linux go to your home directory there you should find .aws folder
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47939576

http://stackoverflow.com/q/47999518
has answer: http://stackoverflow.com/a/48001905
has body: Why I can't install pip with pypy3 -m ensurepip? I have unpacked PyPy from official package, and followed instructions at official docs but resulting in an error. Interpreter log is below. Traceback (most recent call last): File "D:\pypy3-v5.10.0-win32\lib-python\3\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "D:\pypy3-v5.10.0-win32\lib-python\3\runpy.py", line 85, in _run_code exec(code, run_globals) File "D:\pypy3-v5.10.0-win32\lib-python\3\ensurepip\__main__.py", line 4, in &lt;module&gt; ensurepip._main() File "D:\pypy3-v5.10.0-win32\lib-python\3\ensurepip\__init__.py", line 209, in _main default_pip=args.default_pip, File "D:\pypy3-v5.10.0-win32\lib-python\3\ensurepip\__init__.py", line 116, in bootstrap _run_pip(args + [p[0] for p in _PROJECTS], additional_paths) File "D:\pypy3-v5.10.0-win32\lib-python\3\ensurepip\__init__.py", line 40, in _run_pip import pip File "C:\Users\user\AppData\Local\Temp\tmp5zq6hqua\pip-9.0.1-py2.py3-none-any.whl\pip\__init__.py", line 21, in &lt;module&gt; File "C:\Users\user\AppData\Local\Temp\tmp5zq6hqua\pip-9.0.1-py2.py3-none-any.whl\pip\_vendor\requests\__init__.py", line 62, in &lt;module&gt; File "C:\Users\user\AppData\Local\Temp\tmp5zq6hqua\pip-9.0.1-py2.py3-none-any.whl\pip\_vendor\requests\packages\__init__.py", line 27, in &lt;module&gt; File "C:\Users\user\AppData\Local\Temp\tmp5zq6hqua\pip-9.0.1-py2.py3-none-any.whl\pip\_vendor\requests\packages\urllib3\__init__.py", line 8, in &lt;module&gt; File "C:\Users\user\AppData\Local\Temp\tmp5zq6hqua\pip-9.0.1-py2.py3-none-any.whl\pip\_vendor\requests\packages\urllib3\connectionpool.py", line 101, in &lt;module&gt; AttributeError: module 'errno' has no attribute 'EWOULDBLOCK'
has answer: http://stackoverflow.com/a/48002867
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/48002867
tagged with: pypy
favorite count: 0
type: Question
score: 3
tagged with: windows
tagged with: python
tagged with: installation
upvote count: 3
has title: pip install with ensurepip on PyPy3.5 v5.10 in Windows 7 x64
answer count: 2
tagged with: pip
possible better answer: http://stackoverflow.com/a/48001905

http://stackoverflow.com/q/47885196
tagged with: scipy
has comment: http://stackoverflow.com/comment/85253622
tagged with: dendrogram
answer count: 0
downvote count: 0
type: UnansweredQuestion
has title: Implement hierarchal sampaling active learning
score: 1
favorite count: 0
type: Question
upvote count: 1
tagged with: python
has body: I recently came across this paper proposing hierarchical sampling for active learning. The algorithm (pseudocode) is as follows: [pseudocode][2] I am working to implement this using Python 3 and to begin I wrote the following code: Z = ward(X.todense()) fig = plt.figure(figsize=(25, 10)) dn = dendrogram(Z) which hierarchically clusters the dataset. However, I am now unsure how to access the classes to whcih each row belongs to. How can I do this?
tagged with: hierarchical-clustering

http://stackoverflow.com/comment/82906812
comment on: http://stackoverflow.com/a/47968352
has text: one more thing, I'm actually gonna do it by county not state, and sometimes county names can be same for different states, is there a best practice to solve this issue ?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/47966249
has comment: http://stackoverflow.com/comment/82902138
accepted answer of: http://stackoverflow.com/q/47966215
answers question: http://stackoverflow.com/q/47966215
type: AcceptedAnswer
type: Answer
score: 7
has body: Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? Postgres is not in the "localhost" for the gitlab-ci runner. The gitlab-ci runs on a container, and the postgresql runs on a different one. As specified in your .gitlab-ci.yml, the Postgres container can be discovered by just using the name "postgres": services: - postgres:latest So replacing "localhost" by "postgres" in your code would solve your problem.
upvote count: 7
downvote count: 0

backend
tags question: http://stackoverflow.com/q/47986522
tags question: http://stackoverflow.com/q/47977415
type: Tag
tag name: backend

http://stackoverflow.com/a/48006325
has body: You use the asterisk * when you call the function: def mapper(func, *sequences): result = [] if len(sequences) > 0: minl = min(len(subseq) for subseq in sequences) for i in range(minl): result.append(func(*[subseq[i] for subseq in sequences])) return result This produces: &gt;&gt;&gt; import operator &gt;&gt;&gt; mapper(operator.add, [1,2,4], [3,6,9]) [4, 8, 13] By using the asterisk, we unpack the iterable as separate parameters in the function call. Note that this is still not fully equivalent, since: the sequences should be iterables, not per se lists, so we can not always index; and the result of a map in python-3.x is an iterable as well, so not a list. A more python-3.x-like map function would be: def mapper(func, *sequences): if not sequences: raise TypeError('Mapper should have at least two parameters') iters = [iter(seq) for seq in sequences] try: while True: yield func(*[next(it) for it in iters]) except StopIteration: pass Note however that most Python interpreters will implement map closer to the interpreter than Python code, so it is definitely more efficient to use the builtin map, than writing your own. N.B.: it is better not to use variable names like list, set, dict, etc. since these will override (here locally) the reference to the list type. As a result a call like list(some_iterable) will no longer work.
score: 5
upvote count: 5
accepted answer of: http://stackoverflow.com/q/48006242
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48006242
downvote count: 0
type: Answer

http://stackoverflow.com/comment/101788347
has text: @vishes_shell you are absolutely correct, edited.
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/47928628

http://stackoverflow.com/comment/82861986
type: QuestionComment
comment on: http://stackoverflow.com/q/47945669
has text: In this case `vstack` does the same thing, turning the inputs into 2d arrays. `hstack` is the same as `concatenate` on the last axis (here the only one). It's a good idea to read their code.
score: 0
type: Comment

http://stackoverflow.com/a/47983272
has comment: http://stackoverflow.com/comment/82935240
has body: re.findall with zero-width positive lookbehind ((?&lt;=language )) to match language before, then getting the desired substrings with \w+ and print-ing with sep='\n' to get desired output format: In [33]: s = 'This is my first Python language and I like this language to the most.' In [34]: print(*re.findall(r'(?&lt;=language )\w+', s), sep='\n') and to
answers question: http://stackoverflow.com/q/47983239
has comment: http://stackoverflow.com/comment/82935375
score: 0
has comment: http://stackoverflow.com/comment/82935261
has comment: http://stackoverflow.com/comment/82935431
type: Answer

http://stackoverflow.com/comment/82970209
has text: DownVoter, could you explain yourself?
comment on: http://stackoverflow.com/a/47998874
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47942945
downvote count: 0
has body: I believe you are quite confused as to what it is you want to do and how to achieve it. Assuming I understood your question correctly, this is how I would do it: from collections import OrderedDict def info_from_row(my_dict): try: return float(my_dict['Duration']) except KeyError: return float(my_dict['Duration (min)']) example_dict = {'X': OrderedDict([('ID', '123456'), ('Duration', '54941')]), 'Y': OrderedDict([('ID', '789101'), ('Duration (min)', '7869')])} print(info_from_row(example_dict['X'])) # -&gt; 54941.0 print(info_from_row(example_dict['Y'])) # -&gt; 7869.0 As you can see, the duration is printed regardless of which subdictionary you wish to query. Another way to do the exact same thing that does not use try-except is this: def info_from_row(my_dict): if 'Duration' in my_dict: return float(my_dict['Duration']) else: return float(my_dict['Duration (min)']) which has exactly the same outcome and is called in the exact same way; info_from_row(example_dict['Y']). If you want the main key ('X' or 'Y') to be a function-argument as well, you can slightly modify the function (any of them) like so: def info_from_row(my_dict, main_key): if 'Duration' in my_dict[main_key]: return float(my_dict[main_key]['Duration']) else: return float(my_dict[main_key]['Duration (min)']) but then the call statements have to be modified as well: print(info_from_row(example_dict, 'X')) # -&gt; 54941.0 print(info_from_row(example_dict, 'Y')) # -&gt; 7869.0
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47942735
accepted answer of: http://stackoverflow.com/q/47942735
has comment: http://stackoverflow.com/comment/82855462
type: AcceptedAnswer

http://stackoverflow.com/comment/82749319
has text: @OdayHajYehia your desired output is 7x7 as well. Can you clarify?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47891353
type: Comment

http://stackoverflow.com/q/47901397
linked to: http://stackoverflow.com/q/47854129
has comment: http://stackoverflow.com/comment/82769837
has comment: http://stackoverflow.com/comment/82769493
answer count: 1
score: 0
has body: I have a simple script that navigates to the following pages highlighted in yellow and green below. My question is, how do I create a page counter so I know where the job is at for this? Ideally it would read: Page 5 Page 4 #For each of the loop The following tends to work, though I am having issues with the following: elements = [x.get_text("*") for x in wait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,'(//div[div/div/text()="Main Lists"]//div[starts-with(@class, "sm-CouponLink_Label") and normalize-space()]')))] Full code: import collections from random import shuffle from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait as wait driver = webdriver.Chrome() driver.set_window_size(1024, 600) driver.maximize_window() driver.get('https://www.bet365.com.au/#/AS/B1/') driver.get('https://www.bet365.com.au/#/AS/B1/') def page_counter(): for x in range(1000): yield x clickMe = wait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,'(//div[div/div/text()="Main Lists"]//div[starts-with(@class, "sm-CouponLink_Label") and normalize-space()])'))) options = driver.find_elements_by_xpath('//div[div/div/text()="Main Lists"]//div[starts-with(@class, "sm-CouponLink_Label") and normalize-space()]') indexes = [index for index in range(len(options))] shuffle(indexes) for index in indexes: count = page_counter() driver.get('https://www.bet365.com.au/#/AS/B1/') elements = [x.get_text("*") for x in wait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,'(//div[div/div/text()="Main Lists"]//div[starts-with(@class, "sm-CouponLink_Label") and normalize-space()]')))] #elements = [x.get_attribute("href") for x in # driver.find_elements_by_xpath('//div[div/div/text()="Main Lists"]//div[starts-with(@class, "sm-CouponLink_Label") and normalize-space()]')))] clickMe.click() shuffle…
has comment: http://stackoverflow.com/comment/82769631
tagged with: python
has comment: http://stackoverflow.com/comment/82769741
has answer: http://stackoverflow.com/a/47908431
type: AnsweredQuestion
tagged with: python-3.x
tagged with: selenium
has title: Page counter for css elements
type: Question
accepted answer: http://stackoverflow.com/a/47908431

http://stackoverflow.com/comment/82748848
type: Comment
type: QuestionComment
score: 4
comment on: http://stackoverflow.com/q/47891089
has text: If you have code that produces an error, please reduce that code to the shortest possible **complete** example that demonstrates the error. See [mcve] for more information.

http://stackoverflow.com/q/47864573
favorite count: 0
has title: Equality of Django's Q objects
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/47864574
upvote count: 4
possible better answer: http://stackoverflow.com/a/56063904
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/47864574
type: Question
has body: I am trying to compare django's Q objects which are composed in the exact same way. But despite all children and relations between them being same, they aren't deemed equal. from django.db.models import Q $ q1 = Q(a=1) &amp; Q(b=1) &amp; Q(c=1) $ q2 = Q(a=1) &amp; Q(b=1) &amp; Q(c=1) $ q1 == q2 $ False This is posing problems in my unit tests where I build up filters for my querysets using Q objects. Why are the two Q objects not equal? I am using Django 1.11.
tagged with: django-models
score: 4
has answer: http://stackoverflow.com/a/56063904
answer count: 2

http://stackoverflow.com/q/47856160
tagged with: encoder
answer count: 3
has answer: http://stackoverflow.com/a/47856250
tagged with: python
has answer: http://stackoverflow.com/a/47856209
favorite count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/43017783
has answer: http://stackoverflow.com/a/47856210
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/82676418
tagged with: numpy
duplicate of: http://stackoverflow.com/q/43017783
has body: Simple question, I want to get a 1D numpy array. Given a 2D array where each row contains a single '1' value, how can it be converted to a 1D array, consisting of the column index of the '1' in the 2D array [[ 0. 0. 1.] [ 0. 0. 1.] [ 0. 0. 1.] [ 0. 1. 0.] [ 0. 1. 0.] [ 0. 1. 0.] [ 0. 1. 0.] [ 1. 0. 0.]] to [2 2 1 1 1 1 0] How would I do it in python? I don't know the terminology for it, do let me know the proper terms for such transformation.
tagged with: transformation
tagged with: arrays
downvote count: 0
score: 4
has title: Python 2D Numpy Array to 1D (sort of..)

http://stackoverflow.com/comment/82864124
type: QuestionComment
score: 0
has text: Are the values of the column stored as datetimes? You can verify this through e.g. `df.info()`. If you add the code you used to generate the dataframe, the question will be more easily answerable.
comment on: http://stackoverflow.com/q/47947095
type: Comment

http://stackoverflow.com/q/47930552
tagged with: python
has answer: http://stackoverflow.com/a/47930584
favorite count: 0
type: AnsweredQuestion
has body: I have a DataFrame as such: Iter ID Time 0 1 A 12:00:00 1 1 B 12:00:01 2 1 C 12:00:01 3 2 B 12:02:00 4 2 A 12:02:02 5 2 C 12:02:06 6 3 C 12:05:01 7 3 B 12:05:00 8 3 A 12:05:05 I would like to get the offset of each timestamp from it's minimum timestamp for that iteration. For instance the column of "Delta" for this example could be Iter ID Time Delta 0 1 A 12:00:00 00:00:00 1 1 B 12:00:01 00:00:01 2 1 C 12:00:01 00:00:01 3 2 B 12:02:00 00:00:00 4 2 A 12:02:02 00:00:02 5 2 C 12:02:06 00:00:06 6 3 C 12:05:01 00:00:01 7 3 B 12:05:00 00:00:00 8 3 A 12:05:05 00:00:05 My first thought was to use apply, but not sure how to do it on only groups of Iter.
upvote count: 5
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/47930584
type: Question
score: 5
answer count: 1
downvote count: 0
has title: Subtract smallest timestamp per group from every other timestamp in pandas
tagged with: pandas-groupby
tagged with: pandas

http://stackoverflow.com/comment/82751504
has text: Do you mean the `i` that is used inside `annual_emi_scale` or the `i` from the main loop?
comment on: http://stackoverflow.com/q/47892431
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47932005
accepted answer of: http://stackoverflow.com/q/47931749
type: Answer
score: 3
upvote count: 3
has body: The Excel function PERCENTILERANK.INC excludes the max value (in my case 45). Which is why it shows 0 versus 6.25 like scipy does. To rectify this, I modified my function to remove the max values of the array like so: array = list(filter(lambda a: a != max(array), array)) return 100 - int(stats.percentileofscore(array, score, kind='strict')) This gave me the correct results, and all my other tests passed. Additional information based on Brian Pendleton's comment. Here is a link to the Excel functions explaining PERCENTILERANK.INC as well as other ranking functions. Thanks for this.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47931749

http://stackoverflow.com/comment/82704736
comment on: http://stackoverflow.com/q/47868884
type: Comment
type: QuestionComment
has text: @eyllanesc I've included it in my post now.
score: 0

http://stackoverflow.com/comment/82793167
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47903962
has text: I thought it was a particular solution to address a class object issue I experienced but instead I've added the method inside a socket_server not an elegant solution but does the job for now). So I've taken it out again. I'll post that issue later this week with a ref to it here. (its more or less your example I've linked that helped me out trying the QVarant which at first glance looked solving the issue, but now I'm wirting down the issue based on your program structure tree; not jet ready to post it).

http://stackoverflow.com/comment/82891005
score: 0
type: Comment
has text: `print(dir(fut))` may help. You should call it before and after importing your own module and compare.
type: QuestionComment
comment on: http://stackoverflow.com/q/47960795

http://stackoverflow.com/comment/82678605
type: Comment
has text: Nothing changed
comment on: http://stackoverflow.com/a/47857096
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82747305
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47888240
has text: Do you change `API_KEY` ?

http://stackoverflow.com/a/47914112
downvote count: 0
score: 1
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47913568
has body: A rook can move horizontally or vertically. So a rook can attack another rook if they're in the same row or column of the chessboard, i.e. there are at least two rooks in the same row or column. This code seems to assume that the only pieces in the chessboard are rooks. If a square has a piece the value of the list element is 1, otherwise it's 0. The first for loop goes through each row of the chessboard, counting the number of squares that have a piece in that row. If the count is more than 1, the rooks are not safe, and it returns false. The second for loop does the same thing, but goes by column instead of row. If neither loop returns false, it means all the rooks are safe, and it returns true at the end.

http://stackoverflow.com/comment/82787215
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47908770
has text: Thank you so much. This was exactly what I was looking for. Could you describe why you resized the image as (64,64) since the colored image has three dimensions?
score: 0

http://stackoverflow.com/comment/82678033
score: 1
has text: That doesn't look like a valid JSON string.
type: Comment
comment on: http://stackoverflow.com/q/47856882
type: QuestionComment

http://stackoverflow.com/comment/82773087
comment on: http://stackoverflow.com/q/47903168
type: Comment
score: 1
has text: why don't you add property as -JbaseDir=/tmp/jmeter-3sc0ppq5/ and use baseDir property in script?
type: QuestionComment

http://stackoverflow.com/q/47920356
has comment: http://stackoverflow.com/comment/82816913
score: 0
answer count: 1
tagged with: pyqt4
accepted answer: http://stackoverflow.com/a/47932566
has comment: http://stackoverflow.com/comment/82816658
tagged with: python
has comment: http://stackoverflow.com/comment/82834199
type: AnsweredQuestion
has title: PyQt4 : making certain text on QTextEdit uneditable
has body: Is there any way I can make certain text on QTextEdit permanent. Applications like cmd.exe where the current user directory is displayed and the rest of the screen is up for input. I tried inserting a QLabel but unable to do so, here's my code, I am currently taking user input through a separate line edit. UPDATE I had a look at Ipython QtConsole where the line number is displayed constantly, how can I do that, I am looking in the source but if anyone who already knows it, please do tell. Here is the QtConsole for ipython notebook, I am trying to replicate this. import os import sys import PyQt4 import PyQt4.QtCore from PyQt4.QtGui import * def main(): app = QApplication(sys.argv) w = MyWindow() w.show() sys.exit(app.exec_()) class MyWindow(QWidget): def __init__(self, *args): QWidget.__init__(self, *args) # create objects label = QLabel(self.tr("Enter command and press Return")) self.le = QLineEdit() self.te = QTextEdit() self.lbl = QLabel(str(os.getcwd())+"&gt; ") # layout layout = QVBoxLayout(self) layout.addWidget(label) layout.addWidget(self.le) layout.addWidget(self.te) self.setLayout(layout) # styling self.te.setReadOnly(True) # create connection self.mytext = str(self.le.text()) self.connect(self.le, PyQt4.QtCore.SIGNAL("returnPressed(void)"), self.display) def display(self): mytext = str(self.le.text()) self.te.append(self.lbl +str(os.popen(mytext).read())) self.le.setText("") if __name__ == "__main__": main()
has answer: http://stackoverflow.com/a/47932566
has comment: http://stackoverflow.com/comment/82833802
type: Question
tagged with: qtconsole
has comment: http://stackoverflow.com/comment/82816805
has comment: http://stackoverflow.com/comment/82816877

http://stackoverflow.com/comment/82891054
comment on: http://stackoverflow.com/a/47960843
has text: Glenn Codes, what would be a good statement to only process the file name if it has ".jpg" in it?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82940498
comment on: http://stackoverflow.com/a/47978594
type: Comment
has text: @Ian_De_Oliveira please see the updated answer. I further broke down the texts such as BILE BEANS FOR BILIOUSNESS B into BILE - BEANS - FOR - BILIOUSNESS - B. In my analogy you have texts like 'x y z' and 'y y' for every lodgement_year, and my updated answer counts each and every x's, y's, and z's; instead of counting 'x y z' and 'y y' strings. I couldn't think of an easy solution using lambda. Lambda notation may not always be easy, but if someone else proposes a lambda-based solution, I will enjoy learning it :)
score: 0
type: AnswerComment

http://stackoverflow.com/comment/124567627
type: AnswerComment
type: Comment
has text: @j_4321 Thanks. That helps! I will upto 12 progress bars in my game I am developing!
comment on: http://stackoverflow.com/a/47902046
score: 0

import
type: Tag
tags question: http://stackoverflow.com/q/47895053
tags question: http://stackoverflow.com/q/47871423
tag name: import
tags question: http://stackoverflow.com/q/47961723
tags question: http://stackoverflow.com/q/47877985
tags question: http://stackoverflow.com/q/47922801
tags question: http://stackoverflow.com/q/47860840
tags question: http://stackoverflow.com/q/47858657
tags question: http://stackoverflow.com/q/47945766
tags question: http://stackoverflow.com/q/48004562
tags question: http://stackoverflow.com/q/47973561
tags question: http://stackoverflow.com/q/47887134
tags question: http://stackoverflow.com/q/47895551
tags question: http://stackoverflow.com/q/47869843

http://stackoverflow.com/comment/82856834
has text: if `b` is the output of my function below, `np.all(np.isclose(np.rot90(a, 2), b)) == True`. So this is 2 rotations of 90°.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47930428
type: Comment

http://stackoverflow.com/q/48000761
answer count: 5
has answer: http://stackoverflow.com/a/48000917
has answer: http://stackoverflow.com/a/65193885
tagged with: python
tagged with: module
has comment: http://stackoverflow.com/comment/82970167
has body: How to get the name/list of all submodules of an already imported Python module? (Not the external imported module/packages, just that one in the same folder as module sub-folder). I am using import inspect print([o[0] for o in inspect.getmembers(module_imported) if inspect.ismodule(o[1])]) but this print also the system modules imported and files in the main module folder.
downvote count: 0
has comment: http://stackoverflow.com/comment/82987575
type: UnansweredQuestion
has title: List submodules of a python module
has answer: http://stackoverflow.com/a/60736779
has comment: http://stackoverflow.com/comment/82970016
type: Question
upvote count: 39
has answer: http://stackoverflow.com/a/58684066
has comment: http://stackoverflow.com/comment/136016246
has comment: http://stackoverflow.com/comment/82970111
linked to: http://stackoverflow.com/q/1707709
has comment: http://stackoverflow.com/comment/82970037
favorite count: 0
score: 39
has answer: http://stackoverflow.com/a/68716018

wsgi
type: Tag
tags question: http://stackoverflow.com/q/47863536
tag name: wsgi

http://stackoverflow.com/q/47985750
has comment: http://stackoverflow.com/comment/82958266
type: AnsweredQuestion
has title: Extracting data/string from Pandas DF column
downvote count: 1
accepted answer: http://stackoverflow.com/a/47985802
type: Question
has body: Im trying to extract currency pairs from the poloniex API using Python pandas. I believe the data returned is all just a single column name: Columns: [{"BTC_BCN":{"BTC":"479.74697466", "BCN":"1087153595.32266165"}, "BTC_BELA":{"BTC":"32.92293515", "BELA":"1807337.13247948"}, "BTC_BLK":{"BTC":"25.70374054", "BLK":"606717.86348734"}, "BTC_BTCD":{"BTC":"24.32220571", "BTCD":"1264.02352237"}, "BTC_BTM":{"BTC":"11.57816905", "BTM":"80673.47934437"}, "BTC_BTS":{"BTC":"1102.88787610", "BTS":"30426626.64558044"} The result I want: BTC_BCN, BTC_BELA, BTC_BLK, etc... But not really sure if there is a simple way to get this without string parsing since they all appear to just be column names. Code: from bs4 import BeautifulSoup import csv import urllib2 import pandas as pd try: from StringIO import StringIO except: from io import StringIO sock= urllib2.urlopen('https://poloniex.com/public?command=return24hVolume') link=sock.read() soup = BeautifulSoup(link,'lxml') csv_data = StringIO(soup.text) df=pd.read_csv(csv_data,delimiter=' *, *',engine='python') df2=df.iloc[1:2,0:20]
upvote count: 0
has comment: http://stackoverflow.com/comment/82940704
score: -1
tagged with: pandas
answer count: 1
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/47985802
tagged with: python

http://stackoverflow.com/a/47879057
downvote count: 0
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47878846
has body: Just to add on to an excellent existing answer, but this doesn't work because you are modifying the class instance, and not the class. In order to get the behavior you desire, you can modify the class during __init__, however, this is woefully inadequate (since it modifies the class, and therefore all instances of the class), and you are better off making those changes visible at the class scope. For example, the following are equivalent: class SpecialInteger1: def __init__(self,x): self.x = x self.__class__.__eq__ = self.equals_normal ... class SpecialInteger2: def __init__(self,x): self.x = x def equals_normal(self,other): return self.x == other.x def __eq__(self, other): return self.equals_normal(other) You should prefer case SpecialInteger2 in all examples, since it is more explicit about what it does. However, none of this actually solves the issue you are trying to solve: how can I create a specialized equality comparison at the instance level that I can toggle? The answer is through the use of an enum (in Python 3): from enum import Enum class Equality(Enum): NORMAL = 1 SPECIAL = 2 class SpecialInteger: def __init__(self, x, eq = Equality.NORMAL): self.x = x self.eq = eq def equals_normal(self, other): return self.x == other.x def equals_special(self, other): return self.x != other.x def __eq__(self, other): return self.__comp[self.eq](self, other) # Define a dictionary for O(1) access # to call the right method. __comp = { Equality.NORMAL: equals_normal, Equality.SPECIAL: equals_special } Let's walk through this quickly, since there are 3 parts: An instance member variable of eq, which can be modified dynamically. An implementation of __eq__ that selects the correct equality function based on the value of self.eq. A namespace-mangled dictionary (a class/member variable that starts with __, in this case, self.__comp) that allows efficient lookup of the desired equality method. The dictionary can easily be done-away with, especially for cases where you only wi…

http://stackoverflow.com/a/48088667
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47897996
has comment: http://stackoverflow.com/comment/83171237
answers question: http://stackoverflow.com/q/47897996
score: 1
has comment: http://stackoverflow.com/comment/83152106
has body: Looks like you passing data as parameters and using incorrect url. Proper curl request: ########## REQUEST ########## curl -i --data '{ "username": "android", "password": "AC7IBG09A3DTSYM4R41UJWL07VLN8JI7", "deviceModel": "android-generic", "version": "5", "includeUrls": true }' -X POST 'https://tuner.pandora.com:443/services/json/?method=auth.partnerLogin' -H "Content-Type: application/json" -A 'pinobar' ########## OUTPUT ########## HTTP/1.1 200 OK Date: Thu, 04 Jan 2018 03:46:54 GMT Server: Apache Content-Type: text/plain; charset=utf-8 Content-Length: 741 Cache-Control: must-revalidate, max-age=0 Expires: -1 Vary: Accept-Encoding {"stat":"ok","result":{"syncTime":"f6f071bb4b886bc3545fbd66701b8d38","deviceProperties":{"followOnAdRefreshInterval":3,"ooyala":{"streamingPercentage":0,"streamingWhitelist":[534051315],"videoAdBufferRetryCount":3,"videoAdLoadingTimeout":2,"videoAdPlayTimeout":8},"videoAdUniqueInterval":0,"videoAdStartInterval":180,"optionalFeatures":{"optionalFeature":[{"feature":"useAudioProxy2","enabled":"false","platformVersionRange":{"low":"4.0","high":"5.0.0"},"productVersionRange":{"low":"1.6","high":"*"}}]},"adRefreshInterval":3,"videoAdRefreshInterval":870},"partnerAuthToken":"VADEjNzUq9Ew9HUkIzUT489kVe9kjo0If3","partnerId":"42","stationSkipUnit":"hour","urls":{"autoComplete":"http://autocomplete.pandora.com/search"},"stationSkipLimit":6}} I would suggest use urllib2 sample. Here working sample for our case: import json import urllib2 username = "android" password = "AC7IBG09A3DTSYM4R41UJWL07VLN8JI7" deviceModel = "android-generic" url = "https://tuner.pandora.com:443/services/json/?method=auth.partnerLogin" values = { "username" : username, "password" : password, "deviceModel": deviceModel, "version" : "5" } data = json.dumps(values) headers = {'content-type': 'application/json'} req = urllib2.Request(url, data, headers) response = urllib2.urlopen(req) content = response.read() print("data:", data) print("url:", url) print("response:", response…
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83152091

http://stackoverflow.com/a/47893818
downvote count: 1
score: -1
has body: I think what you're missing is a "weights_only=True" argument in the load: model.load("model.tflearn", weights_only=True)
answers question: http://stackoverflow.com/q/47888595
upvote count: 0
type: Answer

http://stackoverflow.com/comment/82724121
type: Comment
has text: An attack with magnitude M will be successful with a chance of (100-M)%. That is, higher magnitude means higher risk of missing it. For instance, if M is 30, the chance of succeeding would be 70%, whereas, if M is 10, the chance of succeeding would be 90%. If an attack with magnitude 3 | P a g e M is successful, the attacked hero’s health points will decrease by M. If the user writes more than 50 or less than 1, the game should warn the player, and re-ask for another attack magnitude as below. this is the original question
comment on: http://stackoverflow.com/a/47878854
type: AnswerComment
score: 0

http://stackoverflow.com/q/47920758
has comment: http://stackoverflow.com/comment/82809564
has answer: http://stackoverflow.com/a/47923839
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82813213
has comment: http://stackoverflow.com/comment/82814500
type: Question
has comment: http://stackoverflow.com/comment/82812795
tagged with: python
has comment: http://stackoverflow.com/comment/82811775
favorite count: 0
has comment: http://stackoverflow.com/comment/82811668
has body: EDIT: Updated now that I've narrowed down the problem to the context processor variable not being available to a template that I'm loading with a custom tag. I'm using Django 1.11 and this is my first time trying to use a custom context processor. The problem is that the context variable I'm supposed to be adding from the context processor does not return anything from within a template loaded from a custom tag. I don't receive any errors. So below {{ testcontext }} should return "IT WORKED!" and does so in my base.html template, but returns nothing in the template loaded with @register.inclusion_tag(). settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'appname.context_processors.test_context', ], }, }, ] context_processors.py: def test_context(request): return {'testcontext': 'TEST WORKED!'} tags.py from django import template from appname.models import Category register = template.Library() @register.inclusion_tag('template.html') def load_category(selected_slug=None): return { 'categories': Category.objects.all(), 'selected':selected_slug, } views.py: from django.views.generic import ListView from appname.models import MyModel class MyView(ListView): model = MyModel urls.py from django.conf.urls import url from appname.views import MyView urlpatterns = [ url(r'^$', MyView.as_view(), name="home"), ] template.html {{ testcontext }}
score: 5
tagged with: django
answer count: 1
upvote count: 5
has title: Django context processor doesn't display new context values in template

http://stackoverflow.com/comment/82989330
type: Comment
type: QuestionComment
score: 0
has text: Yup, I would like a minimal example reproducing the issue.
comment on: http://stackoverflow.com/q/48009792

cryptography
tag name: cryptography
tags question: http://stackoverflow.com/q/47998565
type: Tag
tags question: http://stackoverflow.com/q/47861874
tags question: http://stackoverflow.com/q/48002298
tags question: http://stackoverflow.com/q/47871602

http://stackoverflow.com/q/47861084
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/47874627
downvote count: 0
type: UnansweredQuestion
score: 34
tagged with: tensorflow
type: Question
tagged with: numpy
has title: how to store numpy arrays as tfrecord?
has body: I am trying to create a dataset in tfrecord format from numpy arrays. I am trying to store 2d and 3d coordinates. 2d coordinates are numpy array of shape (2,10) of type float64 3d coordinates are numpy array of shape (3,10) of type float64 this is my code: def _floats_feature(value): return tf.train.Feature(float_list=tf.train.FloatList(value=value)) train_filename = 'train.tfrecords' # address to save the TFRecords file writer = tf.python_io.TFRecordWriter(train_filename) for c in range(0,1000): #get 2d and 3d coordinates and save in c2d and c3d feature = {'train/coord2d': _floats_feature(c2d), 'train/coord3d': _floats_feature(c3d)} sample = tf.train.Example(features=tf.train.Features(feature=feature)) writer.write(sample.SerializeToString()) writer.close() when i run this i get the error: feature = {'train/coord2d': _floats_feature(c2d), File "genData.py", line 19, in _floats_feature return tf.train.Feature(float_list=tf.train.FloatList(value=value)) File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\google\protobuf\internal\python_message.py", line 510, in init copy.extend(field_value) File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\google\protobuf\internal\containers.py", line 275, in extend new_values = [self._type_checker.CheckValue(elem) for elem in elem_seq_iter] File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\google\protobuf\internal\containers.py", line 275, in &lt;listcomp&gt; new_values = [self._type_checker.CheckValue(elem) for elem in elem_seq_iter] File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\google\protobuf\internal\type_checkers.py", line 109, in CheckValue raise TypeError(message) TypeError: array([-163.685, 240.818, -114.05 , -518.554, 107.968, 427.184, 157.418, -161.798, 87.102, 406.318]) has type &lt;class 'numpy.ndarray'&gt;, but expected one of: ((&lt;class 'numbers.Real'&gt;,),) I dont know how to fix this. should i store the fe…
answer count: 3
has answer: http://stackoverflow.com/a/60283571
has answer: http://stackoverflow.com/a/65706184
tagged with: tfrecord
upvote count: 34

http://stackoverflow.com/comment/82936564
has text: Mr. Roseman was correct, of course. For anyone following, settings.py must include EMAIL_HOST_USER and EMAIL_HOST_PASSWORD. I also added USE_TLS = True, although another SO post suggests it's unneeded.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47981685
type: Comment

http://stackoverflow.com/comment/82960578
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47996051
has text: Nothing really, the problem occures in a bigger script with that exact number of entries, but a more complex application of simps. I clarified the example.

http://stackoverflow.com/q/47977615
has comment: http://stackoverflow.com/comment/82924466
has comment: http://stackoverflow.com/comment/136911453
tagged with: quest
answer count: 2
downvote count: 3
has comment: http://stackoverflow.com/comment/82924200
has answer: http://stackoverflow.com/a/47977860
has title: Python 3 quest command, IndentationError: unindent does not match any outer indentation level
has body: def register(): print("Register") login = input("Enter login") passwd = input("Enter password") passwdacc = input("Accept password") if passwdacc = passwd: print("You have registered, now please sign up") else: print("Try again, passwords dont matches") login2 = input("Enter login") password = input("Enter password") if password = passwd and login2 = login print("Accepted") else: print("Try again") sign_up() Error(s), warning(s): File "source_file.py", line 3 login = input("Enter login") ^ IndentationError: unindent does not match any outer indentation level
score: -3
linked to: http://stackoverflow.com/q/45621722
type: AnsweredQuestion
upvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/47977787
duplicate of: http://stackoverflow.com/q/45621722
accepted answer: http://stackoverflow.com/a/47977860
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47977787
type: Question
tagged with: python

http://stackoverflow.com/a/47915189
upvote count: 62
has comment: http://stackoverflow.com/comment/82798539
score: 60
answers question: http://stackoverflow.com/q/47914980
has comment: http://stackoverflow.com/comment/137940416
has comment: http://stackoverflow.com/comment/82798661
type: Answer
has comment: http://stackoverflow.com/comment/82798692
downvote count: 2
has body: Go with the mouse to the Windows Icon (lower left) and start typing "Anaconda". There should show up some matching entries. Select "Anaconda Prompt". A new command window, named "Anaconda Prompt" will open. Now, you can work from there with Python, conda and other tools.

http://stackoverflow.com/comment/82746906
score: 1
has text: In most regex flavors OTHER than Python re, a non capturing group is the only way to get local flags. `(?i:BOB|ALLEN)` will make that capture case insensitive inside the group. There is no way to replicate that in a capture group. Python does not support local flags however.... If you wanted Bob to be case insensitive but Allen not and capture the result, `((?i:BOB)|Allen)` is the most logical way to do that in PCRE.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47887882

http://stackoverflow.com/q/48014309
favorite count: 0
answer count: 0
type: UnansweredQuestion
tagged with: python
has body: I have a Flask API that uploads files. Currently I am working on scaling the application. I have a scenario where a user uploads a large file - in that case, I save the file locally in the flask request and then kick off a celery task that then uploads it to S3 (and does other things). My problem now is that the celery worker(s) will be running on multiple machines - so they won't be able to access the local filesystem of the Flask server. My solution is to simply upload to S3 in the Flask request. The issues is that large files (100MB) can take upwards of 30 seconds and that bogs down the flask server. I am looking for either a solution on how to use boto3 to upload files asynch (with a callback) or perhaps a better design pattern. Or perhaps someway to pass the entire file to a celery task?
score: 2
tagged with: amazon-s3
tagged with: celery
has comment: http://stackoverflow.com/comment/82998031
type: Question
linked to: http://stackoverflow.com/q/47728803
has comment: http://stackoverflow.com/comment/82998181
downvote count: 0
tagged with: boto3
tagged with: flask
has comment: http://stackoverflow.com/comment/82997976
has comment: http://stackoverflow.com/comment/82997757
upvote count: 2
has title: Upload a file asynchronously to S3 in Flask request
has comment: http://stackoverflow.com/comment/82997702

http://stackoverflow.com/q/47864590
has body: I want to make a mask that has ones corresponding to certain cells in an image. These cells should have at least one of their RGB color values greater than a threshold. Here is my code that doesn't work: B = image[0:h,0:w,0].astype(int) G = image[0:h,0:w,1].astype(int) R = image[0:h,0:w,2].astype(int) mask = np.zeros((h,w)) mask[np.where( max(R,G,B) &gt; threshold )] = 1 This gives an error: ValueError occurred Message=The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
accepted answer: http://stackoverflow.com/a/47864630
type: Question
has title: NumPy where condition to get cells with max(R,G,B) > a threshold
tagged with: numpy
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/47864630
tagged with: python
tagged with: opencv
type: AnsweredQuestion
tagged with: image-processing

http://stackoverflow.com/q/47970818
has answer: http://stackoverflow.com/a/47970850
favorite count: 0
tagged with: beautifulsoup
has body: in my code i'm trying to split a string and put links(that are in the string ) in an array, with the method .split(), but when i try to do that. ciao = [] for article in soup.find_all("a", {"style": "height:81px;"}): ciao = article.get("href").split() print(ciao[1]) i get the error : "IndexError: list index out of range so i tryed to print out the list ciao = [] for article in soup.find_all("a", {"style": "height:81px;"}): ciao = article.get("href").split() print (ciao) it gives me: [link1] [link2] [link3] [link4] [link5] [link6] ... instead of [link1, link2, link3, ...] can you explain me why and how can i correct my code to obtain a list?
has comment: http://stackoverflow.com/comment/82911223
has comment: http://stackoverflow.com/comment/82911133
has answer: http://stackoverflow.com/a/47970869
has comment: http://stackoverflow.com/comment/82911377
has answer: http://stackoverflow.com/a/47970872
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/82911090
tagged with: list
upvote count: 1
has title: .split() doesn't transform string in list
has comment: http://stackoverflow.com/comment/82911142
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47970872
score: 1
type: Question
has answer: http://stackoverflow.com/a/47970873
has comment: http://stackoverflow.com/comment/82911200
possible better answer: http://stackoverflow.com/a/47970850
downvote count: 0

http://stackoverflow.com/a/47958054
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47957827
score: 1
has body: How to read the mangled attribute, data-cachedhtml The HTML is a mess. Try the techniques listed in How to parse invalid (bad / not well-formed) XML? to get viable markup before using XPath. It may take three passes: Cleanup the markup mess. Get the attribute value of data-cachedhtml. Use XPath to extract the image links. XPath part For the de-mangled data-chachedhtml in this form: loading... This XPath will retrieve the preview image links: //a/img/@src (That is, all src attributes of img element children of a elements.) or This XPath will retrieve the click-through image links: //a[img]/@href (That is, all href attributes of the a elements that have a img child.)

http://stackoverflow.com/a/57263546
has body: try this: df["A"] = np.mean(dff.loc[:,["A","B"]],axis=1) df.drop(columns=["B"],inplace=True) A 0 1.0 1 2.0 2 1.5
answers question: http://stackoverflow.com/q/47963927
score: 0
type: Answer

http://stackoverflow.com/a/47919205
has comment: http://stackoverflow.com/comment/82807065
has comment: http://stackoverflow.com/comment/123914335
downvote count: 1
upvote count: 4
has comment: http://stackoverflow.com/comment/82807335
type: AcceptedAnswer
has body: You can use joins val diff = df2.join(df1,df2.col("pitid")!=df1.col("pitid"),"left") If values of all columns will be same in both dataframe then you can use except df2.subtract(df1) Both will gives records in dataframe2 but not in dataframe1
has comment: http://stackoverflow.com/comment/82806690
accepted answer of: http://stackoverflow.com/q/47919022
answers question: http://stackoverflow.com/q/47919022
has comment: http://stackoverflow.com/comment/82807020
type: Answer
has comment: http://stackoverflow.com/comment/82806853
score: 3
has comment: http://stackoverflow.com/comment/82807169

http://stackoverflow.com/comment/108026028
score: 0
type: AnswerComment
has text: @JohnAndrews what do you mean? What are you trying to do? Rules are used with CrawlSpider
type: Comment
comment on: http://stackoverflow.com/a/47963721

http://stackoverflow.com/q/47925244
has body: I'm working with python 3.4.1 interpreter in pycharm. I'm trying to do several things on a changing number of variables. I'v found it convenient to use exec() in order of changing the variable name and execute the same command on a different variable name. After doing it successfully for some time, for some reason, errors started to appear. Those errors happened because I had variables initialization within an exec() command so they weren't recognized by the interpreter. While changing those lines and removing unnecessary variables, I wrote one command that seems to be running just fine when executes in python console, but won't run in run time or debugging mode. Usually I use the console as a expression evaluator, so it helps me understand and correct wrong commands, but this time it seems to be the right command and still nothing happens when i'm running the script. This is the code, doc2text_path was initialized erlier: $newdir = "" exec("newdir = " + "doc2text_path%s" % scrape_number) The command executes and the value of newdir remains "". newdir is a new variable that i want to create, doc2txt_path is a string variable containing the path of a file I want to write in to later on. I have about 4 files like that one all referred to with variables in following name format: doc2text_path and a serial number: doc2text_path1 doc2text_path2 etc' That way i can use a for loop in order of referring to each one of them. thanks.
type: Question
linked to: http://stackoverflow.com/q/14241133
has title: why doesn't exec() work at run time, but work as a single command in python console
score: 0
duplicate of: http://stackoverflow.com/q/1373164
has comment: http://stackoverflow.com/comment/82818055
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82818126
duplicate of: http://stackoverflow.com/q/14241133
answer count: 0

http://stackoverflow.com/a/47969796
score: 1
downvote count: 1
has body: Add extra brackets when querying for multiple columns. import pandas as pd import numpy as np def myfunc1(row): C = row['A'] + 10 D = row['A'] + 50 return [C, D] df = pd.DataFrame(np.random.randint(0,10,size=(2, 2)), columns=list('AB')) df'C', 'D' = df.apply(myfunc1 ,axis=1)
upvote count: 2
answers question: http://stackoverflow.com/q/47969756
type: Answer

http://stackoverflow.com/a/47981636
score: 0
has body: To benchmark or profile your ideas, try using dis and timeit libraries that are built into Python. I'm using Python 2.7 on Windows 7 x64. import copy import dis import timeit def method_one(): def add_one(i): return i+1 orig_tuple = (1, 0, 0) new_tuple = (add_one(element) for element in orig_tuple) def method_two(): def add_one(i): return i+1 orig_tuple = (1, 0, 0) new_tuple = copy.deepcopy(orig_tuple) for i in new_tuple: i = add_one(i) print dis.dis(method_one) print timeit.timeit(method_one, number=10000) print dis.dis(method_two) print timeit.timeit(method_two, number=10000) Produced: D:\Users\user&gt;python help.py 6 0 LOAD_CONST 1 (&lt;code object add_one at 01DA6B60, file "help.py", line 6 &gt;) 3 MAKE_FUNCTION 0 6 STORE_DEREF 0 (add_one) 9 9 LOAD_CONST 5 ((1, 0, 0)) 12 STORE_FAST 0 (orig_tuple) 10 15 LOAD_CLOSURE 0 (add_one) 18 BUILD_TUPLE 1 21 LOAD_CONST 4 (&lt;code object &lt;genexpr&gt; at 01DA6CC8, file "help.py", line 10&gt;) 24 MAKE_CLOSURE 0 27 LOAD_FAST 0 (orig_tuple) 30 GET_ITER 31 CALL_FUNCTION 1 34 STORE_FAST 1 (new_tuple) 37 LOAD_CONST 0 (None) 40 RETURN_VALUE None 0.0088386 13 0 LOAD_CONST 1 (&lt;code object add_one at 020C6F50, file "help.py", line 1 3&gt;) 3 MAKE_FUNCTION 0 6 STORE_FAST 0 (add_one) 16 9 LOAD_CONST 4 ((1, 0, 0)) 12 STORE_FAST 1 (orig_tuple) 17 15 LOAD_GLOBAL 0 (copy) 18 LOAD_ATTR 1 (deepcopy) 21 LOAD_FAST 1 (orig_tuple) 24 CALL_FUNCTION 1 27 STORE_FAST 2 (new_tuple) 18 30 SETUP_LOOP 26 (to 59) 33 LOAD_FAST 2 (new_tuple) 36 GET_ITER &gt;&gt; 37 FOR_ITER 18 (to 58) 40 STORE_FAST 3 (i) 19 43 LOAD_FAST 0 (add_one) 46 LOAD_FAST 3 (i) 49 CALL_FUNCTION 1 52 STORE_FAST 3 (i) 55 JUMP_ABSOLUTE 37 &gt;&gt; 58 POP_BLOCK &gt;&gt; 59 LOAD_CONST 0 (None) 62 RETURN_VALUE None 0.1026118 As you can see, it looks like creating that generator is much faster. method_two was the only other way I could think of off the top of my head to do what you wanted to accomplish. If you have any other ideas, test them and edit your question if you need feedback…
has comment: http://stackoverflow.com/comment/82931746
type: Answer
answers question: http://stackoverflow.com/q/47981562

http://stackoverflow.com/comment/82986752
score: 1
has text: You could get rid of the `else` if you really want to.
type: QuestionComment
comment on: http://stackoverflow.com/q/48009265
type: Comment

http://stackoverflow.com/comment/82691055
comment on: http://stackoverflow.com/q/47862840
score: 0
has text: You probably have several pip scripts in different folders on your system and either PATH selects one of them or /usr/bin/pip symlinks to one of them. Try finding all executable files called pip\* on the system.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82957025
comment on: http://stackoverflow.com/a/47993539
has text: After I give to MenuScreen the 'id: menu' in kv file and in Button the 'on_release: menu.count = 20' property, I am receiving the following error: 'NameError: name 'menu' is not defined.'
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/82831991
type: AnswerComment
comment on: http://stackoverflow.com/a/47931000
score: 0
type: Comment
has text: @TylerNG `df1.index.str.split('-').str[0]`?

http://stackoverflow.com/q/47956746
answer count: 2
has comment: http://stackoverflow.com/comment/82883096
has comment: http://stackoverflow.com/comment/82883045
has answer: http://stackoverflow.com/a/58512476
upvote count: 6
linked to: http://stackoverflow.com/q/4700614
tagged with: figure
has comment: http://stackoverflow.com/comment/82882981
possible better answer: http://stackoverflow.com/a/58512476
linked to: http://stackoverflow.com/q/43967663
linked to: http://stackoverflow.com/q/21654635
has comment: http://stackoverflow.com/comment/82883060
linked to: http://stackoverflow.com/q/9012487
favorite count: 0
accepted answer: http://stackoverflow.com/a/47956856
has comment: http://stackoverflow.com/comment/82883074
has comment: http://stackoverflow.com/comment/82882962
score: 6
tagged with: python
has body: I'm fairly new to matplotlib and am limping along. That said, I haven't found an obvious answer to this question. I have a scatter plot I wanted colored by groups, and it looked like plotting via a loop was the way to roll. Here is my reproducible example, based on the first link above: import matplotlib.pyplot as plt import pandas as pd from pydataset import data df = data('mtcars').iloc[0:10] df['car'] = df.index fig, ax = plt.subplots(1) plt.figure(figsize=(12, 9)) for ind in df.index: ax.scatter(df.loc[ind, 'wt'], df.loc[ind, 'mpg'], label=ind) ax.legend(bbox_to_anchor=(1.05, 1), loc=2) # plt.show() # plt.savefig('file.png') Uncommenting plt.show() yields what I want: Searching around, it looked like plt.savefig() is the way to save a file; if I re-comment out plt.show() and run plt.savefig() instead, I get a blank white picture. This question, suggests this is cause by calling show() before savefig(), but I have it entirely commented out. Another question has a comment suggesting I can save the ax object directly, but that cuts off my legend: The same question has an alternative that uses fig.savefig() instead. I get the same chopped legend. There's this question which seems related, but I'm not plotting a DataFrame directly so I'm not sure how to apply the answer (where dtf is the pd.DataFrame they're plotting): plot = dtf.plot() fig = plot.get_figure() fig.savefig("output.png") Thanks for any suggestions. Edit: to test the suggestion below to try tight_layout(), I ran this and still get a blank white image file: fig, ax = plt.subplots(1) plt.figure(figsize=(12, 9)) for ind in df.index: ax.scatter(df.loc[ind, 'wt'], df.loc[ind, 'mpg'], label=ind) ax.legend(bbox_to_anchor=(1.05, 1), loc=2) fig.tight_layout() plt.savefig('test.png')
tagged with: savefig
has comment: http://stackoverflow.com/comment/82882903
linked to: http://stackoverflow.com/q/19555525
has comment: http://stackoverflow.com/comment/82883027
has answer: http://stackoverflow.com/a/47956856
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82883050
has comment: http://stackoverflow.com/comment/82883006
downvote count: 0
has title: Saving matplotlib subplot figure to image file
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/82883016
has comment: http://stackoverflow.com/comment/82883150
type: Question

http://stackoverflow.com/q/47941965
upvote count: 1
has comment: http://stackoverflow.com/comment/82854407
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/47943682
has title: Show Django template with a camera stream
has comment: http://stackoverflow.com/comment/82854021
answer count: 1
favorite count: 0
has body: I'm trying to build a simple website in Python with Django. I want to load and show a template, and then show, on top of the template's background, the images acquired from the webcam for few seconds. The images do not need to be shown as part of the template, it's ok if they are shown on top of it, on a separate window. The problem is that the template is loaded and showed only after the camera code finishes, i.e. I see the window with the camera stream, but only when it finishes the template is loaded. I'd like to have the template loaded and then the window shown. This is the code: from django.shortcuts import render def takePicture(request): temp = render(request,'pepper/picture.html') camstream() return temp camstream() is the method that activates the stream from the camera, and it works as expected. It uses pygame, following this tutorial. Any suggestion?
has comment: http://stackoverflow.com/comment/82856201
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47943682
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82853806
score: 1

http://stackoverflow.com/q/47954784
tagged with: exception
tagged with: python
type: AnsweredQuestion
upvote count: 3
tagged with: error-handling
tagged with: django
has title: Designing code for proper error handling in a Django / Python app?
type: Question
has answer: http://stackoverflow.com/a/47955054
score: 3
accepted answer: http://stackoverflow.com/a/47956482
has body: I'm in the midst of building a Django app and am hoping to get some advice on the proper way to handle errors and bugs in my code. Here's a common situation exemplary of the problems I have: a user purchases a product. To process the purchase, my views need to perform a number of actions: First, the view should create a User object in the database. If that is successful, the view should create an Order object and assign it to the newly-created User. If that is successful, my code should create a Product object and add it to the newly created Order. This is all well and good when no errors occur - but I find that the occasional error is inevitable in my code, and I want my app to deal with errors gracefully, rather than crashing outright. For example, if, for any reason, an Order object cannot be created, the view should show the user an error and remove the User object that was previously created. And, it should throw a graceful error message rather than crashing outright and serving the user a Http 500 error. The only way I can think of to do this is an extremely complex series of nested try / except clauses, like below. But designing my code this way is extremely messy and time-consuming, and it doesn't feel like the right way to do things. I know there must be a better way to design for proper error handling in Django and Python, but I'm not quite sure what it is. I would greatly appreciate any advice on how to better structure my code in this situation. Example code: try: # Create a new user u = User(email='test@test.com') u.save() try: # Create a new order o = Order(user=u, name='Order name') o.save() try: # Create a new product p = Product(order=o, name='Product name') p.save() # If a product cannot be created, print an error message and try deleting the user and order that were previously created except: messages.add_message(request, messages.ERROR, 'Product could not be created') # If deleting the order doesn't work for any reason (for example, o.save() didn…
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/47956482
favorite count: 0
possible better answer: http://stackoverflow.com/a/47955054

http://stackoverflow.com/comment/82913943
has text: Python uses as one of the design principles EAFP: **E**asier to **A**sk **F**orgiveness than **P**ermission. There is nothing wrong with using `try`-`except`.
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/47972136

http://stackoverflow.com/comment/82994552
type: Comment
type: QuestionComment
has text: okay i'll edit this question ..
comment on: http://stackoverflow.com/q/48012711
score: 0

http://stackoverflow.com/q/47877251
has comment: http://stackoverflow.com/comment/82720540
has comment: http://stackoverflow.com/comment/82720526
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82720438
tagged with: pyglet
accepted answer: http://stackoverflow.com/a/47877590
has answer: http://stackoverflow.com/a/47877403
type: Question
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/82720508
possible better answer: http://stackoverflow.com/a/47877403
has comment: http://stackoverflow.com/comment/82720568
has title: After installing pyglet, module has no Attributes or anything
has body: I just installed pyglet with pip3 to try some new things out. I go to try out some of the sample code from the pyglet website to create a window that displays some text. import pyglet window = pyglet.window.Window() The rest of the code is meaningless to continue on with because if I run the code I get: AttributeError: module 'pyglet' has no attribute 'window' So I figure okay, let me look and see what's inside the module. help(pyglet) And all I get is: Help on package pyglet: NAME pyglet PACKAGE CONTENTS FILE (built-in) (END) What I don't understand is why the module has nothing in it? Also, I did install pyglet with pip install before and for some reason it doesn't import with python2. If I run it with python2 I get: ImportError: No module named pyglet But pip list shows that I do have it as does pip3.
tagged with: python
has answer: http://stackoverflow.com/a/47877590

http://stackoverflow.com/comment/82872358
type: QuestionComment
comment on: http://stackoverflow.com/q/47945785
score: 0
has text: f1 and f2 can be in single sentence. I will miss out the feature that I need to capture if they are in the same sentences.
type: Comment

http://stackoverflow.com/a/52859204
type: Answer
answers question: http://stackoverflow.com/q/47878933
has body: I don't know if you managed to get this sorted but if you add ItemPage="#" it will return that page number of results. response = amazon.ItemSearch(Keywords=searchTerm, SearchIndex="All", ItemPage="2") I have recently just found this out myself. I think it has to do with the arguments being encoded into the URL as parameters so some of them off the API reference sheet work but maybe not all.
score: 0

http://stackoverflow.com/comment/82800660
comment on: http://stackoverflow.com/a/47916091
score: 0
type: AnswerComment
has text: it works fine now, thanks but it doesn't add up all the values monthly
type: Comment

http://stackoverflow.com/comment/82753498
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47893393
has text: What if you `w.show()` after `w.setLayout`?
score: 0

http://stackoverflow.com/q/47924520
accepted answer: http://stackoverflow.com/a/47924547
has title: lambda with reduce error in Python3
favorite count: 0
has body: I am trying to use reduce as follows: &gt;&gt;&gt; reduce(lambda z,(x,y): (z+1) if x == y else z, [(3, 4), (5, 2), (4, 4), (5, 5)], 0) In Python 2.7 I get the expected: 2 While the exact same line returns the following error in Python 3.5: File "&lt;stdin&gt;", line 1 reduce(lambda z,(x,y): (z+1) if x == y else z, [(3, 4), (5, 2), (4, 4), (5, 5)], 0) ^ SyntaxError: invalid syntax Any suggestions as to what the syntax should be for Python 3? Thanks.
tagged with: python
duplicate of: http://stackoverflow.com/q/21892989
upvote count: 2
tagged with: lambda
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47924547
tagged with: reduce
has comment: http://stackoverflow.com/comment/82816578
linked to: http://stackoverflow.com/q/21892989
type: Question
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82817121

http://stackoverflow.com/comment/82868267
type: QuestionComment
comment on: http://stackoverflow.com/q/47949071
has text: ...the big reason this question is frowned on, by the way, is that in asking for "the best" X, when there are a whole lot of implementations of X around, it gets towards being an opinion poll or a recommendation request (see #2 in "some questions are still off-topic" at https://stackoverflow.com/help/on-topic) rather than something where a canonical, objectively complete and correct answer exists.
score: 0
type: Comment

http://stackoverflow.com/comment/82744937
score: 0
type: Comment
type: QuestionComment
has text: I'm new to python and it'd take me a lot of time to learn the ethics of coding in Python. btw could you please give me the line number to place global variable into my code @furas
comment on: http://stackoverflow.com/q/47889011

http://stackoverflow.com/comment/82791405
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47911694
has text: I think you want to give your grouper an aggregation function. `df.groupby(['A', 'B'])` gives you a weird groupby object without any aggregation yet, `df.groupby(['A', 'B']).sum()` or `df.groupby(['A', 'B']).mean()` will give you a dataframe you can iterate through like any other, using `df.iterrows().`

http://stackoverflow.com/q/47946239
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/82862454
type: Question
has comment: http://stackoverflow.com/comment/82961351
type: AnsweredQuestion
tagged with: pytest
has title: Pattern for reading and writing files with pytest
upvote count: 4
has answer: http://stackoverflow.com/a/48004379
downvote count: 0
answer count: 1
has body: constants.py import os BASE_PATH = os.path.abspath(os.path.dirname(__file__)) INPUT_PATH = os.path.join(BASE_PATH, 'input') FILE_INPUT1_PATH = os.path.join(INPUT_PATH, 'input1.csv') FILE_INPUT2_PATH = os.path.join(INPUT_PATH, 'input2.csv') PROCESSED_PATH = os.path.join(BASE_PATH, 'processed') FILE_PROC1_PATH = os.path.join(PROCESSED_PATH, 'processed1.pkl') FILE_PROC2_PATH = os.path.join(PROCESSED_PATH, 'processed2.pkl') structure dir: root |__ constant.py |__ input |__ input1.csv |__ input2.csv |__ process |__ processed1.pkl |__ processed2.pkl data_handling.py from constants import FILE_INPUT1_PATH, FILE_INPUT2_PATH, FILE_PROC1_PATH, FILE_PROC2_PATH def foo(*args): file = FILE_INPUT1_PATH # Here it is doing staff # Finally I write data into FILE_PROC1_PATH def bar(*args): file = FILE_INPUT2_PATH # Here it is doing staff # Finally I write data into FILE_PROC2_PATH Currently I'm trying to use pytest and testing foo() and bar() but I don't know how to proceed due to input files and processed files are too big and test process musn't override processed files. One approach is to change definition bar() to bar(path) and then call bar(FILE_INPUT2_PATH) but that it isn't make sense in the code because bar always needs to read FILE_INPUT2_PATH and it is called in many places. Unit test for foo() and bar() would test if the processed files were created or not because it depends on *args. So... question is how can I solve it? Does a pattern/good practice exists for this case? What should I change in my code?
linked to: http://stackoverflow.com/q/27252840
favorite count: 0
accepted answer: http://stackoverflow.com/a/48004379

http://stackoverflow.com/q/47916457
has comment: http://stackoverflow.com/comment/82801070
upvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82801064
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82801123
linked to: http://stackoverflow.com/q/240178
has comment: http://stackoverflow.com/comment/82821575
tagged with: python
has title: Make Robot Walk Path in Python
has comment: http://stackoverflow.com/comment/82801025
duplicate of: http://stackoverflow.com/q/240178
tagged with: list
downvote count: 1
type: Question
has body: So this problem was given as an end of the class quiz. I didnt have time to test it out so I tried re-writting it and testing. However for some reason its not working the way I want it and I dont know why. So you've got a nxn grid given as lists. A robot with an initial starting point given as a tuple. And the path the robot will travel given as "N", "S", "E", "W" within a list. so input would be something like make_grid(starting_point, path, size_of_grid) make_grid((0,0),["S","E","S","S"],4) with an output like [".","_","_","_"],[".",".","_","_"],["_",".""_""_"],["_",".""_""_"] where the "." is the robots starting point and traveled path. The "_" are the untraveled areas of the grid. And if it hits the border it stays in the exact same spot. My problem is the result is that it marks the whole column as a traveled path with a period def check(coord ,size): if ((coord&lt;0) or (coord&gt;size)): return True else: return False def make_grid(start, path, size): n = 0 row = [] while (n &lt; size): row.append("_") n += 1 n = 1 grid = [row] while ( n &lt; size): grid.append(row) n +=1 x = start[0] y = start[1] grid[x][y] = "." n = 0 while (n &lt; len(path)): if (path[n] == "N"): x -= 1 if (check(x,size)): x += 1 elif (path[n] == "E"): y += 1 if (check(y,size)): y -= 1 elif (path[n] == "S"): x +=1 if (check(x,size)): x -=1 elif (path[n] == "W"): y -=1 if (check(y,size)): y += 1 grid[x][y] = "." n += 1 n = 0 while (n &lt; size): print grid[n] n += 1
score: -1
has answer: http://stackoverflow.com/a/47916845

http://stackoverflow.com/comment/83172661
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48012696
has text: When I run the script my webcam sees it (the green 'on' light shows itself shortly) thanks for all of the help anyway, I'm still struggling to get it working..
score: 0

http://stackoverflow.com/comment/82687540
comment on: http://stackoverflow.com/q/47858950
type: Comment
type: QuestionComment
has text: @Jean-FrançoisFabre thank you for your response. That seemed to work just fine. Also, apologies for the duplicate question. I do have one last question: If i needed to modify my code to add a sorting feature that would sort all the file information by file size, how would I do that? I feel like I would need to pass the information through a list or array prior to sorting, but I'm not sure how to begin.
score: 0

http://stackoverflow.com/a/47929834
has comment: http://stackoverflow.com/comment/82828400
has comment: http://stackoverflow.com/comment/82828265
answers question: http://stackoverflow.com/q/47929785
score: 0
has comment: http://stackoverflow.com/comment/82828327
has body: Try using os.chmod as seen here https://docs.python.org/3/library/os.html#os.chmod to change permissions To execute you can use subprocess.Popen(["executable_file"], stdout=subprocess.PIPE)
type: Answer

http://stackoverflow.com/q/47952987
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47953652
score: 9
tagged with: brute-force
has comment: http://stackoverflow.com/comment/82875314
tagged with: python
answer count: 4
has body: So I was trying to make a program that brute forces passwords. Firstly, I made a program for a password of length 1: password = input('What is your password?\n') chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' def brute_force(): for char in chars: if char == password: return char print(brute_force()) Then I edited it for a password of length 2: def brute_force(): guess = [None, None] for char in chars: guess[0] = char for char2 in chars: guess[1] = char2 if ''.join(guess) == password: return ''.join(guess) Finally I did the same for a password of length 3: def brute_force(): guess = [None, None, None] for char in chars: guess[0] = char for char2 in chars: guess[1] = char2 for char3 in chars: guess[2] = char3 if ''.join(guess) == password: return ''.join(guess) How could I generalize this for a variable called length which contains the integer value of the lenght of the password?
possible better answer: http://stackoverflow.com/a/47953652
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82881339
has answer: http://stackoverflow.com/a/47953137
upvote count: 10
downvote count: 1
has answer: http://stackoverflow.com/a/47953073
type: Question
has answer: http://stackoverflow.com/a/47953095
accepted answer: http://stackoverflow.com/a/47953095
has title: How to make all of the permutations of a password for brute force?
tagged with: permutation
favorite count: 0

http://stackoverflow.com/a/47877557
upvote count: 2
has body: You can use break up your df and group then concatenate back: pd.concat([df.query('measure == 3'), df.query('measure != 3') .groupby(['H#','measure'],as_index=False)['D','N'] .agg('sum')]) Output: H# measure D N 3 12843 3 1 4 4 20000 3 1 5 5 20000 3 1 0 6 20000 3 2 0 0 12843 1 3 6 1 20000 2 2 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47877485
type: Answer
answers question: http://stackoverflow.com/q/47877485
score: 2

http://stackoverflow.com/a/47911903
accepted answer of: http://stackoverflow.com/q/47899753
type: Answer
has comment: http://stackoverflow.com/comment/82800985
answers question: http://stackoverflow.com/q/47899753
upvote count: 4
has body: If you're using Lambda Proxy integration, you are responsible for returning a proper response whether its a success or an exception. You can do so by catching the exception. def handler(event, context): try: return { 'statusCode': 200, 'body': json.dumps({ 'hello': 'world' }) } except BadRequestError: return { 'statusCode': 400, 'body': json.dumps({ 'error': 'Bad Request Error' }) } except: return { 'statusCode': 500, 'body': json.dumps({ 'error': 'Internal Server Error' }) }
type: AcceptedAnswer
downvote count: 0
score: 4

http://stackoverflow.com/a/47949327
has comment: http://stackoverflow.com/comment/91448188
answers question: http://stackoverflow.com/q/47856247
score: 19
accepted answer of: http://stackoverflow.com/q/47856247
has comment: http://stackoverflow.com/comment/125964549
has body: This might help you. from __future__ import unicode_literals import spacy,en_core_web_sm import textacy nlp = en_core_web_sm.load() sentence = 'The author is writing a new book.' pattern = r'&lt;VERB&gt;?&lt;ADV&gt;*&lt;VERB&gt;+' doc = textacy.Doc(sentence, lang='en_core_web_sm') lists = textacy.extract.pos_regex_matches(doc, pattern) for list in lists: print(list.text) Output: is writing On how to highlight the verb phrases do check the link below. Highlight verb phrases using spacy and html Another Approach: Recently observed Textacy has made some changes to regex matches. Based on that approach i tried this way. from __future__ import unicode_literals import spacy,en_core_web_sm import textacy nlp = en_core_web_sm.load() sentence = 'The cat sat on the mat. He dog jumped into the water. The author is writing a book.' pattern = [{'POS': 'VERB', 'OP': '?'}, {'POS': 'ADV', 'OP': '*'}, {'POS': 'VERB', 'OP': '+'}] doc = textacy.make_spacy_doc(sentence, lang='en_core_web_sm') lists = textacy.extract.matches(doc, pattern) for list in lists: print(list.text) Output: sat jumped writing I checked the POS matches in this links seems the result is not the intended one. [https://explosion.ai/demos/matcher][1] Did anybody try framing POS tags instead of Regexp pattern for finding Verb phrases? Edit 2: import spacy from spacy.matcher import Matcher from spacy.util import filter_spans nlp = spacy.load('en_core_web_sm') sentence = 'The cat sat on the mat. He quickly ran to the market. The dog jumped into the water. The author is writing a book.' pattern = [{'POS': 'VERB', 'OP': '?'}, {'POS': 'ADV', 'OP': '*'}, {'POS': 'AUX', 'OP': '*'}, {'POS': 'VERB', 'OP': '+'}] # instantiate a Matcher instance matcher = Matcher(nlp.vocab) matcher.add("Verb phrase", None, pattern) doc = nlp(sentence) # call the matcher to find matches matches = matcher(doc) spans = [doc[start:end] for _, start, end in matches] print (filter_spans(spans)) Output: [sat, quickly ran, jumped, is writing] Based on h…
has comment: http://stackoverflow.com/comment/91448172
upvote count: 19
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91266158
type: Answer

http://stackoverflow.com/comment/82826637
has text: You can use the AWS SDK to create a scheduled cloudwatch event rule (schedule trigger) from inside function A (at the end) to invoke function B and make sure to delete the cloudwatch event rule inside function B
comment on: http://stackoverflow.com/q/47923452
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/125901491
type: Comment
has text: How does this work for a project of the form 'python -m mydir.main', which is what @AlienWebGuy asked initially?
comment on: http://stackoverflow.com/a/52831592
type: AnswerComment
score: 0

http://stackoverflow.com/q/47880332
type: Question
has comment: http://stackoverflow.com/comment/82726940
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82767974
has title: convert a embedded json string into pandas dataframe
has comment: http://stackoverflow.com/comment/82726782
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/47880632
has comment: http://stackoverflow.com/comment/82726800
favorite count: 0
has comment: http://stackoverflow.com/comment/82726671
has comment: http://stackoverflow.com/comment/82726679
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82726733
has body: I have following data: json_str = "[{“key1”: “value1”, “key2”= “value2”, “key3”: “{“key_a”: “value_a1”, “key_b”: “value_b1”, “key_c”: “value_c1”}”,“key4”: 4}, {“key1”: “value5”, “key2”= “value6”, “key3”: “{“key_a”: “value_a2”, “key_b”: “value_b2”, “key_c”: “value_c2”}”,“key4”: 8}]" which i want to convert into pandas DataFrame. i have tried this : #code1 data = pd.read_json(json_str) print(data) #code2 data = pd.read_json(json_str, typ ='series') print(data) #code3 data = pd.DataFrame.from_dict([json_str], orient='columns', dtype= None) print(data) #same output ValueError: Unexpected character found when decoding object value Again: data = json.loads(json_str) print(data) enter code here error : json.decoder.JSONDecodeError: Expecting ',' delimiter I couldnot use .replace() as i need to have a column name "key3" which contains JSON values for eg: {“key_a”: “value_a1”, “key_b”: “value_b1”, “key_c”: “value_c1”}
has comment: http://stackoverflow.com/comment/82726614
downvote count: 1
has comment: http://stackoverflow.com/comment/82726727
has comment: http://stackoverflow.com/comment/82726752
tagged with: http://stackoverflow.com/tag/json
score: -1
has comment: http://stackoverflow.com/comment/82726987

http://stackoverflow.com/a/47886589
has body: The way you're doing it right now will actually just overwrite the classifier for each chunk in your training data as you're creating a new SklearnClassifier object each time. What you need to do is instantiate the SklearnClassifier prior to getting into the training loop. However, looking at the code here, it appears that the NLTK SklearnClassifier uses the fit method of the underlying Sklearn model. This means that you can't actually update a model once it is trained. What you need to do is instantiate the Sklearn model directly and use the partial_fit method. Something like this should work: from nltk.classify.scikitlearn import SklearnClassifier from sklearn.naive_bayes import MultinomialNB clf = MultinomialNB() # must instantiate classifier outside of the loop or it will just get overwritten while True: training_set, proceed = download_chunk() # pseudo clf.partial_fit(training_set) if not proceed: break At the end, you'll have a MultinomialNB() classifier that has been trained on each chunk of your data. Typically, if the whole dataset will fit in memory, it is somewhat more performant to just download the whole thing and call fit once (in which case you could actually use the nltk SklearnClassifier). See the notes about the partial_fit method here. However, if you are unable to fit the entire set in memory, it is certainly common practice to train on chunks of the data. You can do this by making several calls to the database or by extracting all of the information from the database, placing it in a CSV on your hard drive, and reading chunks of it from there. Note If you're using a shared database with other users, the DBAs may prefer you to extract all of it at once as once as this would (probably) take up fewer DB resources than making several separate, smaller calls to the database would.
answers question: http://stackoverflow.com/q/47886227
has comment: http://stackoverflow.com/comment/82739055
has comment: http://stackoverflow.com/comment/82738991
score: 7
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82739366
has comment: http://stackoverflow.com/comment/82739437
type: Answer
has comment: http://stackoverflow.com/comment/82739659
accepted answer of: http://stackoverflow.com/q/47886227
has comment: http://stackoverflow.com/comment/82739689
upvote count: 7

http://stackoverflow.com/comment/82716549
has text: @schwobaseggl Could you put that in an answer so I can mark it as such (and give you the points you deserve)?
score: 0
comment on: http://stackoverflow.com/q/47875439
type: Comment
type: QuestionComment

error-handling
tags question: http://stackoverflow.com/q/47892530
tag name: error-handling
tags question: http://stackoverflow.com/q/47935881
tags question: http://stackoverflow.com/q/47975539
tags question: http://stackoverflow.com/q/47995757
tags question: http://stackoverflow.com/q/47954784
tags question: http://stackoverflow.com/q/47975705
tags question: http://stackoverflow.com/q/47972594
tags question: http://stackoverflow.com/q/47989446
type: Tag

http://stackoverflow.com/q/47989609
tagged with: loops
type: Question
upvote count: 0
score: -2
answer count: 1
favorite count: 0
has title: I want to create a column loop in Python
has answer: http://stackoverflow.com/a/47999588
has comment: http://stackoverflow.com/comment/82947836
has comment: http://stackoverflow.com/comment/82948505
type: UnansweredQuestion
downvote count: 2
tagged with: openpyxl
tagged with: python
tagged with: excel
has comment: http://stackoverflow.com/comment/82948433
has comment: http://stackoverflow.com/comment/82948544
has body: I want to create a loop in Excel using openpyxl, everything works perfectly, updates my column, but when saving I only value the last value of the last column. from openpyxl import Workbook x = 1 while True: wb = Workbook() ws = wb.active ws['A' + str(x)] = 42 wb.save("test.xlsx") y = input("dasdsa :") if y == "ESC": break else: x += 1 continue'

http://stackoverflow.com/a/47949174
downvote count: 0
has comment: http://stackoverflow.com/comment/129667490
type: Answer
has comment: http://stackoverflow.com/comment/126034099
has comment: http://stackoverflow.com/comment/126025553
score: 18
answers question: http://stackoverflow.com/q/47949173
has body: Heroku doesn't care if you're using virtualenv or conda to manage environments. Using one or the other is mostly irrelevant to the deployment process. Don't bother with the Conda Environment Buildpack instructions since those are for deploying a remote conda environment which is not what you are trying to do. You, my friend, are trying to deploy a remote your_app environment. Here's how to do that with a dash application and conda: Create a new folder for your project: $ mkdir dash_app_example $ cd dash_app_example Initialize the folder with git $ git init # initializes an empty git repo Create an environment.yml file in dash_app_example: name: dash_app #Environment name dependencies: - python=3.6 - pip: - dash - dash-renderer - dash-core-components - dash-html-components - plotly - gunicorn # for app deployment Create the environment from environment.yml: $ conda env create Activate the conda environment $ source activate dash_app #Writing source is not required on Windows Confirm that the environment you're in is correct. It should currently be in dash_app: $ conda info --envs #Current environment is noted by a * Initialze the folder with app.py, requirements.txt, and a Procfile: app.py import dash import dash_core_components as dcc import dash_html_components as html import os app = dash.Dash(__name__) server = app.server app.css.append_css({"external_url": "https://codepen.io/chriddyp/pen/bWLwgP.css"}) app.layout = html.Div([ html.H2('Hello World'), dcc.Dropdown( id='dropdown', options=[{'label': i, 'value': i} for i in ['LA', 'NYC', 'MTL']], value='LA' ), html.Div(id='display-value') ]) @app.callback(dash.dependencies.Output('display-value', 'children'), [dash.dependencies.Input('dropdown', 'value')]) def display_value(value): return 'You have selected "{}"'.format(value) if __name__ == '__main__': app.run_server(debug=True) Procfile web: gunicorn app:server requirements.txt: describes your Python dependencies. You can fill this file in automatically by running…
upvote count: 18
accepted answer of: http://stackoverflow.com/q/47949173
has comment: http://stackoverflow.com/comment/91800388
type: AcceptedAnswer

http://stackoverflow.com/a/47877630
has body: To compute the squared euclidean distance for each pair of elements off them - x and y, we need to find : (Xik-Yjk)**2 = Xik**2 + Yjk**2 - 2*Xik*Yjk and then sum along k to get the distance at coressponding point as dist(Xi,Yj). Using associativity, it reduces to : dist(Xi,Yj) = sum_k(Xik**2) + sum_k(Yjk**2) - 2*sum_k(Xik*Yjk) Bringing in matrix-multiplication for the last part, we would have all the distances, like so - dist = sum_rows(X^2), sum_rows(Y^2), -2*matrix_multiplication(X, Y.T) Hence, putting into NumPy terms, we would end up with the euclidean distances for our case with a and b as the inputs, like so - np.sqrt((a**2).sum(1)[:,None] + (b**2).sum(1) - 2*a.dot(b.T)) Leveraging np.einsum, we could replace the first two summation-reductions with - np.einsum('ij,ij-&gt;i',a,a)[:,None] + np.einsum('ij,ij-&gt;i',b,b) More info could be found on eucl_dist package's wiki page (disclaimer: I am its author).
upvote count: 5
score: 5
downvote count: 0
answers question: http://stackoverflow.com/q/47877530
type: Answer

http://stackoverflow.com/comment/82844262
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47937366
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/161791/discussion-between-shiva-and-nishanth).
score: 0

http://stackoverflow.com/comment/82820421
has text: Thank you for the clue, since these resources are to be hosted on a CoAP server so i used coap uri, and it worked
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47892990

http://stackoverflow.com/comment/82756558
has text: I may be missing something but if you've figured out how to update the sprites and the display when you press a key you should be pretty close. You could add waypoint_active (default = False) and waypoint_index (default = 0) properties to the Car class. A key press sets waypoint_active to True and some logic in your main event loop checks waypoint_active == True then sets the car position based on the waypoint at the index position and increments the waypoint_index.
comment on: http://stackoverflow.com/q/47894415
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83121545
score: 0
has text: i finally could test ist i got on the `echo $PATH` the answer `/usr/local/bin:/usr/bin`
type: AnswerComment
comment on: http://stackoverflow.com/a/47944563
type: Comment

http://stackoverflow.com/a/47966575
answers question: http://stackoverflow.com/q/47966494
has body: Use variable instead of constant there : So first step just extract the len() of your description and save that len to a variable : len_= int(response.xpath('.//*[@class="txtGrey size14-description"]/text()').extract()) Then just check by if condition : if len(len_)==4: If above condition is true then execute below code : Second step now use that variable as index_no for slicing : description = response.xpath('.//*[@class="txtGrey size14-description"]/text()').extract()[-len_:]
type: Answer
has comment: http://stackoverflow.com/comment/82911448
has comment: http://stackoverflow.com/comment/82903478
downvote count: 1
has comment: http://stackoverflow.com/comment/82903011
score: -1
has comment: http://stackoverflow.com/comment/82902993
accepted answer of: http://stackoverflow.com/q/47966494
has comment: http://stackoverflow.com/comment/82903411
upvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/a/47861734
score: 1
has body: set(s.lower()) # gives unique elements in lower case and s.lower().count(c)&gt;1 #checks if an element shows up more than once All in all the function finds number of not unique elements in a string ,ignoring case. I believe using collections.Counter is more efficient: In [7]: from collections import Counter In [8]: sum(v &gt; 1 for v in Counter("Aabcc".lower()).values()) Out[8]: 2
answers question: http://stackoverflow.com/q/47861656
has comment: http://stackoverflow.com/comment/82688458
upvote count: 1
type: Answer
downvote count: 0

http://stackoverflow.com/q/47999652
has title: Selenium not locating xpath element
tagged with: python
score: 1
tagged with: xpath
tagged with: selenium-chromedriver
tagged with: selenium
upvote count: 1
answer count: 1
has body: I'm running Selenium to download a sample PdF file and open it in Chrome but for some reason, I can't manage to get Selenium to click on the first result in the downloads section. The XPath has been specified but it just won't click on the element, the process is just aborted due to a timeout error (below). Please, does anyone have any ideas of what I am doing wrong? ====================================================================== ERROR: testSearch (__main__.InitialSearch) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/Josh/PycharmProjects/ideqcomps/test.py", line 33, in testSearch lambda driver: driver.find_elements_by_xpath(downloaded_file_XPath)) File "/Users/Josh/Library/Python/3.6/lib/python/site-packages/selenium/webdriver/support/wait.py", line 80, in until raise TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message: ---------------------------------------------------------------------- Ran 1 test in 24.415s FAILED (errors=1) Process finished with exit code 1 Here is the code I'm running: from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait import unittest class InitialSearch(unittest.TestCase): def setUp(self): options = webdriver.ChromeOptions() self.driver = webdriver.Chrome(chrome_options=options) self.driver.get("https://wetransfer.com/downloads/5451e039a782938826861676664ae91a20171227191356/a45960") def testSearch(self): driver = self.driver download_button_xpath = '//*[@id="file-link"]' agree_xpath = '//*[@id="5451e039a782938826861676664ae91a20171227191356"]/div/div[2]/button' downloaded_file_xpath = '//*[@id="downloads-list"]/downloads-item[1]' # Click on agree to terms button agree_element = WebDriverWait(driver, 10).until( lambda driver: driver.find_element_by_xpath(agree_xpath)) agree_element.click() # Click on download button download_button_element = WebDriverWait(driver, 10).until( lambda dr…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82976030
downvote count: 0
has answer: http://stackoverflow.com/a/47999797
favorite count: 0
has comment: http://stackoverflow.com/comment/82973648
type: Question

http://stackoverflow.com/a/47864487
accepted answer of: http://stackoverflow.com/q/47862345
score: 3
type: AcceptedAnswer
downvote count: 0
has body: The documentation says: The sqlite3 module supports two kinds of placeholders: question marks (qmark style) and named placeholders (named style). Here’s an example of both styles: # This is the qmark style: cur.execute("insert into people values (?, ?)", (who, age)) # And this is the named style: cur.execute("select * from people where name_last=:who and age=:age", {"who": who, "age": age}) Keyword arguments are not supported. However, you could explicitly convert them into a dictionary (or write a wrapper for execute that does this): db.execute("SELECT ... :username", dict(username = username))
has comment: http://stackoverflow.com/comment/82709219
type: Answer
answers question: http://stackoverflow.com/q/47862345
upvote count: 3

http://stackoverflow.com/comment/98419525
type: Comment
score: 13
comment on: http://stackoverflow.com/a/49932648
has text: A little misleading since your `path()` example allows non-four-digit numbers.
type: AnswerComment

http://stackoverflow.com/comment/82947636
type: Comment
comment on: http://stackoverflow.com/a/47972962
has text: its happens , no worries bro chill we can't change their behaviour :)
type: AnswerComment
score: 0

http://stackoverflow.com/q/47936150
tagged with: django
tagged with: python
has body: My sauce is below. Elements in the template created using render_to_string are not Jquery controls. ▶ index.html {% extends 'common/base.html' %} {% block contents %} {% endblock %} {% block jquery %} {% endblock %} ▶ index.js $(function() { show_inf_list('0','0','0','0','0'); function show_inf_list(section, selection, ordering, start, limit){ $.ajax({ url:'/campaign/list/', data:{ 'campaign_section': section, 'selection_type': selection, 'ordering_type': ordering, 'start': start, 'limit': limit }, dataType:'json', success: function (data) { $('#prod_list').html(data.campaign_list); } }); } $('a[name=btn_like]').on('click', function (e) { e.preventDefault() console.log('a'); return false; }); }); ▶ views.py def ... data['campaign_list'] = render_to_string( 'main/include/prod_list.html', context=context, request=request ) return JsonResponse(data) ▶ prod_list.html {% if user.influencer in campaign.like_users.all %} {% else %} {% endif %} I want control 'btn_like' element But, I can't control the 'a[name=btn_like]' How to use Jquery Control in element of render_to_string template?
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/47939832
accepted answer: http://stackoverflow.com/a/47939832
type: Question
tagged with: render-to-string
answer count: 1
downvote count: 0
tagged with: javascript
tagged with: jquery
upvote count: 1
favorite count: 0
has title: Python3 + Django : How to use Jquery in render_to_string template?

http://stackoverflow.com/comment/82715931
comment on: http://stackoverflow.com/q/47871639
score: 3
has text: @beasy: It is *either* two dots *or* three, depending on how you want it to behave at the end of the range.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82903108
type: QuestionComment
has text: Actually I originally used "data"(not " full data") in my original code. But for the community to understand it i just replaced it with full data. Let me rephrase the whole question again. Then plzz help me with my problem. :)
comment on: http://stackoverflow.com/q/47966602
score: 0
type: Comment

http://stackoverflow.com/a/47993140
type: Answer
downvote count: 0
score: 1
has body: You can access the value of Slider pretty much like how you would access the property of any other object. By doing myslider = Slider(min=0,max=100,value=50) myslider.value Here is an example of a BoxLayout having a Button and a Slider. Click on the button would print the current value of the Slider class MyWidget(BoxLayout): def __init__(self, *args): super(MyWidget, self).__init__() self.orientation = 'vertical' self.myslider = Slider(min=-100, max=100, value=25) self.add_widget(self.myslider) # Add the slider self.mybutton = Button(text='Click to get slider val') self.add_widget(self.mybutton) # Add button self.mybutton.bind(on_press=self.onclickgetval) # bind button to print slider value def onclickgetval(self,instance): print(self.myslider.value) class MyRandomApp(App): def build(self): return MyWidget() if __name__ == '__main__': MyRandomApp().run() Please Note While writing everything in Python works, it can look a little messy, which is why you should make extensive use of .kv file. Its extremely easy, much more intuitive and understandable.
upvote count: 1
has comment: http://stackoverflow.com/comment/83022123
answers question: http://stackoverflow.com/q/47978366
has comment: http://stackoverflow.com/comment/83017918
has comment: http://stackoverflow.com/comment/83022521

http://stackoverflow.com/q/47989418
tagged with: python
has answer: http://stackoverflow.com/a/64616828
has comment: http://stackoverflow.com/comment/82975315
has comment: http://stackoverflow.com/comment/82975327
has comment: http://stackoverflow.com/comment/82947402
has comment: http://stackoverflow.com/comment/82947484
tagged with: python-multiprocessing
type: Question
upvote count: 33
has comment: http://stackoverflow.com/comment/114074513
has comment: http://stackoverflow.com/comment/82968910
has title: Multiprocessing python program inside Docker
has answer: http://stackoverflow.com/a/64523210
has body: I am trying to test multiprocessing for python inside a docker container but even, if the processes are created successfully (I have 8 CPUs and 8 processes are created), they always take only one physical CPU. Here is my code: from sklearn.externals.joblib.parallel import Parallel, delayed import multiprocessing import pandas import numpy from scipy.stats import linregress import random import logging def applyParallel(dfGrouped, func): retLst = Parallel(n_jobs=multiprocessing.cpu_count())(delayed(func)(group) for name, group in dfGrouped) return pandas.concat(retLst) def compute_regression(df): result = {} (slope,intercept,rvalue,pvalue,stderr) = linregress(df.date,df.value) result["slope"] = [slope] result["intercept"] = [intercept] return pandas.DataFrame(result) if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logging.info("start") random_list = [] for i in range(1,10000): for j in range(1,100): random_list.append({"id":i,"date":j,"value":random.random()}) df = pandas.DataFrame(random_list) df = applyParallel(df.groupby('id'), compute_regression) logging.info("end") I tried multiple docker options when I launch like --cpus or --cpuset but it is always using only 1 physical CPUs. Is it an issue in Docker, python, the OS? Docker version is 1.13.1 The result of the cpu_count(): &gt;&gt;&gt; import multiprocessing &gt;&gt;&gt; multiprocessing.cpu_count() 8 During the run, here is a top. We can see the main process and the 8 child processes but I find the percentages weird. And then, if I change to 4 processes, total amount of CPU used is always the same:
has comment: http://stackoverflow.com/comment/88932527
has answer: http://stackoverflow.com/a/64619127
score: 33
tagged with: docker
has answer: http://stackoverflow.com/a/64598493
has comment: http://stackoverflow.com/comment/114112522
has answer: http://stackoverflow.com/a/47990475
downvote count: 0
has comment: http://stackoverflow.com/comment/82947723
favorite count: 0
has comment: http://stackoverflow.com/comment/82976931
has comment: http://stackoverflow.com/comment/88933842
answer count: 5
type: UnansweredQuestion

http://stackoverflow.com/q/47890011
has title: Passing Arcpy environment variable to R from R script
tagged with: python
type: AnsweredQuestion
tagged with: arcpy
has answer: http://stackoverflow.com/a/47890384
type: Question
tagged with: http://stackoverflow.com/tag/r
tagged with: system
score: 0
accepted answer: http://stackoverflow.com/a/47890384
answer count: 1
has body: I am working with an R script and am trying to pass an environment variable from Python into a variable that I can work with in R. I have written a very simple python script which gets the variable I am looking for - when run as a standalone Python script it prints the path fine. Here is the very simple Python script saved as pathgetter.py: import arcpy print(arcpy.env.scratchFolder) I then call this Python script in my R script with the following line: tmp &lt;- system("python -c 'C:/coa/script_tool/pathgetter.py'", intern=TRUE) However, the variable that is stored in R is character(0). I would like the tmp variable in R to contain the path that is printed in the Python script. Does anyone have any suggestions for changes?

http://stackoverflow.com/q/47863634
score: 1
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/82700328
has answer: http://stackoverflow.com/a/47867893
has title: Python Tkinter TclError
upvote count: 2
has answer: http://stackoverflow.com/a/47864016
linked to: http://stackoverflow.com/q/16059592
downvote count: 1
has comment: http://stackoverflow.com/comment/82692136
favorite count: 0
tagged with: tkinter
type: UnansweredQuestion
has body: I designed an arc which can rotate, but I can't figure out why IDLE tells me there is still an error in my code. Here is my code: from Tkinter import* from math import * from time import sleep pai=Tk() cv=Canvas(pai,width=1100,height=631,bg="white") cv.pack() bb=(150,110,550,510) temp1=0 temp2=24 t=0 arc1=cv.create_arc(bb,start=temp1,extent=temp2,fill="yellow") while True: t=0.51 temp1+=t cv.itemconfig(arc1,start=temp1) cv.update() And this is the results: Traceback (most recent call last): File "C:\Users\amazi\Desktop\作业\s.py", line 15, in &lt;module&gt; cv.itemconfig(arc1,start=temp1) File "C:\Python27\lib\lib-tk\Tkinter.py", line 2408, in itemconfigure return self._configure(('itemconfigure', tagOrId), cnf, kw) File "C:\Python27\lib\lib-tk\Tkinter.py", line 1321, in _configure self.tk.call(_flatten((self._w, cmd)) + self._options(cnf)) TclError: invalid command name ".93591304L"
has comment: http://stackoverflow.com/comment/82693553
tagged with: python
has comment: http://stackoverflow.com/comment/82693605

http://stackoverflow.com/a/47887344
answers question: http://stackoverflow.com/q/47887191
downvote count: 0
score: 7
accepted answer of: http://stackoverflow.com/q/47887191
has body: You can read the key/values from a CSV file or whatever, store them as a dict and initialize the enum as follows: &gt;&gt;&gt; d = {"WGS84" : "4326", "POP_WEB" : "3857", "UTM_33N" : "3767" } &gt;&gt;&gt; e = enum.Enum("CRS", d.items()) Now you can access the enum values as usual: &gt;&gt;&gt; e.POP_WEB &lt;CRS.POP_WEB: '3857'&gt; &gt;&gt;&gt; e.WGS84 &lt;CRS.WGS84: '4326'&gt;
upvote count: 7
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/48011029
has comment: http://stackoverflow.com/comment/82991331
favorite count: 0
has comment: http://stackoverflow.com/comment/82991130
accepted answer: http://stackoverflow.com/a/48020103
has comment: http://stackoverflow.com/comment/82990947
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82990909
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48020103
has title: String converted to integer during indexation
has comment: http://stackoverflow.com/comment/82991930
has body: I'm creating a program to check if a user's inputted guess is correct(much like pigs and bulls). The correct code is generated by the computer. During the process of checking if the user inputted is correct a string variable is changed(or so I think) to an int and stops being iterable. I've tried doing some debugging with print(type()) to check for the type of the variable. Right up until the moment it's being iterated, the variable is a String, yet I get a TypeError: argument of type 'int' is not iterable. here's the code: def create_code(creator=list): creator = [random.randint(0, 9) for index in range(0, 4)] return creator def guesses(): state = True user_inputs = [] while state: get_user_input = str(input('Please insert your 4 digit guess: ')) user_inputs.append(get_user_input) for index in range(0,len(get_user_input)+1): touro(index, get_user_input[index]) #goes to touro to check if the number inputted is in the code and in the correct position def touro(index, user_input): t = 0 print(type(user_input[index]))#this returns str print(type(create_code))#this returns list if user_input[index] in create_code()[index]: print('th') t += 1 else: pigs(index, user_input)#this function is just to check if the inputted number currently being iterated is even in the code print('ty') return t Error: File "C:/Users/Miguel/PycharmProjects/untitled1/Trabalho1.py", line 14, in guesses touro(index, get_user_input[index]) File "C:/Users/Miguel/PycharmProjects/untitled1/Trabalho1.py", line 27, in touro if user_input[index] in create_code()[index]: TypeError: argument of type 'int' is not iterable I don't get what i'm doing wrong, and I haven't any questions with similar problems, does anybody now what I'm doing wrong?
has comment: http://stackoverflow.com/comment/82990776
has comment: http://stackoverflow.com/comment/82991458
has comment: http://stackoverflow.com/comment/82991043
tagged with: type-conversion
score: 0
has comment: http://stackoverflow.com/comment/82991004
has comment: http://stackoverflow.com/comment/82991183
answer count: 1

http://stackoverflow.com/comment/83058223
comment on: http://stackoverflow.com/q/47981081
score: 0
type: QuestionComment
type: Comment
has text: I choose to override the `on_model_change` method to achieve my purpose.

http://stackoverflow.com/comment/120529062
score: 1
has text: @sfb Have you been able to solve your issue with the use of separate AppDomain(s)? I am actually facing the exact same issue from my WPF app.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48069615

http://stackoverflow.com/comment/82832907
type: AnswerComment
has text: Update: on testng I changed the intial code to take the initializer as a string with its name instead, as during class construction, "classmethod" is quite a different beast than what you retrieve after the class is created, as it is itself a descriptor with a behavior set when retrieved from its class.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47931849

http://stackoverflow.com/q/47939606
tagged with: django
tagged with: python
type: AnsweredQuestion
tagged with: mysql
type: Question
has title: django + apscheduler - How to configure APScheduler to use django db connection data in settings.py?
has answer: http://stackoverflow.com/a/53011497
accepted answer: http://stackoverflow.com/a/53011497
score: 0
tagged with: apscheduler
answer count: 1
has body: I have a working Django project with its database and model tables.Now, I want to integrate APScheduler and save APScheduler job in the same database as other tables, using the Django database connection. I have read the User Guide which gives examples of hardcoding db connection string into code: from pytz import utc from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.jobstores.mongodb import MongoDBJobStore from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor jobstores = { 'mongo': MongoDBJobStore(), 'default': SQLAlchemyJobStore(url='sqlite:///jobs.sqlite') } executors = { 'default': ThreadPoolExecutor(20), 'processpool': ProcessPoolExecutor(5) } job_defaults = { 'coalesce': False, 'max_instances': 3 } scheduler = BackgroundScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults, timezone=utc) But the config data I already have it in Django setting file. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'xxxxx', 'USER': "manager", 'PASSWORD': "xxxxxxxx", 'HOST': 'localhost', # Or an IP Address that your DB is hosted on 'PORT': '3306', } } Can I just use Django connection? I don't want to write these data into another properties file to maintain two files. I ask this basically because I don't want to hard code credentials. EDIT: I realized that I can use something like: 'url': 'mysql+mysqldb://' + settings.DATABASES['default']['USER'] + ':' + settings.DATABASES['default']['PASSWORD'] + '@' + settings.DATABASES['default']['HOST'] + '/' + settings.DATABASES['default']['NAME'] Now, if my password is encrypted, will APScheduler recognize it?

http://stackoverflow.com/q/47873275
tagged with: sqlalchemy
has body: I have sqlalchemy connecting to a sqllite database in a small flask app. If I do: check = MyTable.query.filter(MyTable.run_dt &gt;= datetime.date(2017,12,14)).all() Then I receive a sqlalchemy object that contains a list of all rows with run_dt greater than or equal to 2017-12-14. It contains several rows with a date '2017-12-14'. This is what I would expect. If I do: check = MyTable.query.filter(MyTable.run_dt == datetime.date(2017,12,14)).all() I get an empty set. I can't figure out why. run_dt is a db.Column(db.Date) in the model object. I've tried switching it to strings and it didn't work. In fact, doing the above with strings works. I'm sorry if this is a goofy question, but I find it bewildering and appreciate any help anyone can give.
tagged with: sqlite
answer count: 1
has answer: http://stackoverflow.com/a/47874129
accepted answer: http://stackoverflow.com/a/47874129
has comment: http://stackoverflow.com/comment/82713172
score: 0
has title: Date query in flask-sqlalchemy empty when equal, non-empty when ge or le
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82713357
type: Question
has comment: http://stackoverflow.com/comment/82766565

http://stackoverflow.com/a/47878067
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47878019
has body: Say df is your DataFrame and the column in question is category: You can first get a 1d NumPy array of categories, then call set() constructor on it: set(df.category.str.split('::', expand=True).values.flatten()) Example: print(df) category 0 food::restaurant::cafe::business 1 car dealer::business::automotive 2 barber::business res = set(df.category.str.split('::', expand=True).values.flatten()) {'barber', 'automotive', 'car dealer', 'restaurant', None, 'cafe', 'food', 'business'} To get rid of None: res = df.category.str.split('::', expand=True).values.flatten() res = set(filter(lambda x: x is not None, res))

http://stackoverflow.com/comment/82745512
score: 0
has text: If your problem is to have all your columns with a sum between 98 and 100, it's not possible as your max value is 94 (in row 6), and it will necessarily be with a 6 in row 1 (as in your example). So you have at least one columns that can't be below 100. If your problem is to have a least one column satisfying this condition, then it's much simpler.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47888396

http://stackoverflow.com/q/48000268
type: Question
tagged with: pyinstaller
answer count: 2
score: 5
has answer: http://stackoverflow.com/a/48738766
has comment: http://stackoverflow.com/comment/84301555
has title: Pyinstaller - libmagic not found after compiling app
tagged with: python
has comment: http://stackoverflow.com/comment/92014867
accepted answer: http://stackoverflow.com/a/48738766
upvote count: 5
tagged with: python-3.6
tagged with: libmagic
has comment: http://stackoverflow.com/comment/84302871
type: AnsweredQuestion
downvote count: 0
possible better answer: http://stackoverflow.com/a/70460706
has body: Problem I'm writing an application in Python. It works just fine in my python environment, but when I compile it with PyInstaller and try to run the resulting executable, I get the following error: ImportError: failed to find libmagic. Check your installation I have a feeling that this has something to do with "python-magic-bin", an install containing the binaries that were required for a module named "magic", because if I uninstall "python-magic-bin" from my Python environment and try to run the app, I get the same exact error. I think that for some reason these binaries aren't being carried to the compiled exe. If it makes a difference, I installed the "python-magic-bin" from a .whl file. This install added a folder called "libmagic" files libmagic.dll and magic.mgc to the directory that "magic" was installed to. Question If I'm right about the problem, how do I get PyInstaller to carry over the binaries that "magic" needs? Recreate the Problem The following can be done to recreate the problem: Copy and paste this code into your editor. Save it as a file called "test.py" import magic m=magic.MAGIC_NONE print(m) Download "python_magic_bin-0.4.14-py2.py3-none-win32.whl" from this link and use the following commands in the interpreter to install the required libraries to Python 3.6 &gt;&gt;&gt; pip install pyinstaller &gt;&gt;&gt; pip install python-magic &gt;&gt;&gt; pip install python_magic_bin-0.4.14-py2.py3-none-win32.whl &gt;&gt;&gt; pip install libmagic Open a command prompt in the same directory as that "test.py" file and use the following command to compile the program using pyinstaller: &gt; pyinstaller test.py After it's done, move to the newly created /dist/test directory (cd ./dist/test) and run the .exe using: &gt; ./test.exe After running it, you should see an error reading: ImportError: failed to find libmagic. Check your installation and Failed to execute script test Spec File This is the spec file I'm using to compile my project. # -*- mode: python -…
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82969303
has answer: http://stackoverflow.com/a/70460706

http://stackoverflow.com/q/48014071
answer count: 1
downvote count: 0
favorite count: 0
tagged with: google-app-engine
tagged with: python
has answer: http://stackoverflow.com/a/48026949
has body: I have an SDK for my web service that is distributed as a Python library via PyPI. My library uses requests for communicating with the backend using typical REST-like requests. I would like my library to be compatible with applications that are hosted on Google App Engine (GAE). According to the GAE documentation on HTTP requests: To use requests, you'll need to install both requests and requests-toolbelt using the vendoring instructions. Once installed, use the requests_toolbelt.adapters.appengine module to configure requests to use URLFetch: So I follow the example given there and have this in my library's main module: if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine/'): import requests_toolbelt.adapters.appengine requests_toolbelt.adapters.appengine.monkeypatch() This seems to do the trick when a client application using my library is actually running on an App Engine instance. However, when the client application is run locally using the development web server (dev_appserver.py), os.getenv('SERVER_SOFTWARE') returns "Development/2.0" and so the monkeypatch is not executed. I subsequently get these errors when trying to issue requests: ConnectionError: ('Connection aborted.', error(13, 'Permission denied')) How can I detect that the host application for my library is running either in Google App Engine itself, or inside the development web server? Checking for "Development/2.0" doesn't seem like it would be discriminating enough. Or, is there a better general pattern to follow when shipping a shared Python library that needs support for "typical" network requests?
type: UnansweredQuestion
upvote count: 1
tagged with: python-requests
has title: Using requests in Google App Engine local development server
score: 1
type: Question

qtstylesheets
tags question: http://stackoverflow.com/q/47893393
tag name: qtstylesheets
type: Tag

http://stackoverflow.com/comment/82755600
type: Comment
type: QuestionComment
has text: `percentage_int =(percentage)` just sets `percentage_int` to exactly the same value as `percentage`. It's a string.
comment on: http://stackoverflow.com/q/47894484
score: 2

http://stackoverflow.com/q/47906952
score: 1
has comment: http://stackoverflow.com/comment/82781095
has body: Say I have a list of tuples, top_n, of the top n most common bigrams found in a corpus of text: import nltk from nltk import bigrams from nltk import FreqDist bi_grams = bigrams(text) # text is a list of strings (tokens) fdistBigram = FreqDist(bi_grams) n = 300 top_n= [list(t) for t in zip(*fdistBigram.most_common(n))][0]; top_n &gt;&gt;&gt; [('let', 'us'), ('us', 'know'), ('as', 'possible') .... Now I want to replace instances of sets of words that are bigrams in top_n with their concatenation in place. For example, say we have a new variable query which is a list of strings: query = ['please','let','us','know','as','soon','as','possible'] would become ['please','letus', 'usknow', 'as', 'soon', 'aspossible'] after the desired operation. More explicitly, I want to search every element of query and check if the ith and (i+1)th element are in top_n; if they are, then replace query[i] and query[i+1] with a single concatenated bigram i.e (query[i], query[i+1]) -&gt; query[i] + query[i+1]. Is there some way to do this using NLTK, or what would be the best way to do this if looping over each word in query is necessary?
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/47907622
answer count: 2
tagged with: nltk
has comment: http://stackoverflow.com/comment/82780980
has answer: http://stackoverflow.com/a/47941182
tagged with: n-gram
has comment: http://stackoverflow.com/comment/82781287
downvote count: 0
possible better answer: http://stackoverflow.com/a/47941182
has comment: http://stackoverflow.com/comment/82783437
accepted answer: http://stackoverflow.com/a/47907622
favorite count: 0
tagged with: python
has title: How to replace bigrams in place using NLTK?
linked to: http://stackoverflow.com/q/35716121
type: AnsweredQuestion

http://stackoverflow.com/q/47922188
upvote count: 0
has answer: http://stackoverflow.com/a/47922205
has comment: http://stackoverflow.com/comment/82813474
score: -1
has answer: http://stackoverflow.com/a/47922743
tagged with: pandas
possible better answer: http://stackoverflow.com/a/47922743
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47922205
has comment: http://stackoverflow.com/comment/82812231
tagged with: python
tagged with: regex
downvote count: 1
has title: Replacing pandas column value with value in parenthesis, with comma in front
has body: I have a dataframe where one column contains names, and part of it is in parenthesis, like so: Names Apple (juicy) Banana (crunchy) Grape (sour) I want to change it to the following format: Names Apple, juicy Banana, crunchy Grape, sour How can this be accomplished using pandas and regex? I've tried this: df['Names'] = df1['Names'].str.replace(r"\s+\(.*\)",", " + r"\(.*\)") but the problem is in the last bit ( r"(.*)" ), where I don't know how to successfully transfer whatever is inside the parenthesis. With the above code, I'm getting this: Names Apple, \(.*\) Banana, \(.*\) Grape, \(.*\)
type: AnsweredQuestion
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/82812955

http://stackoverflow.com/a/67861019
upvote count: 2
answers question: http://stackoverflow.com/q/47990695
type: Answer
score: 2
downvote count: 0
has body: I had the same problem and solved it by setting the window I want the video to be played in with set_xwindow: player.set_xwindow(display.winfo_id()) Another answer here uses set_hwnd which did not work for me (played only audio, while giving the same error of "no frame" etc.). When I exchanged it with set_xwindow it started to work and displayed the video as well as played the sound. For vlc I ended up with: Instance = vlc.Instance() player = Instance.media_player_new() Media = Instance.media_new('example.mp4') player.set_xwindow(display.winfo_id()) player.set_media(Media) player.play() And for tkinter: root = tk.Tk() frame = tk.Frame(root, width=700, height=600) frame.pack() display = tk.Frame(frame, bd=5) display.place(relwidth=1, relheight=1) root.mainloop()

http://stackoverflow.com/q/47962856
has comment: http://stackoverflow.com/comment/82897831
favorite count: 0
has answer: http://stackoverflow.com/a/47964526
has comment: http://stackoverflow.com/comment/82898378
upvote count: 1
tagged with: python
tagged with: dummy-variable
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47963904
score: 1
linked to: http://stackoverflow.com/q/18889588
tagged with: dataframe
has title: Pandas - Map - Dummy Variables - Assign value of 1
accepted answer: http://stackoverflow.com/a/47964526
type: Question
possible better answer: http://stackoverflow.com/a/47963904
downvote count: 0
has body: I have two dataframes, x.head() looks like this: top mid adc support jungle Irelia Ahri Jinx Janna RekSai Gnar Ahri Caitlyn Leona Rengar Renekton Fizz Sivir Annie Rengar Irelia Leblanc Sivir Thresh JarvanIV Gnar Lissandra Tristana Janna JarvanIV and dataframe fullmatrix.head() that I have created looks like this: Irelia Gnar Renekton Kassadin Sion Jax Lulu Maokai Rumble Lissandra ... XinZhao Amumu Udyr Ivern Shaco Skarner FiddleSticks Aatrox Volibear MonkeyKing 0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 0 0 0 ... Now what I cannot figure out is how to assign a value of 1 for each name in the x dataframe to the respective column that has the same name in the fullmatrix dataframe row by row (both dataframes have the same number of rows).
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/47964136

http://stackoverflow.com/q/47916107
has title: coloring data points using vector of RGB values for each data point
upvote count: 3
tagged with: stripplot
has body: I have a pandas dataframe with some values. I wanted to use seaborn's stripplot to visualize the spread of my data, although this is the first time I'm using seaborn. I thought it would be interesting to color the datapoints that were outliers, so I created a column containing RGB tuples for each value. I have used this approach before and I find it very convenient so I would love to find a way to make this work because seaborn is quite nice. This is how the dataframe might look: SUBJECT CONDITION(num) hit hit_box_outliers \ 0 4.0 1.0 0.807692 0 1 4.0 2.0 0.942308 0 2 4.0 3.0 1.000000 0 3 4.0 4.0 1.000000 0 4 5.0 1.0 0.865385 0 hit_colours 0 (0.38823529411764707, 0.38823529411764707, 0.3... 1 (0.38823529411764707, 0.38823529411764707, 0.3... 2 (0.38823529411764707, 0.38823529411764707, 0.3... 3 (0.38823529411764707, 0.38823529411764707, 0.3... 4 (0.38823529411764707, 0.38823529411764707, 0.3... Then I try to plot it here: sns.stripplot(x='CONDITION(num)', y='hit', data=edfg, jitter=True, color=edfg['hit_colours']) and I am given the following error: ValueError: Could not generate a palette for &lt;map object at 0x000002265939FB00&gt; Any ideas for how I can achieve this seemingly easy task?
type: Question
score: 3
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47916250
favorite count: 0
tagged with: seaborn
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/47970869
has comment: http://stackoverflow.com/comment/82911241
has comment: http://stackoverflow.com/comment/82911546
has body: I think the logic is unclear for you: soup.find_all("a", {"style": "height:81px;"}) This retrieves a list of articles, so ciao = article.get("href") will return a single link for the article. To get the list of links there are a few options, one is the famous list comprehension: mylist = [article.get('href') for article in soup.find_all("a", {"style": "height:81px;"})] and you might also like to be acquainted with map, which is considered a bit more 'complex', especially since I'm involving a lambda term: mylist = list(map(lambda article: article.get('href'),soup.find_all("a", {"style": "height:81px;"}))) If you want to iterate the list you can leave it as a map. The logic in both solutions is you want to convert soup.find_all list by applying to each item a get.
upvote count: 1
answers question: http://stackoverflow.com/q/47970818
has comment: http://stackoverflow.com/comment/82911193
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/82748575
type: Comment
type: QuestionComment
score: 1
has text: Please show your code, so that we can help you figuring out your mistake. We do not intend to write it for you.
comment on: http://stackoverflow.com/q/47891051

http://stackoverflow.com/comment/82996917
type: QuestionComment
has text: `'png' not in text` is `True`, everything after that is not even evaluated. `a or b` is true if `a` is true or b is true or both are true.
score: 0
comment on: http://stackoverflow.com/q/48014006
type: Comment

http://stackoverflow.com/q/47896540
has title: How to run two threads simultaneously?
type: Question
accepted answer: http://stackoverflow.com/a/47896583
score: 4
tagged with: python-multiprocessing
has answer: http://stackoverflow.com/a/47896583
duplicate of: http://stackoverflow.com/q/45897566
answer count: 1
favorite count: 0
has body: from threading import Thread import time class ThreadTest(): def loop1(self): for i in range(0, 100, 5): print(i) time.sleep(2) def loop2(self): for i in range(100, 210, 11): print(i) time.sleep(2) if __name__ == '__main__': T1 = Thread(target=ThreadTest().loop1(), args=()) T2 = Thread(target=ThreadTest().loop2(), args=()) T1.start() T2.start() T1.join() T2.join() The above code runs the methods in sequence rather than simultaneously. I want a way where I can run two method/process simultaneously.
tagged with: python-3.x
linked to: http://stackoverflow.com/q/45897566
tagged with: python
upvote count: 4
type: AnsweredQuestion
downvote count: 0
tagged with: multithreading

http://stackoverflow.com/comment/82807379
comment on: http://stackoverflow.com/a/47918727
has text: ah, figured it out ... my predicted values for the same type are the same value; I did not actually run a prediction ... these values were given to me as the predictions
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/47957314
has title: matplotlib / scipy produces weird results when calculating and plotting multiple data sets (phase portraits of ODEs)
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: python
tagged with: plot
tagged with: matplotlib
tagged with: scipy
type: Question
tagged with: numpy
has body: Let me try to pose the problem I've encountered: Given is an ordinary differential equation dx/dt = f(x, t) whose phase portrait is to be plotted by plotting the phase trajectories for an array of initial values with the following code: import matplotlib.pyplot as plt import numpy as np from scipy.integrate import odeint def phase_trajectories(func, inits, xbound, ybound): """func: RHS of ODE to be integrated by odeint inits: list or array of initial-value-tuples xbound, ybound: Boundaries for plotting """ t = np.linspace(0, 10, 100) # solution is calculated for these values axis = plt.gca() def f_neg(x, t): return -func(x, t) for i in inits: sol_fwd = odeint(func, i, t) # calc solution forward sol_bwd = odeint(f_neg, i, t) # and backward in time sol = np.vstack((np.flipud(sol_bwd), sol_fwd)) # put both together sol_x = sol[:,0] sol_y = sol[:,1] sol_x_masked = np.ma.masked_outside(sol_x, *xbound) # masking the data because sol_y_masked = np.ma.masked_outside(sol_y, *ybound) # of blow-up of the solution axis.plot(sol_x_masked, sol_y_masked, c='b') plt.plot() As a specific example take a look at dx/dt = x(t)² with the initial value x(t0) = x0: # inits contains tuples (t0, x0) inits = np.array([(i, j) for i in range(-2, 3) for j in (-1, 1)]) def func(x, t): # receives x as array with shape (n,) from odeint # returns [dt/dt, dx/dt] return np.array([1, x[1]**2]) Now calling phase_trajectories(func, inits, (-2, 2), (-2, 2)) plots the expected trajectories but also adds unwanted noise that seems to differ each time the function is invoked: example with noise another example In order to get the bottom of this, I called phase_trajectories not for the whole inits-array at once but for each initial-value-pair seperatly using a generator with calling its next methode manually until exhaustion: def generator_pt(): for i in inits: yield phase_trajectories(func, (i,), (-2, 2), (-2, 2)) g = generator_pt() next(g) This, however, would sometimes (strangely not every time) give me the…
has answer: http://stackoverflow.com/a/48045375

http://stackoverflow.com/q/47965828
has answer: http://stackoverflow.com/a/47966033
has title: Why pandas expanding count when axis = 1 not working
score: 1
upvote count: 1
type: Question
downvote count: 0
tagged with: pandas
has body: I have a dataframe like: df = pd.DataFrame({'A': [0, 1, 2, np.nan, 4], 'B': [0, 1, 2, np.nan, 4], 'C': [0, 1, 2, np.nan, 4], 'D': [0, 1, 2, np.nan, 4], 'E': [0, 1, 2, np.nan, 4], 'F': [0, 1, 2, np.nan, 4]}) and I expect df.expanding(axis = 1).count to produce results like: A B C D E F 0 1.0 2.0 3.0 4.0 5.0 6.0 1 1.0 2.0 3.0 4.0 5.0 6.0 2 1.0 2.0 3.0 4.0 5.0 6.0 3 0.0 0.0 0.0 0.0 0.0 0.0 4 1.0 2.0 3.0 4.0 5.0 6.0 However, the results produced are the same as df2.expanding().count() would do: A B C D E F 0 1.0 1.0 1.0 1.0 1.0 1.0 1 2.0 2.0 2.0 2.0 2.0 2.0 2 3.0 3.0 3.0 3.0 3.0 3.0 3 3.0 3.0 3.0 3.0 3.0 3.0 4 4.0 4.0 4.0 4.0 4.0 4.0 What did I miss here?
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: count
tagged with: python

http://stackoverflow.com/q/47933656
has answer: http://stackoverflow.com/a/47933812
accepted answer: http://stackoverflow.com/a/47933729
score: -1
has answer: http://stackoverflow.com/a/47933780
possible better answer: http://stackoverflow.com/a/47933766
downvote count: 2
has answer: http://stackoverflow.com/a/47933766
tagged with: range
upvote count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47933751
has comment: http://stackoverflow.com/comment/82836685
has title: How can I convert a range of ints to strings to be used for variables?
has comment: http://stackoverflow.com/comment/82837110
has body: So I have a few variables that use numbers at the end of the string. But the "i" doesn't seem to convert to a string when I use an str function. Any idea why this might be? code: has_GroupConnection1 = True has_GroupConnection2 = True has_GroupConnection3 = True GroupConnection1 = 45 GroupConnection2 = 88 GroupConnection3 = 55 for i in range(1,3): if str(has_GroupConnection[i]) == True: print(str(GroupConnection[i]))
has answer: http://stackoverflow.com/a/47933729
type: Question
linked to: http://stackoverflow.com/q/29177693
answer count: 6
tagged with: variables
favorite count: 0
has answer: http://stackoverflow.com/a/47933825

http://stackoverflow.com/comment/82709946
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47872106
has text: Does `file_content.decode('cp1252')` work? `0x94` is a closing curly double quote in cp1252, which is a common encoding on Windows systems.

http://stackoverflow.com/a/47925641
answers question: http://stackoverflow.com/q/47922948
score: 0
has body: you need to remove return in def action_upgrade_to_assigned
type: Answer

http://stackoverflow.com/q/47864999
type: Question
tagged with: port
tagged with: ssh
tagged with: python
accepted answer: http://stackoverflow.com/a/47865083
has body: How to use the python script which create a tab with special ssh port, like this: # $language = "python" # $interface = "1.0" host = '192.168.1.1' user = 'test' passwd = 'test' def main(): # how to use the port 22333 for ssh cmd = "/SSH2 /PASSWORD %s %s@%s port=22567" % (passwd, user, host) crt.Session.ConnectInTab(cmd, True) main() this is not working, but with the of the default port 22, it is working: cmd = "/SSH2 /PASSWORD %s %s@%s" % (passwd, user, host) thanks
upvote count: 1
answer count: 1
has title: securecrt python script open ssh with special port
has answer: http://stackoverflow.com/a/47865083
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/comment/83395598
type: QuestionComment
has text: What kind of database are you using? What python wrapper?
type: Comment
comment on: http://stackoverflow.com/q/47880348
score: 0

http://stackoverflow.com/a/47868704
has body: Typical error on Windows because the default user directory is C:\user\&lt;your_user&gt;, so when you want to use this path as an string parameter into a Python function, you get a Unicode error, just because the \u is a Unicode escape. Any character not numeric after this produces an error. To solve it, just double the backslashes: C:\\\user\\\&lt;\your_user&gt;...
answers question: http://stackoverflow.com/q/47868498
type: Answer
score: 0

http://stackoverflow.com/q/48003622
upvote count: 3
has body: My dataframe looks like this: In [120]: data.head() Out[120]: date open high low close volume 0 2017-08-07 2.276 2.276 2.253 2.257 0.0 1 2017-08-08 2.260 2.291 2.253 2.283 0.0 2 2017-08-09 2.225 2.249 2.212 2.241 0.0 3 2017-08-10 2.241 2.241 2.210 2.212 0.0 4 2017-08-11 2.199 2.222 2.182 2.189 0.0 after doing: data.index = pd.to_datetime(data['date']) I end up with this: In [122]: data.head() Out[122]: date open high low close volume date 2017-08-07 2017-08-07 2.276 2.276 2.253 2.257 0.0 2017-08-08 2017-08-08 2.260 2.291 2.253 2.283 0.0 2017-08-09 2017-08-09 2.225 2.249 2.212 2.241 0.0 2017-08-10 2017-08-10 2.241 2.241 2.210 2.212 0.0 2017-08-11 2017-08-11 2.199 2.222 2.182 2.189 0.0 how can i avoid ending up with a duplicate date column? Grateful for your help. (Pandas 0.21.1)
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48003737
downvote count: 0
tagged with: python-3.6
tagged with: pandas
possible better answer: http://stackoverflow.com/a/48004220
score: 3
tagged with: python
has answer: http://stackoverflow.com/a/48004220
favorite count: 0
accepted answer: http://stackoverflow.com/a/48003737
type: AnsweredQuestion
has title: Set index in pandas df without creating duplicate column
has comment: http://stackoverflow.com/comment/82975380

tkinter
tags question: http://stackoverflow.com/q/47861592
tags question: http://stackoverflow.com/q/47946838
tags question: http://stackoverflow.com/q/47924021
tags question: http://stackoverflow.com/q/47863634
tags question: http://stackoverflow.com/q/47943951
tags question: http://stackoverflow.com/q/47919609
tags question: http://stackoverflow.com/q/47895320
tags question: http://stackoverflow.com/q/47888605
tags question: http://stackoverflow.com/q/47983017
tags question: http://stackoverflow.com/q/47856817
tags question: http://stackoverflow.com/q/47902807
tags question: http://stackoverflow.com/q/48012086
tags question: http://stackoverflow.com/q/47954439
tags question: http://stackoverflow.com/q/47984251
tags question: http://stackoverflow.com/q/47878838
tags question: http://stackoverflow.com/q/47888904
tags question: http://stackoverflow.com/q/47873311
tags question: http://stackoverflow.com/q/47873201
tag name: tkinter
tags question: http://stackoverflow.com/q/47972342
tags question: http://stackoverflow.com/q/47958537
tags question: http://stackoverflow.com/q/47978761
tags question: http://stackoverflow.com/q/47965015
tags question: http://stackoverflow.com/q/47984318
tags question: http://stackoverflow.com/q/47947023
tags question: http://stackoverflow.com/q/47888350
tags question: http://stackoverflow.com/q/47961996
tags question: http://stackoverflow.com/q/47896109
tags question: http://stackoverflow.com/q/47917916
tags question: http://stackoverflow.com/q/47929103
tags question: http://stackoverflow.com/q/47914501
tags question: http://stackoverflow.com/q/47935108
tags question: http://stackoverflow.com/q/47882305
tags question: http://stackoverflow.com/q/47995101
tags question: http://stackoverflow.com/q/47999555
tags question: http://stackoverflow.com/q/47985807
tags question: http://stackoverflow.com/q/47871084
tags question: http://stackoverflow.com/q/47971617
tags question: http://stackoverflow.com/q/47931718
tags question: http://stackoverflow.com/q/47858588
tags question: http://stackoverflow.com/q/47936475
tags question: http://stackoverflow.com/q/47994778
tags question: http://stackoverflow.com/q/47959785
tags question: http://stackoverflow.com/q/47878705
tags question: http://stackoverflow.com/q/47869843
tags question: http://stackoverflow.com/q/47942973
tags question: http://stackoverflow.com/q/47895350
tags question: http://stackoverflow.com/q/47913548
tags question: http://stackoverflow.com/q/47895765
tags question: http://stackoverflow.com/q/48009783
tags question: http://stackoverflow.com/q/47897282
tags question: http://stackoverflow.com/q/47988625
tags question: http://stackoverflow.com/q/47996749
tags question: http://stackoverflow.com/q/47986012
tags question: http://stackoverflow.com/q/47896881
tags question: http://stackoverflow.com/q/47966301
tags question: http://stackoverflow.com/q/48003979
tags question: http://stackoverflow.com/q/47888559
tags question: http://stackoverflow.com/q/47946448
tags question: http://stackoverflow.com/q/47893541
tags question: http://stackoverflow.com/q/47970163
tags question: http://stackoverflow.com/q/47907615
tags question: http://stackoverflow.com/q/47934173
tags question: http://stackoverflow.com/q/47892321
tags question: http://stackoverflow.com/q/47946713
tags question: http://stackoverflow.com/q/47909342
tags question: http://stackoverflow.com/q/47934144
tags question: http://stackoverflow.com/q/47895168
tags question: http://stackoverflow.com/q/47894128
tags question: http://stackoverflow.com/q/47996904
tags question: http://stackoverflow.com/q/47965657
tags question: http://stackoverflow.com/q/47973248
tags question: http://stackoverflow.com/q/47873982
tags question: http://stackoverflow.com/q/47958564
tags question: http://stackoverflow.com/q/47941051
tags question: http://stackoverflow.com/q/47996265
tags question: http://stackoverflow.com/q/47878492
tags question: http://stackoverflow.com/q/47934321
tags question: http://stackoverflow.com/q/47988306
tags question: http://stackoverflow.com/q/47933169

http://stackoverflow.com/comment/82711008
type: Comment
comment on: http://stackoverflow.com/a/47871866
score: 0
type: AnswerComment
has text: If "the value is copied, not referenced", then why is `health1[1] is hp1` true?

http://stackoverflow.com/a/47874145
accepted answer of: http://stackoverflow.com/q/47873934
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: I'm not entirely sure what's going on with the rest of your code, but i is never initialized before you try to increment. It's like adding 1 to nothing, which raises an error. Add the line: i = 0 before your For statement. If added after the For, you'll simply get i = 1 with every loop, since 1 is added to 0 each time. Additionally, the gram variable isn't being used anywhere, and that too will raise an error. Whatever the value gram is, it should be used to do something within your method. Otherwise there's no point in iterating through generated_ngrams.
answers question: http://stackoverflow.com/q/47873934
score: 1
upvote count: 1

http://stackoverflow.com/q/47892790
type: Question
has title: python lxml xml.etree.ElementTree.Element to string will not convert
has body: type(ikePanProfiles) &lt;class 'xml.etree.ElementTree.Element'&gt; etree.tostring(ikePanProfiles) Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; File "src/lxml/etree.pyx", line 3367, in lxml.etree.tostring (src/lxml/etree.c:82622) TypeError: Type 'Element' cannot be serialized. I'm accessing an API that responds in kind with an object type of "xml.etree.ElementTree.Element" So I'm not sure how to covert this tostring?
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/47893028
tagged with: lxml
tagged with: python
tagged with: elementtree
tagged with: http://stackoverflow.com/tag/xml
upvote count: 3
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47893028
score: 3

http://stackoverflow.com/comment/82886400
comment on: http://stackoverflow.com/a/47958339
type: AnswerComment
type: Comment
has text: It depends I think. In some cases, a view is returned, and in others, it's a fresh array. Better be safe I suppose.
score: 1

http://stackoverflow.com/comment/83057635
type: Comment
comment on: http://stackoverflow.com/a/48028250
has text: I use the scatter_matrix to find correlation of different features of users. I mark on these plots all the known fraud devices I have, and I wish to create a heat-map to use on unknown devices, and see how close they are to the fraud behavior
type: AnswerComment
score: 0

http://stackoverflow.com/a/47963229
has comment: http://stackoverflow.com/comment/82898705
score: 1
accepted answer of: http://stackoverflow.com/q/47962865
answers question: http://stackoverflow.com/q/47962865
has body: Have you tried pandas? import pandas as pd # get some output as a dictionary. i got this from the link you provided dict_to_output = {u'123456': {'ask': u'0.00000000', 'askQty': u'0.00000000', 'bid': u'0.00000000', 'bidQty': u'0.00000000'}, u'ASTBTC': {'ask': u'0.00005149', 'askQty': u'3396.00000000', 'bid': u'0.00004951', 'bidQty': u'222.00000000'}} # load the output into pandas dataframe df_to_output = pd.DataFrame(dict_to_output) # output the file df_to_output.to_csv(r'C:\Users\fffrost\Desktop\output.csv')
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer

series
tag name: series
type: Tag
tags question: http://stackoverflow.com/q/47912611
tags question: http://stackoverflow.com/q/47986121
tags question: http://stackoverflow.com/q/47862070
tags question: http://stackoverflow.com/q/47994917

http://stackoverflow.com/q/47963763
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47963853
has title: Python Logging levels don't seem to be working
type: Question
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-2.7
tagged with: python
has answer: http://stackoverflow.com/a/47963853
upvote count: 2
has body: I would like to log info level information to a file and debug level info to the console. I am using StreamHandlers, but both logging.info and logging.debug both log to the console and file. I would like the console to just show test1 and the file to just show test. import logging import os rootLogger_file = logging.getLogger() rootLogger_file.setLevel(logging.INFO) rootLogger_console = logging.getLogger() rootLogger_console.setLevel(logging.DEBUG) fileHandler = logging.FileHandler('info', "w") rootLogger_file.addHandler(fileHandler) consoleHandler = logging.StreamHandler() rootLogger_console.addHandler(consoleHandler) rootLogger_file.info('test') rootLogger_console.debug('test1')
tagged with: logging

http://stackoverflow.com/q/47875726
type: Question
has comment: http://stackoverflow.com/comment/82717692
downvote count: 0
has comment: http://stackoverflow.com/comment/82716860
answer count: 3
has comment: http://stackoverflow.com/comment/82717377
tagged with: port
has comment: http://stackoverflow.com/comment/82717566
linked to: http://stackoverflow.com/q/20449427
favorite count: 0
has comment: http://stackoverflow.com/comment/82716950
has title: Simple Port Scanner in Python - Error: an integer is required
has comment: http://stackoverflow.com/comment/82717180
has answer: http://stackoverflow.com/a/47875786
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82716981
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47875786
has body: #!/usr/bin/python3 import socket ip = input('Enter the IP address: ') port = input('Enter the Port: ') s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if s.connect_ex((ip,port)): print ('Port', port, 'is closed') else: print ('Port', port, 'is open') As you can see, it is a very simply port scanner that I have attempted to run (currently learning some Penetration Testing). This is the error I get: Traceback (most recent call last): File "./python.py", line 9, in &lt;module&gt; if s.connect_ex((ip,port)): TypeError: an integer is required (got type str) I assume that I need to set line 9 as an integer - how do I do this? Cheers in advance.
possible better answer: http://stackoverflow.com/a/47875787
score: 1
has answer: http://stackoverflow.com/a/47875787
has answer: http://stackoverflow.com/a/47875837

http://stackoverflow.com/q/47907268
upvote count: 13
has answer: http://stackoverflow.com/a/47907515
has comment: http://stackoverflow.com/comment/82781726
has answer: http://stackoverflow.com/a/47907298
type: AnsweredQuestion
tagged with: python-3.x
has title: How do I pass a string as an argument name?
score: 13
type: Question
has body: I have the following function: def create_act(user, verb, fk_name=None, fk_value=None): fk = getattr(Action, fk_name) action = Action(user=user, verb=verb, fk=fk_value) action.save() Action is a class. The class has multiple attributes, and I don't know at the beginning, which attribute will get a value. I get the attribute name dynamic. I want the kwarg fk, to be an actual attribute of the class action. FK can be account or company. class Action(models.Model): account = models.ForeignKey(Account, blank=True, null=True, related_name='activity', on_delete=models.CASCADE) company = models.ForeignKey(Company, blank=True, null=True, related_name='activity', on_delete=models.CASCADE) I found on the forums some answers but nothing relevant to me, or in python. I saw some suggestion on other sites to use eval, but eval is not safe.
accepted answer: http://stackoverflow.com/a/47907298
has comment: http://stackoverflow.com/comment/82781729
answer count: 2
tagged with: function
downvote count: 0
linked to: http://stackoverflow.com/q/3394835
favorite count: 0
has comment: http://stackoverflow.com/comment/82781829
has comment: http://stackoverflow.com/comment/82781954
tagged with: arguments
tagged with: python
possible better answer: http://stackoverflow.com/a/47907515

http://stackoverflow.com/q/47996046
tagged with: pytorch
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48115761
tagged with: neural-network
answer count: 1
downvote count: 0
favorite count: 0
has body: I am trying to add hidden units to a 3-layered neural network(input, hidden,output) dynamically as I train it. I want to keep the weights of trained part of the network as I add new hidden units.This is my code, class my_network(torch.nn.Module): def __init__(self,input_dim,hidden_dim,output_dim): super(my_network,self).__init__() self.I = input_dim self.H = hidden_dim self.O = output_dim self.layer1 = torch.nn.Linear(input_dim,hidden_dim) self.layer2 = torch.nn.Linear(hidden_dim,output_dim) def add_neurons(self,no_of_neurons,flag): if flag == 1: weights = [self.layer1.weight.data,self.layer2.weight.data] self.layer1 = torch.nn.Linear(self.I,self.H+no_of_neurons) self.layer2 = torch.nn.Linear(self.H+no_of_neurons,self.O) self.layer1.weight.data[0:-no_of_neurons,:] = weights[0] self.layer2.weight.data[:,0:-no_of_neurons] = weights[1] self.H = self.H + no_of_neurons return self.layer1.weight.shape[0] def forward(self,x): temp = self.layer1(x) out = self.layer2(temp) return out I have noticed that once I call “add_neurons” method, the weights stop updating(while gradients are generated). Any help would be much appreciated.
type: UnansweredQuestion
tagged with: python
has title: Dynamic addition of hidden units in pytorch

http://stackoverflow.com/comment/83601574
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47930893
has text: You guys are reinventing the wheel. Use [`botocore.stub`](http://botocore.readthedocs.io/en/latest/reference/stubber.html) and your lives will get much easier.
score: 1

http://stackoverflow.com/comment/82767724
type: QuestionComment
has text: Using css `contains` is dangerous. I have seen it fail in many cases.
comment on: http://stackoverflow.com/q/47900465
score: 0
type: Comment

http://stackoverflow.com/a/65995550
score: 0
has body: How to Print * in a triangle shape in python? * * * * * * * * * * * * * * * This is one of the coding interview questions. def print_triangle(n): for i, j in zip(range(1,n+1), range(n,0,-1)): print(&quot; &quot;*j, '* '*i, &quot; &quot;*j) print_triangle(5)
type: Answer
answers question: http://stackoverflow.com/q/47860473
has comment: http://stackoverflow.com/comment/116730926

http://stackoverflow.com/comment/82804223
type: QuestionComment
comment on: http://stackoverflow.com/q/47917906
has text: What do you mean by trace ? Also your `startTrace` has no base condition and the recursion may run for infinity.
score: 0
type: Comment

http://stackoverflow.com/q/47878639
has comment: http://stackoverflow.com/comment/82723365
has answer: http://stackoverflow.com/a/47878753
linked to: http://stackoverflow.com/q/47581326
has comment: http://stackoverflow.com/comment/82723875
downvote count: 0
has answer: http://stackoverflow.com/a/47878926
favorite count: 0
has comment: http://stackoverflow.com/comment/82723721
has body: So, I have recently been tasked with writing a function in python 2 that can time the execution of another function. This is simple enough, but the catch is I have to do it WITHOUT importing any modules; this naturally includes time, timeit, etc. Using only built in functions and statements (e.g. sum(), or, yield) is this even possible? I don't want to see a solution, I need to work that out for myself, but I would greatly appreciate knowing if this is even possible. If not, then I'd rather not waste the time bashing my head against the proverbial brick wall.
has comment: http://stackoverflow.com/comment/82723510
tagged with: time
has comment: http://stackoverflow.com/comment/82723659
tagged with: python
has comment: http://stackoverflow.com/comment/82723529
accepted answer: http://stackoverflow.com/a/47878753
has title: Time a python 2 function takes to run WITHOUT ANY imports; is it possible?
has comment: http://stackoverflow.com/comment/82723464
answer count: 4
tagged with: timeit
type: AnsweredQuestion
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/47878676
has comment: http://stackoverflow.com/comment/82723606
has comment: http://stackoverflow.com/comment/82723339
has comment: http://stackoverflow.com/comment/82723324
has comment: http://stackoverflow.com/comment/82724023
type: Question
possible better answer: http://stackoverflow.com/a/47878676
has answer: http://stackoverflow.com/a/47878761

http://stackoverflow.com/q/47856660
tagged with: google-api-python-client
tagged with: python
has answer: http://stackoverflow.com/a/47942074
score: 2
upvote count: 2
tagged with: google-api
type: Question
tagged with: exponential-backoff
type: AnsweredQuestion
has body: So, here I have written a script that adds students to the courses (Google Classroom API). students = getStudents('Year10', '10A') # VAR for student in students: newStudent = { # Student Identifier 'userId': student } batch1_1.add(service.courses().students().create(courseId=arCourseId, body=newStudent)) batch1_1.add(service.courses().students().create(courseId=ciCourseId, body=newStudent)) batch1_1.add(service.courses().students().create(courseId=dtCourseId, body=newStudent)) batch1_1.add(service.courses().students().create(courseId=drCourseId, body=newStudent)) batch1_1.add(service.courses().students().create(courseId=enCourseId, body=newStudent)) batch1_2.add(service.courses().students().create(courseId=geCourseId, body=newStudent)) batch1_2.add(service.courses().students().create(courseId=hiCourseId, body=newStudent)) batch1_2.add(service.courses().students().create(courseId=icCourseId, body=newStudent)) batch1_2.add(service.courses().students().create(courseId=laCourseId, body=newStudent)) batch1_2.add(service.courses().students().create(courseId=maCourseId, body=newStudent)) batch1_3.add(service.courses().students().create(courseId=muCourseId, body=newStudent)) batch1_3.add(service.courses().students().create(courseId=peCourseId, body=newStudent)) batch1_3.add(service.courses().students().create(courseId=reCourseId, body=newStudent)) batch1_3.add(service.courses().students().create(courseId=scCourseId, body=newStudent)) batch1_1.execute() time.sleep(1) batch1_2.execute() time.sleep(1) batch1_3.execute() time.sleep(1) It does work, however, sometimes individual requests return: "HttpError 500 when requesting https://classroom.googleapis.com/v1/courses/[COURSE ID]/students?alt=json returned "Internal Error"" And for these individual requests, I'd like to write the code so that it retries the individual failed request when receiving a 5xx error. I am unsure how to implement this though. At the moment, I'm having to re-run the whole script if even just 1 student h…
accepted answer: http://stackoverflow.com/a/47942074
has title: In Python, is it possible to use 'exponential backoff' per request for batched HTTP requests?
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/47982568
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/47982657
score: 2
type: AnsweredQuestion
upvote count: 2
type: Question
has title: Filter Pandas Data frame
accepted answer: http://stackoverflow.com/a/47982657
tagged with: dataframe
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82933685
has body: I have this pandas dataframe: open high low close volume TimeStamp 2016-06-23 10:00:00 586.76 594.00 585.54 589.94 478.176973 2016-06-23 11:00:00 589.94 595.49 588.23 592.63 448.689485 2016-06-23 12:00:00 592.63 592.63 1.50 581.13 527.816891 2016-06-23 13:00:00 581.13 586.33 578.58 580.96 728.424757 As you can see one of the values is not ok. So I want to filter it and change it to the mean of the last 5 values With this df['avg']=df['low'].rolling(5).mean().shift() I get this open high low close volume avg TimeStamp 2016-06-23 10:00:00 586.76 594.00 585.54 589.94 478.176973 573.326 2016-06-23 11:00:00 589.94 595.49 588.23 592.63 448.689485 578.438 2016-06-23 12:00:00 592.63 592.63 1.50 581.13 527.816891 583.202 2016-06-23 13:00:00 581.13 586.33 578.58 580.96 728.424757 467.348 And now I want to give to the low the same value of avg. The filter finds value that has a "variance" bigger than 5. df.loc[(df['high']/df['low'])&gt;5]['low'] open high low close volume avg TimeStamp 2016-06-23 12:00:00 592.63 592.63 1.5 581.13 527.816891 583.202 But when I try to give the value, it doesn't work.. df.loc[(df['high']/df['low'])&gt;5]['low']=df.loc[(df['high']/df['low'])&gt;5]['avg'] Can you help me?
favorite count: 0
tagged with: data-analysis

http://stackoverflow.com/comment/82964401
has text: @t.m.adam thanks, yes I've made a note of that one.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47994573
score: 0

http://stackoverflow.com/comment/82935343
type: Comment
has text: You don't have to use it as values for placeholder. They're already part of the graph, hence you don't have to feed anything. Read this guide for a better understanding: https://www.tensorflow.org/api_guides/python/reading_data
comment on: http://stackoverflow.com/a/47978614
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82771502
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47901728
has text: If it is possible to get the input data in another format (actual JSON, for example), it would probably be best to go from there.

http://stackoverflow.com/comment/82924837
type: AnswerComment
has text: I get this error: `Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__ return self.func(*args) File "C:\Users\User\Desktop\PyEngine\gui.py", line 75, in save x1 = uni_get(X) File "C:\Users\User\Desktop\PyEngine\gui.py", line 70, in uni_get print(disp_str) UnboundLocalError: local variable 'disp_str' referenced before assignment`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47977855

http://stackoverflow.com/comment/82782348
comment on: http://stackoverflow.com/q/47907256
has text: @stucash -I am thinking if there is sometimes different step, e.g. 2, then solution should be different.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48014190
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/83018511
has comment: http://stackoverflow.com/comment/83023589
has body: Here is a relatively straightforward solution using json: import re, json, pprint, urllib.request regex_data = re.compile(r""" ^\s*var\s+TralbumData\s*=\s*\{(.*?)^\}; """, re.DOTALL | re.MULTILINE | re.VERBOSE) regex_item = re.compile(r""" ^\s*([\'"]?)([a-z][a-z0-9_]*)\1\s*:\s*(.+?)\s*,?\s*$ """, re.IGNORECASE | re.VERBOSE) def scrape(url): result = {} response = urllib.request.urlopen(url) html = response.read().decode('utf8') response.close() match = regex_data.search(html) if match is not None: for line in match.group(0).splitlines(): match = regex_item.match(line) if match is None: continue key, value = match.group(2, 3) try: result[key] = json.loads(value) except json.JSONDecodeError: pass return result tralbumdata = scrape('https://studiomdhr.bandcamp.com/releases') pprint.pprint(tralbumdata) This assumes that the layout of TralbumData object in the javascript code has each of its top-level key:value items on a separate line. It also assumes that all lower-level javascript objects have string keys, as this is required by the json format. (Note that lines ending in a comment cannot be parsed, because json doesn't support comments at all).
score: 1
has comment: http://stackoverflow.com/comment/83022368
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83020528
accepted answer of: http://stackoverflow.com/q/48012370
has comment: http://stackoverflow.com/comment/83017759
has comment: http://stackoverflow.com/comment/83023458
answers question: http://stackoverflow.com/q/48012370

http://stackoverflow.com/a/47856479
answers question: http://stackoverflow.com/q/47856432
score: 1
accepted answer of: http://stackoverflow.com/q/47856432
has comment: http://stackoverflow.com/comment/82678720
has comment: http://stackoverflow.com/comment/82677692
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82679038
has comment: http://stackoverflow.com/comment/82677174
has body: Function: sample = ['f','l','a','m','e','s'] def last_item(sample, x): rest = 0 a = 0 while (len(sample) &gt;1): rest = (x+rest-a) % len(sample) if rest == 0: rest = len(sample) print('element eliminated', sample[rest - 1]) sample.pop(rest - 1) a = 1 return sample print(last_item(sample, 5)) Output x = 5: element eliminated e element eliminated m element eliminated s element eliminated l element eliminated a ['f']
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/82679195
downvote count: 0
has comment: http://stackoverflow.com/comment/82677827
has comment: http://stackoverflow.com/comment/82678461

http://stackoverflow.com/q/47857863
has comment: http://stackoverflow.com/comment/82680310
has comment: http://stackoverflow.com/comment/82680435
has body: I am trying to count the number of separated pairs of 1s in a string using a regex and re.findall() in Python. The regex applied to the string 11110 should return 2 and applied to 01101 it should return 1. My code is the following: matches = len(re.findall(r'1[\w]+1', str1)) But applied to 110110 it returns 1 as it is only finding the substring 11011. I would expect it to also find the substring 101. Is my regex wrong or is re.findall() not the function I should be using?
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/82680098
has comment: http://stackoverflow.com/comment/82680147
upvote count: 0
tagged with: matching
linked to: http://stackoverflow.com/q/5616822
has answer: http://stackoverflow.com/a/47857975
has comment: http://stackoverflow.com/comment/82693798
score: -1
has title: Find number of pairs separated pairs of 1s in a string
has comment: http://stackoverflow.com/comment/82680567
duplicate of: http://stackoverflow.com/q/5616822
answer count: 1
has comment: http://stackoverflow.com/comment/82680527
tagged with: string
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: regex

http://stackoverflow.com/q/47904443
type: Question
tagged with: arrays
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/82781273
has answer: http://stackoverflow.com/a/52185498
has comment: http://stackoverflow.com/comment/82779087
has title: Build SQL query with long hex strings in Python
tagged with: sql
tagged with: sqlite
tagged with: python
has comment: http://stackoverflow.com/comment/82783001
tagged with: hex
has body: I have the array of md5 hashes as hex strings: hashes = ['abcdefabcdefabcdef', '12f456789012345678', 'acd24ef6dcbe98753a'] I need to build a SQL query to find records by the hashes. If I create a query manually, it looks like this "SELECT * FROM mytable WHERE hash IN (x'abcdefabcdefabcdef', x'12f456789012345678', x'acd24ef6dcbe98753a')" For a single hash I'd use string formatting, like this "SELECT * ... WHERE md5 = x'%s'" % hash However I have no idea how to build the query using array transformations in Python to put it into the sqlite3's cursor.execute() method.
upvote count: 1
accepted answer: http://stackoverflow.com/a/52185498
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82783621
score: 1

http://stackoverflow.com/q/48003741
tagged with: python
type: AnsweredQuestion
has body: I've deployed few apps on Google Kubernetes Engine and exposed two controllers based on Flask Python, with Service which contains type: LoadBalancer. apiVersion: v1 kind: Service metadata: labels: app: my-app name: controller namespace: ns-app spec: type: LoadBalancer ports: - name: "5001" port: 5001 targetPort: 5001 selector: app: my-app When I send Http Request via Python/Postman/Curl sometimes the Controller response with 200 ok, But most of the time the request is being rejected immediately, without timeout or anything. I had few speculation and thought that the load balancer reject the requests. Then I tried to use Ingress for expose the controller... using this tutorial The example in the tutorial works like charm, but forcing it on my app is not working. I'd change the service type to NodePort ingress.yaml: apiVersion: extensions/v1beta1 kind: Ingress metadata: name: controller-ingress namespace: ns-app spec: backend: serviceName: controller servicePort: 5001 service.yaml apiVersion: v1 kind: Service metadata: labels: app: my-app name: controller namespace: ns-app spec: type: NodePort ports: - name: "5001" port: 5001 targetPort: 5001 selector: app: my-app after waiting for ~15 minutes I entered to the Ingress external IP and I get default backend - 404. Questions: 1. How can I solve it? 2. There is difference between LoadBalancer and NodePort+Ingress? I need to expose my Flask Controller to have external IP in order to receive Http Requests. Thank you
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/48222705
score: 0
tagged with: google-kubernetes-engine
has title: Controller arbitrary reject requests on Google Kubernetes Engine
accepted answer: http://stackoverflow.com/a/48222705

http://stackoverflow.com/a/47936112
has body: You can do in one line without importing any module or making it more complex : just use lambda : Number = [25, 30, 36] Ratings = [ [101, 201, 301], [102, 202, 302], [103, 203, 304,] ] print(list(map(lambda x:list(map(lambda y,y1:[y,y1],x,Number)),Ratings))) output: [[[101, 25], [201, 30], [301, 36]], [[102, 25], [202, 30], [302, 36]], [[103, 25], [203, 30], [304, 36]]]
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47934348

http://stackoverflow.com/q/47897270
tagged with: python
has comment: http://stackoverflow.com/comment/82761402
tagged with: macos
answer count: 0
has comment: http://stackoverflow.com/comment/82772872
has title: Conda environment sometimes words, sometimes not
type: Question
tagged with: conda
score: 0
has comment: http://stackoverflow.com/comment/82761440
tagged with: shell
has body: I have been wanting to play with rllab (https://github.com/rll/rllab) for a while, and followed all their instructions to install it. Right now, along with a lot of junk I will probably want removed in the future, I have my terminal where I can type source activate rllab3 python which will get me into a python shell where I can import rllab and play with it. However there are two weird behaviours that I am not being able to fix. I had the environment active in one terminal window, opened another one, activated the environment and the python shell, and all import calls to rllab failed. I brought up another python shell on my initial terminal, and it imported rllab just fine. So having two shells set for the same environment, with the same python executable running, sometimes both work, sometimes only one works, sometimes none works. When they work, calling rllab.__file__ prints the path to the correct file, when it doesn't work I can run import rllab with no problems, however calling rllab.__file__ results in an AttributeError. The second problem came when I decided to try out some editors for debugging. After managing to get it to work (sometimes...) with Atom, I decided to see what had come bundled with Anaconda, and decided to give Spyder a try. I activated the environment, installed Spyder in it, and I keep getting import errors. I tried setting PYTHONPATH inside Spyder to point directly to the rllab directory, and it still didn't work. I am on Mac OS X 10.9, latest version of Anaconda.
type: UnansweredQuestion

http://stackoverflow.com/a/54140246
type: Answer
has body: I had the same problem using poetry. Running poetry run pip install --upgrade pip setuptools instead of pip install --upgrade pip setuptools fixed the issue.
answers question: http://stackoverflow.com/q/47955397
score: 0

http://stackoverflow.com/comment/82837929
type: Comment
has text: my problem is i am to query the table in hive but not through pyspark .. any idea what would be the issue ? The path mentioned in the error log is partition path which i deleted
comment on: http://stackoverflow.com/a/47934114
type: AnswerComment
score: 0

http://stackoverflow.com/a/47983315
answers question: http://stackoverflow.com/q/47983239
has comment: http://stackoverflow.com/comment/82937215
type: Answer
has comment: http://stackoverflow.com/comment/82935823
has comment: http://stackoverflow.com/comment/82937239
has body: data = 'This is my first Python language and I like this language to the most.' for i, word in enumerate(data.split()): if word == 'language': print(data.split()[i + 1])
score: 0
has comment: http://stackoverflow.com/comment/82935608

http://stackoverflow.com/a/47883104
downvote count: 0
has comment: http://stackoverflow.com/comment/82733127
has comment: http://stackoverflow.com/comment/82733569
has comment: http://stackoverflow.com/comment/82735934
type: Answer
answers question: http://stackoverflow.com/q/47882916
has comment: http://stackoverflow.com/comment/82733231
has body: If you can install scripts, you can also install a wrapper called python3.5 which simply dispatches python3. #!/bin/sh exec env python3 "$@" You'll obviously need to chmod a+x this script just like the others you install. You'll have to add the script's directory to your PATH after the system python3.5 directory to avoid having this go into an endless loop, and only use this script as a fallback when the system doesn't already provide python3.5. As you noted, env doesn't know or care about your personal shell aliases or functions, and doesn't provide for any dynamic calculation of the binary to run by itself; but you have the shell at your disposal (and Python of course, once you find it!) -- it simply uses the PATH so if you can install your other scripts in a directory which is in your PATH (which must be the case for the #!/usr/bin/env shebang to make sense in the first place) you can store this script there, too. As noted in comments, it's weird and user-hostile to only install python3.5 and not at least optionally make python3 a symlink to it, so perhaps you could eventually persuade whoever maintains the image you are installing into to provide this.
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/82732905

http://stackoverflow.com/comment/82958613
comment on: http://stackoverflow.com/a/47994971
type: AnswerComment
has text: i know they are two different modules, that's the point i tried to make to him, that he could more easily use tkinter to do what he was doing than Pyqt as tkinter is actually better for calculations in script
score: 0
type: Comment

http://stackoverflow.com/comment/82722618
has text: and the rest erased from both df1 and df2?
score: 0
comment on: http://stackoverflow.com/q/47878204
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47939696
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47959297
accepted answer: http://stackoverflow.com/a/47959297
downvote count: 0
possible better answer: http://stackoverflow.com/a/47939933
tagged with: entry-point
upvote count: 1
favorite count: 0
has body: I am trying to develop a python package that is importable and also has entry_point to call from shell. When trying to call the entry point I get: pkg_resources.VersionConflict: (pysec-aws 0.1.dev1 (/Users/myuser/PycharmProjects/pysec-aws), Requirement.parse('pysec-aws==0.1.dev0')) Essentially what I did before getting this error, is incrementing the version from 0.1.dev0 to 0.1.dev1 in setup.py, and running python setup.py sdist and then pip install -e . What am I doing wrong? What is the proper way to install development versions of packages you are actively developing and bundling with setuptools?
has comment: http://stackoverflow.com/comment/82865458
has title: Unable to load python entry_point when developing python package
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/82865408
has answer: http://stackoverflow.com/a/47939933
type: AnsweredQuestion
score: 1
tagged with: setuptools

http://stackoverflow.com/comment/82704674
type: Comment
comment on: http://stackoverflow.com/q/47867589
type: QuestionComment
has text: put Traceback in question. It will be more readable.
score: 0

http://stackoverflow.com/a/47863273
type: Answer
has body: I had a similar issue in the past. After having changed the Jupyter start folder as suggested in this post: how to change jupyter start folder? , just put the excel file in this folder and to load them it isn't necessary to write the path. This is enough: xl_file = pd.ExcelFile('myFile.xls')
answers question: http://stackoverflow.com/q/47860314
score: 0

http://stackoverflow.com/q/47985623
has answer: http://stackoverflow.com/a/47993711
has title: Subset Venn Diagrams - i.e. venn diagrams embedded in whole set
has answer: http://stackoverflow.com/a/47985734
has comment: http://stackoverflow.com/comment/82940227
has body: I'm comparing a set of tweets about a new fine implemented in London that is applied to heavily polluting vehicles. I want to compare how many tweets mention words related to traffic, and how many mention words related to pollution. I'm using a venn diagram to do this, but ideally I'd like the overlapping circles to both be contained within a large circle representing the entire set of all tweets. Here's an example of something I mean (sorry don;t have the reputation to post images yet) (https://media1.britannica.com/eb-media/79/63279-004-ED30922B.gif) I'm using matplotlib-venn currently. many thanks.
favorite count: 0
type: UnansweredQuestion
tagged with: venn-diagram
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82940483
score: 1
tagged with: matplotlib
type: Question
answer count: 2
tagged with: matplotlib-venn
downvote count: 0

http://stackoverflow.com/comment/82846605
score: 0
has text: thanks for bringing up the pd.Grouper function, which I didn't know. But I tried your suggested method, it seems not working as what I expected. df_x.groupby(pd.Grouper(freq='5Min')).apply(func)
type: Comment
comment on: http://stackoverflow.com/a/47938392
type: AnswerComment

http://stackoverflow.com/a/47978731
downvote count: 0
has body: As others have mentioned you accidentally read the first line, but then throw it away, so it never reaches your reversed string. This should be a working solution: def main(): fp = open( "reverse", "w" ) hello = open("correct") add = "" while True: text = hello.readline() for i in range(len(text)-1, -1, -1): add += str(text[i]) if text == "": fp.writelines(add) break fp.close() fp = open("reverse") buffer = fp.read() fp.close() print( buffer ) if __name__ == '__main__': main() But I also wanted to show you something cool with Python. Given any iterable (a string, a list, etc.) you can reverse it very easily. l = [1, 2, 3] print(l[::-1]) # prints [3, 2, 1] So your entire program can be written in just two lines! def main(): with open('reverse', 'w') as r_fp, open('correct', 'r') as c_fp: r_fp.write(c_fp.read()[::-1]) if __name__ == '__main__': main()
type: Answer
answers question: http://stackoverflow.com/q/47978522
has comment: http://stackoverflow.com/comment/82926166
upvote count: 2
has comment: http://stackoverflow.com/comment/82926109
score: 2

http://stackoverflow.com/comment/82906980
type: AnswerComment
has text: I tried to explain my answer, if you have a specific question please ask. About the location info, do you need the link or the text?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47968626

http://stackoverflow.com/comment/82892604
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47961641
has text: @cᴏʟᴅsᴘᴇᴇᴅ yes but still its not working

http://stackoverflow.com/q/47932542
has comment: http://stackoverflow.com/comment/82834249
has comment: http://stackoverflow.com/comment/82834361
upvote count: 1
has comment: http://stackoverflow.com/comment/82834466
type: Question
has comment: http://stackoverflow.com/comment/82834301
accepted answer: http://stackoverflow.com/a/47932784
linked to: http://stackoverflow.com/q/42223125
has title: TypeError: 'float' object is not iterable on a list in built in max function
has comment: http://stackoverflow.com/comment/82834350
tagged with: pandas
answer count: 1
downvote count: 0
score: 1
tagged with: iterable
favorite count: 0
has comment: http://stackoverflow.com/comment/82834172
tagged with: typeerror
has body: I am trying to find the closest match to an approximate movie title given an actual movie title using the max function and its key argument. If I define a sample list and test the function it works... from difflib import SequenceMatcher as SM movies = ['fake movie title', 'faker movie title', 'shaun died'] approx_title = 'Shaun of the Dead.' max(movies, key = lambda title: SM(None, approx_title, title).ratio()) 'shaun died' But I am trying to match to an entire column in a separate dataframe, so I tried converting that Pandas Series to a list and running the same function, but instead I get a type_error, even though I've checked the datatype of both movies &amp; movie_lst are lists. Old id New id Title Year Critics Score Audience Score Rating NaN 21736.0 Peter Pan 1999.0 NaN 70.0 PG nothing objectionable NaN 771471359.0 Dragonheart Battle for the Heartfire 2017.0 NaN 50.0 PG13 NaN 770725090.0 The Nude Vampire Vampire nue, La 1974.0 NaN 24.0 NR 2281.0 19887.0 Beyond the Clouds 1995.0 65.0 67.0 NR 10913.0 11286.0 Wild America 1997.0 27.0 59.0 PG violence movie_lst = rt_info['Title'].tolist() ['Peter Pan', 'Dragonheart Battle for the Heartfire', 'The Nude Vampire Vampire nue, La', 'Beyond the Clouds', 'Wild America', 'Sexual Dependency', 'Body Slam', 'Hatchet II', 'Lion of the Desert Omar Mukhtar', 'Imagine That', 'Harold', 'A United Kingdom', 'Violent City The FamilyCitt violenta', 'Ratchet Clank', 'Wes Craven Presents Carnival of Souls', 'The Adventures of Ociee Nash', 'Blackfish', 'For Petes Sake', 'Daybreakers', 'The Big One', 'Godzilla vs Megaguirus', 'In a Lonely Place', 'Case 39', ... ] max(movie_lst, key = lambda title: SM(None, approx_title, title).ratio()) TypeError Traceback (most recent call last) &lt;ipython-input-88-0022a3c1bdb9&gt; in &lt;module&gt;() ----&gt; 1 max(movie_lst, key = lambda title: SM(None, approx_title, title).ratio()) &lt;ipython-input-88-0022a3c1bdb9&gt; in &lt;lambda&gt;(title) ----&gt; 1 max(movie_lst, key = lambda title: SM(None, app…
has comment: http://stackoverflow.com/comment/82834426
tagged with: python
has answer: http://stackoverflow.com/a/47932784
has comment: http://stackoverflow.com/comment/82834399
has comment: http://stackoverflow.com/comment/82834259
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/comment/82735947
type: QuestionComment
has text: all right! thank you very much! You gave me the idea to let the code run just if the connection is right. I'll let you know if works :) @t.m.adam
score: 0
comment on: http://stackoverflow.com/q/47860238
type: Comment

http://stackoverflow.com/comment/82898441
has text: @PaulH to my knowledge, the only remaining is the surface function. However, I tried it, trying to map de data to a 2D grid in order to work, and I got nothing, a null plot.
comment on: http://stackoverflow.com/q/47963797
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82971100
comment on: http://stackoverflow.com/a/48001232
type: Comment
has text: I find it strange, I just made that modification and it works normally, maybe you have an old version that has that bug.
type: AnswerComment
score: 0

http://stackoverflow.com/q/47964378
type: Question
has answer: http://stackoverflow.com/a/47965432
has body: I want to split a text into subsentence. How can I do that? For example: text = "Hi, this is an apple. Hi, that is pineapple." The result should be: ['Hi,', 'this is an apple.', 'Hi,', 'that is pineapple.'] (P.S. I tried with the string.split(r'[,.]'), but it will remove the separators.)
tagged with: nltk
has title: How to split text into subsentence with python?
has comment: http://stackoverflow.com/comment/82898464
has comment: http://stackoverflow.com/comment/82898525
has answer: http://stackoverflow.com/a/47964434
has comment: http://stackoverflow.com/comment/82898706
has comment: http://stackoverflow.com/comment/82898589
possible better answer: http://stackoverflow.com/a/47964492
has answer: http://stackoverflow.com/a/47964492
favorite count: 0
upvote count: 2
answer count: 5
has answer: http://stackoverflow.com/a/47964427
tagged with: python
tagged with: nlp
accepted answer: http://stackoverflow.com/a/47964434
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82898497
linked to: http://stackoverflow.com/q/4576077
has comment: http://stackoverflow.com/comment/82898492
score: 1
has comment: http://stackoverflow.com/comment/82898541
has comment: http://stackoverflow.com/comment/82898581
downvote count: 1
has answer: http://stackoverflow.com/a/47966737

http://stackoverflow.com/a/48045627
downvote count: 0
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48000800
has body: I have changed the above statement from ./test.sh to screen -d -m ./test.sh and it did the trick for me.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48000800
has comment: http://stackoverflow.com/comment/128705312
type: Answer

http://stackoverflow.com/comment/82762834
comment on: http://stackoverflow.com/a/47897872
type: AnswerComment
score: 0
type: Comment
has text: i got: `Traceback (most recent call last): File "C:\Users\Michael\Desktop\list_exceptions.py", line 12, in <module> print(get_exceptions()) File "C:\Users\Michael\Desktop\list_exceptions.py", line 5, in get_exceptions for k in __builtins__.keys(): AttributeError: 'module' object has no attribute 'keys' >>> `

http://stackoverflow.com/comment/82823118
has text: What are the "integer pandas" in your question title?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47927371
score: 0

http://stackoverflow.com/comment/83011016
type: QuestionComment
score: 0
has text: Ahwell, I see this now. Please excuse, my redundant question.
comment on: http://stackoverflow.com/q/47992383
type: Comment

http://stackoverflow.com/a/47882523
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82730916
type: Answer
has comment: http://stackoverflow.com/comment/82731989
upvote count: 2
answers question: http://stackoverflow.com/q/47881729
score: 2
has body: To achieve your goal all you have to do is to check if dictionary contains key. You should define a function for example update_keys() which would take two arguments: dict1 and dict2. To check if dictionary has key simply write (as mentioned in this question): if key in dictionary: # Action you want to take if dictionary has key. Therefore your solution would look like this (note that deepcopy function is imported from copy module, as mentioned in Update 1 below): #!/usr/bin/env python3 from copy import deepcopy def update_keys(dict1, dict2): result_dict = deepcopy(dict1) for key in dict2: if key in result_dict: for sub_key in dict2[key]: result_dict[key].update({sub_key: dict2[key][sub_key]}) else: result_dict.update({key: dict2[key]}) return result_dict dict3 = update_keys(dict1, dict2) also to clarify things, you could iterate using values by using dictionary.items() like mentioned in this question, because in nested loop and multiple if statements you might get lost between all the variables. #!/usr/bin/env python3 from copy import deepcopy dict1={ 1: {"trait1": 32, "trait2": 43, "trait3": 98}, 2: {"trait1": 38, "trait2": 40, "trait3": 95} } dict2={ 1: {"trait1": 32, "trait2": 43, "trait4": 54}, 2: {"trait1": 38, "trait2": 40, "trait4": 56} } def update_keys(dict_one, dict_two): result_dict = deepcopy(dict_one) for key, value in dict_two.items(): if key in result_dict: for sub_key, sub_value in value.items(): if sub_key not in result_dict[key]: result_dict[key].update({sub_key: sub_value}) else: result_dict.update({key: value}) return result_dict dict3 = update_keys(dict1, dict2) Update 1: Thanks to @shash678 I could improve my answer. Earlier passing dictionary to method and making copy by assigning new value created shallow copy as mentioned in this question topic. Therefore if dict1 is to be preserved, importing copy module and using deepcopy() function from it is necessary. Thanks to @shash678, this answer does its job without modifying dict1.
has comment: http://stackoverflow.com/comment/82733053
accepted answer of: http://stackoverflow.com/q/47881729

http://stackoverflow.com/comment/92359896
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52717145
type: Comment
has text: While links can be good, try to quote the most important parts, just in case the link is down or something alike.

http://stackoverflow.com/comment/82886878
comment on: http://stackoverflow.com/q/47958793
score: 0
type: Comment
type: QuestionComment
has text: isnt list comprehesion highly effecient compared to loop?

http://stackoverflow.com/q/47915290
favorite count: 0
has comment: http://stackoverflow.com/comment/82798671
has body: import csv import numpy as np from sklearn.svm import SVR import matplotlib.pyplot as plt dates = [] prices = [] def get_data(filename): with open(filename, 'r') as csvfile: csvFileReader = csv.reader(csvfile) next(csvFileReader) for row in csvFileReader: dates.append(int(row[0].split('-')[0])) prices.append(float(row[1])) return def predict_price(dates, prices, x): dates = np.reshape(dates,(len(dates), 1)) svr_rbf = SVR(kernel='rbf', C=1e3, gamma=0,1) svr_lin = SVR(kernel='linear', C=1e3) svr_poly = SVR(kernel='poly', C=1e3, degree=2) svn_lin.fit(dates, prices) svr_poly.fit(dates, prices) svr_rbf.fit(dates, prices) plt.scatter(dates, prices, color = 'black', label = 'Data') plt.plot(dates, svr_rbf.predict(dates), color = 'red', label = 'RBF model') plt.plot(dates, svr_lin.predict(dates), color = 'green', label = 'linear model') plt.plot(dates, svr_poly.predict(dates), color = 'blue', label = 'polynomial model') plt.xlabel('Date') plt.xlabel("Price") plt.title('Support Vector Regression') plt.legend() plt.show() return svr_rbf.predict(x)[0], svr_lin.predict(x)[0], svr_poly.predict(x)[0] get_data('aapl.csv') predicted_price = predict_price(dates, prices, 29) print (predicted_price) OUTPUT: File "predictstocks.py", line 21 svr_rbf = SVR(kernel='rbf', C=1e3, gamma=0,1) SyntaxError: non-keyword arg after keyword arg Okay, so i have searched the internet for hours now, and looked in the different docs.. but i cant find the solution for my problem. as my title says the python code returns this: Syntaxerror non-keyword after keyword arg
tagged with: python
has comment: http://stackoverflow.com/comment/82798668
has comment: http://stackoverflow.com/comment/82798968
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47915343
upvote count: 1
has title: Python code returns: Syntaxerror non-keyword after keyword arg
downvote count: 1
has comment: http://stackoverflow.com/comment/82798697
type: Question
has comment: http://stackoverflow.com/comment/82798676
tagged with: syntax-error
accepted answer: http://stackoverflow.com/a/47915343
answer count: 1
tagged with: scikit-learn

http://stackoverflow.com/comment/83047727
comment on: http://stackoverflow.com/q/48006213
has text: I'm not sure how the "zgexpv" function works or what input it expects. if it expects a matrix, or you need to perform some matrix operations before sending the input to zgexpv, I think you should try to use the original matrix. There might be a better way of representing the matrix if it's really big, but that is probably the basis for a new question.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82987423
has text: Yes, if you could append arbitrary values to a tuple it wouldn't be a tuple.
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48009566

http://stackoverflow.com/a/47978614
answers question: http://stackoverflow.com/q/47978137
has comment: http://stackoverflow.com/comment/82927225
has comment: http://stackoverflow.com/comment/82935343
upvote count: 2
type: Answer
has body: The optimized way of doing this is to use Tensorflow for doing everything. There's a straightforward way to do this: # load csv content csv_path = tf.train.string_input_producer(['images.txt']) textReader = tf.TextLineReader() _, csv_content = textReader.read(csv_path) im_name, label = tf.decode_csv(csv_content, record_defaults=[[""], [0]]) # load images im_content = tf.read_file(im_name) image = tf.image.decode_jpeg(im_content, channels=3) # preprocess your input image (scale, subtract mean, resize, ...) # make batches bs = 32 im_batch, lb_batch = tf.train.batch([image, label], batch_size=bs) In this way you're using Tensorflow to read the CSV, the images and the labels and create batches of size 32. You can just use im_batch and lb_batch as input and and targets to your network.
score: 2
downvote count: 0

http://stackoverflow.com/comment/82807902
has text: This feature is known as [code folding](https://en.wikipedia.org/wiki/Code_folding).
score: 0
comment on: http://stackoverflow.com/q/47919669
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82796639
score: 0
comment on: http://stackoverflow.com/q/47898271
type: Comment
type: QuestionComment
has text: @philipxy I don't know what you mean by value type, the database records have attributes which are chars and ints, there really isn't anything going on behind the scenes. No restrictions that I am aware of. With your mentioning of fetchall, I was able to use cursor.fetchall() in order to get nikpod's suggestion working. The sentence "What is are examples of printing & extracting parts from googling 'python sqlite fetchall'?" has left me somewhat confused.

http://stackoverflow.com/q/47910707
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47910896
accepted answer: http://stackoverflow.com/a/47910955
tagged with: python
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/47910955
downvote count: 0
has body: I discovered a strange error when using concurrent.futures to read from multiple text files. Here is a small reproducible example: import os import concurrent.futures def read_file(file): with open(os.path.join(data_dir, file),buffering=1000) as f: for row in f: try: print(row) except Exception as e: print(str(e)) if __name__ == '__main__': data_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'data')) files = ['file1', 'file2'] with concurrent.futures.ProcessPoolExecutor() as executor: for file,_ in zip(files,executor.map(read_file,files)): pass file1 and file2 are arbitrary text files in the data directory. I am getting the following error (basically a process tries to read data_dir variable before it is assigned): concurrent.futures.process._RemoteTraceback: """ Traceback (most recent call last): File "C:\Users\my_username\AppData\Local\Continuum\Anaconda3\lib\concurrent\futures\process.py", line 175, in _process_worker r = call_item.fn(*call_item.args, **call_item.kwargs) File "C:\Users\my_username\AppData\Local\Continuum\Anaconda3\lib\concurrent\futures\process.py", line 153, in _process_chunk return [fn(*args) for args in chunk] File "C:\Users\my_username\AppData\Local\Continuum\Anaconda3\lib\concurrent\futures\process.py", line 153, in &lt;listcomp&gt; return [fn(*args) for args in chunk] File "C:\Users\my_username\Downloads\example.py", line 5, in read_file with open(os.path.join(data_dir, file),buffering=1000) as f: NameError: name 'data_dir' is not defined """ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "example.py", line 16, in &lt;module&gt; for file,_ in zip(files,executor.map(read_file,files)): File "C:\Users\my_username\AppData\Local\Continuum\Anaconda3\lib\concurrent\futures\_base.py", line 556, in result_iterator yield future.result() File "C:\Users\my_username\AppData\Local\Continuum\Anaconda3\lib\concurrent\futures\_base.py", line 405, in result return self.__get_result(…
type: Question
tagged with: multiprocessing
answer count: 2
tagged with: race-condition
upvote count: 2
has title: Python multiprocessing race condition
possible better answer: http://stackoverflow.com/a/47910896

http://stackoverflow.com/comment/82922973
score: 0
has text: :( I don't have a clue what went wrong there then.
comment on: http://stackoverflow.com/q/47948160
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47917990
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47917926
type: Answer
score: 6
upvote count: 6
has body: The choices for on_delete can be found in django/db/models/deletion.py For example, models.SET_NULL is implemented as: def SET_NULL(collector, field, sub_objs, using): collector.add_field_update(field, None, sub_objs) And models.CASCADE (which is slightly more complicated) is implemented as: def CASCADE(collector, field, sub_objs, using): collector.collect(sub_objs, source=field.remote_field.model, source_attr=field.name, nullable=field.null) if field.null and not connections[using].features.can_defer_constraint_checks: collector.add_field_update(field, None, sub_objs) So, if you figure out what those arguments are then you should be able to define your own function to pass to the on_delete argument for model fields. collector is most likely an instance of Collector (defined in the same file, not sure what it's for exactly), field is most likely the model field being deleted, sub_objs is likely instances that relate to the object by that field, and using denotes the database being used. There are alternatives for custom logic for deletions too, incase overriding the on_delete may be a bit overkill for you. The post_delete and pre_delete allows you define some custom logic to run before or after an instance is deleted. from django.db.models.signals import post_save def delete_ipv4manage(sender, instance, using): print('{instance} was deleted'.format(instance=str(instance))) post_delete.connect(delete_ipv4manage, sender=IPv4Manage) And lastly you can override the delete() method of the Model/Queryset, however be aware of caveats with bulk deletes using this method: Overridden model methods are not called on bulk operations Note that the delete() method for an object is not necessarily called when deleting objects in bulk using a QuerySet or as a result of a cascading delete. To ensure customized delete logic gets executed, you can use pre_delete and/or post_delete signals.
answers question: http://stackoverflow.com/q/47917926
type: AcceptedAnswer

http://stackoverflow.com/a/47886990
has body: that all sounds like fun. Normally when you get a segmentation fault it means that you are trying to do too many things at once and it's jamming up your memory. It's possible that your code isn't just stopping without an error, it could still be going, just really really slowly. It looks like you open an image in every iteration of that loop, so maybe all the open images are using up your working memory. You could try closing the image before the end of the loop.
answers question: http://stackoverflow.com/q/47886837
has comment: http://stackoverflow.com/comment/82769380
score: 0
type: Answer

http://stackoverflow.com/comment/82729971
has text: It didn't work - still won't copy. But it's good to know that there's nothing wrong with the code (i.e I did everything right). May I ask what you're typing into the run window? I'm afraid I might be passing a wrong argument or something.
type: AnswerComment
comment on: http://stackoverflow.com/a/47881778
score: 0
type: Comment

http://stackoverflow.com/q/47943619
has comment: http://stackoverflow.com/comment/82857245
tagged with: lxml
has title: LXML can't parse transitional XHTML 1.0 schema
upvote count: 1
has comment: http://stackoverflow.com/comment/82857103
tagged with: http://stackoverflow.com/tag/xml
favorite count: 0
has comment: http://stackoverflow.com/comment/82857063
type: UnansweredQuestion
tagged with: python
tagged with: xsd
answer count: 0
downvote count: 0
score: 1
type: Question
has body: I use the latest version (4.1.1) of lxml library to validate XHTML documents against XHTML Transitional Schema, but I'm getting a strange error as lxml is throws a strange error while parsing the XML schema which is clearly valid. Does anybody have any ideas about why this error could be happening? Here is my code: In [1]: import lxml.etree In [2]: schema = lxml.etree.XMLSchema(file='xhtml1-loose.xsd') --------------------------------------------------------------------------- XMLSchemaParseError Traceback (most recent call last) &lt;ipython-input-2-d29a13bdd5f3&gt; in &lt;module&gt;() ----&gt; 1 schema = lxml.etree.XMLSchema(file='xhtml1-loose.xsd') src/lxml/xmlschema.pxi in lxml.etree.XMLSchema.__init__ (src/lxml/etree.c:204036)() XMLSchemaParseError: Element '{http://www.w3.org/2001/XMLSchema}complexType': The content is not valid. Expected is (annotation?, (simpleContent | complexContent | ((group | all | choice | sequence)?, ((attribute | attributeGroup)*, anyAttribute?)))). p.s. I took xhtml1-loose.xsd file from the official source from w3.org.
tagged with: http://stackoverflow.com/tag/xhtml

http://stackoverflow.com/comment/82881045
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47955767
type: QuestionComment
has text: Have you tried creating a super-A that is just a concatenation of copies of A of length `n`, so that you only have to do a single subtraction and a single call to `norm()`? Not sure what exactly is the bottleneck. Can you specify the order of magnitude for `n` and `m`?

http://stackoverflow.com/comment/82833763
type: QuestionComment
comment on: http://stackoverflow.com/q/47932029
has text: Which python, osx, and tensorflow versions are you using? Did you have to configure any cuda stuff separately?
score: 0
type: Comment

http://stackoverflow.com/comment/82934543
type: Comment
type: QuestionComment
has text: @mkrieger1: for example, take G = {1:[2,3,4], 2:[1,3,4], 3:[1,2,4], 4:[1,2,3]} (i.e. the complete 4-graph) and run hamilton(G,4,1,[]). It returns a NoneType object, but if you print the path instead of returning it as a value, you'll see that it actually finds all six paths starting at 1.
score: 0
comment on: http://stackoverflow.com/q/47982604

http://stackoverflow.com/a/47985512
upvote count: 3
answers question: http://stackoverflow.com/q/47985297
type: Answer
score: 3
downvote count: 0
has body: a = ['hello','world'] b = ['hello','world','im','steve'] a = set(a) b = set(b) print(a.symmetric_difference(b)) This code print elements that are only in one of the tables. Look here: https://learnpython.org/en/Sets
has comment: http://stackoverflow.com/comment/82939993

http://stackoverflow.com/a/48065914
downvote count: 0
has body: Consider Jython, Jython is an implementation of the high-level, dynamic, object-oriented language Python seamlessly integrated with the Java platform. The predecessor to Jython, JPython, is certified as 100% Pure Java. mbedded scripting - Java programmers can add the Jython libraries to their system to allow end users to write simple or complicated scripts that add functionality to the application. Interactive experimentation - Jython provides an interactive interpreter that can be used to interact with Java packages or with running Java applications. This allows programmers to experiment and debug any Java system using Jython. Rapid application development - Python programs are typically 2-10X shorter than the equivalent Java program. This translates directly to increased programmer productivity. The seamless interaction between Python and Java allows developers to freely mix the two languages both during development and in shipping products. The awesome features of Jython are as follows, Dynamic compilation to Java bytecodes - leads to highest possible performance without sacrificing interactivity. Ability to extend existing Java classes in Jython - allows effective use of abstract classes. Jython doesn't compile to "pure java", it compiles to java bytecode subsequently to class files. To develop for Android, one compile java bytecode to Dalvik bytecode. To be honest, this path of development is not official , thus you will run into lots of problem with compatibility of course.
upvote count: 2
answers question: http://stackoverflow.com/q/47968040
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/91653423

http://stackoverflow.com/a/47861695
has body: you can see python language references expression-statements.
type: Answer
accepted answer of: http://stackoverflow.com/q/47861392
answers question: http://stackoverflow.com/q/47861392
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/47888855
tagged with: python
has comment: http://stackoverflow.com/comment/82792327
tagged with: logging
type: AnsweredQuestion
downvote count: 0
score: 7
type: Question
linked to: http://stackoverflow.com/q/2183233
has comment: http://stackoverflow.com/comment/134186352
has title: Python3 add logging level
accepted answer: http://stackoverflow.com/a/47912062
tagged with: python-logging
has body: I have this code which works just fine for me. import logging import logging.handlers logger = None def create_logger(): global logger logger = logging.getLogger('Logger') logger.setLevel(logging.DEBUG) handler = logging.handlers.RotatingFileHandler("C:/Users/user/Desktop/info.log", maxBytes=1000000, backupCount=20) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) create_logger() logger.info("Text info") logger.debug("Text debug") logger.warning("Text warning") logger.error("Text error") logger.critical("Text critical") And the output looks great: 2017-12-19 15:06:43,021 - Logger - INFO - Text info 2017-12-19 15:06:43,021 - Logger - DEBUG - Text debug 2017-12-19 15:06:43,022 - Logger - WARNING - Text warning 2017-12-19 15:06:43,022 - Logger - ERROR - Text error 2017-12-19 15:06:43,022 - Logger - CRITICAL - Text critical Well, I want to add a new logging level like this: logger.message("Text message") And the output should be like this 2017-12-19 15:06:43,022 - Logger - MESSAGE - Text message
upvote count: 7
answer count: 1
has answer: http://stackoverflow.com/a/47912062
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/82743468
has text: @Divakar your code doesn't work for me. ; and : are raising syntax error
comment on: http://stackoverflow.com/q/47888396
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82906749
score: 0
comment on: http://stackoverflow.com/a/47968548
type: Comment
has text: @schwobaseggl agreed. I wonder why this answer does not get upvotes. Maybe people who ask such a basic question feel bad when they see Python's list comprehensions (else they would probably not ask the question)
type: AnswerComment

http://stackoverflow.com/a/48005552
has comment: http://stackoverflow.com/comment/82979694
has comment: http://stackoverflow.com/comment/82979824
upvote count: 5
score: 5
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48005152
has body: without any library pos = [ sum(y&gt;=0 for y in x) for x in zip(*mylist) ] neg = [ len(mylist)-x for x in pos] print(pos, neg) demo

http://stackoverflow.com/comment/82682111
has text: So I used a function "create_entry", to be called to create multiple entries. But this will not allow me to recall variable names in future as they were all initialized as "Entry".
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47858722

http://stackoverflow.com/comment/137262423
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52283085
has text: Note that as of Python 3.10, slots can be created automatically with `@dataclass(slots=True)`. See https://docs.python.org/3/library/dataclasses.html#module-contents
type: AnswerComment

http://stackoverflow.com/comment/82779300
type: Comment
has text: this works,thanks! reading a comment from above, it says : """Docstring: __import__(name, globals=None, locals=None, fromlist=(), level=0) -> module Import a module. Because this function is meant for use by the Python interpreter and not for general use it is better to use importlib.import_module() to programmatically import a module.""" is there a way to do this with import_module as its the "proper" python way?
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/47899097

http://stackoverflow.com/comment/82805885
comment on: http://stackoverflow.com/q/47919127
type: Comment
has text: please include the code you have tried and sample text
type: QuestionComment
score: 1

http://stackoverflow.com/comment/114391590
comment on: http://stackoverflow.com/a/47874375
type: Comment
type: AnswerComment
has text: @slogan621: only in Python 2, as inheriting from `object` makes it a new-style class. In Python 3 all classes are new-style classes. `super()` only works in new-style classes.
score: 0

http://stackoverflow.com/comment/82815141
score: 0
type: Comment
type: QuestionComment
has text: @MarkSetchell: Hmm I have no limitation in this direction. Currently I configure the SimpleBlobDetector with params that tell him to use no limits at all.
comment on: http://stackoverflow.com/q/47920789

http://stackoverflow.com/comment/82764000
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47898340
has text: We are not seeing //[@id="VF"] anywhere in your html code

http://stackoverflow.com/q/47878204
has comment: http://stackoverflow.com/comment/82724517
has comment: http://stackoverflow.com/comment/82722510
tagged with: dataframe
score: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/82722622
has answer: http://stackoverflow.com/a/47878467
favorite count: 0
has comment: http://stackoverflow.com/comment/82722455
has comment: http://stackoverflow.com/comment/82722618
linked to: http://stackoverflow.com/q/19618912
has comment: http://stackoverflow.com/comment/82722393
tagged with: python
type: AnsweredQuestion
has title: Create new df if value in df one column is included in df two same column name
has comment: http://stackoverflow.com/comment/82722529
has comment: http://stackoverflow.com/comment/82722518
accepted answer: http://stackoverflow.com/a/47878467
upvote count: 1
has comment: http://stackoverflow.com/comment/82722730
downvote count: 1
type: Question
has body: I was on here a couple days ago, and I am going to try to reword my question better. I am working with Python and Pandas and trying to do a certain task. I am working with two dataframes and they both have student IDs in there. I want to be able to merge a new dataframe together if column 2 contains a student id that is in column one. Does anybody know how to do this? I tried researching and using pd.melt(),pd.merge(), and join. But I do not believe it does not get the job done for me. Example in a df1 column, "student", id is 1234. If df2 has that same student ID, put it in the dataframe. That way I have all the grades of one particular student in one df and they are in a different df from a different group of students. Unless you truly find the answer, please do not just mark as duplicate because I have been searching for days for the answer.

http://stackoverflow.com/comment/82701317
type: Comment
has text: It's optional. Don't provide it for your case. It is used for temp session token that you use with STS.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47868159

http://stackoverflow.com/comment/82959641
type: Comment
comment on: http://stackoverflow.com/a/47990761
score: 0
has text: the library no longer supports the recent django version and i am still looking for a concrete solution to the issue
type: AnswerComment

http://stackoverflow.com/comment/82752579
type: QuestionComment
comment on: http://stackoverflow.com/q/47892944
has text: How can the output be C,D,F,G,A if the input is B? Shouldn't it be only C and D?
score: 0
type: Comment

http://stackoverflow.com/a/47955401
has comment: http://stackoverflow.com/comment/82880885
has comment: http://stackoverflow.com/comment/82880767
has comment: http://stackoverflow.com/comment/82880914
downvote count: 1
has body: You could do num = dict(zip(range(1,6), 'abcde')).get(var, 'f') # f in case you need a default using the dictionary pattern to mimick a switch. You just build a mapping for all the cases and use dict.get with a default value: d = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'} num = d.get(var, 'f') If your data and mapping are as regular and trivial as in your example, there are even easier ways, e.g.: num = 'abcde'[var - 1]
upvote count: 5
answers question: http://stackoverflow.com/q/47955389
has comment: http://stackoverflow.com/comment/82881101
score: 4
type: Answer

http://stackoverflow.com/comment/82722053
comment on: http://stackoverflow.com/q/47877726
score: 0
has text: Have you tried specifying the _pip_ version?(I.e. `pip2 install matplotlib`)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82896224
has text: `s1=' abdjjc Item ljapoge ' print re.sub(r'(<table.*?>(?!.*Item).* )', 'FOO', s1) s2=' abdjjc Item <> ljapoge ' print re.sub(r'(<table.*?>(?!.*Item).* )', 'FOO', s2)` For the code I above, it doesn't match s1 but it matches s2. I don't want to match s2 since it also has Item in it. Thank you!
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47959185

http://stackoverflow.com/comment/82909309
type: Comment
comment on: http://stackoverflow.com/a/47961362
score: 0
type: AnswerComment
has text: @Mahesh , Please create new ticket regarding this new issue

http://stackoverflow.com/comment/82912399
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47971431
has text: If you're looping over an array, you're doing it wrong...

http://stackoverflow.com/comment/90703626
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48008086
has text: did you find a solution? I am using app engine but having similar issue
score: 0

http://stackoverflow.com/a/47930032
upvote count: 8
downvote count: 2
type: Answer
score: 6
has body: You are using the wrong parameters. In Postgres you have to use something like this: conn = pg.DB(host="localhost", user="USERNAME", passwd="PASSWORD", dbname="DBNAME") That should fix it.
has comment: http://stackoverflow.com/comment/138772114
has comment: http://stackoverflow.com/comment/115515192
answers question: http://stackoverflow.com/q/47928883
has comment: http://stackoverflow.com/comment/82839245
has comment: http://stackoverflow.com/comment/112661291

http://stackoverflow.com/a/47931183
upvote count: 0
has comment: http://stackoverflow.com/comment/82831198
downvote count: 1
score: -1
has body: Try the following steps Cast the column into datetime format. Use the .month method to get the month number Use the shift() method in pandas to calculate difference example code will look something like this df['diff_mnts'] = date_dt.month - date_dt.shift().month
answers question: http://stackoverflow.com/q/47931088
type: Answer

http://stackoverflow.com/comment/82684382
score: 0
type: Comment
type: QuestionComment
has text: I tried to make the code snippet a bit more compact and easier to read. Sorry for copying the entire thing last time
comment on: http://stackoverflow.com/q/47859521

http://stackoverflow.com/comment/82738422
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47886113
has text: You are having a typo : `args="--file=\"${_file}\" –-title=\"${_file}\" –-description=\"show 2018\" -–keywords=\"2018,show, Winter,show 2018,\" -–category=\"28\" -–privacyStatus=\"private\""` Watch out `--file=\"${_file}\" –-title=` there is an `–-`instead of `--`

http://stackoverflow.com/comment/82723939
comment on: http://stackoverflow.com/q/47862070
score: 0
has text: @atru i think it is the problem.thanks! the values are float numbers.when i print them , it maynot show the precise number and i cannot get a result from searching it.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47904699
score: 0
has comment: http://stackoverflow.com/comment/82776866
accepted answer of: http://stackoverflow.com/q/47902803
has comment: http://stackoverflow.com/comment/82777163
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82777207
answers question: http://stackoverflow.com/q/47902803
has comment: http://stackoverflow.com/comment/82777479
type: Answer
has comment: http://stackoverflow.com/comment/82777438
has comment: http://stackoverflow.com/comment/82776296
has body: I believe you need between with np.where or cast boolean to ints and then to strings: rng = pd.date_range('2010-03-12 15:00:00', periods=10, freq='20H') X = pd.DataFrame({'Datetime': rng}) mask = X['Datetime'].between('2010-03-12 16:49:00', '2010-03-14 16:49:00') #solution1 X['CLASS'] = np.where(mask,'1','0') #solution2 #X['CLASS'] = mask.astype(int).astype(str) print (X) Datetime CLASS 0 2010-03-12 15:00:00 0 1 2010-03-13 11:00:00 1 2 2010-03-14 07:00:00 1 3 2010-03-15 03:00:00 0 4 2010-03-15 23:00:00 0 5 2010-03-16 19:00:00 0 6 2010-03-17 15:00:00 0 7 2010-03-18 11:00:00 0 8 2010-03-19 07:00:00 0 9 2010-03-20 03:00:00 0 EDIT: rng = pd.date_range('2010-03-12 16:35:00', periods=30, freq='T') X = pd.DataFrame({'Datetime': rng}) #same output as below #conditions = [X['Datetime'] &lt; '2010-03-12 16:39:00', # (X['Datetime'] &lt; '2010-03-12 16:49:00') &amp; (X['Datetime']&gt;= '2010-03-12 16:39:00'), # X['Datetime']&gt;='2010-03-12 17:01:00'] conditions = [X['Datetime'] &lt; '2010-03-12 16:39:00', X['Datetime'].between('2010-03-12 16:39:00','2010-03-12 16:48:00'), X['Datetime']&gt;='2010-03-12 17:01:00'] classes = ['0','1','2'] #gaps are repalced to NaNs X['CLASS'] = np.select(conditions, classes, default=np.nan) #if want bin all data without gaps bins = pd.DatetimeIndex(['1900-01-01', '2010-03-12 16:38:00', '2010-03-12 16:48:00', '2262-04-11']) labels=['0','1','2'] X['label'] = pd.cut(X['Datetime'], bins=bins, labels=labels, right=True) print (X) Datetime CLASS label 0 2010-03-12 16:35:00 0 0 1 2010-03-12 16:36:00 0 0 2 2010-03-12 16:37:00 0 0 3 2010-03-12 16:38:00 0 0 4 2010-03-12 16:39:00 1 1 5 2010-03-12 16:40:00 1 1 6 2010-03-12 16:41:00 1 1 7 2010-03-12 16:42:00 1 1 8 2010-03-12 16:43:00 1 1 9 2010-03-12 16:44:00 1 1 10 2010-03-12 16:45:00 1 1 11 2010-03-12 16:46:00 1 1 12 2010-03-12 16:47:00 1 1 13 2010-03-12 16:48:00 1 1 14 2010-03-12 16:49:00 nan 2 15 2010-03-12 16:50:00 nan 2 16 2010-03-12 16:51:00 nan 2 17 2010-03-12 16:52:00 nan 2 18 2010-03-12 16:53:00 nan…
has comment: http://stackoverflow.com/comment/82776809

http://stackoverflow.com/comment/82823293
has text: If you can remove the first bit of your answer, and elaborate on `df.eval`, you'll have my upvote.
type: AnswerComment
comment on: http://stackoverflow.com/a/47927498
type: Comment
score: 0

http://stackoverflow.com/comment/105120988
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48017495
type: AnswerComment
has text: @S.K.Venkat Checkout [Chromeoptions and setExperimentalOption code](https://stackoverflow.com/questions/49465124/chromeoptions-and-setexperimentaloption-code/49469595#49469595)

http://stackoverflow.com/q/47970964
has answer: http://stackoverflow.com/a/70994934
has title: Pyusb isn't working
has body: I got Pyusb with pip install pyusb but when I try to import usb.core I get: Traceback (most recent call last): File "&lt;pyshell#0&gt;", line 1, in &lt;module&gt; import usb.core File "C:\Users\Owner\Desktop\usb.py", line 1, in &lt;module&gt; import pyusb ImportError: No module named 'pyusb' I also tried installing pyusb-1.0.2.tar.gz manuall with pip, but that didn't fix the issue.
has comment: http://stackoverflow.com/comment/82911518
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82911811
has comment: http://stackoverflow.com/comment/82911428
type: Question
tagged with: pyusb
has comment: http://stackoverflow.com/comment/82911568
answer count: 1
has comment: http://stackoverflow.com/comment/82911767
has comment: http://stackoverflow.com/comment/82911461
has comment: http://stackoverflow.com/comment/82911699
tagged with: python

http://stackoverflow.com/q/47891130
type: Question
has title: Adding two lists to the first column and last row of string
tagged with: class
score: 0
answer count: 3
accepted answer: http://stackoverflow.com/a/47891500
tagged with: matrix
tagged with: arrays
possible better answer: http://stackoverflow.com/a/47891353
has answer: http://stackoverflow.com/a/47891367
has answer: http://stackoverflow.com/a/47891353
favorite count: 0
tagged with: python
type: AnsweredQuestion
tagged with: list
has body: I have this code: def __repr__(self): """ :return: Return a string representation of the board. """ list1=['0','1','2','3','4','5','-'] list2=['0','1','2','E','4','5'] output='' for row in self.board: output=output+str(row)+'\n' return output self.board is list of lists with the output below, the output of this is this matrix as string : ['_', '_', '_', 'R', '_', '_'] ['_', '_', '_', 'R', '_', '_'] ['_', '_', '_', '_', '_', '_'] ['_', '_', '_', '_', '_', '_'] ['_', '_', '_', '_', '_', '_'] ['p', 'p', '_', '_', '_', '_'] Now, what I want as you see in the code I have defined two lists , I want to add the list1 as the first column in this string , and the list2 as the last row , I still cannot figure out how can I do that exactly.. this is the output I want to do: ['0', '_', '_', '_', 'R', '_', '_'] ['1', '_', '_', '_', 'R', '_', '_'] ['2', '_', '_', '_', '_', '_', '_'] ['3', '_', '_', '_', '_', '_', '_'] ['4', '_', '_', '_', '_', '_', '_'] ['5', 'p', 'p', '_', '_', '_', '_'] ['-', '0', '1', '2', 'E', '4', '5'] Any ideas to update my code in order to manage that? Thanks!
has answer: http://stackoverflow.com/a/47891500
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/47970629
has body: I'm using sklearn Decision Tree Classifier with some continuous features. When I run export_graphviz I see the same features in more than one nodes and with different values. Example: I would like to take the top important ones and want to use feature_importances_ for that. The problem is that feature_importances_ is array without reference to the tree nodes. I have the original features but as each one can be more than one time in the tree I'm not sure how to relate importance to node.
score: 2
answer count: 0
upvote count: 3
type: UnansweredQuestion
has title: python sklearn decision tree classifier feature_importances_ with feature names when using continuous values
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/82922526
tagged with: scikit-learn
tagged with: decision-tree
tagged with: data-science
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/82883011
type: QuestionComment
comment on: http://stackoverflow.com/q/47956695
score: 0
has text: Note that `entry_widget.get()` isn't the same thing as `entry_widget.get`.
type: Comment

http://stackoverflow.com/q/47866857
downvote count: 1
has title: initiate random play without clicking mouse
tagged with: python
upvote count: 0
has body: I am writing a code that plays a game by selecting values randomly when the mouse is clicked. def random_play(event): #some random selections fig.canvas.draw() cid = fig.canvas.mpl_connect('button_press_event',random_play) How to play the game as soon as I run the code without the need to click the mouse?
type: Question
type: AnsweredQuestion
tagged with: matplotlib
score: -1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47866960
accepted answer: http://stackoverflow.com/a/47866960

http://stackoverflow.com/a/47882397
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47882237
has body: The solution given by Wiktor in the comment above works. Reproduction: Install regex library: pip install regex Run the following in python shell: &gt;&gt;&gt; import regex &gt;&gt;&gt; r=regex.compile("(?&lt;=(AA|BBB)12345)") &gt;&gt;&gt; r.findall('AA12345') ['AA'] &gt;&gt;&gt; r.findall('BBB12345') ['BBB'] &gt;&gt;&gt; r.findall('CCC12345') []
upvote count: 2
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47882237

http://stackoverflow.com/comment/82842923
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47936741
has text: I have no clue why you're filling a list with a, b, c, d and then subsequently replacing it with something else. Why not just create an empty list and then use `list.append`?

http://stackoverflow.com/a/47971528
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82920363
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47971491
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47971491
has body: There are two buttons with the login-submit name and you are clicking the wrong one. Adjust your locator to target the desired form submit button: submit = driver.find_element_by_css_selector("#main button[name=login-submit]") submit.click() You can also submit the form using the submit() method directly: username.submit() The appropriate form submit button would then be located and "clicked" automatically.
type: Answer

http://stackoverflow.com/q/47859759
has comment: http://stackoverflow.com/comment/89911412
type: Question
has title: Why does my powerset function run out of memory?
accepted answer: http://stackoverflow.com/a/47859812
answer count: 1
has comment: http://stackoverflow.com/comment/82684258
favorite count: 0
score: 0
tagged with: python
tagged with: powerset
upvote count: 1
has answer: http://stackoverflow.com/a/47859812
downvote count: 1
has body: def powerset(x): total1 = [[]] total2 = [[]] for a in x: for b in total1: c = list(b + [x[a]]) total2.append(c) total1 = total2 # the total 1 and total 2 system should prevent it # from creating an infinite loop when we add to the total. print (total1) f = [1,2,3] g = powerset(f) print (g) Here is my attempt at creating a powerset for an intro to data science class. When I run this I receive [[], [2]] as outputs before running out of memory. I don't understand why it it returns [[], [2]] nor why it runs out of memory, since total1 is changed outside of the loop. The variable g should return a power set of f. Could somebody explain what I'm doing wrong?
type: AnsweredQuestion

http://stackoverflow.com/comment/82895120
type: AnswerComment
has text: @MihanEntalpo So I merged both models back into models.py in the root directory to avoid confusion so admin.py and models.py are in the same directory but now `from .models import Post` doesn't work.
comment on: http://stackoverflow.com/a/47962816
score: 0
type: Comment

http://stackoverflow.com/comment/83055359
has text: How can I check if I have more than one python installed?
type: QuestionComment
comment on: http://stackoverflow.com/q/47983662
type: Comment
score: 0

http://stackoverflow.com/q/47911863
tagged with: python
has title: Setting indexes in pandas dataframe subclass
has body: What I want to do: I am currently building a subclass of the pandas DataFrame using python 3. One feature of the class is the user inputs their data as well as the names of columns to use to create a MultiIndex for the class at time of construction. However, I am struggling for find a clean way of doing this. Failed Strategy #1 My first attempt looked something like the following where I try to construct the data and the index values before calling the DataFrame constructor: class DFSubClass(pd.DataFrame): @property def _constructor(self): return DFSubClass def __init__(self, data=None, #other DataFrame parameters#, col_for_multi_index = None): multi_index = CreateMultiIndex(data, col_for_multi_index) data_subset = RemoveIndexColumnsFromData(data, col_for_multi_index) super(DFSubClass,self).__init__(data = data_subset, index = multi_index, #other DataFrame parameters#) multi_index = ComputeMultiIndexFromColumns(data, col_for_multi_index) self = self.set_index(multi_index) While I was able to makes something that I think works for ComputeMultiIndexFromColumns(): def ComputeMultiIndexFromColumns(data = None, cols = None): index_values = [np.array(data[i]) for i in cols] index = pd.MultiIndex.from_arrays(index_values, names=cols) return index I couldn't figure out anything for RemoveIndexColumnsFromData() that would cleanly handle all of the different data types a pandas constructor can accept (i.e. numpy arrays, dicts, other DataFrames). Also, when the input was a DataFrame, I ran into this problem where the constructor returns all NaNs because the previous indexes don't match the new index values. Failed Strategy #2 At this point I decided to not reinvent the wheel and let the pandas package handle these problems by first calling the DataFrame constructor and then using the set_index() functionality to re-index my data: class DFSubClass(pd.DataFrame): @property def _constructor(self): return DFSubClass def __init__(self, data=None, #other DataFrame parameters#, col_f…
score: 0
linked to: http://stackoverflow.com/q/27193186
has answer: http://stackoverflow.com/a/48654080
type: Question
tagged with: dataframe
tagged with: inheritance
tagged with: pandas
answer count: 1
tagged with: constructor
type: UnansweredQuestion

http://stackoverflow.com/q/47869521
tagged with: ubuntu
tagged with: linux
tagged with: python-module
has body: I often encounter some python packages (which I installed using pip) which can be accessed like a standalone binary on Terminal . Not just a python module . I want to know the standard way to create a package which can be installed by $pip install mypackage ( or by $python setup.py install) and is also available like $mypackage from anywhere. I know that I can access the __main__.py file by $python -m mypackage . But I want my package to function just like any binary stored in /usr/bin . I am not looking for any alias/path variable hack and don't want to create .deb/.rpm stuffs . EDIT: I got help from commentbox . Eventually , setuptools already has the option . Setuptools Documention entry_point parameter of setup() function does the trick . setup( # other arguments here... entry_points={ 'console_scripts': [ 'foo = my_package.some_module:main_func', 'bar = other_module:some_func', ], 'gui_scripts': [ 'baz = my_package_gui:start_func', ] } Here entry_point takes a dictionary whose value contains a list . Two CLI scripts named foo and bar are created which contains function main_func and some_func respectively from my_package.some_module and other_module . Gui scripts can also be created via this method .
has comment: http://stackoverflow.com/comment/82704111
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82704403
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/82742589
has comment: http://stackoverflow.com/comment/121992385
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/82705429
type: Question
has comment: http://stackoverflow.com/comment/82704089
has title: How to install a Python package system-wide on Linux?

facebook
tags question: http://stackoverflow.com/q/47983156
type: Tag
tags question: http://stackoverflow.com/q/47953384
tag name: facebook
tags question: http://stackoverflow.com/q/48004466

http://stackoverflow.com/comment/82972267
has text: perfect! This is exactly what i was looking for!
type: Comment
comment on: http://stackoverflow.com/a/48001617
score: 0
type: AnswerComment

oop
tags question: http://stackoverflow.com/q/47954904
tags question: http://stackoverflow.com/q/48014503
tags question: http://stackoverflow.com/q/47997537
tags question: http://stackoverflow.com/q/47981164
tags question: http://stackoverflow.com/q/47878170
tag name: oop
tags question: http://stackoverflow.com/q/47997805
tags question: http://stackoverflow.com/q/47955005
tags question: http://stackoverflow.com/q/47873402
tags question: http://stackoverflow.com/q/47868009
tags question: http://stackoverflow.com/q/47861343
tags question: http://stackoverflow.com/q/47876517
tags question: http://stackoverflow.com/q/47888904
tags question: http://stackoverflow.com/q/47865002
tags question: http://stackoverflow.com/q/47907655
tags question: http://stackoverflow.com/q/47980075
tags question: http://stackoverflow.com/q/47927026
tags question: http://stackoverflow.com/q/47856233
tags question: http://stackoverflow.com/q/47963008
tags question: http://stackoverflow.com/q/48006803
tags question: http://stackoverflow.com/q/47890055
tags question: http://stackoverflow.com/q/47974960
tags question: http://stackoverflow.com/q/47972736
type: Tag
tags question: http://stackoverflow.com/q/47920589
tags question: http://stackoverflow.com/q/47870331

http://stackoverflow.com/q/48006488
has title: Tensorflow ValueError: Batch length of predictions should be same
score: 2
upvote count: 2
type: UnansweredQuestion
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/50039300
tagged with: python-2.7
tagged with: batch-processing
answer count: 1
has body: I'm trying to visualize the output of a convolutional autoencoder using TensorFlow Estimator API input_fn = tf.estimator.inputs.numpy_input_fn( x={"x": train_data}, y=None, batch_size=8, num_epochs=None, shuffle=True) autoencoder = tf.estimator.Estimator(model_fn=autoencoder_model_fn, model_dir=model_dir) tensors_to_log = {"loss": "loss"} logging_hook = tf.train.LoggingTensorHook(tensors=tensors_to_log, every_n_iter=1000) autoencoder.train( input_fn=input_fn, steps=50000, hooks=[logging_hook]) input_fn_predict = tf.estimator.inputs.numpy_input_fn( x={"x": train_data}, y=None, batch_size=1, num_epochs=None, shuffle=False) predictions = autoencoder.predict(input_fn=input_fn_predict) predictions = [p['decoded_image'] for p in predictions] print predictions[0].shape I get the following error : Traceback (most recent call last): File "AutoEncoder.py", line 164, in &lt;module&gt; main() File "AutoEncoder.py", line 157, in main predictions = [p['decoded_image'] for p in predictions] File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/estimator/estimator.py", line 425, in predict for i in range(self._extract_batch_length(preds_evaluated)): File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/estimator/estimator.py", line 592, in _extract_batch_length 'different batch length then others.' % key) ValueError: Batch length of predictions should be same. features has different batch length then others. Can anybody see what I did wrong? As I understand it, my batch size during prediction is a constant, equal to 1... Thanks in advance!
downvote count: 0
favorite count: 0
tagged with: python

http://stackoverflow.com/a/47976981
type: Answer
has comment: http://stackoverflow.com/comment/82926219
has comment: http://stackoverflow.com/comment/82933084
accepted answer of: http://stackoverflow.com/q/47976748
upvote count: 1
answers question: http://stackoverflow.com/q/47976748
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82926167
has comment: http://stackoverflow.com/comment/82933120
has body: First, set country to be the index for every dataframe. df_list = [df1, df2, ...] for i, df in enumerate(df_list): df_list[i] = df.set_index('country') Next, concatenate them by axis, find the max along each row, and reset the index. df = pd.concat(df_list, axis=1)\ .max(axis=1)\ .to_frame('max_value')\ .reset_index() df country max_value 0 A 8.518074e+11 1 B 1.138434e+11 2 C 8.745698e+10 3 D 7.543453e+10 4 E 6.387533e+10 If you want an indicator in your result, you'll need to modify your code a bit, to add a new indicator column, and then perform a concatenation along the 0th axis, and find the idxmax of each group - df_list = [df1, df2, ...] for i, df in enumerate(df_list): df_list[i] = df.assign(indicator=i + 1) df = pd.concat(df_list, ignore_index=True) df.loc[df.groupby('country')['value'].idxmax().values] df country value indicator 0 A 8.518074e+11 1 1 B 1.138434e+11 1 2 C 8.745698e+10 1 3 D 7.543453e+10 1 4 E 6.387533e+10 1

http://stackoverflow.com/comment/82724852
has text: @running.t Yes, I did commit it as a file and it renders perfectly on GitHub but I want to create a gist(one that renders by notebook) so that I can easily embed it in my jekyll-based static blog.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47868625

http://stackoverflow.com/q/47935253
accepted answer: http://stackoverflow.com/a/47935340
type: AnsweredQuestion
has body: I am trying to plot VGG16 architecture diagram using Keras. However, i see the below image with None, some dimension. What does None mean, is that a bug ? from keras.utils import plot_model model = VGG19(include_top=True, weights='imagenet') #print(model.summary()) plot_model(model, to_file='model_Vgg19.png',show_shapes=True) I can see that this is a known issue in Keras: https://github.com/keras-team/keras/issues/1877.
has answer: http://stackoverflow.com/a/47935340
type: Question
has title: Keras model to plot gives none, dimensions
linked to: http://stackoverflow.com/q/49705084
score: 0
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/131328040
answer count: 1
tagged with: keras
tagged with: python

http://stackoverflow.com/comment/82964453
score: 0
type: AnswerComment
has text: @user61629 Shouldn't be the case unless you have multiple instances of `Tk`.
type: Comment
comment on: http://stackoverflow.com/a/47996869

http://stackoverflow.com/comment/82880264
type: Comment
has text: How about using `FormView`? It has an attribute `success_url`, where you could specify your next page and in the method `form_valid` you could implement the logic.
type: QuestionComment
comment on: http://stackoverflow.com/q/47953973
score: 0

http://stackoverflow.com/a/47973372
upvote count: 1
score: 1
has body: On the new machine you must source venv/bin/activate so your path environment variables are set properly. In particular, which python should say venv/bin/python rather than /usr/bin/python. Also, take care to conda env update or pip install -r requirements.txt so you'll have suitable venv libraries on the new machine.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47973244

http://stackoverflow.com/comment/82967836
score: 0
type: Comment
type: QuestionComment
has text: @Ryan Oups! You are right, thank you very much!
comment on: http://stackoverflow.com/q/47999634

http://stackoverflow.com/q/47981171
linked to: http://stackoverflow.com/q/31172719
has body: Yesterday, I installed Django on my aunt's pc and it worked wonders. Today, I'm trying to install it on my pc, and it gives the following error: Exception: Traceback (most recent call last): File "c:\program files\python36-32\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\program files\python36-32\lib\site-packages\pip\commands\install.py", line 342, in run prefix=options.prefix_path, File "c:\program files\python36-32\lib\site-packages\pip\req\req_set.py", line 784, in install **kwargs File "c:\program files\python36-32\lib\site-packages\pip\req\req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "c:\program files\python36-32\lib\site-packages\pip\req\req_install.py", line 1064, in move_wheel_f isolated=self.isolated, File "c:\program files\python36-32\lib\site-packages\pip\wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "c:\program files\python36-32\lib\site-packages\pip\wheel.py", line 316, in clobber ensure_dir(destdir) File "c:\program files\python36-32\lib\site-packages\pip\utils\__init__.py", line 83, in ensure_dir os.makedirs(path) File "c:\program files\python36-32\lib\os.py", line 220, in makedirs mkdir(name, mode) PermissionError: [WinError 5] Acceso denegado: 'c:\\program files\\python36-32\\Lib\\site-packages\\pytz' I'm counting on you guys. I'm new to this world, and I'm willing to learn. P.D.: "Acceso denegado" = "Access denied"
has comment: http://stackoverflow.com/comment/82930838
has comment: http://stackoverflow.com/comment/82930855
type: UnansweredQuestion
tagged with: web-applications
tagged with: django
tagged with: python
answer count: 0
score: 0
type: Question
has title: Error during Pip Django Install

http://stackoverflow.com/comment/82698131
has text: but i want to use A as as constant like on integrating Asin(x) we get -Acos(x) +c
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47866140
type: AnswerComment

http://stackoverflow.com/comment/82926217
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47978371
has text: Thanks, that explains my issue. Unfortunatelly, `__text_signature__` returns None. But I will have a closer look at you link.
type: AnswerComment

celery
tags question: http://stackoverflow.com/q/47932483
tags question: http://stackoverflow.com/q/47929932
tags question: http://stackoverflow.com/q/47889252
tags question: http://stackoverflow.com/q/47923169
tags question: http://stackoverflow.com/q/48000561
tag name: celery
tags question: http://stackoverflow.com/q/47979831
tags question: http://stackoverflow.com/q/47953643
tags question: http://stackoverflow.com/q/47965384
tags question: http://stackoverflow.com/q/47882213
tags question: http://stackoverflow.com/q/48014309
tags question: http://stackoverflow.com/q/47996392
tags question: http://stackoverflow.com/q/47912542
type: Tag
tags question: http://stackoverflow.com/q/48003587
tags question: http://stackoverflow.com/q/47897121
tags question: http://stackoverflow.com/q/47938133

http://stackoverflow.com/comment/82746023
has text: Thanks, @jezrael. For what I understand, that will also copy the entries where the years are ok. Am I correct?
comment on: http://stackoverflow.com/a/47889858
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47856198
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/82751613
answer count: 0
type: Question
tagged with: geopandas
has comment: http://stackoverflow.com/comment/125669597
tagged with: python
tagged with: geoalchemy
has title: Python Insert geojson into mssql
has body: I am attempting to load geojson from a file into mssql express using sqlalchemy for the insert and geopandas to load and read the file. sqlserver examples seems to be hard to find, but below is what i was able to scrape together at this point, which doesn't work. geodataframe = geopandas.read_file(fname) geodataframe['geom'] = geodataframe['geometry'].apply(lambda x: WKTElement(x.wkt, srid=4326)) geodataframe.drop('geometry', 1, inplace=True) geodataframe.to_sql('geo', engine, if_exists='append', index=False,dtype={'geom': Geometry('POINT', srid= 4326)}) does anyone have a working example of loading geojson into Sql Server sqlexpress with python?
score: 0
has comment: http://stackoverflow.com/comment/82747657
linked to: http://stackoverflow.com/q/38361336
type: UnansweredQuestion
tagged with: sqlalchemy

http://stackoverflow.com/comment/82739517
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47882092
score: 0
has text: Unfortunately not, as far as I know, PySpark does not allow you to create UDAF (user defined aggregation functions) as this stage.

http://stackoverflow.com/q/47894597
type: Question
tagged with: pyspark
has body: I wrote a pyspark script to loop through tables in a hive database and do something with them (can't say exactly what per company policy), for example: hc = HiveContext(sc) for table in tables: df = hc.sql("select * from {}".format(table)) df.do_something() df.unpersist() It works fine until I get a few tables in and then I get an error: ERROR DiskBlockObjectWriter:... java.io.FileNotFoundException ... (Too many open files) This is because of all the intermediate files spark creates before shuffle. I thought I could avoid this by unpersisting the data frame (df.unpersist()) immediately after using it and going into the next loop, but that doesn't seem to help. Is there a way I can close all open files after use and before the next loop? Once I finish each loop, I have no more use for that df. I am certain there is no issue with the specific table that it fails on because I can read that specific table into a DF just fine as long as I haven't opened too many other ones previously.
has comment: http://stackoverflow.com/comment/82757854
score: 0
tagged with: apache-spark
has title: Close Intermediate Files After Loop Pyspark
has comment: http://stackoverflow.com/comment/82758026
answer count: 0
has comment: http://stackoverflow.com/comment/82757550
type: UnansweredQuestion
tagged with: python
tagged with: dataframe

http://stackoverflow.com/q/47946875
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/47947032
favorite count: 0
has comment: http://stackoverflow.com/comment/82865091
tagged with: python
has answer: http://stackoverflow.com/a/47948284
has title: get the Alarm object of CloudWatch using boto 2
type: AnsweredQuestion
downvote count: 0
score: 1
possible better answer: http://stackoverflow.com/a/47948284
has comment: http://stackoverflow.com/comment/82865628
has body: I created an alarm and want to delete it afterward... The documentation for boto 2 doesn't show how to do that. Any help ? Thanks
tagged with: amazon-cloudwatch
type: Question
tagged with: amazon-ec2
tagged with: boto3
tagged with: amazon-web-services
accepted answer: http://stackoverflow.com/a/47947032

http://stackoverflow.com/comment/82961023
type: QuestionComment
has text: Install anaconda and jupyter notebook/lab. Best environment for newbies I think :)
comment on: http://stackoverflow.com/q/47996460
score: 0
type: Comment

http://stackoverflow.com/a/48007454
type: Answer
has body: It's probably best not to do this in nginx alone, because your webapp probably generates URLs of its own, and some of these might contain absolute paths. So if it thinks it's hosted at /, it will generate the wrong URLs, and nginx has no way to know. If you really want to do it this way, you might try a rewrite rule like this: location /xml { rewrite /xml(.*) $1 break; proxy_pass http://127.0.0.1:6544; }
answers question: http://stackoverflow.com/q/48006981
score: 0

http://stackoverflow.com/comment/82736474
type: QuestionComment
has text: you can just use `set()` for it. you will get all unique items only
score: 2
comment on: http://stackoverflow.com/q/47885362
type: Comment

http://stackoverflow.com/a/47942612
type: Answer
has body: To skip your ambiguous sequences, you have 2 solutions that come into my mind. You could either use if nucl in nucleotide_weigths. It will check whether or not the character exists in the dictionnary. If it does, it will return True and you can evaluate this nucl element, and it will return False if the character is not found. You could then do : if nucl not in nucleotide_weigths: break So that it breaks the actual sequence if it is ambiguous. The other option is to make a try/except block. It basically works like this : try: mol_weight += nucleotide_weights[nucl] except: break You can specify an error after the keyword except so it doesn't stop any errors coming (you don't want this), but what you need to know is : If an exception is raised (e.g : ValueError, IndexError, KeyError, TypeError, ...), the code in the except block will run. And so the break statement will get you out of your loop and this ambiguous sequence will be eluded. :) As for your function needs, and double-loops I think the error comes from the first part where you'd have some errors trying to check a data you didn't have registered. If it's not the same, please post the code you tried for the double-loops and the traceback. :)
score: 0
answers question: http://stackoverflow.com/q/47942453

modal-dialog
tag name: modal-dialog
type: Tag
tags question: http://stackoverflow.com/q/47879413

http://stackoverflow.com/comment/82898608
comment on: http://stackoverflow.com/a/47964408
type: AnswerComment
has text: The Brobdingnag package doesn't define `as.character()`.
score: 0
type: Comment

http://stackoverflow.com/a/47917281
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47915356
upvote count: 10
type: Answer
has body: Even though not quite understand your question, due to lack of background of your aws related problem. It's doable to use context to do this, just as you mentioned. import threading import time class Sleeper(threading.Thread): def __init__(self, sleep=5.0): threading.Thread.__init__(self, name='Sleeper') self.stop_event = threading.Event() self.sleep = sleep def run(self): print('Thread {thread} started'.format(thread=threading.current_thread())) while self.sleep &gt; 0 and not self.stop_event.is_set(): time.sleep(1.0) self.sleep -= 1 print('Thread {thread} ended'.format(thread=threading.current_thread())) def stop(self): self.stop_event.set() def __enter__(self): self.start() return self def __exit__(self, *args, **kwargs): self.stop() print('Force set Thread Sleeper stop_event') with Sleeper(sleep=2.0) as sleeper: time.sleep(5) print('Main Thread ends') You can test the two cases: 1. main sleep more time, 2. Sleeper thread has a bigger sleep parameter, they will end up two results; If you still want to interact with the Sleeper thread with the main, your code should looks like this: with Sleeper(sleep=2.0) as sleeper: cnt = 15 while cnt &gt; 0 and sleeper.is_alive(): print(cnt) cnt -= 1 time.sleep(1) And you can see the main just print a few number, due to the sleeper has end and is not alive anymore.
downvote count: 0
score: 10
answers question: http://stackoverflow.com/q/47915356

http://stackoverflow.com/a/47959287
score: 1
answers question: http://stackoverflow.com/q/47959204
downvote count: 0
type: Answer
upvote count: 1
has body: Return Statement terminate loop and end program. If c % 2 == 0 is True, it Return True and terminate program not check all values. Try This def allEven(n): for c in n: if c % 2 == 0: continue else: return False return True

http://stackoverflow.com/q/47873270
downvote count: 1
type: Question
has body: Suppose I have the text: text = 'Washington state Washington DC" I want my new output to be 'WA state Washington DC' I've tried re.sub('Washington(\s[^DC])', 'WA ', text) and get the following output that drops the first letter of "state": 'WA tate Washington DC' Basically, I want every instance of "Washington" to be changed to "WA" as long as it doesn't precede "DC". I'm sure there is a really easy way to do this and my brain just doesn't feel like working today! (I'm using Python 3.x) Please help! Thanks
possible better answer: http://stackoverflow.com/a/47873600
has comment: http://stackoverflow.com/comment/82711947
score: -1
answer count: 3
upvote count: 0
has answer: http://stackoverflow.com/a/47873600
has answer: http://stackoverflow.com/a/47873349
accepted answer: http://stackoverflow.com/a/47873349
favorite count: 0
tagged with: python-3.x
has title: How do you replace only partial string with re.sub
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/47874004
type: AnsweredQuestion

http://stackoverflow.com/comment/82752925
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47892778
has text: @kabanus *technically* yes. But if you want to ensure the full number format is captured as a whole (i.e. `1.2E+23` instead of `1` and `2E+23)

http://stackoverflow.com/comment/82702056
type: Comment
comment on: http://stackoverflow.com/q/47868306
score: 0
type: QuestionComment
has text: What is the contents and date of your `logmyshit.log` file?

http://stackoverflow.com/comment/82806911
type: AnswerComment
score: 0
type: Comment
has text: Okay..Also I dont want all the elements in the Json only 4 elements for the algorithm. is there a way to pick up only those? select "macAddress","value"."speed", "value"."trackId", "value"."trackPos", "value"."battery" where "deviceType"='AnkiCar' and "param"='status'
comment on: http://stackoverflow.com/a/47919575

http://stackoverflow.com/q/47968108
has body: I want to get '8.0' from the HTML below: ==$0 "8.0" /10 ::after I have tried the code below to extract '8.0' inside div class = 'js-otelpuani', but it seems it did not work; import urllib import requests from bs4 import BeautifulSoup import pyodbc headers = { "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5)", "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "accept-charset": "cp1254,ISO-8859-9,utf-8;q=0.7,*;q=0.3", "accept-encoding": "gzip,deflate,sdch", "accept-language": "tr,tr-TR,en-US,en;q=0.8", } r = requests.get('https://www.otelz.com/otel/elvin-deluxehotel#.WkDIBd9l_IU', headers=headers) if r.status_code != 200: print("request denied") else: print("ok") soup = BeautifulSoup(r.text) score = soup.find('div',attrs={'class': 'js-otelpuani'}) print(score) I get these as output but unfortunately I could not get '8.0' value that I want to extract; ok .0 / 10 0 0 I will be grateful for any help!
type: Question
has title: Extract html div class using BeautifulSoup
has answer: http://stackoverflow.com/a/47968179
tagged with: python-3.6
tagged with: beautifulsoup
upvote count: 3
has answer: http://stackoverflow.com/a/47968198
accepted answer: http://stackoverflow.com/a/47968198
answer count: 3
favorite count: 0
tagged with: web-scraping
tagged with: python
possible better answer: http://stackoverflow.com/a/47968179
tagged with: python-requests
has answer: http://stackoverflow.com/a/47968235
type: AnsweredQuestion
score: 3
downvote count: 0

http://stackoverflow.com/comment/82939465
score: 2
has text: BTW if you want to make a formal answer so I can mark you as the best answer, that'd be great so we can help others who are searching google/stack overflow.
comment on: http://stackoverflow.com/q/47985177
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82940783
score: 0
type: Comment
type: QuestionComment
has text: So you want to leave NaN there without touching it?
comment on: http://stackoverflow.com/q/47985787

http://stackoverflow.com/q/47879894
type: Question
tagged with: python
upvote count: 6
has body: When I store an object to Redis like this, it works fine payload = {'age': 12} key = 'animals:cow' r.hmset(key, payload) However when I create the key by joining 2 strings payload = {'age': 12} key = 'animals:' + 'cow' r.hmset(key, payload) I get the error redis.exceptions.ResponseError: WRONGTYPE Operation against a key holding the wrong kind of value Why is the second example giving an error when the key string is the same as in the first example?
has title: REDIS Error: WRONGTYPE Operation against a key holding the wrong kind of value
linked to: http://stackoverflow.com/q/37953019
type: UnansweredQuestion
score: 6
has answer: http://stackoverflow.com/a/58043725
answer count: 1
has comment: http://stackoverflow.com/comment/86000423
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: redis

http://stackoverflow.com/comment/82941343
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47986188
has text: @Julien Value error? How to handle this...sorry I'm new to Python.

http://stackoverflow.com/q/47889499
has body: I'm currently working with a database and i would like to display its values on a webpage, using highcharts. Here is what i use to fetch the data in the web app : @app.route("/data.json") def data(): connection = sqlite3.connect("/home/pi/database/Main_Database.db") cursor = connection.cursor() cursor.execute("SELECT epochTime, data_x from table") results = cursor.fetchall() return json.dumps(results) Then i currently get this value by doing this in my html: $.getJSON('http://192.168.1.xx/data.json', function (data) { // Create the chart $('#container').highcharts('StockChart', { rangeSelector : { selected : 1 }, title : { text : 'title' }, series : [{ name : 'Value', data : data, tooltip: { valueDecimals: 2 }, ....... This works if i want to display only one data array. If i want to display more than one array, then it looks like each arrays must be preceded by its name respecting a certain parsing (i checked on the data sample used by highcharts). Example: data1:[(epochTime, 200),(epochTime,400)];data2:[(epochTime, 2),(epochTime,4)] I have some trouble to json.dumps two arrays from two different tables for example. I tried to use this following command : json.dumps({data1:results}). But the results is still not readable. Do you have any advice ? Or example/templates of webapp/highcharts using sqlite? Thanks a lot !
has comment: http://stackoverflow.com/comment/82777423
tagged with: sqlite
tagged with: python
favorite count: 0
downvote count: 0
type: AnsweredQuestion
score: 2
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/47905744
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/82772990
has comment: http://stackoverflow.com/comment/82777195
answer count: 1
tagged with: highcharts
has answer: http://stackoverflow.com/a/47905744
has title: Sqlite3 Db to Json, used for Highcharts?

http://stackoverflow.com/comment/82952693
comment on: http://stackoverflow.com/a/47992089
type: Comment
has text: This is the cleanest and most Pythonic approach!
score: 3
type: AnswerComment

http://stackoverflow.com/q/47914176
has body: I have this code that reads messages from Gdax, what I would like to do now is start a new thread that reads messages from another websocket from another exchange and runs concurrently. How do I do that ? import websocket from json import dumps, loads try: import thread except ImportError: import _thread as thread def on_message(ws, message): parsed_msg = loads(message) print(parsed_msg["product_id"], parsed_msg["price"]) def on_open(ws): def run(*args): params = { "type": "subscribe", "channels": [{"name": "ticker", "product_ids": ["BTC-USD", "ETH-USD"]}] } ws.send(dumps(params)) thread.start_new_thread(run, ()) if __name__ == "__main__": websocket.enableTrace(True) ws = websocket.WebSocketApp("wss://ws-feed.gdax.com", on_open=on_open, on_message = on_message) ws.run_forever()
downvote count: 0
tagged with: websocket
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 0
upvote count: 2
tagged with: concurrency
type: Question
has title: How would you open multiple websockets in multiple threads and run them concurrently

http://stackoverflow.com/q/47916762
has body: I got thus far: import xml.etree.ElementTree as ET tree = ET.parse(file) for elem in tree.iter(): print elem.text list=[] list.append(elem.text) and get these as the print result of elem.text: . . . VA-2017-VBA-0018 VA-2017-VBA-0020 VA-2017-VBA-0025 VA-2017-VHA-0003 VA-2017-VHA-0013 VA-2017-VHA-0021 VA-2017-VHA-0023 VA-2017-VHA-0024 VA-2017-VHA-0026 VETS-2017-0001 WHD-2017-0002 But when I print list, I get only ['WHD-2017-0002'] When what I want is either [..., VA-2017-VHA-0026, VETS-2017-0001, WHD-2017-0002] or {1: ABMC-2017-0002, ..., 997: VA-2017-VHA-0026, 998: VETS-2017-0001, 999: WHD-2017-0002} Can someone tell me how to make the list or a numerically labeled dictionary out of texts?
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
tagged with: list
answer count: 0
tagged with: loops
type: Question
has title: Iterate an .xml file and save the text as list or dictionary
has comment: http://stackoverflow.com/comment/82801868
has comment: http://stackoverflow.com/comment/82801726
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/82801660

tabs
type: Tag
tags question: http://stackoverflow.com/q/47870251
tags question: http://stackoverflow.com/q/47980908
tag name: tabs

http://stackoverflow.com/q/47933042
has comment: http://stackoverflow.com/comment/82847794
has comment: http://stackoverflow.com/comment/82835488
type: UnansweredQuestion
tagged with: sockets
tagged with: python
has answer: http://stackoverflow.com/a/47934208
tagged with: formatting
type: Question
tagged with: c#
linked to: http://stackoverflow.com/q/28225303
score: 0
has body: I am translating a python communication library into C#, and am having trouble interpreting how the string gets formatted before being sent over tcp. The relevant portion of the code is as follows: struct.pack( '!HHBH'+str(var_name_len)+'s', self.msg_id, req_len, flag, var_name_len, self.varname ) Then it gets sent with: sendall() I have looked at the Python documentation (https://docs.python.org/2/library/struct.html) but am still drawing a blank regarding the first line: '!HHBH'+str(var_name_len)+'s', I understand this is where the formatting is set, but what it is being formatted to is beyond me. The python code that I am translating can be found at the following link: https://github.com/linuxsand/py_openshowvar/blob/master/py_openshowvar.py Any python and C# vigilantes out there that can help me build this bridge? Edit: Based on jas' answer, I have written the following c# struct: public struct messageFormat { ushort messageId; ushort reqLength; char functionType; ushort varLengthHex; string varname; ... Once I populate it, I will need to send it over TCP. I have an open socket, but need to convert to to a byte[] I assume so I can use socket.send(byte[])? Thanks
answer count: 1
has title: Python to C#: how to format data for sockets?

http://stackoverflow.com/comment/82847113
comment on: http://stackoverflow.com/q/47938945
type: Comment
type: QuestionComment
score: 0
has text: What have you tried/researched?

http://stackoverflow.com/q/48007230
type: Question
answer count: 1
has title: Python, Check if a string exists in an XML tag
accepted answer: http://stackoverflow.com/a/48007955
score: 0
tagged with: python
linked to: http://stackoverflow.com/q/16471332
tagged with: http://stackoverflow.com/tag/xml
has comment: http://stackoverflow.com/comment/82982844
has body: am trying to read a word from a text file and check if this word exists in an xml tag, alse the file contains special characters. This is the code: import lxml.objectify from lxml import etree import codecs import xml.etree.cElementTree as ET file_path = "C:\Users\HP\Downloads\Morphalou-2.0.xml" for event, elem in ET.iterparse(file_path, events=("start", "end")): if elem.tag == 'orthography' and event =='start': data = elem.text f = codecs.open ('test.txt', encoding="ISO-8859-1") for line in f: check = line if check in data: print (check,":", "true") break else: print (check,":", "false") break elem.clear() When I tipe print (check), the word looks axactly how I want it "garçon", but when I add the test if check in data: print (check,":", "true") break else: print (check,":", "false") break This is what i get : (u'gar\xe7on', ':', 'false') Thought the result has to be true!! Am missing something, does anyone know what it is, Please Help! Advance Thanks.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48007955

http://stackoverflow.com/q/47918268
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47918363
type: AnsweredQuestion
type: Question
has body: I know there are lot of questions already ask about this error but for some reason none of them work for me. What i am trying to do? I am trying to pass a variable from view ActivateAccount to another view result upon email confirmation. What is the problem? I am doing everything right according to docs and previously posted question about the same error but i still get this error: Reverse for 'result' with keyword arguments '{'test': 'Email confirmed successfully!'}' not found. 1 pattern(s) tried: ['(?P&lt;test&gt;[\\w-]+)/$'] caller view.py: def ActivateAccount(request, uidb64, token): test = '' if uidb64 is not None and token is not None: ... test = "Email confirmed successfully!" return HttpResponseRedirect(reverse('result', kwargs={'test': test})) urls.py: url(r'^(?P&lt;test&gt;[\w-]+)/$', views.result, name='result') receiver view.py: def result(request, test=None, *args, **kargs): data = {'msg': test} return JsonResponse(data) // this return the result to ajax 'GET' And i would also like to know why is there double backslash \\ in the regex ([\\w-]) instead of single in the error. As in my url i have a single \ ([\w-]). thanks for your time.
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82804868
accepted answer: http://stackoverflow.com/a/47918363
has title: NoReverseMatch in Django 1.11

http://stackoverflow.com/a/47982337
has body: When you have shell=False in the Popen constructor, it expects the cmd to be a sequence; any type of str could be one but then the string is treated as the single element of the sequence -- this is happening in your case and the whole mpirun -np 4 pw.x string is being treated as the executable filename. To solve this, you can: Use shell=True and keep everything else as-is, but beware of the security issues as this would be run directly in shell and you should not do this for any untrusted executable Use a proper sequence e.g. list for cmd in Popen: import shlex process = Popen(shlex.split("mpirun -np 4 pw.x"), shell=False, ...) Both assuming mpirun exists in your PATH.
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47982203
downvote count: 0
type: Answer

http://stackoverflow.com/comment/83008969
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48003431
type: QuestionComment
has text: Do you have on the first line of your script `check_ganglia.py` something like `#!/usr/bin/python`?

arima
tag name: arima
tags question: http://stackoverflow.com/q/47922290
type: Tag

http://stackoverflow.com/a/47858290
score: 0
has comment: http://stackoverflow.com/comment/82700065
type: Answer
answers question: http://stackoverflow.com/q/47857957
has body: try this one (New way with similarity to you code) def ing(l): new=[] b="ing" for d in l: if b in d: new.append(d)#I am adding the wording ending with 'ing' to a new list #you were missing appending print(new) l= ['training','bicycle','working','carrying','bite','eat'] ing(l)#calling_function The thing you were missing was that you the list you given doesn't consist of string. To put them in string use ' ' or " " as I have done above. Also, when you are using return then there should be some thing to hold that specific return. You didn't use such thing. Still any doubt, Feels free to ask via comment. Happy to help.

http://stackoverflow.com/comment/82862132
type: Comment
score: 1
comment on: http://stackoverflow.com/q/47946061
has text: does normal [slicing/indexing](https://www.tutorialspoint.com/numpy/numpy_indexing_and_slicing.htm) not work for your desired outcome?
type: QuestionComment

http://stackoverflow.com/a/47956366
has comment: http://stackoverflow.com/comment/82882197
type: Answer
score: 2
has body: You might be able to trick nose into using your own decorator that keeps the function unchanged. Write a file numba.py that contains this function: def jit(func): return func and placed in your PYTHONPATH. Either run your test from directory this file is located in or do this in your test file as the first line: import sys sys.path.insert(0, 'path/to/dir/with/myfile') Alternatively, you can set the environmental variable PYTHONPATH to the directory where your file is located. Windows: set PYTHONPATH=%PYTHONPATH%;path/to/dir/with/myfile Unix/Mac: export PYTHONPATH=$PYTHONPATH$:path/to/dir/with/myfile
downvote count: 0
answers question: http://stackoverflow.com/q/47956236
has comment: http://stackoverflow.com/comment/82882216
upvote count: 2

http://stackoverflow.com/q/47917482
has answer: http://stackoverflow.com/a/47917669
has comment: http://stackoverflow.com/comment/82803897
tagged with: python
tagged with: python-3.x
tagged with: syntax
type: UnansweredQuestion
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/47917522
has comment: http://stackoverflow.com/comment/82803181
score: -1
has body: import time print("hello, do you want to play this detective game?") choice == input( "Yes or no?") if choice 'no' : print: "ok then, bye" exit if choice'yes': start name == input("Enter your name") print("hello, " + name ", in this game you are a famous detective handling a theft case." time.sleep(1) print(" you have gone on a holiday but ended up lost in the forest. you see a man walking up to you") time.sleep(1) print ("man:' hi there! you seem quite lost! Do you want to stay the night with me?'") print(" you said:'why should i? i dont even know you'") print(" man : ' Do as you please, but if you stay in the forest for the night here's a friendly warning: there's wild wolves in the forests.'") choose == input( "stay the night or refuse?" ) if choose "refuse": print("man: ' boy, you are stubborn!") print( "the man walks away, leaving you behind" + " In the end, you got eaten by the wolves due to your stubborness. THE END") choice == input("do you want to play again? yes or no?") if choice "yes": start if choice "no": print( "ok then, bye!") exit Basically my question is this ' invalid syntax' at the upper [do you want to play? ] 'no' response. But when I erase it the problem goes to the next line. It is very annoying and i cant find how to solve it. I tried changing between ' and " but the result is still the same. I would be glad if any of you would take the time to response as i just started yesterday and is still not very clear about invalid syntax.
answer count: 3
upvote count: 0
has comment: http://stackoverflow.com/comment/82803183
has answer: http://stackoverflow.com/a/47917661
favorite count: 0
has title: Cannot fix python invalid syntax

http://stackoverflow.com/a/63848713
upvote count: 1
has body: Status code 503 means that the server is down for maintenance. Just try again later.
answers question: http://stackoverflow.com/q/47910854
score: -2
type: Answer
downvote count: 3

http://stackoverflow.com/comment/82793931
type: QuestionComment
type: Comment
has text: Do all vectors have the same dimension? (I hope)
comment on: http://stackoverflow.com/q/47912611
score: 0

http://stackoverflow.com/q/47873311
score: 0
tagged with: canvas
answer count: 1
has comment: http://stackoverflow.com/comment/82712274
has title: Showing pictures from the list of files
has comment: http://stackoverflow.com/comment/82713161
tagged with: python
has body: I'd like to show pictures from list of files.gif in catalog, the pictures should change every 3s. I did try different solution but either is shown only firs pic or nothing. TIA from tkinter import * import os path = os.getcwd() arr = [] for files in next(os.walk('/home/vimart/Python/img/'))[2]: arr.append('/home/vimart/Python/img' + "/" + files) canvas_width = 300 canvas_height =300 master = Tk() canvas = Canvas(master, width=canvas_width, height=canvas_height) canvas.pack() def display(): canvas.create_image(20,20, anchor=NW, image=canvas.img) def get_picture(): for picture in arr: canvas.img = PhotoImage(picture) master.after(3000, display) get_picture() mainloop()
has answer: http://stackoverflow.com/a/47873770
tagged with: python-3.x
tagged with: tkinter
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/47861343
has comment: http://stackoverflow.com/comment/82712637
type: Question

http://stackoverflow.com/comment/82875529
score: 0
type: AnswerComment
has text: Exactly what I meant, for completeness I would define chars within the function and you are good.
comment on: http://stackoverflow.com/a/47953095
type: Comment

http://stackoverflow.com/q/47858650
has title: Collect a return value from a javascript function using BeautifulSoup
downvote count: 2
has answer: http://stackoverflow.com/a/47859609
accepted answer: http://stackoverflow.com/a/47859609
upvote count: 1
answer count: 1
favorite count: 0
tagged with: beautifulsoup
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82683431
tagged with: web-scraping
tagged with: python-requests
type: Question
has body: I want to collect Agencies phone number using BeautifulSoup from this url: https://www.cv-library.co.uk/companies/agencies/0-9. But the problem is, I have to click a link first which is bound to a javascript function called "contactDetails()" to show a number. I managed to click all the links using Selenium. but how can I now collect the numbers? So, what should I do now to overcome the issue? Thanks in Advance. Note: I am new in web-scraping. import requests,bs4 from selenium import webdriver site_url = "https://www.cv-library.co.uk/companies/agencies/0-9" #---------------------------------- Opening Firefox with Selenium Webdrivre --------------- #browser = webdriver.Firefox() #I need my Firefox browser's current profile for a reason. profile = webdriver.FirefoxProfile(r"C:\Users\USER\AppData\Roaming\Mozilla\Firefox\Profiles\i27jf7iw.default") browser = webdriver.Firefox(firefox_profile=profile) browser.get(site_url) #---------------------------------- Clicking Phone Buttons --------------------- phone_btn = browser.find_elements_by_link_text("Phone - Click to View") for i in range(0,20): phone_btn[i].click()
tagged with: javascript
score: -1

http://stackoverflow.com/comment/82878266
comment on: http://stackoverflow.com/q/47954453
type: QuestionComment
type: Comment
has text: What is "wrong" is pretty clear--the tick labels on the y axis increase from 20.3 to 24.2, and then drop down to 8.0.
score: 1

checkbox
tag name: checkbox
tags question: http://stackoverflow.com/q/47971928
type: Tag

data-layers
type: Tag
tag name: data-layers
tags question: http://stackoverflow.com/q/47980423

http://stackoverflow.com/a/48008098
downvote count: 0
has comment: http://stackoverflow.com/comment/82986441
has body: You need the PIL module, try the first one else try the second one conda install PIL conda install Pillow or if both PIL and Pillow exists, uninstall both and re-install PIL
answers question: http://stackoverflow.com/q/48008048
has comment: http://stackoverflow.com/comment/82986735
upvote count: 3
has comment: http://stackoverflow.com/comment/82986360
has comment: http://stackoverflow.com/comment/82987958
type: Answer
has comment: http://stackoverflow.com/comment/82996900
score: 3

http://stackoverflow.com/comment/82688257
type: Comment
score: 0
has text: create minimal working example so we could run it and see your problem.
type: QuestionComment
comment on: http://stackoverflow.com/q/47861592

http://stackoverflow.com/q/47994597
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82957456
tagged with: python
has title: How to reduce weight's bit or change to lower bit's type in tensorflow by using MNIST?
has body: I'm doing CNN model compression,and trying to reduce the weight's bit to get relation between bit's length and accuracy. But when I use Tensorflow Website's method to change the weight's Type of CNN,it came out an error : " TypeError : Value passed to paramter 'a' has DataType int8 not in list of allowed value : float16 , float32 , float64 , int32 , complex64 , complex128 ". It seems that weight's cannot be other Dtype. But I read some papers like that https://arxiv.org/pdf/1502.02551.pdf . it is possible to reduce weight's bits to 6bits , 4bits , even lower bit. my code is here (ignore import somethings): import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/",one_hot=True) x = tf.placeholder(tf.int8,[None,784]) W = tf.Variable(tf.zeros([784,10]),tf.int8) b = tf.Variable(tf.zeros([10]),tf.int8) y = tf.nn.softmax(tf.matmul(x,W)+b) #the error come out with "y = tf.nn.softmax(tf.matmul(x,W)+b)" It is just a standard tensorflow official code and Just changing the Dtype of the variables. Also I have tried tf.cast , but it still come out the error . tf.cast(W,tf.int8) tf.cast(b,tf.int8) Can anyone tell me how to overcome this situation? Thanks a lot !!
score: 3
tagged with: 8-bit
has answer: http://stackoverflow.com/a/47994655
upvote count: 3
has answer: http://stackoverflow.com/a/52361002
tagged with: tensorflow
type: Question
tagged with: mnist
answer count: 2
downvote count: 0
tagged with: training-data

http://stackoverflow.com/comment/82747086
has text: Did python ever solve the global interpreter lock problem? If not, concurrency in python is surprisingly not concurrent.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47887030
score: 0

http://stackoverflow.com/q/47982535
type: Question
tagged with: pyqt
downvote count: 0
has answer: http://stackoverflow.com/a/47982799
tagged with: focus
answer count: 1
accepted answer: http://stackoverflow.com/a/47982799
favorite count: 0
has title: How to prevent QTabWidget scroll buttons from gaining focus?
tagged with: qtabwidget
tagged with: python
type: AnsweredQuestion
has body: In the following code the red background will jump back and forth with each tab-key press. Adding more tabs (around eight for me) causes the tab-bar scroll buttons to appear, and causes a situation where a double tab-key press will be required. Is there any way to prevent the scroll buttons from getting the keyboard focus? # Testing with python 3.6.3 pip installed pyqt5 5.9.2 in virtualenv on Ubuntu import sys from PyQt5 import QtCore, QtWidgets class Widget(QtWidgets.QWidget): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) layout = QtWidgets.QVBoxLayout() self.setLayout(layout) self.tabs_left = QtWidgets.QTabWidget() self.tabs_left.setFocusPolicy(QtCore.Qt.NoFocus) self._add_tab(self.tabs_left) self.tabs_right = QtWidgets.QTabWidget() self.tabs_right.setFocusPolicy(QtCore.Qt.NoFocus) self._add_tab(self.tabs_right) layout.addWidget(self.tabs_left) layout.addWidget(self.tabs_right) self.add_button = QtWidgets.QPushButton('Add Tab') self.add_button.setFocusPolicy(QtCore.Qt.NoFocus) layout.addWidget(self.add_button) self.add_button.clicked.connect(self._add_tab_left) def _add_tab(self, tabs): edit = QtWidgets.QTextEdit() edit.setReadOnly(True) edit.setStyleSheet("QTextEdit:focus { background-color: red;}") tabs.addTab(edit, '{}'.format(tabs.count())) def _add_tab_left(self): self._add_tab(self.tabs_left) if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) widget = Widget() widget.show() sys.exit(app.exec_())
score: 1
tagged with: pyqt5
upvote count: 1

http://stackoverflow.com/comment/82848992
has text: Why does id 3 only have `phone3`, but id 1 has `phone1 - phone1`? Why is the logic different for these 2?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47939873

http://stackoverflow.com/comment/82726438
comment on: http://stackoverflow.com/a/47879839
score: 0
type: AnswerComment
has text: Well, name attributes `j_username` and `j_password` are within ` ` tag. So inturn we are helping Selenium locate our `WebElements` faster which increases the performance of our Test Execution.
type: Comment

http://stackoverflow.com/comment/82940521
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/47985807
has text: use button `{}` to correctly format code

http://stackoverflow.com/comment/82908411
type: Comment
score: 0
type: AnswerComment
has text: Thank you very much. I kind of gave up and did the def keyPressEvent(self, e): function way (from the two links I provided).. The only downpoint of it is that it doesnt check the focus on lineedit, but I decided that was okay. If I rearange my code I will definitely use the solution you have provided. Thanks again @ekhumoro !
comment on: http://stackoverflow.com/a/47963560

http://stackoverflow.com/comment/82860284
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47945116
has text: if I put `print` statements before and after the subprocess.call I get both statements printed, no errors. The argument in `-i` is correct because when I run exactly same argument through command line `sqlcmd 'path to the script + script name'` I get the script to run. If the argument in `-i` was incorrect I would get an error.
score: 0

http://stackoverflow.com/q/47885643
tagged with: python-2.7
tagged with: python
favorite count: 0
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: pyside2
score: 2
has comment: http://stackoverflow.com/comment/82752027
tagged with: pyside
has title: issue porting signal code from PyQt4 to PySide2
has body: the QtCore.QObject.connect in PySide2 is not working as it was in PyQt4. Signal ordering seams to be the issue. Is it a known bug or a feature that is not supported in PySide2 ? Any help will be appreciated, Thanks you, Eric Working example: (sorry I couldn't make it shorter to demonstrate the issue) Typically the output under PySide2 is complaining about signal and slot not being ordered. Signals and slots in QMetaObject 'BaseEditor' are not ordered correctly, this may lead to issues. Signal initFirstTimeDONE(object) Slot aclick(object) Signal optionChangeDONE(object) import os import sys import types from collections import namedtuple try: from PySide2 import QtCore,QtWidgets,QtGui SINGLE_ARG = 'object' except: from PyQt4 import QtCore,QtGui from PyQt4 import QtGui as QtWidgets SINGLE_ARG = 'PyQt_PyObject' ###################################################################### class baseSig(object): """ helper mixing for signal name and signature """ @property def asTuple(self): return self.name,self.arg class signalInfoT(namedtuple("signalInfo", "name arg signature"),baseSig): __slots__ = () def signalInfo(name, arg, signature=None): if signature == None: return signalInfoT(name,arg,"%s(%s)" % (name,arg)) else: return signalInfoT(name,arg,signature) # declare 2 signalInfo OPTION = signalInfo('optionChange',SINGLE_ARG) INITF = signalInfo('initFirstTime',SINGLE_ARG) ###################################################################### class Msg(object): """ Signal argument type """ def __init__(self,a): self.a = a ###################################################################### class BaseEditor(QtCore.QObject): """ object that centralized all the signal declaration (as a hub) and in which widget can register connection (request_connect) """ def __init__(self,**args): super(BaseEditor,self).__init__() self._Assign = {} self.declare_signalT(INITF.asTuple, self.initFirst, SINGLE_ARG) self.declare_signalT(OPTION.asTuple, self.aclick, SINGLE_ARG) def declare_signa…
has comment: http://stackoverflow.com/comment/88852445
type: Question
downvote count: 0

http://stackoverflow.com/q/47925776
has comment: http://stackoverflow.com/comment/82820011
answer count: 2
possible better answer: http://stackoverflow.com/a/47926112
downvote count: 0
favorite count: 0
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82819805
type: AnsweredQuestion
has body: I have created a custom Manager, but in my case its method adds some string to the end of particular field in a model instead of just filtering queryset as in usual cases. My goal is to return already changed objects when calling SomeModel.objects. Django`s documentation says: You can override a Manager’s base QuerySet by overriding the Manager.get_queryset() method. get_queryset() should return a QuerySet with the properties you require. My approach works, when I call SomeModel.objects.all(), but if I apply some filter for objects or just after .all() I can see that data become just regular. models.py: class BaseModelQuerySet(models.QuerySet): def edit_desc(self, string): if self.exists(): for obj in self: if 'description' in obj.__dict__: obj.__dict__['description'] += string return self class BaseModelManager(models.Manager): def get_queryset(self): return BaseModelQuerySet(self.model, using=self._db).edit_desc('...extra text') class BaseModel(models.Model): objects = BaseModelManager() class Meta: abstract = True Shell output: &gt;&gt;&gt; Macro.objects.all()[0].description 'Test text...extra text' &gt;&gt;&gt; Macro.objects.all().filter(id=1)[0].description 'Test text' That makes me confused. Such impression that other methods calling regular queryset instead of one returned with custom objects.
type: Question
tagged with: django-managers
has answer: http://stackoverflow.com/a/47993062
has title: Django custom manager`s method that changes data works incorrectly with other manager`s methods (filter, get, etc.)
has answer: http://stackoverflow.com/a/47926112
tagged with: django-models
score: 4
accepted answer: http://stackoverflow.com/a/47993062
upvote count: 4

http://stackoverflow.com/comment/82911101
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47969353
has text: I find it curious that in Octave you use `c(i,j)` indexing, but with numpy you use `c[i][j]`. Why not `c[i,j]`?
type: AnswerComment

http://stackoverflow.com/comment/83461606
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48159986
has text: I have the top view of the image in which you marked the red points. I have chosen an arbitrary larger square on the wooden base and since I know the homography H, I found the corresponding corner coordinates of this larger square in I2. I used these points (which make up a much larger square than the square base of the statue) and calculated k. When I took another square of the same size in another part of the image, I got a different value of k.

http://stackoverflow.com/q/47974626
has body: I recently installed gensim and glove in my mac and am trying to get word embedding for textual data I have. However, I'm having trouble finding the right function for it. I've only come across methods to get similarity metrics between two words. How do I train a glove object with data present in the library and use it to obtain embeddings for words in my dataset? Or is there any other library in python to do this? Thanks!
type: Question
has answer: http://stackoverflow.com/a/48072355
has title: Getting word embeddings for your dataset using training data in glove
answer count: 1
downvote count: 0
favorite count: 0
score: 3
tagged with: python
tagged with: macos
tagged with: nlp
accepted answer: http://stackoverflow.com/a/48072355
type: AnsweredQuestion
upvote count: 3

http://stackoverflow.com/comment/82766576
comment on: http://stackoverflow.com/q/47899416
score: 0
type: Comment
type: QuestionComment
has text: `2017-12-19 12:30:00` to `2017-12-19 12:50:00` is that a special case or not required for some purpose?

http://stackoverflow.com/a/47906712
answers question: http://stackoverflow.com/q/47903305
has comment: http://stackoverflow.com/comment/82792760
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has body: Leaving this comment from @JohnE here, as a suitable preamble for this post. you are fundamentally misunderstanding nan, which means "not a number" like missing data or the result of an invalid operation (e.g. divide by zero). Zero is a valid number (like black is a valid color, I guess ;-) admittedly, zeroes can be interpreted as false by python when numbers are implicitly treated as booleans, but generally speaking, zeroes are valid numbers, and certainly are considered valid for any numerical methods like mean, max, etc. In my opinion, a good solution would involve mask - s 0 22.0 1 0.0 2 0.0 3 0.0 4 35.0 Name: 0, dtype: float64 s.mask(s.eq(0)).mean() 28.5 Or, np.nanmean(s.mask(s.eq(0)).values) 28.5 The advantage of this solution is that it works for Series as well as DataFrame objects. If you have a series (or single column dataframe), the solution simplifies. You could perform boolean indexing to get rid of 0 rows and then call mean. s[s != 0].mean() 28.5 Alternatively, call mean on the values. This should be much faster. i = s.values i[i != 0].mean() 28.5
has comment: http://stackoverflow.com/comment/82932434
has comment: http://stackoverflow.com/comment/82932474
type: Answer
accepted answer of: http://stackoverflow.com/q/47903305

http://stackoverflow.com/comment/82745857
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47889749
has text: can you give us a short example of your class? what is your df composed of? you said it's a dict then it's a DataFrame? Series?
type: Comment

http://stackoverflow.com/q/47870681
has comment: http://stackoverflow.com/comment/82706895
type: UnansweredQuestion
type: Question
has title: Using python function from other python file and subsequent class?
tagged with: class
has answer: http://stackoverflow.com/a/47870812
answer count: 2
has answer: http://stackoverflow.com/a/47870890
has body: I have been learning working with classes in python after learning OOPs in c++. I am working on a project, where I have a class defined in one file, and an important function to be used in the class in the seperate file. I have to call the class in the first file, but I am getting the ImportError. Great, if you could help. try1.py from try2 import prnt class a: def __init__(self): print("started") def func1(self): print("func1") prnt() try2.py from try1 import a b = a() b.func1() def prnt(): b.func() As for eg, in the above example, when I am running try1.py, I am getting an ImportError: cannot import name 'prnt'.
has comment: http://stackoverflow.com/comment/82706501
score: 0
tagged with: python
tagged with: module

http://stackoverflow.com/a/47909002
has comment: http://stackoverflow.com/comment/82785995
type: Answer
downvote count: 0
score: 2
answers question: http://stackoverflow.com/q/47908827
upvote count: 2
has body: df1.Distance=pd.to_numeric(df1.Distance) df2.Distance=pd.to_numeric(df2.Distance) df=pd.concat([df1.assign(key=df1.idA+df1.idB),df2.assign(key=df2.idA+df2.idB)]).\ groupby('key').agg({'Distance':'sum','idA':'first','idB':'first'}) df Out[672]: Distance idA idB key 2 0.727273 1 1 3 1.037273 2 1 6 3.927273 2 4 11 0.127273 3 8 12 0.800000 5 7 Updated df1'idA','idB'=np.sort(df1'idA','idB'.values) df2'idA','idB'=np.sort(df2'idA','idB'.values) pd.concat([df1,df2]).groupby(['idA','idB'],as_index=False).Distance.sum() Out[678]: idA idB Distance 0 1 1 0.727273 1 1 2 1.037273 2 1 5 0.100000 3 2 4 3.827273 4 3 8 0.127273 5 5 7 0.800000
has comment: http://stackoverflow.com/comment/82786072

http://stackoverflow.com/comment/82839976
type: Comment
type: QuestionComment
has text: Please show what you've tried.
score: 0
comment on: http://stackoverflow.com/q/47935108

http://stackoverflow.com/comment/83117950
has text: @alvas it was a misconception, you can cross merge. Check out the last edit. It worked in kaggle kernel for me.
type: AnswerComment
comment on: http://stackoverflow.com/a/48005487
score: 0
type: Comment

http://stackoverflow.com/a/47882124
type: Answer
has body: You could use itertools.starmap import itertools def get_values_from_indices(array_values, array_indices): """ This function will accept two params, once is a multi-dimensional list, and other one is list of indices. """ return list(itertools.starmap(lambda x, y: x[y[0]], zip(array_values, array_indices))) DEMO multi_dimensional_array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] list_of_indices = [[2], [0], [1]] result = get_values_from_indices(multi_dimensional_array , list_of_indices) print(result) # [3, 4, 8]
upvote count: 3
has comment: http://stackoverflow.com/comment/82737467
accepted answer of: http://stackoverflow.com/q/47881815
score: 3
answers question: http://stackoverflow.com/q/47881815
has comment: http://stackoverflow.com/comment/82739872
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47946026
type: UnansweredQuestion
tagged with: python
has title: new step on abaqus using python script
type: Question
has body: I'm trying to create a new step using Python. I have already created a 'Step1' step which results a deformed structure, and now I'm trying to add new results of a new step 'Step2', which should be inserted after 'step1'. Using this script: odb = openOdb(path='my_odb_path') newStep= odb.Step(name='Step2', previous='Step1',domain=TIME) newFrame = newStep.Frame(incrementNumber=0, frameValue=0.0) newField = newFrame.FieldOutput(name='...',description='..', type=SCALAR) newField.addData(position=...,instance=...,labels=...,data=...) odb.save() The problem is in the statement "previous", the error message is : (keyword error on previous) Does anyone knows how to solve this problem thank you
score: 0
has answer: http://stackoverflow.com/a/47949893
answer count: 1
tagged with: abaqus

http://stackoverflow.com/a/47937588
type: Answer
answers question: http://stackoverflow.com/q/47936890
score: 2
upvote count: 2
has body: As Paul Panzer said, the flaw of your approach is that you look for "weight" and "angle" instead of covariance matrix. The covariance matrix fits perfectly in your approach: just compute one more moment, mixed xy. The function get_weight should be replaced with def get_covariance (mesh, func, dxy): g_mesh = [mesh[0]-dxy[0], mesh[1]-dxy[1]] Mxx = moment (g_mesh, func, (2, 0)) Myy = moment (g_mesh, func, (0, 2)) Mxy = moment (g_mesh, func, (1, 1)) return np.array([[Mxx, Mxy], [Mxy, Myy]]) Add one more import, from scipy.stats import multivariate_normal for reconstruction purpose. Still using your make_gauss function to create the original PDF, this is how it now gets reconstructed: s0xy = get_centroid (mesh, fxy0) w0xy = get_covariance (mesh, fxy0, s0xy) fxy1 = multivariate_normal.pdf(np.stack(mesh, -1), mean=s0xy, cov=w0xy) That's it; reconstruction works fine now. Units on the color bar are not the same, because your make_gauss formula does not normalize the PDF.
downvote count: 0

http://stackoverflow.com/a/47985363
upvote count: 3
answers question: http://stackoverflow.com/q/47985297
has body: You could also just create a function that filters elements from l1 that don't exist in l2, and call it twice with the arguments flipped: a = ['hello','world', 'foo'] b = ['hello','world','im','steve'] def difference(l1, l2): return list(filter(lambda x: x not in l2, l1)) print(difference(a, b) + difference(b, a)) # ['foo', 'im', 'steve'] If you don't wish to use filter(), a simple list comprehension like this also works: [item for item in l1 if item not in l2]
score: 3
downvote count: 0
type: Answer

http://stackoverflow.com/a/48069615
has comment: http://stackoverflow.com/comment/138721963
accepted answer of: http://stackoverflow.com/q/47978171
upvote count: 3
answers question: http://stackoverflow.com/q/47978171
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/120529062
type: Answer
has comment: http://stackoverflow.com/comment/83193491
downvote count: 0
score: 3
has body: For each python call, 1. Create an appDomain 2. Create a task in the appdomain that will run the python asynchronously. Since it's separate AppDomains, the static methods will be independent. Creating an using an AppDomain is heavy, so I couldn't do it if the number of calls you have is extremely large, but it sounds like you just might have a small number of processes to run asynchronously.
has comment: http://stackoverflow.com/comment/83211261

http://stackoverflow.com/a/47990160
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/82948881
has body: use alter command for change column name and donot need change foreign or primary key. simply change name use alter command ALTER TABLE table_name modify column name old name new name datatype
has comment: http://stackoverflow.com/comment/82948746
answers question: http://stackoverflow.com/q/47989980

http://stackoverflow.com/comment/82741876
has text: Does it require Python database programming?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47887942

http://stackoverflow.com/q/47917610
has answer: http://stackoverflow.com/a/47917816
answer count: 2
score: 3
downvote count: 0
has title: Why does __prepare__ take name and bases as parameters
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47925616
tagged with: python
has body: I'm in the process of migrating from 2.7 to 3.x and I'm trying to understand the __prepare__ method for metaclasses introduced in PEP3115. In most of the examples I've seen, implementations of this method ignore the parameters (name, bases, and **kwargs) simply returns a custom dictionary that does something interesting to the namespace provided to the __new__ and __init__ methods for the metaclass. Even the example in PEP3115 does nothing with the parameters. I don't doubt that there is some good reason for the signature of __prepare__ but I haven't seen the use case. What are some good examples that demonstrate the rational for making the signature of __prepare__ take these parameters?
tagged with: metaclass
upvote count: 3
has comment: http://stackoverflow.com/comment/82803269
type: Question

http://stackoverflow.com/q/47983240
upvote count: 1
has body: I want to send data with php and get with python. But shell_exec cannot send parameter. I cannot understand where is the problem. this does not fix my error this is my php file &lt;?php if(isset($_POST["username"])){ $nick = $_POST["username"]; echo $nick;//prints ozan to webpage $res = shell_exec("C:\Python27\python.exe C:\wamp\www\MLWebsite\website\new.py '".$nick."'"); echo $res; } ?&gt; new.py #!c:/Python27/python.exe print("Content-Type: text/html") print(""" &lt;TITLE&gt;&lt;/TITLE&gt; &lt;H1&gt;&lt;/H1&gt; """ ) import pymysql.cursors import sys import json import urllib2, urllib import requests x = sys.argv[1] print x Error Content-Type: text/html Traceback (most recent call last): File "C:\wamp\www\MLWebsite\website\new.py", line 15, in x = sys.argv1 IndexError: list index out of range Please help me to solve this problem
answer count: 1
has comment: http://stackoverflow.com/comment/82935437
has comment: http://stackoverflow.com/comment/82935200
favorite count: 0
has title: python sys.argv[1] list index out of range
has answer: http://stackoverflow.com/a/47983330
has comment: http://stackoverflow.com/comment/82935148
has comment: http://stackoverflow.com/comment/82935163
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82935424
tagged with: python
tagged with: php
linked to: http://stackoverflow.com/q/16932113
has comment: http://stackoverflow.com/comment/82935101
has comment: http://stackoverflow.com/comment/82935247
has comment: http://stackoverflow.com/comment/82935320
has comment: http://stackoverflow.com/comment/82935209
has comment: http://stackoverflow.com/comment/82935342
type: Question
score: -1
has comment: http://stackoverflow.com/comment/82935222
has comment: http://stackoverflow.com/comment/82935107
has comment: http://stackoverflow.com/comment/82935255
has comment: http://stackoverflow.com/comment/82935456
has comment: http://stackoverflow.com/comment/82935513
downvote count: 2

http://stackoverflow.com/q/47865500
tagged with: dev-appserver
has body: The App Engine local dev server reloads every time there's a change to files - which is cool. What's uncool is that it also reloads on changes in .idea folder of the PyCharm editor, cluttering the logs. Tried adding this to app.yaml: skip_files: - ^(.*/)?#.*#$ - ^(.*/)?.*~$ - ^(.*/)?.*\.py[co]$ - ^(.*/)?.*/RCS/.*$ - ^(.*/)?\..*$ - ^\.idea$ # added this line in order to try and ignore .idea folder on build This didn't help. Still rebuilds every time I do arbitrary stuff in the editor (not changing any code). How can I tell App Engine dev server which folder to ignore for hot reload?
has title: Prevent App Engine hot reload on change in PyCharm .idea folder
type: Question
has comment: http://stackoverflow.com/comment/82709329
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: google-app-engine
tagged with: python
has answer: http://stackoverflow.com/a/47872910

http://stackoverflow.com/a/47875270
type: Answer
has body: Looks like you got the parameters for Popen wrong. with open("nmap_http_output.txt", "w") as f: for x in scripts: # iterate over http scripts print(x) # for debugging purposes - this prints print(ip) # for debugging purposes - this prints nmap_http_ps = subprocess.Popen( ['nmap', '-p', '80', ' --script=%s' % x, ip], stdout=f, stderr=subprocess.STDOUT ) output = nmap_http_ps.communicate() print(output) Popen expects a list of "elements" of a command, but you have to be careful in terms of what constitutes an "element". I believe (can not test it right now) that you must fix two things: '-p' becomes '-p', '80' (two elements - a switch and a parameter) ' --script=', x becomes '--script=%s' % x (instead of two elements, this should be just one - and there is also a leading space too much)
has comment: http://stackoverflow.com/comment/82716580
score: 0
accepted answer of: http://stackoverflow.com/q/47870930
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47870930

http://stackoverflow.com/q/47913774
tagged with: gimp
has title: Gimp python-fu external editor importerror
has comment: http://stackoverflow.com/comment/82795624
has comment: http://stackoverflow.com/comment/82800135
has comment: http://stackoverflow.com/comment/83012912
tagged with: python-2.7
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: gimpfu
has comment: http://stackoverflow.com/comment/82796848
tagged with: python
answer count: 0
score: 1
has body: I'm looking to build a script using Gimps build in Python extension. I have run into a problem though, and these are my symptoms, perhaps someone here is able to help me. When I run Python-fu from Gimp I get what you would expect, and a clear indication that everything is working. System details: Win10 - 64 bit Gimp 2.8.22 Python.exe - version 2.7 (the one included in Gimp installation and seperate install to be sure) Gimp message: GIMP 2.8.22 Python Console Python 2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)] &gt;&gt;&gt; sys.path ['C:\\Program Files\\GIMP 2\\lib\\gimp\\2.0\\plug-ins', 'C:\\Program Files\\GIMP 2\\32\\lib\\gimp\\2.0\\python', 'C:\\Program Files\\GIMP 2\\Python\\python27.zip', 'C:\\Program Files\\GIMP 2\\Python\\DLLs', 'C:\\Program Files\\GIMP 2\\Python\\lib', 'C:\\Program Files\\GIMP 2\\Python\\lib\\plat-win', 'C:\\Program Files\\GIMP 2\\Python\\lib\\lib-tk', 'C:\\Program Files\\GIMP 2\\Python', 'C:\\Program Files\\GIMP 2\\Python\\lib\\site-packages', 'C:\\Program Files\\GIMP 2\\Python\\lib\\site-packages\\gtk-2.0', 'C:\\Program Files\\GIMP 2\\Python\\lib\\site-packages'] &gt;&gt;&gt; gimp &lt;module 'gimp' from 'C:\Program Files\GIMP 2\32\lib\gimp\2.0\python\gimp.pyd'&gt; However when I run a script with that entire path included, from the python.exe file I get: C:\Python27\python.exe D:/P5/m-cworkshop/Sprites2d/spritofu.py Traceback (most recent call last): File "D:/P5/m-cworkshop/Sprites2d/spritofu.py", line 2, in &lt;module&gt; from gimpfu import * File "C:\Program Files\GIMP 2\32\lib\gimp\2.0\python\gimpfu.py", line 76, in &lt;module&gt; import gimp ImportError: DLL load failed: Det angivne modul blev ikke fundet. (Translation edit!: The indicated module was not found) Process finished with exit code 1 So its clearly able to pick up the gimpfu.py file, but not the gimp.pyd file right next to it. Here is what i have been able to verify so far: My python installations are 32 bit. This happens on both my computers. This happe…
upvote count: 1
type: Question

http://stackoverflow.com/comment/93994194
type: AnswerComment
score: 0
type: Comment
has text: Just my 2 cent. Use `df.div(df.groupby(level=[0, 1]).transform('sum'))` if df is already a multiindex dataframe.
comment on: http://stackoverflow.com/a/47876761

http://stackoverflow.com/a/47872562
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: pyladies_source = uReq("http://pyladies.com") pyladies_source = pyladies_source.read() 'python' in str(pyladies_source) # Returns false in this case, at least when I ran it. All you had to change was casting pyladies_source to a string so you can look for 'python'
accepted answer of: http://stackoverflow.com/q/47872366
answers question: http://stackoverflow.com/q/47872366
score: 1

http://stackoverflow.com/comment/82789671
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47910903
has text: Not necessarily. It returns 503 because they want to prevent you scraping the site
score: 3

http://stackoverflow.com/comment/82932210
type: QuestionComment
has text: Is the user entering the data manually or through a text file? That part is not clear from your question
comment on: http://stackoverflow.com/q/47981828
score: 0
type: Comment

http://stackoverflow.com/a/47872267
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/47871398
has comment: http://stackoverflow.com/comment/82712283
has body: You need to start bokeh with the bokeh server, like this: bokeh serve myscript.py And then open localhost:5006 in your browser. If you start bokeh without the server then it just creates a static html file and there is no way you can either make the page call your functions (that's why you don't see the prints) or alter the page with your python code after the initial load. From the docs: The architecture of Bokeh is such that high-level “model objects” (representing things like plots, ranges, axes, glyphs, etc.) are created in Python, and then converted to a JSON format that is consumed by the client library, BokehJS. [...] However, if it were possible to keep the “model objects” in python and in the browser in sync with one another, then more [you could also] respond to UI and tool events generated in a browser with computations or queries using the full power of python
downvote count: 0

http://stackoverflow.com/q/47949853
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/82869421
has comment: http://stackoverflow.com/comment/82869409
score: 0
answer count: 1
tagged with: unicode
has answer: http://stackoverflow.com/a/47984683
has title: Custom value on python unicode \u
tagged with: python
has body: I'm quite new to python and i've been trying to get this working with no success. Is there any way to make something like this work unicode_code = "00000061" character = "\u" + unicode_code A example would be appreciated.
has comment: http://stackoverflow.com/comment/82869373

http://stackoverflow.com/comment/82895902
score: 0
type: Comment
has text: Yes. Suppose that we need to apply shifts to the right or the left, on any one of the dimensions.
comment on: http://stackoverflow.com/a/47963114
type: AnswerComment

http://stackoverflow.com/a/47887770
accepted answer of: http://stackoverflow.com/q/47887746
answers question: http://stackoverflow.com/q/47887746
has body: You can use a generator expression in any to check each substring against your original string &gt;&gt;&gt; flag = any(i in mystring for i in mylist) &gt;&gt;&gt; flag True If you want an int instead of a bool you can modify the above to &gt;&gt;&gt; flag = int(any(i in mystring for i in mylist)) &gt;&gt;&gt; flag 1
type: AcceptedAnswer
score: 4
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/82741728
downvote count: 0

http://stackoverflow.com/q/47964694
has comment: http://stackoverflow.com/comment/83258434
has comment: http://stackoverflow.com/comment/83324767
score: 0
has title: Upload video from ios device using ionic/cordova to django rest-framework file field
tagged with: angularjs
answer count: 0
type: UnansweredQuestion
tagged with: ng-file-upload
tagged with: python
has comment: http://stackoverflow.com/comment/83263177
has body: I am trying to upload a video from an Ionic app to django device. I am using $cordovaCamera.getPicture to grab the video from the photo gallery of the device. I am using ng-file-upload to upload the video. On the django rest-framework side I have this on the ViewSet: def perform_create(self, serializer): f = self.request.data.get('file') serializer.save(file=f) JS upload looks like this: var url = 'http://ip...' Upload.upload({ url: url, data: params, headers: {'Authorization': "Token " + token, "Content-Type": 'video/'+ext}, }).then(onSuccess, function (resp) { ... Here are the headers: POST http://10.100.102.8:83/image/?content=business REMOTE_ADDR=10.100.102.4 CONTENT_LENGTH=442 CONTENT_TYPE=multipart/form-data; boundary=---- WebKitFormBoundarywbpGxg45jBTAQmun HTTP_ACCEPT=application/json, text/plain, */* HTTP_ACCEPT_ENCODING=gzip, deflate HTTP_ACCEPT_LANGUAGE=en-us HTTP_AUTHORIZATION=Token 032c6d410a11352d57cb8958b0d4aaf991c HTTP_CONNECTION=keep-alive HTTP_HOST=10.100.102.8:83 HTTP_ORIGIN=file:// HTTP_USER_AGENT=Mozilla/5.0 (iPhone; CPU iPhone OS 11_2 like Mac OS X) AppleWebKit/604.4.7 (KHTML, like Gecko) Mobile/15C107 (1455558801991342) And the 400 Http Response I get: 400 400 Vary: Accept Content-Type: application/json Allow: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS With videos from the web browser it is working fine. With Images it works well from both browser and device. When uploading images I am converting the image to base64. I keep getting 400 error log with no extra info when uploading a video from device. Any advice?
type: Question
tagged with: javascript
tagged with: django-rest-framework

http://stackoverflow.com/q/47856115
type: UnansweredQuestion
tagged with: multithreading
tagged with: python
has answer: http://stackoverflow.com/a/47862636
has title: Sending the same continuous updates to multiple threads spawned by another thread
type: Question
has body: I'm struggling to get my head around this so hoping for a bit of input. I plan on having a thread running a socket server, that checks every second for new client connections. If it finds one, it will spawn a thread for that connection, and close it once the client is disconnected. This is the bit I have working. I would like to get information from the main program passed to the end threads, so that every client receives the same information. I can't really use multiprocessing.Queue as that would delete the item after the first thread used it (and I can't intercept it in the server thread as the updates would be limited to 1 per second, and the main thread won't know how many connections there are), so does anyone have any suggestions? The layout of threads is a bit like this: Main script (running many times per second) -server (running 1 time per second) -client (sending information as soon as it receives it, ideally in sync with the main script) -client -client I guess I could probably spawn a thread from the server to receive input, and that thread will then spawn the client threads and send a different Queue item to each one, but it sounds like there should be a less messy way. Edit: The inbetween thread idea doesn't work, you can't pass connections or queues across threads unfortunately.
score: 0
answer count: 1

http://stackoverflow.com/comment/82958268
score: 0
comment on: http://stackoverflow.com/q/47993485
has text: Don't know exactly, because its converting the text in file but my file is excel file.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82705040
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47869933
has text: show the first case. Then show what you attempted for the second and explain what went wrong
type: Comment

python-datetime
tag name: python-datetime
tags question: http://stackoverflow.com/q/47952986
type: Tag
tags question: http://stackoverflow.com/q/47876299

web-applications
tags question: http://stackoverflow.com/q/47966082
tag name: web-applications
tags question: http://stackoverflow.com/q/47981171
type: Tag

http://stackoverflow.com/q/47867216
has answer: http://stackoverflow.com/a/55191893
has answer: http://stackoverflow.com/a/47871642
accepted answer: http://stackoverflow.com/a/47871642
favorite count: 0
has comment: http://stackoverflow.com/comment/82699489
has comment: http://stackoverflow.com/comment/82699610
tagged with: python
tagged with: sha256
downvote count: 0
tagged with: encryption
has body: I am developing a webapp using python and flask. It has a user system, so, of course, a registration form. I am using, to encrypt the password of the user that wants to registrate, passlib.hash.sha256 . Here's what I am doing: from passlib.hash import sha256_crypt as sha256 [...] if request.method == "POST" and form.validate(): username = request.form['username'] password = request.form['password'] confirm_password = request.form['confirm_password'] email = request.form['email'] password = sha256.encrypt(password) #Encryption. c, conn = connection('accounts') #Connection to the database x = c.execute("SELECT * FROM accounts WHERE username = '%s' OR email = '%s'" %(thwart(username), thwart(email))) if x: flash("We are very sorry, but this Username/Email-address is already taken. Please try again") else: c.execute('INSERT INTO accounts VALUES ("%s", "%s", "%s")' %(thwart(username), thwart(password), thwart(email))) conn.commit() flash('Succesfully Registered!') In the database, the hash is always varying, even if the same password has been inputed. Does anybody know why? What am I doing wrong?
possible better answer: http://stackoverflow.com/a/55191893
has answer: http://stackoverflow.com/a/47867564
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82699435
score: 1
type: Question
answer count: 3
upvote count: 1
has title: sha256_crypt.encrypt always returning another hash

http://stackoverflow.com/comment/82840137
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47934536
has text: I tried that before but it doesn't work. `self.__class__ = myProject.tests.TestDemo.TestBase` and `TestBase = myProject.tests.TesBase.TestBase` when I run `python setup.py test` and since they are not the same the test would still run
score: 0

http://stackoverflow.com/q/47897050
type: Question
tagged with: hadoop
has answer: http://stackoverflow.com/a/47898455
accepted answer: http://stackoverflow.com/a/47898455
answer count: 2
tagged with: pyspark
has answer: http://stackoverflow.com/a/47897801
favorite count: 0
upvote count: 3
tagged with: apache-spark
has body: I am using Hive Metastore in EMR. I am able to query the table manually through HiveSQL or SparkSQL. But When i use the same table in Spark Job, it says Table or view not found File "/usr/lib/spark/python/lib/pyspark.zip/pyspark/sql/utils.py", line 69, in deco pyspark.sql.utils.AnalysisException: u"Table or view not found: `logan_test`.`salary_csv`; line 1 pos 21; 'Aggregate [unresolvedalias(count(1), None)] +- 'UnresolvedRelation `logan_test`.`salary_csv` Here is my full code from pyspark import SparkContext, HiveContext from pyspark import SQLContext from pyspark.sql import SparkSession sc = SparkContext(appName = "test") sqlContext = SQLContext(sparkContext=sc) sqlContext.sql("select count(*) from logan_test.salary_csv").show() print("done..") I submitted my job as below to use hive catalog tables. spark-submit test.py --files /usr/lib/hive/conf/hive-site.xml
downvote count: 0
possible better answer: http://stackoverflow.com/a/47897801
tagged with: python
has title: hive table does not exist in spark job
tagged with: hive
type: AnsweredQuestion
score: 3
linked to: http://stackoverflow.com/q/36359812
linked to: http://stackoverflow.com/q/47933705

http://stackoverflow.com/comment/82751590
score: 0
type: QuestionComment
type: Comment
has text: please see edit:
comment on: http://stackoverflow.com/q/47891056

http://stackoverflow.com/comment/82986262
comment on: http://stackoverflow.com/a/48008192
type: AnswerComment
type: Comment
score: 1
has text: I was never been to this error till today. Nice for pointing it out.

http://stackoverflow.com/a/47983541
answers question: http://stackoverflow.com/q/47983466
downvote count: 0
has comment: http://stackoverflow.com/comment/82936477
has comment: http://stackoverflow.com/comment/115045771
type: AcceptedAnswer
type: Answer
has body: Adding pd.Series df'sum', 'difference' = df.apply( lambda row: pd.Series(add_subtract(row['a'], row['b'])), axis=1) df yields a b sum difference 0 1 4 5 -3 1 2 5 7 -3 2 3 6 9 -3
has comment: http://stackoverflow.com/comment/136560005
has comment: http://stackoverflow.com/comment/82936300
score: 9
accepted answer of: http://stackoverflow.com/q/47983466
upvote count: 9

http://stackoverflow.com/q/47887071
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47887113
type: Question
tagged with: dataframe
has title: Best way to build data frame from nested dictionary
tagged with: pandas
accepted answer: http://stackoverflow.com/a/47887113
answer count: 1
downvote count: 0
has body: After processing the data I have saved group level calculations in following structure (Nested Dictionary): {'Source1': {(1, 2): {'value1': -1.4089917877152731, 'value2': 0.15890127107708821}, (1, 3): {'value1': -3.6436438771179183, 'value2': 0.00027189114106343325}, (1, 4): {'value1': 1.3921379718956783, 'value2': 0.1639443047264573}, (2, 3): {'value1': -2.1272739953077449, 'value2': 0.033444556519261023}, (3, 4): {'value1': 5.0887284442498775, 'value2': 3.7318559307126006e-07}, (2, 4): {'value1': 2.781268059718232, 'value2': 0.0054326884405563099}}, 'Source2': {(1, 2): {'value1': 1.6065065530210021, 'value2': 0.10840303417258132}, (1, 3): {'value1': -0.67561007794063666, 'value2': 0.49941051115943469}, (1, 4): {'value1': -0.99500921260852215, 'value2': 0.31991568858488023}, (2, 3): {'value1': -2.4076869756909676, 'value2': 0.016168545874782416}, (3, 4): {'value1': -0.31851460166510093, 'value2': 0.75013768971795858}, (2, 4): {'value1': -2.7976881039916965, 'value2': 0.0052043800033575345}}} Structure of the dictionary is: Level1 - Source Level2 - Group comparison (1,2) means compare Group 1 vs Group2 Level3 - Value of the comparison in two measurement types My goal is to obtain following table Source Name | (1,2) | (1,3) | (1,4) | ......| (2,4)| Source1 | value1 | value1 | ................| value1 I think including value 2 is somewhat impossilbe so ignore the value2 Whats the best way to convert this into a pandas data frame.
favorite count: 0

http://stackoverflow.com/a/47910491
score: 1
has body: (Assuming you don't want to force, but give an initial-guess. The fixed-case probably needs to touch the whole code and it's highly questionable if the whole EM-approach is of use then. It probably collapes into some optimization problem approachable by scipy's optimize module.) Just follow the docs. It's supported at time of GaussianMixture-creation. weights_init : array-like, shape (n_components, ), optional The user-provided initial weights, defaults to None. If it None, weights are initialized using the init_params method. means_init : array-like, shape (n_components, n_features), optional The user-provided initial means, defaults to None, If it None, means are initialized using the init_params method.
answers question: http://stackoverflow.com/q/47910446
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/82789147
has comment: http://stackoverflow.com/comment/82789179
downvote count: 0

http://stackoverflow.com/comment/82892556
score: 0
type: AnswerComment
type: Comment
has text: This is my first project i'm working on, Thanks for helping me understad and solving my problem
comment on: http://stackoverflow.com/a/47961586

http://stackoverflow.com/q/47899678
downvote count: 0
type: UnansweredQuestion
tagged with: logging
has answer: http://stackoverflow.com/a/47901024
tagged with: paramiko
type: Question
tagged with: python-2.7
answer count: 1
has title: How to avoid these keepalive@openssh.com log messages when Paramiko Python module is used?
score: 4
tagged with: sftp
tagged with: python
upvote count: 4
favorite count: 0
has body: I am using Python Paramiko module to do download files from SFTP server. But it is displaying the following the log messages continuously. Wed Dec 20 06:51:00 2017 transport line:1572 22192 /PoolWorker-13 139861396514560 Thread-138 DEBUG Received global request "keepalive@openssh.com" Wed Dec 20 06:51:00 2017 transport line:1572 22192 /PoolWorker-13 139861396514560 Thread-138 DEBUG Rejecting "keepalive@openssh.com" global request from server. Wed Dec 20 06:51:00 2017 transport line:1572 22192 /PoolWorker-13 139861395986176 Thread-140 DEBUG Received global request "keepalive@openssh.com" Wed Dec 20 06:51:00 2017 transport line:1572 22192 /PoolWorker-13 139861395986176 Thread-140 DEBUG Rejecting "keepalive@openssh.com" global request from server. What is the change required to avoid the above lines to be displayed in logs for Paramiko module? I am using Paramiko 2.1.2 module on Python 2.7.6. Will those log lines will be gone if we use pysftp module instead of Paramiko?

http://stackoverflow.com/q/47986657
has comment: http://stackoverflow.com/comment/82942184
answer count: 0
has title: Can you use a where constraint on an inner joined table to limit results?
has comment: http://stackoverflow.com/comment/82942257
type: Question
has body: SOLVED sql = "SELECT Title, Year, TmdbId, MovieFileId, Quality " \ "FROM Movies " \ "INNER JOIN MovieFiles on MovieFiles.Id = Movies.MovieFileId " \ "WHERE Quality = 7" sql = "SELECT Title, Year, TmdbId, MovieFileId, MovieFiles.Quality " \ "FROM Movies " \ "INNER JOIN MovieFiles on MovieFiles.Id = Movies.MovieFileId " \ "WHERE MovieFiles.Quality = 7" Neither of these work for me, I am getting no rows returned. Quality is part of the MovieFiles table. And Yes, rows exist that meet this criteria. sql = "SELECT Title, Year, TmdbId, MovieFileId, Quality " \ "FROM Movies " \ "INNER JOIN MovieFiles on MovieFiles.Id = Movies.MovieFileId " This works just fine, and returns the correct quality. But, if I add the where, it does not work and just returns nothing. Am I doing something wrong? (Using python) Edit: Schema request CREATE TABLE "Movies" ("Id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "ImdbId" TEXT, "Title" TEXT NOT NULL, "TitleSlug" TEXT NOT NULL, "SortTitle" TEXT, "CleanTitle" TEXT NOT NULL, "Status" INTEGER NOT NULL, "Overview" TEXT, "Images" TEXT NOT NULL, "Path" TEXT NOT NULL, "Monitored" INTEGER NOT NULL, "ProfileId" INTEGER NOT NULL, "LastInfoSync" DATETIME, "LastDiskSync" DATETIME, "Runtime" INTEGER NOT NULL, "InCinemas" DATETIME, "Year" INTEGER, "Added" DATETIME, "Actors" TEXT, "Ratings" TEXT, "Genres" TEXT, "Tags" TEXT, "Certification" TEXT, "AddOptions" TEXT, "MovieFileId" INTEGER NOT NULL, "TmdbId" INTEGER NOT NULL, "Website" TEXT, "PhysicalRelease" DATETIME, "YouTubeTrailerId" TEXT, "Studio" TEXT, "MinimumAvailability" INTEGER NOT NULL, "HasPreDBEntry" INTEGER NOT NULL, "PathState" INTEGER NOT NULL, "PhysicalReleaseNote" TEXT, "SecondaryYear" INTEGER, "SecondaryYearSourceId" INTEGER) CREATE TABLE "MovieFiles" ("Id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "MovieId" INTEGER NOT NULL, "Path" TEXT, "Quality" TEXT NOT NULL, "Size" INTEGER NOT NULL, "DateAdded" DATETIME NOT NULL, "SceneName" TEXT, "MediaInfo" TEXT, "ReleaseGroup" TEXT, "RelativePath" TEX…
has comment: http://stackoverflow.com/comment/82942247
score: 0
tagged with: sqlite
has comment: http://stackoverflow.com/comment/82942197
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82942229
tagged with: python
has comment: http://stackoverflow.com/comment/82942177

http://stackoverflow.com/comment/82711780
score: 0
comment on: http://stackoverflow.com/q/47873133
type: Comment
type: QuestionComment
has text: If you don't have to render any plot at all in a notebook, don't call `%matplotlib inline`?

http://stackoverflow.com/q/47918946
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/47923620
has body: I am new to ORM, so any comment are appreciated. Using the following code, I am trying to get all Contacts that are related to certain Classification. Base = declarative_base() contact_category_association_table = Table('contact_category_association', Base.metadata, Column('contact_id', Integer, ForeignKey('contacts.id')), Column('category_id', Integer, ForeignKey('contact_categories.id')) ) class Contact(Base): __tablename__ = 'contacts' id = Column(Integer, primary_key=True) name = Column(String) categories = relationship('ContactCategory', secondary=contact_category_association_table) class ContactCategory(Base): __tablename__ = 'contact_categories' id = Column(Integer, primary_key=True) name = Column(String) contacts = relationship('Contact', secondary=contact_category_association_table) classification_id = Column(Integer, ForeignKey('contact_classification.id')) classification = relationship('ContactClassification', back_populates='categories') class ContactClassification(Base): __tablename__ = 'contact_classification' id = Column(Integer, primary_key=True) name = Column(String) categories = relationship('ContactCategory', back_populates='classification') Using the following SQL I managed to get a result close to my need. However, I could not translate that using sqlalchemy ORM. select * from contacts c join contact_categories cc, contact_category_association cca, contact_classification ccl where c.id = cca.contact_id and cc.id = cca.category_id and ccl.id = cc.classification_id; The result I am seeking is a dict object. The key will be the id or name of the classification. The value will be a list of contacts. Update: To elaborate more. Each contact is categorized by their profession (ContactCategory). The relation between contact and category is many-to-many. Categories are being classified (or group) into classes. Each category can belong to 1 class (one-to-many). The following are an example data: Contacts 1|Alpha 2|Bear 3|Cel 4|Deer 5|Elk ContactCategory 1…
tagged with: python
has comment: http://stackoverflow.com/comment/82811788
type: AnsweredQuestion
tagged with: orm
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/82813454
has answer: http://stackoverflow.com/a/47923620
has title: SQLAlchemy: querying all objects with no direct relationship

http://stackoverflow.com/q/47866039
tagged with: multithreading
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
has title: Python multithreaded server can handle one client message at a time
type: Question
has answer: http://stackoverflow.com/a/47866356
accepted answer: http://stackoverflow.com/a/47866356
has body: I was playing around to understand multithreading so I wrote the following client/server application, where the server sends a command to the client, the client checks this command if it is equal to 'a' it sends a reply to the server. In the server code I created two sockets and one thread; the first socket sends (publishes) the command to all of the connected (subscribed) clients. In the thread the second socket waits for any reply from the clients but because the thread performs some blocking operations (e.g. storing the information sent by the client in a database) it can handle one client at a time even though the socket (req-rep socket) can receive multiple message at the same time. server.py import zmq import logging import threading import time logging.basicConfig(level=logging.DEBUG) class Server(object): def __init__(self): self.context = zmq.Context() self.pub_port = 7777 self.rep_port = 7778 self.pub_socket = None self.rep_socket = None self.interface = "*" def bind_ports(self): logging.debug("[bind_ports] binding the ports....") self.pub_socket = self.context.socket(zmq.PUB) pub_bind_str = "tcp://{}:{}".format(self.interface, self.pub_port) self.pub_socket.bind(pub_bind_str) self.rep_socket = self.context.socket(zmq.REP) rep_bind_str = "tcp://{}:{}".format(self.interface, self.rep_port) self.rep_socket.bind(rep_bind_str) def received_info(self): while True: # logging.debug("[received_flow] ") cl_data = self.rep_socket.recv_json() logging.info("[received_data] data &lt;{}&gt;".format(flow)) self.rep_socket.send(b"\x00") self.blocking_op(cl_data) def blocking_op(self, data): time.sleep(1) # simulating some blocking operations e.g. storing info in a database def push_instruction(self, cmd): logging.debug("[push_inst] Sending the instruction &lt;%s&gt; to the clients...", # logging.debug("[push_inst] Sending the instruction &lt;%s&gt; to the agents ...", cmd) instruction = {"cmd": cmd} self.pub_socket.send_json(instruction) def create_thread(self): thread = …
has comment: http://stackoverflow.com/comment/82697289
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/82849063
has text: do you have ` ` in every ` ` ? Then you should get ever ` ` in result - you use `find_all()` to get all ` ` and `find_all()` to get all ` ` in ` `. You don't use `find()` to get only first element. You don't use index (ie. `tag_[0]`) or slicing (ie. `tag_[0:1]`) to check only one ` `
comment on: http://stackoverflow.com/q/47939702
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82724369
has text: Sorry. See if this okay? df1 = pd.DataFrame(index=range(0,20)) df1['is_guarantee'] = np.random.choice([0,1], df1.shape[0]) df1['hotel_star'] = np.random.choice([0,1,2,3,4,5], df1.shape[0]) df1['order_status'] = np.random.choice([40,60,80], df1.shape[0]) df1['journey '] = np.random.choice([0,1,2], df1.shape[0])
score: 0
comment on: http://stackoverflow.com/q/47867249
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47949404
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82869284
tagged with: http://stackoverflow.com/tag/gif
tagged with: moviepy
has title: moviepy: How to define the ending part backwards for cut?
type: Question
score: 0
has comment: http://stackoverflow.com/comment/82914306
has body: To this question I am referring to the example from http://zulko.github.io/blog/2014/01/23/making-animated-gifs-from-video-files-with-python/ To be exactly, to these codes I refer. from moviepy.editor import * clip = (VideoFileClip("frozen_trailer.mp4") .subclip((1,22.65),(1,23.2)) .resize(0.3)) clip.write_gif("use_your_head.gif") The code above selects the part between 1’22.65 (1 minute 22.65 seconds) and 1’23.2. My question: How to define the ending part backwards? How to define the subclip， so it cut e.g. the beginning 1’22.65, and cut the last 3 minute 20.15 seconds? I have many MP4s with different length, but they have same beginning and ending parts. It will be very convenient. Thanks!
tagged with: python
has comment: http://stackoverflow.com/comment/82869309
tagged with: video
answer count: 0

http://stackoverflow.com/comment/82781694
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47900358
has text: Thank you for taking the time to look over this. Everything looks great except the blank row in between each data row. I edited my New Ouput above and I was wondering if there is a way to remove those empty rows?

http://stackoverflow.com/a/48016722
type: Answer
answers question: http://stackoverflow.com/q/47963386
score: 2
has comment: http://stackoverflow.com/comment/83026454
upvote count: 2
has body: I had a very similar problem! I did two things to make it work 1) The CoreImage.framework is not in the right place, /System/Library/Frameworks/CoreImage.framework/Versions/A/CoreImage. It is actually inside the /System/Library/Frameworks/QuartzCore.framework directory, so copy that into the right location 2) Then you will have to upgrade to latest Mac OS, i'm now on 10.13.2 After that, provided you have opencv installed, it should work.
downvote count: 0

http://stackoverflow.com/comment/82762797
comment on: http://stackoverflow.com/q/47878386
has text: Thanks a lot!!! I got it, and I'm using python 3.6
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47955263
tagged with: python-3.7
possible better answer: http://stackoverflow.com/a/52283085
downvote count: 7
upvote count: 504
linked to: http://stackoverflow.com/q/11351032
tagged with: python-dataclasses
favorite count: 0
linked to: http://stackoverflow.com/q/50764873
has comment: http://stackoverflow.com/comment/82879953
answer count: 5
has answer: http://stackoverflow.com/a/79453698
has answer: http://stackoverflow.com/a/47955313
accepted answer: http://stackoverflow.com/a/47955313
linked to: http://stackoverflow.com/q/44287623
tagged with: python
has comment: http://stackoverflow.com/comment/96296004
has body: PEP 557 introduces data classes into the Python standard library. It says that by applying the @dataclass decorator shown below, it will generate "among other things, an __init__()". from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost(self) -> float: return self.unit_price * self.quantity_on_hand It also says dataclasses are "mutable namedtuples with default", but I don't understand what this means, nor how data classes are different from common classes. What are data classes and when is it best to use them?
score: 497
has comment: http://stackoverflow.com/comment/83984843
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47955306
linked to: http://stackoverflow.com/q/3357581
type: Question
has comment: http://stackoverflow.com/comment/101295618
has answer: http://stackoverflow.com/a/52283085
linked to: http://stackoverflow.com/q/51564841
has answer: http://stackoverflow.com/a/56281598
has title: What are data classes and how are they different from common classes?
tagged with: class

http://stackoverflow.com/comment/82751487
comment on: http://stackoverflow.com/q/47890399
score: 0
type: Comment
has text: Yes, you need to declare it in python. Check the Odoo documentation
type: QuestionComment

http://stackoverflow.com/comment/82803010
has text: Great! I think this matches the output. +1
type: AnswerComment
comment on: http://stackoverflow.com/a/47917169
score: 0
type: Comment

http://stackoverflow.com/a/47942770
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47942730
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47942730
has body: Command Line interprets $6hhh as a variable. Enclose it in single quotes, so your command would be: python main.py 'main$6hhh'

http://stackoverflow.com/a/56420205
upvote count: 1
downvote count: 0
type: Answer
has body: I had the same problem on Mac (python3). I launch Spyder 3.3.3 via Anaconda. In response to the following code: from factor_analyzer import FactorAnalyzer I received the following error: ModuleNotFoundError: No module named 'factor_analyzer' So, I opened Terminal (equivalent of Command Prompt on windows) and typed: pip install factor_analyzer Then, the problem was resolved.
answers question: http://stackoverflow.com/q/47973216
score: 1

http://stackoverflow.com/comment/82914802
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/47972005
has text: part of the trick is to use: p.join() on the items in the array to way on them all finishing. you would add a for loop after the spawn of the process that loops over the list of processes created and then waits on them. example: if you create a procArray = [] and append the p (process) to it for the three spawned process then you can itereate over procArray with something like procArray[i].join() to wait on the processes finishing.

http://stackoverflow.com/q/47964029
has comment: http://stackoverflow.com/comment/82897695
has comment: http://stackoverflow.com/comment/82898648
tagged with: button
score: 0
has comment: http://stackoverflow.com/comment/82899477
tagged with: python
has title: How can i get this "askopenfilename" result without any loop or doubled open?
has body: How can I get fname without any loop? When I write a=loadfile() the window opens 2 times. How can I fix this? def loadfile(): fname = askopenfilename(filetypes=(("Image files(jpg,jpeg,tif,tiff,bmp,png", ("*.jpg","*.jpeg","*.tif","*.tiff","*.png","*.bmp")), ("All files", "*.*"))) return fname buton=Button(frame1,text="File",fg="red",command=loadfile) buton.grid(row=0,column=1,sticky=W) label2= Label(frame1,width=58) label2.grid(row=0,column=2,sticky=E) a=fname root.mainloop()
tagged with: tkinter
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82897745
type: Question

http://stackoverflow.com/q/47862148
tagged with: python
has answer: http://stackoverflow.com/a/47864454
score: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47900396
possible better answer: http://stackoverflow.com/a/47864454
tagged with: signal-processing
type: Question
tagged with: signals
has title: Python SIGINT not terminating calling shell
upvote count: 4
has body: When running Python from a Linux shell (same behavior observed in both bash and ksh), and generating a SIGINT with a Ctl-C keypress, I have discovered behavior that I am unable to understand, and which has frustrated me considerably. When I press Ctl-C, the Python process appropriately terminates, but the shell continues to the next command on the line, as shown in the following console capture: $ python -c "import time; time.sleep(100)"; echo END ^CTraceback (most recent call last): File "<string>", line 1, in <module> KeyboardInterrupt END In contrast, I had expected, and would like, that the shell processes the signal in such a way that execution does not continue to the next command on the line, as I see when I call the sleep function from a bash subshell instead of from Python. For example, I would expect the above capture to appear more similar to the following: $ bash -c "sleep 100"; echo END ^C Python 2 and 3 are installed on my system, and while the above capture was generated running Python 2, both behave the same way. My best explanation is that when I press Ctl-C while the Python process is running, the signal somehow goes directly to the Python process, whereas normally it is handled by the calling shell, then propagated to the subprocess. However, I have no idea why or how Python is causing this difference. The examples above are trivial tests but the behavior is also observed in real-world uses. Installing custom signal handlers does not resolve the issue.
answer count: 3
has answer: http://stackoverflow.com/a/47900396
downvote count: 0
tagged with: shell
favorite count: 0
has answer: http://stackoverflow.com/a/58178464
tagged with: linux

http://stackoverflow.com/q/47896657
has title: Run a docker container from python
favorite count: 0
has comment: http://stackoverflow.com/comment/82760173
tagged with: python
has body: I am trying to 'port' this (working) shell command: IMAGE_NAME="myimage" CONTAINER_NAME="myname" docker run -d --name $CONTAINER_NAME $IMAGE_NAME tail -f /dev/null to start a container from an image to python with: import subprocess IMAGE_NAME="myimage" CONTAINER_NAME="myname" subprocess.check_output(['docker', 'run',"-d","--name %s" % CONTAINER_NAME,"%s" % IMAGE_NAME]) but if fails with: unknown flag: --name myname See 'docker run --help'. Any suggestions?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82760117
upvote count: 1
has answer: http://stackoverflow.com/a/47896710
type: Question
possible better answer: http://stackoverflow.com/a/47896776
has answer: http://stackoverflow.com/a/47896776
accepted answer: http://stackoverflow.com/a/47896710
tagged with: docker
has answer: http://stackoverflow.com/a/60489151
answer count: 3
downvote count: 0
score: 1

inject
tags question: http://stackoverflow.com/q/47999442
tag name: inject
type: Tag

http://stackoverflow.com/q/48013683
has title: Python kivy | Arabic text on Label text
type: AnsweredQuestion
tagged with: kivy-language
score: 1
has answer: http://stackoverflow.com/a/48014297
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/48014297
answer count: 1
favorite count: 0
has body: My problem when i try type arabic text My code is : import kivy from kivy.app import App from kivy.uix.textinput import TextInput class TestApp(App): def build(self): return TextInput(text='مرحبا بكم ') myapp=TestApp() myapp.run() when i execute Textinput text is a some of Square
upvote count: 2
tagged with: python
tagged with: kivy

http://stackoverflow.com/comment/82978518
type: Comment
comment on: http://stackoverflow.com/a/48004825
type: AnswerComment
has text: @WillemVanOnsem according to Django documentation path doesn't use regex as input but string, that is what I was trying to point out https://docs.djangoproject.com/en/2.0/ref/urls/#path The route argument should be a string or gettext_lazy()
score: 0

http://stackoverflow.com/comment/82687046
type: QuestionComment
has text: @Adam It's interesting, I have done this with textfields, when you have the rendered page then you get the content of a textfield and do something. But can't make it work while the page load. I'm afraid that it's not possible.
comment on: http://stackoverflow.com/q/47860912
score: 0
type: Comment

http://stackoverflow.com/q/47913568
score: -5
downvote count: 7
has comment: http://stackoverflow.com/comment/82794828
type: Question
tagged with: for-loop
has comment: http://stackoverflow.com/comment/82794900
has answer: http://stackoverflow.com/a/47914112
has comment: http://stackoverflow.com/comment/82957413
has title: How on earth does this code work
answer count: 1
tagged with: jupyter-notebook
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
has body: I am a bit confused on how this code works. What it does is check whether the rook piece can move somewhere without getting attacked by another root. Here's the code: def rooks_are_safe(chessboard): n = len(chessboard) for row_i in range(n): row_count = 0 for col_i in range(n): row_count += chessboard[row_i][col_i] if row_count &gt; 1: return False for col_i in range(n): col_count = 0 for row_i in range(n): col_count += chessboard[row_i][col_i] if col_count &gt; 1: return False return True

http://stackoverflow.com/comment/82721495
has text: See my Edit2 of the answer.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47874909

http://stackoverflow.com/comment/82894665
has text: "are using the numpy.r_() and it finds every peak". Seriously? [`numpy.r_`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.r_.html) is not a peak finding method.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47962044
score: 1

http://stackoverflow.com/comment/82862619
type: Comment
has text: You had that right already, `x=u[:,0]`. You get different solutions for different values of `x0,v0`, you need to give them to specify an initial-value-problem that then has a unique solution.
comment on: http://stackoverflow.com/a/47944083
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82990798
score: 0
comment on: http://stackoverflow.com/q/48011070
type: QuestionComment
type: Comment
has text: The data is a list of tuples, converted to an ndarray of xs and ys. Inserting a NAN will remove a point from the path. I was thinking I need to look at the difference between consecutive points, but then not sure how to tell plot not to join those points.

http://stackoverflow.com/q/47959435
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82888188
has title: TypeError: 'list' object is not callable(python)
has comment: http://stackoverflow.com/comment/82888163
linked to: http://stackoverflow.com/q/45740182
answer count: 0
duplicate of: http://stackoverflow.com/q/45740182
type: Question
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/82888214
has body: I have following class in python: class State: def __init__(self,current): self.state=list(current) self.costToPath=0 self.stepToPath=[] def costToPath(self,parent): self.costToPath=parent.getCostToPath()+1 def stepToPath(self,path): self.stepToPath.append(path) def setState(self,newState): self.state=list(newState) def getState(self): return self.state def getPath(self): return self.stepToPath def getCostToPath(self): return self.costToPath and when I try to make object os State and call the function costToStep like: s=State([1,2,3]) s.stepToPath("up") I get the following error: TypeError: 'list' object is not callable I am not able to figure this out.

http://stackoverflow.com/comment/82960770
type: QuestionComment
comment on: http://stackoverflow.com/q/47996294
has text: What metrix tool are you using to get the resulting numbers?
score: 0
type: Comment

http://stackoverflow.com/comment/82730521
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47881985
has text: I still have a confusion though. The font color automatically changes to white once selected. How to avoid that and keep the font color not changing?

http://stackoverflow.com/comment/82685559
has text: Sure. The first entry will be the sum of the numbers in the column 'number' which correspond to name 'a'. The first element `0` corresponds to the period `2017-01-01` up to `2017-01-07`(inclusive). The second element `24` corresponds to the period `2017-01-08` up to `2017-01-14`(inclusive) e.t.c.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47860321

http://stackoverflow.com/q/47960299
tagged with: amazon-web-services
has body: I have two PostgreSQL databases db1 = source database and db2 = destination database in a AWS server endpoint. For db1, I just have read rights and for the db2 I have both read and write rights. db1 being production database has a table called 'public.purchases', my task is to get incrementally all the data from 'public.purchases' table in db1 to a 'to be newly created table' in db2 (let me call the table as 'public.purchases_copy'). And every time I run the script to perform this action the destination table which is 'public.purchases_copy' in db2 needs to be updated without fully reloading the table. My question is what would be the best way to achieve this task more efficiently. I did quite a bit of research online and I found out that it can be achieved by connecting Python to PostgreSQL using 'psycopg2' module. Me being not so proficient in Python it would be of great help if somebody help me out in pointing out the links in StackOverflow where the similar question was being answered or guide me in what can be done or how this can be achieved or any particular tutorial which I can refer? Thanks in advance. PostgreSQL version: 9.5, PostgreSQL GUI using: pgadmin 3, Python version installed: 3.5
score: 0
answer count: 1
tagged with: postgresql
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47963320
tagged with: python
has title: Incrementally get all data from source table (in db1) to destination table (in db2) in PostgreSQL
type: Question
tagged with: database

http://stackoverflow.com/a/47989283
answers question: http://stackoverflow.com/q/47989140
score: 0
has body: It is the closest I could get: (\W+|\d{1,}(?!\d\[A-Za-z]))(?![A-Za-z]{2,}) Just replace all matches with space
type: Answer

http://stackoverflow.com/a/48818047
accepted answer of: http://stackoverflow.com/q/47912520
score: 11
answers question: http://stackoverflow.com/q/47912520
type: AcceptedAnswer
downvote count: 0
has body: Normally, when add()ing objects to a session, their related objects will get auto-added like you wanted. That behavior is controlled by the relationship's cascade. Setting cascade to 'delete' in Steps.overview removes the default 'save-update', which is what turns on the auto-adding. You could just add it back with cascade='save-update, delete', but take a look at the possible traits and see what else you might need. A common set is 'all, delete-orphan'. And remember these are strictly ORM behaviors; setting a 'delete' in your cascade won't set the column's ON [event] CASCADE.
type: Answer
upvote count: 11

http://stackoverflow.com/a/47981416
answers question: http://stackoverflow.com/q/47981276
has comment: http://stackoverflow.com/comment/85061989
has comment: http://stackoverflow.com/comment/82943311
score: 0
has body: You can add this code to the model of the view you want to modify: @api.depends() def _compute_module_x_installed(self): for record in self: module = self.env['ir.module.module'].search([ ('name', '=', 'the_module_name') ]) if module and module.state == 'installed': record.update({ 'module_x_installed': True, }) module_x_installed = fields.Boolean( compute='_compute_module_x_installed', string='Is X installed?', ) That way you'll have a field which will indicate you whether the module is installed or not.
has comment: http://stackoverflow.com/comment/82947542
type: Answer
has comment: http://stackoverflow.com/comment/85064253

http://stackoverflow.com/q/47910505
type: UnansweredQuestion
has body: I have several projects in Python cloned from GitHub. Every project needs to first run a setup.py file to install local packages next I run main.py file to execute the code. How can I run all projects in one code (.py file)? I would like to run the first project every minute and the second every 15 seconds.
type: Question
has title: run several .py file with local packages
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/47910730
tagged with: python
tagged with: projects

http://stackoverflow.com/comment/82878666
type: Comment
type: QuestionComment
has text: for first columns its 0, so I Will keep original column, for the 2nd column is position 2, so I would like to get values at position 4, 5 and so on
comment on: http://stackoverflow.com/q/47954564
score: 0

wagtail
tag name: wagtail
tags question: http://stackoverflow.com/q/47955851
tags question: http://stackoverflow.com/q/47863175
tags question: http://stackoverflow.com/q/47994517
tags question: http://stackoverflow.com/q/47858703
tags question: http://stackoverflow.com/q/47913326
type: Tag

http://stackoverflow.com/comment/82902940
type: Comment
type: QuestionComment
has text: did you do something like `numpy = float()` ??
comment on: http://stackoverflow.com/q/47966728
score: 0

http://stackoverflow.com/q/47913291
downvote count: 0
has answer: http://stackoverflow.com/a/47913570
has comment: http://stackoverflow.com/comment/82794290
favorite count: 0
type: Question
tagged with: python
upvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/82794355
has comment: http://stackoverflow.com/comment/82794731
has comment: http://stackoverflow.com/comment/82794328
type: UnansweredQuestion
tagged with: python-3.6
has title: Does python close the file after it comes out?
has body: I tired two code examples , one with close and the other with out close, strace says both code has called .close() is it safe to understand python3.6 does an automatic close: Eg1: the lines in the file is : f = open('./myConfig.cfg') jsonda = json.loads(f.read()) The corresponding strace o/p is open("./myConfig.cfg", O_RDONLY|O_CLOEXEC) = 3 fstat(3, {st_mode=S_IFREG|0644, st_size=693, ...}) = 0 ioctl(3, TCGETS, 0x7ffe829a80a0) = -1 ENOTTY (Inappropriate ioctl for device) lseek(3, 0, SEEK_CUR) = 0 ioctl(3, TCGETS, 0x7ffe829a8040) = -1 ENOTTY (Inappropriate ioctl for device) lseek(3, 0, SEEK_CUR) = 0 lseek(3, 0, SEEK_CUR) = 0 fstat(3, {st_mode=S_IFREG|0644, st_size=693, ...}) = 0 read(3, "{\n \"osns\" : [\n {\n \"fabr"..., 694) = 693 read(3, "", 1) = 0 rt_sigaction(SIGINT, {SIG_DFL, [], SA_RESTORER, 0x7f57b2bc1390}, {0x442160, [], SA_RESTORER, 0x7f57b2bc1390}, 8) = 0 close(3) = 0 sigaltstack(NULL, {ss_sp=0x1f2b0b0, ss_flags=0, ss_size=8192}) = 0 sigaltstack({ss_sp=NULL, ss_flags=SS_DISABLE, ss_size=0}, NULL) = 0 exit_group(0) = ? +++ exited with 0 +++ Similarly in the second file: f = open('./myConfig.cfg') jsonda = json.loads(f.read()) f.close() The corresponding strace o/p is open("./myConfig.cfg", O_RDONLY|O_CLOEXEC) = 3 fstat(3, {st_mode=S_IFREG|0644, st_size=693, ...}) = 0 ioctl(3, TCGETS, 0x7fff2e3f27c0) = -1 ENOTTY (Inappropriate ioctl for device) lseek(3, 0, SEEK_CUR) = 0 ioctl(3, TCGETS, 0x7fff2e3f2760) = -1 ENOTTY (Inappropriate ioctl for device) lseek(3, 0, SEEK_CUR) = 0 lseek(3, 0, SEEK_CUR) = 0 fstat(3, {st_mode=S_IFREG|0644, st_size=693, ...}) = 0 read(3, "{\n \"osns\" : [\n {\n \"fabr"..., 694) = 693 read(3, "", 1) = 0 close(3) = 0 rt_sigaction(SIGINT, {SIG_DFL, [], SA_RESTORER, 0x7f4f52f6d390}, {0x442160, [], SA_RESTORER, 0x7f4f52f6d390}, 8) = 0 sigaltstack(NULL, {ss_sp=0x15130b0, ss_flags=0, ss_size=8192}) = 0 sigaltstack({ss_sp=NULL, ss_flags=SS_DISABLE, ss_size=0}, NULL) = 0 exit_group(0) = ? +++ exited with 0 +++
score: 2

http://stackoverflow.com/comment/82899273
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47964783
score: 0
has text: Python doesn't support bit arrays. Or what do you mean?

http://stackoverflow.com/q/47864617
tagged with: fortran
has comment: http://stackoverflow.com/comment/82694197
has comment: http://stackoverflow.com/comment/82708085
has comment: http://stackoverflow.com/comment/82703087
has comment: http://stackoverflow.com/comment/82694963
has comment: http://stackoverflow.com/comment/82694916
has answer: http://stackoverflow.com/a/47871725
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/82703566
upvote count: 3
has comment: http://stackoverflow.com/comment/82705027
has comment: http://stackoverflow.com/comment/82698298
type: Question
has comment: http://stackoverflow.com/comment/82702353
has comment: http://stackoverflow.com/comment/82694376
has comment: http://stackoverflow.com/comment/82702701
downvote count: 0
tagged with: fortran77
accepted answer: http://stackoverflow.com/a/47871725
has title: Converting Fortran 77 code to Python
answer count: 1
has comment: http://stackoverflow.com/comment/82698777
tagged with: python
has body: I have looked at this Q/A Intent of this Fotran77 code and I have almost converted the below Fortran77 style code into Python 3.x except I had a doubt where the i = i + 1 should be placed in the Python version. As mentioned in the comments of the linked question I have done the conformance tests and the results are off by a margin of 2. Hence the question. i = 0 500 continue i = i +1 if (i .le. ni) then if (u(i,j-1) .gt. -9999.) then r(1,j) = u(i,j-1) go to 600 else missing = i go to 500 end if end if 600 continue Here is my Python version i = 0 while (i &lt;= ni): i = i+1 if (u[i,j-1] &gt; -9999.0): r[0,j] = u[i,j-1] break else: missing = i Did I place the increment counter at the right location ?
linked to: http://stackoverflow.com/q/45719258
favorite count: 0
has comment: http://stackoverflow.com/comment/82694662

http://stackoverflow.com/q/47954657
has title: Python continue from input with the space key
score: 4
answer count: 2
accepted answer: http://stackoverflow.com/a/47955311
has comment: http://stackoverflow.com/comment/82878925
tagged with: key-bindings
has body: I'm making a typing speed test game and trying to make it so that when a user is typing into a python input(), it can be submitted by them pressing space rather than just enter, on Windows. My code is similar to the following: score = 0 start_time = int(time.time()) characters = 0 words = 0 current_word = random.choice(WORDS) next_word = random.choice(WORDS) while (int(time.time()) - start_time) &lt;= TIME_LIMIT: os.system('cls') print(f"Your word is {current_word}") print(f"The next word will be {next_word}") print(f"Your current score is {score}") attempt = input("&gt; ") if attempt.lower() == current_word.lower(): score = score + 1 words = words + 1 characters = characters + len(current_word) current_word = next_word next_word = random.choice(WORDS) Is there any way for this to work or is it best to maybe create my own input function?
has answer: http://stackoverflow.com/a/47955341
linked to: http://stackoverflow.com/q/7821661
upvote count: 4
possible better answer: http://stackoverflow.com/a/47955341
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/136386694
linked to: http://stackoverflow.com/q/510357
favorite count: 0
has answer: http://stackoverflow.com/a/47955311
type: Question
tagged with: input
has comment: http://stackoverflow.com/comment/136386791
tagged with: python

http://stackoverflow.com/q/47984383
score: 0
has answer: http://stackoverflow.com/a/47984422
answer count: 1
has title: ValueError when converting a string to dict:dictionary update sequence element #0 has length 1; 2 is required
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82937756
has body: I'm trying to convert a string to a dictionary but I keep getting this error: ValueError: dictionary update sequence element #0 has length 1; 2 is required Here's my code: string = r'{"extra":[{"text":"Hello World"}]}' json_data = dict(string)
type: Question

http://stackoverflow.com/comment/82754201
has text: try to be more specific with your question title
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47893829
type: Comment

http://stackoverflow.com/comment/82910179
has text: @HameerAbbasi Ah I guess it works just as well with a tuple of scalars as well for this special one axis reduction case.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47969388
score: 0

http://stackoverflow.com/comment/130065619
score: 0
comment on: http://stackoverflow.com/q/47857154
type: QuestionComment
type: Comment
has text: json.load(open('C:/Users/bilal butt/Desktop/PanamalEakJson.json'))['text']

http://stackoverflow.com/a/47929167
score: 2
answers question: http://stackoverflow.com/q/47915483
downvote count: 0
upvote count: 2
has body: Try SERVER and PORT in one variable like this: server = '192.168.0.19, 1433' and remove PORT. If that doesn't work, try {SQL Server} in DRIVER.
type: Answer

http://stackoverflow.com/q/47870165
has answer: http://stackoverflow.com/a/47876008
type: Question
tagged with: twitter-bootstrap
answer count: 2
has body: I would like to customize my django forms. For example, in my code I have working hour settings which I like to produce like this format: mon_start mon_end tue_start tue_end .... but instead it creates a form mon_start mon_end tue_start tue_end .... Here is a view of the output that I dont want Below are my code: forms.py class CompanyWorkingHoursSettingsForm(forms.ModelForm): mon_start = forms.TimeField() mon_end = forms.TimeField() tue_start = forms.TimeField() tue_end = forms.TimeField() class Meta: model = Workinghours fields = ("mon_start","mon_end","tue_start","tue_end") workinghourssettings.html {% extends 'project/base.html' %} {% load bootstrap3 %} {% block page %} Working Hours Settings {% csrf_token %} {% bootstrap_form company_workinghourssettings_form %} Update {% endblock %} How do i produce a custom arranged form for my form fields above ? (in bootstrap)
has comment: http://stackoverflow.com/comment/82706315
tagged with: django
tagged with: python
has title: custom django form template (in bootstrap)
score: 0
tagged with: forms
accepted answer: http://stackoverflow.com/a/47876008
has comment: http://stackoverflow.com/comment/82705977
has comment: http://stackoverflow.com/comment/82706277
possible better answer: http://stackoverflow.com/a/47872496
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47872496

http://stackoverflow.com/comment/82887620
type: Comment
comment on: http://stackoverflow.com/a/47959087
has text: Do you mean `assignment_stmt ::= (target_list "=")+ (expression_list | yield_expression | assignment_stmt)`?
type: AnswerComment
score: 0

http://stackoverflow.com/q/47864389
has comment: http://stackoverflow.com/comment/82706922
has body: I would like to transfer most of my code written on T-SQL to Python, and came across basic data problems that could not be solved by searching in the SQLAlchemy documentation and in other forums. Question: How can I implement the following query options with SQLAlchemy (example for the test - below)? select a.field1, a.field2, b.field2 from server1.database1.schema1.table_a as a inner server2.database1.schema1.table_b as b on a.fileld1 = b.fileld1 select a.field1, a.field2, b.field2 from server1.database1.schema1.table_a as a inner dataset_variable (**) as b on a.fileld1 = b.fileld1 The result of the query - print (select) (see below in the test case) returns an error: sqlalchemy.exc.ProgrammingError: (pyodbc.ProgrammingError) ('42S02', "[42S02] [M icrosoft] [ODBC SQL Server Driver] [SQL Server] Invalid object name 'server2.database1schema1.table_b'. ** Data received from another SQLAlchemy session (server2.database1.schema1.table_b) and stored in the variable dataset_variable Test connection example: Two linked sql servers are used. engine = create_engine("mssql+pyodbc://@{server1}/{}?driver=SQL+Server?trusted_connection=yes", echo=True) metadata = MetaData(engine) Base = declarative_base(metadata=metadata) class table_a(Base): __tablename__ = 'table_a ' __table_args__ = { 'schema': 'database1.schema1' } id = Column(Integer, primary_key=True) f1 = Column(String(100)) f2 = Column(String(100)) class table_b(Base): __tablename__ = 'table_b ' __table_args__ = { 'schema': 'server2.database1.schema1' } id = Column(Integer, primary_key=True) f1 = Column(String(100)) f2 = Column(String(100)) Session = sessionmaker(bind=engine) session = Session() select = session.query(table_b.id).first() print(select)
answer count: 0
score: 1
upvote count: 1
tagged with: sqlalchemy
type: Question
tagged with: sql-server
has comment: http://stackoverflow.com/comment/82703445
linked to: http://stackoverflow.com/q/1857465
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: How can do cross-server queries in SQLAlchemy?

http://stackoverflow.com/comment/82753965
score: 0
type: Comment
type: QuestionComment
has text: Either postgres or sqlite
comment on: http://stackoverflow.com/q/47893496

http://stackoverflow.com/comment/83035762
comment on: http://stackoverflow.com/a/48032542
score: 0
type: AnswerComment
has text: I think you are right, thanks . More precise, by this line https://github.com/pytries/datrie/blob/master/libdatrie/datrie/triedefs.h#L56 from the dependency `libdatrie` . So the cython code is not wrong, error comes from c code.
type: Comment

http://stackoverflow.com/comment/82826958
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47916032
has text: @MadPhysicist, It depends on the extent to which the OP wishes to use these objects. Left to me, I wouldn't be handling raw dicts retrieved from an API like that, especially when they are this complex. I would much rather go the route of combining modularity with encapsulation, so that I'm not scrambling about dealing with each individual component separately.

http://stackoverflow.com/comment/82779870
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47906305
score: 0
has text: @Cleb The result is array([array([[1, 2], [3, 4]]), array([[3, 4], [1, 2], [3, 4]])], dtype=object)

http://stackoverflow.com/comment/82845694
type: Comment
has text: I normally try to use `cmds.window` as it's not so flexible, if you want to `indent` you can just use empty space as ' Output Directory' or a tab `\tOutput Directory`
comment on: http://stackoverflow.com/a/47938068
score: 0
type: AnswerComment

scrapy-splash
tag name: scrapy-splash
tags question: http://stackoverflow.com/q/47857042
tags question: http://stackoverflow.com/q/47948598
type: Tag

http://stackoverflow.com/comment/82881085
comment on: http://stackoverflow.com/a/47955688
type: AnswerComment
has text: I can understand the others, however I think yours is best for others who may view this question, as it's formatted very well and provides answers aimed at programmers at all levels. Upvoted & Accepted.
score: 0
type: Comment

http://stackoverflow.com/comment/82834147
score: 0
has text: @MunSays `os.scandir` can do roughly the same thing as `os.walk` you'll have to read the docs (which Arman has provided) to see how it works.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47906423

http://stackoverflow.com/comment/82852079
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47939136
has text: More precisely it's August 21, 2016. And the seven-digits dates range from about 4000 years ago to over 20000 years into the future. So I find it very reasonable to assume that lexicographical order suffices.
type: AnswerComment

pypy
tags question: http://stackoverflow.com/q/48013074
tags question: http://stackoverflow.com/q/47899347
tag name: pypy
tags question: http://stackoverflow.com/q/47999518
type: Tag

http://stackoverflow.com/a/47944476
answers question: http://stackoverflow.com/q/47944426
upvote count: 1
has body: xgb_model argument was added to the fit() method quite recently (Oct 1). Make sure you have the latest xgboost version installed.
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47944426

http://stackoverflow.com/comment/82720908
type: AnswerComment
comment on: http://stackoverflow.com/a/47877298
has text: @TylerNG fix it , can you try again ?
type: Comment
score: 0

http://stackoverflow.com/a/47923187
score: 1
has comment: http://stackoverflow.com/comment/82814467
has body: Depending on how big is your data, you can build it yourself. That would create list of timestamp with a 1 milisecond difference spanning 1 second. t = [pd.Timestamp('2014-10-07') + pd.Timedelta(x, 'ms') for x in range(1000)] You can modify the initial timestamp including hours/minutes/seconds I have used '2014-10-07' plainly. If you want to modify the frequency then you can add multiples to create a different period (66.67 ms ~ 15Hz) pd.Timedelta(66.67*x, 'ms')
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47922913
type: Answer
has comment: http://stackoverflow.com/comment/82814282
accepted answer of: http://stackoverflow.com/q/47922913
downvote count: 0

http://stackoverflow.com/q/47957480
has comment: http://stackoverflow.com/comment/82884288
has comment: http://stackoverflow.com/comment/82884306
has comment: http://stackoverflow.com/comment/82884349
has title: Why is Poloniex API blocked by CAPTCHA? Expected JSON, but response is HTML
has comment: http://stackoverflow.com/comment/82884335
has comment: http://stackoverflow.com/comment/82884340
type: Question
has answer: http://stackoverflow.com/a/47957795
has comment: http://stackoverflow.com/comment/82884346
answer count: 2
score: 2
has comment: http://stackoverflow.com/comment/82884371
downvote count: 0
tagged with: poloniex
favorite count: 0
has comment: http://stackoverflow.com/comment/82884329
has comment: http://stackoverflow.com/comment/82884313
has comment: http://stackoverflow.com/comment/82884261
has comment: http://stackoverflow.com/comment/82884333
has comment: http://stackoverflow.com/comment/82884900
has comment: http://stackoverflow.com/comment/82884256
tagged with: python
has answer: http://stackoverflow.com/a/49567269
has body: I am using the following code to look up json from the poloniex API. It is returning HTML instead of JSON. What am I doing wrong? I would like JSON. import requests res = requests.get("https://poloniex.com/public?command=returnTradeHistory&amp;currencyPair=BTC_NXT&amp;start=1410158341&amp;end=1410499372") print(res.text)
has comment: http://stackoverflow.com/comment/82884322
has comment: http://stackoverflow.com/comment/82884394
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82884290
tagged with: python-requests
has comment: http://stackoverflow.com/comment/82884347
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/a/47999690
has comment: http://stackoverflow.com/comment/82968024
accepted answer of: http://stackoverflow.com/q/47999547
answers question: http://stackoverflow.com/q/47999547
has body: Initialize q to a list of 1000 0's. Then each time through the loop, combine the new q returned from the function to the existing q. bayesian_prices = [] q = [0]*1000 for i in range(10): newq = dayqvalue(i, grid, fullData) q = [sum(x) for x in zip(q, newq)] w = compute_dayweights(q) option_data, index_prices, initial_date = get_samedated_opt(fullData, i, 1) callput, tmt, ex, mkt = orderdata(option_data) baypr = compute_bayesian_prices(w, grid, callput, tmt, ex, index_prices) bayesian_prices.append(baypr) See Element-wise addition of 2 lists? for other ways to add two lists.
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/47865046
type: Question
tagged with: function
has title: Python why i got no output here
tagged with: yield
has answer: http://stackoverflow.com/a/47865352
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/47865352
has body: I recently started learning python and I cannot figure why I got no output from the code below: def countdown(): i = 5 while i &gt; 0: return i i -= 1 print (i)
tagged with: return
tagged with: python
has comment: http://stackoverflow.com/comment/82694984
type: AnsweredQuestion
score: 1
upvote count: 1

http://stackoverflow.com/comment/82768571
has text: the link is leading to a deprecated version of what is now called the "flexible environment". I'm using standard environment.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47872910
type: AnswerComment

http://stackoverflow.com/q/47877278
tagged with: python
tagged with: machine-learning
downvote count: 1
has title: Google Cloud machine learning out of memory
has answer: http://stackoverflow.com/a/48694883
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48694883
score: -1
type: Question
tagged with: google-cloud-platform
upvote count: 0
tagged with: cloud
answer count: 1
favorite count: 0
has body: I am having a issue of getting out of memory when I choose the following configuration (config.yaml): trainingInput: scaleTier: CUSTOM masterType: large_model workerType: complex_model_m parameterServerType: large_model workerCount: 10 parameterServerCount: 10 I was following Google's tutorial on "criteo_tft": https://github.com/GoogleCloudPlatform/cloudml-samples/blob/master/criteo_tft/config-large.yaml That link says they were able to train 1TB data! I was so impressed to give a try!!! My dataset is categorical so it creates a pretty big matrix after one-hot-encoding (a 2D numpy array of size 520000 x 4000). I am able to train my data set in a local machine having 32GB memory but I am not able to do the same in cloud!!! Here are my errors: ERROR 2017-12-18 12:57:37 +1100 worker-replica-1 Using TensorFlow backend. ERROR 2017-12-18 12:57:37 +1100 worker-replica-4 Using TensorFlow backend. INFO 2017-12-18 12:57:37 +1100 worker-replica-0 Running command: python -m trainer.task --train-file gs://my_bucket/my_training_file.csv -- job-dir gs://my_bucket/my_bucket_20171218_125645 ERROR 2017-12-18 12:57:38 +1100 worker-replica-2 Using TensorFlow backend. ERROR 2017-12-18 12:57:40 +1100 worker-replica-0 Using TensorFlow backend. ERROR 2017-12-18 12:57:53 +1100 worker-replica-3 Command '['python', '-m', u'trainer.task', u'--train-file', u'gs://my_bucket/my_training_file.csv', '--job-dir', u'gs://my_bucket/my_bucket_20171218_125645']' returned non-zero exit status -9 INFO 2017-12-18 12:57:53 +1100 worker-replica-3 Module completed; cleaning up. INFO 2017-12-18 12:57:53 +1100 worker-replica-3 Clean up finished. ERROR 2017-12-18 12:57:56 +1100 worker-replica-4 Command '['python', '-m', u'trainer.task', u'--train-file', u'gs://my_bucket/my_training_file.csv', '--job-dir', u'gs://my_bucket/my_bucket_20171218_125645']' returned non-zero exit status -9 INFO 2017-12-18 12:57:56 +1100 worker-replica-4 Module completed; cleaning up. INFO 2017-12-18 12:57:56 +1100 worker-replica-4 Clea…
tagged with: out-of-memory

http://stackoverflow.com/comment/82682861
score: 1
has text: Just so you know, the pixel data in PNG files is compressed. A tiny change in the data, but also a different compression algorithm, may change the file size. To compare the actual data, do so on the decompressed pixels.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47858996

http://stackoverflow.com/comment/82784878
type: Comment
has text: its a list which contains the probabilities its something like set structure
comment on: http://stackoverflow.com/a/47908467
type: AnswerComment
score: 0

vector
tags question: http://stackoverflow.com/q/47897282
type: Tag
tags question: http://stackoverflow.com/q/47949918
tag name: vector
tags question: http://stackoverflow.com/q/47870003

http://stackoverflow.com/q/47935982
has body: I am trying to scrape a list of website on Shopee. Some example include dudesgadget and 2ubest. Each of these shopee shop have different design and way of constructing their web element and different domain as well. They looks like stand alone website but they are actually not. So the main problem here is I am trying to scrape the product details. I will summarize some different structure: 2ubest littleplayland And few other, and I had discover a pattern between them. The thing that I am looking for will for sure in The thing that I am looking for is within a The only thing that I not sure is the distance from to My solution is: def parse(self, response): body = response.xpath("//body") for script in body.xpath("//script/text()").extract(): #Manipulate the script with js2xml here I am able to extract the littleplayland, dailysteals and many others which has very less distance from the to , but does not works for the 2ubest which has a lot of other html element in between to the thing I am looking for. Can I know are there solution that I can ignore all the html element in between and only look for the tag? I need a single solution that are generic and can work across all Shopee website if possible since all of them have the characteristic that I had mention above. Which mean that the solution should not filter using because every different website have different numbers of
has comment: http://stackoverflow.com/comment/82841823
favorite count: 0
tagged with: xpath
has comment: http://stackoverflow.com/comment/82841985
has answer: http://stackoverflow.com/a/47936285
tagged with: python
has comment: http://stackoverflow.com/comment/82841778
has title: Scrapy Scrape element within unknown number of
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82841931
score: 1
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/82841808
upvote count: 1
tagged with: scrapy
possible better answer: http://stackoverflow.com/a/47936294
type: Question
has answer: http://stackoverflow.com/a/47936294
answer count: 2
accepted answer: http://stackoverflow.com/a/47936285
downvote count: 0
has comment: http://stackoverflow.com/comment/82842255

http://stackoverflow.com/a/47898621
has body: You can use a generator expression in the all function for this. Here's a short demo. count = 0 postag = [('micro', 'NN'), ('walk', 'V'), ('texts', 'NN')] count += all(u[1] == 'NN' for u in postag) print(count) postag = [('micro', 'NN'), ('blog', 'NN'), ('texts', 'NN')] count += all(u[1] == 'NN' for u in postag) print(count) output 0 1 The all function and the related any function are quite efficient, and they short-circuit, which means they stop checking as soon as they have a definite result. So all stops the generator expression loop as soon as it detects a false result.
accepted answer of: http://stackoverflow.com/q/47898582
answers question: http://stackoverflow.com/q/47898582
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/a/47991286
type: Answer
has comment: http://stackoverflow.com/comment/82988638
answers question: http://stackoverflow.com/q/47979623
downvote count: 0
has body: Reading from the web I made this little mod of the code of Axel to read from a txt on the web, Alice in wonderland, to apply the code (as I don't have your txt file and I wanted to try it). So, I publish it here in case someone should need something like this. from collections import Counter import re from urllib.request import urlopen testo = str(urlopen("https://www.gutenberg.org/files/11/11.txt").read()) wanted = ["whereby", "also", "thus", "Alice", "down", "up", "cup"] cnt = Counter() words = re.findall('\w+', testo) for word in words: if word in wanted: cnt[word] += 1 print(cnt) total_cnt = sum(cnt.values()) print(float(total_cnt) / len(cnt)) output Counter({'Alice': 334, 'up': 97, 'down': 90, 'also': 4, 'cup': 2}) 105.4 &gt;&gt;&gt; How many times the same word is found in adjacent sentences This answer to the request (from the author of the question) of looking for how many times a word is found in adjacent sentences. If in a sentence there are more same words (ex.: 'had') and in the next there is another equal, I counted that for 1 ripetition. That is why I used the wordfound list. from collections import Counter import re testo = """There was nothing so VERY remarkable in that; nor did Alice think it so? Thanks VERY much. Out of the way to hear the Rabbit say to itself, 'Oh dear! Oh dear! I shall be late!' (when she thought it over afterwards, it occurred to her that she ought to have wondered at this, but at the time it all seemed. Quite natural); but when the Rabbit actually TOOK A WATCH OUT OF ITS? WAISTCOAT-POCKET, and looked at it, and then hurried on. Alice started to her feet, for it flashed across her mind that she had never before seen a rabbit. with either a waistcoat-pocket, or a watch to take out of it! and burning with curiosity, she ran across the field after it, and fortunately was just in time to see it pop? Down a large rabbit-hole under the hedge. Alice opened the door and found that it led into a small passage, not much larger than a rat-…
has comment: http://stackoverflow.com/comment/82982746
has comment: http://stackoverflow.com/comment/82959077
score: 1
has comment: http://stackoverflow.com/comment/82988380
has comment: http://stackoverflow.com/comment/82988595
has comment: http://stackoverflow.com/comment/82989539
upvote count: 1
has comment: http://stackoverflow.com/comment/82954498

http://stackoverflow.com/comment/82718125
has text: @ ahed87 - I am in Python 3.6.2.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47874513
type: AnswerComment

http://stackoverflow.com/q/47943458
tagged with: regex
has comment: http://stackoverflow.com/comment/82856518
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47943495
has title: Regex - extract word inside < > brackets
has body: I am trying to extract an email address from a string like John Smith &lt;jsmith@email.com&gt; I just need the email address in the &lt; > brackets. Here is what I have tried so far, but I'm not very good with regex and it doesn't seem to be working, can anyone help? import re sender = str(message.sender) p = re.search(r"\&lt;(\w+)\&gt;", sender) logging.info(p.group(1))
has comment: http://stackoverflow.com/comment/82856749
type: Question
has answer: http://stackoverflow.com/a/47943613
has comment: http://stackoverflow.com/comment/82856468
score: 0
has answer: http://stackoverflow.com/a/47943642
answer count: 3

http://stackoverflow.com/comment/82894638
comment on: http://stackoverflow.com/q/47959383
score: 0
type: Comment
type: QuestionComment
has text: The correct syntax for running a file in the current directory in bash is `./run_web.sh`. There should not be any `exec` involved in bash.

http://stackoverflow.com/comment/82830924
comment on: http://stackoverflow.com/q/47930827
score: 0
type: QuestionComment
has text: Oh okay. Sorry about that. Thank you!
type: Comment

http://stackoverflow.com/q/47872237
upvote count: 4
possible better answer: http://stackoverflow.com/a/47872317
answer count: 4
tagged with: integer
has comment: http://stackoverflow.com/comment/82709904
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47873241
downvote count: 0
type: Question
has title: How to read an input file of integers separated by a space using readlines in Python 3?
has comment: http://stackoverflow.com/comment/82709970
score: 4
has body: I need to read an input file (input.txt) which contains one line of integers (13 34 14 53 56 76) and then compute the sum of the squares of each number. This is my code: # define main program function def main(): print("\nThis is the last function: sum_of_squares") print("Please include the path if the input file is not in the root directory") fname = input("Please enter a filename : ") sum_of_squares(fname) def sum_of_squares(fname): infile = open(fname, 'r') sum2 = 0 for items in infile.readlines(): items = int(items) sum2 += items**2 print("The sum of the squares is:", sum2) infile.close() # execute main program function main() If each number is on its own line, it works fine. But, I can't figure out how to do it when all the numbers are on one line separated by a space. In that case, I receive the error: ValueError: invalid literal for int() with base 10: '13 34 14 53 56 76'
has answer: http://stackoverflow.com/a/47872317
has comment: http://stackoverflow.com/comment/82709994
accepted answer: http://stackoverflow.com/a/47872327
has comment: http://stackoverflow.com/comment/82709927
has comment: http://stackoverflow.com/comment/82709898
has answer: http://stackoverflow.com/a/47872367
has answer: http://stackoverflow.com/a/47872327
favorite count: 0
tagged with: readlines
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82709849
tagged with: python

http://stackoverflow.com/q/47902295
downvote count: 0
has answer: http://stackoverflow.com/a/47905435
accepted answer: http://stackoverflow.com/a/47905435
has answer: http://stackoverflow.com/a/64798003
possible better answer: http://stackoverflow.com/a/53117864
type: Question
tagged with: verbose
has answer: http://stackoverflow.com/a/57257512
upvote count: 174
answer count: 6
has body: I'm running the LSTM model for the first time. Here is my model: opt = Adam(0.002) inp = Input(...) print(inp) x = Embedding(....)(inp) x = LSTM(...)(x) x = BatchNormalization()(x) pred = Dense(5,activation='softmax')(x) model = Model(inp,pred) model.compile(....) idx = np.random.permutation(X_train.shape[0]) model.fit(X_train[idx], y_train[idx], nb_epoch=1, batch_size=128, verbose=1) What is the use of verbose while training the model?
has answer: http://stackoverflow.com/a/52355114
tagged with: deep-learning
has answer: http://stackoverflow.com/a/53117864
tagged with: keras
favorite count: 0
has title: What is the use of verbose in Keras while validating the model?
has answer: http://stackoverflow.com/a/68039309
score: 174
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/47953970
has body: I think you should just go to http://localhost:5000/index or http://127.0.0.1:5000/index but if you want to make that page your code should be like that from flask import Flask app = Flask(__name__) @app.route('/') def index(): return 'Hello World' if __name__ == '__main__': app.run(debug=True) change @app.route('/index') to @app.route('/') also you should check this http://flask.pocoo.org/docs/0.12/quickstart/#routing
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47953621
score: 8
answers question: http://stackoverflow.com/q/47953621
type: Answer
has comment: http://stackoverflow.com/comment/82886254
downvote count: 0
upvote count: 8

http://stackoverflow.com/q/47932190
tagged with: pass-by-reference
has comment: http://stackoverflow.com/comment/82834116
has comment: http://stackoverflow.com/comment/82833899
has comment: http://stackoverflow.com/comment/82835829
has body: My intention when executing the following line of code was to use cv2 to draw on my original image (i.e., img). As best I can tell, it did so but modified img (which was not desired). cbImg = cv2.drawChessboardCorners(img, (nx, ny), corners, ret) I understand that Python is pass-by-reference, which means the argument can be changed by the method. To avoid modifying the original image, it is necessary to operate on a copy (e.g., as shown below) cbImg = cv2.drawChessboardCorners(copy.copy(img), (nx, ny), corners, ret) I passed a copy to cv2.drawChessboardCorners() because I cannot modify the method. However, I have seen a number of examples where the copy is performed within the method. Is there a best practice regarding where copying should take place? In other words, if I am using someone else's method, should I always pass a copy to ensure my original image is not modified? Alternatively, when writing my own methods, should I always (or never) perform a copy within my method to ensure that I do not unintentionally modify someone else's argument? Furthermore, is it generally advisable to assume an argument passed by reference should be modified (or not)?
type: Question
has comment: http://stackoverflow.com/comment/82834262
has answer: http://stackoverflow.com/a/47933335
accepted answer: http://stackoverflow.com/a/47933335
tagged with: copy
has comment: http://stackoverflow.com/comment/82833662
score: 0
has comment: http://stackoverflow.com/comment/82833489
has comment: http://stackoverflow.com/comment/82834814
has comment: http://stackoverflow.com/comment/82833694
has comment: http://stackoverflow.com/comment/82834905
answer count: 1
has comment: http://stackoverflow.com/comment/82833449
has comment: http://stackoverflow.com/comment/82834609
has title: Best practice for copying argument passed by reference to method that avoids unintentionally modifying argument
has comment: http://stackoverflow.com/comment/82834149
tagged with: python
has comment: http://stackoverflow.com/comment/82834217
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82835952
has comment: http://stackoverflow.com/comment/82833632

http://stackoverflow.com/comment/82771454
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47899493
has text: are you repeating `bp::exec_file(filename, dict, dict);` to run the script twice? That looks like a smoking gun. You probably need to dispose of the contents of dict between runs
type: Comment

http://stackoverflow.com/a/47986559
answers question: http://stackoverflow.com/q/47979852
has comment: http://stackoverflow.com/comment/82943620
has body: Try doing it this way: torch.cuda.synchronize() t = Variable(torch.randn(5)) t =t.cuda() print(t) Then, it should be blazing fast depending on your GPU memory, at least on every re-run it should be.
score: 0
has comment: http://stackoverflow.com/comment/82943422
has comment: http://stackoverflow.com/comment/82943779
type: Answer

http://stackoverflow.com/comment/82723094
comment on: http://stackoverflow.com/q/47878060
type: Comment
has text: @Inversus. Have you checked to see if there's another module named `enum` on your python path? What is the output of this: `import enum; print(enum.__file__)`?
type: QuestionComment
score: 1

http://stackoverflow.com/q/47946448
type: Question
has comment: http://stackoverflow.com/comment/82862855
score: 0
tagged with: canvas
has body: I am trying to create a rectangle on a tkinter canvas the line of code I am using is this: c.create_rectangle(x, y, x2, y2, fill=fill_, outline=outline_). The variables are all defined c being the canvas variable and the rest numbers and colour names when I run the code the following error occurs: invalid command name ".130125072" (This number is random) and bearing in mind that all of the arguments I have given are integers I have no idea why this error is occurring. If you could give me the answer to why this is not working I will be very grateful. Thanks in advance.
answer count: 1
has comment: http://stackoverflow.com/comment/82862838
has answer: http://stackoverflow.com/a/47946650
has comment: http://stackoverflow.com/comment/82863121
tagged with: python
type: AnsweredQuestion
tagged with: tkinter
has title: Python tkinter creating rectangle error
accepted answer: http://stackoverflow.com/a/47946650

http://stackoverflow.com/a/62143576
has comment: http://stackoverflow.com/comment/112885974
score: 0
type: Answer
has body: One can also achieve this through the AWS sam cli and Docker (we'll explain this requirement later). 1.Create a directory and initialize sam mkdir some_module_layer cd some_module_layer sam init by typing the last command a series of three question would be prompted. One could choose the following series of answers (I'm considering working under Python3.7, but other options are possible). 1 - AWS Quick Start Templates 8 - Python 3.7 Project name [sam-app]: some_module_layer 1 - Hello World Example 2. Modify requirements.txt file cd some_module_layer vim hello_world/requirements.txt this will open requirements.txt file on vim, on Windows you could type instead code hello_world/requirements.txt to edit the file on Visual Studio Code. 3. Add pyarrow to requirements.txt Alongside pyarrow, it will work to include additionnaly pandas and s3fs. In this case including pandas will avoid it to not recognize pyarrow as an engine to read parquet files. pandas pyarrow s3fs 4. Build with a container Docker is required to use the option --use-container when running the sam build command. If it's the first time, it will pull the lambci/lambda:build-python3.7 Docker image. sam build --use-container rm .aws-sam/build/HelloWorldFunction/app.py rm .aws-sam/build/HelloWorldFunction/__init__.py rm .aws-sam/build/HelloWorldFunction/requirements.txt notice that we're keeping only the python libraries. 5. Zip files cp -r .aws-sam/build/HelloWorldFunction/ python/ zip -r some_module_layer.zip python/ On Windows, it would work to run Compress-Archive python/ some_module_layer.zip. 6. Upload zip file to AWS The following link is useful for this.
has comment: http://stackoverflow.com/comment/112885186
answers question: http://stackoverflow.com/q/47984322

http://stackoverflow.com/a/47950485
has body: Edit-1 26-Dec: Updated code to generate data based on your data Based on your requirements I would suggest the below Write headers in headers.csv file Write data in a data.csv file When you want to read/send this file, just merge the two files in one At start of your program read the existing headers.csv file and create field to index mapping When you encounter new keys in data you update the header map with a new index and update header.csv While writing dictionary data, you will use the header map to create the row data Below is a quick/dirty POC of the same and it works well for me import csv try: f = open("headers.csv", mode="r+", encoding="utf-8") except FileNotFoundError: f = open("headers.csv", mode="w+", encoding="utf-8") f2 = open("data.csv", mode="a+", encoding="utf-8") f.seek(0) headers = f.readline().strip().split(",") if headers == ['']: headers = [] headers_map = {} for index, field in enumerate(headers): headers_map[field] = index def update_header_dict(data): updated_headers = False for key in data.keys(): if key not in headers_map: new_index = len(headers_map) headers_map[key] = new_index updated_headers = True if updated_headers: f.seek(0) csv.DictWriter(f, headers_map.keys()).writeheader() f.flush() def get_row_data_dict(data): row_data = [""] * len(headers_map) for k, v in data.items(): # if v and v[0] in ('=', '-'): # # Mark the value as text, only needed if you want to display data in excel # # else should be commented out # v = "'" + v row_data[headers_map[k]] = v return row_data def main(data): data_writer = csv.writer(f2) for row in data: update_header_dict(row) data_writer.writerow(get_row_data_dict(row)) data_ = [ {'Catalog link': '', 'Category': 'Tools and Shop Supplies / Workshop Accessories / Tool ' 'Accessories / Sander Accessories', 'Description': 'Exclusive single-piece hub design reduces pad vibration and ' 'ensures smooth performance.', 'Each': '$ 24.70', 'Info': '', 'Line art': '', 'Name': '(5") Non-Vacuum Disc Pad Vinyl-Face', 'P…
has comment: http://stackoverflow.com/comment/82871699
has comment: http://stackoverflow.com/comment/82930245
score: 4
has comment: http://stackoverflow.com/comment/82873346
has comment: http://stackoverflow.com/comment/82871286
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/47914844
downvote count: 0

http://stackoverflow.com/comment/82708085
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47864617
has text: `missing` should be initialized. (Sloppy old fortan assumption to assume it is initially zero). More importantly is the numeric value actually used or is it just go-no-go flag?
score: 0

http://stackoverflow.com/comment/82680242
comment on: http://stackoverflow.com/q/47857782
type: Comment
type: QuestionComment
has text: Why are you using numpy to save a list of lists? That doesn't make any sense, I wouldn't be surprised if it tries to create an array out of it first.
score: 1

http://stackoverflow.com/comment/82896466
type: QuestionComment
comment on: http://stackoverflow.com/q/47963198
score: 0
has text: The solution was to add buildKV = Builder.load_file("test.kv")
type: Comment

http://stackoverflow.com/q/47999982
tagged with: gdax-api
tagged with: coinbase-api
has title: Websocket to useable data in Python - get price from GDAX websocket feed
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
has body: I am trying to get the last price data to use which is easy enough using polling on /ticker endpoint i.e. rawticker = requests.get('https://api.gdax.com/products/BTC-EUR/ticker') json_data = json.loads(rawticker.text) price = json_data['price'] but the GDAX API discourages polling. How could I get the same information using websocket. How could I get the following code to run just once and then extract the price information. from websocket import WebSocketApp from json import dumps, loads from pprint import pprint URL = "wss://ws-feed.gdax.com" def on_message(_, message): """Callback executed when a message comes. Positional argument: message -- The message itself (string) """ pprint(loads(message)) print def on_open(socket): """Callback executed at socket opening. Keyword argument: socket -- The websocket itself """ params = { "type": "subscribe", "channels": [{"name": "ticker", "product_ids": ["BTC-EUR"]}] } socket.send(dumps(params)) def main(): """Main function.""" ws = WebSocketApp(URL, on_open=on_open, on_message=on_message) ws.run_forever() if __name__ == '__main__': main() Thanks for any help.
type: Question
has answer: http://stackoverflow.com/a/48480447
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/82784472
type: Comment
has text: No, I haven't done that before but VM has no difference from a local machine, so it should work.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47893408

http://stackoverflow.com/comment/82817515
type: Comment
comment on: http://stackoverflow.com/a/47924928
has text: Yes, I could create a wrapper. But is there a downside to using the -u flag?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82701126
comment on: http://stackoverflow.com/a/47867939
type: Comment
has text: You asked for recommandations on the best way to design your model. My recommandation is to use a properly normalized schema. If you want to use some denormalized schema instead please do, but I won't answer on this because I don't think this would really help. If you wonder why, try both solutions, and see which one makes your life easier when it comes to handling answers, scores, and just any stats on your questions/choices/answers.
score: 1
type: AnswerComment

http://stackoverflow.com/q/47906459
score: 1
has title: max_length does not work
has answer: http://stackoverflow.com/a/58066400
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82779777
tagged with: python
has body: I have such field in my model: name = models.CharField(max_length=20, default='Anonymous') But when I enter more characters in that field, there is no errors, I can enter any amount of characters. And I can do it in my view, do it in admin/, there is no errors anyway. Somebody adviced me to make .full_clean() before saving entries, but it does not affect, this field still allows to enter more than 20 characters. Same with other fields. And I very, very, very sorry for my bad english. UPD: Full code of my models.py: from django.db import models from django.core.files.storage import FileSystemStorage import imgboard.const as c fs = FileSystemStorage(location='/static/img') class Board(models.Model): addr = models.CharField(max_length=5, primary_key=True) # Short description to be displayed on index page description = models.CharField(max_length=20, verbose_name="Short description") # Is namefags allowed in this thread names_allowed = models.BooleanField(default=False, verbose_name="Custom names is allowed") default_name = models.CharField(max_length=20, default='Anonymous') # Description to be displayed in header of board page verbose_description = models.CharField(max_length=400, default='') # Allowed extensions of files that can be uploaded to this board allowed_extensions = models.CharField(max_length=1024, default=c.ALLOWED_EXTENSIONS) # Number of a thread, that will be pinned to top. pinned_thread_id = models.IntegerField(default=-1) # Is threads w/o pic allowed file_required = models.BooleanField(default=False, verbose_name="File is required") def __str__(self): return '/'+self.addr+'/ - '+self.description class Meta: ordering = ['addr'] class Thread(models.Model): board = models.ForeignKey(Board, db_column='addr', on_delete=models.CASCADE) name = models.CharField(max_length=20, default='Anonymous') last_msg_date = models.DateTimeField(verbose_name='Time of last message published in this thread', auto_now_add=True) pic = models.CharField(max_length=3000, default…
has comment: http://stackoverflow.com/comment/82792158
accepted answer: http://stackoverflow.com/a/58066400
tagged with: django
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/82780169
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/a/47940422
upvote count: 1
answers question: http://stackoverflow.com/q/47939524
has comment: http://stackoverflow.com/comment/82851985
type: Answer
downvote count: 0
score: 1
has body: I would do something like: /path/README /path/requirements.txt /path/cleverappname/__main__.py /path/cleverappname/__init__.py /path/cleverappname/foo.py /path/cleverappname/bar.py Assuming you have something like class CleverName(object) in __init__.py and things like class Foo(object) in foo.py (same for bar, you got the idea). In __main__: from cleverappname import CleverName from cleverappname.foo import Foo from cleverappname.bar import Bar But, it needs you to use it as a python and not a script (which is right, because that's what it is): python3 -m clevername Pylint seems happy about that.

http://stackoverflow.com/comment/82700328
type: Comment
score: 0
has text: Possible duplicate of [\_tkinter.TclError: invalid command name ".4302957584"](https://stackoverflow.com/questions/16059592/tkinter-tclerror-invalid-command-name-4302957584)
type: QuestionComment
comment on: http://stackoverflow.com/q/47863634

http://stackoverflow.com/q/47956695
has comment: http://stackoverflow.com/comment/82883097
answer count: 1
has title: Converting entry to string in Python TKinter
has comment: http://stackoverflow.com/comment/82883148
favorite count: 0
has comment: http://stackoverflow.com/comment/82882987
accepted answer: http://stackoverflow.com/a/47956882
tagged with: python
tagged with: tkinter
has comment: http://stackoverflow.com/comment/82883110
downvote count: 3
has answer: http://stackoverflow.com/a/47956882
has body: I'm trying to write a simple logging app in TKinter. Basicly I need to compare an entry with a given string (proper pass). Unfortunatly, whenever I type the password, the result of the "entry.get()" method varries the input - printing it returns: &lt;bound method Entry.get of &lt;tkinter.Entry object .!entry&gt;&gt; The code def start_page(): start_window = Tk() ent_1 = Entry(start_window) but_1 = Button(start_window, text='Login', command=partial(login, ent_1.get)) but_1.grid(row=1,column=1) ent_1.grid(row=0, column=1) start_window.mainloop() def login(input_password): correct_password = 'password' if correct_password == input_password: coefficient_calc() start_window.destroy() else: print('You typed:', input_password) print('Please type the correct password.') Any idea how to either convert it or "get" the entry in a desired form? I found few similar topics, but none answerred this particular issue.
upvote count: 1
type: AnsweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/82883011
type: Question

http://stackoverflow.com/q/47992786
has comment: http://stackoverflow.com/comment/82953957
downvote count: 1
tagged with: python
has title: python pickle IndexError: tuple index out of range
favorite count: 0
upvote count: 0
type: UnansweredQuestion
tagged with: pickle
has comment: http://stackoverflow.com/comment/82953676
has answer: http://stackoverflow.com/a/47993507
score: -1
type: Question
answer count: 1
tagged with: python-2.7
has body: Hi I'm working on a python text adventure and I got a save feature working that saved all main variables inventory, location and gold. Then I added in 2 more variables and it wouldn't work. Thanks in advance. Here's my working code. def do_save(self, arg): saveGame = open('savegame.txt', 'wb') saveValues = (inventory, gold, location) pickle.dump(saveValues, saveGame) saveGame.close() def do_load(self, arg): global inventory global gold global location global equiped global health loadGame = open('savegame.txt', 'rb') loadValues = pickle.load(loadGame) inventory = loadValues[0] gold = loadValues[1] location = loadValues[2] loadGame.close() This is the code that isn't working def do_save(self, arg): saveGame = open('savegame.txt', 'wb') saveValues = (inventory, gold, location, equiped, health) pickle.dump(saveValues, saveGame) saveGame.close() def do_load(self, arg): global inventory global gold global location global equiped global health loadGame = open('savegame.txt', 'rb') loadValues = pickle.load(loadGame) inventory = loadValues[0] gold = loadValues[1] location = loadValues[2] equiped = loadValues[3] health = loadValues[4] loadGame.close() The error message I'm getting is IndexError: tuple index out of range

gdb
tags question: http://stackoverflow.com/q/47993882
tag name: gdb
type: Tag

http://stackoverflow.com/comment/82913751
type: Comment
type: QuestionComment
score: 1
has text: @NumberCruncher Well what you have is an iterable. You can read it (scan through start to end) to memory with the readlines() function or just loop over it. Depends what you want to do. One more thing: In Python you can use the `with open(....)` statement to open files which will make sure they are closed. Look it up!
comment on: http://stackoverflow.com/q/47972027

http://stackoverflow.com/a/49244149
answers question: http://stackoverflow.com/q/47916730
accepted answer of: http://stackoverflow.com/q/47916730
has body: I resolved this issue by using another approach to install CDF. Use CDF installer from the link (for Windows) - https://spdf.sci.gsfc.nasa.gov/pub/software/cdf/dist/cdf36_4/windows/ Turn off Anti virus Firewall and then install cdf36_4_0-setup-64.exe or cdf36_4_0-setup-32.exe, based on if you want a 64-bit or a 32-bit version respectively. Without turning off Firewall, I was getting error "Insufficient system resources exist to complete the requested service".
score: 0
type: AcceptedAnswer
type: Answer

indexing
tags question: http://stackoverflow.com/q/47954929
tags question: http://stackoverflow.com/q/47860097
tags question: http://stackoverflow.com/q/47934307
tags question: http://stackoverflow.com/q/48006755
type: Tag
tags question: http://stackoverflow.com/q/48006213
tags question: http://stackoverflow.com/q/47963421
tags question: http://stackoverflow.com/q/47892530
tags question: http://stackoverflow.com/q/47924407
tags question: http://stackoverflow.com/q/47890176
tags question: http://stackoverflow.com/q/47896510
tags question: http://stackoverflow.com/q/47957598
tags question: http://stackoverflow.com/q/47917460
tag name: indexing
tags question: http://stackoverflow.com/q/47972892
tags question: http://stackoverflow.com/q/47857372
tags question: http://stackoverflow.com/q/48011431
tags question: http://stackoverflow.com/q/47892698
tags question: http://stackoverflow.com/q/47909292
tags question: http://stackoverflow.com/q/47877215
tags question: http://stackoverflow.com/q/47997566

http://stackoverflow.com/comment/82723870
type: Comment
comment on: http://stackoverflow.com/a/47878752
has text: You can also use `if not df.empty:`
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82970457
type: QuestionComment
has text: Oh guys, I saw my mistake. As the Patrick said, I have to use randomarray[x]
score: 0
comment on: http://stackoverflow.com/q/48000786
type: Comment

http://stackoverflow.com/a/47988219
downvote count: 0
has body: Ok I found out what the problem was... You cannot use "import scipy" in your script and then later try to exclude it from pyinstaller. I found a way around it where I only include modules inside each of my functions (which are all saved/organized in one file and used for any program I make) now I can go and use: pyinstaller --exclude-module scipy which will successfully remove scipy since it is only listed inside a function which is not being used for the current script i'm trying to convert to EXE Also I see now that python only imports once even if you tell it to import multiple times so this shouldn't slow down my programs even if I keep calling functions that import the same module multiple times
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47985796

http://stackoverflow.com/comment/82743403
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47888605
has text: Is this your whole code? If not, please add some context.
type: Comment

scatter-plot
type: Tag
tags question: http://stackoverflow.com/q/47908429
tags question: http://stackoverflow.com/q/47903691
tag name: scatter-plot

http://stackoverflow.com/comment/82888445
score: 0
has text: Yes, but it's not a good choice for this task. Simple proof: There are no examples of image manipulations in Kivy documentation (other than Scatter).
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47951587

http://stackoverflow.com/q/47955660
tagged with: web-scraping
linked to: http://stackoverflow.com/q/2612548
type: Question
has title: Extracting HTML content with Python using Beautiful Soup
has body: Hi I am using the beautiful soup library to parse content from an html page. I use the following script the get to the part of the page I want to: review_list = soup.find(class_="review_list_score_breakdown_right") Cleanliness 10 Comfort 10 Facilities 10 Staff 10 Value for money 10 Free WiFi 10 Location 10 I need to extract the score from the data-question tags. For example, if I want to know the hotel comfort score, I'd need to access data-question= "hotel_confort" I've tried with the function find() but it doesn't work.
answer count: 2
has answer: http://stackoverflow.com/a/47955718
tagged with: beautifulsoup
score: 0
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has answer: http://stackoverflow.com/a/47957090
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82880955

http://stackoverflow.com/a/47963630
type: Answer
downvote count: 0
has body: Here's another way, using Redis which is a very fast, very simple "data structure server". It can serve strings, integers, atomic integers, lists, queues, hashes, sets, sorted sets and so on and there are clients for C, C++, PHP, Python, the command-line etc. So, if you install Redis on your Raspberry Pi, and start it up with systemctl, you can set and get values. So, let's run a Python script that loops around checking the temperature setting every second: #!/usr/local/bin/python3 import redis from time import sleep # Connect to local Redis server con = redis.Redis("localhost") while True: print(con.get("setting")) sleep(1) Then, on any other machine on the network, you can just use the command line client to set a value for the setting string, e.g: redis-cli -h &lt;IP-ADDRESS-OF-PI&gt; &lt;&lt;&lt; "SET setting 31" Here is an animation of it in action. The top half would be your control program running on the Raspberry Pi, getting the temperature each time through its loop. The bottom half is any other machine on the network, just setting the required temperature at the command line: Of course, you could also transfer data the other way - from Pi to network clients - by storing the actual, measured temperature on the Pi in another variable (SET actual 23) and getting it on your clients with "GET actual".
score: 1
answers question: http://stackoverflow.com/q/47919009
upvote count: 1

http://stackoverflow.com/comment/82707044
type: Comment
comment on: http://stackoverflow.com/q/47870791
score: 0
type: QuestionComment
has text: @Thomas , Thanks for your help. Is there any way to get modified result by JS with scrapy?

http://stackoverflow.com/a/72037459
downvote count: 0
type: Answer
has body: Adding this code below to "urls.py" displays media files in "DEBUG = False": # "urls.py" from django.conf.urls import url from django.views.static import serve from django.conf import settings urlpatterns = [ # ... url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}), ]
upvote count: 2
answers question: http://stackoverflow.com/q/47950571
score: 2

http://stackoverflow.com/comment/82788469
has text: Take a look at this link and let us know if what you are asking is beyond this information. https://github.com/SeleniumHQ/selenium/issues/854
comment on: http://stackoverflow.com/q/47910355
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/47866972
tagged with: python
has answer: http://stackoverflow.com/a/47873893
has comment: http://stackoverflow.com/comment/82699455
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/73894489
upvote count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/82701511
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/73894489
has comment: http://stackoverflow.com/comment/82699668
accepted answer: http://stackoverflow.com/a/47873893
has body: What is the difference between these three: np.zeros(img), np.zeros_like(img), and np.copy(img)*0? When should I use each of them?
score: 0
answer count: 2
has title: What's difference between np.zeros(img) and np.copy(img)*0?
has comment: http://stackoverflow.com/comment/82699507
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82699729

http://stackoverflow.com/q/47859656
has answer: http://stackoverflow.com/a/47859715
tagged with: matrix
has answer: http://stackoverflow.com/a/47859787
has answer: http://stackoverflow.com/a/47859692
has comment: http://stackoverflow.com/comment/82684106
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47859835
tagged with: python
has answer: http://stackoverflow.com/a/47859714
score: 0
type: Question
tagged with: numpy
tagged with: for-loop
has comment: http://stackoverflow.com/comment/82684040
has comment: http://stackoverflow.com/comment/82684083
has body: Suppose I wanted to define an n x m matrix whose i,j th entry is i+j. How do I specify what I want the i,j th entry to be? In a 'for' loop, it doesn't let me say, for example, A[i,j]=i+j. How do I do this?
has title: defining the i,j th entry of a matrix in loop
has comment: http://stackoverflow.com/comment/82684150

http://stackoverflow.com/comment/82908719
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47961427
has text: @coldspeed: It worked. Thank you again and Merry Christmas. I am new to Panda. Could you please explain why the v = x.mul(x.columns.values) was giving NAN. I got the answer by myself after printing v :)
type: AnswerComment

http://stackoverflow.com/comment/103226173
type: Comment
comment on: http://stackoverflow.com/a/54100781
has text: Yes - this is in the DAG Python file. Works till day for me.
score: 0
type: AnswerComment

http://stackoverflow.com/a/47934373
score: 4
has body: You can use zip with list comprehension: Number = [25, 30, 36] Ratings = [ [101, 201, 301], [102, 202, 302], [103, 203, 304,] ] new_data = [[[a, b] for a, b in zip(i, Number)] for i in Ratings] Output: [[[101, 25], [201, 30], [301, 36]], [[102, 25], [202, 30], [302, 36]], [[103, 25], [203, 30], [304, 36]]]
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47934348
type: Answer
answers question: http://stackoverflow.com/q/47934348
upvote count: 4

http://stackoverflow.com/comment/82966918
comment on: http://stackoverflow.com/q/47995938
type: Comment
score: 1
has text: it seems it runs event loop to work correctly - so you may have to run it in thread to not block your mainloop (event lop). It has also `startLoop()` and `endLoop()` to work with other event loop so maybe it can help - see [last example](http://pyttsx.readthedocs.io/en/latest/engine.html#using-an-external-event-loop). You whould have to put your mainloop between `startLoop` and `endLoop` and use `say` (and engine.iterate()`) inside both loops.
type: QuestionComment

http://stackoverflow.com/q/47856092
tagged with: machine-learning
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82678234
downvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/60519480
has comment: http://stackoverflow.com/comment/82716783
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47910911
accepted answer: http://stackoverflow.com/a/47910911
tagged with: cross-validation
tagged with: grid-search
has body: The documentation of best_param_ in GridSearchCV states: best_params_ : dict Parameter setting that gave the best results on the hold out data. From that, I assumed "best results" means best score (highest accuracy / lowest error) and lowest variance over my k-folds. However, this is not case as we can see in cv_results_: Here best_param_ returns k=5 instead of k=9 where mean_test_score and the variance would be optimal. I know I can implement my own scoring function or my own best_param function using the output of cv_results_. But what is the rationale behind not taking the variance into account in the first place? I ran in that situation by applying KNN to iris dataset with 70% train split and a 3-fold cross-validation. Edit: Example code: import numpy as np import pandas as pd from sklearn import neighbors from sklearn import model_selection from sklearn import datasets X = datasets.load_iris().data y = datasets.load_iris().target X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, train_size=0.7, test_size=0.3, random_state=62) knn_model = neighbors.KNeighborsClassifier() param_grid = [{"n_neighbors" : np.arange(1, 31, 2)}] grid_search = model_selection.GridSearchCV(knn_model, param_grid, cv=3, return_train_score=False) grid_search.fit(X_train, y_train.ravel()) results = pd.DataFrame(grid_search.cv_results_) k_opt = grid_search.best_params_.get("n_neighbors") print("Value returned by best_param_:",k_opt) results.head(6) It results in a different table than the image above, but the situation is the same: for k=5 mean_test_score and std_test_score are optimal. However best_param_ returns k=1.
tagged with: scikit-learn
favorite count: 0
has title: Why does best_params_ in GridSearchCV ignore the variance?
score: 0
has comment: http://stackoverflow.com/comment/82676500
has comment: http://stackoverflow.com/comment/82776256
possible better answer: http://stackoverflow.com/a/60519480

http://stackoverflow.com/q/48007017
score: 7
upvote count: 7
has answer: http://stackoverflow.com/a/48007170
accepted answer: http://stackoverflow.com/a/48007059
type: Question
downvote count: 0
possible better answer: http://stackoverflow.com/a/48007170
has body: I'm very lost with a problem and some help or tips will be appreciated. The problem: I've a csv file with a column with the possibility of multiple values like: Fruit;Color;The_evil_column Apple;Red;something1 Apple;Green;something1 Orange;Orange;something1 Orange;Green;something2 Apple;Red;something2 Apple;Red;something3 I've loaded the data into a dataframe and i need to split that dataframe into multiple dataframes based on the value of the column "The_evil_column": df1 Fruit;Color;The_evil_column Apple;Red;something1 Apple;Green;something1 Orange;Orange;something1 df2 Fruit;Color;The_evil_column Orange;Green;something2 Apple;Red;something2 df3 Fruit;Color;The_evil_column Apple;Red;something3 After reading some posts i'm even more confused and i need some tip about this please.
tagged with: python-2.7
tagged with: pandas-groupby
answer count: 3
tagged with: pandas
has title: Pandas split CSV into multiple CSV's (or DataFrames) by a column
favorite count: 0
has answer: http://stackoverflow.com/a/48007248
has answer: http://stackoverflow.com/a/48007059
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/83020888
comment on: http://stackoverflow.com/q/48013749
has text: Ok, with your tip I managed to remove the lines in the init function, but not the arrows because. stream.arrows.remove() is not implemented yet. Furthermore the intial frame gets its arrows removed but not the following frames, i.e. the animation continuously adds lines and arrows. So I guess I have to implement a stream.lines.remove() somewhere in the animate function?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47934388
has comment: http://stackoverflow.com/comment/82859903
has comment: http://stackoverflow.com/comment/82866999
type: Answer
has body: Adding another custom drop down class and adding a button method to open/dismiss the second drop down. The open_drop2() method does the open/dismiss. Added padding to each Button in an attempt to show the cascading a bit. Additional cascading can be done using the same scheme, i.e., add a CustomDropDown3 class that is opened by a button in CustomDropDown2. Note that the dismiss_on_select: False in the kv file is required to be sure that the is2Displayed attribute is updated correctly. .py: from kivy.app import App from kivy.properties import StringProperty from kivy.uix.dropdown import DropDown from kivy.uix.screenmanager import ScreenManager, Screen from kivy.lang import Builder class MyScreenManager(ScreenManager): button_text = StringProperty('Show possibilities') def __init__(self, **kwargs): super(MyScreenManager, self).__init__(**kwargs) self.dropdown = CustomDropDown1(self) def open_drop_down(self, widget): self.dropdown.open(widget) class MyScreen(Screen): def __init__(self, **kwargs): super(MyScreen, self).__init__(**kwargs) class CustomDropDown1(DropDown): def __init__(self, screen_manager, **kwargs): super(CustomDropDown1, self).__init__(**kwargs) self.sm = screen_manager self.dropdown2 = CustomDropDown2(self.sm) self.is2Displayed = False def on_select(self, data): self.sm.button_text = data def open_drop2(self): if not self.is2Displayed: self.dropdown2.open(self) self.is2Displayed = True else: self.dropdown2.dismiss() self.is2Displayed = False class CustomDropDown2(DropDown): def __init__(self, screen_manager, **kwargs): super(CustomDropDown2, self).__init__(**kwargs) self.sm = screen_manager def on_select(self, data): self.sm.button_text = data Builder.load_file("debug.kv") class MyAppli(App): def build(self): return MyScreenManager() if __name__ == '__main__': MyAppli().run() .kv: &lt;MyScreenManager&gt;: MyScreen: FloatLayout: Button: text: root.button_text size: (200, 50) size_hint:(None,None) pos_hint: {'center_x': 0.5, 'top': 1.0} on_release: root.…
score: 0
answers question: http://stackoverflow.com/q/47893756

http://stackoverflow.com/comment/82827220
has text: It took me a while to understand the last part. Now I got it. Thanks again!!!
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47928628

http://stackoverflow.com/comment/82749454
comment on: http://stackoverflow.com/a/47891463
score: 0
has text: I hope you can make this into a proper function yourself. Feel free to ask if something's unclear about it.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48000225
upvote count: 33
has answer: http://stackoverflow.com/a/77103275
downvote count: 0
possible better answer: http://stackoverflow.com/a/74651544
tagged with: pandas
has comment: http://stackoverflow.com/comment/82969108
has answer: http://stackoverflow.com/a/48000572
tagged with: valueerror
has title: Must have equal len keys and value when setting with an iterable
accepted answer: http://stackoverflow.com/a/48000572
favorite count: 0
tagged with: python-3.x
tagged with: python
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/74651544
tagged with: dataframe
has body: I have two dataframes as follows: leader: 0 11 1 8 2 5 3 9 4 8 5 6 [6065 rows x 2 columns] DatasetLabel: 0 1 .... 7 8 9 10 11 12 0 A J .... 1 2 5 NaN NaN NaN 1 B K .... 3 4 NaN NaN NaN NaN [4095 rows x 14 columns] The Information dataset column names 0 to 6 are DatasetLabel about data and 7 to 12 are indexes that refer to the first column of leader Dataframe. I want to create dataset where instead of the indexes in DatasetLabel dataframe, I have the value of each index from the leader dataframe, which is leader.iloc[index,1]. How can I do it using python features? The output should look like: DatasetLabel: 0 1 .... 7 8 9 10 11 12 0 A J .... 8 5 6 NaN NaN NaN 1 B K .... 9 8 NaN NaN NaN NaN I have come up with the following, but I get an error: for column in DatasetLabel.ix[:, 8:13]: DatasetLabel[DatasetLabel[column].notnull()] = leader.iloc[DatasetLabel[DatasetLabel[column].notnull()][column].values, 1] Error: ValueError: Must have equal len keys and value when setting with an iterable
score: 33
type: Question
has answer: http://stackoverflow.com/a/79201635

http://stackoverflow.com/comment/82925957
has text: you can do that in perform_create method or by overriding post method
type: QuestionComment
comment on: http://stackoverflow.com/q/47880666
score: 0
type: Comment

http://stackoverflow.com/q/47892039
tagged with: spyder
accepted answer: http://stackoverflow.com/a/47895902
favorite count: 0
has title: How to import/export syntax coloring scheme
tagged with: python
has answer: http://stackoverflow.com/a/47895902
upvote count: 4
type: AnsweredQuestion
tagged with: anaconda
has body: Is it possible to export my color scheme, so I can import back and forth on other computers and Anaconda envs? I can't seem to find a practical way of doing it.
possible better answer: http://stackoverflow.com/a/57806388
type: Question
answer count: 2
downvote count: 0
score: 4
has answer: http://stackoverflow.com/a/57806388

http://stackoverflow.com/comment/82896716
has text: The objects you are zipping will truncate, but they are of the same length: `(aapl, cisco, ibm, amzn)` has length 3, so does `[.3,.2,.4,.1]`.
comment on: http://stackoverflow.com/q/47963519
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47970238
favorite count: 0
accepted answer: http://stackoverflow.com/a/47970809
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82909925
downvote count: 2
has comment: http://stackoverflow.com/comment/82909838
has body: pref_network_find = re.findall('(\S+\s+255.255.255\S+)',data) prefixes = '\n'.join(['ip ip-prefix VSP_NETWORKS index permit ' + q for q in pref_network_find]) Hi everyone! I have this simple code and the output: ip ip-prefix VSP_NETWORKS index permit 10.185.97.160 255.255.255.224 ip ip-prefix VSP_NETWORKS index permit 11.185.45.64 255.255.255.240 ip ip-prefix VSP_NETWORKS index permit 55.110.192.24 255.255.255.248 ip ip-prefix VSP_NETWORKS index permit 55.110.203.0 255.255.255.0 So, what I need is to add a variable to each line of the list automatically assigned a number with a step of ten. It must be a variable binded to number of lines in the list. Finally, the output must be like this: ip ip-prefix VSP_NETWORKS index 10 permit 10.185.97.160 255.255.255.224 ip ip-prefix VSP_NETWORKS index 20 permit 11.185.45.64 255.255.255.240 ip ip-prefix VSP_NETWORKS index 30 permit 55.110.192.24 255.255.255.248 ip ip-prefix VSP_NETWORKS index 40 permit 55.110.203.0 255.255.255.0
upvote count: 1
type: Question
score: -1
has answer: http://stackoverflow.com/a/47970809
has title: Add a variable with a specific step in a list output
tagged with: python-2.7
answer count: 1

http://stackoverflow.com/q/47946266
upvote count: 0
has comment: http://stackoverflow.com/comment/82862445
favorite count: 0
has comment: http://stackoverflow.com/comment/82862415
has body: what is the mistake in below code? where to define the list variable Jewels? for jew in range(0,Total_Jewels): Jewels[jew]=int(raw_input("Please Enter approx price for Jewel#"+str(jew+1))) error Please Enter approx price for Jewel#111 --------------------------------------------------------------------------- NameError Traceback (most recent call last) in () 1 for jew in range(0,Total_Jewels): ----> 2 Jewels[jew]=int(raw_input("Please Enter approx price for Jewel#"+str(jew+1))) NameError: name 'Jewels' is not defined
tagged with: python
possible better answer: http://stackoverflow.com/a/47946313
has comment: http://stackoverflow.com/comment/82862651
accepted answer: http://stackoverflow.com/a/47946333
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47946313
score: -5
has title: python name error: NameError: name 'Jewels' is not defined
type: Question
downvote count: 5
tagged with: python-2.7
answer count: 2
has answer: http://stackoverflow.com/a/47946333

http://stackoverflow.com/comment/82970297
has text: Why we need agg here ? df.mean()
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48000487
score: 0

http://stackoverflow.com/comment/82762033
type: Comment
has text: @Tom-OliverHeidel's idea would be the most portable. Another that I've personally used is a combination of relatively simple in-line conditional expressions and a standalone function name `pluralize()`: For example: `"%d*day%s" % (self.dperiod, pluralize(self.dperiod))`. The definition of `pluralize()` being `def pluralize(count, ending='s', ones=(-1, 1)):`, `return ending if count not in ones else ''`.
comment on: http://stackoverflow.com/q/47897235
score: 0
type: QuestionComment

http://stackoverflow.com/a/47905264
upvote count: 4
has comment: http://stackoverflow.com/comment/82781448
accepted answer of: http://stackoverflow.com/q/47905049
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47905049
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/82781282
has body: The for loop does not "read" my_copy again on every iteration, but my_copy.remove does. for elem in my_copy: my_copy.remove(elem) On the first iteration, my_copy in both lines refers to the same object. You're actually modifying the object for iterates over. However, at the end of the iteration, you replace my_copy with something else. The for loop retains its original object reference, but my_copy.remove refers to the current version of my_copy. So now the object the for loop iterates over and the object that you remove an element from are two different objects. Hence remove interferes with the loop only on the first iteration.
has comment: http://stackoverflow.com/comment/82781743

http://stackoverflow.com/comment/82682073
score: 0
has text: And you have at least 10 zeros. So again, I don't see, where's your problem is.
type: Comment
comment on: http://stackoverflow.com/a/47858519
type: AnswerComment

pyzmq
tags question: http://stackoverflow.com/q/47898250
tags question: http://stackoverflow.com/q/47971907
tag name: pyzmq
type: Tag

http://stackoverflow.com/q/47951927
accepted answer: http://stackoverflow.com/a/47952107
upvote count: 2
has body: I am confused while inserting data to my Postgres Database in heroku. Here's the thing, I have created connection to database, then cursor = conn.cursor() cursor.execute("INSERT INTO users(username, useremail, userpass) VALUES ('"+_name+"','"+_email+"','"+_password+"')") After executing, I checked the sql status by print(cursor.statusmessage) it returns, INSERT 0 1 but on executing, data = cursor.fetchall() it throws me error File "/Users/abc/PycharmProjects/testSkillNetwork/app.py", line 75, in signUp data = cursor.fetchall(). ProgrammingError: no results to fetch So, i am unable to understand why 'no results' when insertion is successful. Any help will be appreciated. Thanks.
has title: Heroku Database: Insert operation
type: Question
tagged with: heroku
answer count: 2
score: 2
has answer: http://stackoverflow.com/a/47952107
downvote count: 0
favorite count: 0
tagged with: postgresql
possible better answer: http://stackoverflow.com/a/47952095
has answer: http://stackoverflow.com/a/47952095
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/82916977
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47973735
score: 3
has text: where is your python code?

http://stackoverflow.com/comment/82801445
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47898271
has text: "is are" is a typo for "are"; I meant, do the google, find examples of code calling fetchall, and find out how they print out parts of what fetchall returns. You seem to not be exerting any effort to inform yourself. So I suggest that you exert the effort to do what my other comments said, including if necessary exerting the effort to find out what my comments mean. Eg "type" is a technical term. Eg take my comments to a mentor. Eg read an intro to Python. Good luck.

http://stackoverflow.com/q/47927361
has comment: http://stackoverflow.com/comment/83054849
has comment: http://stackoverflow.com/comment/82832308
has comment: http://stackoverflow.com/comment/82822874
score: 1
type: Question
answer count: 2
has title: Python Selenium click() method on web application
has answer: http://stackoverflow.com/a/47927780
has comment: http://stackoverflow.com/comment/82823140
downvote count: 0
tagged with: click
favorite count: 0
has comment: http://stackoverflow.com/comment/82828563
tagged with: python
has answer: http://stackoverflow.com/a/47927491
has body: I am trying to write a program which will interact with a web application. from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By browser = webdriver.Firefox() browser.get('https://www.easports.com/fifa/ultimate-team/web-app/') element = WebDriverWait(browser, 20).until(EC.presence_of_element_located(\ (By.ID, 'Login'))) element.click() print("Found %s" % element) print("locatione %s" % element.location) By design it should've open the browser, wait for page to load and then find and click "Login" button. "Login" button is found, but it doesn't click on it. Location is obviously printing wrong coordinates too. What are possible reasons and solutions for this problem?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82824838
tagged with: selenium
upvote count: 1

http://stackoverflow.com/comment/83004461
has text: you have `data`, `masked_data`, if you want to work from `masked_data` it looks like `masked_data.fill(255)` would cast it to a regular np.array, maybe you need to cast to uint8 too: `np.array(data, dtype=np.uint8)` - then it should be recognized by image processing functions as a grayscale image
comment on: http://stackoverflow.com/q/48013355
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82798240
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47914434
has text: Wow it works! This is so different than excel. Thanks again! you're awesome!
type: AnswerComment

http://stackoverflow.com/comment/82732008
comment on: http://stackoverflow.com/a/47881306
type: AnswerComment
type: Comment
has text: Wasn't sure if I was allowed to do this on stakeoverflow, must confess I try not to post on here. NameError: global name 'parse_object' is not defined <--- parse_object is a function in the parser.py file.
score: 0

http://stackoverflow.com/comment/82679838
comment on: http://stackoverflow.com/q/47856953
score: 0
type: Comment
type: QuestionComment
has text: Try downloading the latest Chromedriver version

http://stackoverflow.com/q/47955218
type: Question
has title: Replacing labels with names using merge
has comment: http://stackoverflow.com/comment/82881532
has answer: http://stackoverflow.com/a/47956067
has comment: http://stackoverflow.com/comment/82881437
tagged with: pandas
answer count: 1
downvote count: 0
has body: I am trying to figure out how to do merge. I have a labels.csv which contains the names that I have to use to replace the numbers for the same field in my dat.csv My dat.csv is as follows: Id,Help in household,Maths,Reading,Science,Social 11011001001,4,20.37,,27.78, 11011001002,3,12.96,,38.18, 11011001003,4,27.78,70,, 11011001004,4,,56.67,,36 11011001005,1,,,14.55,8.33 11011001006,4,,23.33,,30 11011001007,4,40.74,70,, 11011001008,3,,26.67,,22.92 11011001009,2,24.07,,25.45, 11011001010,4,18.52,26.67,, 11011001012,2,37.04,16.67,, 11011001013,4,20.37,,20, 11011001014,2,,,29.63,35.42 11011001015,4,27.78,66.67,, 11011001016,0,18.52,,, 11011001017,4,,,42.59,32 11011001018,2,16.67,,, 11011001019,3,,,21.82, 11011001020,4,,20,,16 11011001021,1,,,18.52,16.67 My labels.csv is as follows: Column,Name,Level,Rename Help in household,Every day,4,Every day Help in household,Never,1,Never Help in household,Once a month,2,Once a month Help in household,Once a week,3,Once a week my programme is as follows: import pandas as pd df = pd.read_csv('dat.csv') labels = pd.read_csv('labels.csv') df=df.merge(labels,left_on='Help in household',right_on='Name',how='left') print df However, the names do not appear as I want them to. STUID Help in household Maths % Reading % Science % Social % \ 0 11011001001 4 20.37 NaN 27.78 NaN 1 11011001002 3 12.96 NaN 38.18 NaN 2 11011001003 4 27.78 70.00 NaN NaN 3 11011001004 4 NaN 56.67 NaN 36.00 4 11011001005 1 NaN NaN 14.55 8.33 5 11011001006 4 NaN 23.33 NaN 30.00 6 11011001007 4 40.74 70.00 NaN NaN 7 11011001008 3 NaN 26.67 NaN 22.92 8 11011001009 2 24.07 NaN 25.45 NaN 9 11011001010 4 18.52 26.67 NaN NaN 10 11011001012 2 37.04 16.67 NaN NaN 11 11011001013 4 20.37 NaN 20.00 NaN 12 11011001014 2 NaN NaN 29.63 35.42 13 11011001015 4 27.78 66.67 NaN NaN 14 11011001016 0 18.52 NaN NaN NaN 15 11011001017 4 NaN NaN 42.59 32.00 16 11011001018 2 16.67 NaN NaN NaN 17 11011001019 3 NaN NaN 21.82 NaN 18 11011001020 4 NaN 20.00 NaN 16.00 19 11011001021 1 NaN NaN 18.5…
has comment: http://stackoverflow.com/comment/82880523
favorite count: 0
has comment: http://stackoverflow.com/comment/82880166
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
accepted answer: http://stackoverflow.com/a/47956067
type: AnsweredQuestion
score: 1
upvote count: 1

http://stackoverflow.com/comment/82805324
comment on: http://stackoverflow.com/a/47918363
score: 0
type: Comment
has text: @Exprator `[a-zA-Z\s]+` to `[a-zA-Z!\s]+`
type: AnswerComment

http://stackoverflow.com/a/47916395
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47915713
has body: The ValueError: math domain error is produced when a function is being asked to calculate a value using parameters that don't make sense for the calculation. If you ask for the log of a negative number, for example. In this case, I'd bet that the user is entering values that are impossible for a right triangle. A hypotenuse that's shorter than one of the other two sides for example.
type: AcceptedAnswer
upvote count: 2
answers question: http://stackoverflow.com/q/47915713
type: Answer

http://stackoverflow.com/comment/82812955
type: QuestionComment
has text: Hm, I get this error: sre_constants.error: missing ), unterminated subpattern at position 1
score: 0
comment on: http://stackoverflow.com/q/47922188
type: Comment

http://stackoverflow.com/q/47860292
upvote count: 5
possible better answer: http://stackoverflow.com/a/47860555
tagged with: python
accepted answer: http://stackoverflow.com/a/47860321
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/47860321
type: Question
score: 5
has title: Creating a pivot table in pandas and grouping at the same time the dates per week
has answer: http://stackoverflow.com/a/47860555
answer count: 3
tagged with: pandas-groupby
tagged with: pandas
has answer: http://stackoverflow.com/a/66873474
has body: I want to create a pd.pivot_table in python where one column is a datetime object, but I want also, to group my results on a weekly basis. Here's a simple example: I have the following DataFrame: import pandas as pd names = ['a', 'b', 'c', 'd'] * 7 dates = ['2017-01-11', '2017-01-08', '2017-01-14', '2017-01-05', '2017-01-10', '2017-01-13', '2017-01-02', '2017-01-12', '2017-01-10', '2017-01-05', '2017-01-01', '2017-01-04', '2017-01-11', '2017-01-14', '2017-01-05', '2017-01-06', '2017-01-14', '2017-01-11', '2017-01-06', '2017-01-05', '2017-01-08', '2017-01-10', '2017-01-07', '2017-01-04', '2017-01-02', '2017-01-04', '2017-01-01', '2017-01-12'] dates = [pd.to_datetime(i).date() for i in dates] numbers = [4, 3, 2, 1 ] * 7 data = {'name': names , 'date': dates, 'number': numbers} df = pd.DataFrame(data) which yields: date name number 0 2017-01-11 a 4 1 2017-01-08 b 3 2 2017-01-14 c 2 3 2017-01-05 d 1 4 2017-01-10 a 4 5 2017-01-13 b 3 6 2017-01-02 c 2 7 2017-01-12 d 1 8 2017-01-10 a 4 9 2017-01-05 b 3 10 2017-01-01 c 2 11 2017-01-04 d 1 12 2017-01-11 a 4 13 2017-01-14 b 3 14 2017-01-05 c 2 15 2017-01-06 d 1 16 2017-01-14 a 4 17 2017-01-11 b 3 18 2017-01-06 c 2 19 2017-01-05 d 1 20 2017-01-08 a 4 21 2017-01-10 b 3 22 2017-01-07 c 2 23 2017-01-04 d 1 24 2017-01-02 a 4 25 2017-01-04 b 3 26 2017-01-01 c 2 27 2017-01-12 d 1 I want to create a pivot table where the rows are going to be the names, the columns are going to be the dates on a weekly basis and the numbers are going to be the sum of the number column. For example, the first row of the pivot table will be: 2017-01-01 2017-01-08 2017-01-15 ... a 4 24 0 What I am doing is: pd.pivot_table(data=df, values='number', columns=pd.Grouper(key='date', freq='1W'), index='name', aggfunc=sum) but I get the Error: TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex'. How am I supposed to do that? I don't know if I can use the date as an index, since all the date values are not…
favorite count: 0

http://stackoverflow.com/q/47951375
type: Question
has title: Python import class from other files
upvote count: 0
answer count: 1
has body: I have three files under the same directory, namely, main.py, Newtester.py, and fileUtility.py. In Newtester.py there is a class named Function. In main.py, there are the following codes: from file.py import * ... def main(): ... funcs = parseFuncSpec(funcInputFile) parseFuncSpec is defined in fileUtilities.py as: some code to import Newtester.py def parseFuncSpec(fName): curFunc = function(funcName, numTest, [], score) Regardless of what I put in import Newtester.py, I always get an error saying "Function" (the class defined in the file "Newtester.py") is not defined. Following Python: How to import other Python files, I have attempted import Newtester __import__("Newtester") exec("Newtester.py") exec("Newtester") import importlib importlib.__import__("Newtester") os.system("Newtester.py") But none of them seemed to work. Any advice is appreciated. See https://github.com/r2dong/unitTesting if you are interested in seeing the complete files.
favorite count: 0
linked to: http://stackoverflow.com/q/2349991
has answer: http://stackoverflow.com/a/47951450
tagged with: python
score: -2
downvote count: 2
has comment: http://stackoverflow.com/comment/82872830
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47951450

http://stackoverflow.com/comment/82895507
score: 0
comment on: http://stackoverflow.com/q/47963008
type: Comment
type: QuestionComment
has text: got what you are saying. @jonrsharpe

http://stackoverflow.com/comment/83072939
comment on: http://stackoverflow.com/q/48006887
type: QuestionComment
type: Comment
has text: How? Can you please tell me how? an example will be helpful@EmiproTechnologiesPvt.Ltd.
score: 0

xml.etree
type: Tag
tag name: xml.etree
tags question: http://stackoverflow.com/q/47935275

http://stackoverflow.com/comment/82791993
score: 0
type: AnswerComment
type: Comment
has text: @Craig Sorry I was away. Glad you got help!
comment on: http://stackoverflow.com/a/47909765

http://stackoverflow.com/comment/82892637
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47961670
has text: what is output you are currently getting ?
score: 0

http://stackoverflow.com/comment/82727062
has text: A number is never going to equal a string.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47880600
score: 3

http://stackoverflow.com/comment/82684331
has text: I did a quick test and indeed your code looks faster. Execution time 0.9 seconds, prior to mine that took 2.2. very good!
type: Comment
comment on: http://stackoverflow.com/a/47859619
score: 0
type: AnswerComment

http://stackoverflow.com/a/47963361
answers question: http://stackoverflow.com/q/47961349
score: 0
has body: Model at least has the following: class YourModel(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(blank=True, null=True) You need to create a file named utils in your app folder which contains the following code: utils.py from django.utils.text import slugify def random_string_generator(size=10, chars=string.ascii_lowercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) def unique_slug_generator(instance, new_slug=None): if new_slug is not None: slug = new_slug else: slug = slugify(instance.title) Klass = instance.__class__ qs_exists = Klass.objects.filter(slug=slug).exists() if qs_exists: new_slug = "{slug}-{randstr}".format( slug=slug, randstr=random_string_generator(size=4) ) return unique_slug_generator(instance, new_slug=new_slug) return slug Models.py from django.db.models.signals import pre_save, post_save from .utils import unique_slug_generator def pre_save_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(pre_save_receiver, sender=YourModel)
type: Answer

http://stackoverflow.com/q/47870573
has comment: http://stackoverflow.com/comment/82706806
tagged with: opencv
has title: Resize a polygon drawn with Numpy and OpenCV in Python
has comment: http://stackoverflow.com/comment/82706512
has comment: http://stackoverflow.com/comment/90173030
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/55722316
has comment: http://stackoverflow.com/comment/82712148
has comment: http://stackoverflow.com/comment/82706669
has comment: http://stackoverflow.com/comment/82706719
has comment: http://stackoverflow.com/comment/82706734
has body: I got a polygon of outer lip from reading face landmarks using dlib and OpenCV as a numpy array of shape (1, 13, 2) Now, I don't want to draw this polygon but instead draw a scaled version of this polygon, let say by increase by 2 times, onto a black image. I came across cv2.resize() but it seems to accept an image for scaling. Giving in the numpy array of points directly to cv.resize() gave this error: OpenCV Error: Assertion failed (func != 0) in cv::hal::resize So, my question is, how to scale first and then draw? Do I have to manually select the upper half and translate the points and separately translate the lower half since the both need translation in different directions. Or is there some way I can use the cv2.resize directly?
score: 0
has comment: http://stackoverflow.com/comment/82706871
answer count: 1
has comment: http://stackoverflow.com/comment/82712106
has comment: http://stackoverflow.com/comment/82706926
has comment: http://stackoverflow.com/comment/82706681
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/47915478
has comment: http://stackoverflow.com/comment/82802385
accepted answer of: http://stackoverflow.com/q/47915147
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82805621
has comment: http://stackoverflow.com/comment/82839730
type: Answer
answers question: http://stackoverflow.com/q/47915147
score: 1
upvote count: 1
has body: troposphere maintainer/stacker author here. So a few things: You want to use TroposphereType(ecs.NetworkConfiguration, many=True) since that's the type of object you want to create. ecs.NetworkConfiguration (https://github.com/cloudtools/troposphere/blob/master/troposphere/ecs.py#L71) is a AWSProperty type, which means the values inside of it, if using "many" needs to be a list of dictionaries per: http://stacker.readthedocs.io/en/latest/blueprints.html#property-types So what I think you want is in your config variables: Networks: - AwsvpcConfiguration: AssignPublicIp: False SecurityGroups: - sg-id Subnets: - subnet-id1 - subnet-id2 This is because TroposphereType expects you to pass in the exact arguments that the type expects. A NetworkConfiguration expects a single key, AwsvpcConfiguration, and the values you were passing were values that were expected by the AwsvcpConfiguration object. The bigger question now is how you expect to use those objects. In Cloudformation/troposphere, Property types aren't created on their own - they used as properties of actual resources- in this case the ecs.Service type. Are you not planning to include the Service in the same blueprint? If not, what is your plan to share these properties with other blueprints where those services live? A better fit might be to have a blueprint that builds the service along with it's NetworkConfiguration. Then, if you want to have the same NetworkConfiguration easily shared between multiple stacks using that blueprint, you can do something with YAML anchors like: common_network_configuration: &amp;common_network_configuration - AwsvpcConfiguration: AssignPublicIp: False SecurityGroups: - sg-id Subnets: - subnet-id1 - subnet-id2 And then use it wherever you want in variables like: variables: &lt;&lt; : *common_network_configuration I hope that makes sense - if you have any more questions, you can always reach us on the stacker Slack as well: https://empire-slack.herokuapp.com/ Have a good one!

http://stackoverflow.com/comment/82741369
score: 3
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47887780
has text: You shouldn't edit files remotely *at all*, either through SFTP or SSH. You should edit locally, commit to version control, then push to your server from there.

amazon-web-services
tags question: http://stackoverflow.com/q/47918524
tags question: http://stackoverflow.com/q/47859052
tags question: http://stackoverflow.com/q/47867995
tags question: http://stackoverflow.com/q/47988417
tags question: http://stackoverflow.com/q/47960299
tags question: http://stackoverflow.com/q/47905855
tags question: http://stackoverflow.com/q/47888472
tags question: http://stackoverflow.com/q/47924089
tags question: http://stackoverflow.com/q/47890544
tags question: http://stackoverflow.com/q/47986073
type: Tag
tags question: http://stackoverflow.com/q/47923452
tags question: http://stackoverflow.com/q/47857179
tags question: http://stackoverflow.com/q/47942154
tag name: amazon-web-services
tags question: http://stackoverflow.com/q/47972522
tags question: http://stackoverflow.com/q/47933565
tags question: http://stackoverflow.com/q/48014551
tags question: http://stackoverflow.com/q/47889975
tags question: http://stackoverflow.com/q/47946875
tags question: http://stackoverflow.com/q/47878893
tags question: http://stackoverflow.com/q/47954451
tags question: http://stackoverflow.com/q/47900138
tags question: http://stackoverflow.com/q/47909840
tags question: http://stackoverflow.com/q/47930893
tags question: http://stackoverflow.com/q/47919164
tags question: http://stackoverflow.com/q/47907641
tags question: http://stackoverflow.com/q/47994825
tags question: http://stackoverflow.com/q/47944567
tags question: http://stackoverflow.com/q/47980946
tags question: http://stackoverflow.com/q/47959037
tags question: http://stackoverflow.com/q/47998944
tags question: http://stackoverflow.com/q/47912359
tags question: http://stackoverflow.com/q/47961638
tags question: http://stackoverflow.com/q/47899753

http://stackoverflow.com/comment/82870611
score: 0
comment on: http://stackoverflow.com/q/47950507
type: QuestionComment
type: Comment
has text: What's with the random bolding?

http://stackoverflow.com/q/48011682
accepted answer: http://stackoverflow.com/a/48012388
tagged with: javascript
tagged with: flask
favorite count: 0
tagged with: ajax
tagged with: python-2.7
has body: I have a page with a button that makes a ajax post to a flask route. I'd like the route to compute a message (simplified by hardcoding for the example) and passes it back to another route and reloads the page the user is on. redirect(urlfor()) does call the other route, but render_template seems not to be called as the page doesn't reload. init.py from flask import Flask, render_template, request, redirect, url_for app = Flask(__name__) @app.route('/second_route', methods=['POST']) def second_route(): print request.json return redirect(url_for('hello_world', message='test')) @app.route('/') def hello_world(message=None): return render_template('index.html', message=message) app.run() index.html {{ message }} Click Me!
tagged with: python
linked to: http://stackoverflow.com/q/199099
upvote count: 3
downvote count: 2
has title: Flask redirect(urlfor()) doesn't reload the page
possible better answer: http://stackoverflow.com/a/48013454
duplicate of: http://stackoverflow.com/q/199099
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48013454
score: 1
has answer: http://stackoverflow.com/a/48012388
type: Question
answer count: 2

http://stackoverflow.com/comment/82706994
type: QuestionComment
score: 1
has text: @Vingtoft I think you misunderstood me, I said *"It's just strange the OP is asking for more advanced methods, **but hasn't shown the most straightforward approach possible**"*. I also did not say that asking for more advanced solutions is bad, just wondering why you didn't post your attempted solution to begin with. This shows that you've put effort into the problem beforehand, instead of just asking people to write code for you. This would also be helpful for users answering to compare the efficiency between the **your** approach and a **library function** approach.
comment on: http://stackoverflow.com/q/47868482
type: Comment

regex
tags question: http://stackoverflow.com/q/47939924
tags question: http://stackoverflow.com/q/47899984
tags question: http://stackoverflow.com/q/47992385
tags question: http://stackoverflow.com/q/47952873
tags question: http://stackoverflow.com/q/47956457
tags question: http://stackoverflow.com/q/47861912
tags question: http://stackoverflow.com/q/47998420
tags question: http://stackoverflow.com/q/47973735
tags question: http://stackoverflow.com/q/48002325
tags question: http://stackoverflow.com/q/47877816
tags question: http://stackoverflow.com/q/47990782
tags question: http://stackoverflow.com/q/47937697
tag name: regex
tags question: http://stackoverflow.com/q/47947950
tags question: http://stackoverflow.com/q/47915716
tags question: http://stackoverflow.com/q/47956930
tags question: http://stackoverflow.com/q/47979949
tags question: http://stackoverflow.com/q/47887769
tags question: http://stackoverflow.com/q/47879781
tags question: http://stackoverflow.com/q/47972604
tags question: http://stackoverflow.com/q/47879126
tags question: http://stackoverflow.com/q/47887882
tags question: http://stackoverflow.com/q/47906708
tags question: http://stackoverflow.com/q/47996333
tags question: http://stackoverflow.com/q/47857863
tags question: http://stackoverflow.com/q/47994214
tags question: http://stackoverflow.com/q/47948505
tags question: http://stackoverflow.com/q/47917731
tags question: http://stackoverflow.com/q/47997500
tags question: http://stackoverflow.com/q/47974814
tags question: http://stackoverflow.com/q/47875765
tags question: http://stackoverflow.com/q/47962817
tags question: http://stackoverflow.com/q/47922188
tags question: http://stackoverflow.com/q/48002016
tags question: http://stackoverflow.com/q/47953523
tags question: http://stackoverflow.com/q/47856288
tags question: http://stackoverflow.com/q/47919127
tags question: http://stackoverflow.com/q/47886800
tags question: http://stackoverflow.com/q/47871354
tags question: http://stackoverflow.com/q/47962902
tags question: http://stackoverflow.com/q/47938345
tags question: http://stackoverflow.com/q/47989140
tags question: http://stackoverflow.com/q/47984091
tags question: http://stackoverflow.com/q/47877144
tags question: http://stackoverflow.com/q/48014040
tags question: http://stackoverflow.com/q/48009046
tags question: http://stackoverflow.com/q/47892494
tags question: http://stackoverflow.com/q/47945819
tags question: http://stackoverflow.com/q/47883436
tags question: http://stackoverflow.com/q/47980835
tags question: http://stackoverflow.com/q/47896449
tags question: http://stackoverflow.com/q/47882237
tags question: http://stackoverflow.com/q/47862783
tags question: http://stackoverflow.com/q/47961210
tags question: http://stackoverflow.com/q/48010179
tags question: http://stackoverflow.com/q/47943458
tags question: http://stackoverflow.com/q/47985855
tags question: http://stackoverflow.com/q/47920064
tags question: http://stackoverflow.com/q/47881392
tags question: http://stackoverflow.com/q/47966556
tags question: http://stackoverflow.com/q/47863881
tags question: http://stackoverflow.com/q/47857664
tags question: http://stackoverflow.com/q/47974903
tags question: http://stackoverflow.com/q/47873270
tags question: http://stackoverflow.com/q/47893426
tags question: http://stackoverflow.com/q/48004509
tags question: http://stackoverflow.com/q/47982949
tags question: http://stackoverflow.com/q/48009064
tags question: http://stackoverflow.com/q/47929324
tags question: http://stackoverflow.com/q/47957841
tags question: http://stackoverflow.com/q/47959054
tags question: http://stackoverflow.com/q/47955661
tags question: http://stackoverflow.com/q/47988787
tags question: http://stackoverflow.com/q/47927980
tags question: http://stackoverflow.com/q/47936681
tags question: http://stackoverflow.com/q/47915831
tags question: http://stackoverflow.com/q/47982331
tags question: http://stackoverflow.com/q/47997174
tags question: http://stackoverflow.com/q/47946897
tags question: http://stackoverflow.com/q/48000993

http://stackoverflow.com/q/47953069
type: Question
upvote count: 2
has body: I have the following api output from a url. I need a specific values for all the 'Zones' from these but i am unable to fetch it . Could you suggest what i need to change here. dict =[ { "Fabric": "Madgth", "Zones": "rqu_kan23_34334_6666_56713", "Members": "00:00:00:00:c9:ae:9f:10 40:00:01:65:36:e4:20:ea" }, { "Fabric": "Madgth", "Zones": "rqu_kan23_C9AE9F10_6666_ytr9", "Members": "00:00:00:00:c9:ae:9f:10 40:00:01:69:36:e4:20:ea" }, { "Fabric": "Madgth", "Zones": "sdgh_5672_kan23_asd0", "Members": "00:00:00:00:c9:ae:9f:10 40:00:01:62:46:e0:70:bc" }, { "Fabric": "Madgth", "Zones": "fdsf_ytr2_kan23_dsd1", "Members": "00:00:00:00:c9:ae:9f:10 40:00:01:6a:46:e0:70:t5" }, { "Fabric": "Madgth", "Zones": "asdasd_5673_kan21_sdg0", "Members": "00:00:00:00:c9:ae:9f:14 40:00:01:63:47:60:04:b2" }, { "Fabric": "Madgth", "Zones": "FGF546_ytr3_kan21_SHQ1", "Members": "00:00:00:00:c9:ae:9f:14 40:00:01:6b:47:60:04:b2" }, { "Fabric": "sdfsdf", "Zones": "rqu_kan23_C9AE9F11_6666_5678", "Members": "00:00:00:00:c9:ae:9f:11 40:00:01:60:36:e4:20:ea" }, { "Fabric": "sdfsdf", "Zones": "rqu_kan23_C9AE9F11_6666_ytr12", "Members": "00:00:00:00:c9:ae:9f:11 40:00:01:6c:36:e4:20:ea" }, { "Fabric": "sdfsdf", "Zones": "FGF1166_5673_kan23_SHQ0", "Members": "00:00:00:00:c9:ae:9f:11 40:00:01:63:46:e0:70:bc" }, { "Fabric": "sdfsdf", "Zones": "FGF1166_ytr3_kan23_SHQ1", "Members": "00:00:00:00:c9:ae:9f:11 40:00:01:6b:46:e0:70:bc" }, { "Fabric": "sdfsdf", "Zones": "FGF546_5670_kan21_SHQ0", "Members": "00:00:00:00:c9:ae:9f:15 40:00:01:60:47:60:04:b2" }, { "Fabric": "sdfsdf", "Zones": "FGF546_ytr0_kan21_SHQ1", "Members": "00:00:00:00:c9:ae:9f:15 00:00:00:00:47:60:04:b2" } ] print dict['Zones'] i seem to be getting the following error. File "test.py", line 3, in print dict['Zones'] TypeError: tuple indices must be integers, not str
tagged with: arrays
has answer: http://stackoverflow.com/a/47953200
has answer: http://stackoverflow.com/a/47953130
answer count: 3
has comment: http://stackoverflow.com/comment/82875567
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: find value from json output
has comment: http://stackoverflow.com/comment/82875526
tagged with: http://stackoverflow.com/tag/json
downvote count: 3
score: -1
has answer: http://stackoverflow.com/a/47953139

http://stackoverflow.com/comment/82885586
type: Comment
comment on: http://stackoverflow.com/a/47958147
type: AnswerComment
has text: Ahh there is a copy& paste mistake for first point. I close and join the pool outside the loop. I will try on 2nd point.
score: 0

http://stackoverflow.com/comment/82896432
type: QuestionComment
has text: @ForceBru I'm sorry, I'm just a high school student, I really don't know much. We were given a base code to work off of for this. def pascals_triangle is how it was given to me, but we are supposed to write the code for def combination. Would it help if I posted the base code?
score: 0
comment on: http://stackoverflow.com/q/47963422
type: Comment

http://stackoverflow.com/q/47874121
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82713974
tagged with: orm
tagged with: django-models
type: Question
has body: Imagine you have a table A which has a foreign key pointing to other table B, but in that B table there is no such key. What should you do if you want to achieve this functionality - add the key in the table B if the key does not exist? Are there any serious concerns about performance issues? Is firstly inserting the record to B then to A worth thinking about?
has title: If foreign key does not exist create it. Django framework
has comment: http://stackoverflow.com/comment/113399310
score: 0
has comment: http://stackoverflow.com/comment/82714022
has comment: http://stackoverflow.com/comment/82714004
tagged with: sql
has comment: http://stackoverflow.com/comment/82713842
answer count: 0

http://stackoverflow.com/comment/82718682
comment on: http://stackoverflow.com/q/47876486
has text: jonrsharpe, you are right. Post that as an answer so I can accept it. juanpa, yes, I acknowledge the performance is pretty horrendous.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/82682737
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47859054
has text: Please clearly state `What is not working?`

http://stackoverflow.com/q/47880348
tagged with: python
answer count: 0
has body: From JSON file, the data is created into data base and stored some fields into an array. How to validate these strings that are mapped to this single array. How can I write a code for this? For example: From this JSON, below strings are stored in DB as an array From JSON { "roadTrip" : [{ "firstStop" : "Place1", "SecondStop" : "Place2", "currency" : "DOLLAR" }] } To DB: roadTrip:Array "firstStop" : "Place1", "SecondStop" : "Place2", "currency" : "DOLLAR"
score: 1
has title: How to Parse JSON strings stored as an in DB
upvote count: 1
has comment: http://stackoverflow.com/comment/83395799
type: Question
has comment: http://stackoverflow.com/comment/83395598
downvote count: 0
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/47984934
tagged with: mysql
has comment: http://stackoverflow.com/comment/82939343
has comment: http://stackoverflow.com/comment/82938847
type: Question
has comment: http://stackoverflow.com/comment/82939361
has comment: http://stackoverflow.com/comment/82939837
has comment: http://stackoverflow.com/comment/82939355
has body: I have the following values pulled from a csv file: vars = ( '001U0000016lf5jIAA', 'Bam Margera Presents: Where the #$&amp;% is Santa? (Unrated)', 'a0KU000000JMpgzMAD' ) How would I insert these? This is what I'm currently doing but it's giving a SQL error probably because of the unescaped % in the second var -- cursor.execute('''INSERT INTO mytable VALUES (%s, %s, %s)''', vars) TypeError: not all arguments converted during string formatting Note: I'd rather keep the vars as-is (without trying to escape anything within it and just modify the SQL/python statement.
answer count: 1
tagged with: mysql-python
has title: Escaping values in mysqldb
has answer: http://stackoverflow.com/a/47985324
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82938842
score: 0

http://stackoverflow.com/comment/82839507
type: Comment
has text: My apologies about the content. I actually corrected the title before it ever got traction but didn't think to look at the content. Thanks again for the help.
comment on: http://stackoverflow.com/a/47934985
type: AnswerComment
score: 0

http://stackoverflow.com/q/47879268
has comment: http://stackoverflow.com/comment/82724762
downvote count: 5
linked to: http://stackoverflow.com/q/1732348
has body: response = 'li&gt;&lt;a href="/beautifulsoup/" title="BeautifulSoup"&gt;&lt;......' what I intend to capture is /beautifulsoup/ this is the correct code link =re.findall(r'href=\"?([^\" ]+)',response) this is my code link =re.findall(r'&gt;&lt;a\b href=\"? .\"\b',response) I had three questions: 1) why are square brackets used. they should only be used for some sequence in character 2) why there is no '.' in correct code after question mark 3) why are parenthesis used; they should only be used for grouping but there is no grouping required
has title: confused with regular expression square brackets
upvote count: 0
answer count: 1
duplicate of: http://stackoverflow.com/q/1545751
favorite count: 0
has answer: http://stackoverflow.com/a/47879485
accepted answer: http://stackoverflow.com/a/47879485
tagged with: python
tagged with: regex
type: AnsweredQuestion
score: -5
linked to: http://stackoverflow.com/q/1545751
linked to: http://stackoverflow.com/q/22937618
type: Question
has comment: http://stackoverflow.com/comment/82725069

http://stackoverflow.com/q/47999638
has comment: http://stackoverflow.com/comment/82967962
has answer: http://stackoverflow.com/a/48001707
has title: How can I make my lines not cross with Turtle?
tagged with: turtle-graphics
type: Question
tagged with: python
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/82968279
has comment: http://stackoverflow.com/comment/82968408
type: UnansweredQuestion
has body: This is part of my code (not ready yet). I need to make lines of the circles not cross, pretending to be overlaying objects. I'd like not to fill in the blank circles. Thanks in advance! # G7 for i in range (140,0,-20): turtle.up() turtle.sety(160) turtle.setx(i) turtle.down() turtle.setheading(90) turtle.circle(i) # G8 for i in range (160,0,-20): turtle.up() turtle.sety(0) turtle.setx(i) turtle.down() turtle.setheading(90) turtle.circle(i,180)

http://stackoverflow.com/a/47941466
has body: For your use case, you could also use a regexp: filtered = a[a.str.contains('E*')]
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/47940850
upvote count: 1

package
tag name: package
tags question: http://stackoverflow.com/q/47961723
tags question: http://stackoverflow.com/q/47901099
type: Tag
tags question: http://stackoverflow.com/q/47949330
tags question: http://stackoverflow.com/q/47935249
tags question: http://stackoverflow.com/q/47940521
tags question: http://stackoverflow.com/q/47895807

http://stackoverflow.com/comment/82942603
type: AnswerComment
has text: BTW: if you use `scrapy` then it can automatically save in `CSV`, `XML`, `JSON`
type: Comment
comment on: http://stackoverflow.com/a/47858268
score: 1

http://stackoverflow.com/comment/82784365
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47908480
has text: For one thing, `window1 = np.zeros((64,1))` does nothing. the new array gets discarded immediately.

http://stackoverflow.com/comment/82838421
comment on: http://stackoverflow.com/q/47934073
score: 0
type: Comment
type: QuestionComment
has text: Shouldn't it be over the sum of the weights, I think the sd is correct

http://stackoverflow.com/comment/82844718
type: QuestionComment
comment on: http://stackoverflow.com/q/47933420
score: 0
has text: BTW, I'm new to posting on the forums... what's the best way to close this out?
type: Comment

http://stackoverflow.com/a/47890283
upvote count: 4
accepted answer of: http://stackoverflow.com/q/47889999
downvote count: 0
has body: If you are trying to make a prediction on a single image, you should add one dimension and then make the prediction like this: import numpy as np img = np.expand_dims(img, axis=0) prediction = model.predict(img)
score: 4
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47889999
type: Answer

http://stackoverflow.com/q/47973735
has body: I'm trying to use regex to verify input. It should accept 8 and only 8 digits (no spaces letters etc). For example: 88884444, 55551234 I tried this but it seems to accept if i put more than 8 digits (if I add letters after that it also accepts) Thanks r'^[0-9]{8,8}'
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/82917003
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82917024
has comment: http://stackoverflow.com/comment/82917097
has title: Python 3 Regex 8 numbers only
type: Question
downvote count: 8
has answer: http://stackoverflow.com/a/47973770
accepted answer: http://stackoverflow.com/a/47973770
has comment: http://stackoverflow.com/comment/82917001
has comment: http://stackoverflow.com/comment/82916996
has comment: http://stackoverflow.com/comment/82916977
upvote count: 1
has comment: http://stackoverflow.com/comment/82917049
answer count: 1
score: -7
has comment: http://stackoverflow.com/comment/82916993
favorite count: 0
has comment: http://stackoverflow.com/comment/82916983

http://stackoverflow.com/q/48009265
linked to: http://stackoverflow.com/q/394809
has title: Sorting strings characters in Python and test the first letter in string
favorite count: 0
has body: def a_letter(string): s = string.lower() if s[0] == 'a': return 'alpha' else: return 'zebra' This code is testing the first letter of a string - if it's an 'a' then return alpha, else return zebra. Is there a better way to do this?
has comment: http://stackoverflow.com/comment/82986878
has comment: http://stackoverflow.com/comment/82986681
has answer: http://stackoverflow.com/a/48009400
answer count: 4
has comment: http://stackoverflow.com/comment/82986752
has comment: http://stackoverflow.com/comment/82986700
has comment: http://stackoverflow.com/comment/82987481
type: UnansweredQuestion
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/82986741
has comment: http://stackoverflow.com/comment/82986939
has answer: http://stackoverflow.com/a/48009562
score: -1
has answer: http://stackoverflow.com/a/48009375
has answer: http://stackoverflow.com/a/48009360
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/82986799
has comment: http://stackoverflow.com/comment/82986682

http://stackoverflow.com/q/47863507
tagged with: web-scraping
tagged with: python
type: AnsweredQuestion
tagged with: selenium
possible better answer: http://stackoverflow.com/a/47863669
type: Question
has answer: http://stackoverflow.com/a/47863669
has comment: http://stackoverflow.com/comment/82692878
has body: I am attempting to download a file from a website using Selenium and Python 3. This requires pressing a confirmation button on an overlay window. The overlay window is not within an iFrame - the HTML is simply dynamically added when the overlay appears - but Selenium is not able to find the button by xPath, returning a NoSuchElementException. Am I missing anything that would cause Selenium not to be able to see the element as it appears in the page source? So far as I can tell, Selenium should be able to locate the button with no issue. #Initialize Driver driver = webdriver.Safari() cmd = "osascript -e 'tell application \"Safari\" to set bounds of front window to {0, 22, 1500, 1022}'" os.system(cmd) #Call up seach link driver.get(data_url) wait_a = WebDriverWait(driver, 15) element = wait_a.until(EC.presence_of_element_located((By.ID, "md-input-3"))) #Initialize and send login information (defined above) username = driver.find_element_by_id("md-input-3") password = driver.find_element_by_id("md-input-6") username.send_keys(crunchbase_username) password.send_keys(crunchbase_password) #Click login button password.send_keys(Keys.ENTER) #Wait for results page to finish loading wait = WebDriverWait(driver, 15) element = wait.until(EC.title_contains("Signals")) time.sleep(2) #Press Download Button driver.find_element_by_xpath("//button[@aria-label='Export your results']").click() time.sleep(2) #Press csv button driver.find_element_by_xpath("//button[@aria-label='Export to CSV']").click() time.sleep(2) #Confirm downlaod driver.find_element_by_xpath("//*[@id='cdk-overlay-36']/md-dialog-container/confirmation-dialog/dialog-layout/div/md-dialog-actions/div/button[2]").click() #Close driver #driver.close() The page source is overly complicated and highly stylized so I will not include it here, but a screenshot of the relevant section of the code in my browser's web inspector is below. The element which I'm trying to click is highlighted in blue. Web Inspector Screenshot I appr…
tagged with: javascript
has comment: http://stackoverflow.com/comment/82692263
score: 0
has answer: http://stackoverflow.com/a/47863996
answer count: 3
has answer: http://stackoverflow.com/a/73924284
tagged with: http://stackoverflow.com/tag/html
accepted answer: http://stackoverflow.com/a/47863996
has title: Selenium cannot find element in main window

http://stackoverflow.com/q/47938193
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/47938239
tagged with: list
has body: Goal: I want to extract longlat tuples in the map key from a request.POST below. &lt;QueryDict: {'map': ['(38.70053557156445, 149.81571853160858)', '(38.70060091643143, 149.8153966665268)'], 'csrfmiddlewaretoken': ###}&gt; Problem: I used ast.literal_eval to extract the tuples but somehow only 2nd tuple is returned. markers = request.POST position = ast.literal_eval(markers['map']) I also tried looping over map with but this is giving me SyntaxError: unexpected EOF while parsing on tuple parentheses. for idx, val in enumerate(markers['map']): position = ast.literal_eval(markers['map'][idx]) Finally, I tried list(map(ast.literal_eval, markers['map'])), but this returns the same SyntaxError as above.
upvote count: 2
accepted answer: http://stackoverflow.com/a/47938239
type: Question
has title: ast.literal_eval - loop over string elements in a list
answer count: 1
downvote count: 0
favorite count: 0
tagged with: tuples

http://stackoverflow.com/q/47897070
accepted answer: http://stackoverflow.com/a/47914603
score: -1
has body: Python is throwing error for some functions that used to run without any issue. I installed pycharm and upgraded some packages on my system. def __init__( self, dbUrl, username, password, use_service_name=False ): dsn = cx_Oracle.makedsn(dbUrl,1521, service_name="TUNET1") if use_service_name else cx_Oracle.makedsn(dbUrl,1521,"TUNET1") self.dbConn = cx_Oracle.connect(username, password, dsn) TypeError: makedsn() takes no keyword arguments And the following as well in another code. TypeError: normalize() argument 2 must be unicode, not str Is this some compatibility issue with python?
tagged with: python-2.7
answer count: 2
has answer: http://stackoverflow.com/a/47914603
tagged with: cx-oracle
downvote count: 1
possible better answer: http://stackoverflow.com/a/47898341
favorite count: 0
tagged with: python
type: AnsweredQuestion
upvote count: 0
has title: Python compatibility issue?
tagged with: pycharm
has answer: http://stackoverflow.com/a/47898341
type: Question

http://stackoverflow.com/comment/82870190
comment on: http://stackoverflow.com/a/47950285
score: 0
type: AnswerComment
has text: Feel free to [edit] with an updated response
type: Comment

http://stackoverflow.com/q/47913841
has comment: http://stackoverflow.com/comment/82801092
has comment: http://stackoverflow.com/comment/82798177
has answer: http://stackoverflow.com/a/47916493
downvote count: 1
has body: Though the question may seem strange, sometimes it really can be useful. For example, I have to build a histogram using plt.hist, but I am not going to plot it, only to send the heights of the bars to the front-end side for actual plotting, and since the back-end side is run on an Ubuntu Server instance, I cannot install matplotlib via pip. Is it possible in general? Are there any other options in my particular case?
type: Question
tagged with: matplotlib
score: -1
tagged with: ubuntu-server
accepted answer: http://stackoverflow.com/a/47916493
upvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82795395
tagged with: python
has title: Matplotlib on OS without GUI
type: AnsweredQuestion

http://stackoverflow.com/q/47922384
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82812518
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82812607
upvote count: 1
tagged with: python
has body: I wrote a pretty simple program that creates a random string, asks the user to enter a string and counts how many letter he missed/hit. It goes on until he guesses the random string. For some reason, when I try to run it I get the error: "to much data to process". I have never seen this error before and don't really know what went wrong and why. I would love to get your input about this. Here is the code I wrote: import random import string def cows_and_bulls(real_string, guess_string): hits = 0 missed = 0 hits_set = [] missed_set = [] for index, letter in enumerate(guess_string): if real_string[index] == letter: hits +=1 hits_set.append(letter) elif letter in real_string and letter not in hits_set: missed +=1 missed_set.append(letter) print(hits, missed) return ("hits:" +str( hits), "missed:" +str( missed)) def main(): random_string = ''.join([random.choice(string.ascii_letters) for n in range(5)]) guess_string = input("please enter a guess string") if len(guess_string) != 5 or guess_string.isalpha == False: print("please enter a new guess") guess_string = input("please enter a guess string") win = False while win is not True: hits,missed = cows_and_bulls(random_string, guess_string) if hits == len(random_string): print("you win!") win = True break if __name__ == '__main__': main() print(cows_and_bulls("abcd", "abdz"))
score: 1
has comment: http://stackoverflow.com/comment/82812652
has comment: http://stackoverflow.com/comment/82812446
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/82813148
has answer: http://stackoverflow.com/a/47923205
has comment: http://stackoverflow.com/comment/82812862
has comment: http://stackoverflow.com/comment/82812874
has title: Too much data to process
has comment: http://stackoverflow.com/comment/82812349
downvote count: 0
has answer: http://stackoverflow.com/a/47922778
has comment: http://stackoverflow.com/comment/82812581
favorite count: 0

http://stackoverflow.com/comment/82988624
type: AnswerComment
type: Comment
has text: @RoadRunner What's wrong with my solution? It also does what the OP wants.
comment on: http://stackoverflow.com/a/48009970
score: 0

http://stackoverflow.com/a/48010939
has body: The problem with this is the else statement. If even one of the checks is false then it will return None. Remove the else statement and get rid of the [2] on the list in the append statement, unless you just want to append the day. lists = [(2012, 'january', 'monday'), (2012, 'february', 'monday'), (2012, 'january', 'tuesday')] day = input("Give day: ") #monday def select_monday(lists, day): list2 = [] for list in lists: if list[2] == day: #from here I'm stuck and do not know how to continue list2.append(list) return list2
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48010796

http://stackoverflow.com/comment/82852512
comment on: http://stackoverflow.com/a/47941455
has text: This does create a *new* `dictionary` though, not change the original
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/82921651
score: 0
has text: Try to increase implicit wait to 30sec
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47973352

http://stackoverflow.com/q/47874370
has comment: http://stackoverflow.com/comment/82801072
tagged with: numpy-ufunc
has comment: http://stackoverflow.com/comment/82781435
type: Question
tagged with: numba
has title: Declaring vectorized ufunc with numba, signature error: 'Float' instance not allowed
tagged with: python
score: 0
tagged with: numpy
type: UnansweredQuestion
has body: I'm trying to write a function that can be vectorized by numba to act as a ufunc on a set of arrays: from numba import float32, float64, vectorize @vectorize([float32, float32, float32, float32(float32, float32, float32, float32, float32, float32, float32, numba.float32), float64, float64, float64, float64(float64, float64, float64, float64, float64, float64, float64, numba.float64)]) def _cafec_coeff_ufunc(ET_bar, PET_bar, R_bar, PR_bar, L_bar, PL_bar, RO_bar, PRO_bar): # calculate alpha if PET_bar == 0: if ET_bar == 0: alpha = 1 else: alpha = 0 else: alpha = ET_bar / PET_bar # calculate beta if PR_bar == 0: if R_bar == 0: beta = 1 else: beta = 0 else: beta = R_bar / PR_bar # calculate gamma if PRO_bar == 0: if RO_bar == 0: gamma = 1 else: gamma = 0 else: gamma = RO_bar / PRO_bar # calculate delta if PL_bar == 0: if L_bar == 0: delta = 1 else: delta = 0 else: delta = L_bar / PL_bar return alpha, beta, gamma, delta I call the above function in another function, passing the eight arrays it needs as arguments. My expectation is that this function will be applied in a broadcasting fashion, as if a 1-D loop for each element i (assuming all input arrays are equal size) with the ufunc getting scalars from each array at the i-th index as its arguments, finally returning with four arrays with corresponding values in the i-th locations of the output arrays (result of the ufunc broadcast reduced into output arrays). alpha, beta, gamma, delta = _cafec_coeff_ufunc(ETbar, PETbar, Rbar, PRbar, Lbar, PLbar, RObar, PRObar) When I run the code above as part of a unit test for the calling method I get the following errors in console: File "C:\home\git\indices_python\palmer.py", line 342, in <module> numba.float64, numba.float64, numba.float64, numba.float64(numba.float64, numba.float64, numba.float64, numba.float64, numba.float64, numba.float64, numba.float64, numba.float64)]) File "C:\Anaconda3\lib\site-packages\numba\npyufunc\decorators.py", line 120, in wrap vec.add(sig) File "C:\…
tagged with: array-broadcasting
answer count: 0

http://stackoverflow.com/comment/82988212
comment on: http://stackoverflow.com/a/48009885
score: 0
type: AnswerComment
type: Comment
has text: It's a math, the definition says it that the number divisible by 2 is even else odd.

fortran77
type: Tag
tags question: http://stackoverflow.com/q/47864617
tag name: fortran77

http://stackoverflow.com/comment/82687406
type: QuestionComment
comment on: http://stackoverflow.com/q/47861191
type: Comment
has text: Can you also include the import statements in your code please? I guess `sp` is SymPy, `sc` is SciPy and where did you import the `gamma()` function from?
score: 0

http://stackoverflow.com/comment/82722341
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47878044
score: 1
has text: Alternatively, you could do `map = dict(zip(mylist, ranklist))` then `sorted(mylist, key=map.get)`

http://stackoverflow.com/comment/82957627
comment on: http://stackoverflow.com/a/47985841
score: 0
type: AnswerComment
type: Comment
has text: That works and results with a sql query. So why is my text input showing as blank??? Though the entry box shows my text?

http://stackoverflow.com/comment/82832531
comment on: http://stackoverflow.com/q/47931749
score: 0
type: QuestionComment
has text: I get `6.25` instead of `0` for the last result with SciPy.
type: Comment

http://stackoverflow.com/a/47891881
has body: pd.Series.mask. df['b'] = df.b.mask(df.index &lt; 2) df a b c 0 1 NaN 3 1 4 NaN 6 2 7 8.0 9 If your df.index is not a monotonically increasing integer index, then you can replace df.index with np.arange(len(df)) - df.b.mask(np.arange(len(df)) &lt; 2) 0 NaN 1 NaN 2 8.0 Name: b, dtype: float64 np.where df['b'] = np.where(df.index &lt; 2, np.nan, df.b) df a b c 0 1 NaN 3 1 4 NaN 6 2 7 8.0 9 np.ndarray.__getitem__ Similar to Wen's iloc, indexing on numpy arrays - i = df.b.values i[:2] = np.nan df['b'] = i df a b c 0 1 NaN 3 1 4 NaN 6 2 7 8.0 9
score: 5
type: Answer
has comment: http://stackoverflow.com/comment/82751813
accepted answer of: http://stackoverflow.com/q/47891866
type: AcceptedAnswer
upvote count: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/82751830
answers question: http://stackoverflow.com/q/47891866

http://stackoverflow.com/q/47862083
has answer: http://stackoverflow.com/a/47862219
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/47862184
upvote count: 1
type: Question
type: AnsweredQuestion
tagged with: performance
has body: I am currently implementing Huffman coding in python and I've finished it but I want to make it more efficient. This is the method I use to get the content of the original file def getDecodedFile(self, text, codes): code = "" origin = [] for ch in text: code += ch if code in codes: origin.append(codes[code]) code = "" bCodes = bytes(origin) return bCodes text Is the large string and codes is a dictionary of Huffman codes (Key is a string of the code and value is an int between 0 and 255) I've trying using ''.join(somelist) instead of code += ch but the result was way slower. Currently this method takes 3 seconds to execute with len(text) = 13972363 and the shortest code length is 6 Example of data: text = "0100101110111" codes = {'0': 65, '100': 66, '101': 67, '110': 68, '111': 69} That would result in origin = [65,66,67,68,69] I would appreciate any suggestion to make my code efficient.
has title: Iterating over a large string and checking membership of substrings in a dictionary performance
answer count: 2
accepted answer: http://stackoverflow.com/a/47862184
downvote count: 0
tagged with: string
favorite count: 0
possible better answer: http://stackoverflow.com/a/47862219