http://stackoverflow.com/comment/89997121
has text: No. Apache bench tool is a command line program that you run to test any server. Did you even bother to open the link I posted in my comment?
comment on: http://stackoverflow.com/q/51462924
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89692051
type: AnswerComment
type: Comment
has text: i totally get your point. I knew my data was float but i was still confused as to why the column type was an object .thats why i was using `to_numeric`. then you pointed at the issue of using int and float in one column ...still investigating how to fix this by replacing 0
comment on: http://stackoverflow.com/a/51359437
score: 0

http://stackoverflow.com/q/51381806
has comment: http://stackoverflow.com/comment/89738836
type: UnansweredQuestion
score: 2
has title: Read CSV file with specific columns as String in PySpark
has comment: http://stackoverflow.com/comment/89737890
tagged with: pyspark
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/89738686
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/89738539
tagged with: python
favorite count: 0
has body: I have a large file which is dynamically generated, a small sample of which is given below: ID,FEES,I_CLSS 11,5555,00000110 12,5555,654321 13,5555,000030 14,5555,07640 15,5555,14550 17,5555,99070 19,5555,090090 My issue is that I will always have a column like I_CLSS that is starting with 0s in this file. I'd like to read the file to a spark dataframe with I_CLSS column as StringType. For this, in python I can do something like, df = pandas.read_csv('INPUT2.csv',dtype={'I_CLSS': str}) But is there an alternative to this command in pyspark? I understand that I can manually specify the schema of a file in Pyspark. But it would be extremely diffficult to do for a file whose columns are dynamically generated. So I'd appreciate it if somebody could help me with this.
has comment: http://stackoverflow.com/comment/89738073
answer count: 0
upvote count: 2

http://stackoverflow.com/a/51346326
upvote count: 1
has body: remove(x) doesn't remove the item indexed x from the set (sets are unordered in Python), but the element with value x: remove(elem) Remove element elem from the set. Raises KeyError if elem is not contained in the set.
downvote count: 0
answers question: http://stackoverflow.com/q/51346270
type: Answer
score: 1

http://stackoverflow.com/comment/89683471
has text: Agreed. I want to point to this related meta post: https://meta.stackoverflow.com/questions/329321/unethical-possibly-illegal-assistance
score: 0
comment on: http://stackoverflow.com/q/51354616
type: Comment
type: QuestionComment

http://stackoverflow.com/a/53001780
type: Answer
has comment: http://stackoverflow.com/comment/92958201
answers question: http://stackoverflow.com/q/51472284
score: 0
has body: I had the same issue but I followed Tom's advice and used CMD to navigate to the Scripts folder. Then I went to https://www.pygame.org/wiki/GettingStarted and used py -m pip install -U pygame --user for windows installation.

http://stackoverflow.com/q/51368696
has answer: http://stackoverflow.com/a/51368953
answer count: 3
has answer: http://stackoverflow.com/a/51374468
has comment: http://stackoverflow.com/comment/89712215
score: 2
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89711076
has comment: http://stackoverflow.com/comment/89711338
tagged with: pandas
has comment: http://stackoverflow.com/comment/89710106
has title: Having columns with subscripts/indices in pandas
tagged with: python
has body: Let's say that I have som data from a file where some columns are "of the same kind", only of different subscripts of some mathematical variable, say x: n A B C x[0] x[1] x[2] 0 1 2 3 4 5 6 1 2 3 4 5 6 7 Is there some way I can load this into a pandas dataframe df and somehow treat the three x-columns as an indexable, array-like entity (I'm new to pandas)? I believe it would be convenient, because I could do operations on the data-series contained in x such as sum(df.x). Kind regards. EDIT: Admittedly, my original post was not clear enough. I'm not just interested in getting the sum of three columns. That was just an example. I'm looking for a generally applicable abstraction that I hope is built into pandas. I'd like to have multiple columns accessible through (sub-)indices of one entity, e.g. df.x[0], such that I (or any other user of the data) can do whichever operation he/she wants (sum/max/min/avg/standard deviation, you name it). You can consider the x's as an ensamble of time-dependent measurements if you like. Kind regards.
favorite count: 0
has comment: http://stackoverflow.com/comment/89709819
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/51369026

http://stackoverflow.com/q/51429792
has comment: http://stackoverflow.com/comment/90285487
has comment: http://stackoverflow.com/comment/90285375
has comment: http://stackoverflow.com/comment/89831073
has comment: http://stackoverflow.com/comment/89831132
tagged with: scipy
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/89831833
has answer: http://stackoverflow.com/a/51753202
has title: Unexpected FFT Results with Python
has comment: http://stackoverflow.com/comment/90285253
has comment: http://stackoverflow.com/comment/89832343
downvote count: 0
has comment: http://stackoverflow.com/comment/89880094
has comment: http://stackoverflow.com/comment/89831621
answer count: 1
accepted answer: http://stackoverflow.com/a/51753202
favorite count: 0
tagged with: fft
linked to: http://stackoverflow.com/q/25735153
upvote count: 2
tagged with: dft
has body: I'm analyzing what is essentially a respiratory waveform, constructed in 3 different shapes (the data originates from MRI, so multiple echo times were used; see here if you'd like some quick background). Here are a couple of segments of two of the plotted waveforms for some context: For each waveform, I'm trying to perform a DFT in order to discover the dominant frequency or frequencies of respiration. My issue is that when I plot the DFTs that I perform, I get one of two things, dependent on the FFT library that I use. Furthermore, neither of them is representative of what I am expecting. I understand that data doesn't always look the way we want, but I clearly have waveforms present in my data, so I would expect a discrete Fourier transform to produce a frequency peak somewhere reasonable. For reference here, I would expect about 80 to 130 Hz. My data is stored in a pandas data frame, with each echo time's data in a separate series. I'm applying the FFT function of choice (see the code below) and receiving different results for each of them. SciPy (fftpack) import pandas as pd import scipy.fftpack # temporary copy to maintain data structure lead_pts_fft_df = lead_pts_df.copy() # apply a discrete fast Fourier transform to each data series in the data frame lead_pts_fft_df.magnitude = lead_pts_df.magnitude.apply(scipy.fftpack.fft) lead_pts_fft_df NumPy: import pandas as pd import numpy as np # temporary copy to maintain data structure lead_pts_fft_df = lead_pts_df.copy() # apply a discrete fast Fourier transform to each data series in the data frame lead_pts_fft_df.magnitude = lead_pts_df.magnitude.apply(np.fft.fft) lead_pts_fft_df The rest of the relevant code: ECHO_TIMES = [0.080, 0.200, 0.400] # milliseconds f_s = 1 / (0.006) # 0.006 = time between samples freq = np.linspace(0, 29556, 29556) * (f_s / 29556) # (29556 = length of data) # generate subplots fig, axes = plt.subplots(3, 1, figsize=(18, 16)) for idx in range(len(ECHO_TIMES)): axes[idx].plot(freq, lead_p…
has comment: http://stackoverflow.com/comment/90285458
tagged with: python
has comment: http://stackoverflow.com/comment/90028240
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90023579

http://stackoverflow.com/comment/89868016
has text: Have you tried searching for it? Not very hard to find i think. Have a look at this answer from Polynomial https://stackoverflow.com/questions/8560166/silent-installation-of-a-msi-package
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51448642
score: 0

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

http://stackoverflow.com/comment/89685389
type: Comment
comment on: http://stackoverflow.com/a/51349872
has text: I am not sure, but there was only one version of gurobipy available in pycharm. I will check again. and tnx for your time
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89772943
type: Comment
comment on: http://stackoverflow.com/a/51400630
has text: @laland `for row in reader:` variable row is a list of strings now.. you need to do something like `row.append(row['first_name']; row.append(row['last_name'];` or `row.append(row[0]; row.append(row[1];` to add new list items.
type: AnswerComment
score: 0

http://stackoverflow.com/q/51336934
has comment: http://stackoverflow.com/comment/89648558
linked to: http://stackoverflow.com/q/16970982
has title: Remove only rows which contain duplicates within that row of 3D numpy array
type: AnsweredQuestion
score: 3
upvote count: 3
type: Question
tagged with: numpy
answer count: 2
has body: I have a 3D numpy array like this: &gt;&gt;&gt; a array([[[0, 1, 2], [0, 1, 2], [6, 7, 8]], [[6, 7, 8], [0, 1, 2], [6, 7, 8]], [[0, 1, 2], [3, 4, 5], [6, 7, 8]]]) I want to remove only those rows which contain duplicates within themselves. For instance the output should look like this: &gt;&gt;&gt; remove_row_duplicates(a) array([[[0, 1, 2], [3, 4, 5], [6, 7, 8]]]) This is the function that I am using: delindices = np.empty(0, dtype=int) for i in range(len(a)): _, indices = np.unique(np.around(a[i], decimals=10), axis=0, return_index=True) if len(indices) &lt; len(a[i]): delindices = np.append(delindices, i) a = np.delete(a, delindices, 0) This works perfectly, but the problem is now my array shape is like (1000000,7,3). The for loop is pretty slow in python and this take a lot of time. Also my original array contains floating numbers. Any one who has a better solution or who can help me vectorizing this function?
possible better answer: http://stackoverflow.com/a/51337050
downvote count: 0
has answer: http://stackoverflow.com/a/51337046
has answer: http://stackoverflow.com/a/51337050
tagged with: multidimensional-array
accepted answer: http://stackoverflow.com/a/51337046
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/89640133
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51331054
has text: Your `CODEA` example doesn't contain regex searches. You are checking for a literal string there.

http://stackoverflow.com/q/51371356
has title: How to improve Precision and Recall on Imbalanced Dataset in Python
tagged with: precision-recall
tagged with: nlp
favorite count: 0
has body: I built a supervised model to classify medical text data (my output predicts the positive or negative occurrence of a disease). The data is very imbalanced (130 positive cases compared to 1600 negative cases, which is understandable since the disease is rare). I first cleaned the data (removed unnecessary words, lemmatization, etc..) and applied POS afterwards. I then applied TfidfVectorizer and TfidfTransformer to this cleaned data. For classification, I tried both SVM and Random Forest, but achieved only 56% precision and 58% recall for the positive data even after tuning their parameters with GridSearchCV (I also made class_weight = 'balanced'). Does anyone have advice as to how to improve this low precision and recall? Thank you very much. Here is my current Pipeline (obviously I only use one of the classifiers when I run it, but I displayed both just to show their parameters). pipeline = Pipeline([ ('vectors', TfidfVectorizer(ngram_range = (2,3),norm = 'l1', token_pattern = r"\w+\b\|\w+" ,min_df = 2, max_features = 1000).fit(data['final'])), ('classifier', RandomForestClassifier(n_estimators = 51, min_samples_split = 8, min_samples_leaf = 2, max_depth = 14, class_weight= 'balanced')), ('classifier', SVC(C = 1000, gamma = 1, class_weight = 'balanced', kernel='linear')), ])
tagged with: machine-learning
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/89715358
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51371428
upvote count: 3
downvote count: 1
type: Question
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/51371428
answer count: 1

http://stackoverflow.com/comment/89671422
score: 0
type: AnswerComment
type: Comment
has text: now it does not generate an error, but it does not do anything!
comment on: http://stackoverflow.com/a/51348871

http://stackoverflow.com/a/51482539
has body: You can using drop_duplicates #df['date'] = pd.to_datetime(df.date) df.sort_values('date').drop_duplicates(['email'],keep='last')
type: Answer
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/51481521
downvote count: 0

http://stackoverflow.com/q/51382183
has comment: http://stackoverflow.com/comment/89736152
tagged with: python
has comment: http://stackoverflow.com/comment/89736348
type: UnansweredQuestion
has title: TypeError: can only concatenate list (not "str") to list - python
downvote count: 5
has answer: http://stackoverflow.com/a/51382271
type: Question
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/89736228
has comment: http://stackoverflow.com/comment/89737463
upvote count: 0
score: -5
answer count: 1
has body: I have some code like this: for x in self.fiturs: a = x[:1] + x[-5] uji.append(a) and the data is: A,1,7,8,7,9 B,1,1,1,2,3 C,2,34,5,1,2 I just want to get index 0 and index 3. So the output I want is like this: A,8 B,1 C,5 How can I do that?
favorite count: 0
has comment: http://stackoverflow.com/comment/89736186

http://stackoverflow.com/a/51402610
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/89950042
has comment: http://stackoverflow.com/comment/89933980
has comment: http://stackoverflow.com/comment/89955536
upvote count: 1
has body: I feel like there should be a better library to work with xml files, but I haven't found one yet. Maybe there's room for improvement there. Anyway, this is a solution I came up with - the idea is to use a recursive function to extract as much detail as possible from every element, and return it to the above layer. import xml.etree.ElementTree as ET xml = ET.parse('p.xml') root = xml.getroot() def getDataRecursive(element): data = list() # get attributes of element, necessary for all elements for key in element.attrib.keys(): data.append(element.tag + '.' + key + ' ' + element.attrib.get(key)) # only end-of-line elements have important text, at least in this example if len(element) == 0: if element.text is not None: data.append(element.tag + ' ' + element.text) # otherwise, go deeper and add to the current tag else: for el in element: within = getDataRecursive(el) for data_point in within: data.append(element.tag + '.' + data_point) return data # print results for x in getDataRecursive(root): print(x)
accepted answer of: http://stackoverflow.com/q/51401826
answers question: http://stackoverflow.com/q/51401826
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51347194
has answer: http://stackoverflow.com/a/51347249
accepted answer: http://stackoverflow.com/a/51348091
has title: Convert White Pixels to Black in OpenCV python
has answer: http://stackoverflow.com/a/51348091
has comment: http://stackoverflow.com/comment/89667272
tagged with: python
tagged with: opencv
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51347249
has comment: http://stackoverflow.com/comment/89667532
type: Question
answer count: 2
downvote count: 2
linked to: http://stackoverflow.com/q/19666626
linked to: http://stackoverflow.com/q/49888538
upvote count: 6
has body: I am trying to convert the white background of the input image into black using python OpenCV.But all the white pixels are not completely getting converted to black. I have attached the input and output images. Input Image : Output Image: I have used the following code for conversion: img[np.where((img==[255,255,255]).all(axis=2))] = [0,0,0]; What should I do?
score: 4
favorite count: 0

http://stackoverflow.com/comment/89858012
has text: Could you explain this ? what is A? img_split = [ np.array_split(A, num, axis = 0) for A in np.array_split(img, num, axis = 1) ]
type: Comment
comment on: http://stackoverflow.com/a/51436995
score: 0
type: AnswerComment

pandas
tags question: http://stackoverflow.com/q/51389626
tags question: http://stackoverflow.com/q/51420917
tags question: http://stackoverflow.com/q/51368801
tags question: http://stackoverflow.com/q/51369145
tags question: http://stackoverflow.com/q/51352901
tags question: http://stackoverflow.com/q/51372631
tags question: http://stackoverflow.com/q/51328832
tags question: http://stackoverflow.com/q/51368187
tags question: http://stackoverflow.com/q/51414331
tags question: http://stackoverflow.com/q/51391201
tags question: http://stackoverflow.com/q/51415919
tags question: http://stackoverflow.com/q/51345286
tags question: http://stackoverflow.com/q/51451951
tags question: http://stackoverflow.com/q/51384210
tags question: http://stackoverflow.com/q/51385880
tags question: http://stackoverflow.com/q/51383400
tags question: http://stackoverflow.com/q/51330439
tags question: http://stackoverflow.com/q/51433017
tags question: http://stackoverflow.com/q/51332485
tags question: http://stackoverflow.com/q/51481884
tags question: http://stackoverflow.com/q/51390323
tags question: http://stackoverflow.com/q/51460881
tags question: http://stackoverflow.com/q/51445631
tags question: http://stackoverflow.com/q/51424336
tags question: http://stackoverflow.com/q/51470574
tags question: http://stackoverflow.com/q/51329934
tags question: http://stackoverflow.com/q/51369750
tags question: http://stackoverflow.com/q/51457100
tags question: http://stackoverflow.com/q/51344512
tags question: http://stackoverflow.com/q/51344739
tags question: http://stackoverflow.com/q/51461365
tags question: http://stackoverflow.com/q/51431263
tags question: http://stackoverflow.com/q/51380372
tags question: http://stackoverflow.com/q/51428084
tags question: http://stackoverflow.com/q/51349283
tags question: http://stackoverflow.com/q/51340686
tags question: http://stackoverflow.com/q/51359418
tags question: http://stackoverflow.com/q/51337357
tags question: http://stackoverflow.com/q/51396272
tags question: http://stackoverflow.com/q/51406341
tags question: http://stackoverflow.com/q/51341532
tags question: http://stackoverflow.com/q/51433415
tags question: http://stackoverflow.com/q/51458991
tags question: http://stackoverflow.com/q/51389086
tags question: http://stackoverflow.com/q/51347800
tags question: http://stackoverflow.com/q/51402714
tags question: http://stackoverflow.com/q/51400612
tags question: http://stackoverflow.com/q/51461337
tags question: http://stackoverflow.com/q/51404436
tags question: http://stackoverflow.com/q/51346710
tags question: http://stackoverflow.com/q/51325227
tags question: http://stackoverflow.com/q/51355691
tags question: http://stackoverflow.com/q/51329392
tags question: http://stackoverflow.com/q/51362588
tags question: http://stackoverflow.com/q/51335475
tags question: http://stackoverflow.com/q/51459150
tags question: http://stackoverflow.com/q/51352699
tags question: http://stackoverflow.com/q/51333050
tags question: http://stackoverflow.com/q/51418309
tags question: http://stackoverflow.com/q/51460112
tags question: http://stackoverflow.com/q/51343638
tags question: http://stackoverflow.com/q/51325385
tags question: http://stackoverflow.com/q/51375616
tags question: http://stackoverflow.com/q/51409861
tags question: http://stackoverflow.com/q/51372800
tags question: http://stackoverflow.com/q/51375678
tags question: http://stackoverflow.com/q/51390464
tags question: http://stackoverflow.com/q/51415275
tags question: http://stackoverflow.com/q/51437045
tags question: http://stackoverflow.com/q/51431327
tags question: http://stackoverflow.com/q/51472231
tags question: http://stackoverflow.com/q/51382250
tags question: http://stackoverflow.com/q/51453326
tags question: http://stackoverflow.com/q/51346030
tags question: http://stackoverflow.com/q/51388549
tags question: http://stackoverflow.com/q/51347115
tags question: http://stackoverflow.com/q/51438083
tags question: http://stackoverflow.com/q/51369226
tags question: http://stackoverflow.com/q/51340848
tags question: http://stackoverflow.com/q/51327767

http://stackoverflow.com/comment/89935874
type: Comment
comment on: http://stackoverflow.com/a/51478866
has text: my problem is that I've got fake dates in the list (e.g. 31/12/9999) giving an error "ValueError: Given date string not likely a datetime."
score: 0
type: AnswerComment

http://stackoverflow.com/a/62410269
score: 1
upvote count: 1
has body: I'm seeing the same thing. I'm afraid that's just the extent to which it works. Speech detection is a difficult task and webrtcvad wants to be light on resources so there's only so much you can do. If you need more accuracy then you would need different packages/methods that will necessarily take more computing power. On aggressiveness, you're right that even on 3 there are still a lot of false positives. I'm also seeing false negatives however so one trick I'm using is running three instances of the detector, one for each aggressiveness setting. Then instead of classifying a frame 0 or 1 I give it the value of the highest aggressiveness that still said it was speech. In other words each sample now has a score of 0 to 3 with 0 meaning even the least strict detector said it wasn't speech and 3 meaning even the strictest setting said it was. I get a little bit more resolution like that and even with the false positives it is good enough for me.
answers question: http://stackoverflow.com/q/51463146
downvote count: 0
type: Answer

http://stackoverflow.com/comment/89795442
comment on: http://stackoverflow.com/q/51408678
score: 0
has text: I see no reason why you'd do this by writing commands to a CMD shell session. These commands (e.g. "ipconfig.exe") should all be run individually, after which for each you would wait and get the return code via `rc = p.wait()`. A return code of 0 means success, and a non-zero value usually indicates a failure, but this depends on the program.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/115274028
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/60354806
score: 1
has text: Even if you do have a setup.py, some features of the requirements file require a newer pip. I had a build that was failing when using `-e path/to/package#egg=package` and a `pip -U install pip` before installing the requirements solved this for me.

http://stackoverflow.com/q/51453681
has comment: http://stackoverflow.com/comment/89877251
tagged with: python
tagged with: plugins
has title: RobotFramework Configuration in Eclipse with Python?
has comment: http://stackoverflow.com/comment/89877218
upvote count: 0
type: UnansweredQuestion
score: -1
has comment: http://stackoverflow.com/comment/89894082
tagged with: eclipse
has answer: http://stackoverflow.com/a/51462524
type: Question
has comment: http://stackoverflow.com/comment/89893668
answer count: 2
has body: Hi All I have python and robotframework installed on my Windows 7, I wanted to configure this into Eclipse IDE. I was trying with External Tools to configure it by giving Pybot.bat file and working directory but I am able to understand the Arguments ${resources_loc} section. Here what value we have to give?? can someone help me out with this or provide alternative to configure it?
tagged with: robotframework
has answer: http://stackoverflow.com/a/51463541
downvote count: 1
tagged with: eclipse-plugin
favorite count: 0

http://stackoverflow.com/q/51382814
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/51383215
has body: I have the following code for my python app that exports data to Excel. There are a few fields that I want the strings_to_numbers option to apply to so that number fields do not export as "Number stored as text", however, I do not want this option to apply to all fields as I do want to preserve some fields as text where there are mixed character values and values with leading zeroes. Is there a way to selectively apply the strings_to_numbers option? nexusexp_file_name = "dataexport.xlsx" workbook = xlsxwriter.Workbook(nexusexp_file_name,{'strings_to_numbers': True}) worksheet1 = workbook.add_worksheet('Sheet1') textformat = workbook.add_format() textformat.set_num_format('0') cur.execute(query) i = 2 for row in cur.fetchall(): worksheet1.write('A' + str(i), row[0],textformat) worksheet1.write('B' + str(i), row[1]) worksheet1.write('C' + str(i), row[2]) worksheet1.write('D' + str(i), row[3]) worksheet1.write('E' + str(i), row[4]) worksheet1.write('F' + str(i), row[5]) worksheet1.write('G' + str(i), row[6]) worksheet1.write('H' + str(i), row[7]) worksheet1.write('I' + str(i), row[8]) worksheet1.write('J' + str(i), row[9],textformat) worksheet1.write('K' + str(i), row[10],textformat) worksheet1.write('L' + str(i), row[11]) i += 1
has title: using xlsxwriter strings_to_numbers option on select fields
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
downvote count: 0
tagged with: xlsxwriter

http://stackoverflow.com/q/51423035
has body: d = {'Consumer Staples': [-0.065], 'Technology': [0.04], 'Financials': [0.06], 'Health Care': [0.07]} df = pd.DataFrame(data = d) I only want to return the names of the columns whose absolute value of Value is greater than 0.05. In this example, it should return Consumer Staples, Financials, And Health Care, but not Technology. How do I do this on Pandas? Thank you!
upvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51423449
downvote count: 5
type: Question
answer count: 1
favorite count: 0
has title: Select columns by their values
has comment: http://stackoverflow.com/comment/89817485
tagged with: pandas
has comment: http://stackoverflow.com/comment/89817636
has answer: http://stackoverflow.com/a/51423449
tagged with: python
has comment: http://stackoverflow.com/comment/89817007
has comment: http://stackoverflow.com/comment/89817582
score: -4

http://stackoverflow.com/comment/89697871
has text: Take a look at jinja2: https://realpython.com/primer-on-jinja-templating/
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51332848

http://stackoverflow.com/a/51444030
answers question: http://stackoverflow.com/q/51434717
type: Answer
score: 2
has body: Run the code: sudo apt-get update And if its not working Try to update repository in software centre.
downvote count: 0
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51434717

http://stackoverflow.com/a/51460190
type: Answer
answers question: http://stackoverflow.com/q/51460113
has body: What you are trying to do is get the first and second element without iterating over an iterator. You need to iterate over it to get values from it like - for i in gen(): c, d = i # you need this because you are returning a tuple You can go through this post to learn more about iterators and generators
score: 0

http://stackoverflow.com/q/51341934
downvote count: 0
favorite count: 0
has body: I have 3 DFs, and I want to find all cells with common directions (i.e. always positive or always negative, across DFs): test=pd.DataFrame([[0,1,0,3], [-1,3,0,2], [2,1.5,-3,1]], columns=['a','b','c','d'] ) test2=pd.DataFrame([[1,1,0,2], [1,-3,0,1], [2,1.5,-2,1]], columns=['a','b','c','d'] ) test3=pd.DataFrame([[1,2,0,2], [1,-2,0,1], [2,1.5,-2,1]], columns=['a','b','c','d'] ) The outcome should be the 3 dataframes, where elements that are not consistent show NAs. For instance, for test1 it would be: test=pd.DataFrame([[NA,1,NA,3], [NA,NA,NA,2], [2,1.5,-3,1]], columns=['a','b','c','d'] ) Note that 0 is not considered (i.e., leads to NA). I can do this cell by cell, but I'm wondering if this is possible to do in the entire dataframes at once? I was trying to do ((test&gt;0)&amp;(test1&gt;0)&amp;(test2&gt;0)) and this works, but I cannot merge this with the negatives. Thanks so much in advance
tagged with: pandas
has answer: http://stackoverflow.com/a/51342263
has answer: http://stackoverflow.com/a/51342033
upvote count: 2
possible better answer: http://stackoverflow.com/a/51342033
tagged with: python
score: 2
type: AnsweredQuestion
has title: Selecting common elements in dataframes Python
accepted answer: http://stackoverflow.com/a/51342263
type: Question
answer count: 2

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

http://stackoverflow.com/q/51430844
upvote count: 4
answer count: 3
has body: I was looking at google, but I could not find an answer. if 5 != 10: print('True') # True if not 5 == 10: print('True') # True Both seem to do the same. When to use "not ==" and when to use "!="?
downvote count: 0
tagged with: operators
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51431164
has title: What is the difference between "not ==" and "!="?
has answer: http://stackoverflow.com/a/51430861
tagged with: python
has comment: http://stackoverflow.com/comment/89832959
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/51430861
possible better answer: http://stackoverflow.com/a/51430927
tagged with: equality
has answer: http://stackoverflow.com/a/51430927
score: 4

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

http://stackoverflow.com/q/51474875
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
tagged with: hyperlink
tagged with: jira
type: Question
answer count: 1
downvote count: 0
favorite count: 0
has body: I want to add a web link into link session. I know to add a issue link with that : issue = jira.issue(issue_source) issue2 = jira.issue(issue_destination) jira.create_issue_link('Duplicate', issue, issue2, None) but I don't know to add web link, I also try, that but I get an error : jira.add_simple_link(args.js, { "object": { "url":"http://www.mycompany.com/support?id=1", "title":"Crazy customer support issue" } }) Thanks
tagged with: web
has answer: http://stackoverflow.com/a/51475729
has title: How I can add web link into jira issue with jira python

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/51476274
tags question: http://stackoverflow.com/q/51325476
tags question: http://stackoverflow.com/q/51392756
tags question: http://stackoverflow.com/q/51365332
tags question: http://stackoverflow.com/q/51399204
tags question: http://stackoverflow.com/q/51327887
tags question: http://stackoverflow.com/q/51403157
tags question: http://stackoverflow.com/q/51344191
tags question: http://stackoverflow.com/q/51409728
tags question: http://stackoverflow.com/q/51355922
tags question: http://stackoverflow.com/q/51381335
tags question: http://stackoverflow.com/q/51479635
tags question: http://stackoverflow.com/q/51352834
tags question: http://stackoverflow.com/q/51461842
tags question: http://stackoverflow.com/q/51341625
tags question: http://stackoverflow.com/q/51444242
tags question: http://stackoverflow.com/q/51326833
tags question: http://stackoverflow.com/q/51452663
tags question: http://stackoverflow.com/q/51414783
tags question: http://stackoverflow.com/q/51373370
type: Tag
tags question: http://stackoverflow.com/q/51395298
tags question: http://stackoverflow.com/q/51352415
tags question: http://stackoverflow.com/q/51368338
tags question: http://stackoverflow.com/q/51389042
tags question: http://stackoverflow.com/q/51418952
tags question: http://stackoverflow.com/q/51470503
tags question: http://stackoverflow.com/q/51380876
tags question: http://stackoverflow.com/q/51423488
tags question: http://stackoverflow.com/q/51367251
tags question: http://stackoverflow.com/q/51467627
tags question: http://stackoverflow.com/q/51411302
tags question: http://stackoverflow.com/q/51367753
tags question: http://stackoverflow.com/q/51384135
tags question: http://stackoverflow.com/q/51459007
tags question: http://stackoverflow.com/q/51351696
tags question: http://stackoverflow.com/q/51472218
tags question: http://stackoverflow.com/q/51390819
tags question: http://stackoverflow.com/q/51330863
tags question: http://stackoverflow.com/q/51347364

linux
tags question: http://stackoverflow.com/q/51329802
tags question: http://stackoverflow.com/q/51396165
tags question: http://stackoverflow.com/q/51350178
tags question: http://stackoverflow.com/q/51404984
tags question: http://stackoverflow.com/q/51353857
tags question: http://stackoverflow.com/q/51329742
tags question: http://stackoverflow.com/q/51331994
tags question: http://stackoverflow.com/q/51470103
tags question: http://stackoverflow.com/q/51445064
type: Tag
tags question: http://stackoverflow.com/q/51348008
tags question: http://stackoverflow.com/q/51405279
tags question: http://stackoverflow.com/q/51434268
tags question: http://stackoverflow.com/q/51372094
tags question: http://stackoverflow.com/q/51371679
tag name: linux
tags question: http://stackoverflow.com/q/51340142
tags question: http://stackoverflow.com/q/51331528
tags question: http://stackoverflow.com/q/51364219
tags question: http://stackoverflow.com/q/51469120
tags question: http://stackoverflow.com/q/51426065
tags question: http://stackoverflow.com/q/51467101
tags question: http://stackoverflow.com/q/51378194
tags question: http://stackoverflow.com/q/51342416
tags question: http://stackoverflow.com/q/51412856
tags question: http://stackoverflow.com/q/51472136
tags question: http://stackoverflow.com/q/51344717
tags question: http://stackoverflow.com/q/51439113
tags question: http://stackoverflow.com/q/51433272
tags question: http://stackoverflow.com/q/51400077
tags question: http://stackoverflow.com/q/51420002
tags question: http://stackoverflow.com/q/51372922
tags question: http://stackoverflow.com/q/51409202

http://stackoverflow.com/comment/89891792
score: 0
type: Comment
type: QuestionComment
has text: @Reblochon Masque, basically i am answering 'if I add or change something in the Building, I need to change every single room initialisation and the init code if additional attributes have been added.', it can be another attribute of the building. I admit I am wrong in location.
comment on: http://stackoverflow.com/q/51461210

http://stackoverflow.com/q/51383418
has answer: http://stackoverflow.com/a/51394891
accepted answer: http://stackoverflow.com/a/51394891
has body: I need to create a copy of a table (if it does not already exist), and this copy needs one of the existing columns to become a primary key. Currently I have the following SQL commands (in a Python script): CREATE TABLE IF NOT EXISTS FilteredTable AS SELECT * FROM RawTable WHERE &lt;cond&gt; ALTER TABLE FilteredTable ADD COLUMN IF NOT EXISTS (NewCol1 TEXT, etc TEXT) ALTER TABLE FilteredTable ADD PRIMARY KEY (ColumnNameFromRaw) This works fine the first time around, but of course when run again after the table already exists it complains that a primary key already exists. Is there a way to combine the ADD PRIMARY KEY with the CREATE TABLE ... command so that it only attempts to set the primary key when the table needs to be created? EDIT Python code can be used. SQL: 10.1.23-MariaDB Python: 2.7
possible better answer: http://stackoverflow.com/a/51385020
has comment: http://stackoverflow.com/comment/89740986
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89739075
has comment: http://stackoverflow.com/comment/89741220
tagged with: mysql
type: Question
has comment: http://stackoverflow.com/comment/89739121
tagged with: python-2.7
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/89738813
has comment: http://stackoverflow.com/comment/89739477
has answer: http://stackoverflow.com/a/51385020
tagged with: mariadb
has comment: http://stackoverflow.com/comment/89739242
has title: Combine CREATE TABLE, ADD COLUMNS, PRIMARY KEY, AS SELECT, and WHERE into one operation

http://stackoverflow.com/comment/89857918
comment on: http://stackoverflow.com/q/51443826
score: 0
type: Comment
type: QuestionComment
has text: well.. I guess it doesn't

http://stackoverflow.com/q/51456613
has title: ValueError: Error when checking target: expected dense_3 to have shape (1,) but got array with shape (5,)
tagged with: python
type: AnsweredQuestion
tagged with: conv-neural-network
has answer: http://stackoverflow.com/a/51456629
score: 1
downvote count: 1
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/51456629
answer count: 1
tagged with: keras
favorite count: 0
upvote count: 2
has body: How to Fix this error? I tried visiting all the forums searching for answers to rectify this issue. There are 5 classes in train_set and test_Set. from keras.models import Sequential from keras.preprocessing.image import ImageDataGenerator from keras.layers import Convolution2D, MaxPooling2D, Flatten, Dense classifier=Sequential() #1st Convolution Layer classifier.add(Convolution2D(32, 3, 3, input_shape=(64,64,3),activation="relu")) #Pooling classifier.add(MaxPooling2D(pool_size = (2, 2))) # Adding a second convolutional layer classifier.add(Convolution2D(32, 3, 3, activation = 'relu')) classifier.add(MaxPooling2D(pool_size = (2, 2))) # Flattening classifier.add(Flatten()) classifier.add(Dense(output_dim = 128, activation = 'relu')) classifier.add(Dense(output_dim = 64, activation = 'relu')) classifier.add(Dense(output_dim = 1, activation = 'softmax')) classifier.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy']) print(classifier.summary()) train_datagen = ImageDataGenerator(rescale = 1./255, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True) test_datagen = ImageDataGenerator(rescale = 1./255) training_set= train_datagen.flow_from_directory('flowers/train_set', target_size=(64,64), batch_size=32, class_mode='categorical') test_set= test_datagen.flow_from_directory('flowers/test_set', target_size=(64,64), batch_size=32, class_mode='categorical') classifier.fit_generator(training_set, samples_per_epoch = 3000, nb_epoch = 25, validation_data = test_set, nb_val_samples=1000) Here i have attached the image of the error for review. error
tagged with: machine-learning

http://stackoverflow.com/comment/89743822
comment on: http://stackoverflow.com/a/51385642
has text: In my opinion, if you're going to `fillna(False)` straight afterwards, you might as well directly assign the Boolean series.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89889542
has text: What does "not getting anywhere" mean?
comment on: http://stackoverflow.com/q/51460055
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89754911
score: 0
comment on: http://stackoverflow.com/q/51391315
has text: your answer is right
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51426026
upvote count: 2
tagged with: python-requests
type: Question
has answer: http://stackoverflow.com/a/51598390
answer count: 1
downvote count: 0
favorite count: 0
has body: I'm trying to upload a PDF as an attachment to a Trello card using python-requests. I've been unable to get the request in the function below to return anything other than 400: Error parsing body despite significant tweaks (detailed below). I should note that I'm able to create cards and add URL attachments to them (neither of which require a file upload) without any problems. Here's the code that handles the POST of the file: def post_pdf(session, design, card_id): attachment = { "name": design["campaign_title"] + " - Combined PDF", "mimeType": "application/pdf" } pdf_post = session.post( url = "https://api.trello.com/1/cards/" + card_id + "/attachments", files = {"file": open("combined_pdf.pdf", "rb")}, data = attachment ) The authentication key and token are set Session params when the session was created, so they're not added here. Also, in the actual code, the POST is handled by a wrapper function that adds some boilerplate error-checking and rate limiting to the request, as well as more-verbose error dumps when a request fails, but I've confirmed (in the above example) that the same error persists without the wrapper. Adjustments I've tried Substituting data = attachment with json = attachment Substituting data = attachment with params = attachment Omitting attachment completely and POSTing the file with no associated data Adding stream = True to the request parameters (this doesn't seem to matter for uploads, but I figured it couldn't hurt to try) Encoding the file as base64 (this encoding has been required elsewhere; I was grasping at straws) Encoding the file as base64, combined with the above tweaks to data / json / params Note: The PDF file is potentially a source of the problem - it's generated by converting several images to PDF format and then concatenating them with pdfunite, so I could well have made mistakes in its creation that are causing Trello to reject the file. What seems to confirm this is that Googling for Trello "Error parsing body" returns…
accepted answer: http://stackoverflow.com/a/51598390
has title: Trello API - 400: "Error parsing body" when POSTing a multipart file attachment
tagged with: python
tagged with: trello
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/89890565
has text: Which version of Python are you using?
comment on: http://stackoverflow.com/a/51460330
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/51325430
tagged with: pandas
has title: how to add add new row for each distinct ID in pandas?
favorite count: 0
upvote count: 2
accepted answer: http://stackoverflow.com/a/51325536
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51325536
tagged with: dataframe
type: Question
downvote count: 0
answer count: 1
has body: I have a datframe like this: import pandas as pd df = pd.DataFrame({'Car_ID': ['B332', 'B332', 'B332', 'C315', 'C315', 'C315', 'C315', 'C315', 'F310', 'F310'], \ 'Date': ['2018-03-15', '2018-03-14', '2018-03-12', '2018-03-15', '2018-03-14', '2018-03-13', \ '2018-03-12', '2018-03-11', '2018-03-10', '2018-03-09'], \ 'Driver': ['Alex', 'Alex', 'Alex', 'Sara', 'Sara', 'Sara', 'Sara', 'Sara', 'Franck','Franck'], \ 'Info': ["Group_B", "Group_B", "Group_B", "Group_C", "Group_C", "Group_C", "Group_C", "Group_C", "Group_F", "Group_F"]}) df Car_ID Date Driver Info 0 B332 2018-03-15 Alex Group_B 1 B332 2018-03-14 Alex Group_B 2 B332 2018-03-12 Alex Group_B 3 C315 2018-03-15 Sara Group_C 4 C315 2018-03-14 Sara Group_C 5 C315 2018-03-13 Sara Group_C 6 C315 2018-03-12 Sara Group_C 7 C315 2018-03-11 Sara Group_C 8 F310 2018-03-10 Franck Group_F 9 F310 2018-03-09 Franck Group_F I want to add new row before each distinct Car_ID like this: Car_ID Date Driver Info 0 B332 2018-03-15 Alex Group_B 1 B332 2018-03-14 Alex Group_B 2 B332 2018-03-12 Alex Group_B 3 B332 2018-03-12 Alex Changed 4 C315 2018-03-15 Sara Group_C 5 C315 2018-03-14 Sara Group_C 6 C315 2018-03-13 Sara Group_C 7 C315 2018-03-12 Sara Group_C 8 C315 2018-03-11 Sara Group_C 9 C315 2018-03-11 Sara Changed 10 F310 2018-03-10 Franck Group_F 11 F310 2018-03-09 Franck Group_F 12 F310 2018-03-09 Franck Changed How could I do this job by shift()? Thanks

pyqt
type: Tag
tags question: http://stackoverflow.com/q/51428377
tags question: http://stackoverflow.com/q/51343544
tags question: http://stackoverflow.com/q/51332260
tags question: http://stackoverflow.com/q/51458754
tags question: http://stackoverflow.com/q/51459982
tags question: http://stackoverflow.com/q/51392167
tags question: http://stackoverflow.com/q/51344147
tags question: http://stackoverflow.com/q/51425354
tags question: http://stackoverflow.com/q/51364552
tags question: http://stackoverflow.com/q/51357642
tags question: http://stackoverflow.com/q/51335167
tags question: http://stackoverflow.com/q/51338580
tags question: http://stackoverflow.com/q/51472956
tags question: http://stackoverflow.com/q/51382376
tags question: http://stackoverflow.com/q/51369081
tags question: http://stackoverflow.com/q/51442487
tags question: http://stackoverflow.com/q/51459331
tags question: http://stackoverflow.com/q/51335526
tags question: http://stackoverflow.com/q/51343109
tags question: http://stackoverflow.com/q/51363762
tags question: http://stackoverflow.com/q/51359162
tags question: http://stackoverflow.com/q/51465953
tags question: http://stackoverflow.com/q/51341158
tags question: http://stackoverflow.com/q/51443461
tags question: http://stackoverflow.com/q/51464962
tags question: http://stackoverflow.com/q/51336612
tags question: http://stackoverflow.com/q/51433403
tags question: http://stackoverflow.com/q/51442769
tags question: http://stackoverflow.com/q/51330113
tags question: http://stackoverflow.com/q/51433523
tags question: http://stackoverflow.com/q/51443198
tags question: http://stackoverflow.com/q/51420099
tags question: http://stackoverflow.com/q/51328745
tags question: http://stackoverflow.com/q/51361674
tags question: http://stackoverflow.com/q/51469559
tags question: http://stackoverflow.com/q/51464209
tags question: http://stackoverflow.com/q/51413254
tags question: http://stackoverflow.com/q/51442896
tags question: http://stackoverflow.com/q/51333771
tags question: http://stackoverflow.com/q/51388443
tags question: http://stackoverflow.com/q/51405824
tags question: http://stackoverflow.com/q/51389423
tag name: pyqt
tags question: http://stackoverflow.com/q/51329489
tags question: http://stackoverflow.com/q/51334861
tags question: http://stackoverflow.com/q/51371122
tags question: http://stackoverflow.com/q/51396555
tags question: http://stackoverflow.com/q/51475306
tags question: http://stackoverflow.com/q/51338059

http://stackoverflow.com/q/51462596
has answer: http://stackoverflow.com/a/51462614
type: UnansweredQuestion
score: -3
upvote count: 0
has title: The dot in module import (python 3.x)
has comment: http://stackoverflow.com/comment/89894193
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: python
has body: For what i can use the "." in import module. I meet it in sklearn library. It looks like: from .externals import six
linked to: http://stackoverflow.com/q/7279810
linked to: http://stackoverflow.com/q/48304317
downvote count: 3
duplicate of: http://stackoverflow.com/q/7279810
answer count: 1

http://stackoverflow.com/comment/89709922
type: Comment
score: 2
has text: this worked well. I'm kinda surprised there isn't a more straight forward way to do this (coming from working with excel a lot). Regardless, thanks so much for the help!
type: AnswerComment
comment on: http://stackoverflow.com/a/51364430

http://stackoverflow.com/a/51441281
type: Answer
score: 1
upvote count: 1
has body: Since you opened your file in binary format, mode='rb', I think you probably just need to specify a bytes-like character to strip: newLine = line.strip(b'|').split()
answers question: http://stackoverflow.com/q/51441167
downvote count: 0

django-rest-framework
tags question: http://stackoverflow.com/q/51432860
tags question: http://stackoverflow.com/q/51348982
tags question: http://stackoverflow.com/q/51351696
tags question: http://stackoverflow.com/q/51433569
tags question: http://stackoverflow.com/q/51459180
tags question: http://stackoverflow.com/q/51359259
tags question: http://stackoverflow.com/q/51426968
tags question: http://stackoverflow.com/q/51412849
tags question: http://stackoverflow.com/q/51434005
tags question: http://stackoverflow.com/q/51412219
tags question: http://stackoverflow.com/q/51430094
tags question: http://stackoverflow.com/q/51356728
tags question: http://stackoverflow.com/q/51462779
type: Tag
tags question: http://stackoverflow.com/q/51360970
tags question: http://stackoverflow.com/q/51371219
tags question: http://stackoverflow.com/q/51387421
tags question: http://stackoverflow.com/q/51366456
tags question: http://stackoverflow.com/q/51325893
tags question: http://stackoverflow.com/q/51326833
tags question: http://stackoverflow.com/q/51343394
tags question: http://stackoverflow.com/q/51424773
tags question: http://stackoverflow.com/q/51437271
tags question: http://stackoverflow.com/q/51372303
tag name: django-rest-framework
tags question: http://stackoverflow.com/q/51463507
tags question: http://stackoverflow.com/q/51348467
tags question: http://stackoverflow.com/q/51411892
tags question: http://stackoverflow.com/q/51396045
tags question: http://stackoverflow.com/q/51441532
tags question: http://stackoverflow.com/q/51332141
tags question: http://stackoverflow.com/q/51345385
tags question: http://stackoverflow.com/q/51363232
tags question: http://stackoverflow.com/q/51460557
tags question: http://stackoverflow.com/q/51407382
tags question: http://stackoverflow.com/q/51359439
tags question: http://stackoverflow.com/q/51401675

http://stackoverflow.com/comment/89785214
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51403226
has text: Depends... you need to change the checkbox based in someone from your Django? or you just need some url based in some logic in frontend?

http://stackoverflow.com/q/51381534
has comment: http://stackoverflow.com/comment/89735025
downvote count: 0
has title: Python - insert into list horizontally in table
has comment: http://stackoverflow.com/comment/89735275
favorite count: 0
answer count: 3
has answer: http://stackoverflow.com/a/51382058
tagged with: python
has answer: http://stackoverflow.com/a/51381795
type: AnsweredQuestion
tagged with: list
tagged with: stack
has comment: http://stackoverflow.com/comment/89734959
has comment: http://stackoverflow.com/comment/89735442
upvote count: 1
has comment: http://stackoverflow.com/comment/89734907
type: Question
possible better answer: http://stackoverflow.com/a/51381962
has comment: http://stackoverflow.com/comment/89734932
has answer: http://stackoverflow.com/a/51381962
score: 1
has comment: http://stackoverflow.com/comment/89734894
has comment: http://stackoverflow.com/comment/89735142
accepted answer: http://stackoverflow.com/a/51381795
has body: i'm not particularly sure how to explain this, but this is the output I am currently getting: 0x0 PUSH1 80 ['80'] 0x2 PUSH1 40 ['40'] 0x4 MSTORE [] 0x8 PUSH2 0010 ['0010'] for each time a PUSH item occurs, I would like to insert the last item into the list horizontally so I get this representation of the stack: 0x0 PUSH1 80 ['80'] 0x2 PUSH1 40 ['40', '80'] 0x4 MSTORE 0x8 PUSH2 0010 ['0010', '40', '80'] this is my current code: for (addr, op, params), y in zip(self.instructions, self.stack[::-1]): codes = [] for x in range(0, 33): if op == 'PUSH' + str(x): codes.append(params) print addr + "\t" + op + "\t\t" + params + "\t" + str(codes) I'm sorry if this is unclear, been stuck on this for hours, thank you for the help!

http://stackoverflow.com/a/68637624
downvote count: 0
answers question: http://stackoverflow.com/q/51405048
upvote count: 2
type: Answer
score: 2
has body: This should work driver = webdriver.Chrome(chromeDriver, options=options) params = {'behavior' : 'allow', 'downloadPath':r"C:\Users\downloads"} driver.execute_cdp_cmd('Page.setDownloadBehavior', params)

http://stackoverflow.com/q/51337718
favorite count: 0
tagged with: python-3.x
has body: When I add an item to my list, it gets removed next time I add another item. food_choice = str(input("Do you want to add an item, remove an item or search for a recipes? ")) food = [] if food_choice in ["Add", "add"]: food_to_add = str(input("Which item would you like to add? ")) food.append(food_to_add) print(food_to_add, "has been addded to your fridge list.") print(food)
tagged with: python
has title: Why does my list.append not permanently add my item?
tagged with: list
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51337876
accepted answer: http://stackoverflow.com/a/51337876
type: Question
upvote count: 2
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/89718110
comment on: http://stackoverflow.com/q/51347381
has text: Thanks. It helped.
score: 0
type: Comment
type: QuestionComment

algorithm
tags question: http://stackoverflow.com/q/51463529
tags question: http://stackoverflow.com/q/51481021
tag name: algorithm
tags question: http://stackoverflow.com/q/51392673
tags question: http://stackoverflow.com/q/51329426
tags question: http://stackoverflow.com/q/51480779
tags question: http://stackoverflow.com/q/51389795
tags question: http://stackoverflow.com/q/51395627
tags question: http://stackoverflow.com/q/51353893
tags question: http://stackoverflow.com/q/51394973
tags question: http://stackoverflow.com/q/51343689
tags question: http://stackoverflow.com/q/51373571
tags question: http://stackoverflow.com/q/51403553
tags question: http://stackoverflow.com/q/51445446
tags question: http://stackoverflow.com/q/51328575
tags question: http://stackoverflow.com/q/51462548
tags question: http://stackoverflow.com/q/51411878
type: Tag
tags question: http://stackoverflow.com/q/51429844
tags question: http://stackoverflow.com/q/51459160
tags question: http://stackoverflow.com/q/51390354
tags question: http://stackoverflow.com/q/51371365
tags question: http://stackoverflow.com/q/51363584
tags question: http://stackoverflow.com/q/51380580
tags question: http://stackoverflow.com/q/51335422
tags question: http://stackoverflow.com/q/51456472
tags question: http://stackoverflow.com/q/51426623
tags question: http://stackoverflow.com/q/51456060
tags question: http://stackoverflow.com/q/51395853
tags question: http://stackoverflow.com/q/51330651
tags question: http://stackoverflow.com/q/51394631
tags question: http://stackoverflow.com/q/51340316
tags question: http://stackoverflow.com/q/51478951
tags question: http://stackoverflow.com/q/51379058
tags question: http://stackoverflow.com/q/51448343

http://stackoverflow.com/comment/89710852
comment on: http://stackoverflow.com/q/51369226
has text: Can you show me what your graph should look like. What does "The data is grouped and colored by index" two indexes, info and more info.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89791491
type: QuestionComment
comment on: http://stackoverflow.com/q/51406583
score: 0
has text: I'm loading a dataframe, and am working on one column ( rows are strings)
type: Comment

http://stackoverflow.com/comment/90046818
comment on: http://stackoverflow.com/q/51460923
score: 0
type: Comment
type: QuestionComment
has text: For a timeout: `import time` and the line will be : `time.sleep(A)`. A = number of seconds you want to do a timeout.

http://stackoverflow.com/comment/89734411
has text: @user10092387 For demonstration purposes.
type: AnswerComment
comment on: http://stackoverflow.com/a/51381093
score: 0
type: Comment

http://stackoverflow.com/comment/89716208
comment on: http://stackoverflow.com/q/51371902
type: QuestionComment
has text: Yes, the sparse `hstack` wants a list, just like the `np.hstack`. It'll be worth your while to look at its code (and at `bmat`).
type: Comment
score: 1

http://stackoverflow.com/q/51375145
has comment: http://stackoverflow.com/comment/89721979
type: Question
has comment: http://stackoverflow.com/comment/89722388
has body: I'm writing a parser wherein one of the default values for an optional argument can be readily computed from one of the positional arguments, and one might occassionally want to use a different value. Is it possible to defer the computation of the default value with argparse?
has title: Argparse: compute default from positional argument
has comment: http://stackoverflow.com/comment/89724336
score: 0
has comment: http://stackoverflow.com/comment/89731340
tagged with: argparse
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89724334
tagged with: python
has comment: http://stackoverflow.com/comment/89725335

http://stackoverflow.com/comment/90008666
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51418240
has text: It was happening because of the offset,I set some offset while clicking on the div and it worked
score: 0

http://stackoverflow.com/comment/89717125
has text: Whats the logic ?
comment on: http://stackoverflow.com/q/51372651
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51454964
type: Question
answer count: 2
has body: I am building a simple website with Flask, where the user login form is available in the upper right corner, no matter on which url the user currently is (html form is defined in my base.html template, which is extended by all other templates). So one of the choices to make it work, is to handle the login form in each @app.route() method, but it adds a lot of redundant code, it looks ugly, and I'm looking for a way to simplify it. So my question is: Is it possible to create one method that will handle the login form for each endpoint in my application? Here is some code of my login form: @app.route('/', methods=['GET', 'POST']) def login(): if current_user.is_authenticated: return redirect(url_for('home')) form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user is None or not user.check_password(form.password.data): flash('Invalid username or password') return redirect(url_for('login')) login_user(user, remember=True) return redirect(url_for('home')) return render_template('index.html', form=form) And here is the screenshot of the rendered form itself: https://i.sstatic.net/PXNSB.png EDIT: So far I came up only with this, but is there any better solution? (The endpoint argument is to redirect the user back to the page where he logged from) # method used in each URL for login purpose def login_function(form, endpoint): user = User.query.filter_by(username=form.username.data).first() if user is None or not user.check_password(form.password.data): flash('Invalid username or password') return redirect(url_for(endpoint)) login_user(user, remember=True) return redirect(url_for(endpoint)) And that method is accessed in each URL like this: login_form = LoginForm() if login_form.validate_on_submit(): return login_function(login_form, 'home')
tagged with: web
tagged with: flask
favorite count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/51457670
tagged with: python
has title: Flask, Jinja2 and WTForms - one method for all URLs?
downvote count: 0
tagged with: flask-wtforms
has answer: http://stackoverflow.com/a/51457518
has answer: http://stackoverflow.com/a/51457670
tagged with: jinja2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51457518
score: 1

http://stackoverflow.com/q/51407230
tagged with: aws-fargate
type: Question
answer count: 2
has body: I'm trying to download all private repos in my organisation. I have a script that I want to run once a day using Fargate. The problem I'm experiencing when running it is below: Warning: Permanently added the RSA host key for IP address '192.30.253.113' to the list of known hosts. Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. I understand the error and in my dockerfile I add an ssh key to the image: FROM python:3.6 RUN mkdir /backup WORKDIR /backup ADD . /backup/ RUN mkdir /root/.ssh/ ADD id_rsa /root/.ssh/id_rsa RUN chmod 400 /root/.ssh/id_rsa RUN python3 -m pip install -r requirements.txt This is the script where I try to download all repos and upload them to S3 bucket: TOKEN = os.environ['TOKEN'] DATE = str(date.today()) def archive(zipname, directory): return shutil.make_archive(zipname, 'zip', root_dir=directory, base_dir=None) def assume_role(role_to_assume, duration=900): sts_client = boto3.client('sts') assumed_role = sts_client.assume_role( RoleArn=role_to_assume, RoleSessionName='session', DurationSeconds=duration ) credentials = assumed_role['Credentials'] return (credentials['AccessKeyId'], credentials['SecretAccessKey'], credentials['SessionToken']) def upload_to_s3(key, file_name, access_role): access_key, secret_key, session_token = assume_role(access_role) s3 = boto3.resource( 's3', aws_access_key_id=access_key, aws_secret_access_key=secret_key, aws_session_token=session_token ) s3.Bucket('zego-github-backup').put_object( Key=key, Body=file_name ) print('Uploaded') def login_github(): g = Github(TOKEN) org = g.get_organization("Organisation").get_repos() role = "arn:aws:iam::7893729191287:role/Github_backup" for repo in org: repo_name = repo.name key = f"{repo_name} {DATE}.zip" ssh_url = repo.ssh_url os.system(f"GIT_SSH_COMMAND=\"ssh -o StrictHostKeyChecking=no\" git clone --depth 1 {ssh_url}") archive(f"{repo_name} {DATE}", repo_name) archive…
has title: Git clone private repo in AWS ECS
has comment: http://stackoverflow.com/comment/89788302
tagged with: amazon-web-services
has answer: http://stackoverflow.com/a/51409227
tagged with: docker
score: 0
has answer: http://stackoverflow.com/a/73266309
type: UnansweredQuestion
tagged with: python
tagged with: git

http://stackoverflow.com/q/51446944
has answer: http://stackoverflow.com/a/51447859
has answer: http://stackoverflow.com/a/51448404
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51447893
type: Question
upvote count: 4
has title: Python - How to exclude Sat. and Sun. from weeks
has body: I was hoping that someone could give me some examples of ways in which I can return calendar data that does the following. Returns the number of days in any given month (past/present/future), but after excluding Saturdays and Sundays. Example: input('Year: ') — 2018 input('Month: ') — 7 End Result: The number of weekdays in (July) of (2018) is (22). Assign an iterator to each weekday after excluding Sat. and Sun. Example: input('Year: ') — 2018 input('Month: ') — 7 input('date: ') — 20 End Result: The (20) is a (Friday) and is the (15) weekday of (July), (2018). This is the code that I've been able to create so far... import calendar year = float(input('Year: ')) month = float(input('Month: ')) input_year = [] input_month = [] if year &gt;= 1000 and year &lt;=3000: input_year.append(year) if month &gt;= 1 and month &lt;=12: input_month.append(month) cal_format = calendar.TextCalendar(calendar.MONDAY) result_cal = cal_format.formatmonth(int(input_year[0]), int(input_month[0])) print(result_cal) THE END RESULT IS... Year: 1978 Month: 3 March 1978 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 This only prints out a Text Calendar with Sat. and Sun at the end of each week, so I can at least visually exclude them. But I would really like to be able to programmatically exclude them and be able to input the above variables to calculate weekdays in a month, and which weekday each day is within that month.
downvote count: 0
accepted answer: http://stackoverflow.com/a/51447859
score: 4
tagged with: python
has answer: http://stackoverflow.com/a/51451802
answer count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/51447893
tagged with: calendar

http://stackoverflow.com/comment/89651481
has text: Ah ok! Should it just return the data or do something else?
comment on: http://stackoverflow.com/q/51330948
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51481397
tagged with: matplotlib
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89934669
linked to: http://stackoverflow.com/q/50826119
type: UnansweredQuestion
tagged with: python
score: 1
tagged with: astronomy
upvote count: 1
has title: How to plot a background image in Mollweide view (Python)?
tagged with: plot
has answer: http://stackoverflow.com/a/51496155
type: Question
has body: I am doing astronomical data analysis, using Sky Coordinates. How do I place an image as the background of a Mollweide view plot? What I've tried is to do the graph normally and add: imag = mpimg.imread('gamma_ray_Fermi.png') plt.imshow(imag) But it just returns a deformed graph, instead of the usual plot with background.

http://stackoverflow.com/q/51424523
type: Question
has body: GOAL : Detect people in real time with minimal delay/latency from given remote video stream. Setup : Raspberry Pi (2) w/ usb web camera serving up images/video stream using Flask. Local machine ( macbook pro ) obtains video stream, processes images through OpenCV, Darknet/DarkFlow/Yolo, and Tensorflow. Display obtained processed stream with detected people. Detected people will have a rectangle around them. Python 3 I currently have the base functionality working, BUT, it seems to be rather slow. A image is processed about every few seconds, when I need it to be processed in less than a second. So the result is a video that shows updates way behind the stream and is choppy. From searching around, this seems to be a common problem but I have not seemed to find a straight forward answer. I have implemented the stream grab as its own thread as some forums have said, but I believe the issue now to be just the time it takes to process that grabbed image. Is it possible to improve performance? Do I need to do this processing in the cloud on a system supplying a good GPU so I can take advantage of that performance increase? Am I using the wrong yolo weights and cfg? I know yolov3 is out, but I think I had issues getting to work with my env. incoming_frames = queue.Queue() class Stream(threading.Thread): def __init__(self, ID): threading.Thread.__init__(self) self.cam=cv2.VideoCapture('http://raspberrypi.local:5000/') def run(self): frame_id = 0 while True: ret,frame=self.cam.read() if ret: frame_id = frame_id + 1 frame_dict = {} frame_dict['frame'] = frame frame_dict['id'] = frame_id incoming_frames.put(frame_dict) print("ACQUIRED FRAME " + str(frame_id)) time.sleep(0.1) def stop(self): self._stop_event.set() print("[INFO] Starting Process......") print("[INFO] Load Model / Weights") options = {"model": "cfg/yolo.cfg", "load": "bin/yolo.weights", "threshold": 0.1} tfnet = TFNet(options) print("[INFO] Start Video Grab Thread") stream = Stream(0) stream.start() while True: i…
downvote count: 0
has title: Issues performing person detection nearing real time from video stream
favorite count: 0
tagged with: yolo
type: UnansweredQuestion
tagged with: darknet
tagged with: darkflow
tagged with: python
tagged with: opencv
answer count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/89848460
type: QuestionComment
has text: Yes, I execute them in the same way.
comment on: http://stackoverflow.com/q/51439113
score: 0
type: Comment

http://stackoverflow.com/q/51422146
type: AnsweredQuestion
has title: How to Install the latest version of seaborn
accepted answer: http://stackoverflow.com/a/51422773
type: Question
upvote count: 15
has answer: http://stackoverflow.com/a/68958618
has answer: http://stackoverflow.com/a/56740223
possible better answer: http://stackoverflow.com/a/51765071
score: 15
has answer: http://stackoverflow.com/a/51765071
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51422773
answer count: 5
tagged with: seaborn
tagged with: python
has body: I want to create a catplot using seaborn package and I know that in order to be able to do that I need the latest version of seaborn(0.9.0). I installed the package for conda using: conda install seaborn but it downloaded version 0.8.1. I therefore installed the version that I want using pip: pip3 install seaborn==0.9.0 but I keep getting the same error whenever I run my code: AttributeError: module 'seaborn' has no attribute 'catplot' (attribute that is only available in the latest version). Can anyone please assist with this?
has answer: http://stackoverflow.com/a/51422396

http://stackoverflow.com/q/51404476
favorite count: 0
has comment: http://stackoverflow.com/comment/138872482
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/4789837
has title: How to use asyncio to continously read from a process and kill it after a timeout
type: Question
upvote count: 2
answer count: 1
downvote count: 0
has body: I'd like to use asyncio to continuously read from a process until I stop it some time later. I've tried tons of things but can't figure out how to do it. Here's one attempt that just doesn't seem to care about the kill at all import io import asyncio class Foo(): async def run(self): proc = await asyncio.create_subprocess_shell('ping www.google.de', stdout=asyncio.subprocess.PIPE) await asyncio.gather(self.run_proc(proc), self.kill_proc(proc)) async def run_proc(self, proc): while True: await asyncio.sleep(0) line = await proc.stdout.readline() print(line) async def kill_proc(self, proc): await asyncio.sleep(1000) print("meh") proc.kill() f = Foo() loop = asyncio.get_event_loop() loop.run_until_complete(f.run()) UPDATE: Here's the working code incorporating the feedback from user4815162342 import io import asyncio class Foo(): async def run(self): proc = await asyncio.create_subprocess_exec('ping', 'www.google.de', stdout=asyncio.subprocess.PIPE) await asyncio.gather(self.run_proc(proc), self.kill_proc(proc)) async def run_proc(self, proc): while True: line = await proc.stdout.readline() if line == b'': break print(line) async def kill_proc(self, proc): await asyncio.sleep(1) print("meh") proc.kill() f = Foo() loop = asyncio.get_event_loop() loop.run_until_complete(f.run())
has answer: http://stackoverflow.com/a/51404816
accepted answer: http://stackoverflow.com/a/51404816
has comment: http://stackoverflow.com/comment/119113740
tagged with: python-asyncio
tagged with: python
linked to: http://stackoverflow.com/q/1230669

http://stackoverflow.com/comment/89681047
has text: @Blckknight. Thanks for your help. Is there any way we can track (or print) the two wrappers? I tried debugging the code, and I couldn't understand these doubly wrapped decorators. Thanks in advance.
comment on: http://stackoverflow.com/a/51352465
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51463643
has comment: http://stackoverflow.com/comment/89896212
score: 7
has title: Pandas cast all levels of a multi-index to another type
possible better answer: http://stackoverflow.com/a/73128216
type: Question
answer count: 2
has body: I have a multi-index and I would like to convert all of its levels to float. I'm doing the following: my_dataframe.index.map(lambda i: (float(i[0]), float(i[1]))) However this does not seem to "scale" very well if I have many levels. I tried this: my_dataframe.index.astype(np.float, copy=False) but it fails with a TypeError: TypeError: Setting &lt;class 'pandas.core.indexes.multi.MultiIndex'&gt; dtype to anything other than object is not supported What would be the best/easiest way to achieve this?
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/73128216
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51463725
accepted answer: http://stackoverflow.com/a/51463725
tagged with: python
upvote count: 7
type: AnsweredQuestion

http://stackoverflow.com/comment/89830556
comment on: http://stackoverflow.com/a/51403566
score: 0
type: AnswerComment
has text: this works just the way i was looking for...you r brilliant ..Thanks a lot
type: Comment

http://stackoverflow.com/comment/89864148
type: QuestionComment
has text: Please check your spelling ;-)
type: Comment
comment on: http://stackoverflow.com/q/51446989
score: 1

http://stackoverflow.com/comment/89711991
score: 0
type: AnswerComment
has text: Yes this approach works, however the line `df.apply(_drop)` creates a new dataframe. The original `df` remains with -1 as in my question. That might be the reason why the id is different.
comment on: http://stackoverflow.com/a/51362568
type: Comment

http://stackoverflow.com/a/51409646
score: 0
type: Answer
has body: ... #strings True except "" print(bool("Hello World")) print(bool(" ")) # missing parenthesis in this line -&gt; print(bool("") print(bool("")) #print(int(True)) #print(2 + True)
answers question: http://stackoverflow.com/q/51409601

http://stackoverflow.com/a/51476906
score: 1
has body: You could use python's replace function with count for number of replaces like - str.replace("_", ":", 2) #where 2 is the number of instances of "_" # you want to replace in a string Ex - x = "HARPS.2010-10-19T02_24_55.819_e2ds_A.fits" x = x.replace("_", ":", 2) print(x) # prints HARPS.2010-10-19T02:24:55.819_e2ds_A.fits
has comment: http://stackoverflow.com/comment/89922243
upvote count: 1
answers question: http://stackoverflow.com/q/51476763
type: Answer
downvote count: 0

http://stackoverflow.com/a/51410457
upvote count: 1
has comment: http://stackoverflow.com/comment/89793332
answers question: http://stackoverflow.com/q/51410155
downvote count: 0
type: Answer
has body: You can use numpy.repeat to make the workaround more efficient: import numpy as np dataToLearn = np.array([1,2,3,4,5]) weights = np.array([1,2,1,1,3]) print(np.repeat(dataToLearn, weights)) # Output: array([1, 2, 2, 3, 4, 5, 5, 5]) Very basic performance test of numpy.repeat performance: import timeit code_before = """ weights = np.array([1,2,1,1,3] * 1000) dataToLearn = np.array([1,2,3,4,5] * 1000) dataToLearn2 = [] for i, d in enumerate(dataToLearn): dataToLearn2 += int(weights[i]) * [d] """ code_after = """ weights = np.array([1,2,1,1,3] * 1000) dataToLearn = np.array([1,2,3,4,5] * 1000) np.repeat(dataToLearn, weights) """ print(timeit.timeit(code_before, setup="import numpy as np", number=1000)) print(timeit.timeit(code_after, setup="import numpy as np", number=1000)) As a result, I've got roughly 3.38 for your current approach vs 0.75 for numpy.repeat
score: 1

http://stackoverflow.com/comment/89897575
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51418976
has text: This has nothing to do with Python. The capitalized words refer to *environment settings*. Look up how to verify and, optionally change, them for your OS.

http://stackoverflow.com/q/51446217
tagged with: curve-fitting
has comment: http://stackoverflow.com/comment/89889559
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: I am looking for simple and easy examples or template scripts of Recurrent Neural Networks (RNN) with Tensorflow, applicabel to my problem. I am trying to fit a curve trough noisy data x, with the additional challenge that the data has a gap (see figure below) - in that sense I am trying to predict x inside and outside the gap. More about my problem and data: Beside x, I also have as data the time and 2 other features, which are partially influencing the behavior of x. So, I have as potential input 690 data vectors, each vector with a length of 4 features (time, x and 2 other features). For time=[340,580] there is only a gap in x, but not in the 2 other features. Have you encountered some simple codes that I can easily modify for my problem? Have you done some ML/AI-networks tutorials, that were using code applicable to my problem?
score: 1
has answer: http://stackoverflow.com/a/51469761
tagged with: recurrent-neural-network
has title: Tensorflow RNN simple and easy examples/ templates for fitting curves?
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/89898682
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/89643543
score: 3
comment on: http://stackoverflow.com/q/51334092
type: Comment
type: QuestionComment
has text: You indeed cannot pass the file object. Even if you could it wouldn't be valid anywhere else. Either pass the file name and open it remotely, or pass the file data around by reading the file first.

http://stackoverflow.com/comment/89894975
has text: your `generate_list([1,2,3])` gives `[[3], [2, 3], [1, 2, 3]]`. the OP wanted `[[3], [3, 2], [1, 2, 3]]`
type: Comment
comment on: http://stackoverflow.com/a/51462973
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89740371
comment on: http://stackoverflow.com/a/51383947
has text: Thanks wen so much.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51372651
has comment: http://stackoverflow.com/comment/89717105
downvote count: 5
has comment: http://stackoverflow.com/comment/89717125
has body: Here in Python, I have a list like this: array = [[[0,0,1,0],[0,0,0,1],[1,0,0,0],[0,1,0,0]], [[0,1,0],[1,0,0],[0,0,1],[0,0,1]], [[0],[1],[0],[1]], [[1],[1],[0],[1]]] I want to reshape it into: array = [[[0,0,1,0],[0,1,0],[0],[1]], [[0,0,0,0],[1,0,0],[1],[1]], [[1,0,0,0],[0,0,1],[0],[0]], [[0,1,0,0],[0,0,1],[0],[1]]] Any suggestions?
tagged with: numpy
upvote count: 0
has answer: http://stackoverflow.com/a/51372689
tagged with: arrays
answer count: 1
has comment: http://stackoverflow.com/comment/89717211
favorite count: 0
linked to: http://stackoverflow.com/q/19339
has comment: http://stackoverflow.com/comment/89717150
tagged with: python
has comment: http://stackoverflow.com/comment/89717106
has comment: http://stackoverflow.com/comment/89717118
has title: Reshaping a weird list in python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89717165
tagged with: list
score: -5
duplicate of: http://stackoverflow.com/q/19339
accepted answer: http://stackoverflow.com/a/51372689
type: Question
has comment: http://stackoverflow.com/comment/89717114
has comment: http://stackoverflow.com/comment/89717187

http://stackoverflow.com/a/67930700
has body: OK an engineered solution finally, with which you can still intentionally leak selected variables. from scoping import scoping a = 2 with scoping(): assert(2 == a) a = 3 b = 4 scoping.keep('b') assert(3 == a) assert(2 == a) assert(4 == b) https://github.com/l74d/scoping
answers question: http://stackoverflow.com/q/51359018
upvote count: 1
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/a/68965740
score: 2
upvote count: 2
has body: You can use the thread, datetime and time. import threading import telebot import time import datetime def message_timer(): while 1: if str (datetime.datetime.now().strftime("% H")) == "7": bot.send_message(user_id, "Message") # 60*65 because it doesn't send the message continuously but only does it once time.sleep(60*65) # Do some stuff ... x = threading.Thread(target=message_timer) x.start() # Do some stuff ...
answers question: http://stackoverflow.com/q/51394011
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51394011
type: Answer

http://stackoverflow.com/q/51364273
tagged with: python
answer count: 1
tagged with: pytorch
tagged with: recurrent-neural-network
accepted answer: http://stackoverflow.com/a/51364384
has title: Pixel RNN Pytorch Implementation
downvote count: 0
has body: I am trying to implement Pixel RNN in pytorch, but I cannot seem to find any documentation on this. The main parts of Pixel RNN are Row LSTM and BiDiagonal LSTM, so I am looking for some code of these algorithms to better understand what they are doing. Specifically, I am confused as to these algorithms calculate one row and diagonal at once, respectively. Any help would be much appreciated.
tagged with: lstm
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/108552650
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51364384
type: Question
tagged with: machine-learning
upvote count: 1

http://stackoverflow.com/q/51423255
has title: Sublist values to two different variables?
downvote count: 2
tagged with: python-requests
linked to: http://stackoverflow.com/q/19300174
accepted answer: http://stackoverflow.com/a/51423297
has comment: http://stackoverflow.com/comment/89817364
type: AnsweredQuestion
type: Question
has body: I'm trying to assign two values of a list to two different variables. Here is the json list. Its raising key error. Please let me know where I am wrong. [{'min': 1.158, 'max': 1.150, 'id': 269097, 'to': 1532003820, 'from': 1532003760, 'check': 1.15852, 'no_check': 1.15822, 'volume': 0},{'min': 1.1, 'max': 1.17, 'id': 269098, 'to': 1532003880, 'from': 1532003820, 'check': 1.158615, 'nocheck': 1.158515, 'volume': 0}] Here is my code python3 code: pt = [{'min': 1.158, 'max': 1.150, 'id': 269097, 'to': 1532003820, 'from': 1532003760, 'check': 1.15852, 'no_check': 1.15822, 'volume': 0},{'min': 1.1, 'max': 1.17, 'id': 269098, 'to': 1532003880, 'from': 1532003820, 'check': 1.158615, 'nocheck': 1.158515, 'volume': 0}] y = [item[0] for item in pt] z = [item[0] for item in pt] print(y) print(z) Error: File "test_YourM.py", line 19, in &lt;module&gt; y = [item[0][0] for item in pt] File "test_YourM.py", line 19, in &lt;listcomp&gt; y = [item[0][0] for item in pt] KeyError: 0 Expected output: print(y) # {'min': 1.158, 'max': 1.150, 'id': 269097, 'to': 1532003820, 'from': 1532003760, 'check': 1.15852, 'no_check': 1.15822, 'volume': 0} print(z) # {'min': 1.1, 'max': 1.17, 'id': 269098, 'to': 1532003880, 'from': 1532003820, 'check': 1.158615, 'nocheck': 1.158515, 'volume': 0}
answer count: 1
has comment: http://stackoverflow.com/comment/89817619
favorite count: 0
has answer: http://stackoverflow.com/a/51423297
score: 0
has comment: http://stackoverflow.com/comment/89817543
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89817355
tagged with: subprocess
has comment: http://stackoverflow.com/comment/89817483
upvote count: 2

http://stackoverflow.com/comment/89907355
type: AnswerComment
type: Comment
score: 0
has text: That adds the new entries to the end each dict. The rest of my code relies on all keys being in the same order. Is there another way to do this?
comment on: http://stackoverflow.com/a/51469465

http://stackoverflow.com/comment/89715067
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51371470
has text: Just do `if not seq: print("The median cannot be found.")`
type: Comment

http://stackoverflow.com/q/51413834
score: 0
answer count: 1
has body: I need to change the default arrow style for digraphs on networkx. I've read something about matplotlib.patches.ArrowStyle, but I am too new coding and even newer in python, so I did not understand at all. My current code is: G=nx.DiGraph() n=len(C) print(n) for i in range(n): G.add_node(i) for i in nodos_usuarios: for j in nodos_cri: if Y[i,j].x==1: G.add_edge(i,j) pos = nx.circular_layout(G) x=G.node() y=G.edges() elist = edges print(x) print("") print(y) print("") nx.draw_networkx_nodes(G, pos, label="ciudades",size=0.1) nx.draw_networkx_labels(G, pos) nx.draw_networkx_edges(G, pos, edgelist=elist, edge_color='green', width=3, label="S") plt.legend(fontsize = 'medium') plt.axes().set_aspect('equal') plt.savefig("Red.png") plt.show() Y is a matrix related to the graph G. My current output is: Ugly graph - Ugly arrow So I need help to change this arrow style to the classical arrow that we all know. Is there someone could help me to do this more easily?
has comment: http://stackoverflow.com/comment/89833364
type: UnansweredQuestion
tagged with: python
tagged with: plot
has comment: http://stackoverflow.com/comment/90108414
tagged with: networkx
has comment: http://stackoverflow.com/comment/89833000
has comment: http://stackoverflow.com/comment/89825593
has answer: http://stackoverflow.com/a/51414110
type: Question
linked to: http://stackoverflow.com/q/20133479
has title: Networkx: arrows, ploting
has comment: http://stackoverflow.com/comment/90108445

http://stackoverflow.com/comment/89795474
has text: Order doesn’t matter providing each split includes all elements of the group. Of course the groups will have varying lengths. The grouping variables are random number IDs in the data frame I intend to apply this to.
type: QuestionComment
comment on: http://stackoverflow.com/q/51411506
type: Comment
score: 0

http://stackoverflow.com/comment/89944870
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51454159
score: 0
has text: You have to adjust the path based on your file structure.

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

http://stackoverflow.com/a/51408190
accepted answer of: http://stackoverflow.com/q/51401475
has comment: http://stackoverflow.com/comment/89805248
type: Answer
has body: First create an image with black pixels having the same shape and datatype of the original image. Then draw the detected lines on this image. black = np.zeros_like(gray) Here black is an array where all elements are 0. In other words it is a black image having the same shape and datatype as gray. cv2.line(black, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (255, 0, 0), 1, cv2.LINE_AA) cv2.imwrite(out_path, black) The right way would be to first draw the lines using cv21.line() within the for loop. After this proceed to save the image using cv2.imwrite(). Here the complete code you can run: import numpy as np import cv2 in_path = 'my/tif/file' out_path = 'my/output/tif/file' gray = cv2.imread(in_path) edges = cv2.Canny(gray,50,150,apertureSize = 3) cv2.imwrite('edges.tif',edges) minLineLength=10 lines = cv2.HoughLinesP(image=edges,rho=3,theta=np.pi/180, threshold=100,lines=np.array([]), minLineLength=minLineLength,maxLineGap=20) black = np.zeros_like(gray) a,b,c = lines.shape for i in range(a): cv2.line(black, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (255, 0, 0), 1, cv2.LINE_AA) cv2.imwrite(out_path,gray)
answers question: http://stackoverflow.com/q/51401475
score: 0
has comment: http://stackoverflow.com/comment/89805299
type: AcceptedAnswer

pyside
tags question: http://stackoverflow.com/q/51363762
tags question: http://stackoverflow.com/q/51346212
type: Tag
tag name: pyside

http://stackoverflow.com/q/51382344
has comment: http://stackoverflow.com/comment/89737079
has comment: http://stackoverflow.com/comment/89736878
type: Question
has body: https://github.com/maartenww/100daysOfCode_projectOne/tree/StackOverflow (For reference here is the Repo to my code with a branch to code with the error, (so it's still readable for other people)) Hi, I'm creating a platformer and i'm stuck with a problem where I try to make collision between two sprites work using the pygame library. class Game: def sprite_col(self, player_1, platform_list): sprites_hit = pygame.sprite.spritecollide(player_1, platform_list, False) The sprites position is calculated with the use of pygame vectors vec = pygame.math.Vector2 class Player(pygame.sprite.Sprite): # Player Constructor def __init__(self, player_width, player_height, player_color): pygame.sprite.Sprite.__init__(self) self.rect = self.image.get_rect() self.player_pos = vec(screen_width / 2, screen_height / 2) self.rect.x = self.player_pos.x self.rect.y = self.player_pos.y I have no idea why the top code block doesn't run however. I've googled my problem and looked at this video that I'm using for reference : https://www.youtube.com/watch?v=pN9pBx5ln40&amp;list=PLsk-HSGFjnaG-BwZkuAOcVwWldfCLu1pq&amp;index=3 (Skip to 8:40) It gives me the following error: Traceback (most recent call last): File "C:/ScrewAround/100DaysOfCodeProject1/main.py", line 81, in main() File "C:/ScrewAround/100DaysOfCodeProject1/main.py", line 76, in main g.run(Player_1) File "C:/ScrewAround/100DaysOfCodeProject1/main.py", line 65, in run self.update_game(player_1) File "C:/ScrewAround/100DaysOfCodeProject1/main.py", line 58, in update_game self.sprite_col(player_1) File "C:/ScrewAround/100DaysOfCodeProject1/main.py", line 41, in sprite_col sprites_hit = pygame.sprite.spritecollide(player_1, platform_sprites, False) File "C:\ScrewAround\100DaysOfCodeProject1\venv\lib\site-packages\pygame\sprite.py", line 1524, in spritecollide spritecollide = sprite.rect.colliderect AttributeError: 'pygame.math.Vector2' object has no attribute 'colliderect' As you can see it's an AttributeError with Vectors and collidere…
score: 0
has title: How do I create sprite collision in PyGame using vectors?
answer count: 1
has answer: http://stackoverflow.com/a/51382720
accepted answer: http://stackoverflow.com/a/51382720
favorite count: 0
has comment: http://stackoverflow.com/comment/89736914
has comment: http://stackoverflow.com/comment/89736502
tagged with: python
tagged with: pygame
type: AnsweredQuestion
tagged with: python-3.x
upvote count: 1
downvote count: 1

qtabwidget
tags question: http://stackoverflow.com/q/51404102
tag name: qtabwidget
type: Tag

http://stackoverflow.com/comment/89882808
comment on: http://stackoverflow.com/a/51449705
type: AnswerComment
type: Comment
has text: If I do that list index is out of range.
score: 0

http://stackoverflow.com/q/51456930
answer count: 0
type: UnansweredQuestion
has title: Optimal 1d kernel density bandwidth in Python
tagged with: kernel-density
tagged with: bandwidth
type: Question
score: 0
has comment: http://stackoverflow.com/comment/89884906
has body: Is there any direct function that computes the optimal bandwidth for a univariate density estimation in Python? In scikit-learn, the KernelDensity function has nothing predefined. I want to avoid grid searching and would like to have something that you enter with a vector and it comes out a value, it could be any of the classic rules (rule-of-thumbs, plug-in, Silverman, Sheater and Jones, etc.) like the functions bw.nrd0 and bw.nrd of R. Best.
tagged with: python
has comment: http://stackoverflow.com/comment/90811181

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

http://stackoverflow.com/q/51388068
has comment: http://stackoverflow.com/comment/89750399
has comment: http://stackoverflow.com/comment/89754732
type: Question
upvote count: 1
tagged with: python
answer count: 1
tagged with: excel
tagged with: git
tagged with: xlwings
has answer: http://stackoverflow.com/a/51395034
has title: Overwriting Python Path in xlwings
has body: I have two repositories in my file structure R1 and R2. Repository 1 (R1) is in my PYTHONPATH. I'm trying out xlwings which works wonderfully when I run from Python to change an Excel file. However, I'm having issues with running scripts from Repository 2 (R2). When I put the path to R2 in PYTHONPATH in the xlwings addin it seems to be appending R2 onto the original PYTHONPATH and since R1 is first it seems to be defaulting to R1 when importing. Is there a way to (locally) overwrite the PYTHONPATH just for that xlwings instance well keeping R1 in my system PYTHONPATH?
has comment: http://stackoverflow.com/comment/89754525
tagged with: python-import
has comment: http://stackoverflow.com/comment/89749892
downvote count: 0
accepted answer: http://stackoverflow.com/a/51395034
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89748615
score: 1
favorite count: 0

http://stackoverflow.com/a/51412128
accepted answer of: http://stackoverflow.com/q/51411981
type: Answer
answers question: http://stackoverflow.com/q/51411981
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89795949
has body: I did some digging, and while not documented or official, using __args__ works. &gt;&gt;&gt; Union[str, bool].__args__ (&lt;class 'str'&gt;, &lt;class 'bool'&gt;) &gt;&gt;&gt; List[str].__args__ (&lt;class 'str'&gt;,) For some reason the union of an int and a bool is just an int, I don't dare dig any further in the mess that this module is. &gt;&gt;&gt; Union[int, bool] &lt;class 'int'&gt; &gt;&gt;&gt; Union[bool, int] &lt;class 'int'&gt;
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/89869073
type: AnswerComment
type: Comment
has text: The problem with particular element is solved, I have added the code snippet in the answer
comment on: http://stackoverflow.com/a/51448704
score: 0

http://stackoverflow.com/comment/89647886
has text: I’m running in the server Jupyter sets up for iPads and iPhone and I’m assuming now that they do not have pandas. I emailed them to see what they have to say but may take a while
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51335475
score: 1

machine-learning
tags question: http://stackoverflow.com/q/51417007
tags question: http://stackoverflow.com/q/51354915
tags question: http://stackoverflow.com/q/51369419
tags question: http://stackoverflow.com/q/51394659
tags question: http://stackoverflow.com/q/51385210
tags question: http://stackoverflow.com/q/51373903
tags question: http://stackoverflow.com/q/51397611
tags question: http://stackoverflow.com/q/51342354
tags question: http://stackoverflow.com/q/51380832
tags question: http://stackoverflow.com/q/51346750
tags question: http://stackoverflow.com/q/51367755
tags question: http://stackoverflow.com/q/51467350
tags question: http://stackoverflow.com/q/51371356
tags question: http://stackoverflow.com/q/51474535
tags question: http://stackoverflow.com/q/51450185
tags question: http://stackoverflow.com/q/51340885
tags question: http://stackoverflow.com/q/51433041
tags question: http://stackoverflow.com/q/51473904
tags question: http://stackoverflow.com/q/51370531
tags question: http://stackoverflow.com/q/51328263
tags question: http://stackoverflow.com/q/51342763
tags question: http://stackoverflow.com/q/51462538
tags question: http://stackoverflow.com/q/51454466
tags question: http://stackoverflow.com/q/51385657
tags question: http://stackoverflow.com/q/51328208
tags question: http://stackoverflow.com/q/51350585
tags question: http://stackoverflow.com/q/51342369
tags question: http://stackoverflow.com/q/51400043
tags question: http://stackoverflow.com/q/51370733
tags question: http://stackoverflow.com/q/51376756
tags question: http://stackoverflow.com/q/51401416
tags question: http://stackoverflow.com/q/51345535
tags question: http://stackoverflow.com/q/51369709
tag name: machine-learning
tags question: http://stackoverflow.com/q/51447720
tags question: http://stackoverflow.com/q/51380812
tags question: http://stackoverflow.com/q/51476725
tags question: http://stackoverflow.com/q/51452031
tags question: http://stackoverflow.com/q/51446438
tags question: http://stackoverflow.com/q/51378105
tags question: http://stackoverflow.com/q/51368416
tags question: http://stackoverflow.com/q/51372886
tags question: http://stackoverflow.com/q/51469446
tags question: http://stackoverflow.com/q/51464322
tags question: http://stackoverflow.com/q/51371427
tags question: http://stackoverflow.com/q/51430094
tags question: http://stackoverflow.com/q/51363372
tags question: http://stackoverflow.com/q/51456613
tags question: http://stackoverflow.com/q/51341865
tags question: http://stackoverflow.com/q/51439968
type: Tag
tags question: http://stackoverflow.com/q/51441690
tags question: http://stackoverflow.com/q/51335512
tags question: http://stackoverflow.com/q/51328575
tags question: http://stackoverflow.com/q/51425436
tags question: http://stackoverflow.com/q/51365661
tags question: http://stackoverflow.com/q/51428696
tags question: http://stackoverflow.com/q/51360966
tags question: http://stackoverflow.com/q/51330993
tags question: http://stackoverflow.com/q/51404204
tags question: http://stackoverflow.com/q/51340100
tags question: http://stackoverflow.com/q/51377371
tags question: http://stackoverflow.com/q/51386902
tags question: http://stackoverflow.com/q/51364273
tags question: http://stackoverflow.com/q/51461272
tags question: http://stackoverflow.com/q/51392178
tags question: http://stackoverflow.com/q/51332144
tags question: http://stackoverflow.com/q/51404963
tags question: http://stackoverflow.com/q/51420917
tags question: http://stackoverflow.com/q/51365607
tags question: http://stackoverflow.com/q/51346918
tags question: http://stackoverflow.com/q/51470179
tags question: http://stackoverflow.com/q/51354086
tags question: http://stackoverflow.com/q/51465665
tags question: http://stackoverflow.com/q/51480706
tags question: http://stackoverflow.com/q/51359476
tags question: http://stackoverflow.com/q/51435800
tags question: http://stackoverflow.com/q/51459406
tags question: http://stackoverflow.com/q/51334970
tags question: http://stackoverflow.com/q/51387317

http://stackoverflow.com/a/51556791
score: 0
has body: As we see in the source (for python 3.7) map returns a function: def map(self, fn, *iterables, timeout=None, chunksize=1): ... if timeout is not None: end_time = timeout + time.time() fs = [self.submit(fn, *args) for args in zip(*iterables)] # Yield must be hidden in closure so that the futures are submitted # before the first iterator value is required. def result_iterator(): try: # reverse to keep finishing order fs.reverse() while fs: # Careful not to keep a reference to the popped future if timeout is None: yield fs.pop().result() else: yield fs.pop().result(end_time - time.time()) finally: for future in fs: future.cancel() return result_iterator() The TimeoutError is raised from yield fs.pop().result(end_time - time.time()) call but you have to request a result to reach that call. The rationale is that you do not care about submitting the tasks. The tasks are submitted and start running in the background threads. What you care about is timing out when you request a result - it is a usual use case you submit tasks and you request a result from them in a limited time, not just submitting them and expect them to terminate in a limited time. If the latter is what you were about you could use wait, as illustrated for instance in Individual timeouts for concurrent.futures
has comment: http://stackoverflow.com/comment/90138503
has comment: http://stackoverflow.com/comment/90138570
type: Answer
answers question: http://stackoverflow.com/q/51420758

http://stackoverflow.com/q/51348016
has comment: http://stackoverflow.com/comment/89668726
tagged with: read-eval-print-loop
tagged with: interpreter
has comment: http://stackoverflow.com/comment/89669459
has body: My debian python 2.7 and python 3.4 had normal up/down button command history. When I go into my newly built/installed python 3.6.3 the cursor physically moves to the line above instead. If this is correct behaviour how do I recall command history in the interpreter?
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/89668640
type: Question
has comment: http://stackoverflow.com/comment/89669453
has title: Has the python3.6 interpreter changed?
tagged with: python
has comment: http://stackoverflow.com/comment/89672686
has comment: http://stackoverflow.com/comment/89668619
answer count: 0
type: UnansweredQuestion
score: 0

http://stackoverflow.com/comment/89705890
score: 0
type: AnswerComment
has text: Well there are many different popup windows with different looks for different needs but to have a truly customer window to fit your exact needs you will need to look into the `TopLevel()` method and design your own popup.
comment on: http://stackoverflow.com/a/51366482
type: Comment

http://stackoverflow.com/comment/89901827
type: QuestionComment
has text: As written this code compiles correctly. Cython won't allow `np.ndarray[...]` types in nested functions or in classes. However __neither of those cases are shown in your code__. Typed memoryviews work fine in these situations though.
score: 2
comment on: http://stackoverflow.com/q/51460725
type: Comment

http://stackoverflow.com/a/51413750
has comment: http://stackoverflow.com/comment/89947665
answers question: http://stackoverflow.com/q/51413663
type: Answer
upvote count: 4
downvote count: 0
score: 4
has body: If root is a Tkinter object, then shouldn't I be able to call mainloop() on the class MainApplication that I made? No. root is a tkinter object, but app is not. So, you can call root.mainloop(), but you can't call app.mainloop(). Sure, your app has a bunch of tkinter objects (self.master is a Tk, self.frame is a Frame, etc.), but that doesn't mean it is one. If that isn't obvious, consider this code: class Point: def __init__(self, x, y): self.x = x self.y = y pt = Point(2, 3) Your pt has some integers, but that doesn't mean it is one. You wouldn't expect pt.bit_length() or pt + 6 or float(pt) to work, right? If you've seen examples that seem similar to your code (e.g., the Effbot book is full of them), the key difference is that make MainApplication a subclass of either tkinter.Tk or tkinter.Frame. If you did that, then app would be a tkinter object (a Tk or a Frame). But you didn't.

http://stackoverflow.com/a/51412389
type: Answer
has body: Use a lambda to define an anonymous function inline: foo(lambda x: 4 * fcn1(x)) You could hide this behind a helper function: def times_n(n, f): return lambda x: n * f(x) foo(times_n(4, fcn1)) If you don't like lambdas you can use all named functions: def times_n(n, f): def fn(x): return n * f(x) return fn A new fn(x) will be created each time times_n() is called, bound to varying values of n.
score: 2
answers question: http://stackoverflow.com/q/51412366
downvote count: 0
upvote count: 2

http://stackoverflow.com/q/51397611
has answer: http://stackoverflow.com/a/51397795
accepted answer: http://stackoverflow.com/a/51397795
favorite count: 0
has title: RandomForestClassifier instance not fitted yet. Call 'fit' with appropriate arguments before using this method
has body: I am trying to train a decision tree model, save it, and then reload it when I need it later. However, I keep getting the following error: This DecisionTreeClassifier instance is not fitted yet. Call 'fit' with appropriate arguments before using this method. Here is my code: X_train, X_test, y_train, y_test = train_test_split(data, label, test_size=0.20, random_state=4) names = ["Decision Tree", "Random Forest", "Neural Net"] classifiers = [ DecisionTreeClassifier(), RandomForestClassifier(), MLPClassifier() ] score = 0 for name, clf in zip(names, classifiers): if name == "Decision Tree": clf = DecisionTreeClassifier(random_state=0) grid_search = GridSearchCV(clf, param_grid=param_grid_DT) grid_search.fit(X_train, y_train_TF) if grid_search.best_score_ &gt; score: score = grid_search.best_score_ best_clf = clf elif name == "Random Forest": clf = RandomForestClassifier(random_state=0) grid_search = GridSearchCV(clf, param_grid_RF) grid_search.fit(X_train, y_train_TF) if grid_search.best_score_ &gt; score: score = grid_search.best_score_ best_clf = clf elif name == "Neural Net": clf = MLPClassifier() clf.fit(X_train, y_train_TF) y_pred = clf.predict(X_test) current_score = accuracy_score(y_test_TF, y_pred) if current_score &gt; score: score = current_score best_clf = clf pkl_filename = "pickle_model.pkl" with open(pkl_filename, 'wb') as file: pickle.dump(best_clf, file) from sklearn.externals import joblib # Save to file in the current working directory joblib_file = "joblib_model.pkl" joblib.dump(best_clf, joblib_file) print("best classifier: ", best_clf, " Accuracy= ", score) Here is how I load the model and test it: #First method with open(pkl_filename, 'rb') as h: loaded_model = pickle.load(h) #Second method joblib_model = joblib.load(joblib_file) As you can see, I have tried two ways of saving it but none has worked. Here is how I tested: print(loaded_model.predict(test)) print(joblib_model.predict(test)) You can clearly see that the models are actually fitted an…
upvote count: 5
has comment: http://stackoverflow.com/comment/89766400
tagged with: python
type: AnsweredQuestion
downvote count: 0
possible better answer: http://stackoverflow.com/a/71880555
has answer: http://stackoverflow.com/a/71880555
tagged with: machine-learning
type: Question
tagged with: cross-validation
tagged with: grid-search
has comment: http://stackoverflow.com/comment/136288020
answer count: 2
score: 5
tagged with: scikit-learn

http://stackoverflow.com/q/51364165
has title: How to explain clustering results?
favorite count: 0
score: 2
has comment: http://stackoverflow.com/comment/89700745
tagged with: python
has comment: http://stackoverflow.com/comment/89700873
type: AnsweredQuestion
has body: Say I have a high dimensional dataset which I assume to be well separable by some kind of clustering algorithm. And I run the algorithm and end up with my clusters. Is there any sort of way (preferable not "hacky" or some kind of heuristic) to explain "what features and thresholds were important in making members of cluster A (for example) part of cluster A?" I have tried looking at cluster centroids but this gets tedious with a high dimensional dataset. I have also tried fitting a decision tree to my clusters and then looking at the tree to determine which decision path most of the members of a given cluster follow. I have also tried fitting an SVM to my clusters and then using LIME on the closest samples to the centroids in order to get an idea of what features were important in classifying near the centroids. However, both of these latter 2 ways require the use of supervised learning in an unsupervised setting and feel "hacky" to me, whereas I'd like something more grounded.
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51369003
has answer: http://stackoverflow.com/a/51364582
accepted answer: http://stackoverflow.com/a/51369003
tagged with: k-means
tagged with: cluster-analysis
downvote count: 1
tagged with: scikit-learn
upvote count: 3
possible better answer: http://stackoverflow.com/a/51364582

http://stackoverflow.com/q/51357410
answer count: 2
downvote count: 0
tagged with: paho
has comment: http://stackoverflow.com/comment/89693948
score: 3
favorite count: 0
tagged with: latency
has comment: http://stackoverflow.com/comment/89687681
has answer: http://stackoverflow.com/a/51363050
type: UnansweredQuestion
tagged with: mqtt
tagged with: python
has body: I'm trying measure the latency from my publisher to my subscriber in an MQTT network. I was hoping to use the on_message() function to measure how long this trip takes but its not clear to me whether this callback comes after the broker receives the message or after the subscriber receives it? Also does anyone else have any other suggestion on how to measure latency across the network?
tagged with: c++
has title: How to measure latency in paho-mqtt network
has answer: http://stackoverflow.com/a/51361548
upvote count: 3
type: Question

http://stackoverflow.com/q/51476943
score: -1
has answer: http://stackoverflow.com/a/51477060
favorite count: 0
has answer: http://stackoverflow.com/a/51477171
tagged with: python
answer count: 4
type: AnsweredQuestion
upvote count: 0
accepted answer: http://stackoverflow.com/a/51478778
has title: statistical operation in csv file using python
downvote count: 1
has body: I have .csv file and trying to get the average of every 3 lines in turn. meaning lines 1 to 3, then lines 4 to 6 etc. here is a small example: 2 5 8 11 14 17 20 23 26 and the output I expect to get is: 5 14 23 I am trying to do that in python and wrote the following code. it does not return what I expect: infile = open("finename.csv", "r") sum = 0 for i in range(len(infile)): if i+(i+1)+(i+2) %3 = 0, sum += infile[i] average = sum/3 do you know how to fix it?
type: Question
possible better answer: http://stackoverflow.com/a/51477171
has answer: http://stackoverflow.com/a/51478778
has answer: http://stackoverflow.com/a/51477153

http://stackoverflow.com/q/51406066
tagged with: nlp
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89783502
downvote count: 0
has comment: http://stackoverflow.com/comment/89784005
accepted answer: http://stackoverflow.com/a/51406375
type: Question
has answer: http://stackoverflow.com/a/51406375
score: 4
tagged with: fuzzy-comparison
answer count: 1
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/89783290
tagged with: similarity
has body: I am trying to measure the similarity of company names, however I am having difficulties while I'm trying to match the abbreviations for those names. For example: IBM The International Business Machines Corporation I have tried using fuzzywuzzy to measure the similarity: &gt;&gt;&gt; fuzz.partial_ratio("IBM","The International Business Machines Corporation") 33 &gt;&gt;&gt; fuzz.partial_ratio("General Electric","GE Company") 20 &gt;&gt;&gt; fuzz.partial_ratio("LTCG Holdings Corp","Long Term Care Group Inc") 39 &gt;&gt;&gt; fuzz.partial_ratio("Young Innovations Inc","YI LLC") 33 Do you know any techniques to measure a higher similarity for such abbreviations?
has title: Abbreviation Detection for Python
tagged with: python
has comment: http://stackoverflow.com/comment/89783204
upvote count: 4

http://stackoverflow.com/q/51350907
downvote count: 2
has comment: http://stackoverflow.com/comment/89674708
tagged with: python
has title: How to save .py files in VSCode on linux and write the admin password only once?
has body: I am using Visual Studio Code on Linux Sabayon (Gnome) and when I want to save any .py files I have to write the admin password for each one. Is there some settings that may fix it? I know that I can run Visual Studio Code as admin but that's not the best option for me.
has comment: http://stackoverflow.com/comment/89674589
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51351258
type: Question
tagged with: visual-studio-code
has comment: http://stackoverflow.com/comment/89674638
has comment: http://stackoverflow.com/comment/89674578
has comment: http://stackoverflow.com/comment/89674616
accepted answer: http://stackoverflow.com/a/51351258
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89674337
favorite count: 0
upvote count: 2

http://stackoverflow.com/comment/89746232
has text: @Prune, `help(tkinter.Tk.mainloop)` describes the function as `mainloop(self, n=0)`
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51386979
type: QuestionComment

http://stackoverflow.com/comment/89860762
type: AnswerComment
comment on: http://stackoverflow.com/a/51444890
score: 0
type: Comment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/176424/discussion-between-stone-rock-and-xyzjayne).

http://stackoverflow.com/a/51411689
type: Answer
answers question: http://stackoverflow.com/q/51410808
has comment: http://stackoverflow.com/comment/89795259
has comment: http://stackoverflow.com/comment/89795335
has comment: http://stackoverflow.com/comment/89797667
score: 0
has comment: http://stackoverflow.com/comment/89795422
has comment: http://stackoverflow.com/comment/89795809
has body: If x is sorted, use bisect: import bisect test_out=[] max_x=max(x) min_x=min(x) for f in y: if f&gt;=max_x: idx=-1 elif f&lt;=min_x: idx=0 else: idx=bisect.bisect_left(x,f) if abs(x[idx-1]-f)&lt;abs(x[idx]-f): idx-=1 test_out.append(x[idx]) &gt;&gt;&gt; test_out==desired_output True

http://stackoverflow.com/a/51357374
answers question: http://stackoverflow.com/q/51357272
type: Answer
has comment: http://stackoverflow.com/comment/89686992
downvote count: 0
score: 1
has body: You need to assign it a default value and it automatically becomes optional. You might need to rework the logic a bit but as for the function for example def common_pos(doc, n, pos='VERB'): would take whatever pos you give it but if you don't, it will become 'VERB'.
has comment: http://stackoverflow.com/comment/89698814
upvote count: 1

big-o
tags question: http://stackoverflow.com/q/51410808
type: Tag
tags question: http://stackoverflow.com/q/51338089
tags question: http://stackoverflow.com/q/51390499
tag name: big-o

http://stackoverflow.com/comment/89828785
comment on: http://stackoverflow.com/q/51428825
has text: You could try using the `glob` module.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89839925
type: Comment
score: 0
has text: I get the following error: `AttributeError: 'DataFrame' object has no attribute 'RowID'`
comment on: http://stackoverflow.com/a/51434865
type: AnswerComment

http://stackoverflow.com/q/51398724
downvote count: 0
favorite count: 0
upvote count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/51398779
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/59035312
tagged with: flask-mongoengine
has answer: http://stackoverflow.com/a/59035312
tagged with: mongoengine
type: Question
tagged with: mongodb
has answer: http://stackoverflow.com/a/51399583
has body: I have flask-mongoengine application and I have a seriuos problem when I want to iterate over a mongoengine queryset object. here is the code for my mongoengine object: mongo_models: class Candid(Document): candid_intent_id = StringField() id_list = ListField(StringField()) custom_code = StringField() is_approved = BooleanField() def to_json(self, *args, **kwargs): return {'candid_intent_id': self.candid_intent_id, 'id_list': self.id_list, 'custom_code': self.custom_code, 'is_approved': self.is_approved} and I want to iterate over them like this: candid_list: custom_code = 'Bob' query_set = Candid.objects(is_denied=False, custom_code=current_request.custom_code) try: for candid in query_set: suggested_intent_list.append(candid.to_json()) if not candid.is_approved: suggested_intent_count += 1 except StopIteration: return 'StopIteration error' now here is the catch: when run my code (with python 3.5.2) using a local mongo server it works fine (whether Candid collection is empty or not), but I deploy the code on a dockerized server (with python 3.7.0) I get the following Runtime Error: File "/controller.py", line 25, in &lt;candid_list&gt; for candid in query_set: RuntimeError: generator raised StopIteration btw, mongoengine version is the same for local and docker server run: mongoengine==0.15.0. please tell me if I have to provide more information, and any help would be greatly appriciated.
has answer: http://stackoverflow.com/a/51398779
answer count: 3
has title: mongoengine - RuntimeError: generator raised StopIteration

google-analytics-firebase
tags question: http://stackoverflow.com/q/51343262
tag name: google-analytics-firebase
type: Tag

http://stackoverflow.com/comment/89835506
type: Comment
score: 3
has text: If you're trying to put references to the methods into your option map, you shouldn't be *calling* them. But this whole thing seems a bit convoluted, shouldn't those things belong to an *instance* of the menu rather than the *class*?
type: QuestionComment
comment on: http://stackoverflow.com/q/51432300

python-3.x
tags question: http://stackoverflow.com/q/51386630
tags question: http://stackoverflow.com/q/51409474
tags question: http://stackoverflow.com/q/51341929
tags question: http://stackoverflow.com/q/51332086
tags question: http://stackoverflow.com/q/51348243
tags question: http://stackoverflow.com/q/51466462
tags question: http://stackoverflow.com/q/51474825
tags question: http://stackoverflow.com/q/51389086
tags question: http://stackoverflow.com/q/51468791
tags question: http://stackoverflow.com/q/51470023
tags question: http://stackoverflow.com/q/51414147
tags question: http://stackoverflow.com/q/51387973
tags question: http://stackoverflow.com/q/51461306
tags question: http://stackoverflow.com/q/51413076
tags question: http://stackoverflow.com/q/51456470
tags question: http://stackoverflow.com/q/51359476
tags question: http://stackoverflow.com/q/51362459
tags question: http://stackoverflow.com/q/51480786
tags question: http://stackoverflow.com/q/51352479
tags question: http://stackoverflow.com/q/51482400
tags question: http://stackoverflow.com/q/51379338
tags question: http://stackoverflow.com/q/51373456
tags question: http://stackoverflow.com/q/51401920
tags question: http://stackoverflow.com/q/51446194
tags question: http://stackoverflow.com/q/51415248
tags question: http://stackoverflow.com/q/51360609
tags question: http://stackoverflow.com/q/51451699
tags question: http://stackoverflow.com/q/51408496
tags question: http://stackoverflow.com/q/51386399
tags question: http://stackoverflow.com/q/51333050
tags question: http://stackoverflow.com/q/51444526
tags question: http://stackoverflow.com/q/51430672
tags question: http://stackoverflow.com/q/51455383
tags question: http://stackoverflow.com/q/51359978
tags question: http://stackoverflow.com/q/51466921
tags question: http://stackoverflow.com/q/51455827
tags question: http://stackoverflow.com/q/51366452
tags question: http://stackoverflow.com/q/51459784
tags question: http://stackoverflow.com/q/51392915
tags question: http://stackoverflow.com/q/51458170
tags question: http://stackoverflow.com/q/51353969
tags question: http://stackoverflow.com/q/51434573
tags question: http://stackoverflow.com/q/51328609
tags question: http://stackoverflow.com/q/51328784
tags question: http://stackoverflow.com/q/51454362
tags question: http://stackoverflow.com/q/51418113
tags question: http://stackoverflow.com/q/51352002
tags question: http://stackoverflow.com/q/51468317
tags question: http://stackoverflow.com/q/51429088
tags question: http://stackoverflow.com/q/51479954
tags question: http://stackoverflow.com/q/51341959
tags question: http://stackoverflow.com/q/51405790
tags question: http://stackoverflow.com/q/51472668
tags question: http://stackoverflow.com/q/51405006
tags question: http://stackoverflow.com/q/51366083
tags question: http://stackoverflow.com/q/51474515
tags question: http://stackoverflow.com/q/51450091
tags question: http://stackoverflow.com/q/51327493
tags question: http://stackoverflow.com/q/51432600
tags question: http://stackoverflow.com/q/51405148
tags question: http://stackoverflow.com/q/51392321
tags question: http://stackoverflow.com/q/51470241
tags question: http://stackoverflow.com/q/51438898
tags question: http://stackoverflow.com/q/51378815
tags question: http://stackoverflow.com/q/51463223
tags question: http://stackoverflow.com/q/51395116
tags question: http://stackoverflow.com/q/51337167
tags question: http://stackoverflow.com/q/51468810
tags question: http://stackoverflow.com/q/51477958
tags question: http://stackoverflow.com/q/51364320
tags question: http://stackoverflow.com/q/51350989
tags question: http://stackoverflow.com/q/51463025
tags question: http://stackoverflow.com/q/51409026
tags question: http://stackoverflow.com/q/51358500
tags question: http://stackoverflow.com/q/51448664
tags question: http://stackoverflow.com/q/51380692
tags question: http://stackoverflow.com/q/51394659
tags question: http://stackoverflow.com/q/51334226
tags question: http://stackoverflow.com/q/51461881
tags question: http://stackoverflow.com/q/51446661

http://stackoverflow.com/comment/89874077
type: QuestionComment
has text: Do you actually want to do a string compare? Or did you intend to compare ints?
comment on: http://stackoverflow.com/q/51451992
score: 0
type: Comment

http://stackoverflow.com/q/51343421
tagged with: apt
favorite count: 0
has answer: http://stackoverflow.com/a/51451855
has comment: http://stackoverflow.com/comment/89660426
has body: As Python 3.7 was being prepared I installed Python 3.7.0b3 from source. Now 3.7 is out and I want to use the version packaged for Ubuntu. So I've done apt-get install python3.7 but $ which python3.7 /usr/local/bin/python3.7 $ /usr/local/bin/python3.7 --version Python 3.7.0b3 How does one uninstall a Python installed from source (on Ubuntu)? Or how can I replace it with the apt repo packaged version?
accepted answer: http://stackoverflow.com/a/51451855
has title: How do I replace a Python installed from source with a packaged version?
tagged with: uninstallation
score: 6
tagged with: python
downvote count: 1
possible better answer: http://stackoverflow.com/a/51451964
has comment: http://stackoverflow.com/comment/89660468
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/3544378
upvote count: 7
type: Question
has comment: http://stackoverflow.com/comment/89873963
has answer: http://stackoverflow.com/a/51452180
has answer: http://stackoverflow.com/a/51451964
answer count: 3

http://stackoverflow.com/q/51445252
answer count: 4
tagged with: for-loop
score: 2
type: AnsweredQuestion
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/492860
type: Question
accepted answer: http://stackoverflow.com/a/51445359
has answer: http://stackoverflow.com/a/51445863
tagged with: python
tagged with: python-3.x
upvote count: 2
has answer: http://stackoverflow.com/a/51446162
possible better answer: http://stackoverflow.com/a/51445321
has body: [python] 3.6 Hello, I was trying to iterate over a list with a for cycle, where I had to restart the cycle whenever a condition was confirmed. In C I would do: for(i = 0; i &lt; 10; i++){ if(list[i] == something) i = 0; } Here I was trying to do this: for x in listPrimes: if((num % x) == 0): num /= x # divide by the prime factorials.append(x) x = 2 # reset to the first prime in the list? which doesn't work correctly. What are the ways to reset the for to a certain iteration of the list? Do I have to do the for in some other way? Thanks for your time
has answer: http://stackoverflow.com/a/51445321
tagged with: list
has title: restarting for cycle iterating over list python3
has answer: http://stackoverflow.com/a/51445359
has comment: http://stackoverflow.com/comment/89863395

http://stackoverflow.com/a/51456681
downvote count: 0
type: Answer
score: 2
upvote count: 2
has body: to create a series from that text file do the following with open(file) as f: txt = f.read().replace("\n","") series = pd.Series(txt.split(";"))
answers question: http://stackoverflow.com/q/51456650
accepted answer of: http://stackoverflow.com/q/51456650
type: AcceptedAnswer

http://stackoverflow.com/comment/89855844
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51442437
type: QuestionComment
has text: @sophros I added an MCVE!

http://stackoverflow.com/a/51327826
has comment: http://stackoverflow.com/comment/89636931
score: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51327745
type: Answer
accepted answer of: http://stackoverflow.com/q/51327745
upvote count: 2
has comment: http://stackoverflow.com/comment/89636647
has body: You can add a "Gender" column before concatenating. We use Categorical Data with groupby to calculate the Cartesian product. This should also yield performance benefits. df = pd.concat([df_Male.assign(gender='Male'), df_Female.assign(gender='Female'), df_Transgender.assign(gender='Transgender')]) for col in ['gender', 'continent']: df[col] = df[col].astype('category') res = df.groupby(['gender', 'continent']).first().fillna(0).astype(int) print(res) avg_count_country avg_age gender continent Female Africa 60 12 America 0 0 Asia 50 7 Europe 70 0 Male Africa 65 10 America 0 0 Asia 55 5 Europe 75 8 Transgender Africa 40 11 America 80 10 Asia 30 6 Europe 0 0

http://stackoverflow.com/a/51410813
type: Answer
has body: You are importing datetime from datetime. Later in the code you using datetime.datetime, so that's giving you error. You shoud just call t = datetime(*struct_time[:6]) or just do import datetime and call it t = datetime.datetime(*struct_time[:6]) The correct program should look like: import time import datetime time_string = '2018-07-16T23:50:55+0000' #Reduct 8 hours and print in human readable format struct_time = time.strptime(time_string, "%Y-%m-%dT%H:%M:%S+0000") t = datetime.datetime(*struct_time[:6]) delta = datetime.timedelta(hours=8) print(t+delta)
upvote count: 1
has comment: http://stackoverflow.com/comment/89793160
has comment: http://stackoverflow.com/comment/89793220
has comment: http://stackoverflow.com/comment/89793137
type: AcceptedAnswer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51410772
answers question: http://stackoverflow.com/q/51410772
has comment: http://stackoverflow.com/comment/89793235

http://stackoverflow.com/comment/89833952
has text: I still think your answer is conflating two different things: `__bool__` implements truth value determination. `not` simply negates an existing boolean value. Hence there is no special method on an object to "implement `not`" -- whereas there *is* such a special method for `!=`
comment on: http://stackoverflow.com/a/51430927
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51358924
type: Answer
answers question: http://stackoverflow.com/q/51358500
has body: Did you try setting up an empty array and then changing the values if you have any? import numpy as np items = numpy.empty((len(DataFrame)) items[:] = numpy.nan if relevant_item != 'None' and relevant_item != 'Not in dict': items[i] = relevant_item # supposing you have some so len_item = count_nonzero(np.isnan(items)) if len_item == 1: item_result = items if len_item == 2: two = items item_result = some_method(two) if len_item == 3: threes = items item_result = some_method(three) This way your items array has the same length as the data frame and you will not get that error. If NaN array is not suitable, why not try numpy.zeros ? Hope this helps!
score: 0

http://stackoverflow.com/a/51406778
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51406492
has body: PySocks is the name of the package. It installs two modules : socks and sockshandler. These are the ones you can import and use in your Python script. Source : https://github.com/Anorov/PySocks
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/89797322

http://stackoverflow.com/a/51439877
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51439644
has body: This should work: for i in range(0, len(a)): if i &lt; 4: previous_4 = a[ : i+1] else: previous_4 = a[i-4: i+1]

http://stackoverflow.com/comment/89649707
comment on: http://stackoverflow.com/q/51337460
has text: I want to collect the qualified records to a list @ThatBird
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51474650
tagged with: python
tagged with: xmlhttprequest
has title: Need help in scraping list of hotel from a website with fixed urls and dynamically loading the content?
has comment: http://stackoverflow.com/comment/89917538
answer count: 0
upvote count: 1
tagged with: web-scraping
tagged with: scrapy
type: Question
has body: I am trying to scrape the details from a hotel listing site this site. Here when we click the next button for the next page the url remain the same and when looked with inspect element there site is sending a XHR request. I tried to use selenium webdriver and python and the following is my code from time import sleep import scrapy from selenium import webdriver from scrapy.selector import Selector from scrapy.http import Request from selenium.common.exceptions import NoSuchElementException class DineoutRestaurantSpider(scrapy.Spider): name = 'dineout_restaurant' allowed_domains = ['dineout.co.in/bangalore-restaurants?search_str='] start_urls = ['http://dineout.co.in/bangalore-restaurants?search_str='] def start_requests(self): self.driver = webdriver.Chrome('/Users/macbookpro/Downloads/chromedriver') self.driver.get('https://www.dineout.co.in/bangalore-restaurants?search_str=')' url = 'https://www.dineout.co.in/bangalore-restaurants?search_str=' **yield Request(url, callback=self.parse)** self.logger.info('Empty message') for i in range(1, 4): try: next_page = self.driver.find_element_by_xpath('//a[text()="Next "]') sleep(11) self.logger.info('Sleeping for 11 seconds.') next_page.click() url = 'https://www.dineout.co.in/bangalore-restaurants?search_str=' yield Request(url, callback=self.parse) except NoSuchElementException: self.logger.info('No more pages to load.') self.driver.quit() break def parse(self, response): self.logger.info('Entered parse method') restaurants = response.xpath('//*[@class="cardBg"]') for restaurant in restaurants: name = restaurant.xpath('.//*[@class="titleDiv"]/h4/a/text()').extract_first() location = restaurant.xpath('.//*[@class="location"]/a/text()').extract() rating = restaurant.xpath('.//*[@class="rating rating-5"]/a/span/text()').extract_first() yield{ 'Name': name, 'Location': location, 'Rating': rating, }` In the above code the yield Request doesnot goto the parse function? Am I missing anything?I am not getting any error But the s…
downvote count: 0
score: 1
favorite count: 0
type: UnansweredQuestion

pandas-groupby
tags question: http://stackoverflow.com/q/51459150
tags question: http://stackoverflow.com/q/51333050
tags question: http://stackoverflow.com/q/51347115
tags question: http://stackoverflow.com/q/51408383
tags question: http://stackoverflow.com/q/51352544
tags question: http://stackoverflow.com/q/51358307
tags question: http://stackoverflow.com/q/51378987
tags question: http://stackoverflow.com/q/51327498
tags question: http://stackoverflow.com/q/51335107
tags question: http://stackoverflow.com/q/51463838
tags question: http://stackoverflow.com/q/51327948
tags question: http://stackoverflow.com/q/51408907
tags question: http://stackoverflow.com/q/51338028
tags question: http://stackoverflow.com/q/51346991
tags question: http://stackoverflow.com/q/51374595
tags question: http://stackoverflow.com/q/51423948
tag name: pandas-groupby
tags question: http://stackoverflow.com/q/51425532
tags question: http://stackoverflow.com/q/51367776
type: Tag
tags question: http://stackoverflow.com/q/51384734
tags question: http://stackoverflow.com/q/51375632
tags question: http://stackoverflow.com/q/51378799
tags question: http://stackoverflow.com/q/51406949
tags question: http://stackoverflow.com/q/51349283
tags question: http://stackoverflow.com/q/51376759
tags question: http://stackoverflow.com/q/51348636
tags question: http://stackoverflow.com/q/51346710
tags question: http://stackoverflow.com/q/51428230
tags question: http://stackoverflow.com/q/51332972
tags question: http://stackoverflow.com/q/51366404
tags question: http://stackoverflow.com/q/51384053
tags question: http://stackoverflow.com/q/51325444
tags question: http://stackoverflow.com/q/51424613
tags question: http://stackoverflow.com/q/51355691

http://stackoverflow.com/comment/89657825
type: QuestionComment
has text: Edit your question and paste your code there. Dont forget to format your code (with Ctrl+K for example)!
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51342162

http://stackoverflow.com/q/51476150
has answer: http://stackoverflow.com/a/51476329
type: AnsweredQuestion
score: 3
upvote count: 3
has body: apologies my multiple attempts looking through SO have been in vain. I need some assistance with the below: I have a df as follows : import pandas as pd df = pd.DataFrame({'subject' : ['Eng' ,'Math', 'Science'], 'role' : ['Teacher', '', 'Dr'], 'ID' : ['123', '444', 'NaN'] }) print(df) ID role subject 0 123 Teacher Eng 1 444 Math 2 NaN Dr Science As this is potentially unvalidated data, what I would usually do (in excel boo) is to create a memo field which aggregates the data and does not potentially damage any good data on upload. so I've been toying with itterrows to try to loop through the df and merge the fields into one. The caveat being that I need to use /n to separate the values in the same column (CHAR(10) for you excel buffs) so I've tried.. for index, row in df2.iterrows(): if row['ID'] and row['subject] and row['role'] == "": #search row for any data while leaving out blanks row['C_MEMO'] = row'ID', 'subject', 'role' else: pass but this isn't really working, any advice/help would be appreciated. my desired output: ID role subject C_MEMO 0 123 Teacher Eng 123, Teacher Eng 1 444 Math 444, Math 2 NaN Dr Science Dr, Science things to consider: I'm working with multiple data types. I'm happy to have the new output as a string.
has answer: http://stackoverflow.com/a/51476569
type: Question
has answer: http://stackoverflow.com/a/51476462
downvote count: 0
answer count: 3
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51476462
favorite count: 0
possible better answer: http://stackoverflow.com/a/51476329
has title: merge multiple string values into one df column
tagged with: python

http://stackoverflow.com/a/51356540
score: 0
type: Answer
has body: Here's a solution that generates a random number (0, 1) and then subtracts the probabilities to find which value to return. import random def choose_with_probability(probs, values): val = random.random() for x in enumerate(values): val -= probs[x[0]] if(val &lt; 0): return x[1] # probs = [0.5, 0.2, 0.1, 0.1, 0.05, 0.05] # values = ['a', 'b', 'c', 'd', 'e', 'f'] The result is 'a' being returned 50% of the time, 'b' 20%, 'c' 10% etc. random.random() returns a number from 0 to 1. enumerate() creates a numbered list from the argument list. e.g. ['a', 'b', 'c'] becomes [[0, 'a'], [1, 'b'], [2, 'c']]. I used the enumeration index to find the probability of each value since both lists correspond 1:1.
answers question: http://stackoverflow.com/q/51356352

http://stackoverflow.com/comment/89674638
score: 0
comment on: http://stackoverflow.com/q/51350907
has text: Because when i want save them as normal i get error saying:"Failed to save 'views.py': Insufficient permissions. Select 'Retry as Admin' to retry as administrator." so then i have to save them as admin ... the folder is located in Documents
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89686892
score: 0
type: QuestionComment
type: Comment
has text: Do you also want a way to convert your condensed version back to a normal list?
comment on: http://stackoverflow.com/q/51357333

http://stackoverflow.com/a/51430913
type: Answer
answers question: http://stackoverflow.com/q/51430857
upvote count: 1
has body: You want to use a pandas dataframe and then you can filter very easily based on the columns. import pandas as pd df = pd.DataFrame(movie_data[1:],columns = movie_data[0]) movie_title director_name color duration actor_1_name language country title_year 0 Avatar James Cameron Color 178 CCH Pounder English USA 2009 1 Pirates of the Caribbean: At World\'s End Gore Verbinski Color 169 Johnny Depp English USA 2007 2 Spectre Sam Mendes Color 148 Christoph Waltz English UK 2015 df[df.country == "USA"] movie_title director_name color duration actor_1_name language country title_year 0 Avatar James Cameron Color 178 CCH Pounder English USA 2009 1 Pirates of the Caribbean: At World\'s End Gore Verbinski Color 169 Johnny Depp English USA 2007
score: 1
downvote count: 0

http://stackoverflow.com/comment/89636091
comment on: http://stackoverflow.com/q/51330160
score: 0
has text: Your (own?) definition of `\W` does not make sense. It would match the character code created with `\x41` but not one with `A` ... Its most basic definition, however, is very clear: *not one of the characters matched by `\w`*.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89636581
type: Comment
type: QuestionComment
has text: Nope https://repl.it/repls/HilariousAppropriateMap
comment on: http://stackoverflow.com/q/51330256
score: 0

http://stackoverflow.com/comment/89672478
has text: please can you add a sample of the xml you are parsing ?
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51349893

http://stackoverflow.com/q/51429740
downvote count: 0
favorite count: 0
upvote count: 3
tagged with: python
tagged with: setup.py
accepted answer: http://stackoverflow.com/a/51429803
type: AnsweredQuestion
score: 3
has body: I have a Python project that uses an executable file. The package structure is something like that: /Project /Package __init__.py aClass.py executableFile LICENSE README.md and I've this setup.py: ... setup( author=... author_email=.... classifiers=[...] description=.... install_requires=[...] license=.. long_description=... include_package_data=True packages=find_packages(include=['Package*']) url=.. version=x.x.x ) but when I upload the package as stated here with twine in PyPI, the executable file is not loaded. How can I properly include that file in the package? PS: I've also read about adding scripts=[..] in setup.py, but it is limited to python files.
tagged with: executable
has title: How to include an executable file in setup.py
tagged with: pypi
type: Question
has answer: http://stackoverflow.com/a/51429803
answer count: 1

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

http://stackoverflow.com/q/51347587
has body: I am currently trying to complete the Django 2.0 tutorial Poll application. I am using Django version 2.0.7 and Python 3.7.0. I have set up a virtual environment for this project. I am very new to Django so apologies if my terminology is incorrect. Basically, I cant get part 1 to work. I have tried numerous times to run it and I cant seem to figure out why it wont work. Before I create the Polls app the site runs correctly and I get the rocket ship, however after I create the app, update polls/views.py, create the polls/urls.py file and update the mysite/urls.py, I get the following error: Page not found (404) Request method GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: polls/ admin/ The empty path didn't match any of these. I thought my code was incorrect, so I copied and pasted the code from the website directly and tried to run it. It still wont work. Below is the code I am trying and the directory layout. Any help would be greatly appreciated. I'm sure I am just missing something simple. Thank you. mysite/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] polls/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] polls/views.py from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") Directory of C:\Users\ad\Documents\projects\mysite\msenv\mysite\mysite print.txt settings.py urls.py wsgi.py init.py pycache Directory of C:\Users\ad\Documents\projects\mysite\msenv\mysite\polls admin.py apps.py migrations models.py tests.py urls.py views.py init.py pycache
has answer: http://stackoverflow.com/a/51347762
type: Question
tagged with: django
tagged with: python
answer count: 1
has title: why is Django giving me a 404 error
score: 0
has comment: http://stackoverflow.com/comment/89684756
accepted answer: http://stackoverflow.com/a/51347762
has comment: http://stackoverflow.com/comment/89667885
tagged with: python-3.7
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89667997

http://stackoverflow.com/comment/110692883
comment on: http://stackoverflow.com/a/53390752
score: 0
type: AnswerComment
has text: Yes, you are right. It could be edited to SelectableGridItem or similar.
type: Comment

http://stackoverflow.com/a/51366721
has body: Just do an element wise multiplication and then sum the rows: (A * B).sum(axis=1) # array([16, 6, 8]) Or use np.einsum: np.einsum('ij,ij-&gt;i', A, B) # array([16, 6, 8])
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/51366648
downvote count: 0
answers question: http://stackoverflow.com/q/51366648
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89706170

http://stackoverflow.com/a/51446784
has comment: http://stackoverflow.com/comment/89907697
type: Answer
answers question: http://stackoverflow.com/q/51446661
score: 0
has body: Perhaps you're looking for a flattened list or a flattened tuple? Not clear from your question, so I'll just include everything. In [79]: val1 = [1,2,3] In [80]: val2=[4,5,6] In [81]: [(i, a, b) for i, (a,b) in enumerate(zip(val1,val2))] Out[81]: [(0, 1, 4), (1, 2, 5), (2, 3, 6)] In [82]: [k for j in [(i, a, b) for i, (a,b) in enumerate(zip(val1,val2))] for k in j] Out[82]: [0, 1, 4, 1, 2, 5, 2, 3, 6] In [84]: tuple(k for j in [(i, a, b) for i, (a,b) in enumerate(zip(val1,val2))] for k in j) Out[84]: (0, 1, 4, 1, 2, 5, 2, 3, 6)

http://stackoverflow.com/comment/130706879
type: AnswerComment
comment on: http://stackoverflow.com/a/66845103
has text: *"Google it to see why"* -> or just give the answer: It represents the percentage of the area under the curve (the sum of the areas of every bars is 1.0)
type: Comment
score: 3

http://stackoverflow.com/a/51530057
type: AcceptedAnswer
has body: Well, I eventually solved this, sort of... I caved and used pure matplotlib, gave up on Seaborn. The matplotlib violinplot takes an array-like positions argument which when passed numeric values, auto-scales the x-axis and behaves exactly as plt.plot or any plot where marker position and axis range are derived from the input data. I still used seaborn.set() to get the nice Seaborn aesthetic. There is matplotlib violin plot customization documentation which has nice examples of how to edit the details of the violins which allowed me to customize the violins and mimic all parts of the Seaborn violin plot.
type: Answer
score: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51412287
answers question: http://stackoverflow.com/q/51412287
has comment: http://stackoverflow.com/comment/122477556
upvote count: 3

http://stackoverflow.com/a/51473837
has body: text = input("Please give your text:") list.extend(list(text)) print (list)
upvote count: 1
downvote count: 1
score: 0
has comment: http://stackoverflow.com/comment/89916016
type: Answer
answers question: http://stackoverflow.com/q/51473572

http://stackoverflow.com/comment/89738123
comment on: http://stackoverflow.com/a/51383073
type: AnswerComment
type: Comment
has text: Yes, that answers it! Thanks!
score: 0

http://stackoverflow.com/a/51444612
type: Answer
has comment: http://stackoverflow.com/comment/113323054
has comment: http://stackoverflow.com/comment/89861047
downvote count: 0
answers question: http://stackoverflow.com/q/51444413
score: 5
has body: Install missing matplotlib qt5 backend sudo apt-get install python-matplotlib-qt5 Get the Matplotlib config file path: python import matplotlib matplotlib.matplotlib_fname() u'/usr/lib64/python3.6/site-packages/matplotlib/mpl-data/matplotlibrc' In the config file, change the backend to qt5agg vi /usr/lib64/python3.6/site-packages/matplotlib/mpl-data/matplotlibrc Change the line to : backend : qt5agg
upvote count: 5
has comment: http://stackoverflow.com/comment/134279558

http://stackoverflow.com/comment/89642728
comment on: http://stackoverflow.com/a/51333691
score: 1
type: AnswerComment
has text: I think you misunderstood linear regression too. Typically linear regression is not done over batches but it considers data as a whole and uses some solving technique (pseudo-inverse/GD whatever). The above code is exactly linear regression with "batched" stochastic gradient descent.
type: Comment

http://stackoverflow.com/q/51481895
duplicate of: http://stackoverflow.com/q/15028648
tagged with: gitlab
favorite count: 0
answer count: 0
type: UnansweredQuestion
score: 5
has title: ModuleNotFoundError: No module named 'gitlab'
tagged with: python
downvote count: 1
upvote count: 6
has body: For some reason I'm coming across this error ModuleNotFoundError: No module named 'gitlab' after installing python-gitlab. I installed it via... start venv with source venv/bin/activate sudo pip install --upgrade python-gitlab (as per python-gitlab docs) Also tried pip install python-gitlab (after pip uninstall of previous) Followed by a pip freeze &gt; requirements.txt Then an import gitlab at the top of my page The output after the installation is... Collecting python-gitlab Requirement not upgraded as not directly required: six in ./venv/lib/python3.6/site-packages (from python-gitlab) (1.11.0) Requirement not upgraded as not directly required: requests&gt;=2.4.2 in ./venv/lib/python3.6/site-packages (from python-gitlab) (2.13.0) Installing collected packages: python-gitlab Successfully installed python-gitlab-1.5.1 I'm using Python 3.6.4. What am I doing wrong?
type: Question
linked to: http://stackoverflow.com/q/15028648

http://stackoverflow.com/q/51403325
accepted answer: http://stackoverflow.com/a/51403410
has title: How can I query a pandas dataframe for a specific value without knowing its index
tagged with: pandas
tagged with: python
answer count: 4
favorite count: 0
tagged with: python-3.x
upvote count: 2
has answer: http://stackoverflow.com/a/51403410
has answer: http://stackoverflow.com/a/51403405
downvote count: 1
tagged with: indexing
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51403695
score: 1
tagged with: dataframe
has body: I have the following simple pandas dataframe. import pandas as pd import numpy as np data = [['5A', 10], ['5B', 20], ['5C', 30], ['5D', 40]] df = pd.DataFrame(data, columns=['Name', 'Values']) print(df) which yields Name Values 0 5A 10 1 5B 20 2 5C 30 3 5D 40 I want to select the value of Values at the position of Name=5B, which should be 20. At first I implemented the following command; mask = df['Name'] == '5B' test = df.loc[mask].Values print(test) which yielded the following Values 1 20 However, this is a dataframe and not a value and I only want the value! I can do the following to transform it into a value, but it requires a-priori knowledge of the index. test = df.loc[mask].Values[1] As mentioned, the user will never know the index of the value, they just know the value that should be queried. With knowledge that only one value will be selected I can transform it into an array as shown and from that I know the value will always be at index 0 of the array; however, there has got to be a more elegant solution. test = np.array(df.loc[mask].Values)[0] print(test) 20 If anyone has a more elegant solution that does not involve having to create a un-needed array I would appreciate it.
has comment: http://stackoverflow.com/comment/89777605
type: Question
has answer: http://stackoverflow.com/a/51404766
possible better answer: http://stackoverflow.com/a/51403695

http://stackoverflow.com/q/51327881
tagged with: python-2.7
score: 0
possible better answer: http://stackoverflow.com/a/51688467
has title: Twython - get the latest direct message
answer count: 2
tagged with: api
has answer: http://stackoverflow.com/a/51688467
accepted answer: http://stackoverflow.com/a/51689046
has body: I need to get the latest direct message from any user. What I already tried is: #importing twython and creating session..... #api is the sessions name results = api.cursor(api.get_direct_messages) but the api only allows 15 requests per 15 minutes and get_direct_messages uses all of them... So I can do api.get_direct_messages only once... So is there a way to get only the latest/newest direct message from any user? (And not using all of the 15 requests at once)? Edit/Solution: It turned out that there is no real solution to this problem because in order to get the latest message you have to find out it's id via get_direct_messages() which I don't want to use.
tagged with: python
tagged with: twython
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51689046

http://stackoverflow.com/q/51460733
has answer: http://stackoverflow.com/a/51464004
tagged with: binary-search-tree
has body: I'm trying to understand following binary search tree node insertion implementation in Python. I have placed a few print statements within the insert function. I could understand the first two prints generated by two insert calls but I couldn't understand third print generated seems before 3rd insert call. The implementation with debug prints looks as follows: class Node: def __init__(self, value): self.value = value self.left = None self.right = None def insert(root, node): if root is None: root = node return root if node.value &lt; root.value: root.left = insert(root.left, node) print("left: " + str(root.left.value)) if node.value &gt; root.value: root.right = insert(root.right, node) print("right: " + str(root.right.value)) return root root = Node(50) insert(root, Node(10)) insert(root, Node(2)) insert(root, Node(80)) insert(root, Node(15)) insert(root, Node(60)) insert(root, Node(90)) The code prints: left: 10 left: 2 left: 10 right: 80 right: 15 left: 10 left: 60 right: 80 right: 90 right: 80 My understanding so far: insert(root, Node(10)) (i) __init__ with value = 10 called. Since root is already set to 50, program gets inside second if condition with 10&lt;50. (ii) recursive insert function is called with root.left as None and node value as 10. Since root.left is None now, program gets in to first if condition and root gets value 10. This finishes the recursive call and program executes next statement which is print("left: " + str(root.left.value)) this prints 10. Program evaluates third if condition as false as expected and finishes the function call for the insertion of 10. insert(root, Node(2)) (i) __init__ with value=2 called. Program gets inside second if condition with 2&lt;50. (ii) recursive insert function is called with root.left as 10 and node value as 2. Program again gets in to second if condition with 2&lt;10. (iii) recursive insert function is called again with root.left as None and value as 2. Now program gets in to first if condition and root …
tagged with: python
accepted answer: http://stackoverflow.com/a/51460903
type: AnsweredQuestion
has title: Understanding binary search tree insertion using Python
has comment: http://stackoverflow.com/comment/89890753
type: Question
downvote count: 0
score: 4
has answer: http://stackoverflow.com/a/51460903
upvote count: 4
answer count: 2
has comment: http://stackoverflow.com/comment/89900335
possible better answer: http://stackoverflow.com/a/51464004
favorite count: 0

http://stackoverflow.com/comment/89650013
type: QuestionComment
has text: I tried 256 X 256 it did work, but it is highly possibily in trading of prediction acurracy. I am just kind of wondering that which kind of machine can do this kind of task.
comment on: http://stackoverflow.com/q/51337578
score: 0
type: Comment

http://stackoverflow.com/q/51366031
has answer: http://stackoverflow.com/a/51366474
linked to: http://stackoverflow.com/q/51423972
has body: I can't figure out how to correctly feed training data to a functional keras model. I have two input types: Image data and float numbers, each number belonging to one image. This data is classified into 6 classes. How do I need to format my input data and how do I need to define it in my keras network? The image data is analyzed by a CNN and should then be concatenated with the float numbers. Afterwards, three dense layers are used for classification. There doesn't seem to be an example or tutorial that is similar to my problem.
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51366474
has title: Format mutiple inputs with mutiple categories for a functional keras model and feed it to the model
tagged with: tensorflow
type: Question
score: 0
answer count: 1
tagged with: keras

http://stackoverflow.com/q/51448741
tagged with: flask
tagged with: flask-sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/89867959
has title: Flask and SQLAlchemy db.session.commit() is not working properly on updates
tagged with: python
score: 0
answer count: 1
tagged with: mysql
type: UnansweredQuestion
has body: Just trying to update a username but it isn't updating in the database even though current_user.username has updated. I'm using mySQL, SQLAlchemy and flask. @app.route('/account', methods = ['GET', 'POST']) @login_required def account(): form = UpdateAccountForm() if form.validate_on_submit(): current_user.username = form.username.data db.session.commit() flash(f"Updated Account information, welcome {form.username.data}, {current_user.username},", 'success') return redirect(url_for('account')) elif request.method == 'GET': form.username.data = current_user.username return render_template('account.html', title='Account', form=form) class UpdateAccountForm(FlaskForm): username = StringField('Username', validators=[DataRequired(), Length(min=4, max=20)]) submit = SubmitField('Update') def validate_username(self, username): if username.data != current_user.username: user = db.session.query(models.User).filter_by(username=username.data).first() if user: raise ValidationError('That username is taken. Please choose another.') return user
has comment: http://stackoverflow.com/comment/89872117
tagged with: sqlalchemy
has answer: http://stackoverflow.com/a/62044392
has comment: http://stackoverflow.com/comment/90742612

http://stackoverflow.com/a/51477738
has comment: http://stackoverflow.com/comment/89925702
has comment: http://stackoverflow.com/comment/89924402
has comment: http://stackoverflow.com/comment/89924755
downvote count: 0
has comment: http://stackoverflow.com/comment/89924498
has comment: http://stackoverflow.com/comment/89925225
has comment: http://stackoverflow.com/comment/89925368
has comment: http://stackoverflow.com/comment/89925081
type: Answer
answers question: http://stackoverflow.com/q/51477628
has comment: http://stackoverflow.com/comment/89924688
has comment: http://stackoverflow.com/comment/89924013
has comment: http://stackoverflow.com/comment/89925006
has body: Why you dont use builtin django Select? from django import forms &gt;&gt;&gt; CHOICES = (('1', 'First',), ('2', 'Second',)) &gt;&gt;&gt; choice_field = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES) &gt;&gt;&gt; choice_field.choices [('1', 'First'), ('2', 'Second')] &gt;&gt;&gt; choice_field.widget.choices [('1', 'First'), ('2', 'Second')] &gt;&gt;&gt; choice_field.widget.choices = () &gt;&gt;&gt; choice_field.choices = (('1', 'First and only',),) &gt;&gt;&gt; choice_field.widget.choices [('1', 'First and only')] https://docs.djangoproject.com/en/2.0/ref/forms/widgets/#widgets-inheriting-from-the-select-widget EDIT: As im looking at your code you doing something pretty weird... you can defing your Form in your models and you settings the models fields in your form? i guess you missplacing the concepts models.py from django.db import models # THIS IS YOUR MODEL, WILL BE PERSISTED IN YOUR DATABASE class Race(models.Model): ... # Here you will place fields related to the race, as name, date and etc... class CharApp(models.Model): VAMPIRE = 'VP' DRAUGR = 'DR' BAELNORN = 'BN' LICH = 'LH' SHADOW = 'SW' RACE_CHOICES = ( ('VP', 'Vampire'), ('DR', 'Draugr'), ('BN', 'Baelnorn'), ('LH', 'Lich'), ('SW', 'Shadow'), ) app_id = models.AutoField(primary_key=True) char_name = models.CharField(max_length=80, verbose_name='Character Name') race = models.ForenignKey(Race, related_name="charapp_race") date_applied = models.DateTimeField(verbose_name='Date Applied') background = models.TextField(verbose_name='Background') account_id = models.IntegerField(default=1, verbose_name='Account ID') submitted = models.BooleanField(default=False) forms.py #create this file at your app folder from django.forms import ModelForm from myapp.models import Article from .models import CharApp, RACE_CHOICES # this is your form class CharAppForm(ModelForm): # Here you can change the widget or add new fields that is not related your model form race = forms.ChoiceField(widget=forms.RadioSelect…
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/89927747
has comment: http://stackoverflow.com/comment/89924556

http://stackoverflow.com/a/51375071
type: Answer
score: 2
has body: new_list is defined as a tuple. Make it as a list by enclosing it in square brackets new_list=["a","g","x","e","s","s"] new_list.sort() print (new_list) # ['a', 'e', 'g', 's', 's', 'x']
downvote count: 0
answers question: http://stackoverflow.com/q/51374995
has comment: http://stackoverflow.com/comment/89723898
upvote count: 2

http://stackoverflow.com/a/51410974
has comment: http://stackoverflow.com/comment/89793714
has body: Say, you have some predicate function pred and a list lst. You can use itertools.dropwhile to get the first element in lst, for which pred returns True with itertools.dropwhile(lambda x: not pred(x), lst).next() It skips all elements for which pred(x) is False and .next() yields you the value for which pred(x) is True. Edit: A sample use to find the first element in lst divisible by 5 &gt;&gt;&gt; import itertools &gt;&gt;&gt; lst = [1,2,10,3,5,3,4] &gt;&gt;&gt; pred = lambda x: x % 5 == 0 &gt;&gt;&gt; itertools.dropwhile(lambda x: not pred(x), lst).next() 10
score: 1
has comment: http://stackoverflow.com/comment/89793803
answers question: http://stackoverflow.com/q/51410881
has comment: http://stackoverflow.com/comment/89818065
has comment: http://stackoverflow.com/comment/89793663
has comment: http://stackoverflow.com/comment/89793742
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/89818169
downvote count: 0

http://stackoverflow.com/q/51388013
tagged with: python
has title: How can I pass an object attribute to lambda function, as function parameter?
has comment: http://stackoverflow.com/comment/89748280
answer count: 4
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/51388059
downvote count: 0
has comment: http://stackoverflow.com/comment/89748489
type: Question
linked to: http://stackoverflow.com/q/12087905
has answer: http://stackoverflow.com/a/51388059
has answer: http://stackoverflow.com/a/51388153
has comment: http://stackoverflow.com/comment/130873173
has comment: http://stackoverflow.com/comment/89748311
upvote count: 2
has comment: http://stackoverflow.com/comment/89747884
possible better answer: http://stackoverflow.com/a/51388153
has answer: http://stackoverflow.com/a/51388312
has answer: http://stackoverflow.com/a/51388053
has body: I created two functions that returns a sorted a list. Both of them take as argument a list containg instances of Employee Class. The first sorts by name attribute and the second by age and both of them use lambda function class Employee(): allEmployees = [] def __init__(self, name, age): self.name = name self.age = age Employee.allEmployees.append(self) def sortEmployeesByName(some_list, name): return sorted(some_list, key=lambda employee: employee.name) def sortEmployeesByAge(some_list, age): return sorted(some_list, key=lambda employee: employee.age) How can I create only one function sortEmployees, where I pass the attribute as the second parameter and also use lambda function? e.g. def sortEmployess(some_list, attribute): return sorted(some_list, key=lambda employee: employee.attribute)
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/51333638
type: Question
has answer: http://stackoverflow.com/a/51333677
answer count: 1
tagged with: python-3.x
linked to: http://stackoverflow.com/q/23294658
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89642675
tagged with: python
tagged with: valueerror
duplicate of: http://stackoverflow.com/q/23294658
has title: How do i handle ValueError in this code Python?
score: 0
has comment: http://stackoverflow.com/comment/89642650
tagged with: error-handling
tagged with: loops
has body: I've done this before but i think this error is showing up because I'm not looping the code, the code works only once then on the second attempt is shows an error. My Code: import string import time def timer(x): for n in range(x,0,-1): time.sleep(1) print(n) print("Times Up"+"\n") ask("Time for: ") def ask(a): x=int(input(str(a))) print("\n"+"Clock's Ticking") timer(x) try: ask("Time for: ") except ValueError: ask("Enter a number to time: ") I want my code to not error when i put in something that isnt a integer for the time but dont know how to loop the exception code until the user enters a integer.

http://stackoverflow.com/comment/132643044
has text: Thanks -- any idea about inter-operability between `pyrubberband`/`librosa` and `pydub`?
type: Comment
comment on: http://stackoverflow.com/a/59269959
type: AnswerComment
score: 0

http://stackoverflow.com/q/51353928
score: 7
type: Question
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51353959
has body: I want to get the value of the lookup list instead of a boolean. I have tried the following codes: val = pd.DataFrame(['An apple','a Banana','a cat','a dog']) lookup = ['banana','dog'] # I tried the follow code: val.iloc[:,0].str.lower().str.contains('|'.join(lookup)) # it returns: 0 False 1 True 2 False 3 True Name: 0, dtype: bool What I want: 0 False 1 banana 2 False 3 dog Any help is appreciated.
tagged with: pandas
tagged with: python
has title: Extract string if match the value in another list
favorite count: 0
upvote count: 7
has answer: http://stackoverflow.com/a/51353959
type: AnsweredQuestion

http://stackoverflow.com/comment/89731524
score: 0
type: Comment
type: QuestionComment
has text: Glad to see @mahesh is helping you out. Please be sure to accept (and hopefully upvote) his answer if it helps you out.
comment on: http://stackoverflow.com/q/51360609

http://stackoverflow.com/q/51461177
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/89891600
downvote count: 3
type: Question
has body: We know how bool() acts on various python objects such as str, int, list. This is a question about the reverse. You can cast bool to int as &gt;&gt;&gt; int(True) 1 &gt;&gt;&gt; int(False) 0 which I think kinda makes sense, but with string we get &gt;&gt;&gt; str(False) 'False' &gt;&gt;&gt; str(True) 'True' which I don't get, as firstly it seems to imply some relation between False and 'False', which only seems relevant at the code level. If what is written in code is to be treated this way, how does this work ... &gt;&gt;&gt; str(not True) 'False' Second, it's not obvious it's for consistency, as &gt;&gt;&gt; bool(str(False)) True My question is ... is there a reason we're allowed to cast bool to str in this way? list for example won't allow it ... &gt;&gt;&gt; list() [] &gt;&gt;&gt; bool() False &gt;&gt;&gt; bool(list()) False &gt;&gt;&gt; list(bool()) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'bool' object is not iterable
accepted answer: http://stackoverflow.com/a/51461208
has answer: http://stackoverflow.com/a/51461326
has answer: http://stackoverflow.com/a/51461207
has comment: http://stackoverflow.com/comment/89892073
has answer: http://stackoverflow.com/a/51461238
has answer: http://stackoverflow.com/a/51461208
score: 0
has comment: http://stackoverflow.com/comment/89891642
has comment: http://stackoverflow.com/comment/89891609
tagged with: truthiness
favorite count: 0
has comment: http://stackoverflow.com/comment/89891627
has comment: http://stackoverflow.com/comment/89891602
has title: Why can we cast bool to str?
tagged with: python
answer count: 4
linked to: http://stackoverflow.com/q/39983695
possible better answer: http://stackoverflow.com/a/51461238

http://stackoverflow.com/q/51423024
score: 1
favorite count: 0
type: Question
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/51423678
tagged with: java
upvote count: 1
accepted answer: http://stackoverflow.com/a/51423678
downvote count: 0
has body: I'm having troubles converting a Multiset Class in java to Python. Im having a particular problem with this this piece of Java-Code to Python: public Multiset unionWith(Multiset other) { Multiset result = new Multiset(); for ( Object object : elts.keySet() ) { for ( int i = 0; i != elts.get(object); ++i ) { result.add(object); } } for ( Object object : other.elts.keySet() ) { for ( int i = 0; i != other.elts.get(object); ++i ) { result.add(object); } } return result; } } This is the entire Class I have made. Everything seems to work except unionWith, Which I can't figure out.I'm pretty sure the problem is with the 'in range', with a condition. How does this work in python? class Multiset: def __init__(self): self.elts= dict() def contains(self, o): if o in self.elts.keys(): return True else: return False def add(self, o): if self.contains(o): newValue = self.elts.get(o) + 1 self.elts[o] = newValue else: self.elts[o] = 1 def remove(self, o): if self.contains(o): newValue = self.elts.get(o) - 1 if newValue &gt; 0: self.elts[o] = newValue else: del self.elts[o] def elements(self): return set(self.elts.keys()) @property def size(self): total = 0 for object in self.elts.values(): total = total + self.elts.get(object) return total def unionWith(self,other): result= Multiset() for object in self.elts.values(): for i in range(0): if i is not self.elts.get(object): break result.add(object) for object in other.elts.values(): for i in range(0): if i is not other.get(object): break result.add(object)
has title: union multiset javaCode to python (in range)
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89816933

http://stackoverflow.com/comment/89745880
type: Comment
type: QuestionComment
score: 0
has text: Requirement already satisfied and a directory.
comment on: http://stackoverflow.com/q/51381763

http://stackoverflow.com/comment/89713241
has text: Or `np.lexsort(np.fliplr(a).T)`, can be handy.
type: AnswerComment
comment on: http://stackoverflow.com/a/51370382
type: Comment
score: 1

http://stackoverflow.com/q/51373300
possible better answer: http://stackoverflow.com/a/51374269
has answer: http://stackoverflow.com/a/51374269
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/51375562
answer count: 4
tagged with: tree
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51381493
has answer: http://stackoverflow.com/a/77760770
tagged with: javascript
linked to: http://stackoverflow.com/q/38310065
has title: How to convert Newick tree format to a tree-like hierarchical object?
tagged with: logic
has answer: http://stackoverflow.com/a/51375562
has body: I want to convert a Newick file to a hierarchical object (similar to what has been posted in this post) in Python. My input is a Newick file like this: (A:0.1,B:0.2,(C:0.3,D:0.4)E:0.5)F:0.9 The original post parses the string character by character. To store the branch lengths also, I have modified the JavaScript file (from here) as follows: var newick = '// (A:0.1,B:0.2,(C:0.3,D:0.4)E:0.5)F:0.9', stack = [], child, root = [], node = root; var na = ""; newick.split('').reverse().forEach(function(n) { switch(n) { case ')': // ')' =&gt; begin child node if (na != "") { node.push(child = { name: na }); na = ""; } stack.push(node); child.children = []; node = child.children; break; case '(': // '(' =&gt; end of child node if (na != "") { node.push(child = { name: na }); na = ""; } node = stack.pop(); // console.log(node); break; case ',': // ',' =&gt; separator (ignored) if (na != "") { node.push(child = { name: na }); na = ""; } break; default: // assume all other characters are node names // node.push(child = { name: n }); na += n; break; } }); console.log(node); Now, I want to translate this code to Python. Here's my attempt (I know it's incorrect): class Node: def __init__(self): self.Name = "" self.Value = 0 self.Children = [] newick = "(A:0.1,B:0.2,(C:0.3,D:0.4)E:0.5,G:0.8)F:0.9" stack = [] # root = [] # node = [] for i in list(reversed(newick)): if i == ')': if na != "": node = Node() node.Name = na child.append(node) na = "" stack.append(node) # insert logic child = node.Children # child.append(child) elif i == '(': if (na != ""): child = Node() child.Name = na node.append(child) na = "" node = stack.pop() elif i == ',': if (na != ""): node = Node() node.Name = na node.append(child) na = "" else: na += n Since I am totally new to JavaScript, I am having trouble 'translating' the code to Python. In particular, I didn't understand the following lines: child.children = []; node = child.children; How can I correctly write this in Python, to also extract the lengths?
downvote count: 0
score: 1
tagged with: parsing
favorite count: 0

http://stackoverflow.com/comment/89775576
type: Comment
type: QuestionComment
has text: @JoyWang yes , the region of the storage
comment on: http://stackoverflow.com/q/51389000
score: 0

http://stackoverflow.com/comment/89817483
score: 0
comment on: http://stackoverflow.com/q/51423255
has text: 1) The code in the error message is different from the code in your question; please decide which code you want to use and what error it produces; 2) what _is_ `item[0]`? What do you expect it to be?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89699021
has text: now, looks good, please provide me error stack in details.
score: 0
comment on: http://stackoverflow.com/q/51363335
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89847376
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51438253
score: 1
has text: Not possible no, you should store your keys somewhere or use vtkFieldData instead

http://stackoverflow.com/a/51383561
downvote count: 0
has body: It's a good question. Actually it would be nice, if someone could explain how to do this. But in addition i can say you, that it would come to "catastrophic forgetting", so it wouldn't work out. You had to train all your data again. But anyway, i also would like to know that espacially for ssd, just for test reasons.
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/111491198
answers question: http://stackoverflow.com/q/51379506
score: 3

http://stackoverflow.com/comment/89854199
comment on: http://stackoverflow.com/q/51441450
type: QuestionComment
has text: If the `-` isn't needed at any other time during the lifespan of these files, I would just write a little script that batch edits the files to remove the extra characters (or, if you control the process that generates the files in the first place, find out where the `-` is being added and get rid of it!).
score: 0
type: Comment

http://stackoverflow.com/a/51351253
type: Answer
has comment: http://stackoverflow.com/comment/89681263
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51333379
answers question: http://stackoverflow.com/q/51333379
has body: I was originally going to leave this in a comment, but my answer started to become a bit long, so here it is... Only two parameters can be specified for MutableMapping: _KT and _VT. This extra _T parameter, then, remains unspecified. How does the type checker go about resolving this 3rd type...? As @jonrsharpe basically said, _T is not a class type parameter, it's a function type parameter. Basically, when you call that method, mypy will have: Already bound _KT and _VT to some other type. So, if we do foo: MutableMapping[str, int] = ... then call foo.pop(...), mypy will understand that _KT and _VT are bound to str and int respectively at the time we call pop. Mypy will additionally notice that we have a free (aka unbound) type parameter floating around if we call the second overload. It will then attempt to infer what the correct type of _T is based on whatever value we pass in/the surrounding context. For example, suppose I do foo.pop("x", "bar"). This matches the second overload. We also previously said that _KT and _VT are bound to str and int respectively. Mypy then notices that _T is unbound and tries to infer an appropriate type. Here, we know that the value we're passing in is of type "str" and that the parameter type is Union[int, _T] (after substituting in the bound types). We also know that the value we pass in must be a subtype of the parameters -- we know that str must be a subtype of Union[int, _T]. Mypy then runs an inference algorithm using all of the above info/all of the known constraints and is able to infer in this case that _T must be of type str. (As a side note, mypy's inference algorithm here isn't perfect. It may sometimes fail to infer the correct type if the expression is particularly complex/currently doesn't correctly handle certain edge cases.) If you want a more detailed description of how exactly mypy's type inference algorithm works, you can try spelunking through mypy's codebase. Specifically, mypy calls this function which in turn c…

http://stackoverflow.com/a/54476537
answers question: http://stackoverflow.com/q/51469194
has body: An alternative way to install PyTorch is the following steps: conda create -n pytorch_env python=3 source activate pytorch_env conda install pytorch-cpu torchvision -c pytorch Go to python shell and import using the command import torch
score: 0
type: Answer

http://stackoverflow.com/q/51410836
score: 0
tagged with: python
tagged with: python-3.x
has body: Suppose I have a function that takes several seconds to compute and I have 8 CPUs (according to multiprocessing.cpu_count()). What happens when I start this process less than 8 times and more than 8 times? When I tried to do this I observed that even when I started 20 processes they were all running parallel-y. I expected them to run 8 at a time, others will wait for them to finish.
tagged with: multiprocessing
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89793229
type: Question
has answer: http://stackoverflow.com/a/51410899
accepted answer: http://stackoverflow.com/a/51410899
has title: Python: Does `multiprocessing.Process(...).start()` start all processes on the same cpu?
answer count: 1

http://stackoverflow.com/q/51462333
linked to: http://stackoverflow.com/q/40179804
has body: Is there any way to call an Excel WorksheetFunction in Python win32com or any other libraries? I would like to use formulas like VLookup/Match/Index/SumIfs in Python.
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51464148
tagged with: excel-formula
tagged with: python
tagged with: excel
linked to: http://stackoverflow.com/q/41172580
has title: Python win32com on Microsoft Excel WorksheetFunction
type: AnsweredQuestion
score: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/51464148
type: Question
linked to: http://stackoverflow.com/q/11213045
tagged with: win32com

http://stackoverflow.com/comment/89893159
comment on: http://stackoverflow.com/q/51461963
score: 0
type: Comment
type: QuestionComment
has text: Normally, you wouldn't want a server to call `input()`. It should be getting its inputs from the clients. If you _do_ need to take input from the user running the server, you will want to either want to move all the server stuff onto a background thread, or put `sys.stdin` into non-blocking mode so you can throw it into the same `selectors` or `asyncio` or whatever loop that you're using for the server. (Without even the vaguest idea of how you implemented your server, it's hard to say anything more specific than that.)

http://stackoverflow.com/a/51332126
score: 1
accepted answer of: http://stackoverflow.com/q/51331028
answers question: http://stackoverflow.com/q/51331028
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: As mentioned this can be achieved with selenium once you have the correct geckodriver installed the following should get you on the right track: from bs4 import BeautifulSoup from selenium import webdriver driver = webdriver.Firefox() driver.get('https://clockofeidolon.com') html = driver.page_source soup = BeautifulSoup(html,'lxml') spans = soup.find_all(class_='big-hour') for span in spans: print(span.text) driver.quit()
type: Answer

http://stackoverflow.com/q/51451230
accepted answer: http://stackoverflow.com/a/51458960
possible better answer: http://stackoverflow.com/a/51451677
has body: I have the following code, in which I simply have a decorator for caching a function's results, and as a concrete implementation, I used the Fibonacci function. After playing around with the code, I wanted to print the cache variable, that's initiated in the cache wrapper. (It's not because I suspect the cache might be faulty, I simply want to know how to access it without going into debug mode and put a breakpoint inside the decorator) I tried to explore the fib_w_cache function in debug mode, which is supposed to actually be the wrapped fib_w_cache, but with no success. import timeit def cache(f, cache = dict()): def args_to_str(*args, **kwargs): return str(args) + str(kwargs) def wrapper(*args, **kwargs): args_str = args_to_str(*args, **kwargs) if args_str in cache: #print("cache used for: %s" % args_str) return cache[args_str] else: val = f(*args, **kwargs) cache[args_str] = val return val return wrapper @cache def fib_w_cache(n): if n == 0: return 0 elif n == 1: return 1 else: return fib_w_cache(n-2) + fib_w_cache(n-1) def fib_wo_cache(n): if n == 0: return 0 elif n == 1: return 1 else: return fib_wo_cache(n-1) + fib_wo_cache(n-2) print(timeit.timeit('[fib_wo_cache(i) for i in range(0,30)]', globals=globals(), number=1)) print(timeit.timeit('[fib_w_cache(i) for i in range(0,30)]', globals=globals(), number=1))
downvote count: 0
tagged with: decorator
has answer: http://stackoverflow.com/a/51451677
favorite count: 0
tagged with: python-3.x
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/51453535
has answer: http://stackoverflow.com/a/51453774
has title: Getting the value of a mutable keyword argument of a decorator
tagged with: python-decorators
has comment: http://stackoverflow.com/comment/89872864
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89872932
has comment: http://stackoverflow.com/comment/89872911
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/51453384
type: Question
has answer: http://stackoverflow.com/a/51458960
has comment: http://stackoverflow.com/comment/89872839
has comment: http://stackoverflow.com/comment/89876544

http://stackoverflow.com/comment/89770412
comment on: http://stackoverflow.com/a/51399779
has text: @NickA. OP has mentioned `duplicated pairs of numbers` in the title :)
type: AnswerComment
type: Comment
score: 2

http://stackoverflow.com/q/51454239
has comment: http://stackoverflow.com/comment/89879470
has body: I am running the following code: import cv2 import numpy f = open("raw_image",'rb') raw_image = f.read(720 * 1280 * 3) image = numpy.fromstring(raw_image, dtype='uint8') image = image.reshape((720, 1280, 3)) cv2.imshow('Image', image) cv2.waitKey(0) cv2.destroyAllWindows() cv2.waitKey(1) and I get this result: the image is RGB image with height of 720p and width of 1280. Any Ideas how to solve it? EDIT: I receive images from a camera with resolution of 720x1280. The image is a colored image. The file raw_image, which I read the bytes from, contains the output from the command: gst-launch-1.0 fdsrc ! h264parse ! avdec_h264 ! filesink location=/dev/stdout As you can see, the received image is malformed, and I dont know how to fix it. EDIT2: this is the raw image: https://drive.google.com/file/d/1hPRUEVNFiKmiUFbzksUlzzC04teml4hw/view?usp=sharing EDIT3: after running the code (NOTE: I am displaying only the first 720*1280 bytes): raw_image = f.read(720 * 1280 * 3) raw_image=raw_image[:720 * 1280] image=numpy.frombuffer(raw_image,dtype='uint8') image = image.reshape((720,1280)) cv2.imshow('Image', image) cv2.waitKey(0) cv2.destroyAllWindows() cv2.waitKey(1) I got this result: When I move some of the left part to the right, by adding the line: image=numpy.concatenate((image[:,141:],image[:,:141]),axis=1) I got a fine image: can it help solving the mystery?
has answer: http://stackoverflow.com/a/77775595
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89879668
has title: odd image using cv2 and numpy
answer count: 3
has answer: http://stackoverflow.com/a/77178806
tagged with: python
type: UnansweredQuestion
tagged with: opencv
type: Question
score: 0
has answer: http://stackoverflow.com/a/51458323
has comment: http://stackoverflow.com/comment/89879214
has comment: http://stackoverflow.com/comment/89885384
has comment: http://stackoverflow.com/comment/89903986

http://stackoverflow.com/comment/89875171
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51452470
has text: A quicker way to MultiIndex columns is just to use split with expand=True. `df_out.columns = df_out.columns.str.split(expand=True)`
type: AnswerComment

http://stackoverflow.com/q/51338095
has comment: http://stackoverflow.com/comment/89651213
has comment: http://stackoverflow.com/comment/89651151
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89650693
score: -6
favorite count: 0
has comment: http://stackoverflow.com/comment/89650867
tagged with: python
downvote count: 6
type: UnansweredQuestion
type: Question
has title: How to run a FOR LOOP over a csv file
has body: I am trying to run the following code over a CSV file, but the code is showing an error that the input data type should be a str and not an int, but I have checked the data type and it is a float. I have tried every conversion from string, to float, to int, but nothing seems to work. please tell me what am I doing wrong. print(stdized_data.X.dtypes) for element in stdized_data: if element != 0: log(element + 1) else: log(element + 2) ###################################OUTPUT################################ float64 -------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-163-6e534ce31c6a&gt; in &lt;module&gt;() 9 for element in stdized_data: 10 if element != 0: ---&gt; 11 log(str(element) + 1) 12 13 else: TypeError: must be str, not int I have loaded the file using pd.read_csv function.
has answer: http://stackoverflow.com/a/51338222

http://stackoverflow.com/comment/89712872
type: QuestionComment
score: 1
has text: Try this implementation of a list in Python: `list`.
comment on: http://stackoverflow.com/q/51370281
type: Comment

python
tags question: http://stackoverflow.com/q/51398843
tags question: http://stackoverflow.com/q/51371400
tags question: http://stackoverflow.com/q/51440105
tags question: http://stackoverflow.com/q/51469901
tags question: http://stackoverflow.com/q/51409852
tags question: http://stackoverflow.com/q/51338357
tags question: http://stackoverflow.com/q/51336624
tags question: http://stackoverflow.com/q/51465704
tags question: http://stackoverflow.com/q/51408379
tags question: http://stackoverflow.com/q/51443998
tags question: http://stackoverflow.com/q/51388624
tags question: http://stackoverflow.com/q/51482526
tags question: http://stackoverflow.com/q/51342007
tags question: http://stackoverflow.com/q/51465526
tags question: http://stackoverflow.com/q/51407264
tags question: http://stackoverflow.com/q/51384816
tags question: http://stackoverflow.com/q/51411156
tags question: http://stackoverflow.com/q/51389443
tags question: http://stackoverflow.com/q/51326574
tags question: http://stackoverflow.com/q/51376872
tags question: http://stackoverflow.com/q/51447695
tags question: http://stackoverflow.com/q/51424336
tags question: http://stackoverflow.com/q/51433622
tags question: http://stackoverflow.com/q/51456925
tags question: http://stackoverflow.com/q/51436036
tags question: http://stackoverflow.com/q/51446471
tags question: http://stackoverflow.com/q/51424392
tags question: http://stackoverflow.com/q/51439271
tags question: http://stackoverflow.com/q/51420925
tags question: http://stackoverflow.com/q/51408458
tags question: http://stackoverflow.com/q/51471914
tags question: http://stackoverflow.com/q/51470864
tags question: http://stackoverflow.com/q/51391797
tags question: http://stackoverflow.com/q/51477339
tags question: http://stackoverflow.com/q/51448572
tags question: http://stackoverflow.com/q/51406583
tags question: http://stackoverflow.com/q/51479486
tags question: http://stackoverflow.com/q/51480726
tags question: http://stackoverflow.com/q/51329903
tags question: http://stackoverflow.com/q/51341717
tags question: http://stackoverflow.com/q/51464999
tags question: http://stackoverflow.com/q/51470075
tags question: http://stackoverflow.com/q/51361316
tags question: http://stackoverflow.com/q/51411654
tags question: http://stackoverflow.com/q/51348100
tags question: http://stackoverflow.com/q/51452723
tags question: http://stackoverflow.com/q/51335083
tags question: http://stackoverflow.com/q/51385655
tags question: http://stackoverflow.com/q/51344368
tags question: http://stackoverflow.com/q/51327856
tags question: http://stackoverflow.com/q/51380101
tags question: http://stackoverflow.com/q/51357272
tags question: http://stackoverflow.com/q/51462420
tags question: http://stackoverflow.com/q/51341514
tags question: http://stackoverflow.com/q/51426929
tags question: http://stackoverflow.com/q/51423517
tags question: http://stackoverflow.com/q/51372741
tags question: http://stackoverflow.com/q/51331028
tags question: http://stackoverflow.com/q/51349074
tags question: http://stackoverflow.com/q/51427785
tags question: http://stackoverflow.com/q/51352527
tags question: http://stackoverflow.com/q/51434149
tags question: http://stackoverflow.com/q/51381112
tags question: http://stackoverflow.com/q/51410794
tags question: http://stackoverflow.com/q/51392046
tags question: http://stackoverflow.com/q/51457418
tags question: http://stackoverflow.com/q/51372389
tags question: http://stackoverflow.com/q/51346771
tags question: http://stackoverflow.com/q/51362759
tags question: http://stackoverflow.com/q/51445930
tags question: http://stackoverflow.com/q/51369505
tags question: http://stackoverflow.com/q/51427323
tags question: http://stackoverflow.com/q/51406913
tags question: http://stackoverflow.com/q/51420112
tags question: http://stackoverflow.com/q/51352674
tags question: http://stackoverflow.com/q/51417591
tags question: http://stackoverflow.com/q/51350812
tags question: http://stackoverflow.com/q/51377889
tags question: http://stackoverflow.com/q/51440116
tags question: http://stackoverflow.com/q/51350775

http://stackoverflow.com/q/51397124
has comment: http://stackoverflow.com/comment/89767230
has comment: http://stackoverflow.com/comment/89766423
tagged with: python
has body: I'm very much new to Python, essentially being pushed into a new project with no knowledge of the language whatsoever. I've gone over a number of tutorials to get a gist of the syntax and some of the functions, but I'm currently stumped on something that seems pretty basic. I have a class GeoLocationHandlerObj in GeoLocationSolver.py which has a method 'myMethod': class GeoLocationHandlerObj(object): def __init__(self, connector, debug=0): self._debug = debug self.locator = GeoLocationSolverObj(connector) return(None) def close(self): ... return(None) def getAdr(self, point, lang): ... return(None) def getCom(self, point, lang): ... return(None) def getHmp(self, point, lang): ... return(None) def myMethod(self): print "test" return(None) I import it and try to call myFunction: import sys import os import psycopg2 import string import json import socket import random from GeoPackage.GeoCoding.GeoLocationSolver import * if __name__ == "__main__": connector = GeoPSConnectorObj(...) handler = GeoLocationHandlerObj(connector) handler.myMethod() When I run this code, I get the following error: AttributeError: 'GeoLocationHandlerObj' object has no attribute 'myMethod'. What am I missing in order to successfully call this method?
score: 2
has comment: http://stackoverflow.com/comment/89766737
upvote count: 2
has comment: http://stackoverflow.com/comment/89766585
has comment: http://stackoverflow.com/comment/89766372
has comment: http://stackoverflow.com/comment/89779991
type: Question
has comment: http://stackoverflow.com/comment/89768281
has comment: http://stackoverflow.com/comment/89780012
tagged with: attributeerror
has answer: http://stackoverflow.com/a/53178932
has title: Python: AttributeError: object has no attribute 'method'
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/89765302
has comment: http://stackoverflow.com/comment/89770282
answer count: 1
has comment: http://stackoverflow.com/comment/89766791
downvote count: 0
has comment: http://stackoverflow.com/comment/89767491
has comment: http://stackoverflow.com/comment/89765447
favorite count: 0
has comment: http://stackoverflow.com/comment/89766129
has comment: http://stackoverflow.com/comment/89768766
type: UnansweredQuestion

http://stackoverflow.com/comment/89711563
has text: @TomShanks it's possible you installed the library in your user's python site-packages instead of the system, since you managed to install it without using `sudo`. Run `pip3 show module_name`, what is the Location?
comment on: http://stackoverflow.com/q/51369426
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89953776
comment on: http://stackoverflow.com/a/51469429
type: AnswerComment
score: 0
type: Comment
has text: I am using spyder with anaconda. Could this be the problem? I have tried conda update --all but it doesn't seem to resolve. I get a different error everytime. Since I use anaconda, I can't use pip?

http://stackoverflow.com/comment/89684906
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51356244
has text: @BenBotvinick any suggestion , what should be the approach?
score: 0

http://stackoverflow.com/comment/89644969
type: QuestionComment
score: 0
has text: Oh wow, that worked. Thanks! However, is there a better way to do this? Writing the import sys code at the beginning of every single test program seems unnecessary.
comment on: http://stackoverflow.com/q/51334847
type: Comment

http://stackoverflow.com/comment/89881371
comment on: http://stackoverflow.com/a/51455934
has text: It only builds one executable of .py file.How I will connect multiples exe files?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/51411302
tagged with: python
type: AnsweredQuestion
tagged with: django-models
tagged with: django-forms
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/51411680
has body: My webpage looks like the following: When I press "Submit" button, the page is "redirected" to some different page. If I don't specify get_absolute_url method in my models.py, I will get ImproperlyConfigured error. If I set where to redirect to in my models.py, upon clicking the Submit button, it will be directed to that page. What I don't understand is, how does only the Submit button redirected to whatever the link I set up on my models.py? Why clicking on the links on the sidebar doesn't redirect to it? Why does get_absolute_url method acts only upon clicking Submit button, but not the others? practice_add_well.html {% extends "base.html" %} {% block content %} Test Page for BHA {% csrf_token %} {{ form.as_p }} {% endblock %} models.py from django.db import models from django.urls import reverse class WellInfo(models.Model): name = models.CharField(max_length=100) region_location = models.CharField(max_length=100) spud_date = models.CharField(max_length=100) well_bore = models.CharField(max_length=100) rig_name = models.CharField(max_length=100) status = models.CharField(max_length=100) def get_absolute_url(self): return reverse(# some link....) views.py from django.shortcuts import render from django.views.generic import View, TemplateView, ListView, DetailView, CreateView, UpdateView, DeleteView from . import models class WellInfoCreateView(CreateView): template_name = 'practice_add_well.html' context_object_name = 'bha_inputs' model = models.WellInfo fields = '__all__'
possible better answer: http://stackoverflow.com/a/65739535
score: 0
has answer: http://stackoverflow.com/a/65739535
linked to: http://stackoverflow.com/q/1200266
has title: Django - how does get_absolute_url work?
tagged with: django
has answer: http://stackoverflow.com/a/51411680

http://stackoverflow.com/comment/89665213
type: Comment
comment on: http://stackoverflow.com/a/51336176
has text: @sal use `data_in = open('MY FILENAME', 'r').read()`, it should work.
type: AnswerComment
score: 0

http://stackoverflow.com/q/51346040
linked to: http://stackoverflow.com/q/25593640
has title: xgboost regression predict same value
has comment: http://stackoverflow.com/comment/89665854
answer count: 1
has answer: http://stackoverflow.com/a/51353616
downvote count: 0
has comment: http://stackoverflow.com/comment/89665412
accepted answer: http://stackoverflow.com/a/51353616
tagged with: xgboost
favorite count: 0
has body: I am new to machine learning and xgboostand I am solving a regression problem. My target value are very small (e.g.-1.23e-12). I am using linear regression and xgboost regressor, but xgboost always predicts the same values, like: [1.32620335e-05 1.32620335e-05 ... 1.32620335e-05]. I tried to tune some parameters in xgboost.regressor, but it also predicted the same values. I've seen Scaling of target causes Scikit-learn SVM regression to break down , so I tried to scale my target value to likes(data.target = data.target*(10**12)) , and it fixed the problem. But I am not sure this is reasonable to scale my target value, and I don't know if this problem in xgboost is the same to SVR? . Here is target value of my data: count 2.800010e+05 mean -1.722068e-12 std 6.219815e-13 min -4.970697e-12 25% -1.965893e-12 50% -1.490800e-12 75% -1.269998e-12 max -1.111604e-12 And part of my code: X = df[feature].values y = df[target].values *(10**(12)) X_train, X_test, y_train, y_test = train_test_split(X, y) xgb = xgboost.XGBRegressor() LR = linear_model.LinearRegression() xgb.fit(X_train,y_train) LR.fit(X_train,y_train) xgb_predicted = xgb.predict(X_test) LR_predicted = LR.predict(X_test) print('xgb predicted:',xgb_predicted[0:5]) print('LR predicted:',LR_predicted[0:5]) print('ground truth:',y_test[0:5]) Output: xgb predicted: [-1.5407631 -1.49756 -1.9647646 -2.7702322 -2.5296502] LR predicted: [-1.60908805 -1.51145989 -1.71565321 -2.25043287 -1.65725868] ground truth: [-1.6572993 -1.59879922 -2.39709641 -2.26119817 -2.01300088] And the output with y = df[target].values (i.e., did not scale target value) xgb predicted: [1.32620335e-05 1.32620335e-05 1.32620335e-05 1.32620335e-05 1.32620335e-05] LR predicted: [-1.60908805e-12 -1.51145989e-12 -1.71565321e-12 -2.25043287e-12 -1.65725868e-12] ground truth: [-1.65729930e-12 -1.59879922e-12 -2.39709641e-12 -2.26119817e-12 -2.01300088e-12]
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
tagged with: regression
has comment: http://stackoverflow.com/comment/89665233
has comment: http://stackoverflow.com/comment/89666416
type: Question

http://stackoverflow.com/comment/89751676
type: QuestionComment
type: Comment
score: 0
has text: As a general rule, if you can't figure out how to turn something into a comprehension, especially when the simpler comprehension you're starting from already barely fits on an 80-character line, the right answer is to just not use a comprehension.
comment on: http://stackoverflow.com/q/51389298

http://stackoverflow.com/a/51453815
score: 1
has body: df.A, df.B = df'A', 'B'.max(axis=1), df'A', 'B'.min(axis=1)
answers question: http://stackoverflow.com/q/51453716
upvote count: 1
type: Answer
downvote count: 0

http://stackoverflow.com/a/51688467
has comment: http://stackoverflow.com/comment/90339881
has comment: http://stackoverflow.com/comment/90339396
has comment: http://stackoverflow.com/comment/90339261
has comment: http://stackoverflow.com/comment/90338867
upvote count: 1
has body: Twitters API states that get_direct_messages returns multiple DM's but that get_direct_message() with a message id parameter returns a single message
score: 0
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51327881

http://stackoverflow.com/comment/114069430
type: AnswerComment
has text: Note here that `im.widget.children[0]`, 0 corresponds to the number of parameters `HDI_vs_CrimeRate` takes. If it had 2 parameters, you need to put 2.
comment on: http://stackoverflow.com/a/51361461
type: Comment
score: 1

recursion
type: Tag
tags question: http://stackoverflow.com/q/51363931
tags question: http://stackoverflow.com/q/51342283
tags question: http://stackoverflow.com/q/51460879
tag name: recursion
tags question: http://stackoverflow.com/q/51342707
tags question: http://stackoverflow.com/q/51456483
tags question: http://stackoverflow.com/q/51466610
tags question: http://stackoverflow.com/q/51386324
tags question: http://stackoverflow.com/q/51331758
tags question: http://stackoverflow.com/q/51461425
tags question: http://stackoverflow.com/q/51337082
tags question: http://stackoverflow.com/q/51446794
tags question: http://stackoverflow.com/q/51408552

http://stackoverflow.com/q/51330525
type: Question
has title: convert tiff file to pdf using img2pdf
tagged with: http://stackoverflow.com/tag/pdf
tagged with: python
has comment: http://stackoverflow.com/comment/89707243
has body: I need to crawl into folders and subfolders, identify tiff file that doesn't have a pdf version and create a new one if necessary. Unfortunately, it does not work for all tiff. I am wondering how to keep going if the conversion does not happen. def makePDF(path, filename, image_files): output_file = path + '/' + filename + ".pdf" try: with open(output_file,"wb") as f: f.write(img2pdf.convert(image_files)) #f.close() except IOError as error: print ('opss') pass
score: 0
tagged with: tiff
has comment: http://stackoverflow.com/comment/89638264
type: UnansweredQuestion
tagged with: image
has comment: http://stackoverflow.com/comment/89702290
answer count: 0

http://stackoverflow.com/q/51327306
has answer: http://stackoverflow.com/a/63845606
has comment: http://stackoverflow.com/comment/93374591
score: 15
has title: How to detect if Chrome browser is headless in selenium?
downvote count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/74953762
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/74301253
tagged with: python
tagged with: selenium-webdriver
tagged with: selenium-chromedriver
upvote count: 19
has answer: http://stackoverflow.com/a/71945936
tagged with: selenium
has body: I'm writing a selenium test which has different behavior given whether the chrome browser was started as headless or not. My question is in my test how do I detect if the browser is headless for my conditional flow?
tagged with: google-chrome
has answer: http://stackoverflow.com/a/51327704
type: Question

http://stackoverflow.com/comment/89646481
score: 1
has text: I get a shape of `(25000,)` both for the train and the test datasets
comment on: http://stackoverflow.com/q/51334491
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51645914
downvote count: 0
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51366197
has body: from datetime import datetime from threading import Timer x=datetime.today() y=x.replace(day=x.day+1, hour=1, minute=0, second=0, microsecond=0) delta_t=y-x secs=delta_t.seconds+1 def hello_world(): print "hello world" #... t = Timer(secs, hello_world) t.start() This will execute a function in the next day at 1 am.

http://stackoverflow.com/comment/89696351
type: Comment
type: QuestionComment
has text: @CBroe I send this `{ "field": "messages", "value": { "page_id": "1067280970047460" } }`
score: 0
comment on: http://stackoverflow.com/q/51361990

http://stackoverflow.com/q/51473138
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51473300
has body: I have some random outcomes, and I want to simulate the random outcomes. outcomes_mapping = {0.10:"Outcome A", 0.60:"Outcome B", 0.30:"Outcome C"} Outcome A should happen 10% of the time, outcome B 60% of the time, outcome C 30% of the time. Currently, my solution is something like this: def random_encounter(): roll = np.random.rand() if roll &lt;= 0.1: return "Outcome A" if roll &gt; 0.1 and roll &lt;=0.6: return "Outcome B" Is there some smarter way to do this? My solution obviously involves a lot of hard coding. Should I be using cumulative probabilities instead? Even if I did, my function would still be in a if roll &gt; 0.1, return this, else return that format. If possible, I would like to maintain a master "outcomes mapping" dictionary which I can reference in my function.
has title: How to simulate random encounters in python
possible better answer: http://stackoverflow.com/a/51473205
has answer: http://stackoverflow.com/a/51473205
has comment: http://stackoverflow.com/comment/89915755
type: Question
has comment: http://stackoverflow.com/comment/89915378
has comment: http://stackoverflow.com/comment/89915313
downvote count: 0
has comment: http://stackoverflow.com/comment/89915614
favorite count: 0
answer count: 3
has answer: http://stackoverflow.com/a/51473300
has answer: http://stackoverflow.com/a/51473301
has comment: http://stackoverflow.com/comment/89914648
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/89914613

http://stackoverflow.com/comment/89916459
type: Comment
type: QuestionComment
has text: "Mapped" how? Is this mapping available to Python and active in the context where you run this script?
score: 1
comment on: http://stackoverflow.com/q/51473437

http://stackoverflow.com/comment/89880367
score: 0
comment on: http://stackoverflow.com/q/51448505
type: Comment
has text: I agree, that's how I'm expecting it to behave. However, in practice, with the code I've displayed above, it works to display the results in reverse chronological order to minutes, but reverts to chronological order if several tests are added in the same minute. I'm not quite sure why this is happening...
type: QuestionComment

http://stackoverflow.com/q/51449417
has body: I am trying to print a list in python with the " quotation marks instead of ' quotations marks. E.g. What I am getting myList = ['a','b','c','d'] What I want to get myList = ["a","b","c","d"] Thanks in advance!
tagged with: format
has answer: http://stackoverflow.com/a/51449719
score: 0
has answer: http://stackoverflow.com/a/51450339
has comment: http://stackoverflow.com/comment/89869320
answer count: 4
has answer: http://stackoverflow.com/a/51449478
type: UnansweredQuestion
has title: Printing in Python shell with " quotations instead of '
has answer: http://stackoverflow.com/a/51449522
tagged with: printing
favorite count: 0
has comment: http://stackoverflow.com/comment/89869484
type: Question
has comment: http://stackoverflow.com/comment/89869444
has comment: http://stackoverflow.com/comment/89869384
has comment: http://stackoverflow.com/comment/89869416
has comment: http://stackoverflow.com/comment/89869346
upvote count: 1
tagged with: python
downvote count: 1

http://stackoverflow.com/comment/89669350
type: Comment
type: QuestionComment
score: 1
has text: you said that you want to delete the read/write to the file... So the code doesn't use the file anymore and pass the url directly to the call back...
comment on: http://stackoverflow.com/q/51346410

shapely
tags question: http://stackoverflow.com/q/51346083
tag name: shapely
type: Tag
tags question: http://stackoverflow.com/q/51370497

http://stackoverflow.com/a/79304134
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51476722
has body: open3d's Tensor based API can be used for mesh intersections. It's MIT licence, well documented and easy to install via pip. box = o3d.geometry.TriangleMesh.create_box() box = o3d.t.geometry.TriangleMesh.from_legacy(box) sphere = o3d.geometry.TriangleMesh.create_sphere(0.8) sphere = o3d.t.geometry.TriangleMesh.from_legacy(sphere) ans = box.boolean_intersection(sphere) o3d.visualization.draw([{'name': 'intersection', 'geometry': ans}]) As of current version (0.18.0) there are two major issues with boolean_intersection: https://github.com/isl-org/Open3D/issues/6710 https://github.com/isl-org/Open3D/issues/5922 Until it is fixed , it is best to use a different library.

http://stackoverflow.com/q/51349040
answer count: 0
has comment: http://stackoverflow.com/comment/89670735
type: UnansweredQuestion
has title: Plot a red line at a certain point in a bar plot (python3 matplotlib)
tagged with: matplotlib
type: Question
has body: is it possible to plot a red line in a bar plot to see what values are under or over the lines if the bar graph is huge? I currently use the following code to plot my bars: import matplotlib.pyplot as plt tempA = 'Identifier' dictionary = frequency_dictionary2.get(tempA) fig = plt.figure(figsize=(150,15)) plt.bar(range(len(dictionary)), dictionary.values(), align='center') plt.xticks(range(len(dictionary)), dictionary.keys(), size='small', rotation='vertical') plt.title("Frequencies of " + tempA) plt.savefig(tempA + ".png", dpi="figure") plt.show() Also if anyone knows how can I make a huge bar graph more readable (without grouping variable) would be very grateful.
score: 0
has comment: http://stackoverflow.com/comment/89670515
tagged with: python

http://stackoverflow.com/comment/89815265
has text: Yes, phi is (96,750). I just edited the question.
comment on: http://stackoverflow.com/q/51413016
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/tag/zip
tags question: http://stackoverflow.com/q/51448429
tags question: http://stackoverflow.com/q/51359946
tags question: http://stackoverflow.com/q/51351000
tags question: http://stackoverflow.com/q/51478288
type: Tag
tags question: http://stackoverflow.com/q/51361646
tags question: http://stackoverflow.com/q/51358672
tags question: http://stackoverflow.com/q/51444059
tags question: http://stackoverflow.com/q/51482260
tags question: http://stackoverflow.com/q/51372009
tag name: zip

http://stackoverflow.com/a/51347856
has comment: http://stackoverflow.com/comment/89668653
has comment: http://stackoverflow.com/comment/89668601
downvote count: 0
has comment: http://stackoverflow.com/comment/89668758
answers question: http://stackoverflow.com/q/51347828
accepted answer of: http://stackoverflow.com/q/51347828
type: AcceptedAnswer
has body: Using a dictionary and list The following uses a dictionary (final_dictionary) to determine the id's of the words. This is great if you have a preset dictionary of id's. def encode_tokens(tokens): encoded_tokens = tokens[:] for i, token in enumerate(tokens): if token in final_dictionary: encoded_tokens[i] = final_dictionary[token] return encoded_tokens print(encode_tokens(tokens)) Adding and maintaining id's If you are dynamically assigning id's I would implement a class to do so (see bellow). If you, however, have a dictionary of id's that you have already defined ahead of time, you can pass in the keyword argument di: token_words_1 = ['I', 'liked', 'the', 'color', 'of', 'this', 'top'] token_words_2 = ['I', 'liked', 'to', 'test', 'repeat', 'words'] class AutoId: def __init__(self, **kwargs): self.di = kwargs.get("di", {}) self.loc = 0 def get(self, value): if value not in self.di: self.di[value] = self.loc self.loc += 1 return self.di[value] def get_list(self, li): return [*map(self.get, li)] encoding = AutoId() print(encoding.get_list(token_words_1)) print(encoding.get_list(token_words_2))
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/q/51473387
tagged with: numpy
possible better answer: http://stackoverflow.com/a/51473608
type: AnsweredQuestion
has body: I have a list and I wish to find a value using numpy and update its neighbor value in a 2D array myList = np.array([['kim' '0'], ['jong' '0'], ['un' '0'], ['is' '0'], ['here' '1']]) np.where(myList == 'is')// some operation to update from '0' to '1'. Please help Result ['kim' '0'], ['jong' '0'], ['un' '0'], ['is' '1'], ['here' '1']
has comment: http://stackoverflow.com/comment/89915326
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/51473596
has title: Using Numpy to find a value and update
score: 0
accepted answer: http://stackoverflow.com/a/51473596
answer count: 2
has answer: http://stackoverflow.com/a/51473608

http://stackoverflow.com/comment/89772287
has text: Hi , i have updated the input tables also for better clarity i get the output from each table in tuple form i.e df,data1 are in tuple form eg: df: (('abc@yahoo.com', abcd'), ('bcd@gmail.com', 'bcda')) data1: (('saha',),)
type: AnswerComment
comment on: http://stackoverflow.com/a/51400503
score: 0
type: Comment

http://stackoverflow.com/comment/89936265
type: Comment
comment on: http://stackoverflow.com/q/51477977
has text: perhaps Cross Validated network might be more appropriate for this question: https://stats.stackexchange.com/
score: 0
type: QuestionComment

http://stackoverflow.com/a/51341102
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51341034
has comment: http://stackoverflow.com/comment/89656401
has body: apt-get is package distribution manager for Ubuntu and a few other linux distributions. It only handles linux packages, so there is no point trying to get it running on Windows 10. For handling / managing Python packages and dependencies, you can try using Conda. You can install it by downloading either Anaconda or Miniconda. After installation, to get a new package use either conda install &lt;packagename&gt; or pip install &lt;packagename&gt; as Anaconda/Miniconda installs pip as well.
has comment: http://stackoverflow.com/comment/89658933
has comment: http://stackoverflow.com/comment/89659158

http://stackoverflow.com/q/51330040
downvote count: 0
has comment: http://stackoverflow.com/comment/89635967
has body: I have a few different lists: scan which is a list of different time stamps and focal which is a list of a few different time stamps repeated, and interval which tells me at what indices the time stamps in focal change. The goal is to calculate the difference of the scan timestamps for each one in focal. I am a little stuck on how to use interval in a while loop for the calculations. Here is what I have so far: def scanDuration(): scan = scanTimeFMT() focal = startTimeFMT() focal.pop(0) interval = [] times = [] i = 0 while i &lt; len(scan): whole = scan[i] time = str(whole[11:]) times.append(time) i += 1 j = 1 while j &lt; len(focal)-1: if focal[j] != focal[j+1]: interval.append(j+1) j += 1 else: j += 1 All help is appreciated, thank you!
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/89635951
has comment: http://stackoverflow.com/comment/89635913
favorite count: 0
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: time
has comment: http://stackoverflow.com/comment/89635904
score: 2
tagged with: list
has comment: http://stackoverflow.com/comment/89635861
type: Question
has title: time differences between multiple lists

http://stackoverflow.com/a/58355067
upvote count: 2
downvote count: 0
type: Answer
has body: Assuming that you will not be using this API through browsable API and some client will consume these API's, you should give a separate endpoint to fetch the options which can be shown in the dropdown. Since the calendar days only depends on the selected Availability, the endpoint can be something like /availability/&lt;:id&gt;/calender-days, where &lt;:id&gt; is the id of the selected option. This will be a GET request with a separate view where you can call your function which calculates calendar days from Availability object and return the list of calendar days. This endpoint will be useful in both cases when you create a new Booking object or you update that. On your point of showing in the browsable API form, browsable API forms don't load dynamic fields, so it will not call your logic to fetch calendar days based on the selection. For the Foriegn key and one-to-one relation, it already loads the queryset of the models while rendering the form and uses those to show the dropdowns. But if your actual use case is to consume API's using browsable API form then you will have to write some custom javascript to load the values.
score: 2
answers question: http://stackoverflow.com/q/51426968

odata
tag name: odata
type: Tag
tags question: http://stackoverflow.com/q/51451760

http://stackoverflow.com/comment/89793641
score: 2
comment on: http://stackoverflow.com/q/51410961
type: Comment
type: QuestionComment
has text: Edited: It may change due to the image. But for now, yes I am getting only two values. Also, I am getting more values when I use `print` function out of the `if` condition. All in all, I need two values ,as above, that must be assigned as variable name.

http://stackoverflow.com/q/51404069
upvote count: 0
has title: How to delete some string in Python
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89779062
type: UnansweredQuestion
has body: import os import sys import time import re import json from openpyxl import Workbook from slackclient import SlackClient from openpyxl.compat import range from openpyxl.utils import get_column_letter slack_client = SlackClient('token') file = slack_client.api_call("users.list") with open('data.json', 'w') as outfile: json.dump(file , outfile, indent=2 ) I need to delete some useless info such as :images, status, emoji.But I really don't get it cuz not familiar with syntax. So I need : Find user info (skype, images and so on ) Delete it Save it I want to create a list of things which I need to delete and compare my list with json file.However I run into an issue with code P.S json file is saved in Desktop folder
score: -3
has answer: http://stackoverflow.com/a/51404425
tagged with: python
has comment: http://stackoverflow.com/comment/89780480
has comment: http://stackoverflow.com/comment/89779251
tagged with: http://stackoverflow.com/tag/json
downvote count: 3
has comment: http://stackoverflow.com/comment/89780155
type: Question

http://stackoverflow.com/a/51398134
downvote count: 0
has body: I think need Series.apply with lambda function: df1 = pd.DataFrame({'d':[28000000000,28000000000]}) df1['times'] = df1['d'].apply(lambda x: time.strftime("%H:%M:%S", time.localtime(x))) Or list comprehension: df1['times'] = [time.strftime("%H:%M:%S", time.localtime(x)) for x in df1['d']] print (df1) d times 0 28000000000 03:46:40 1 28000000000 03:46:40
has comment: http://stackoverflow.com/comment/89767847
type: Answer
answers question: http://stackoverflow.com/q/51397961
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51397961
score: 3
has comment: http://stackoverflow.com/comment/89767937
type: AcceptedAnswer

mlflow
type: Tag
tags question: http://stackoverflow.com/q/51335594
tag name: mlflow

http://stackoverflow.com/comment/89654576
type: Comment
comment on: http://stackoverflow.com/a/51340307
type: AnswerComment
has text: hi thanks for the solution. But i wonder if i have 2 values for example ['Blue shirt', 643 , 2] how can i make it inside the list
score: 0

http://stackoverflow.com/comment/89695530
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51361698
has text: @moshevi yep, just added it:)

http://stackoverflow.com/a/51326399
downvote count: 0
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/89628206
has body: I think loop is not necessary, for selecting use slicers: idx = pd.IndexSlice df1 = df.loc[:, idx[:, 'Open', 'Bid']] print (df1) SPY ARKW Open Open Bid Bid 2018-07-03 272.86 56.00 2018-07-02 269.49 54.87 2018-06-29 272.09 55.58 Or use DataFrame.xs: df1 = df.xs(('Open', 'Bid'), level=[1, 2], axis=1) print (df1) SPY ARKW 2018-07-03 272.86 56.00 2018-07-02 269.49 54.87 2018-06-29 272.09 55.58 df1 = df.xs(('Open', 'Bid'), level=[1, 2], axis=1, drop_level=False) print (df1) SPY ARKW Open Open Bid Bid 2018-07-03 272.86 56.00 2018-07-02 269.49 54.87 2018-06-29 272.09 55.58 EDIT: For better performance all values in MultiIndex has to be sorted: df = df.sort_index(axis=1)
answers question: http://stackoverflow.com/q/51326320
has comment: http://stackoverflow.com/comment/89628112
accepted answer of: http://stackoverflow.com/q/51326320
type: AcceptedAnswer

http://stackoverflow.com/comment/89770574
comment on: http://stackoverflow.com/a/51397640
has text: The second solution strictly speaking does not define an Iterator but a container according to the specification. This means that looping over it with `for` will work, but an explicit call of `next()` will not.
type: AnswerComment
score: 0
type: Comment

scripting
tags question: http://stackoverflow.com/q/51399865
tag name: scripting
tags question: http://stackoverflow.com/q/51371771
tags question: http://stackoverflow.com/q/51363720
tags question: http://stackoverflow.com/q/51389724
tags question: http://stackoverflow.com/q/51434366
type: Tag

http://stackoverflow.com/a/51390015
answers question: http://stackoverflow.com/q/51389597
has body: It is not recommended to clutter/clobber the global namespace and you should look at what @MatthewMoore pointed to. Having said that, you can do this: import importlib globals().update(importlib.import_module(file_name).__dict__) More details here.
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51389597

http://stackoverflow.com/comment/89886578
has text: Read the documentation for [`os.system`](https://docs.python.org/3/library/os.html#os.system). It returns the exit code of the command.
comment on: http://stackoverflow.com/q/51458565
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89707352
comment on: http://stackoverflow.com/a/51367336
type: AnswerComment
score: 0
type: Comment
has text: I resolved it. Had to use __str__. Error with python version! Thanks anyway!

http://stackoverflow.com/comment/89784172
has text: This one is the best answer listed down +1
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51406521
type: Comment

http://stackoverflow.com/q/51384717
has comment: http://stackoverflow.com/comment/89743032
has comment: http://stackoverflow.com/comment/89742979
has comment: http://stackoverflow.com/comment/89743492
has comment: http://stackoverflow.com/comment/89742705
has title: ImportError: No module named pip._internal
score: 2
has comment: http://stackoverflow.com/comment/89743142
downvote count: 0
has comment: http://stackoverflow.com/comment/89743331
has comment: http://stackoverflow.com/comment/89743476
favorite count: 0
tagged with: python-3.x
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: pip
tagged with: python
tagged with: kivy
linked to: http://stackoverflow.com/q/49940813
tagged with: installation
duplicate of: http://stackoverflow.com/q/49940813
type: Question
has body: So I am working on installing Cython for Kivy so I can package my project into an iOS file that I can test on my iPhone. Here is the link I'm following: https://kivy.org/docs/guide/packaging-ios.html The issue I run into when installing something like Cython (or anything else for that matter, I have tried matplotlib for instance, and get the same result), it returns Traceback (most recent call last): File "/usr/local/bin/pip", line 7, in &lt;module&gt; from pip._internal import main ImportError: No module named pip._internal I have gotten this error in the past, and am still trying to figure it out. I used this post a few days ago: https://askubuntu.com/questions/1025189/pip-is-not-working-importerror-no-module-named-pip-internal/1026848?newreg=64574707bd3540948f5c54ec80d2b371 which helped me to install kivy. However, I am now having these issues with downloading other libraries. When I try to sudo easy_install pip, one would expect it would tell me that I already have pip installed. However, I get Traceback (most recent call last): File "/usr/bin/easy_install-2.7", line 7, in &lt;module&gt; from pkg_resources import load_entry_point ImportError: No module named pkg_resources Clearly something is going on here. I am trying to solve once and for all, is there something wrong with my pip? Did I install it wrong? Is it missing this 'pip._internal' file or something? Lastly, of course, I want to be able to successfully download libraries without the pkg_resources error Any feedback would be greatly appreciated Thanks in advance! EDIT: I'm using a Mac with Python 3.6 in PyCharm CE

http://stackoverflow.com/comment/89654463
score: 1
has text: you mean sum up all the elements in all the lists?
type: Comment
comment on: http://stackoverflow.com/q/51340470
type: QuestionComment

http://stackoverflow.com/comment/89648948
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51337053
has text: @StefanoPozzi - Because there is inverted condition, find all values which are `NOT` less as `1`, maybe you think `bow = bow.loc[bow['Rating'] >= 1, bow.sum() >= 50]`
score: 0

http://stackoverflow.com/comment/89834983
score: 1
type: AnswerComment
type: Comment
has text: In python, appending the item to the new list will just be referring back to the original item in memory (rather than copying it), so this isn't as memory-inefficient as it might first seem.
comment on: http://stackoverflow.com/a/51432023

http://stackoverflow.com/a/51403510
has comment: http://stackoverflow.com/comment/89778179
upvote count: 0
has comment: http://stackoverflow.com/comment/89778059
score: -2
has comment: http://stackoverflow.com/comment/89780569
has comment: http://stackoverflow.com/comment/89778508
downvote count: 2
has comment: http://stackoverflow.com/comment/89780399
answers question: http://stackoverflow.com/q/51403126
has body: Try making it explicit: from . import aux
has comment: http://stackoverflow.com/comment/89778755
has comment: http://stackoverflow.com/comment/89778558
type: Answer

http://stackoverflow.com/q/51459752
has body: I have no problems using the R package quantmod, which uses Yahoo to obtain stock data like so: get_stock_prices &lt;- function(target, return_format = "tibble", ...) { # Get stock prices print(target) stock_prices_xts &lt;- getSymbols(Symbols = target, auto.assign = FALSE, ...) # Rename names(stock_prices_xts) &lt;- c("Open", "High", "Low", "Close", "Volume", "Adjusted") # Return in xts format if tibble is not specified if (return_format == "tibble") { stock_prices &lt;- stock_prices_xts %&gt;% as_tibble() %&gt;% rownames_to_column(var = "Date") %&gt;% mutate(Date = ymd(Date)) } else { stock_prices &lt;- stock_prices_xts } write.csv(stock_prices, file = paste(target, "csv", sep = '.')) } I am only aware of pandas_datareader in Python to achieve something similar. Unfortunately, this package is broke as the yahoo and google APIs have changed. This code: import pandas_datareader as pdr panel_data = pdr.get_data_yahoo('MSFT') results in: Yahoo Actions has been immediately deprecated due to large breaks in the API without the introduction of a stable replacement. Pull Requests to re-enable these data connectors are welcome. Is there a currently working Python package to achieve the above. I am aware of quandl but this is a paid service. Thanks.
tagged with: python
has title: get stock data using python - not using quandl
downvote count: 0
score: 11
has comment: http://stackoverflow.com/comment/89889218
has answer: http://stackoverflow.com/a/51459842
type: AnsweredQuestion
tagged with: stockquotes
upvote count: 11
type: Question
tagged with: http://stackoverflow.com/tag/r
answer count: 3
has answer: http://stackoverflow.com/a/51590644
has answer: http://stackoverflow.com/a/51583705
has comment: http://stackoverflow.com/comment/90204975
accepted answer: http://stackoverflow.com/a/51583705
favorite count: 0
possible better answer: http://stackoverflow.com/a/51590644

http://stackoverflow.com/comment/89754012
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51390759
score: 0
has text: I'm trying to use this in the pandas replace function, but getting `look-behind requires fixed-width pattern` error. Any idea how to make it work in pandas?

http://stackoverflow.com/a/51390517
has comment: http://stackoverflow.com/comment/89753296
upvote count: 1
has comment: http://stackoverflow.com/comment/89754828
answers question: http://stackoverflow.com/q/51390464
has comment: http://stackoverflow.com/comment/89754483
has comment: http://stackoverflow.com/comment/89754293
downvote count: 0
has body: Yes, deprecated here means that the attribute or method has been removed from the newer versions. Hence, it is advised to avoid them in your code to avoid future issues.
has comment: http://stackoverflow.com/comment/89753210
type: Answer
score: 1

http://stackoverflow.com/a/51406677
has body: Using dictionary comprehension: o = ['XX.1.60.XX ether XX:16:35:b2:c9:XX C wlan0', 'XXX.168.42.XXX ether XX:35:cd:e8:a5:XX C usb0', 'XX.1.62.XXX ether XX:9f:db:72:61:XX C wlan0', ''] o = {v[0]: v[2] for v in (v.split() for v in o) if len(v) &gt;= 3} print(o) Prints: {'XX.1.60.XX': 'XX:16:35:b2:c9:XX', 'XXX.168.42.XXX': 'XX:35:cd:e8:a5:XX', 'XX.1.62.XXX': 'XX:9f:db:72:61:XX'}
has comment: http://stackoverflow.com/comment/89784744
answers question: http://stackoverflow.com/q/51406567
score: 0
type: Answer

http://stackoverflow.com/a/51340451
has body: You'd only get a O(n^2) solution if you nested your loops. Multiple sequential loops of O(n) (so the next loop running once the preceding loop has completed) add up to a O(n) final solution, you can use as many of those as you need. If your input doesn't include start and end numbers and you only know that they are going to be a sequence of positive integers with one number somewhere in the middle missing, the solution would be to first count the numbers and record the minimum and maximum number. Then loop from minimum to maximum, and include any number that is either missing or has a count of 2. Count using a dictionary, that way you'll also know what numbers are missing: def missing_or_doubled(inputlist): counts = {} for n in inputlist: # O(n) loop counts[n] = counts.get(n, 0) + 1 start, end = min(counts), max(counts) # two sequential O(n) loops # final O(n) loop to find missing number and number that appears twice return [i for i in range(start, end + 1) if counts.get(i) in {2, None}] That's 4 different O(n) loops, all sequential. You can determine start and end inside the for n in inputlist loop too, but that's going to be slower; the min() and max() functions are implemented in C and their lower constant cost will beat any attempt implemented in pure Python. Demo: &gt;&gt;&gt; missing_or_doubled([3, 1, 2, 5, 3]) [3, 4] &gt;&gt;&gt; missing_or_doubled([14, 19, 17, 13, 12, 10, 16, 17, 18, 22, 11, 15, 20]) [17, 21] If you do know the start or end number up front (either because it is passed to your code as a parameter, or the problem description explicitly states what the start or end number will be), then just replace either the min(counts) or max(counts) assignments with that information. For example, if the starting number is always supposed to be 1, just use range(1, end + 1).
has comment: http://stackoverflow.com/comment/89654629
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89654672
accepted answer of: http://stackoverflow.com/q/51340316
has comment: http://stackoverflow.com/comment/89654649
score: 3
type: Answer
answers question: http://stackoverflow.com/q/51340316
has comment: http://stackoverflow.com/comment/89654737
upvote count: 3
has comment: http://stackoverflow.com/comment/89654658

http://stackoverflow.com/a/51382689
answers question: http://stackoverflow.com/q/51382583
accepted answer of: http://stackoverflow.com/q/51382583
score: 0
has comment: http://stackoverflow.com/comment/89737750
type: AcceptedAnswer
type: Answer
has body: Your square function expects a parameter x, and yet in roll you call square() without an argument. You should pass x to it, and remove the redundant x = random.randint(1,6) from the square function.

http://stackoverflow.com/q/51441800
has comment: http://stackoverflow.com/comment/89853638
has comment: http://stackoverflow.com/comment/89853711
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51442089
has title: Reading multiple lines from binary file
has body: I have a binary file, and I want to read its content, Here's the code with open ('file1', 'rb') as fp: itemlist = pickle.load(fp) print(itemlist) and the code I am using to write to the file is with open('file1', 'ab') as fp: pickle.dump(training, fp) The file contains many length 4 lists. The problem is print(itemlist) is just printing the last list while I want all of them to convert to 2-D numpy array.I can even see the file size increasing gradually with every append call. How can I do it?
has answer: http://stackoverflow.com/a/51441968
score: 0
answer count: 2
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/89647006
type: Comment
has text: one more thing- so here during each iteration what is the initial state of the lstm cell. Since this works in a feed-forward manner will this keep a memory during each iteration?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51335922

http://stackoverflow.com/a/51473371
type: Answer
has comment: http://stackoverflow.com/comment/89916237
accepted answer of: http://stackoverflow.com/q/51473216
has comment: http://stackoverflow.com/comment/89916527
answers question: http://stackoverflow.com/q/51473216
score: 1
has body: Your code raises another Exception in the except sub-code. I'd go with this approach while True: try: lat, lon, res = gmaps_geoencoder(place) except: place = place.split(' ', 1)[1] Do note that at some point the try succeed and you want to break. Also, place can come to an end (probably an empty list), and you either break at that point under the except sub-code or put it as a stop-term in the while Last but not least, except: is highly not recommended to use without specific Exceptions. I'd suggest investigating on which Exceptions you want to catch there. Here's a more processed code: while len(place) &gt; 1 : try: lat, lon, res = gmaps_geoencoder(place) break except: place = place.split(' ', 1)[1] I intentionally didn't write this code for you because I don't know exactly what you want to do with lat, lon. Do you want to get the first result? or lists of results? I left it for you with the basic structure that handle the "Unknown" exception.
upvote count: 2
has comment: http://stackoverflow.com/comment/89917024
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/89917211
has comment: http://stackoverflow.com/comment/89916268
has comment: http://stackoverflow.com/comment/89916491

http://stackoverflow.com/comment/89822281
comment on: http://stackoverflow.com/a/51425530
type: AnswerComment
has text: @Kulasangar check `if isinstance(v, list): print(' '.join(v), end=' ')`
score: 0
type: Comment

http://stackoverflow.com/comment/119338830
score: 0
type: AnswerComment
has text: This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/low-quality-posts/28957664)
type: Comment
comment on: http://stackoverflow.com/a/67501528

http://stackoverflow.com/a/51469472
type: Answer
answers question: http://stackoverflow.com/q/51433031
upvote count: 1
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89947138
has body: You can implement a subclass of one of the classes in the io module described in I/O Base Classes, presumably io.BufferedIOBase. The standard library contains an example of something quite similar in the form of the zipfile.ZipExtFile class. At least this way, you won't have to implement complex functions like readline yourself.

http://stackoverflow.com/comment/89793451
score: 0
has text: @Tezra @JacobIRR the instance did it! thank you! working on new error "Employee.cypher() attempted on unsaved node" which im pretty sure is because im using uid, not id attributes `if not hasattr(self, 'id'): raise ValueError("{}.{}() attempted on unsaved node".format( self.__class__.__name__, action))`
type: AnswerComment
comment on: http://stackoverflow.com/a/51407236
type: Comment

http://stackoverflow.com/comment/89930602
type: QuestionComment
has text: Can you edit your question and post sample input XML and desired output?
comment on: http://stackoverflow.com/q/51479952
score: 0
type: Comment

http://stackoverflow.com/comment/89738836
has text: There's a cast function in SparkSQL
comment on: http://stackoverflow.com/q/51381806
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/a/51347277
downvote count: 1
answers question: http://stackoverflow.com/q/51347054
accepted answer of: http://stackoverflow.com/q/51347054
score: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89669258
has comment: http://stackoverflow.com/comment/91481548
type: Answer
has body: I don't know anything about Spyder, but in Anaconda there is a way to install packages from the Anaconda Navigator. If Spyder doesn't have this feature, you can do the following: Create a folder somewhere called PyPDFPath Unzip PyPDF2 into this directory, making sure your directory structure looks like this, with all of the PyPDF2 code inside the PyPDF2 directory At the top of your script, before any other imports, add the following code, where PYPDFPATH is the location of the PyPDFPath folder import sys sys.path.append('PYPDFPATH') In your script, try importing PyPDF2 as you did in your question. If you've done everything right, you should have no problems. The sys.path variable is a list that contains all of the folders that Python should look for modules. If you add a folder to this list with modules you'd like to import in it before you import them, Python will look for those modules in this folder in addition to the default folders it looks for modules in. Note that if you downloaded the PyPDF2 zip from GitHub, your PyPDF2 directory needs to contain the PyPDF2 directory from inside the zip instead of the entire repository. I hope this helps!
upvote count: 3

http://stackoverflow.com/q/51331018
has comment: http://stackoverflow.com/comment/89637863
has comment: http://stackoverflow.com/comment/89637814
has title: longest common sequence instead of word
has answer: http://stackoverflow.com/a/51331825
has comment: http://stackoverflow.com/comment/89637777
downvote count: 2
has comment: http://stackoverflow.com/comment/89637939
type: Question
has comment: http://stackoverflow.com/comment/89637964
has comment: http://stackoverflow.com/comment/89637867
has body: i am using a list and iterating from last to first element of the strings to find the longest common sub word between them. So the value for the current iteration(LC[i][j]) will depend both on the previous iteration LC[i+1][j+1] and the current matching of the element, I am facing two issues. - the else statement LC[i][j] = 0 is forcing the element of LC[i+1][j+1] = 0, so if there is a match in the current iteration then LC[i][j] is becoming 1(because LC[i+1][j+1] has been overwritten to 0. - on removing the else statement instead of finding longest common word it is giving longest common sub sequence. please see the output for both the cases case 1. when else is present. 1st str: zxab enter 2nd str: yzab i = 3 j = 3 LC[i][j] = 1 LC[i+1][j+1] = 0 i = 2 j = 2 LC[i][j] = 1 LC[i+1][j+1] = 0 i = 0 j = 1 LC[i][j] = 1 LC[i+1][j+1] = 0 max len = 1 case 2. else block removed. i = 3 j = 3 LC[i][j] = 1 LC[i+1][j+1] = 0 i = 2 j = 2 LC[i][j] = 2 LC[i+1][j+1] = 1 i = 0 j = 1 LC[i][j] = 3 LC[i+1][j+1] = 2 max len = 3 correct answer for max_len should have been 2. def LCW(u,v): m = len(u) n = len(v) LC = [[0] * (len(v) + 1)] * (len(u) + 1) # create the table one extra due to denote the endng of the word max_len = 0 for i in range(m-1,-1,-1): # because the strng's last elemnt can be accessed by range(m) == m-1 for j in range(n-1,-1,-1): if u[i] == v[j]: LC[i][j] = 1 + LC[i+1][j+1] #else: LC[i][j] = 0 if max_len &lt; LC[i][j]: max_len = LC[i][j] return max_len
score: -2
has comment: http://stackoverflow.com/comment/89638364
upvote count: 0
answer count: 1
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/89637778
tagged with: longest-substring
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89637726
tagged with: python
has comment: http://stackoverflow.com/comment/89637746
has comment: http://stackoverflow.com/comment/89637932

http://stackoverflow.com/comment/89776075
score: 0
type: Comment
type: QuestionComment
has text: relplot => regplot ?
comment on: http://stackoverflow.com/q/51402579

http://stackoverflow.com/a/51424635
score: 0
type: Answer
has body: By using melt+ idxmax Update df.melt().value[df.melt().value.ne(0).idxmax()] Out[536]: 25
has comment: http://stackoverflow.com/comment/89820359
answers question: http://stackoverflow.com/q/51424550

http://stackoverflow.com/q/51458657
upvote count: 3
has body: from tkinter import * import random import time tk=Tk() canvas=Canvas(tk,width=1000,height=1000) canvas.pack() i=0 x1=-50 y1=0 choice=None canvas.create_text(500, 300, text="Choose one.", font='TNR 20 bold') def car(): choice='car' return choice button1=Button(tk,text='car',width=10,command=car) button1.grid(row=1,column=5)#I do not see anything wrong here tk.mainloop() This is just part of my code if you are wondering why I have so many unused variables. This is what is says when I run the code: Traceback (most recent call last): File "(You dont need to know the file name)", line 180, in button1.grid(row=1,column=5) File "C:\Users\()\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 2223, in grid_configure + self._options(cnf, kw)) _tkinter.TclError: cannot use geometry manager grid inside . which already has slaves managed by pack
accepted answer: http://stackoverflow.com/a/51459157
type: AnsweredQuestion
score: 3
has title: Tkintter error: cannot use geometry manager grid inside . which already has slaves managed by pack
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: tkinter
type: Question
has answer: http://stackoverflow.com/a/51459157
tagged with: python

http://stackoverflow.com/comment/89885587
has text: i added dataframe.sort_values(by='Weight',inplace=True) after dataframe.dropna(inplace=True) and the graph still looks jumbled up
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51457942

http://stackoverflow.com/q/51413242
has body: I've downloaded Anaconda Navigator for windows, and during the install process there was a recommendation to install VSCode. I went along with it, and it seems to have a lot of the features I was looking for in a python IDE. But I'm stuck on how to run it with different environments. I have tried selecting an environment in the Anaconda Environments tab, and then clicking Home and launching VSCode. It seems to work to some extent. In the terminal, where.exe python gets me C:\Users\USERNAME\AppData\Local\conda\conda\envs\PYTHON_ENV\python.exe but when I try to check the modules that are available in that environment, it fails. I know they modules are available because I can see them in the Anaconda Navigator Environments tab, or if I start a terminal directly from the Environments tab. This is how it fails at the terminal within VSCode: PS H:\&gt; python -m import sys C:\Users\USERNAME\AppData\Local\conda\conda\envs\PYTHON_ENV\python.exe: No module named import H:\&gt; python Python 2.7.15 |Anaconda, Inc.| (default, May 1 2018, 18:37:09) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; help() File "&lt;stdin&gt;", line 1 help() ^ SyntaxError: invalid syntax &gt;&gt;&gt; quit() File "&lt;stdin&gt;", line 1 quit() ^ SyntaxError: invalid syntax Just in case this is an XY problem, what I'm actually trying to do is run some code I cloned from github which has a PyQt4 dependency. When I open the file in VSCode and try to run it, I get the error: ImportError: No module named PyQt4. I can get it to run from a terminal, but I'd like to know how to do it with VSCode too.
has title: Trying to run python environments in VSCode
answer count: 0
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89840990
has comment: http://stackoverflow.com/comment/89835418
tagged with: python
downvote count: 1
tagged with: environment
score: 2
tagged with: anaconda
has comment: http://stackoverflow.com/comment/89799167
has comment: http://stackoverflow.com/comment/89799072
type: Question
tagged with: visual-studio-code
favorite count: 0

http://stackoverflow.com/q/51337707
upvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51337952
tagged with: python
has body: I am trying to visualize the results of my regression (First time I do a regression be merciful). This is the example I am following but it creates a mess of a plot (tbh I took this example at face value). I have two issues. One is the visualization. The other, is an error I get when plotting trying to plot x_validate Vs. y_validate. I get ValueError: x and y must be the same size but they both have 56 rows. This is the code: # This is where I create the three parts bow.fillna(0, inplace=True) x_train, x_validate, x_test = np.split(bow.sample(frac=1), [int(.6*len(bow)), int(.8*len(bow))]) y_train = x_train['Rating'] y_validate = x_validate['Rating'] y_test = x_test['Rating'] x_train.drop('Rating', 1, inplace=True) x_validate.drop('Rating', 1, inplace=True) x_test.drop('Rating', 1, inplace=True) # This is the regression part regr = m.OrdinalRidge() regr.fit(x_train, y_train) y_pred = regr.predict(x_validate) # This is the plotting plt.scatter(x_validate, y_validate, color='black') # &lt;-- Here is where I get the error plt.plot(x_validate, y_pred, color='blue', linewidth=1) plt.xticks(()) plt.yticks(()) plt.show() This is what x_validate looks like: This is what y_validate looks like: This is what y_pred looks like: The .size of the above are: x_validate -> 3976 (but it has 56 rows and 71 columns) y_validate -> 56 y_pred -> 56 Any help would be greatly appreciated. EDIT: This is the code as suggested by Ach113 : pca = PCA(n_components = 1) # the n will be 2 here since y in your case has 2 columns pca.fit(x_validate) x_validate = pca.transform(x_validate) plt.scatter(x_validate, y_validate, color='black') plt.plot(x_validate, y_pred, color='blue', linewidth=1) plt.show() And this is what the resulting plot looks like: How can I interpret if the regression is performing well? I'm a bit lost...
score: -1
type: UnansweredQuestion
tagged with: regression
has title: How to interpret Plotting results Ordinary Ridge regression (check EDIT)
downvote count: 1
tagged with: plot
type: Question

http://stackoverflow.com/comment/89874873
type: Comment
type: QuestionComment
has text: @OnurOzbek, not trying to have a measuring contest, just noting that you're jumping into the deep end of the python pool. [Google's python course](https://developers.google.com/edu/python/) is right up your alley then, since it is geared toward those who already have some knowledge of programming.
comment on: http://stackoverflow.com/q/51435800
score: 0

http://stackoverflow.com/a/51400564
downvote count: 0
has body: Each time you call date_split(x) it returns a new dict, so updating it won't have an effect on the next call. Instead, you should assign the returning value of date_split(x) to a variable and then use that variable for further processing. std = "2018-07-18" x = "XXXX-01" s = date_split(x) if s['y'] == 'XXXX': new = str(date_split(std)['y']) s['y'] = new date = recompile(s) print(date)
answers question: http://stackoverflow.com/q/51400461
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/a/51446425
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51446194
answers question: http://stackoverflow.com/q/51446194
has comment: http://stackoverflow.com/comment/89863167
type: AcceptedAnswer
downvote count: 0
score: 1
has body: OK, to solve your problem, you just have to actually use your decoded data. Currently your are decoding your data, but then you use the rawData: import re import urllib.request term = input('Enter a word: ') url = "https://www.urbandictionary.com/define.php?term=" + term rawData = urllib.request.urlopen(url).read() decodedData = rawData.decode("utf-8") x = re.search('div class="meaning"', decodedData) start = x.start() end = x.end() result = decodedData[start:end] print(result) That should do it. If this doesn't work, please post an example word that throws this error. (This code will not produce the output you want by the way)
type: Answer

http://stackoverflow.com/comment/89763269
type: AnswerComment
comment on: http://stackoverflow.com/a/51395985
type: Comment
has text: Thanks, how can i print the row number that is empty?
score: 0

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

http://stackoverflow.com/q/51420110
score: 0
tagged with: invoices
type: Question
has comment: http://stackoverflow.com/comment/89811671
has body: How can I write xml file into the invoices in the code? I've tried in many ways but I get minidg to get out.xml empty. Thank you. import xml.etree.ElementTree as ET import sys doc = ET.parse('01-K011116_K011169.xml') for invoice in doc.findall('bizonylat'): invoices = ET.dump(invoice) print(invoices) invoices.write('out.xml') XML structure: <konyveles> Kontír FB 1.12.2.8 2014.01.26 17:05:38 Cég neve Tulajdonos V3 <biz_egyedi_id/><konyv_dat>2013.01.24</konyv_dat><teljesites_dat>2013.02.11</teljesites_dat><esedekesseg_dat>2013.03.20</esedekesseg_dat> <bizonylat_netto>628937,00</bizonylat_netto><bizonylat_brutto>798750,00</bizonylat_brutto> V3 2013.01.242013.02.112013.03.20 628937,00798750,00
has comment: http://stackoverflow.com/comment/89811418
has comment: http://stackoverflow.com/comment/89811824
has comment: http://stackoverflow.com/comment/89827270
type: UnansweredQuestion
tagged with: dump
has comment: http://stackoverflow.com/comment/89821343
has title: How write xml data from ET.dump
tagged with: python
tagged with: merge
tagged with: http://stackoverflow.com/tag/xml
answer count: 0

http://stackoverflow.com/q/51385545
favorite count: 0
upvote count: 2
tagged with: python
type: AnsweredQuestion
tagged with: multiple-axes
tagged with: matplotlib
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51386776
tagged with: subplot
has body: I have found and adapted the following code snippets for generating diagnostic plots for linear regression. This is currently done using the following functions: def residual_plot(some_values): plot_lm_1 = plt.figure(1) plot_lm_1 = sns.residplot() plot_lm_1.axes[0].set_title('title') plot_lm_1.axes[0].set_xlabel('label') plot_lm_1.axes[0].set_ylabel('label') plt.show() def qq_plot(residuals): QQ = ProbPlot(residuals) plot_lm_2 = QQ.qqplot() plot_lm_2.axes[0].set_title('title') plot_lm_2.axes[0].set_xlabel('label') plot_lm_2.axes[0].set_ylabel('label') plt.show() which are called with something like: plot1 = residual_plot(value_set1) plot2 = qq_plot(value_set1) plot3 = residual_plot(value_set2) plot4 = qq_plot(value_set2) How can I create subplots so that these 4 plots are displayed in a 2x2 grid? I have tried using: fig, axes = plt.subplots(2,2) axes[0,0].plot1 axes[0,1].plot2 axes[1,0].plot3 axes[1,1].plot4 plt.show() but receive the error: AttributeError: 'AxesSubplot' object has no attribute 'plot1' Should I set up the axes attributes from within the functions or where else?
has title: Populating matplotlib subplots with figures generated from function
has comment: http://stackoverflow.com/comment/89745685
answer count: 1
score: 1
accepted answer: http://stackoverflow.com/a/51386776

http://stackoverflow.com/q/51467026
downvote count: 1
tagged with: matlab
tagged with: image-processing
score: -1
type: Question
has body: This is the Matlab code which is returning eigenvector in V and eigenvalue in D. Consider C is 9*9 matrix then V is 9*9 matrix and D is 9*9 diagonal. matrix. [V,D] = eig(C); I want the same thing in Python and in the same order as Matlab. I am using this code: [V1, D] = np.linalg.eig(C) V = np.zeros((9,9)) for i in range(9): V[i][i] = V1[i] (consider V to be in the for loop) This code is giving me eigenvalue in V1 and eigenvector in D. I changed V1 to V to get a diagonal 9*9 matrix. But the problem is that I want the eigenvalue and vector in the same order as Matlab which I am not getting in the python. Please help me in getting the values in the same order as Matlab. See the link below for the difference in values between Matlab and python. https://drive.google.com/drive/folders/1zjhbKH0q_XXbBziZhfpL1-qS3B5oDuMb
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/51468820
favorite count: 0
tagged with: matrix
has title: Calculate eigen value in python as same way(order) in Matlab
has comment: http://stackoverflow.com/comment/89906284
has comment: http://stackoverflow.com/comment/89906206
type: UnansweredQuestion
tagged with: python
tagged with: computer-vision

http://stackoverflow.com/a/51479295
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51479023
type: Answer
accepted answer of: http://stackoverflow.com/q/51479023
has body: use df.isnull().sum() to know the total number of missing values in each column
score: 0

http://stackoverflow.com/comment/89754449
has text: @roganjosh Although that link is helpful, I am not entering wrong userinput :(
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51390930

http://stackoverflow.com/a/51400512
downvote count: 0
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51400461
score: 1
answers question: http://stackoverflow.com/q/51400461
has body: You change the return value of a function. Since you don't store it anywhere, it's lost. Instead, do something like custom_date = date_split(x) custom_date['y'] = new date = recompile(custom_date)
type: AcceptedAnswer

http://stackoverflow.com/q/51478739
favorite count: 0
tagged with: filter
answer count: 3
has answer: http://stackoverflow.com/a/51478900
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/51479494
tagged with: python
has comment: http://stackoverflow.com/comment/89925972
has title: How to filter on fieldnames in first row of a text file in python
accepted answer: http://stackoverflow.com/a/51479494
possible better answer: http://stackoverflow.com/a/51478887
upvote count: 1
has answer: http://stackoverflow.com/a/51478887
type: AnsweredQuestion
score: 1
linked to: http://stackoverflow.com/q/25768230
has comment: http://stackoverflow.com/comment/89926032
type: Question
has body: I've got the following text file: id gen age mar loc inc iscr escr 51 F 46 M 0 15100 531 555 52 M 29 M 2 14200 673 633 53 M 25 S 0 22200 742 998 54 M 36 M 2 1000 677 646 55 F 99 S 0 10600 608 998 56 F 45 M 2 6100 710 743 57 M 99 M 2 16500 679 646 58 F 37 M 0 7400 637 683 59 M 45 S 0 22800 683 998 60 M 22 S 0 6400 699 998 61 M 32 S 0 3100 721 998 Now I want to make a function that filters on the fieldnames in the first row, so for example if you call the function: filter('inc') you get this list filtered on 'inc'. Anyone who can help?
downvote count: 0
tagged with: header
has comment: http://stackoverflow.com/comment/89925932

http://stackoverflow.com/q/51360548
downvote count: 4
has answer: http://stackoverflow.com/a/51360591
favorite count: 0
accepted answer: http://stackoverflow.com/a/51360591
has comment: http://stackoverflow.com/comment/89694191
score: -3
type: AnsweredQuestion
tagged with: if-statement
type: Question
answer count: 1
has title: while function not executing under Else statement in python
has comment: http://stackoverflow.com/comment/89693187
tagged with: while-loop
upvote count: 1
has body: x=15 &gt;&gt;&gt; if x==10: print ("not bad") elif x==11: print ("good") elif x==12: print ("best") else: while x==30: x+=1 print(x)
tagged with: python

http://stackoverflow.com/comment/90093283
has text: It's the (-) symbol, I should put a backslash before it, now it works perfectly.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51445296

http://stackoverflow.com/q/51455193
accepted answer: http://stackoverflow.com/a/51455813
has body: may you help me ? I'm trying to make a software in python. I'm using tkinter and pil for training purposes. I want to be able to create an empty image with PIL, draw on it and then make it appear with tkinter. for now I have this def redraw(self): self.canvas.delete("all") image = Image.new ('RGB', (100, 100)) draw = ImageDraw.Draw(image) draw.rectangle ((0,0,100,100), fill = (20,20,20) ) im = ImageTk.PhotoImage (image) self.canvas.create_rectangle (0,0, 100, 100) #appears self.canvas.create_image (0,0, image = im) #does not Almost like the image created would be transparent. Even if I add image.save("image.png", "PNG") which create an image with my desired gray rectangle. Has anyone seen my flaw ? Thank you dearly for your help.
tagged with: python-imaging-library
downvote count: 2
has title: use pil with canvas for python tkinter gives blank image
type: Question
tagged with: canvas
linked to: http://stackoverflow.com/q/16424091
answer count: 1
duplicate of: http://stackoverflow.com/q/16424091
score: -1
favorite count: 0
tagged with: tkinter
has answer: http://stackoverflow.com/a/51455813
upvote count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/51479353
has answer: http://stackoverflow.com/a/51479397
tagged with: input
tagged with: python
has comment: http://stackoverflow.com/comment/89927118
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/10913786
has comment: http://stackoverflow.com/comment/89927148
type: Question
linked to: http://stackoverflow.com/q/10913786
answer count: 1
has body: I am starting to look into Python from a learning perspective and I am finding it nice and easy after Java. I am currently looking at working with files and I am using the 'with open()' command to make use of the open file only whilst the program is running. However, all the tutorials I seem to come across only ever seem to hard code either a filename or file path into the open() command. In Python or any of its libraries - does anyone know of a command I can use to allow the user a pop-up window to navigate and select where the file lives? Kind Regards
has comment: http://stackoverflow.com/comment/89927123
score: 0
has title: Open() in Python - Does a popup window exist?

shiny
tags question: http://stackoverflow.com/q/51442205
tag name: shiny
tags question: http://stackoverflow.com/q/51368984
tags question: http://stackoverflow.com/q/51465466
type: Tag

http://stackoverflow.com/a/51434849
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/51434350
upvote count: 1
has body: If you sort the list or approximate a sorted list using the range function, you can make use of a list comprehension: def solution(A): return [value for value in range(min(A),max(A)) if value not in A] We're basically saying, look at the sequence of numbers beginning with the min value of A to the max value of A, and if any of those values are not in the original A list, return those. This will return multiple missing values, e.g.: &gt;&gt;&gt; def solution(A): ... return [value for value in range(min(A),max(A)) if value not in A] ... A = [1, 2, 3, 4, 7, 8, 10] &gt;&gt;&gt; solution(A) [5, 6, 9] &gt;&gt;&gt; &gt;&gt;&gt; A = [2, 4, 1, 5] &gt;&gt;&gt; &gt;&gt;&gt; solution(A) [3] Note: you mentioned "positive" integers, and not sure if that was a strict requirement or not, but this doesn't account for negative values. I think we can account for that: def solution(A): positive = range(min([max(0,min(A))]),max(A)) return [value for value in positive if value not in A] For example: &gt;&gt;&gt; A = [-6,-8,2,3,5] &gt;&gt;&gt; solution(A) [0, 1, 4]
type: Answer

http://stackoverflow.com/a/51439966
type: Answer
accepted answer of: http://stackoverflow.com/q/51439912
upvote count: 4
answers question: http://stackoverflow.com/q/51439912
has comment: http://stackoverflow.com/comment/103971975
has comment: http://stackoverflow.com/comment/89853116
has comment: http://stackoverflow.com/comment/89855635
has comment: http://stackoverflow.com/comment/89853785
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/103993065
score: 4
has body: Probably aiohttp isn't listening on the right port. You need something like web.run_app(app, port=os.getenv('PORT')). Update: wait, you're trying to serve it both with gunicorn and with web.run_app which is wrong, you'll need to either just have something like web: python application.py or remove the web.run_app(app).

http://stackoverflow.com/q/51387980
has comment: http://stackoverflow.com/comment/89749709
has comment: http://stackoverflow.com/comment/89747799
has comment: http://stackoverflow.com/comment/89748628
has comment: http://stackoverflow.com/comment/89749714
has comment: http://stackoverflow.com/comment/89749466
answer count: 0
has comment: http://stackoverflow.com/comment/89749861
has comment: http://stackoverflow.com/comment/89749959
type: Question
has comment: http://stackoverflow.com/comment/89754887
has comment: http://stackoverflow.com/comment/89747843
tagged with: python-itertools
has title: Assignment with constraints: how to generate possibilities efficiently?
has comment: http://stackoverflow.com/comment/89747851
score: 0
has comment: http://stackoverflow.com/comment/89747891
has comment: http://stackoverflow.com/comment/89747811
has body: I have a cost matrix linking N0 workers to N1 tasks. All assignments are possible if they satisfy a constraint: (1) there is at least one worker assigned to each task, (2) the last worker can be assigned to an arbitrary number of tasks, and (3) the last task can be assigned to an arbitrary number of workers. I would like to generate all configurations which satisfy this constraint. I found one way to do this which is very inefficient. Any guidance is appreciated. edit: For example, a cost matrix could be costs = np.random.random((3,4)) Then I need to find all possible configurations satisfying the constraint. One would be (the last worker can be assigned to more than one task) config = [(0,0),(1,1),(2,2),(2,3)] another would be (the last task is assigned to an arbitrary number of workers) config = [(0,3),(1,3),(2,3),(2,3),(2,0),(2,1),(2,2)] So what I need is all possible lists of tuples linking row to column which satisfy (1) each row links to at least one column, (2) the last row can link to an arbitrary number of columns, and (3) the last column can link to an arbitrary number of rows Edit #2: I believe this is an appropriate generator. Consider that the cost matrix has infinite values which should be ignored. Then the set of all allowed links is n0,n1 = costs.shape links = [] for i in range(n0): for j in range(n1): if not np.isinf(costs[i,j]): links.append((i,j)) def filterfn(config): # (1) each row but the last should be represented in the config cond1 = set(l[0] for l in config if l[0]!=n0-1) == set(range(n0-1)) # (2) each column but the last should be represented in the config cond2 = set(l[1] for l in config if l[1]!=n1-1) == set(range(n1-1)) # (3) each row but the last should be represented exactly once cond3 = len(set(l[0] for l in config if l[0]!=n0-1))==len([l[0] for l in config if l[0]!=n0-1]) # (4) each column but the last should be represented exactly once cond4 = len(set(l[1] for l in config if l[1]!=n1-1))==len([l[1] for l in config if l[1]!=n1-1]) r…
has comment: http://stackoverflow.com/comment/89748206
has comment: http://stackoverflow.com/comment/89749298
has comment: http://stackoverflow.com/comment/89748424
has comment: http://stackoverflow.com/comment/89750124
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/59013616
downvote count: 0
score: 8
upvote count: 8
answers question: http://stackoverflow.com/q/51369858
type: Answer
has comment: http://stackoverflow.com/comment/138442753
has body: nlp.pipe returns a generator on purpose! Generators are awesome. They are more memory-friendly in that they let you iterate over a series of objects, but unlike a list, they only evaluate the next object when they need to, rather than all at once. SpaCy is going to turn those strings into sparse matrices, and they're gonna be big. In fact, spaCy is going to turn those strings into Doc objects, which are honkin' big c structs. If your corpus is big enough, storing it all in one variable (e.g., docs = nlp([doc for doc in matches] or docs = list(nlp.pipe(matches)) will be inefficient or even impossible. If you're training on any significant amount of data, this won't be a great idea. Even if it isn't literally impossible, you can do cool things faster if you use the generator as part of a pipeline instead of just dumping it into a list. If you want to extract only certain information, for example, to create a database column of just the named entities, or just the place names in your data, you wouldn't need to store the whole thing in a list and then do a nested for-loop to get them out. Moreover, the Doc.spans item (and many others) are generators. Similar kinds of data types show up in gensim as well -- half the challenge of NLP is figuring out how to do this stuff in ways that will scale, so it's worth getting used to more efficient containers. (Plus, you can do cooler things with them!) The official spaCy starter has some notes on scaling and performance in Chapter 3.
has comment: http://stackoverflow.com/comment/138183669

http://stackoverflow.com/comment/89883369
type: Comment
has text: Thanks, any alternative to this function for floats?
comment on: http://stackoverflow.com/a/51456917
type: AnswerComment
score: 0

http://stackoverflow.com/q/51437645
duplicate of: http://stackoverflow.com/q/10664856
has comment: http://stackoverflow.com/comment/89845116
tagged with: python-2.7
score: 0
possible better answer: http://stackoverflow.com/a/51437738
has answer: http://stackoverflow.com/a/51437754
tagged with: python
has answer: http://stackoverflow.com/a/51437738
has comment: http://stackoverflow.com/comment/89845182
accepted answer: http://stackoverflow.com/a/51437754
has title: python similar keys in dictionary
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89845295
duplicate of: http://stackoverflow.com/q/11141383
linked to: http://stackoverflow.com/q/10664856
has body: i have dictionary: dict = {key1:value1, key2:value2, key3:value3, key1:value4, key2:value5, key3:value6} if i print keys from dictionary def my_func(): for key in dict: print(key) it print only last 3 keys: for example: key1 key2 key3 but keys in dictionary can be same. Can you explain me why? if the key is the same, how to print like this: key2:value2,value5 if it is possible. thank you in advance.
type: Question
answer count: 2

http://stackoverflow.com/a/51330260
type: AcceptedAnswer
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/89636401
has comment: http://stackoverflow.com/comment/89636268
accepted answer of: http://stackoverflow.com/q/51330170
has comment: http://stackoverflow.com/comment/89636293
answers question: http://stackoverflow.com/q/51330170
has body: You want to use a+b, not r+b rb+ Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file. ab+ Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. Source: http://www.tutorialspoint.com/python/python_files_io.htm Note that the file pointer will be at the end of file if there is any text already there. If you want to open the file using rb+, use a helper method to check if the file exists first, and if the file doesn't exist, create it. def createFileIfNotExists(filePath): open(filePath, 'ab+') close(filePath) return Note my function is inefficient I'd suggest looking for a more elegant solution if you want to go that route.

http://stackoverflow.com/comment/89766387
type: QuestionComment
comment on: http://stackoverflow.com/q/51397604
has text: How did you install bs4 ? Seems that you either installed bs4 under python2, or are running the your py2 code using py3.
score: 0
type: Comment

http://stackoverflow.com/q/51401675
has comment: http://stackoverflow.com/comment/89774408
downvote count: 0
tagged with: url
has title: How to make ImageField returns relative path?
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/51401906
tagged with: python
favorite count: 0
tagged with: imagefield
has comment: http://stackoverflow.com/comment/89774114
upvote count: 1
tagged with: django
has body: I don't know why, but my ImageFields return full URL pathes. This is MEDIA_URL setting: MEDIA_URL = '/cc/cc/media/' I use this custom FileStorage: class ASCIIFileSystemStorage(FileSystemStorage): def get_valid_name(self, name): return str(uuid.uuid4()) + '.' + name.split('.')[-1] And simple ModelSerializers (from django rest framework) without overwriting smth like that for model Module1Item: class Module1Item(models.Model): ... background = models.ImageField(blank=True) class Module1ItemSerializer(serializers.ModelSerializer): class Meta: model = Module1Item fields = '__all__' What can be the reason of those behaviour? I need relative URLs.
accepted answer: http://stackoverflow.com/a/51401906
type: AnsweredQuestion
score: 1
possible better answer: http://stackoverflow.com/a/72989392
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/72989392

http://stackoverflow.com/comment/90506997
comment on: http://stackoverflow.com/q/51479586
score: 0
type: Comment
type: QuestionComment
has text: Yes, mathematically this is possible. Assuming your matrix is square but otherwise not remarkable, the solver will likely calculate `A`'s (sparse) LU decomposition per https://en.wikipedia.org/wiki/LU_decomposition#Solving_linear_equations and if you draw it out, you'll see that it's trivial to solve for the first (or last, depending on whether the triangle is upper or lower) unknown. It's unlikely but possible that the cost of the triangular solve is comparable to the cost of the LU factorization, in which case you can get the first element of the solution faster than solving them all.

http://stackoverflow.com/q/51336401
upvote count: 2
tagged with: django
tagged with: gis
answer count: 1
tagged with: geodjango
has answer: http://stackoverflow.com/a/51337586
has title: How to translate a polygon in GeoDjango?
tagged with: polygon
score: 2
type: AnsweredQuestion
downvote count: 0
has body: I have a Place model which has a polygon field: from django.contrib.gis.db import models class Place(models.Model): area = models.PolygonField() I want to translate the area field of an instance of this Place model. Here is how I am doing it right now: from django.contrib.gis.db.models.functions import Translate place = Place.objects.get(pk=1) place.area = Place.objects.filter(pk=place.pk).annotate(new_area=Translate('area', 0.001, 0.001)).first().new_area place.save() This seems very hacky. I think that there should be a way of doing this in the following way: place = Place.objects.get(pk=1) place.area = Translate(place.area, 0.001, 0.001) place.save() But this throws an exception. Should I be using some library? Which one works well with GeoDjango and its models/fields? What is the better way of doing it?
favorite count: 0
accepted answer: http://stackoverflow.com/a/51337586
type: Question
tagged with: python

http://stackoverflow.com/comment/89839366
comment on: http://stackoverflow.com/q/51434350
score: 1
type: QuestionComment
type: Comment
has text: I gave this a +1 for being a decent question, which is a pretty good start for a new user. Cheers and Welcome to Stack Overflow!

http://stackoverflow.com/comment/89745853
has text: Open your CMD, and type `pip install pynput`. What does it returns ?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51381763

http://stackoverflow.com/a/51457992
type: Answer
score: 1
answers question: http://stackoverflow.com/q/51457944
upvote count: 1
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51457944
has body: datetime.strptime can work in your case too. You can use the %B directive to parse full month names. import datetime s = 'December 7, 2015' date_string = str(datetime.datetime.strptime(s, '%B %d, %Y').date()) &gt;&gt;&gt; date_string '2015-12-07'
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89885280

http://stackoverflow.com/a/51457601
has comment: http://stackoverflow.com/comment/89893101
has comment: http://stackoverflow.com/comment/89885920
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89884778
accepted answer of: http://stackoverflow.com/q/51454466
has body: When I plot time, temperature and pressure as a 3D scatterplot, it does not appear as if the data lies on a surface such that as 3D surface equation can be fitted to the data. Here is my 3D scatterplot:
has comment: http://stackoverflow.com/comment/89886018
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51454466
type: Answer

http://stackoverflow.com/comment/90742612
comment on: http://stackoverflow.com/q/51448741
has text: No errors, yes it does capture the data because i can post the new username on the webpage. current_user is a function from flask login, it detects what user is logged in. So that user already exists in the db. current_user.username = form.username.data should swap to the updated username and commit() should enter that in the db but it doesn't.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89886759
type: Comment
type: QuestionComment
has text: plzz help me plzz
comment on: http://stackoverflow.com/q/51327649
score: 0

http://stackoverflow.com/comment/89683477
type: AnswerComment
comment on: http://stackoverflow.com/a/51355423
type: Comment
has text: @AvinashClinton - not yet tested, maybe some change is necessary. Need some time.
score: 0

http://stackoverflow.com/comment/89735731
has text: @davidzemens thanks!
comment on: http://stackoverflow.com/q/51381874
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51388324
upvote count: 1
has comment: http://stackoverflow.com/comment/89750487
score: 1
has comment: http://stackoverflow.com/comment/89776205
accepted answer of: http://stackoverflow.com/q/51388034
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51388034
type: Answer
has body: Im pretty sure you cant do that fdata.j.i You can use templatetags... Create one folder called templatetags and one file inside it (i'll call it table_templatetags.py) Obs.: Make sure to create empty file called __init__.py so django can understand that can read that folder app/templatetags/table_templatetags.py from django import template register = template.Library() @register.simple_tag(name='get_pos') def get_position(item, j, i): return item[j][i] In your HTML &lt;!-- Place this load in top of your html (after the extends if you using) --&gt; {% load table_templatetags %} &lt;!-- The rest of your HTML --&gt; {% for file_type in flabels %} { {% with i=forloop.counter0 %} label: {{file_type}}, data: [ {% for user in users %} {% with j=forloop.counter0 %} {% get_pos fdata j i %}, &lt;!-- Call your brand new templatetag --&gt; {% endwith %} {% endfor %} ], {% endwith %} } Some snippet mine: https://github.com/Diegow3b/django-utils-snippet/blob/master/template_tag.MD Django Docs: https://docs.djangoproject.com/pt-br/2.0/howto/custom-template-tags/

http://stackoverflow.com/comment/89719745
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51373804
score: 0
has text: Also, what are `a` and `b`? Clearly `b` is a positive integer, but `a` could be anything at all given the code you've shown us.

http://stackoverflow.com/comment/89743331
comment on: http://stackoverflow.com/q/51384717
type: Comment
type: QuestionComment
has text: @Addison In PyCharm, File:Default Settings Are all the modules you are attempting to use in your code located here? Are any of them located in here? If not, then that is why you can't use them in PyCharm.
score: 1

http://stackoverflow.com/comment/89892128
score: 0
type: Comment
has text: `collections.Counter`
type: QuestionComment
comment on: http://stackoverflow.com/q/51461472

http://stackoverflow.com/comment/89813912
comment on: http://stackoverflow.com/q/51419371
has text: If I just stop the script with Ctrl-c valgrind always reports: still reachable: 703,538 bytes in 478 blocks if I use os._exit(0) it always reports: still reachable: 2,202,110 bytes in 2,859 blocks This is still less than the amount leaked and when I look at backtraces it seems it's only memory that gets correctly freed when sys.exit(0) is called.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89803163
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51411080
type: Comment
has text: That's true. Correct, thanks. But I don't know if it's all. I'll try to find it. I have the problem with the variables and with te value. Now is like that prob += lpSum(LpVariable.dicts("var",['c-1_a-2757_p-13','c-1_a-2757_p-12','c-1_a-2757_p-188'],cat='Integer')) >= cent_artic_dict['c-1_a-2757'] where cent_artic_dict = {'c-1_a-2757': var_c_1_a_2757} cent_artic_dict = LpVariable.dicts("var",list(set(df_demand['demand'])),0,cat='Integer')

http://stackoverflow.com/q/51388369
has title: Change SOAP body for python suds call
answer count: 1
type: UnansweredQuestion
tagged with: soap
tagged with: python
has answer: http://stackoverflow.com/a/51403480
tagged with: suds
has body: We have a project that is using suds for some SOAP calls that has been working pretty well until today when I discovered suds is not parsing out the 'choice' objects from the imported wsdl. With this information, I've been trying to figure out a way to inject the xml required to make the call successful I'm calling the suds client like so self.client.service.retrieveService() to which suds is making this style call <SOAP-ENV:Envelope <SOAP-ENV:Header> <tns:wsHeader> xxx xxx <messageType/> </tns:wsHeader> </SOAP-ENV:Header> <ns1:Body> <ns0:retrieveServiceRequest/> </ns1:Body> </SOAP-ENV:Envelope> I've used the suds factory and the wsdl to create the proper input, but I can't figure out how to pass something like this to the client to use for the body: (retrieveServiceRequest){ serialNumberWrapper = (serialNumberWrapper){ serialNumber = "1234567890" } } Note: I've also tried creating my own xml and using __inject, but suds didn't appear to do anything or give any feedback (self.client.last_sent() returns None). I can provide the only parameter properly pulled from the wsdl for retrieveService to the client call and it will be added to the suds call. Any advice at this point would be appreciated, Thanks!
type: Question
score: 0

http://stackoverflow.com/comment/89867757
score: 0
type: Comment
type: QuestionComment
has text: I need to see how you're loading the savedmodel to understand where this error comes from
comment on: http://stackoverflow.com/q/51435117

http://stackoverflow.com/comment/89832319
has text: I do not understand. Other than your new item, what was the original problem described above?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51411562

http://stackoverflow.com/q/51455790
favorite count: 0
type: Question
upvote count: 2
tagged with: python
linked to: http://stackoverflow.com/q/50928942
linked to: http://stackoverflow.com/q/48015378
has answer: http://stackoverflow.com/a/51674264
tagged with: network-analysis
answer count: 1
has body: I want to create a network map similar to in python. So far I am able to draw it on 2D. The density of edges is making the graph untidy. Plotting the edges in 3-D would enhance the beauty and make it more appealing. Any help would be highly appreciated. Thanks in advance
has title: How to draw edges as 3D arcs on a geographic map using python?
accepted answer: http://stackoverflow.com/a/51674264
score: 2
type: AnsweredQuestion
downvote count: 0
tagged with: matplotlib-basemap

http://stackoverflow.com/a/51355768
has comment: http://stackoverflow.com/comment/89683833
downvote count: 0
has body: This looks ugly but, works. from collections import OrderedDict z = OrderedDict([('totalSize', 1), ('done', True), ('records', [OrderedDict([('attributes', OrderedDict([('type', 'Case'), ('url', '/services/data/v38.0/sobjects/Case/5003700000ReKcJAAV')])), ('Id', '5003700000ReKcJAAV')])])]) print(z.get('records')[0].get('Id')) Output: 5003700000ReKcJAAV
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51355690
has comment: http://stackoverflow.com/comment/89683887
answers question: http://stackoverflow.com/q/51355690
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/89684092
score: 1

http://stackoverflow.com/comment/89715167
score: 0
type: Comment
type: QuestionComment
has text: @PM2Ring I think this is a possible solution. I am going to try it.
comment on: http://stackoverflow.com/q/51369844

http://stackoverflow.com/a/57277669
has body: There is no built-in way to go from df_z (z scores) back to df (original values). However, you can do it fairly easily as follows: Step 1: Keep track of the mean and standard deviations of all of the original variables. Perhaps like this: mean_std={} for var in df.columns: mean_std[var]=(df[var].mean(), df[var].std()) Step 2: Convert back to z scores def reverse_zscore(pandas_series, mean, std): '''Mean and standard deviation should be of original variable before standardization''' yis=pandas_series*std+mean return yis original_mean, original_std = mean_std[var] original_var_series = reverse_zscore(df_z[var], original_mean, original_std) Alternatively, just store your original dataframe somewhere
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51471672
answers question: http://stackoverflow.com/q/51471672

http://stackoverflow.com/a/51446259
answers question: http://stackoverflow.com/q/51446082
upvote count: 1
downvote count: 0
score: 1
has body: With Python 2 you can do this with a custom cmp function: def compare(a,b): if a[1] &lt; b[1]: return 1 elif a[1] &gt; b[1]: return -1 else: if a[0] &lt; b[0]: return -1 elif a[0] &gt; b[0]: return 1 else: return 0 d={"h":3,"g":1,"w":1} items = d.items() items = sorted(items, cmp=compare) print items
type: Answer

http://stackoverflow.com/q/51350574
has body: I am trying to create a bash script with python code. I am running this code: foo = raw_input("Hostname:") print "imonitordb.pl -dumpEntityConfig 'device:",foo, "' | grep -v serviceNOC" When I run the command, I get the following output: imonitordb.pl -dumpEntityConfig 'device: monk ' | grep -v serviceNOC I want to get ride of the spaces by monk so it reads: imonitordb.pl -dumpEntityConfig 'device:monk' | grep -v serviceNOC What am I missing? I have tried to add foo1 = foo.strip() but that did not help. I feel there is something really easy I am missing, just seeing if someone has a quick answer
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51350607
accepted answer: http://stackoverflow.com/a/51350607
score: 0
tagged with: bash
has title: How do I strip space in the middle of output with python print
answer count: 1
tagged with: python

http://stackoverflow.com/a/51477178
answers question: http://stackoverflow.com/q/51476964
score: 0
has body: You could use a simple regex - import re word = re.search(u"[(][a-zA-Z]{6}[-]\d+[,]", "&lt;Thread(Thread-11, started daemon 123145310715904)&gt;").group(0).replace("(", "").replace(",", "") # OP 'Thread-11' Explanation of this pattern - [(][a-zA-Z]{6}[-]\d+[,] [(] - match a parentheses [a-zA-Z]{6} - match strings, 6 occurrences [-] - match a hyphen \d+[,] - match digits and then match a hyphen
type: Answer

http://stackoverflow.com/a/51413344
answers question: http://stackoverflow.com/q/51413276
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51413276
has body: IIUC using diff with cumsum create the group key , then we using agg new_df=df.groupby([df['ID'].diff().ne(0).cumsum(),df.ID]).DATETIME.agg([np.ptp,lambda x : x.dt.date.iloc[0]]) new_df=new_df.assign(ptp=new_df.ptp.dt.total_seconds()) new_df Out[45]: ptp &lt;lambda&gt; ID ID 1 432 40.0 2012-05-11 2 123 35998.0 2012-05-11 3 432 76.0 2012-05-11 4 98 10.0 2012-05-11 Update df['helperkey']=df['ID'].diff().ne(0).cumsum() New_df=df.groupby(['helperkey','ID']).DATETIME.agg([np.ptp,lambda x : x.dt.date.iloc[0]]).reset_index() New_df.merge(df.drop_duplicates(['helperkey','ID']),on=['ID','helperkey'],how='left') new_df=new_df.assign(ptp=new_df.ptp.dt.total_seconds())
has comment: http://stackoverflow.com/comment/89798320
type: AcceptedAnswer
upvote count: 3
type: Answer
score: 3

http://stackoverflow.com/q/51394093
has comment: http://stackoverflow.com/comment/89759844
tagged with: flask
has comment: http://stackoverflow.com/comment/89759645
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89759777
has comment: http://stackoverflow.com/comment/89759684
upvote count: 0
has answer: http://stackoverflow.com/a/51486188
type: UnansweredQuestion
tagged with: python
score: -1
has title: Flask displaying response in cmd but not in view
type: Question
has body: I am reviewing this repository https://github.com/ibrahim4529/flask-chatbot to get an inspiration and see how a model can be deployed in a chat UI. I am able to do this in Flask but ran across a quirky situation that I am not sure how to resolve. The UI accepts the first initial message that I type, but when I try returning the response, I get an 'undefined' appended to every line that is supposed to be the bot's response. On CMD though, my function is returning response. I've provided screenshots below: Here is my routing: @app.route('/') def hello(): return render_template('index.html') @app.route('/ask', methods={'POST', 'GET'}) def ask(): if request.method == 'POST': message = (request.form['messageText']) bresponse = response(message) return render_template('Index.html', bresponse=bresponse) 'response' is a function that spits out the response of the model (this is the 'Rrraawwwwg!' response from the input). Below is the js that I reviewed from the link that I am using: $('#chatbot-form').submit(function(e) { e.preventDefault(); var message = $('#messageText').val(); $(".media-list").append(' ' + message + ' '); $.ajax({ type: "POST", url: "/ask", data: $(this).serialize(), success: function(response) { //console.log(response); $('#messageText').val(''); var answers = response.answers; const chatPanel = document.getElementById("chatPanel"); $(".media-list").append(' ' + answers + ' '); $(".fixed-panel").stop().animate({ scrollTop: $(".fixed-panel")[0].scrollHeight}, 1000); I am not sure what I am missing. I am seeing the response in the cli, but seeing an undefined in the UI. Thanks in advance!
has comment: http://stackoverflow.com/comment/89759707

http://stackoverflow.com/comment/89656301
comment on: http://stackoverflow.com/a/51340933
has text: `new_list.pop()` will work but modifies `new_list` in the process which isn't really necessary and can make things confusing
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89953522
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51409039
has text: Thank you, that is a great solution. Using tikz and setting \tikzset{every picture/.style={/utils/exec={\sffamily}}} makes the doc look the same everywhere

http://stackoverflow.com/q/51403755
tagged with: web-scraping
type: Question
tagged with: python-3.6
has title: get renderd javascript lines from website in python
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51423014
has body: I'm using python 3.6.6 for this. I'm trying to get the current versionnumber of pycharm from the pycharm website (https://www.jetbrains.com/pycharm/download/#section=windows). The versionnumber is displayed pretty obvious, still I can't get it because I don't know how to process java script properly. I tried parsing it out with requests_html from: Version: This part should look like this after java script has done its job: Version: 2018.1.4 Here is my not working script by the way: from requests_html import HTMLSession session = HTMLSession() r = session.get('https://www.jetbrains.com/pycharm/download/#section=windows') r.html.render() item = r.html.find('') print(item) I don't care if there would be any parts left over, I would simply filter them out with RegEx. Still the only thing I'm getting from this is: [<Element 'span' data-code='PCP' data-release-version=''>]
tagged with: python
type: AnsweredQuestion
tagged with: python-requests-html
accepted answer: http://stackoverflow.com/a/51423014

http://stackoverflow.com/a/51421150
accepted answer of: http://stackoverflow.com/q/51419417
has body: In your hybrid_property, email, the line self.f.decrypt(self.email_hash.encode('utf-8')) is fine if self.email_hash is a str type, however, as email is a hybrid_property, when SQLAlchemy uses it to generate SQL self.email_hash is actually a sqlalchemy.orm.attributes.InstrumentedAttribute type. From the docs regarding hybrid properties: In many cases, the construction of an in-Python function and a SQLAlchemy SQL expression have enough differences that two separate Python expressions should be defined. And so you can define an hybrid_property.expression method which is what SQLAlchemy will use to generate sql, allowing you to keep your string treatment intact in your hybrid_property method. Here is the code I ended up with that worked for me given your example. I've stripped quite a bit out of your User model for simplicity but all the important parts are there. I also had to make up implementations for other functions/classes that were called in your code but not supplied (see MCVE): class Fernet: def __init__(self, k): self.k = k def encrypt(self, s): return s def decrypt(self, s): return s def get_env_variable(s): return s def generate_password_hash(s): return s class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) email_hash = db.Column(db.String(184), unique=True, nullable=False) f = Fernet(get_env_variable('FERNET_KEY')) @hybrid_property def email(self): return self.f.decrypt(self.email_hash.encode('utf-8')) @email.expression def email(cls): return cls.f.decrypt(cls.email_hash) @email.setter def email(self, email): self.email_hash = self.f.encrypt(email.encode('utf-8')) if __name__ == '__main__': db.drop_all() db.create_all() u = User(email='a@example.com') db.session.add(u) db.session.commit() print(User.query.filter_by(email='a@example.com').first()) # &lt;User 1&gt; Unfortunately, the code above only works because the mock Fernet.decrypt method returns the exact object that was passed in. The problem with storing a Fernet…
has comment: http://stackoverflow.com/comment/94943817
answers question: http://stackoverflow.com/q/51419417
has comment: http://stackoverflow.com/comment/89814290
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/89822412
upvote count: 1
has comment: http://stackoverflow.com/comment/94912488
score: 1
has comment: http://stackoverflow.com/comment/89836868

http://stackoverflow.com/comment/89708694
has text: Edited my question.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51368085

http://stackoverflow.com/q/51352002
score: 1
favorite count: 0
tagged with: while-loop
type: Question
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
tagged with: python-3.x
upvote count: 1
type: UnansweredQuestion
has title: Python XML Parsing - need to correct while loop
has body: Fairly new to Python. I'm parsing an XML file and the following code returns the undesired results. I can understand why I'm getting my results - there are two escalations in the XML for this deal and I'm getting results for each set. I'm need help updating my code to only return the monthly rent for each escalation in the XML: 7 3.8 12 bump 61 1.0 12 bump The rent starts at $3.00/sqft for the first 6 months. This XML block shows that, for each 12 months (RecurrenceInterval), the rent will be $6.80/sqft ($3.00 base + $3.80 escalation). The following twelve months will be $10.60 ($6.80 + 3.80). Each year, the amount per square foot will increase by $3.80 until the 61st month in the term. At that point, the rent will increase by $1.00/sqft for the remainder of the term. The entire term of the lease is 120 months. My results include 114 results based on the first escalation (3.80/sqft) followed by 114 rows showing as if the rent starts at $3.00/sqft incrementing by $1.00/sqft each year. Any help is appreciated! import xml.etree.ElementTree as ET import pyodbc import dateutil.relativedelta as rd import datetime as dt tree = ET.parse('C:\\FileLocation\\DealData.xml') root = tree.getroot() for deal in root.findall("Deals"): for dl in deal.findall("Deal"): dealid = dl.get("DealID") for dts in dl.findall("DealTerms/DealTerm"): dtid = dts.get("ID") darea = float(dts.find("RentableArea").text) dterm = int(dts.find("LeaseTerm").text) for brrent in dts.findall("BaseRents/BaseRent"): brid = brrent.get("ID") rent = float(brrent.find("Rent").text) darea = float(dts.find("RentableArea").text) per = brrent.find("Period").text dtstart = dts.find("CommencementDate").text startyr = int(dtstart[0:4]) startmo = int(dtstart[5:7]) startday = int(dtstart[8:]) start = dt.date(startyr, startmo, startday) end = start + rd.relativedelta(months=dterm) if brrent.find("Duration").text is None: duration = 0 else: duration = int(brrent.find("Duration").text) termbal = dterm - duration for resc in dt…
answer count: 0
downvote count: 0

http://stackoverflow.com/q/51480694
tagged with: python
has comment: http://stackoverflow.com/comment/89935054
has comment: http://stackoverflow.com/comment/89955580
tagged with: hdf5
tagged with: dataframe
has body: I have a pandas dataframe that takes 4 MB of the memory: &gt;&gt;&gt; df.memory_usage(deep=True).sum() / (1024 ** 2) &gt;&gt;&gt; 3.9931907653808594 When I save this dataframe to hdf5 file, the space it took on disk is 21.1 MB: &gt;&gt;&gt; df.to_hdf('my_data.hdf5', key='df', format='table') Can someone explain the reasons? df.info() returns: &lt;class 'pandas.core.frame.DataFrame'&gt; Float64Index: 1440 entries, 1262300460.0 to 1262386800.0 Columns: 879 entries, dtypes: category(212), float32(667) memory usage: 4.0 MB df.dtypes.unique() returns: array([dtype('float32'), CategoricalDtype(categories=['Closing', 'Off'], ordered=False), CategoricalDtype(categories=['Active'], ordered=False), CategoricalDtype(categories=['-'], ordered=False), CategoricalDtype(categories=[], ordered=False), CategoricalDtype(categories=['Active', 'Off'], ordered=False), CategoricalDtype(categories=['Low', 'Off'], ordered=False), CategoricalDtype(categories=['Low'], ordered=False)], dtype=object) Edit 7.24.2018, reply to @jpp If I convert the categorical columns of the dataframe to integer data type, then the dataframe takes 4MB of memory. When I save it to hdf format, it takes 4.3 MB on disk. This is how I convert categorical columns to integer datatype: for col in df.columns[df.dtypes == 'category']: df[col] = df[col].cat.codes If I convert the categorical columns of the dataframe to 'object' data type, then the dataframe takes 24 MB of memory. When I save it to hdf format, it takes 9.7 MB on disk.
score: 4
type: Question
upvote count: 4
downvote count: 0
favorite count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/90145563
answer count: 0
has title: Why the hdf5 file takes larger disk space than the space taken by pandas dataframe in memory?
type: UnansweredQuestion

http://stackoverflow.com/a/51397918
has body: Seems to me like you are trying to use HAVING in a wrong way. The HAVING clause is used for: HAVING filters records that work on summarized GROUP BY results. HAVING applies to summarized group records, whereas WHERE applies to individual records. Only the groups that meet the HAVING criteria will be returned. HAVING requires that a GROUP BY clause is present. WHERE and HAVING can be in the same query. you have to move your AVG(Sales) in the SELECT clause or if you want to compere it you need to build statement in your HAVING clause. HAVING AVG(Sales)&gt;yourValue comment down if you have more questions tnx :)
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/51397747
downvote count: 0
type: Answer

http://stackoverflow.com/comment/89991717
has text: I found some questions that related to this issues, and it seems that they called stable result issues. <https://stackoverflow.com/questions/42156296/dropoutwrapper-being-non-deterministic-across-runs> <https://stackoverflow.com/questions/36288235/how-to-get-stable-results-with-tensorflow-setting-random-seed> Someone pointed out that parallel computation can cause the unstable result due to its independency from the previous values of the loop. (I didn't fully understand what this means, but may be computing gradients of mini-batch cause the problem?)
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51473224
type: Comment

http://stackoverflow.com/comment/89915614
comment on: http://stackoverflow.com/q/51473138
has text: Why would it not? `np.random.rand` returns random samples from a uniform distribution over ``[0, 1)``. Can you help me understand your thinking? Thanks.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89799462
type: Comment
comment on: http://stackoverflow.com/a/51414032
type: AnswerComment
has text: if you did it before plz help me because I have a deadline
score: 0

http://stackoverflow.com/q/51468132
type: Question
score: 0
has title: BadDigest when calling the PutObject operation s3 boto
has comment: http://stackoverflow.com/comment/89905324
tagged with: python
has comment: http://stackoverflow.com/comment/89932610
answer count: 0
type: UnansweredQuestion
has body: This code works fine import boto3 def upload(request): try: get_file = request.POST['file'].file d_filename = 'foo-'+uuid.uuid4().hex s3 = boto3.resource('s3') s3.Bucket('Bucket_name').put_object(Key=d_filename, Body=get_file, ContentType=ContentType) return d_filename except Exception, e: log.error(str(e)) return 'error' but when i want to put md5 hash of file in filename it throws error- "An error occurred (BadDigest) when calling the PutObject operation (reached max retries: 4): The Content-MD5 you specified did not match what we received." import boto3 import hashlib def upload(request): try: get_file = request.POST['file'].file d_filename = 'foo-'+str(hashlib.md5(get_file.read()).hexdigest()) s3 = boto3.resource('s3') s3.Bucket('Bucket_name').put_object(Key=d_filename, Body=get_file, ContentType=ContentType) return d_filename except Exception, e: log.error(str(e)) return 'error' I am not trying to calculate md5 of file already uploaded or trying to set it for file but want md5 in name of the file.
has comment: http://stackoverflow.com/comment/89909732
tagged with: amazon-s3
tagged with: boto3

http://stackoverflow.com/q/51330174
upvote count: 1
downvote count: 1
type: Question
has body: I'm working on a small project to help some of my players that I GM for. Essentially, I want to create an automated system that will roll dice in the OpenLegend RPG system using its rules. One element of the system is a "dice explosion." If you roll the maximum value on a dice, you roll it again, adding the previous value and the new one as well, continuing as many times as it "explodes". I'm having some difficulty figuring out how I would do this, however. At present, my code looks like this: from random import randint as ri def action_roll_script(attribute, score): d20 = ri(1, 20) if score == 0: roll = d20 if score == 1: roll = ri(1,4) if score == 2: roll = ri(1,6) if score == 3: roll = ri(1,8) if score == 4: roll = ri(1,10) if score == 5: roll = ri(1,6) + ri(1,6) if score == 6: roll = ri(1,8) + ri(1,8) if score == 7: roll = ri(1,10) + ri(1,10) if score == 8: roll = ri(1, 8) + ri(1, 8) + ri(1, 8) if score == 9: roll = ri(1, 10) + ri(1, 10) + ri(1, 10) if score == 10: roll = ri(1, 8) + ri(1, 10) + ri(1, 10) + ri(1, 10) print(d20) print(roll) outcome = str(roll + d20) print("You got a " + attribute + " roll of " + outcome + "!") Now, obviously that's fairly inefficient with entirely too many if statements. I'll work on using a dictionary/list for that later. My question for you all is: how can I tell the script to roll the dice again when it lands on a maximum value? For example, if it rolls a 20 on a d20, I want it to save the previous result and roll again, continuing as many times as it gets a 20.
has title: Python: Rolling dice again when at max randint value
tagged with: random
answer count: 2
tagged with: dice
favorite count: 0
has answer: http://stackoverflow.com/a/51330398
has answer: http://stackoverflow.com/a/51330316
score: 0
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/a/51596850
downvote count: 0
score: 17
type: Answer
upvote count: 17
has body: There are two ways of letting the model know your intention i.e do you want to train the model or do you want to use the model to evaluate. In case of model.train() the model knows it has to learn the layers and when we use model.eval() it indicates the model that nothing new is to be learnt and the model is used for testing. model.eval() is also necessary because in pytorch if we are using batchnorm and during test if we want to just pass a single image, pytorch throws an error if model.eval() is not specified.
answers question: http://stackoverflow.com/q/51433378

http://stackoverflow.com/a/51421116
has body: Here another try : import datetime d1 = datetime.date(2018, 7, 26) d2 = datetime.date(2018, 10, 14) days = d1 while days &lt; d2: print(days) days += datetime.timedelta(7)
score: 0
has comment: http://stackoverflow.com/comment/89814126
answers question: http://stackoverflow.com/q/51420715
type: Answer

http://stackoverflow.com/comment/89793784
type: AnswerComment
comment on: http://stackoverflow.com/a/51407236
type: Comment
score: 0
has text: looks like Employee() is creating a new resource `<Employee: {'uid': '115ae498a5024829bd0f6f3b4148955e', 'created_at': datetime.datetime(2018, 7, 18,` ... with none for all fields

http://stackoverflow.com/q/51459087
answer count: 1
has answer: http://stackoverflow.com/a/51459192
has comment: http://stackoverflow.com/comment/89887798
has comment: http://stackoverflow.com/comment/89888328
has comment: http://stackoverflow.com/comment/89887627
has body: I am trying to read the body of a web service call with the requests module in Python 2.7. The body of the result is CSV data. The request is just a GET. I can run the url in Chrome and it returns a complete response of 200 rows. The url looks like: http://localhost:8080/summary-report?endTime=9999999&amp;startTime=0 When I try to get the data from Python, it retrieves only the first row of data. I look at the response header and see the length of the response is only 122 bytes, about the length of the first row. I have run it a number of times from Python and it is consistent in returning only the first row. The code is only: r = requests.get(url) ans = r.content Could it be some with with the new line characters on each line of the CSV file? Or because I am using localhost in the url? I also tried it with 127.0.0.1 but see a similar behavior. Possibly the ampersand is an issue in the URL?
has title: Python 2.7 requests not reading complete body
type: UnansweredQuestion
tagged with: python
tagged with: python-requests
has comment: http://stackoverflow.com/comment/89887683
has comment: http://stackoverflow.com/comment/89888245
has comment: http://stackoverflow.com/comment/89888277
has comment: http://stackoverflow.com/comment/89887770
linked to: http://stackoverflow.com/q/51455112
has comment: http://stackoverflow.com/comment/89887828
type: Question
score: 0
has comment: http://stackoverflow.com/comment/89887723
has comment: http://stackoverflow.com/comment/89888014

http://stackoverflow.com/q/51451709
has comment: http://stackoverflow.com/comment/89873666
has body: I don't know how to use pandas in this context. I have my dataset :How can I read specific colums from a txt file in python?. What I want to do is to take artists and tracks and put them into a "for" to make a Spotify request. I don't know what to put after "for i in". Sorry for my ignorance. import spotipy import spotipy.util as util import pandas as pd df = pd.read_csv('playlist1.txt', sep='\t', header=None, names=['artists', 'tracks'], usecols=[3, 4]) for i in [????]: artist_name = df.artists[i] track_name = df.tracks[i] q = artist_name + ", " + track_name search=spotify.search(q, limit=1, type="track,artist") for i in range (0,limit): if (search["tracks"]["items"]) &lt;&gt; []: array_id.append(search["tracks"]["items"][i]["id"].encode('ascii', 'ignore'))
accepted answer: http://stackoverflow.com/a/51452275
tagged with: for-loop
tagged with: pandas
answer count: 1
downvote count: 0
tagged with: readfile
favorite count: 0
tagged with: python
tagged with: text-files
linked to: http://stackoverflow.com/q/51431017
score: 2
type: AnsweredQuestion
has title: How to put parameters into a for loop from a txt file read with pandas?
has answer: http://stackoverflow.com/a/51452275
upvote count: 2
linked to: http://stackoverflow.com/q/16476924
type: Question

http://stackoverflow.com/q/51385419
has comment: http://stackoverflow.com/comment/89754093
has body: The Context: I'm trying to use the package trackpy for research. I'm on a Mac and I'm using (mostly) Spyder. I’m following the trackpy walkthrough (https://soft-matter.github.io/trackpy/v0.3.2/tutorial/walkthrough.html) and I’m trying to use it on a tif file. Here’s my code: #Install trackpy (https://soft-matter.github.io/trackpy/v0.3.2/installation.html) !conda update conda --yes !conda install -c conda-forge trackpy --yes #Use trackpy (trackpy walkthrough: https://soft-matter.github.io/trackpy/v0.3.2/tutorial/walkthrough.html) from __future__ import division, unicode_literals, print_function import matplotlib as mpl import matplotlib.pyplot as plt %matplotlib inline import numpy as np import pandas as pd from pandas import DataFrame, Series import pims import trackpy as tp #Install libtif for pims.Tiffstack, per the README (which leads to this link: http://nbviewer.jupyter.org/github/soft-matter/pims/blob/master/examples/loading%20video%20frames.ipynb) !conda install libtiff --yes frames = pims.TiffStack("/Users/(my username)/Documents/TSVIEW_Test_5_Grey_1.tif", as_grey=True) The Problems: When I first wrote the code, I got the error: TypeError: init() got an unexpected keyword argument 'as_grey' According to the trackpy walkthrough, it should take as_grey as an argument. However, when I restarted my computer, I got a different error message (without any code changes as far as I can tell): /anaconda3/lib/python3.5/site-packages/tifffile/tifffile.py:2113: UserWarning: invalid ImageJ metadata or corrupted file warnings.warn('invalid ImageJ metadata or corrupted file') Again, I didn't change the code between restarting it. Interestingly, when I tried this code in a different python-running software, I got the first error again. I tried it in Google Colab. The only changes I made to the code were using pip instead of conda (Colab only supports pip), downloading the additional dependencies needed for pip per the trackpy install page (https://soft-matter.github.io/track…
downvote count: 0
tagged with: imagej
score: 1
type: Question
tagged with: tiff
tagged with: invalid-argument
upvote count: 1
has title: Pims "Unexpected Keyword Argument" and “invalid ImageJ metadata or corrupted file”
tagged with: trackpy
favorite count: 0
answer count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51454878
has comment: http://stackoverflow.com/comment/89879138
has comment: http://stackoverflow.com/comment/89912734
type: Question
has body: Here is the test code: Step #1: Request Auth Code args_str = urlencode({ 'response_type' : 'code', 'client_id' : '&lt;app client id&gt;', 'scope' : 'r_emailaddress r_basicprofile', 'state' : '&lt;my state id&gt;', 'redirect_uri' : '&lt;app redirect url&gt;' }) url = 'https://www.linkedin.com/oauth/v2/authorization' return redirect(url + '?' + args_str) Step #2 Handle call back Step #3 Get access token Step #4 Get data from linkedin using access token def get_linkedin_data(request, access_token): api_endpoint_profile = 'https://api.linkedin.com/v1/people/~' access_token = access_token headers = {} headers['Authorization'] = 'Bearer ' + access_token headers['User-Agent'] = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0' headers['x-li-format'] = 'json' values = { 'format' : 'json' } data = urllib.parse.urlencode(values) data = data.encode('ascii') url_request = urllib.request.Request(api_endpoint_profile, data=data, headers=headers, method='GET') url_response = urllib.request.urlopen(url_request) response_data_profile = json.loads(url_response.read().decode('utf-8')) The response_data_profile variable contains basic profile data only but not the email address. What am i missing here? Note: App created in Linkedin developer account with r_basicprofile and r_emailaddress scopes selected Permission granted to scopes basicprofile and emailaddress When api tries to get linked data
score: 0
tagged with: api
tagged with: linkedin-api
type: UnansweredQuestion
tagged with: django
tagged with: python
answer count: 0
has title: Linkedin API does not return email address in Django 2.0

http://stackoverflow.com/q/51413410
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51579052
type: Question
answer count: 2
downvote count: 0
has title: Understanding raise RemoteDisconnected("Remote end closed connection"
has comment: http://stackoverflow.com/comment/89816944
has answer: http://stackoverflow.com/a/51579052
possible better answer: http://stackoverflow.com/a/51423484
upvote count: 6
favorite count: 0
has answer: http://stackoverflow.com/a/51423484
has comment: http://stackoverflow.com/comment/89816344
tagged with: python-3.x
score: 6
tagged with: python
has body: I'm scraping twitter trying to get the friends/users being followed for a list of twitter users. I'm using tweepy and python 3.6.5 on OSX 10.13. An abbreviated code chunk : def get_friends_for_each_twitter_user(UserL=None, Name=None): . . # Auth keys and such . for user in UserL: ### This is a list of USER class with the below fields ### ### Handle protected users ### if(user.protected == True): user.friendsL = "protected" continue screenNameL=[] friendIDL=[] friendL=[] friendScreenNameL=[] ### Get IDs of people that this user follows (i.e. 'friends') ### for page in tweepy.Cursor(api.friends_ids, screen_name=user.screenName).pages(): friendIDL.extend(page) time.sleep(60) ## Loop through IDs, get user profile, keep only friends' screen name ### for i in range(0, len(friendIDL), 100): friendL.extend(api.lookup_users(user_ids=friendIDL[i:i+100])) ### Keep only screen name ### for friend in friendL: friendScreenNameL.append(friend._json['screen_name']) user.friendsL = friendScreenNameL When I do this, after collecting the friends (i.e. profiles that the user follows) for about a dozen users, I get the following errors: Traceback (most recent call last): File "/Users/myusername/.local/virtualenvs/python3.6/lib/python3.6/site-packages/urllib3/connectionpool.py", line 601, in urlopen chunked=chunked) File "/Users/myusername/.local/virtualenvs/python3.6/lib/python3.6/site-packages/urllib3/connectionpool.py", line 387, in _make_request six.raise_from(e, None) File "&lt;string&gt;", line 2, in raise_from File "/Users/myusername/.local/virtualenvs/python3.6/lib/python3.6/site-packages/urllib3/connectionpool.py", line 383, in _make_request httplib_response = conn.getresponse() File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1331, in getresponse response.begin() File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 297, in begin version, status, reason =…
tagged with: tweepy

http://stackoverflow.com/a/51478808
answers question: http://stackoverflow.com/q/51441828
score: 2
downvote count: 0
has body: Thanks MilanVelebit for helping to find out the answer. I post my answer here. You just need to add one line when you import multiprocessing and use pyinstaller. from multiprocessing import Pool,freeze_support if __name__ == "__main__": ##Add support for when a program which uses multiprocessing has been frozen to produce a Windows executable. (Has been tested with py2exe, PyInstaller and cx_Freeze.) #One needs to call this function straight after the '__main__' line of the main module. freeze_support() t1 = time.time() pool = Pool(2) pool.map(readwritevalue, [file for file in gettxtpath()]) pool.close() pool.join() GetFormated() ##Get the Final output of Xunjian-Report.csv Getxlsx() ##Get the Xunjian-Report.xls GetDocx() ##Get the docx format print("Cost time {t}".format(t=time.time() - t1))
upvote count: 2
type: Answer

http://stackoverflow.com/comment/89676219
type: Comment
has text: @Darren: what :O this is badly decoded, in fact this looks like a list with *one* string.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51351746

http://stackoverflow.com/q/51452270
tagged with: tensorflow
type: Question
upvote count: 2
answer count: 1
has body: I traced the gpu usage during training and for conv2d operation, it shows: I tried to calculate the exact memory need for this op with (3*3*3*16 + 32*450*450*3+ 32*448*448*16) * 4/(1024**2) which equals 466.16MB. Obviously, TensorFlow allocates 318MB more memory for Conv2d. Why Would TF do that?
downvote count: 0
favorite count: 0
has title: How does Tensorflow allocate GPU memory for Conv2D operation?
type: UnansweredQuestion
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/51484813

http://stackoverflow.com/q/51463223
tagged with: spyder
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89895393
has answer: http://stackoverflow.com/a/51467284
accepted answer: http://stackoverflow.com/a/51467284
tagged with: python
has comment: http://stackoverflow.com/comment/89895358
score: 14
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89895639
tagged with: anaconda
has answer: http://stackoverflow.com/a/59626455
has body: Is there any way to use pep8 module to check whether the code is compliant with pep8 specifications in Spyder (Anaconda)? I also tried to run the command pep8 --show-source --show-pep8 testsuite/E40.py given at https://pypi.org/project/pep8/ in the command prompt, but it gives syntax error (SyntaxError: invalid syntax).
downvote count: 1
type: Question
upvote count: 15
tagged with: pep8
has title: How to use pep8 module using Spyder
answer count: 2
has comment: http://stackoverflow.com/comment/89895433
possible better answer: http://stackoverflow.com/a/59626455

http://stackoverflow.com/q/51429969
accepted answer: http://stackoverflow.com/a/51430049
type: AnsweredQuestion
upvote count: 2
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/51430037
has answer: http://stackoverflow.com/a/51430037
answer count: 2
has answer: http://stackoverflow.com/a/51430049
tagged with: max
score: 1
favorite count: 0
has title: Find max value(s) of certain key
has body: I need the max value of 'cost' and if there are two or more occurrences of the same key with same value (max) then I need all of them into a single list. For Example: fruits = [{'nama':'oranges','id':9635,'cost':23}, {'nama':'lemons','id':946,'cost':17}, {'nama':'apples','id':954,'cost':16}, {'nama':'oranges','id':989,'cost':23}] I need output to be like: result = [{'nama':'oranges','id':9635,'cost':23}, {'nama':'oranges','id':989,'cost':23}] How do we do this?
has comment: http://stackoverflow.com/comment/89831865
tagged with: python
tagged with: dictionary

http://stackoverflow.com/comment/89839072
type: AnswerComment
type: Comment
has text: thank you very much for explanation. Now I know exactly what I did wrong and understood the logic behind the map function!
score: 0
comment on: http://stackoverflow.com/a/51434213

http://stackoverflow.com/comment/89745872
type: QuestionComment
score: 0
has text: `includes` includes [**modules**](https://docs.python.org/3/tutorial/modules.html), i.e. separate files `*.py`. `packages` adds [**packages**](https://docs.python.org/3/tutorial/modules.html#packages), i.e. directories with `__init__.py` and `*.py` files.
comment on: http://stackoverflow.com/q/51385272
type: Comment

http://stackoverflow.com/a/51389947
type: Answer
has body: You'll have to get it like - x['CategoryArray']['Category'][0]['CategoryParentID'] If we simplify the dict you posted, we get - d = {'CategoryArray': {'Category': [{'CategoryParentID': '20081'}]}} # "CategoryArray" # "Category" child of CategoryArray # Key "Category" contains a list [{'CategoryName': 'Antiques', 'CategoryParentID': '20081'...}] # Get 0th element of key "Category" and get value of key ["CategoryParentID"] I hope it makes sense
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/51389749

http://stackoverflow.com/comment/89671206
comment on: http://stackoverflow.com/q/51348788
score: 0
type: Comment
type: QuestionComment
has text: @PM 2Ring@dmitryro I have solve the problem, THX! I have repeat the code's () etc

http://stackoverflow.com/q/51349197
has comment: http://stackoverflow.com/comment/89670952
answer count: 0
upvote count: 1
downvote count: 1
tagged with: unit-testing
type: Question
has body: As in Python 3, AssertEquals is deprecated and should be replaced with AssertEqual. However, the latter doesn't convey the same information. It doesn't show the difference. e.g. self.assertEquals(result.status_code, 403) File ".pyenv/versions/3.6.4/lib/python3.6/unittest/case.py", line 822, in _baseAssertEqual raise self.failureException(msg) AssertionError: 404 != 403 Great, AssertionError: 404 != 403 this is very useful. But the AssertEqual is like this: File "projects/x_api/tests/test_apply_voucher.py", line 16, in test_add_invalid_code self.assertEqual(result.status_code, 403) That's not very useful, it doesn't show me the content of result.status_code. Do I have to use it differently?
has comment: http://stackoverflow.com/comment/89671089
tagged with: python-3.6
score: 0
has comment: http://stackoverflow.com/comment/89671138
has comment: http://stackoverflow.com/comment/89670926
favorite count: 0
type: UnansweredQuestion
has title: AssertEqual doesn't show the same information as AssertEquals
tagged with: python

pip
tags question: http://stackoverflow.com/q/51446698
tags question: http://stackoverflow.com/q/51331528
tags question: http://stackoverflow.com/q/51358987
tags question: http://stackoverflow.com/q/51344760
tags question: http://stackoverflow.com/q/51348322
tags question: http://stackoverflow.com/q/51373063
tags question: http://stackoverflow.com/q/51446954
tags question: http://stackoverflow.com/q/51463548
tags question: http://stackoverflow.com/q/51460318
tags question: http://stackoverflow.com/q/51370149
tags question: http://stackoverflow.com/q/51476300
tags question: http://stackoverflow.com/q/51414407
tags question: http://stackoverflow.com/q/51444958
tags question: http://stackoverflow.com/q/51344081
tags question: http://stackoverflow.com/q/51344694
tags question: http://stackoverflow.com/q/51467922
tags question: http://stackoverflow.com/q/51469009
tags question: http://stackoverflow.com/q/51400919
tags question: http://stackoverflow.com/q/51402866
tags question: http://stackoverflow.com/q/51451795
tags question: http://stackoverflow.com/q/51451966
tags question: http://stackoverflow.com/q/51384717
tags question: http://stackoverflow.com/q/51334492
tag name: pip
tags question: http://stackoverflow.com/q/51407031
tags question: http://stackoverflow.com/q/51363980
tags question: http://stackoverflow.com/q/51404984
tags question: http://stackoverflow.com/q/51392098
tags question: http://stackoverflow.com/q/51437205
tags question: http://stackoverflow.com/q/51364326
tags question: http://stackoverflow.com/q/51343587
tags question: http://stackoverflow.com/q/51410944
tags question: http://stackoverflow.com/q/51428583
tags question: http://stackoverflow.com/q/51478588
tags question: http://stackoverflow.com/q/51426884
tags question: http://stackoverflow.com/q/51412526
tags question: http://stackoverflow.com/q/51365856
tags question: http://stackoverflow.com/q/51422857
type: Tag
tags question: http://stackoverflow.com/q/51469451
tags question: http://stackoverflow.com/q/51327541
tags question: http://stackoverflow.com/q/51449912
tags question: http://stackoverflow.com/q/51342408
tags question: http://stackoverflow.com/q/51409987
tags question: http://stackoverflow.com/q/51405139
tags question: http://stackoverflow.com/q/51348079
tags question: http://stackoverflow.com/q/51337784
tags question: http://stackoverflow.com/q/51343961
tags question: http://stackoverflow.com/q/51419256
tags question: http://stackoverflow.com/q/51340142
tags question: http://stackoverflow.com/q/51434717
tags question: http://stackoverflow.com/q/51393710
tags question: http://stackoverflow.com/q/51337939

http://stackoverflow.com/q/51342304
answer count: 1
downvote count: 0
tagged with: keras
favorite count: 0
tagged with: python
has title: Keras custom layer and eager execution
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/51368861
upvote count: 2
tagged with: tensorflow
type: Question
has body: I have a simple model with one custom layer which works fine in the normal case. When I switched to eager execution via tf.enable_eager_execution(), I got stuck on a weird error. Here is the code so far: import numpy as np import tensorflow as tf import tensorflow.keras.backend as K from tensorflow.keras.models import Model from tensorflow.keras.layers import Layer, Input from tensorflow.keras.losses import kullback_leibler_divergence tf.enable_eager_execution() class ClusteringLayer(Layer): def __init__(self, output_dim, input_dim=None, alpha=1.0, **kwargs): self.output_dim = output_dim self.input_dim = input_dim self.alpha = alpha super(ClusteringLayer, self).__init__(**kwargs) def build(self, input_shape): self.W = self.add_weight(name='kernel', shape=(self.output_dim, input_shape[1]), initializer='uniform', trainable=True) super(ClusteringLayer, self).build(input_shape) def call(self, x, mask=None): q = 1.0/(1.0 + K.sqrt(K.sum(K.square(K.expand_dims(x, 1) - self.W), axis=2))**2 /self.alpha) q = q**((self.alpha+1.0)/2.0) q = K.transpose(K.transpose(q)/K.sum(q, axis=1)) return q def compute_output_shape(self, input_shape): return (input_shape[0], self.output_dim) def clustering_loss(y_true, y_pred): a = K.square(y_pred) / K.sum(y_pred, axis=0) p = K.transpose(K.transpose(a) / K.sum(a, axis=1)) loss = kullback_leibler_divergence(p, y_pred) return loss input1 = Input(shape=(10,), name="input") out = ClusteringLayer(output_dim = 5, name='clustering')(input1) model = Model(inputs=input1, outputs=out) model.compile(optimizer=tf.train.AdamOptimizer(1e-3), loss={'clustering' : clustering_loss}) X = np.random.random((20, 10)).astype(np.float32) Y = np.random.random((20, 5)).astype(np.float32) model.fit(x={'input' : X}, y={'clustering' : Y}, batch_size=1, epochs=10) The error message is related to the "fit" function: AssertionError: Could not compute output DeferredTensor('None', shape=(5,), dtype=float32) When I tried to check the output of my custom layer, I was surprise…
accepted answer: http://stackoverflow.com/a/51368861

http://stackoverflow.com/q/51327847
has title: building a data frame with pandas out of a nested structure in python
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/51330484
accepted answer: http://stackoverflow.com/a/51330101
tagged with: pandas
tagged with: nested
favorite count: 0
upvote count: 1
tagged with: python
tagged with: structure
has body: I want to implement machine learning with a dataset a bit too complex. I want to work with pandas and then use some of the built-in models in skit-learn. The data looks is given in JSON file, a sample looks like that below: { "demo_Profile": { "sex": "male", "age": 98, "height": 160, "weight": 139, "bmi": 5, "someinfo1": [ "some_more_info1" ], "someinfo2": [ "some_more_inf2" ], "someinfo3": [ "some_more_info3" ], }, "event": { "info_personal": { "info1": 219.59, "info2": 129.18, "info3": 41.15, "info4": 94.19, }, "symptoms": [ { "name": "name1", "socrates": { "associations": [ "associations1" ], "onsetType": "onsetType1", "timeCourse": "timeCourse1" } }, { "name": "name2", "socrates": { "timeCourse": "timeCourse2" } }, { "name": "name3", "socrates": { "onsetType": "onsetType2" } }, { "name": "name4", "socrates": { "onsetType": "onsetType3" } }, { "name": "name5", "socrates": { "associations": [ "associations2" ] } } ], "labs": [ { "name": "name1 ", "value": "valuelab" } ] } } I want to create a pandas data frame that considers this kind of "nested data" but I don't know how to build a data frame which takes into account "nested parameters" besides of "singles parameters" For example, I don't know how to merge "demo_Profile" which contains "single parameters" with symptoms which is a list of dictionaries of, in same cases single values, and in other cases lists. Anybody knows any way to deal with this issue? EDIT********* The JSON shown above is just one example, in other cases, the number of values in lists would be different, as well as the number of symptoms. So, the example shown above is not fixed for every case.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51330101
score: 1
tagged with: http://stackoverflow.com/tag/json
type: Question
has answer: http://stackoverflow.com/a/51330484

http://stackoverflow.com/q/51437443
tagged with: class
has title: How to rewrite python class module from root folder without changing the original package module
tagged with: python
tagged with: module
has comment: http://stackoverflow.com/comment/89846502
answer count: 0
type: UnansweredQuestion
tagged with: package
upvote count: 1
has comment: http://stackoverflow.com/comment/89845186
tagged with: site-packages
score: 1
type: Question
has body: I have a project using python that has site package. I need to do a customization of a class from a module located in site package and used only the custom one. The problem is, I wanted to do it without changing anything in the original site package module. What I have in my mind, I do it by creating folder in project root with the same name as in the site package. Is it possible to do this? In short, I want to rewrite the class 2 (in site package) with some customization to be class 2 located in project root folder. See the picture below. site-package folder: project folder:
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/89669004
type: AnswerComment
type: Comment
has text: Is the maximum length known how should it be detected in an online fashion?
comment on: http://stackoverflow.com/a/51345740
score: 0

http://stackoverflow.com/q/51345105
has answer: http://stackoverflow.com/a/51345191
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: pyqt5
upvote count: 1
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/51345191
has body: Assume I have 2 points in Pyqt5. QtCore.QPoint(200,200) QtCore.QPoint(400,400) Now, I would like to normalize this vector points. Is there a way to find the normalized vector?
has title: pyqt5 normalize a vector
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/89863709
type: Comment
comment on: http://stackoverflow.com/a/51446746
score: 1
has text: I think you should explain why you've chosen to make the changes you've made.
type: AnswerComment

http://stackoverflow.com/q/51441240
has body: Scenario : create a lambda and it will be triggered whenever a message comes to SQS(let's assume SQS-A). The lambda (written in python)is responsible for sending the incoming payload to the another endpoint. The problem is, whenever the target endpoint or server is down, I was trying to place it into the another SQS (let's assume SQS-B), if other exceptions comes than placing it into Deal Letter Queue. Here I want to two things. If ConnectionError (it is the python exception says which says endpoint is down) comes I want to stop the the SQS-A(there is no point to run the lambda as the target server is down). (or) As whenever I get this error I am sending it to the SQS-B, I want the SQS-B to be triggered for when the first request comes and it should check if still there is a connection error, it has to trigger after 10 minutes, and again check, if exception persists trigger after 30 minutes, like this I want to increment the time up to 4 hours and after that check/trigger the lambda every 4 hours. If there is no exception then it should read all the messages in the SQS-B. Help me how to achieve any one of the approach or recommend any other better approach
tagged with: python
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/51443299
accepted answer: http://stackoverflow.com/a/51443299
downvote count: 1
type: Question
score: -1
tagged with: amazon-sqs
answer count: 1
has title: managing AWS SQS and DLQ
tagged with: amazon-web-services
tagged with: aws-lambda
favorite count: 0

http://stackoverflow.com/q/51372303
downvote count: 3
has comment: http://stackoverflow.com/comment/89716803
tagged with: django
answer count: 1
has answer: http://stackoverflow.com/a/51373646
has body: I often look for answers on this website,this time my question was not answered. I have a question: when i create one user in web Interface,i want to create a database at this point. the database name according to username.in other words,I want to have a separate database for each user,My database is mysql. I'm looking for one demo.thanks a lot.
type: UnansweredQuestion
score: -3
linked to: http://stackoverflow.com/q/6585373
has title: Django when i create one user, one database created
upvote count: 0
tagged with: django-rest-framework
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/89720601
tagged with: python

http://stackoverflow.com/q/51455517
type: Question
answer count: 2
has body: I have anaconda3 using python 3.5. I wanted to experiment with something in python 2.7 so I opened the anaconda command prompt and ran: conda create -n py27 python=2.7 anaconda In retrospect that may have been overkill; I didn't need everything in anaconda. I now want to remove it. What I tried I looked for a uninstall executable for the py27, but couldn't find one the docs say to: conda - conda uninstall (but that returned: could not locate 'conda--' I also tried looking in control manager (windows) to see if it was available to uninstall, but it was not Question: How do I undo conda create -n py27 python=2.7 anaconda? That is to say, I want to go back to my original anaconda3 python 3.5 and no py27.
downvote count: 0
has title: Anaconda: Undo conda create
tagged with: jupyter
has answer: http://stackoverflow.com/a/51455556
favorite count: 0
accepted answer: http://stackoverflow.com/a/51455556
upvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: anaconda
possible better answer: http://stackoverflow.com/a/51455550
score: 1
has answer: http://stackoverflow.com/a/51455550

http://stackoverflow.com/q/51351936
accepted answer: http://stackoverflow.com/a/51351988
has title: py-3 | Trying to call a function based on an input doesnt work properly
downvote count: 1
has comment: http://stackoverflow.com/comment/89676431
type: Question
has body: this is my problem :/ So I 've been working in this project but I cannot find any answer to my question... why should I enter the letter C or c many times in order to call the c() function and sometimes doesn't even work? Is my script correct? Script: def c(): print ('do something') def s(): print ('do something else') def main(): if input() == 'S' or input() == 's': print ('Please enter the number you want to start with:') s() elif input() == 'C' or input() == 'c': print ('Please enter the number you want to check:') c() else: print ('Please enter either S or C') main() print ('You want to Start with or Check a number? Enter S or C.') main() script result 1: You want to Start with or Check a number? Input S or C. c c c c do something script result 2: You want to Start with or Check a number? Input S or C. c C c C Please input either S or C You want to Start with or Check a number? Input S or C. EDIT: I am sorry for the poor quality of the post but it's my first one!
tagged with: if-statement
upvote count: 0
score: -1
has comment: http://stackoverflow.com/comment/89676475
has answer: http://stackoverflow.com/a/51351988
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: input
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/89904681
type: QuestionComment
has text: OK, but `import Cookies` is just going to fail with an `ImportError`., because there is no such module. So either you're not really running Python 3, or you've installed some third-party library you're not telling us about.
comment on: http://stackoverflow.com/q/51461881
score: 0
type: Comment

http://stackoverflow.com/q/51405723
tagged with: python
tagged with: curl
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51406631
has body: I'm using the sh module in Python to convert my curl commands into Python, but I get an error because I'm using multiple F flags in the curl call in Python. Here is the original curl code: curl -u admin:admin -F x=y http://localhost:8080/foo curl -u admin:admin -F :operation=copy -F :dest=/foo/bar http://localhost:8080/foo My code is here: def exploit(url, username, password): sh.curl(url, F = "x=y", u = "%s:%s" %(username, password)) sh.curl(url, F = ":operation=copy", F = ":dest=/foo/bar", u = "%s:%s" %(username, password)) def main(): #default username and password is admin:admin username = "admin" password = "admin" exploit("http://localhost:8080/foo", username, password) Here's the error message: File "/Users/Winston/Desktop/sling_exploit.py", line 7 sh.curl(url, F = ":operation=copy", F = ":dest=/foo/bar", u = "%s:%s" %(username, password)) SyntaxError: keyword argument repeated Can anyone help me find a solution? Any help would be appreciated. Thanks.
type: Question
has comment: http://stackoverflow.com/comment/89782710
score: 0
has answer: http://stackoverflow.com/a/51406631
answer count: 1
has title: Using multiple identical flags in curl with Python's sh module

http://stackoverflow.com/comment/89664767
type: Comment
has text: Are you freaking kidding me. This was a complete longshot. Just a note. Originally the "do_greet" definition was inside the console class, but in order for your solution to work it has to be in the main program, not inside a class or so. Also when I run it I get two things printed, "None" is printed followed by what I actually wanted to print. Not sure if I care about that or not. It would be nice if "None" didn't print though. With that said, I found a way to emulate loops in the cmd module. You can simply edit the self.cmdqueue list to effectively loop through whatever you want.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51345522

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

http://stackoverflow.com/q/51394970
has comment: http://stackoverflow.com/comment/89763106
has comment: http://stackoverflow.com/comment/89761283
has comment: http://stackoverflow.com/comment/89761201
answer count: 1
score: 0
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/51395538
accepted answer: http://stackoverflow.com/a/51395538
has title: Why the probability density value of pandas is too large
has body: I am using pandas to draw probability density, and my data are described as follow: count 636149.000000 mean 3.040828 std 3.752975 min 0.000000 25% 0.050000 50% 1.050000 75% 5.050000 max 59.200000 My code as follows: df['data'].hist(bins=1000,density=1) plt.show() The results are shown as shown in the picture. I wonder why my values has reached 5, and should not normally be less than 1?How should I correct it?
type: AnsweredQuestion
tagged with: matplotlib
type: Question

http://stackoverflow.com/a/51406307
score: 2
has body: This is the signature of the Firefox webdriver: class selenium.webdriver.firefox.webdriver.WebDriver(firefox_profile=None, firefox_binary=None, timeout=30, capabilities=None, proxy=None, executable_path='geckodriver', options=None, log_path='geckodriver.log', firefox_options=None, service_args=None) The first argument is a firefox profile, not the driver executable. You'll have to use a keyword argument. driver = webdriver.Firefox(executable_path=driverpath) I guess you copied an example using the webdriver.Chrome, which takes executable_path as it's first argument. They do not have the same signature.
downvote count: 0
answers question: http://stackoverflow.com/q/51405932
upvote count: 2
type: Answer

http://stackoverflow.com/a/51340484
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51340386
score: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/51340386
has body: You might want to consider using the googletrans package. from googletrans import Translator translator = Translator() text = translator.translate('text', src='en', dest='ru') print(text.text)
upvote count: 5

http://stackoverflow.com/a/51402353
type: Answer
answers question: http://stackoverflow.com/q/51392167
score: 0
has body: You don't let it go out of scope after deleting. It is removed from everything Qt, but Python still has the node variable you are using to reference the item.
has comment: http://stackoverflow.com/comment/89775492
has comment: http://stackoverflow.com/comment/89776273
has comment: http://stackoverflow.com/comment/89775873

http://stackoverflow.com/q/51434317
favorite count: 0
type: Question
score: -1
accepted answer: http://stackoverflow.com/a/51434527
has body: I am trying to scrape email address from below URL. myurl="https://www.charitychoice.co.uk/alzheimers-research-uk" agent = {'User-Agent': 'Magic Browser'} req1 = requests.get(myurl, headers=agent, verify=False) soup2 = BeautifulSoup(req1.content, "lxml") for email in soup2.findAll('div', {"class": "charity-contact-details"}): for email1 in email.findAll('p'): for email2 in email1.findAll('span', {"itemprop": "email"}): for email3 in email2.findAll('a'): email4 = email3.text print(email4) It does not print the email that i expected. It works with selenium PhantomJS parser which takes long time to display email address Please help on this with right parser to return email address instantly
tagged with: web-scraping
tagged with: python
downvote count: 1
answer count: 1
has title: Python request does not return email address while scraping in python3
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/51434527

http://stackoverflow.com/q/51426895
favorite count: 0
has answer: http://stackoverflow.com/a/51436173
has comment: http://stackoverflow.com/comment/89851057
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89849654
linked to: http://stackoverflow.com/q/50212082
type: AnsweredQuestion
has title: Can't import models in tasks.py with Celery + Django
has comment: http://stackoverflow.com/comment/89825431
has comment: http://stackoverflow.com/comment/89850027
downvote count: 1
has answer: http://stackoverflow.com/a/51649098
tagged with: celery
type: Question
has comment: http://stackoverflow.com/comment/89825668
has comment: http://stackoverflow.com/comment/89825112
has comment: http://stackoverflow.com/comment/89825302
upvote count: 5
linked to: http://stackoverflow.com/q/38876482
has comment: http://stackoverflow.com/comment/89850996
score: 4
linked to: http://stackoverflow.com/q/36755583
has answer: http://stackoverflow.com/a/51649564
tagged with: python-import
answer count: 3
has body: I want to create a background task to update a record on a specific date. I'm using Django and Celery with RabbitMQ. I've managed to get the task called when the model is saved with this dummy task function: tasks.py from __future__ import absolute_import from celery import Celery from celery.utils.log import get_task_logger logger = get_task_logger(__name__) app = Celery('tasks', broker='amqp://localhost//') @app.task(name='news.tasks.update_news_status') def update_news_status(news_id): # (I pass the news id and return it, nothing complicated about it) return news_id this task is called from my save() method in my models.py from django.db import models from celery import current_app class News(models.model): (...) def save(self, *args, **kwargs): current_app.send_task('news.tasks.update_news_status', args=(self.id,)) super(News, self).save(*args, **kwargs) Thing is I want to import my News model in tasks.py but if I try to like this: from .models import News I get this error : django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. This is how mi celery.py looks like from __future__ import absolute_import, unicode_literals from celery import Celery import os # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') app = Celery('myapp') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) I have already tried…
accepted answer: http://stackoverflow.com/a/51649098
possible better answer: http://stackoverflow.com/a/51436173

http://stackoverflow.com/a/51418835
has body: key = {next((s for s in list_one if v in s), None): i for i, v in enumerate(list_two)} print(sorted(list_one, key=key.get)) This outputs: ['a78', '67b', 'c11']
type: Answer
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/89809159
answers question: http://stackoverflow.com/q/51418552
accepted answer of: http://stackoverflow.com/q/51418552
score: 4
has comment: http://stackoverflow.com/comment/89808975
has comment: http://stackoverflow.com/comment/89809664
has comment: http://stackoverflow.com/comment/89810100
has comment: http://stackoverflow.com/comment/89810165
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89809336

http://stackoverflow.com/a/51433629
accepted answer of: http://stackoverflow.com/q/51433523
answers question: http://stackoverflow.com/q/51433523
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89874700
has body: A variable that is created within a function is local, so it will be deleted when it is finished executing, and sec_win is so it will be displayed but an instant later it will be removed, the solution is to create it before and only show it when necessary. import sys from PyQt4.QtCore import * from PyQt4.QtGui import * app = QApplication(sys.argv) main_window = QWidget() main_window.setWindowTitle("Keep It Safe V1.5") main_window.setWindowIcon(QIcon('lock.png')) main_window.resize(350, 180) main_window.move(500, 200) login_btn = QPushButton('Login', main_window) login_btn.resize(150, 30) login_btn.move(100, 120) User = QLineEdit(main_window) User.resize(250, 30) User.move(50, 10) User.setPlaceholderText('Enter your user name') password = QLineEdit(main_window) password.resize(250, 30) password.move(50, 60) password.setPlaceholderText('Enter your passsword') password.setEchoMode(QLineEdit.Password) check = QCheckBox(main_window, text="I accept the terms and policies") check.move(50, 95) sec_win =QWidget() def login_check(): user = User.text() Pass = password.text() if user == "Admin" and Pass == "admin" and check.isChecked(): print("Clicked") l = QLabel(sec_win , text = "second window opened") sec_win.show() else: fai = QMessageBox.warning(main_window, "Error", "Incorrect user name or passwprd") login_btn.clicked.connect(login_check) main_window.show() sys.exit(app.exec_())
type: Answer

http://stackoverflow.com/comment/89702952
comment on: http://stackoverflow.com/a/51333062
score: 1
has text: no in first method, if found at start, it will return empty list for previous, and if found at end will return empty list for next one.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89729950
comment on: http://stackoverflow.com/q/51379050
has text: empty space means zero length string
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89727699
has text: In case there is a ` Close ` on page you still think that there is no need to specify tag name? Also note that your code is not a Python
type: Comment
comment on: http://stackoverflow.com/a/51377858
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89821022
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51424392
has text: Note the requirement for a [mcve], not pseudocode. Context is important. If `fetch_transaction_invoice` doesn't actually need any class or instance state, why is it even in a class?

http://stackoverflow.com/comment/89882989
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51454466
type: QuestionComment
has text: I have posted the link to data I am using please check it out. @JamesPhillips

http://stackoverflow.com/comment/97528180
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51405692
type: AnswerComment
has text: What is PVer4 and what I need to do to enable it?

http://stackoverflow.com/comment/89813316
type: QuestionComment
has text: What exactly does your csv contains ?
score: 0
comment on: http://stackoverflow.com/q/51421079
type: Comment

http://stackoverflow.com/comment/89661662
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51343356
has text: Awesome! Thank you so much!
type: AnswerComment

http://stackoverflow.com/comment/89766558
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51397640
has text: The use of the `yield` keyword in the `__iter__` method as if it was a generator I find it very interesting, and exactly addresses my problem. Do you know where is it documented?

http://stackoverflow.com/q/51452279
tagged with: dataframe
has answer: http://stackoverflow.com/a/51452332
type: Question
answer count: 2
has title: Python analysis of dataset of prescriptions - loop terminates early, and no output file
downvote count: 0
has body: I have this input data: id,prescriber_last_name,prescriber_first_name,drug_name,drug_cost 1000000001,Smith,James,AMBIEN,100 1000000002,Garcia,Maria,AMBIEN,200 1000000003,Johnson,James,CHLORPROMAZINE,1000 1000000004,Rodriguez,Maria,CHLORPROMAZINE,2000 1000000005,Smith,David,BENZTROPINE MESYLATE,1500 The output is supposed to be as follows: drug_name,num_prescriber,total_cost CHLORPROMAZINE,2,3000 BENZTROPINE MESYLATE,1,1500 AMBIEN,2,300 But instead I get the following output: AMBIEN 2 300 CHLORPROMAZINE 0 0 BENZTROPINE MESYLATE 0 0 Any suggestions would be appreciated! My code is below: fileHandle = """ id,prescriber_last_name,prescriber_first_name,drug_name,drug_cost 1000000001,Smith,James,AMBIEN,100 1000000002,Garcia,Maria,AMBIEN,200 1000000003,Johnson,James,CHLORPROMAZINE,1000 1000000004,Rodriguez,Maria,CHLORPROMAZINE,2000 1000000005,Smith,David,BENZTROPINE MESYLATE,1500 """ input_data = re.sub(r'(\n)', r',\1', fileHandle) fields = input_data.split(',') del fields[0] NumberOfRows = round(len(fields)/5) NumberOfCols = 5 length_of_fields=len(fields) # Expected output: drug_name,number_of_prescribers,total_cost # drug_name at indices 3 (title), 8, 13, 18, 23, 28 # drug_cost at indices 4 (title), 9, 14, 19, 24, 29 #outputfile = open('/output/top_cost_drug.txt','w') # get list of drug names i=8 j=0 drug_name_list=list() drug_name_indices=list() while i&lt;=length_of_fields: drug_name_list.append(fields[i]) drug_name_indices.append(i) i=i+5; j=j+1; # find unique names (same as drug_name_list but without repetition) unique_drug_list = list() # traverse for all elements for x in drug_name_list: # check if exists in unique_name_list or not if x not in unique_drug_list: unique_drug_list.append(x) i=0 j=0 number_of_unique_drugs=len(unique_drug_list) unique_cost_list=[0]*number_of_unique_drugs number_of_prescribers = [0]*number_of_unique_drugs #while i&lt;len(drug_name_list): # while j&lt;number_of_unique_drugs: # if drug_name_list[i]==unique_drug_list[j]: # drug_name_index=d…
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51452369
tagged with: python
has comment: http://stackoverflow.com/comment/89893059
score: 2

http://stackoverflow.com/q/51426583
type: Question
has body: I am trying to find a certain sprite in a collision group. In this case, My code checks every platform to see if the player is touching it. If the player is touching the platform, I want the player's bottom y to become the platform's (that the player is touching) top y. I do not know how to grab a certain platform, and edit the attributes of that one. How would I edit my code to make this work? import pygame import random WIDTH = 500 HEIGHT = 400 FPS = 30 WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) playerImage = "blockBandit/BlockBandit.png" class Player(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((50, 50)) self.image = pygame.image.load(playerImage).convert() self.rect = self.image.get_rect() self.rect.center = (WIDTH / 2, HEIGHT / 2) self.vx = 0 self.vy = 0 class Platform(pygame.sprite.Sprite): def __init__(self, x, y, w, h): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((w, h)) self.image.fill(GREEN) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y pygame.init() pygame.mixer.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Block Bandit") clock = pygame.time.Clock() allPlatforms = pygame.sprite.Group() all_sprites = pygame.sprite.Group() player = Player() p1 = Platform(0, HEIGHT - 40, WIDTH, 40) all_sprites.add(p1) allPlatforms.add(p1) all_sprites.add(player) def moveCharacter(object): keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: object.vx += -2 if keys[pygame.K_RIGHT]: object.vx += 2 if keys[pygame.K_UP]: object.vy -= 12 pygame.quit() object.vx = object.vx * 0.9 if abs(object.vx) &lt; 1: object.vx = 0 if abs(object.vx) &gt; 10: if object.vx &lt; 0: object.vx = -10 else: object.vx = 10 object.vy = object.vy + 1 object.rect.x += object.vx object.rect.y += object.vy hits = pygame.sprite.spritecollide(object, allPlatforms, False) if hits: # object.rect.y = hits[0].rect.m…
answer count: 1
downvote count: 0
tagged with: pygame
has answer: http://stackoverflow.com/a/51427839
favorite count: 0
tagged with: python-3.x
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has title: Get a specific sprite from a group in Pygame
has comment: http://stackoverflow.com/comment/89826866
accepted answer: http://stackoverflow.com/a/51427839

http://stackoverflow.com/a/51353621
score: 0
answers question: http://stackoverflow.com/q/51350025
type: Answer
has body: As per What does it mean when the standard deviation is higher than the mean? What does that tell you about the data? - Quora, SD is a measure of "spread" and mean is a measure of "position". As you can see, these are more or less independent things. Now, if all your samples are positive, SD cannot be greater than the mean because of the way it's calculated, but 2 or 3 SDs very well can. So, basically, SD being roughly equal to the mean means that your data are all over the place. Now, a random variable that's strictly positive indeed cannot be normally distributed. But for a rough estimation, seeing that you still have a bell shape, we can pretend it is and still use SD as a rough measure of the spread (though, since 2 and 3 SD can go into negatives, they lack any physical meaning here whatsoever and so are unusable for the sake of our pretention): E.g. to get a rough prediction of grass growth, you can still take the mean and apply whatever growth model you're using to it -- that will get the new, prospective mean. Then applying the same to mean±SD will give an idea of the new SD. This is very rough, of course. But to get any better, you'll have to somehow check which distribution you're dealing with and use its peak and spread characteristics instead of mean and SD. And in any case, your prediction will not be any better than your growth model -- studies of which are anything but conclusive judging by e.g. https://onlinelibrary.wiley.com/doi/pdf/10.1111/j.1365-3040.2005.01490.x (not a single formula there).

http://stackoverflow.com/a/51463364
type: AcceptedAnswer
downvote count: 0
score: 1
has body: Use: np.random.seed(234) arrays = [np.array(['bar', 'bar', 'bar', 'bar', 'baz','baz', 'baz', 'qux', 'qux','qux', 'qux','foo']), np.array(['AA', 'AB', 'AC','AD', 'BA', 'BB', 'BC', 'CA', 'CB', 'CC', 'CD', 'DA'])] df = pd.DataFrame(np.random.randn(12, 1), index=arrays) print (df) 0 bar AA 0.818792 AB -1.043551 AC 0.350901 AD 0.921578 baz BA -0.087382 BB -3.128885 BC -0.969733 qux CA 0.934666 CB 0.043866 CC 1.425216 CD -0.557063 foo DA 0.926824 Solution with SeriesGroupBy.nlargest: s = df.groupby(level=0)[0].nlargest(2).reset_index(level=0, drop=True) print (s) bar AD 0.921578 AA 0.818792 baz BA -0.087382 BC -0.969733 foo DA 0.926824 qux CC 1.425216 CA 0.934666 Name: 0, dtype: float64 If need avoid sorting of MultiIndex: df1 = (df.groupby(level=0, sort=False)[0] .nlargest(2) .reset_index(level=0, drop=True) .to_frame()) print (df1) 0 bar AD 0.921578 AA 0.818792 baz BA -0.087382 BC -0.969733 qux CC 1.425216 CA 0.934666 foo DA 0.926824 Another solution, working in pandas 0.23.0+ with sort_values and GroupBy.head: df.index.names = ['lvl1','lvl2'] df.columns = ['a'] s = df.sort_values(['lvl1', 'a'], ascending=[True, False]).groupby(level=0).head(2) print (s) a lvl1 lvl2 bar AD 0.921578 AA 0.818792 baz BA -0.087382 BC -0.969733 foo DA 0.926824 qux CC 1.425216 CA 0.934666
has comment: http://stackoverflow.com/comment/89895915
type: Answer
has comment: http://stackoverflow.com/comment/89895893
upvote count: 1
has comment: http://stackoverflow.com/comment/89895885
has comment: http://stackoverflow.com/comment/89895905
accepted answer of: http://stackoverflow.com/q/51463332
has comment: http://stackoverflow.com/comment/89895894
has comment: http://stackoverflow.com/comment/89895971
answers question: http://stackoverflow.com/q/51463332
has comment: http://stackoverflow.com/comment/89895982

http://stackoverflow.com/comment/89643877
type: QuestionComment
comment on: http://stackoverflow.com/q/51334265
has text: `randint` includes both endpoints. If you're using it as an index, you probably want `randrange`, which excludes the end value, just like `range` does.
score: 4
type: Comment

http://stackoverflow.com/comment/89798100
type: Comment
has text: You need to read about how python deals with positional arguments, this is not C...
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51413267

http://stackoverflow.com/q/51350462
has comment: http://stackoverflow.com/comment/89673561
has comment: http://stackoverflow.com/comment/89674629
answer count: 1
has comment: http://stackoverflow.com/comment/89676710
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51352758
has comment: http://stackoverflow.com/comment/89674997
has comment: http://stackoverflow.com/comment/89673596
has comment: http://stackoverflow.com/comment/89676847
tagged with: python
has comment: http://stackoverflow.com/comment/89677983
accepted answer: http://stackoverflow.com/a/51352758
has comment: http://stackoverflow.com/comment/89673830
has comment: http://stackoverflow.com/comment/89675019
has comment: http://stackoverflow.com/comment/89673612
type: AnsweredQuestion
has body: I found some code which I want to incorporate into my Python encryption program. It should encrypt the files in the code's same directory, and I want it to target a directory. But, it's written in Python 2 and when I change around some code to fit Python 3, I get the following error: Traceback (most recent call last): File "/home/pi/Desktop/Projects/FyleCript/Dev Files/encryption.py", line 77, in <module> encrypt(SHA256.new(password).digest(), str(Tfiles)) File "/usr/lib/python3/dist-packages/Crypto/Hash/SHA256.py", line 88, in new return SHA256Hash().new(data) File "/usr/lib/python3/dist-packages/Crypto/Hash/SHA256.py", line 75, in new return SHA256Hash(data) File "/usr/lib/python3/dist-packages/Crypto/Hash/SHA256.py", line 72, in __init__ HashAlgo.__init__(self, hashFactory, data) File "/usr/lib/python3/dist-packages/Crypto/Hash/hashalgo.py", line 51, in __init__ self.update(data) File "/usr/lib/python3/dist-packages/Crypto/Hash/hashalgo.py", line 69, in update return self._hash.update(data) TypeError: Unicode-objects must be encoded before hashing But the code works perfectly in Python 2. I have tried looking for similar questions on SO and Googling, but no help. Code: def encrypt(key, filename): chunksize = 64 * 1024 outFile = os.path.join(os.path.dirname(filename), "(encrypted)"+os.path.basename(filename)) filesize = str(os.path.getsize(filename)).zfill(16) IV = '' for i in range(16): IV += chr(random.randint(0, 0xFF)) encryptor = AES.new(key, AES.MODE_CBC, IV) with open(filename, "rb") as infile: with open(outFile, "wb") as outfile: outfile.write(filesize) outfile.write(IV) while True: chunk = infile.read(chunksize) if len(chunk) == 0: break elif len(chunk) % 16 !=0: chunk += ' ' * (16 - (len(chunk) % 16)) outfile.write(encryptor.encrypt(chunk)) def decrypt(key, filename): outFile = os.path.join(os.path.dirname(filename), os.path.basename(filename[11:])) chunksize = 64 * 1024 with open(filename, "rb") as infile: filesize = infile.read(16) IV = infile.read(16) …
has title: Python encryption unicode error when converting from Python 2 to python 3
upvote count: 1
tagged with: pycrypto
has comment: http://stackoverflow.com/comment/89673908
has comment: http://stackoverflow.com/comment/89675033
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89674743
has comment: http://stackoverflow.com/comment/89674693
tagged with: python-unicode
has comment: http://stackoverflow.com/comment/89673585
has comment: http://stackoverflow.com/comment/89674809
has comment: http://stackoverflow.com/comment/89674023
has comment: http://stackoverflow.com/comment/89673693
tagged with: python-2.7
score: 0

http://stackoverflow.com/a/51401217
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51350314
accepted answer of: http://stackoverflow.com/q/51350314
type: AcceptedAnswer
has body: The problem was that as I am using a custom user model in my common.py I had this: AUTH_USER_MODEL = 'accounts.User' With the changes I was doing, I also add the prefix apps to this setting, don't know why this setttings it works different, but instead of adding the prefix apps I had to leave it like it was before. I think it maybe cause of the initial migration, that some how as is in the initial migration where the custom model is set up, probably the route is store somewhere and that maybe the thing causing the problem

http://stackoverflow.com/comment/89687249
has text: `for` and `if` are lowercase and you need a colon after 30, and further indentation of `print`
score: 1
comment on: http://stackoverflow.com/q/51357570
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51460264
has comment: http://stackoverflow.com/comment/89890425
has comment: http://stackoverflow.com/comment/89890414
has title: Installing OPENCV with cmake failing. Python.h
tagged with: python
has comment: http://stackoverflow.com/comment/89890326
has comment: http://stackoverflow.com/comment/89890586
tagged with: c++
has comment: http://stackoverflow.com/comment/89890644
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/64408415
tagged with: opencv
has comment: http://stackoverflow.com/comment/89890646
type: UnansweredQuestion
has body: When i try to make in opencv/build/ as this guide tells me: https://intelligentbee.com/2015/11/18/build-a-face-detector-on-os-x-using-opencv-and-c/ /Users/oscarlajgaard/opencv-3.3.1/modules/python/src2/cv2.cpp:6:10: fatal error: 'Python.h' file not found #include &lt;Python.h&gt; ^~~~~~~~~~ CMAKE Config PYTHON3 PYTHON3_EXECUTABLE = /usr/local/bin/python3 PYTHON3_INCLUDE_DIR = /usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/include/python3.7m/ PYTHON3_LIBRARY = /usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/libpython3.7.dylib
type: Question

http://stackoverflow.com/a/51389274
downvote count: 0
answers question: http://stackoverflow.com/q/51389042
type: Answer
has body: auto_now takes precedence (obviously, because it updates field each time, while auto_now_add updates on creation only). Here is the code for DateField.pre_save method: def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = datetime.date.today() setattr(model_instance, self.attname, value) return value else: return super().pre_save(model_instance, add) As you can see, if auto_now is set or both auto_now_add is set and the object is new, the field will receive current day. The same for DateTimeField.pre_save: def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = timezone.now() setattr(model_instance, self.attname, value) return value else: return super().pre_save(model_instance, add)
upvote count: 69
score: 69
accepted answer of: http://stackoverflow.com/q/51389042
type: AcceptedAnswer

http://stackoverflow.com/comment/131742961
has text: Please consider adding some explanation describing how the command solves the problem.
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/74603676

http://stackoverflow.com/a/51361498
downvote count: 0
has comment: http://stackoverflow.com/comment/89695970
has comment: http://stackoverflow.com/comment/89696285
score: 4
accepted answer of: http://stackoverflow.com/q/51361426
answers question: http://stackoverflow.com/q/51361426
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89695758
has body: I think problem is in pivot_table default aggregate function is mean, so strings columns are excluded. So need custom function, also order is changed, so reindex is necessary: f = lambda x: x.sum() if np.issubdtype(x.dtype, np.number) else ', '.join(x) cols = df.columns[~df.columns.isin(['No','Type','Task'])].tolist() piv = (pd.pivot_table(df, index=['No','Type','Task'], values = cols, aggfunc=f).reindex(columns=cols)) print (piv) Color Price Unit Pers.ID No Type Task 123 A First blue 10 E 45 B Second red 5 E 6 C First blue 1 E 6 523 A Second black 12 E 43 C Third red 12 E 1 D First red 12 E 9 765 A Fifth red 18 E 2 Another solution with groupby and same aggregation function, ordering is not problem: df = (df.groupby(['No','Type','Task']) .agg(lambda x: x.sum() if np.issubdtype(x.dtype, np.number) else ', '.join(x))) print (df) Color Price Unit Pers.ID No Type Task 123 A First blue 10 E 45 B Second red 5 E 6 C First blue 1 E 6 523 A Second black 12 E 43 C Third red 12 E 1 D First red 12 E 9 765 A Fifth red 18 E 2 But if need set first 3 columns to MultiIndex only: df = df.set_index(['No','Type','Task']) print (df) Color Price Unit Pers.ID No Type Task 123 A First blue 10 E 45 B Second red 5 E 6 C First blue 1 E 6 523 A Second black 12 E 43 C Third red 12 E 1 D First red 12 E 9 765 A Fifth red 18 E 2
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/89696241

http://stackoverflow.com/q/51324477
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/477486
linked to: http://stackoverflow.com/q/477486
has comment: http://stackoverflow.com/comment/89627401
has comment: http://stackoverflow.com/comment/89630831
tagged with: loops
type: Question
has title: How to give step values as float in python for loop?
has body: I want to run the for loop from 0 to 64 with step size of 0.05. If I use the range function it gives a Typeerror. My code for i in range(0,64,2): P=0+i Q=2+i for s in range(P,Q,0.05): X=s I am actually converting a FORTRAN code into python and in that code, 0.05 was usesd as the step size. The code: DO 20 I =0,64,2 P=0+i Q=2+i DO 10 s=P,Q,0.05 X=s IF((X.GE.P).AND.(X.LT.(P+Q/2))) THEN Y = -1 ELSEIF (X.GE.(P+Q/2).AND.(X.LT.Q)) Y=1 ENDIF WRITE(*,*)y Please help me how can I convert this code properly into python. Edit: Please check the rest of the code and I dont understand what this ENDIF statement does.
answer count: 2
has comment: http://stackoverflow.com/comment/89624101
has comment: http://stackoverflow.com/comment/89630652
upvote count: 1
has comment: http://stackoverflow.com/comment/89630907
has comment: http://stackoverflow.com/comment/89627177
has answer: http://stackoverflow.com/a/51324555
score: 0
has comment: http://stackoverflow.com/comment/89631025
has comment: http://stackoverflow.com/comment/89627304
downvote count: 1
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/89627467
has answer: http://stackoverflow.com/a/51324541
tagged with: fortran

http://stackoverflow.com/comment/89696152
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51361855
has text: Hey! Thanks for the answer. What is 'delay' doing?
type: AnswerComment

http://stackoverflow.com/a/51395538
accepted answer of: http://stackoverflow.com/q/51394970
score: 0
has body: As pointed out in one of the comments, values not necessarily need to be 1 at max, but the area of all the bins together should be 1. As you can read in the doc: density : boolean, optional If True, the first element of the return tuple will be the counts normalized to form a probability density, i.e., the area (or integral) under the histogram will sum to 1. This is achieved by dividing the count by the number of observations times the bin width and not dividing by the total number of observations. If stacked is also True, the sum of the histograms is normalized to 1. The area of 1 bin is (obviously) the frequency times the bin-width. Since you have 1000 bins and a range of [0,59.2]. Your bin width is 0.0592, so that results in quite small areas per bin and thus summing all 1000 'small' areas gives an area under the curve of 1. You could check this with np.histogram.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51394970
type: Answer
has comment: http://stackoverflow.com/comment/113038777
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/51472680
downvote count: 1
type: Question
tagged with: flask
answer count: 1
favorite count: 0
has body: I am trying to add two numbers and display it in a new html page, the code follows from flask import Flask,render_template,request app=Flask(__name__) @app.route('/') @app.route('/<name>') def index(name='Priya'): name=request.args.get('name',name) return "I am happy,{}".format(name) @app.route('/add/<int:num1>/<float :num2>') @app.route('/add/<float:num1>/<float :num2>') @app.route('/add/<int:num1>/<int :num2>') @app.route('/add/<float:num1>/<int :num2>') def add(num1,num2): #return str(num1+num2) return """ Addition game! {}+{} = {} """.format(num1,num2,num1+num2) if __name__ == '__main__': app.run(debug=True)
type: UnansweredQuestion
has title: Getting malformed url route-flask
score: 6
tagged with: python
has answer: http://stackoverflow.com/a/51479746
upvote count: 7

http://stackoverflow.com/a/51412552
type: Answer
downvote count: 0
has body: That setting is renamed to locale in recent versions: https://fullcalendar.io/docs/locale For example: $('#calendar').fullCalendar({ locale: 'fr' });
score: 3
answers question: http://stackoverflow.com/q/51412175
upvote count: 3

http://stackoverflow.com/comment/89731998
has text: Maybe you can use try https://github.com/websocket-client/websocket-client. If you just want to test connect to a web socket server, you can just use something simple like curl, ex: https://gist.github.com/htp/fbce19069187ec1cc486b594104f01d0
score: 0
comment on: http://stackoverflow.com/q/51380145
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51455383
possible better answer: http://stackoverflow.com/a/51455523
has answer: http://stackoverflow.com/a/51455523
tagged with: python-requests
type: Question
has comment: http://stackoverflow.com/comment/89880169
accepted answer: http://stackoverflow.com/a/51455413
score: 0
has title: BeautifulSoup4 doesn't find elements properly
answer count: 2
tagged with: beautifulsoup
tagged with: python-3.x
has body: I am using requests and bs4 to extract the first preview from the link http://duckduckgo.com/?q=who+is+harry+potter However, when i try to use bs4's find method to find he div with the class 'result__snippet', it returns None. But when I saved the whole webpage to my hard disk and opened it directly and parsed it with bs4, soup.find('div', class_='result__snippet').get_text() returns the perfect output. Any help?
tagged with: python
has answer: http://stackoverflow.com/a/51455413
type: AnsweredQuestion

http://stackoverflow.com/comment/89687420
comment on: http://stackoverflow.com/q/51353038
has text: Using `np.apply_along_axis()` should be slightly faster than an normal for loop. The rest depends on your amount of RAM. With about 1.5 GB free you should be able to calculate without a for loop. If you have less, you could iterate over slices of say 100000 vectors at a time.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51366170
has title: how do i refresh the answer in a popup
accepted answer: http://stackoverflow.com/a/51366482
has comment: http://stackoverflow.com/comment/89705049
type: Question
has comment: http://stackoverflow.com/comment/89705032
has comment: http://stackoverflow.com/comment/89704675
downvote count: 0
has comment: http://stackoverflow.com/comment/89704835
has comment: http://stackoverflow.com/comment/89704843
has body: So I am just trying to make an dice roller with gui. I created a popup window which displays a random number from 1 to 6 random.randint(1,6). I asigned it to a variable called number number = random.randint(1,6) but it always gives the same number. I just need it to not spit out always the same number when i click on the button def popup_showinfo(): showinfo("You rolled", number) number = random.randint(1,6) class Application(ttk.Frame):` def __init__(self, master): tk.Frame.__init__(self, master) self.pack() self.button_showinfo = ttk.Button(self, text="Roll", command=popup_showinfo) self.button_showinfo.pack() root = tk.Tk() app = Application(root) root.mainloop()
answer count: 1
score: 1
has answer: http://stackoverflow.com/a/51366482
favorite count: 0
has comment: http://stackoverflow.com/comment/89704767
tagged with: tkinter
upvote count: 1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89705040
has comment: http://stackoverflow.com/comment/89704893

http://stackoverflow.com/q/51342521
has body: Python newbiew: I'm using a dict list to store an ascii character along with a score and what I would like to do now is, fill up another dict list that contains all duplicate characters (independent of the score). How can I do this? I'm appendindg the values onto the list with: lpdictlist.append({"ascii_code":a[2],"confidence":a[6]})
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/89660164
accepted answer: http://stackoverflow.com/a/51342598
has title: How can i select duplicates in a dict list
type: Question
has comment: http://stackoverflow.com/comment/89658484
has comment: http://stackoverflow.com/comment/89658741
tagged with: duplicates
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51342598
tagged with: python
tagged with: dictionary
tagged with: append

http://stackoverflow.com/a/51429020
has comment: http://stackoverflow.com/comment/90044827
has comment: http://stackoverflow.com/comment/89831517
downvote count: 0
answers question: http://stackoverflow.com/q/51425127
type: Answer
has body: The iterrows method will give you a pandas.Series object for each row of the data frame, so you can create the place2_coords a bit differently. import geopy.distance import pandas as pd df = pd.read_csv('coordinates.csv', sep=',') site_coords = (38.898556, -77.037852) for index, row in df.iterrows(): place2_coords = (row.Latitude, row.Longitude) x = geopy.distance.vincenty(site_coords, place2_coords )).km print(x) With pandas, looping of the rows isn't the recommended method. Instead, you can apply a function along the columns. def calc_distance(x): site_coords = (38.898556, -77.037852) place2_coords = (x.Latitude, x.Longitude) return geopy.distance.vincenty(site_coords, place2_coords )).km df.apply(calc_distance, axis = 1)
score: 2
has comment: http://stackoverflow.com/comment/89829948
upvote count: 2

http://stackoverflow.com/comment/89918573
comment on: http://stackoverflow.com/q/51474410
score: 0
type: Comment
type: QuestionComment
has text: `for name x in names:` should be changed as `for name_x in name:`

http://stackoverflow.com/comment/89810243
comment on: http://stackoverflow.com/a/51419562
type: AnswerComment
type: Comment
has text: How is that the problem?
score: 1

google-cloud-dataflow
tags question: http://stackoverflow.com/q/51433664
tag name: google-cloud-dataflow
tags question: http://stackoverflow.com/q/51355191
tags question: http://stackoverflow.com/q/51420406
type: Tag

http://stackoverflow.com/comment/89687781
type: QuestionComment
comment on: http://stackoverflow.com/q/51357819
has text: Use a slice. `b.append(a[2:])` (or maybe `extend` instead of `append`)
score: 0
type: Comment

http://stackoverflow.com/q/51383790
answer count: 2
tagged with: sizer
has body: Is there a way to force the BoxSizer to display its elements with a specific gap between them? (closer to each other rather than further) I'm trying to find a way to display 5 StaticText elements closer together so they fit in a small panel, but am only able to fit 4 elements There clearly is space for 5 StaticTexts if they were closer to eachother I assume I could also just make it a single static text with lines but am trying to keep each line as a different object
tagged with: wxpython
has comment: http://stackoverflow.com/comment/89744315
has comment: http://stackoverflow.com/comment/89740220
tagged with: python
has title: How do I make elements in Vertical BoxSizer closer together?
has answer: http://stackoverflow.com/a/51386360
type: UnansweredQuestion
tagged with: static-text
type: Question
has comment: http://stackoverflow.com/comment/89745554
has answer: http://stackoverflow.com/a/51390593
tagged with: wxwidgets
score: 0

http://stackoverflow.com/a/51454824
has comment: http://stackoverflow.com/comment/90581406
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51452112
has body: The spectral colormap has been removed from matplotlib in version 2.2, use "Spectral" or "nipy_spectral" or any other valid colormap. Best do so by obtaining the colormap via the string of its name cmap = cm.get_cmap("Spectral") colors = cmap(a / b)
type: Answer
score: 31
upvote count: 31
answers question: http://stackoverflow.com/q/51452112
has comment: http://stackoverflow.com/comment/105247043

http://stackoverflow.com/comment/89844287
type: QuestionComment
comment on: http://stackoverflow.com/q/51437086
has text: I am not sure I follow, but it might make sense to have a layer which maps the machine's result to something which makes more sense to humans...
score: 0
type: Comment

http://stackoverflow.com/q/51468084
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/89904912
has answer: http://stackoverflow.com/a/51469106
tagged with: return
type: UnansweredQuestion
tagged with: python
has body: I am trying to make a program that asks the user to input numbers, using a while loop and then eventually return how many are odd. Here is my code (I am terrible at formatting so feel free to edit!): count = 0 num = int(input("Enter your number: ")) print ("Here is your number: " + str(num)) while num != -1: if num % 2 == 1: count +=1 input num = int(input("Enter your number: ")) print(num) print(count) NOTE : -1 should not be counted as a value! (this was an instruction included)
has answer: http://stackoverflow.com/a/51468199
tagged with: numbers
has comment: http://stackoverflow.com/comment/89905621
type: Question
has comment: http://stackoverflow.com/comment/89904771
has title: Python Odd Number counting program continues to give me an error
has answer: http://stackoverflow.com/a/51468279

http://stackoverflow.com/comment/89845173
comment on: http://stackoverflow.com/a/51437224
score: 0
type: AnswerComment
type: Comment
has text: Okay. Thanks for the help.

http://stackoverflow.com/comment/117076812
score: 0
type: Comment
has text: How can OP use `toggleMusic` function? The function is not returning any variable and no input parameter. Please update your answer.
type: AnswerComment
comment on: http://stackoverflow.com/a/66220976

http://stackoverflow.com/q/51425667
upvote count: 1
has answer: http://stackoverflow.com/a/51425837
tagged with: arrays
has comment: http://stackoverflow.com/comment/89822624
has answer: http://stackoverflow.com/a/51426830
score: 0
has title: Python: Putting two diffrent entries from one array together
answer count: 3
downvote count: 1
has answer: http://stackoverflow.com/a/51426030
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89823664
possible better answer: http://stackoverflow.com/a/51426030
tagged with: python
tagged with: merge
has comment: http://stackoverflow.com/comment/89822526
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89822634
tagged with: list
accepted answer: http://stackoverflow.com/a/51425837
type: Question
has body: I got stucked with something really easy (probably): I have one list, where list entry [0] should be merged with list entry [1] and [2] with [3] and so on. At the end, after the pairs got merged, I would like to save the outcome in a new list. The for loops I created so far, never worked, so is there maybe someone who could help me? Thank you very much! Like that: list1 = ["A1", "A2", "B1", "B2", "C1", "C2"] list2 = [] # The Output for list2 should be like: ["A1A2", "B1B2", "C1C2"]

http://stackoverflow.com/a/51375699
type: Answer
has comment: http://stackoverflow.com/comment/89723976
has body: You could use datetime to get both the first and the last week and then just everything in between. import datetime import calendar year = datetime.datetime.now().year month = datetime.datetime.now().month first_week = datetime.datetime(year, month, calendar.monthrange(year, month)[0]).isocalendar()[1] last_week = datetime.datetime(year, month, calendar.monthrange(year, month)[1]).isocalendar()[1] print(list(range(first_week, last_week + 1))) from datetime import datetime would save you all the datetime.datetime usage btw.
has comment: http://stackoverflow.com/comment/89723698
score: 4
accepted answer of: http://stackoverflow.com/q/51375564
upvote count: 4
answers question: http://stackoverflow.com/q/51375564
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89723607

http://stackoverflow.com/comment/89704970
has text: Your inner-layer lists probably aren't all the same size.
comment on: http://stackoverflow.com/q/51366329
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51399442
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89769800
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/51489652
has comment: http://stackoverflow.com/comment/89769722
has comment: http://stackoverflow.com/comment/89772487
has title: Unhandled exception in thread started by <function wrapper at 0x7f39d480f230>
upvote count: 1
has body: I get the following error in my Django project: Traceback (most recent call last): File "/home/freddy/environments/py26_env/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/freddy/environments/py26_env/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "/home/freddy/environments/py26_env/local/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/home/freddy/environments/py26_env/local/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/home/freddy/environments/py26_env/local/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/freddy/environments/py26_env/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/home/freddy/environments/py26_env/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/home/freddy/environments/py26_env/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/home/freddy/environments/py26_env/local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/freddy/environments/py26_env/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/freddy/environments/py26_env/local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/freddy/environmen…
type: Question
linked to: http://stackoverflow.com/q/37649934
has comment: http://stackoverflow.com/comment/89769820
has comment: http://stackoverflow.com/comment/89770584
answer count: 1
score: -7
favorite count: 0
downvote count: 8

http://stackoverflow.com/a/51360710
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51360599
accepted answer of: http://stackoverflow.com/q/51360599
has body: You can use NumPy slicing for a vectorised solution: n = Npts A = xrandomsorted res = 12 - 3*A[:n] + 7*A[:n*2:2] - A[:n*3:3] The syntax is akin to Python list slicing syntax, i.e. arr[start : stop : step].
type: Answer
downvote count: 0

http://stackoverflow.com/q/51403653
upvote count: 2
type: UnansweredQuestion
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/51406545
has comment: http://stackoverflow.com/comment/89782553
score: 1
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/89778427
type: Question
answer count: 1
has title: Parse multiple JSON objects to normalize the nested sub parts
has body: I have incoming JSON files which have elements [a,b,c] and a history element that contains nested JSON with same elements [a,b,c]. There could be multiple nested entries or one or none within history element but below is sample on how data looks. Here is an example: { "a": "1", "b": "2", "history": [ { "a": "11", "b": "22", "c": "33" }, { "a": "111", "b": "222", "c": "333" } ], "c":"3" } { "a": "a1", "b": "b1", "history": [ { "a": "a12", "b": "b12", "c": "c12" } ], "c":"c1" } I want to normalize this JSON so that everything looks like {"a": "111", "c": "333", "b": "222"}{"a": "111", "c": "333", "b": "222"}{"a": "1", "c": "3", "b": "2"} I built a simplistic script that reads a file and does a json.loads() and reads "histroy" element. import json j1 = json.loads(j1) if "history" in j1.keys(): j1_hist = j1["history"] with open('/normalzied_json_output', 'w') as f: for i in range(len(j1_hist)): f.write(json.dumps(j1_hist[1])) j1.pop('history', None) f.write(json.dumps(j1)) Basically read all of the history into a variable if it exists and open an output file(normalzied_json_output), and read each nested json entry into the output file and extract only [a,b,c] and appends to the same file. This works at a basic level but I am looking at the possibility of optimizing it. I am expecting a huge volume(100's of thousands) daily and want to know if I can scale this up without too many loops.
has comment: http://stackoverflow.com/comment/89780228
favorite count: 0

http://stackoverflow.com/q/51432641
score: 2
downvote count: 0
tagged with: pandas
answer count: 1
tagged with: nlp
has answer: http://stackoverflow.com/a/51521071
favorite count: 0
has body: I have a text based dataset where I am looking to apply SpaCy's EntityRecognizer to each row for a specific column. I can apply the general spaCy pipeline by doing something like this: df['new_col'] = df['col'].apply(lambda x: nlp(x)) How do I just apply just the entity recongnizer and get its values?
tagged with: spacy
upvote count: 2
type: UnansweredQuestion
tagged with: python
has title: Applying SpaCy's EntityRecognizer to a column within a Pandas dataframe
tagged with: dataframe
type: Question

http://stackoverflow.com/a/51451373
has comment: http://stackoverflow.com/comment/90048085
accepted answer of: http://stackoverflow.com/q/51450366
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89905081
answers question: http://stackoverflow.com/q/51450366
has body: Firstly, you should be aware that pandas allows you to read directly from S3 with something like xyz = pd.read_csv('s3://bucket/file.csv, dtype={..}, encoding='latin-1') however, this does not solve your bad-data problem. Using the python parser engine of regex delimiters might save you, but seems unlikely. The simplest thing to do would be to download the file line-wise and put the bad lines in another output s3 = s3fs.S3FileSystem() with s3.open('bucket/file.csv', 'rb') as fin: with open('out_good.csv', 'wb') as fgood: with open('out_bad.csv', 'wb') as fbad: for line in fin: if ':' in line or '`' in line: fbad.write(line) else: fgood.write(line) The alternative would be to write your own file-like object to read lines, do text decoding and provide read()/readline() methods for pandas to work one (I think it also needs things like readable(), etc).
has comment: http://stackoverflow.com/comment/89941138
type: Answer
has comment: http://stackoverflow.com/comment/89941743
has comment: http://stackoverflow.com/comment/89906176
has comment: http://stackoverflow.com/comment/90049802
has comment: http://stackoverflow.com/comment/89872985
score: 0

http://stackoverflow.com/q/51325979
tagged with: numpy
score: 2
tagged with: function
has answer: http://stackoverflow.com/a/51328626
has comment: http://stackoverflow.com/comment/89627985
favorite count: 0
has comment: http://stackoverflow.com/comment/89627202
has comment: http://stackoverflow.com/comment/89628517
answer count: 1
has comment: http://stackoverflow.com/comment/89627413
has comment: http://stackoverflow.com/comment/89627712
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51328626
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/89627275
has title: Programming a distance
type: AnsweredQuestion
has body: First of all: I am by no means a Python expert, so this question is probably rather easy. Secondly, I worked over more than 2 hours on this and now I've decided I needed help. I want to implement a distance in Python. The distance is given as follows: Where ui and uj are vectors that are given. d is the dimension of that vector. For example: if ui = (1,2,3), then ui_0= 1. Now, this is what I've come up with so far: (here, xi = ui and xj = uj) def dist(xi, xj, k): distances = np.zeros(len(xi)) min1 = (0, 0) min2 = (0, 0) for dim in [0, len(xi)]: for s in [-k, k]: min1 = abs(xi[dim] - xj[dim + s]) min1[-k, k].min() min2 = min(abs(xj[dim] - xi[dim + s])) min2[-k, k].min() distances = max(min1,min2) but it doesn't work. Does anybody know where I've gone wrong? Traceback: Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; File "&lt;input&gt;", line 8, in dist IndexError: invalid index to scalar variable. EDIT: Ok, I tried to look at the case where k is maximal and I've taken the comments of Riley and Wouda into account. I came up with this piece of code: def dist1(xi, xj): for dim in range(len(xi)): for s in range(-dim, len(xi) - dim): return max(min(abs(xi[dim] - xj[dim + s])), min(abs(xj[dim] - xi[dim + s]))) and I still get the error: Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; File "&lt;input&gt;", line 4, in dist1 TypeError: 'numpy.int64' object is not iterable What is going on?
upvote count: 3
has comment: http://stackoverflow.com/comment/89627162
has comment: http://stackoverflow.com/comment/89627288
type: Question

http://stackoverflow.com/q/51373804
upvote count: 2
type: UnansweredQuestion
downvote count: 2
tagged with: python
has body: I was wondering what the time complexity of this function would be in terms of two variables. My guess would be O(a*b), due to the while loop using a and b. def somefunc(a, b): def anotherfunc(current, num_digits): if num_digits == 0: print(current) else: print_01_codes('0' + current, num_digits - 1) print_01_codes('1' + current, num_digits - 1) upper_bound = 0 while True: for i in range(upper_bound): print_01_codes('', a) if upper_bound &gt; b: break upper_bound += 1
type: Question
has answer: http://stackoverflow.com/a/51373947
has comment: http://stackoverflow.com/comment/89719851
has title: What is the run-time complexity of the following algorithm, in terms of a and b?
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/89719745
tagged with: time-complexity
has answer: http://stackoverflow.com/a/51374141
favorite count: 0
has comment: http://stackoverflow.com/comment/89719167

python-2.7
tags question: http://stackoverflow.com/q/51481431
tags question: http://stackoverflow.com/q/51370135
tags question: http://stackoverflow.com/q/51378874
tags question: http://stackoverflow.com/q/51389851
tags question: http://stackoverflow.com/q/51387186
tags question: http://stackoverflow.com/q/51427785
tags question: http://stackoverflow.com/q/51463859
tags question: http://stackoverflow.com/q/51462453
tags question: http://stackoverflow.com/q/51482400
tags question: http://stackoverflow.com/q/51392184
tags question: http://stackoverflow.com/q/51426571
tags question: http://stackoverflow.com/q/51346030
tags question: http://stackoverflow.com/q/51397124
tags question: http://stackoverflow.com/q/51384501
tags question: http://stackoverflow.com/q/51347120
tags question: http://stackoverflow.com/q/51459874
tags question: http://stackoverflow.com/q/51481273
tags question: http://stackoverflow.com/q/51459559
tags question: http://stackoverflow.com/q/51365472
tags question: http://stackoverflow.com/q/51394080
tags question: http://stackoverflow.com/q/51401475
tags question: http://stackoverflow.com/q/51372331
tags question: http://stackoverflow.com/q/51340268
tags question: http://stackoverflow.com/q/51474976
tags question: http://stackoverflow.com/q/51393409
tags question: http://stackoverflow.com/q/51373161
tags question: http://stackoverflow.com/q/51440271
tags question: http://stackoverflow.com/q/51426065
tags question: http://stackoverflow.com/q/51357584
tags question: http://stackoverflow.com/q/51401688
tags question: http://stackoverflow.com/q/51480055
tags question: http://stackoverflow.com/q/51327863
tags question: http://stackoverflow.com/q/51387353
tags question: http://stackoverflow.com/q/51348322
tags question: http://stackoverflow.com/q/51422211
tags question: http://stackoverflow.com/q/51374447
tags question: http://stackoverflow.com/q/51369727
tags question: http://stackoverflow.com/q/51409519
tags question: http://stackoverflow.com/q/51335107
tags question: http://stackoverflow.com/q/51433663
tags question: http://stackoverflow.com/q/51417186
tags question: http://stackoverflow.com/q/51430062
tags question: http://stackoverflow.com/q/51369853
tags question: http://stackoverflow.com/q/51327881
tags question: http://stackoverflow.com/q/51409852
tags question: http://stackoverflow.com/q/51352961
tags question: http://stackoverflow.com/q/51447982
tags question: http://stackoverflow.com/q/51431837
tags question: http://stackoverflow.com/q/51411950
tags question: http://stackoverflow.com/q/51427008
tags question: http://stackoverflow.com/q/51328024
tags question: http://stackoverflow.com/q/51355942
tags question: http://stackoverflow.com/q/51410279
tags question: http://stackoverflow.com/q/51453590
tags question: http://stackoverflow.com/q/51385784
tags question: http://stackoverflow.com/q/51425281
tags question: http://stackoverflow.com/q/51343919
tags question: http://stackoverflow.com/q/51384221
tags question: http://stackoverflow.com/q/51346714
tags question: http://stackoverflow.com/q/51420774
tags question: http://stackoverflow.com/q/51443461
tags question: http://stackoverflow.com/q/51458307
tags question: http://stackoverflow.com/q/51462924
tags question: http://stackoverflow.com/q/51449615
tags question: http://stackoverflow.com/q/51326165
tags question: http://stackoverflow.com/q/51355495
tags question: http://stackoverflow.com/q/51442279
tags question: http://stackoverflow.com/q/51372910
tags question: http://stackoverflow.com/q/51405932
tags question: http://stackoverflow.com/q/51365270
tags question: http://stackoverflow.com/q/51432010
tags question: http://stackoverflow.com/q/51351434
tags question: http://stackoverflow.com/q/51393270
tags question: http://stackoverflow.com/q/51334865
tags question: http://stackoverflow.com/q/51336716
tags question: http://stackoverflow.com/q/51343325
tags question: http://stackoverflow.com/q/51383418
tags question: http://stackoverflow.com/q/51438022
tags question: http://stackoverflow.com/q/51334197
tags question: http://stackoverflow.com/q/51366543

http://stackoverflow.com/comment/89657090
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51327765
has text: Also `FEOEUDNBNUWD` is not one of your original sequences. Clarify whether you want post-concatenation of overlapping sequences.
score: 0

http://stackoverflow.com/a/51331295
has body: Starting at the lower-right corner of your table, you need to backtrack through the creation logic. The general rule is: If the current cell is tagged 1, then add the current item to the solution set, and move left weight cells. Otherwise, the current item is not in the solution set Move up one row Here's how it works for the given case: cell [5, 8] (a.k.a. [-1, -1]) is tagged 1; add item 5 to the solution set (now [0, 0, 0, 0, 1]) and move left by the weight items[5,1], which is 2. Also move up one row to [4, 6] cell [4, 6] is tagged 0; item 4 is not in the solution. Move up one row. cell [3, 6] is tagged 1; add item 3 to the solution (now [0, 0, 1, 0, 1]) and move left by the weight of 5, then up one row. cell [2, 1] is tagged 1; add item 2 to the solution (now [0, 1, 1, 0, 1]) and move left by the weight of 1, then up one row. cell [1, 1] is tagged 0; item 1 is not in the solution. Move up one row. With no more items to check, we're done. The solution is 01101. Code def run_table(table, items): item_ct = len(items) manifest = [0] * item_ct # Start at end of table and retrace steps back to an empty pack. # The table is organized by item (rows) and weight (columns). soln_wt = maxWeight # Weight of the remaining solution for item_no in range(item_ct, 0, -1): print("Check item", item_no, "\t weight", soln_wt) wt, used = table[item_no][soln_wt] if used: manifest[item_no-1] = 1 soln_wt -= items[item_no-1][1] return manifest val_wt = [(3,4),(1,1),(4,5),(3,4),(2,2)] maxWeight = 8 T = createTable(val_wt, maxWeight) bestValue = T[-1][-1][0] # should be the maximum value ( = 7 ) print("Best packing", bestValue) L = run_table(T, val_wt) # should return [0, 1, 1, 0, 1] print(L) Output: Best packing 7 Check item 5 weight 8 Check item 4 weight 6 Check item 3 weight 6 Check item 2 weight 1 Check item 1 weight 0 [0, 1, 1, 0, 1]
has comment: http://stackoverflow.com/comment/89703924
has comment: http://stackoverflow.com/comment/89703821
has comment: http://stackoverflow.com/comment/89648774
has comment: http://stackoverflow.com/comment/89703777
type: AcceptedAnswer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89653502
type: Answer
accepted answer of: http://stackoverflow.com/q/51329426
has comment: http://stackoverflow.com/comment/89641283
answers question: http://stackoverflow.com/q/51329426
upvote count: 1

http://stackoverflow.com/q/51431408
has answer: http://stackoverflow.com/a/51431443
favorite count: 0
has answer: http://stackoverflow.com/a/51431646
has comment: http://stackoverflow.com/comment/89833780
has comment: http://stackoverflow.com/comment/89963708
has answer: http://stackoverflow.com/a/51431444
tagged with: python
tagged with: list
has body: code = ("1 2 3 4") b = code.split() print(b) This code returns ['1','2','3','4'] when I want it to return ['1',' ','2', '3',' ','4']. How would I do that?
has answer: http://stackoverflow.com/a/51431471
upvote count: 2
has comment: http://stackoverflow.com/comment/89833989
type: UnansweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/51431667
has comment: http://stackoverflow.com/comment/89834382
type: Question
has title: How would I convert this string into a list where the spaces are also separate items?
has comment: http://stackoverflow.com/comment/89834325
has answer: http://stackoverflow.com/a/51431574
has comment: http://stackoverflow.com/comment/89833799
has comment: http://stackoverflow.com/comment/89833824
score: 0
has answer: http://stackoverflow.com/a/51431554
has comment: http://stackoverflow.com/comment/89834802
answer count: 7
has comment: http://stackoverflow.com/comment/89833778

http://stackoverflow.com/comment/89695327
has text: [`match.start(1)`](https://docs.python.org/3/library/re.html#re.Match.start) returns the position of the start of the substring captured by the first group in the regex. And by incrementing `pos` by that much, we can skip the first vowels and consonants in the last match for our next iteration.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51361516

http://stackoverflow.com/q/51429760
has body: This is from the book "automate the boring stuff with python". At first I made a .bat file and ran it with arguments from cmd, didnt open any pages in chrome, looked up on here, changed up the code, still it executes perfectly and prints the print line but it doesnt open tabs as it should. What am I doing wrong? Thanks in advance #! python3 # lucky.py opens several google search matches import requests,sys,webbrowser,bs4 searchTerm1 = 'python' print('Googling...') res = requests.get('https://www.google.com/search?={0}'.format(searchTerm1)) res.raise_for_status() #retrieve top search result links soup = bs4.BeautifulSoup(res.text,"html.parser") #open a browser tab for each result. linkElems = soup.select('.r a') numOpen = min(5,len(linkElems)) for i in range(numOpen): webbrowser.open('http://google.com' + linkElems[i].get('href'))
answer count: 2
accepted answer: http://stackoverflow.com/a/51430245
upvote count: 1
favorite count: 0
tagged with: beautifulsoup
linked to: http://stackoverflow.com/q/22623798
has comment: http://stackoverflow.com/comment/89887353
has title: python web scraping code wont open links
has answer: http://stackoverflow.com/a/51430245
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51429881
has comment: http://stackoverflow.com/comment/89830967
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51429881
tagged with: web-scraping
linked to: http://stackoverflow.com/q/6908143
type: Question
has comment: http://stackoverflow.com/comment/89830726

http://stackoverflow.com/q/51467369
answer count: 1
tagged with: python
has title: Errors from building a one hidden neural network
favorite count: 0
has comment: http://stackoverflow.com/comment/89904543
upvote count: 1
downvote count: 1
tagged with: tensorflow
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51469458
type: Question
tagged with: neural-network
has comment: http://stackoverflow.com/comment/89904208
score: 0
has body: I'm currently building my 3-4-1 neural network from scratch using numpy (I avoided using keras and tensorflow for the purpose of learning and trying to demonstrate my knowledge instead of using pre-built libraries to do all the work), the problems I find when I run the program are: 1/ getting "nan" values after a certain number of iterations in the "updated" weights, lowering the learning rate only delays the problem and doesn't solve it. 2/ the second problem is the very low predicting accuracy. I would like to know what causes these bugs on my program and would appreciate any help. here is the code: # Import our dependencies from numpy import exp, array, random, dot, ones_like, where # Create our Artificial Neural Network class class ArtificialNeuralNetwork(): # initializing the class def __init__(self): # generating the same synaptic weights every time the program runs random.seed(1) # synaptic weights (3 × 4 Matrix) of the hidden layer self.w_ij = 2 * random.rand(3, 4) - 1 # synaptic weights (4 × 1 Matrix) of the output layer self.w_jk = 2 * random.rand(4, 1) - 1 def LeakyReLU(self, x): # The Leaky ReLU (short for Rectified Linear Unit) activation function will be applied to the inputs of the hidden layer # The activation function will return the same value of x if x is positive # while it will multiply the negative values of x by the alpha parameter # we used in this example the Leaky ReLU instead of the standard ReLU activation function to avoid the dying ReLU problem return where(x &gt; 0, x, x * 0.01) def LeakyReLUDerivative(self, x, α = 0.01): # The Leaky ReLU Derivative will return 1 for every positive value in the x array # while returning the value of the parameter alpha for every negative value x[x &gt; 0] = 1 # returns 1 for every positive value in the x array x[x &lt;= 0] = α # returns α for every negative value in the x array return x def Sigmoid(self, x): # The Sigmoid activation function will turn every input value into probabilities between 0 and …
tagged with: deep-learning
accepted answer: http://stackoverflow.com/a/51469458

http://stackoverflow.com/a/51479494
answers question: http://stackoverflow.com/q/51478739
type: AcceptedAnswer
has body: You could also create a function which gives you a list of dictionaries containing each of your rows in the text file data: def get_data(filename): data = [] with open(filename) as in_file: headers = next(in_file).split() for line in in_file: row = dict(zip(headers, line.strip().split())) data.append(row) return data Which returns something along the lines of: {'id': '51', 'gen': 'F', 'age': '46', 'mar': 'M', 'loc': '0', 'inc': '15100', 'iscr': '531', 'escr': '555'} {'id': '52', 'gen': 'M', 'age': '29', 'mar': 'M', 'loc': '2', 'inc': '14200', 'iscr': '673', 'escr': '633'} {'id': '53', 'gen': 'M', 'age': '25', 'mar': 'S', 'loc': '0', 'inc': '22200', 'iscr': '742', 'escr': '998'} ... Then you can filter out this data using list comprehensions: &gt;&gt;&gt; data = get_data('filter.txt') &gt;&gt;&gt; [row['inc'] for row in data] ['15100', '14200', '22200', '1000', '10600', '6100', '16500', '7400', '22800', '6400', '3100']
type: Answer
accepted answer of: http://stackoverflow.com/q/51478739
score: 0

http://stackoverflow.com/comment/89749029
score: 0
type: AnswerComment
has text: Yes, but this is not fine, i.e. `ax.scatter(*zip(*tsne), c=X[:,2], cmap='RdBu')`. How can I fix that for the 3D part?
type: Comment
comment on: http://stackoverflow.com/a/51387239

http://stackoverflow.com/comment/89821348
has text: out of curiosity, did removing the cov parameter fix the issue?
type: Comment
comment on: http://stackoverflow.com/a/51423312
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89790304
score: 0
type: Comment
type: QuestionComment
has text: Check these - https://stackoverflow.com/questions/35664994/py4j-protocol-py4jnetworkerror-an-error-occurred-while-trying-to-connect-to-th and https://github.com/bartdag/py4j/issues/262. You may have to use the `--net="host" option in conjunction with the solutions mentioned in the 2 links
comment on: http://stackoverflow.com/q/51408105

http://stackoverflow.com/a/51446155
has comment: http://stackoverflow.com/comment/89866459
has comment: http://stackoverflow.com/comment/89865291
accepted answer of: http://stackoverflow.com/q/51445773
has comment: http://stackoverflow.com/comment/89867612
type: AcceptedAnswer
has body: You can try downloading Django unofficial binaries form https://www.lfd.uci.edu/~gohlke/pythonlibs/ (use ctrl + F to find the package) and install using pip install "path to downloaded wheel file" Edit: Offline installation of Django worked with the OP as he did not like to install the unofficial binaries. Downloaded pytz from https://pypi.org/project/pytz/#files And then downloaded Django from https://pypi.org/project/Django/#files Installed wheel files of pytz first and Django next using pip.
answers question: http://stackoverflow.com/q/51445773
downvote count: 0
has comment: http://stackoverflow.com/comment/89866498
has comment: http://stackoverflow.com/comment/89862836
has comment: http://stackoverflow.com/comment/89862867
has comment: http://stackoverflow.com/comment/89866329
has comment: http://stackoverflow.com/comment/89862645
type: Answer
has comment: http://stackoverflow.com/comment/89862717
has comment: http://stackoverflow.com/comment/89865788
has comment: http://stackoverflow.com/comment/89862567
has comment: http://stackoverflow.com/comment/89862857
has comment: http://stackoverflow.com/comment/89866430
score: 1
has comment: http://stackoverflow.com/comment/89865614
upvote count: 1
has comment: http://stackoverflow.com/comment/89865355
has comment: http://stackoverflow.com/comment/89862780

http://stackoverflow.com/a/51464541
score: 3
has body: I thought I'd add an iterative approach where you loop through the string as it would be easier to understand. Try this: def count(string, substring): count = 0 for i in range(len(string) - len(substring) + 1): if string[i: i + len(substring)] == substring: count += 1 return count Essentially, I'm iterating through the possible values of i, where i is the starting index of each substring which is of the same length as the substring entered. Then, I'm simply checking if each possible substring of the correct length is equivalent to the substring entered. If so, I increment my count by 1.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89901952
type: Answer
accepted answer of: http://stackoverflow.com/q/51464483
has comment: http://stackoverflow.com/comment/89901969
upvote count: 3
answers question: http://stackoverflow.com/q/51464483

http://stackoverflow.com/comment/89770016
type: AnswerComment
type: Comment
has text: thank you for your comment, i understand the issue. the question is how can i avoid this?
comment on: http://stackoverflow.com/a/51397738
score: 0

http://stackoverflow.com/comment/89790805
comment on: http://stackoverflow.com/a/51409095
has text: Don't move it. Just install pyperclip in Python directory. Your default python directory will be ..\local\programs\python\python37. Also, make a habit of doing Custom installation of Python instead of direct Install Now.
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/q/51417442
answer count: 3
has body: I wrote two example codes which share a same pattern. As you can read below, I used if statement to not to pass keyword argument down to a sub function if the argument is None. I want to do it in a better way. Please share your thoughts if you have an idea. # example_1 def mysort(alist, key=None): if key is None: alist = sorted(alist) else: alist = sorted(alist, key=key) return alist # example_2 def create_index(index_name, mapping=None): es = Elasticsearch() if mapping in None: response = es.indices.create(index=index_name) else: response = es.indices.create(index=index_name, body=mapping) return respone
has comment: http://stackoverflow.com/comment/89806356
downvote count: 0
score: 1
tagged with: keyword-argument
favorite count: 0
tagged with: python
has title: Python, How not to pass a keyword argument to a method when the argument is None?
has answer: http://stackoverflow.com/a/51417566
type: UnansweredQuestion
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51417528
has answer: http://stackoverflow.com/a/51422361
linked to: http://stackoverflow.com/q/1132941

http://stackoverflow.com/q/51327765
has comment: http://stackoverflow.com/comment/89632669
has comment: http://stackoverflow.com/comment/89633719
has comment: http://stackoverflow.com/comment/89656989
has comment: http://stackoverflow.com/comment/89632482
has comment: http://stackoverflow.com/comment/89632230
has answer: http://stackoverflow.com/a/51350983
has answer: http://stackoverflow.com/a/51328156
has comment: http://stackoverflow.com/comment/89630939
favorite count: 0
has answer: http://stackoverflow.com/a/51327995
has comment: http://stackoverflow.com/comment/89633978
has comment: http://stackoverflow.com/comment/89633477
linked to: http://stackoverflow.com/q/51406699
has comment: http://stackoverflow.com/comment/89632720
has answer: http://stackoverflow.com/a/51328264
type: UnansweredQuestion
tagged with: bioinformatics
has comment: http://stackoverflow.com/comment/89631694
has title: Remove item from list based on the next item in same list
has comment: http://stackoverflow.com/comment/89632555
has comment: http://stackoverflow.com/comment/89633361
tagged with: python
has comment: http://stackoverflow.com/comment/89643699
score: 19
has answer: http://stackoverflow.com/a/51334022
has comment: http://stackoverflow.com/comment/89631044
has comment: http://stackoverflow.com/comment/89643567
has comment: http://stackoverflow.com/comment/89633110
has comment: http://stackoverflow.com/comment/89630866
upvote count: 19
has body: I just started learning python and here I have a sorted list of protein sequences (total 59,000 sequences) and some of them overlap. I have made a toy list here for example: ABCDE ABCDEFG ABCDEFGH ABCDEFGHIJKLMNO CEST DBTSFDE DBTSFDEO EOEUDNBNUW EOEUDNBNUWD EAEUDNBNUW FEOEUDNBNUW FG FGH I would like to remove those shorter overlap and just keep the longest one so the desired output would look like this: ABCDEFGHIJKLMNO CEST DBTSFDEO EAEUDNBNUW FEOEUDNBNUWD FGH How can I do it? My code looks like this: with open('toy.txt' ,'r') as f: pattern = f.read().splitlines() print pattern for i in range(0, len(pattern)): if pattern[i] in pattern[i+1]: pattern.remove(pattern[i]) print pattern And I got the error message: ['ABCDE', 'ABCDEFG', 'ABCDEFGH', 'ABCDEFGHIJKLMNO', 'CEST', 'DBTSFDE', 'DBTSFDEO', 'EOEUDNBNUW', 'EAEUDNBNUW', 'FG', 'FGH'] ['ABCDEFG', 'ABCDEFGH', 'ABCDEFGHIJKLMNO', 'CEST', 'DBTSFDE', 'DBTSFDEO', 'EOEUDNBNUW', 'EAEUDNBNUW', 'FG', 'FGH'] ['ABCDEFG', 'ABCDEFGHIJKLMNO', 'CEST', 'DBTSFDE', 'DBTSFDEO', 'EOEUDNBNUW', 'EAEUDNBNUW', 'FG', 'FGH'] ['ABCDEFG', 'ABCDEFGHIJKLMNO', 'CEST', 'DBTSFDE', 'DBTSFDEO', 'EOEUDNBNUW', 'EAEUDNBNUW', 'FG', 'FGH'] ['ABCDEFG', 'ABCDEFGHIJKLMNO', 'CEST', 'DBTSFDEO', 'EOEUDNBNUW', 'EAEUDNBNUW', 'FG', 'FGH'] ['ABCDEFG', 'ABCDEFGHIJKLMNO', 'CEST', 'DBTSFDEO', 'EOEUDNBNUW', 'EAEUDNBNUW', 'FG', 'FGH'] ['ABCDEFG', 'ABCDEFGHIJKLMNO', 'CEST', 'DBTSFDEO', 'EOEUDNBNUW', 'EAEUDNBNUW', 'FG', 'FGH'] ['ABCDEFG', 'ABCDEFGHIJKLMNO', 'CEST', 'DBTSFDEO', 'EOEUDNBNUW', 'EAEUDNBNUW', 'FGH'] Traceback (most recent call last): File "test.py", line 8, in &lt;module&gt; if pattern[i] in pattern[i+1]: IndexError: list index out of range
tagged with: list
has comment: http://stackoverflow.com/comment/89657090
has answer: http://stackoverflow.com/a/51328006
has comment: http://stackoverflow.com/comment/89633115
has comment: http://stackoverflow.com/comment/89632135
has answer: http://stackoverflow.com/a/51344455
type: Question
has answer: http://stackoverflow.com/a/51328391
downvote count: 0
has answer: http://stackoverflow.com/a/51327975
has answer: http://stackoverflow.com/a/51330240
answer count: 11
has answer: http://stackoverflow.com/a/51327976

http://stackoverflow.com/q/51359122
has comment: http://stackoverflow.com/comment/89690596
type: UnansweredQuestion
has title: TypeError: len() of unsized object when converting object to numeric
type: Question
has comment: http://stackoverflow.com/comment/89690721
has comment: http://stackoverflow.com/comment/89690656
has answer: http://stackoverflow.com/a/51359376
tagged with: numeric
has comment: http://stackoverflow.com/comment/89690814
answer count: 2
has comment: http://stackoverflow.com/comment/89690320
score: 0
has body: I am working on a dataframe which has a column of the form: allHoldingsFund['ratioBest'] Out[72]: 65357 0.0 65371 0.0 65394 2.396777442094666 65397 0.0 65433 0.0167993412023058 65462 0.0 65560 0.0 Name: ratioBest, Length: 1664, dtype: object the column is an object and i usually convert the object to a numeric value using allHoldingsFund['ratioBest']=pd.to_numeric(allHoldingsFund['ratioBest']) However when I do that I get an error that I am not able to solve: pd.to_numeric(allHoldingsFund['ratioBest']) Traceback (most recent call last): File "/apps/qtrinst/install/python/anaconda/envs/sx_anaconda/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2910, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "&lt;ipython-input-71-6f0ccaf63f24&gt;", line 1, in &lt;module&gt; pd.to_numeric(allHoldingsFund['ratioBest']) File "/apps/qtrinst/install/python/anaconda/envs/sx_anaconda/lib/python3.5/site-packages/pandas/core/tools/numeric.py", line 133, in to_numeric coerce_numeric=coerce_numeric) File "pandas/_libs/src/inference.pyx", line 1111, in pandas._libs.lib.maybe_convert_numeric TypeError: len() of unsized object How can I solve this issue please?
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/51359437
tagged with: python-3.x

http://stackoverflow.com/q/51329628
has body: The x-axis is unreadably cluttered for a grouped vbar plot for some very simple data, &amp; I can't find how to fix it. The intent is to show on a single plot the # of tweets/hr over both the lifetime and last 90 days of a twitter acct. I already have a working version for just the lifetime data which produces a suitably simple/tidy output. For the grouped version I want show a simple ticker like the single version &amp; use a colour legend to indicate data label for columns. from bokeh.io import show, output_file, export_png from bokeh.plotting import figure from bokeh.models import ColumnDataSource, FactorRange, Label, Title from bokeh.transform import factor_cmap data = {'hours_active': {0: 11, 1: 0, 2: 0, 3: 0, 4: 0, 5: 2, 6: 15, 7: 27, 8: 75, 9: 96, 10: 205, 11: 278, 12: 241, 13: 238, 14: 236, 15: 184, 16: 232, 17: 164, 18: 211, 19: 236, 20: 197, 21: 199, 22: 253, 23: 97}, 'ninety_days_hours_active': {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 2, 6: 15, 7: 23, 8: 68, 9: 78, 10: 94, 11: 111, 12: 135, 13: 80, 14: 109, 15: 102, 16: 94, 17: 58, 18: 106, 19: 94, 20: 110, 21: 98, 22: 89, 23: 2}} hours = [str(i) for i in range(0, 24)] days = ['all', '90'] data = {'hours' : hours, 'all':list(data['hours_active'].values()), '90': list(data['ninety_days_hours_active'].values())} x = [ (str(hour), day) for hour in hours for day in days ] counts = sum(zip(data['all'], data['90']), ()) colors = ['#ffff1a', '#191971'] source = ColumnDataSource(data=dict(x=x, counts=counts)) p = figure(x_range=FactorRange(*x), plot_width=500, plot_height=500, title="Tweets All/Last 90 Days", ) p.toolbar_location = None p.xgrid.grid_line_color = None p.min_border = 40 p.axis.axis_line_width = 2 p.y_range.start = 0 p.vbar(x='x', top='counts', width=0.9, source=source, fill_color=factor_cmap('x', palette=colors, factors=days, start=1, end=2)) show(p) Output from above code: Example with suitable x-axis I've chosen to avoid using pandas/dataframes because I want to keep the dependencies as minimal as I can…
tagged with: plot
type: AnsweredQuestion
score: 1
tagged with: bokeh
upvote count: 1
type: Question
has title: Python Bokeh basic grouped vbar - simplify x-axis
accepted answer: http://stackoverflow.com/a/51332942
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51332942
tagged with: python

http://stackoverflow.com/a/51457541
has body: If you use more points than 3 you will get the same result as in the linked question. There are many ways a spline of order 3 can go through 3 points. But you may of course reduce the order to 2. import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import spline x = np.array([0,1,2]) y = np.array([5, 4.31, 4.01]) plt.plot(x, y) xnew = np.linspace(x.min(), x.max(), 300) smooth = spline(x, y, xnew, order=2) plt.plot(xnew, smooth) plt.show()
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51457342
answers question: http://stackoverflow.com/q/51457342
score: 1
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/51453809
type: UnansweredQuestion
has title: How to plot data based on given time?
has answer: http://stackoverflow.com/a/51454480
tagged with: python
answer count: 4
downvote count: 3
upvote count: 1
tagged with: plot
type: Question
score: -2
tagged with: dataframe
linked to: http://stackoverflow.com/q/24251219
tagged with: pandas
has body: I have a dataset like the one shown below. Date;Time;Global_active_power;Global_reactive_power;Voltage;Global_intensity;Sub_metering_1;Sub_metering_2;Sub_metering_3 16/12/2006;17:24:00;4.216;0.418;234.840;18.400;0.000;1.000;17.000 16/12/2006;17:25:00;5.360;0.436;233.630;23.000;0.000;1.000;16.000 16/12/2006;17:26:00;5.374;0.498;233.290;23.000;0.000;2.000;17.000 16/12/2006;17:27:00;5.388;0.502;233.740;23.000;0.000;1.000;17.000 16/12/2006;17:28:00;3.666;0.528;235.680;15.800;0.000;1.000;17.000 16/12/2006;17:29:00;3.520;0.522;235.020;15.000;0.000;2.000;17.000 16/12/2006;17:30:00;3.702;0.520;235.090;15.800;0.000;1.000;17.000 16/12/2006;17:31:00;3.700;0.520;235.220;15.800;0.000;1.000;17.000 16/12/2006;17:32:00;3.668;0.510;233.990;15.800;0.000;1.000;17.000 I've used pandas to get the data into a DataFrame. The dataset has data for multiple days with an interval of 1 min for each row in the dataset. I want to plot separate graphs for the voltage with respect to the time(shown in column 2) for each day(shown in column 1) using python. How can I do that?
has answer: http://stackoverflow.com/a/68547540
favorite count: 0
tagged with: data-analysis
has answer: http://stackoverflow.com/a/51454522
has answer: http://stackoverflow.com/a/51454505

http://stackoverflow.com/comment/89710316
comment on: http://stackoverflow.com/a/51368979
score: 0
type: AnswerComment
has text: It's a little more complicated than I can post publicly due to the nature of the script. But basically, it does. But I have checked and the field type is date in the table. My hope was to explicity change the loaded data by using the DateWCorr
type: Comment

http://stackoverflow.com/a/51393085
has comment: http://stackoverflow.com/comment/89758020
answers question: http://stackoverflow.com/q/51393020
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51393020
score: 1
has body: In your original PHP code, your function returns the key as soon as rand becomes a non-positive number, but in your Python code, you simply print the key without returning. You should return the key in your new code also, and print the returning value of the function instead: import random def getRandomWeightedElement(**data): rand = random.randint(1, sum(data.values())) for key, value in data.items(): rand -= value if rand &lt;= 0: return key test1 = {'One': 25, 'Two': 25, 'Three': 25, 'Four': 25} print(getRandomWeightedElement(**test1))
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51352284
type: Question
has comment: http://stackoverflow.com/comment/89679122
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/1236285
tagged with: logging
has comment: http://stackoverflow.com/comment/89703208
tagged with: django-unittest
upvote count: 2
answer count: 1
has body: I'm having difficulty getting the desired behavior at the intersection of the django test runner, i.e. from django.test import TestCase and the logging solution. my logger is set up and works in other areas with something like this import logging logger = logging.getLogger(__name__) logger.warning("duck!") so when running the Django app, I see the message and metadata as I expect; however, the trouble is that these log lines do not show up in any location I am aware of when running the unit tests, i.e. django-admin run test I want to be able to run tests and see the log output, ideally in STDOUT, and presumably set the output log levels so that tests show those... my settings vis. logging: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'root': { 'level': 'ERROR', 'handlers': ['sentry', 'console'], }, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s ' '%(process)d %(thread)d %(message)s' }, }, 'handlers': { 'sentry': { 'level': 'WARNING', # To capture more than ERROR, change to WARNING, INFO, etc. 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler', 'tags': {'custom-tag': 'x'}, }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose' } }, 'loggers': { 'django.db.backends': { 'level': 'ERROR', 'handlers': ['console'], 'propagate': False, }, 'raven': { 'level': 'WARNING', 'handlers': ['console'], 'propagate': False, }, 'sentry.errors': { 'level': 'DEBUG', 'handlers': ['console'], 'propagate': False, }, 'celery': { 'handlers': ['console'], 'level': 'WARNING', 'proagate': True, }, }, }
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/68594546
score: 2
downvote count: 0
favorite count: 0
has title: Logger results not appearing in unittest output with Django

http://stackoverflow.com/q/51412955
upvote count: 4
answer count: 2
has body: I am re-writing a matlab filter script into python and have vastly different outputs. Does anyone know how to make these functions similar? There was some preliminary calculations made to find the equivalent ripple and other factors. Python Script: from scipy import signal import math as m import matplotlib.pyplot as plt # Variable Values: total_ripple = -20*m.log10(0.001) #get decibels fsamp = 100 Nyqu = fsamp/2 trans_width = (0.7 - 0.1)/Nyqu cut = (0.7+0.1)/2*(Nyqu) # Script: numtaps, beta = signal.kaiserord(total_ripple, trans_width) taps = signal.firwin(numtaps, cutoff=cut, width = trans_width, fs = fsamp, window=('kaiser',numtaps+1, beta), scale=False, pass_zero=True) filtered_data = (signal.lfilter(taps, 1, data1, axis = 0)).tolist() Matlab Script: mags = [1, 0] devs = [0.001, 0.1] fcuts = [0.1 0.7] fsamp = 100 [n,Wn,beta,ftype] = kaiserord(fcuts,mags,devs,fsamp); hh = fir1(n,Wn,ftype,kaiser(n+1,beta),'noscale'); filteredData = filter(hh,1,data); (Edit: added variable values) I know that the fcuts will vary between matlab and python. Python only accepts a single fcuts value in decibels for stopband. Simply plotting taps &amp; hh gives different plots. The final plots with the actual data is different as well.
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89828677
tagged with: python
has comment: http://stackoverflow.com/comment/89798323
tagged with: matlab
has title: Replicating matlab filter in python
score: 2
has answer: http://stackoverflow.com/a/76392978
downvote count: 2
tagged with: scipy
tagged with: signal-processing
type: Question
has answer: http://stackoverflow.com/a/79243282

http://stackoverflow.com/a/51329453
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51329226
downvote count: 0
answers question: http://stackoverflow.com/q/51329226
has body: You can reshape your dataframe and use pandas plot: df_out = df.reset_index(level=1, drop=True)\ .set_index(['continent'], append=True)['avg_count_country']\ .unstack() df_out.plot.bar() Output:
type: Answer
upvote count: 1

http://stackoverflow.com/a/61824187
accepted answer of: http://stackoverflow.com/q/51410283
type: AcceptedAnswer
downvote count: 0
has body: Yeah I agree the annotations solution isn't that efficient. Does this work for what you are trying to do: https://github.com/redransil/plotly-dirgraph import plotly.graph_objects as go import networkx as nx import dash import dash_core_components as dcc import dash_html_components as html from addEdge import addEdge # Controls for how the graph is drawn nodeColor = 'Blue' nodeSize = 20 lineWidth = 2 lineColor = '#000000' # Make a random graph using networkx G = nx.random_geometric_graph(5, .5) pos = nx.layout.spring_layout(G) for node in G.nodes: G.nodes[node]['pos'] = list(pos[node]) # Make list of nodes for plotly node_x = [] node_y = [] for node in G.nodes(): x, y = G.nodes[node]['pos'] node_x.append(x) node_y.append(y) # Make a list of edges for plotly, including line segments that result in arrowheads edge_x = [] edge_y = [] for edge in G.edges(): # addEdge(start, end, edge_x, edge_y, lengthFrac=1, arrowPos = None, arrowLength=0.025, arrowAngle = 30, dotSize=20) start = G.nodes[edge[0]]['pos'] end = G.nodes[edge[1]]['pos'] edge_x, edge_y = addEdge(start, end, edge_x, edge_y, .8, 'end', .04, 30, nodeSize) edge_trace = go.Scatter(x=edge_x, y=edge_y, line=dict(width=lineWidth, color=lineColor), hoverinfo='none', mode='lines') node_trace = go.Scatter(x=node_x, y=node_y, mode='markers', hoverinfo='text', marker=dict(showscale=False, color = nodeColor, size=nodeSize)) fig = go.Figure(data=[edge_trace, node_trace], layout=go.Layout( showlegend=False, hovermode='closest', margin=dict(b=20,l=5,r=5,t=40), xaxis=dict(showgrid=False, zeroline=False, showticklabels=False), yaxis=dict(showgrid=False, zeroline=False, showticklabels=False)) ) # Note: if you don't use fixed ratio axes, the arrows won't be symmetrical fig.update_layout(yaxis = dict(scaleanchor = "x", scaleratio = 1), plot_bgcolor='rgb(255,255,255)') app = dash.Dash() app.layout = html.Div([dcc.Graph(figure=fig)]) app.run_server(debug=True, use_reloader=False) Example: directed graph output
type: Answer
answers question: http://stackoverflow.com/q/51410283
score: 2
upvote count: 2

http://stackoverflow.com/comment/135052647
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51350779
has text: I didn't get tge phrase ``` MSRPC is a way to execute functions on the remote end and to transfer data (parameters to these functions). It is not a way to directly execute remote OS commands on the remote side. ```
type: AnswerComment

http://stackoverflow.com/a/51352758
accepted answer of: http://stackoverflow.com/q/51350462
type: AcceptedAnswer
downvote count: 0
has body: Your 'password' variable is a string, but SHA256.new expects bytes (to allow for unicode, for example). That you need bytes is listed in the Crypto.Hash.SHA256 documentation. The solution is to encode the password to bytes before hashing. This is almost literally what the error message says (if you know that all strings in python 3 are unicode objects): TypeError: Unicode-objects must be encoded before hashing The solution is for example to encode with utf8 : SHA256.new(password.encode('utf8')).digest()
has comment: http://stackoverflow.com/comment/89683571
type: Answer
has comment: http://stackoverflow.com/comment/89679183
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/51350462

http://stackoverflow.com/comment/89702636
comment on: http://stackoverflow.com/a/51363203
has text: Sorry I didn't mention that. I will make a better question next time. But still thanks for your patient to help me, and I will remember not to manually change thing before it is fixed. I will go and reinstall the virtualenv. Thank you.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51415259
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89801958
type: Question
has comment: http://stackoverflow.com/comment/89801890
has comment: http://stackoverflow.com/comment/89804001
has body: I am writing automation script in python to update certain version in a file. Here is the snippet from that file. if "$(CURTARGET)" == "linux_rh_el6_x86_64_32" /* See $VOB/FMSrules.mk */ GOLDEN_CPPHDR_VER=4.4.7 GOLDEN_CPPBKW_VER=3.4.6 GOLDEN_LIBHDR_VER=$(GOLDEN_CPPHDR_VER) RHEL_KERNEL=2.6.32-696.16.1.el6.x86_64 end if "$(CURTARGET)" == "linux_rh_el7_x86_64_32" /* See $VOB/FMSrules.mk */ GOLDEN_CPPHDR_VER=4.8.5 GOLDEN_CPPHDR_VER=4.4.7 GOLDEN_LIBHDR_VER=$(GOLDEN_CPPHDR_VER) RHEL_KERNEL=3.10.0-693.el7.x86_64 end I have to update GOLDEN_CPPHDR_VER,GOLDEN_CPPHDR_VER &amp; RHEL_KERNEL based on the value of $(CURTARGET). AS you can see the 3 variables GOLDEN_CPPHDR_VER,GOLDEN_CPPHDR_VER &amp; RHEL_KERNEL are not unique and i cannot directly search and update the same. I tried coding it in this way. def update_fmsrules(): print " \n\n--- Updating FMSrules.mk ----\n" f = open(FMSrules_file,'r') lines = [] while True: try: line= f.readline() #print line if (re.search(r'\blinux_rh_el7_x86_64_32\b',line)): print "matched\n" nextline = f.next() print nextline if "GOLDEN_CPPHDR_VER" in nextline: print "entered if" print line +"\ntrue\n"+ nextline print f.tell() break except StopIteration: print "exception" return f.close() But it is not working as expected. print "matched\n" I am seeing the above output. nextline = f.next() print nextline But above line is not printing actual nextline but some garbage lines. And the code is running infinitely. what is the best way of doing this using python? How can i do it using file operation in python?
score: 0
has comment: http://stackoverflow.com/comment/89801943
has comment: http://stackoverflow.com/comment/89801907
tagged with: python
tagged with: python-3.x
answer count: 0
has title: Updating mulitple lines of file in python

parameters
tags question: http://stackoverflow.com/q/51400338
type: Tag
tag name: parameters
tags question: http://stackoverflow.com/q/51380949
tags question: http://stackoverflow.com/q/51362773

http://stackoverflow.com/q/51468692
has comment: http://stackoverflow.com/comment/89905954
type: Question
has comment: http://stackoverflow.com/comment/89905909
has comment: http://stackoverflow.com/comment/89905900
linked to: http://stackoverflow.com/q/4448339
upvote count: 2
answer count: 1
has title: python wrong subprocess.call return code
favorite count: 0
accepted answer: http://stackoverflow.com/a/51468768
has comment: http://stackoverflow.com/comment/89905934
tagged with: python
has body: Look at this 2 simples programs in C: #include &lt;stdio.h&gt; int main(int argc, char *argv[]) { return -1; } #include &lt;stdio.h&gt; int main(int argc, char *argv[]) { return 1337; } Now look this very basic python script: &gt;&gt;&gt; import subprocess &gt;&gt;&gt; r=subprocess.call(['./a.out']) I do not understand why but the python script r value contains: 255 for the first C program. It should be -1 57 for the second C program. It should be 1337 Have i something wrong ? Thanks
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51468768
downvote count: 0

http://stackoverflow.com/comment/89901251
type: Comment
comment on: http://stackoverflow.com/a/51462628
has text: Does your json file start with `{"installed": {"client_id": "....` ?. If so, that's your client_id json, not the credentials json.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89709338
score: 0
comment on: http://stackoverflow.com/a/51368523
type: Comment
type: AnswerComment
has text: It's more likely that `&` is special to the shell, not the browser.

http://stackoverflow.com/a/51456885
has comment: http://stackoverflow.com/comment/110503276
type: Answer
has comment: http://stackoverflow.com/comment/110469625
answers question: http://stackoverflow.com/q/51439810
score: 0
has body: If you've got the Google Drive Python API installed, then this shouldn't be too hard. The simplest approach would be to run a query for files with that name. query = "name contains %s" % fileName results = drive_service.files().list(q=query, fields="name, id, parents, webViewLink").execute() files = results.get('files', []) if len(files) == 1: return files[0]['webViewLink'] This will return either one result (hooray! that's your file), or multiple results. If its the latter, you will need to check if the file you've picked is the right one or not. This could be done by searching to see if the parents of any of the returned files match the name of the file path. Ie, if your path is G:\My Drive\Documents\Clowns.mp4, and you have multiple results for the first search of Clowns.mp4, then you could loop through them like so: for current_file in files: parent_id = current_file['parents'][0] parent_folder = drive_service.files().get(fileId=parent_id, fields="name").execute() if parent_folder['name'] == "Documents": print("%s is the right file") return current_file['webViewLink']

http://stackoverflow.com/comment/89721738
score: 0
type: Comment
type: QuestionComment
has text: The example is missing a comma on the `verbosity=0` line.
comment on: http://stackoverflow.com/q/51375115

http://stackoverflow.com/comment/89872411
comment on: http://stackoverflow.com/q/51451046
type: Comment
has text: The result of an integral over an interval is a single number. Do you want to plot that number?
type: QuestionComment
score: 2

http://stackoverflow.com/comment/89912308
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51463061
has text: I am using version 0.8, and here is the link for the tf code: https://github.com/tensorflow/tensorflow/blob/r0.8/tensorflow/python/ops/math_ops.py

http://stackoverflow.com/a/51480876
type: Answer
downvote count: 0
score: 6
answers question: http://stackoverflow.com/q/51446156
upvote count: 6
accepted answer of: http://stackoverflow.com/q/51446156
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/101799105
has body: I'll upload my answer for anyone looking at this in the future :-) def uploads(request): if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): kappa = request.FILES['file'] # Do work on kappa/excel file here with Pandas output = io.BytesIO() writer = pd.ExcelWriter(output, engine='xlsxwriter') kappa.to_excel(writer, index=False) writer.save() output.seek(0) response = HttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s.xlsx' % 'Download' return response else: form = UploadFileForm() return render(request, 'upload_form.html', {'form': form}) I abandoned using 'Django-excel' and instead used 'BytesIO' from the io module. This has the bonus of not relying on a third-party module. you're able to write a Pandas dataframe to io.BytesIO() and then use that in your HttpResponse.

http://stackoverflow.com/a/51455934
has comment: http://stackoverflow.com/comment/89881386
upvote count: 12
has comment: http://stackoverflow.com/comment/89881419
downvote count: 0
answers question: http://stackoverflow.com/q/51455765
has comment: http://stackoverflow.com/comment/89881552
has comment: http://stackoverflow.com/comment/89881377
score: 12
has comment: http://stackoverflow.com/comment/89881371
has comment: http://stackoverflow.com/comment/89881429
type: Answer
has body: Try this: pyinstaller --onefile main_app.py
has comment: http://stackoverflow.com/comment/89881866

http://stackoverflow.com/comment/127595663
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/72205504
score: 0
has text: I would say this a great representation of the graph. Looking forward to learning from the input file and the process of creation. Thank you!

http://stackoverflow.com/comment/89645079
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51334284
type: Comment
has text: the issue is: I have a log file with a whole bunch of information and some JSON lines interleaved. I then grepped the JSON lines and put them into a single file to extract data I'm interested in...

http://stackoverflow.com/a/51354951
answers question: http://stackoverflow.com/q/51353158
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/89704440
has body: You may refer this, Its class, Not ID. driver.find_element_by_xpath("//i[@class='fa fa-linkedin-square fa-2x']").click()

http://stackoverflow.com/a/51367512
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/51366535
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51366535
downvote count: 0
has body: To know why you get this error, see ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(). In your precise situation, why not do &gt;&gt;&gt; np.where(x &lt; 5, 0, 1) Example &gt;&gt;&gt; x = np.arange(10) &gt;&gt;&gt; x array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) &gt;&gt;&gt; np.where(x &lt; 5, 0, 1) array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1]) Using a lambda function &gt;&gt;&gt; anal01 = lambda x,y : np.where(x &lt; 5, 0, 1) &gt;&gt;&gt; anal01(x, None) array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1]) The variable named a (that you don't have in your code) is simply used to illustrate the way you should deal with your array.

http://stackoverflow.com/q/51386494
score: 3
has comment: http://stackoverflow.com/comment/89750191
answer count: 0
upvote count: 3
has title: ValueError When creating a variable inside a loop or conditional, use a lambda as the initializer
tagged with: tensorflow
type: Question
downvote count: 0
tagged with: keras
tagged with: keras-layer
has body: I am trying to train a UNet for image segmentation and I have the following as part of my network. def inception_block(inputs, depth, splitted=True, activation='relu'): actv = LeakyReLU c1_1 = Conv2D(int(depth/4), (1, 1), padding='same')(inputs) c2_1 = Conv2D(int(depth/8*3), (1, 1),padding='same')(inputs) c2_1 = actv()(c2_1) if splitted: c2_2 = Conv2D(int(depth/2), (1, 3), padding='same')(c2_1) c2_2 = BatchNormalization(axis=1)(c2_2) c2_2 = actv()(c2_2) c2_3 = Conv2D(int(depth/2), (3, 1),padding='same')(c2_2) else: c2_3 = Conv2D(int(depth/2), (3, 3), padding='same')(c2_1) c3_1 = Conv2D(int(depth/16), (1, 1), padding='same', activation='relu')(inputs) c3_1 = actv()(c3_1) if splitted: c3_2 = Conv2D(int(depth/8), (1, 5), padding='same')(c3_1) c3_2 = BatchNormalization(axis=1)(c3_2) c3_2 = actv()(c3_2) c3_3 = Conv2D(int(depth/8), (5, 1), padding='same')(c3_2) else: c3_3 = Conv2D(int(depth/8), (5, 5), padding='same')(c3_1) p4_1 = MaxPooling2D(pool_size=(3,3), strides=(1,1),padding='same')(inputs) c4_2 = Conv2D(int(depth/8), (1, 1), padding='same')(p4_1) res = concatenate([c1_1, c2_3, c3_3, c4_2],axis=1) res = BatchNormalization(axis=1)(res) res=actv()(res) return res and def N2(inputs,Z): splitted=True act='relu' strides=(2,2) padding='valid' conv1 = (inception_block(inputs, 32, splitted= splitted, activation= act)) pool1 = poolConvolution2D(32, filters=(3, 3), strides=(2,2))(conv1) pool1=Dropout(Z.drop)(pool1) conv2 = inception_block(pool1, 64, splitted= splitted, activation=act) pool2 = poolConvolution2D(64, filters=(3, 3), strides=(2,2))(conv2) pool2=Dropout(Z.drop)(pool2) conv3 = inception_block(pool2, 128, splitted=splitted, activation=act) pool3 = poolConvolution2D(128, filters=(3, 3), strides=(2,2))(conv3) pool3=Dropout(Z.drop)(pool3) ... def poolConvolution2D(nb_filter, filters, strides=(1, 1)): def f(_input): conv = Conv2D(nb_filter, filters, strides=strides, padding='same')(_input) norm = BatchNormalization(axis=1)(conv) return ELU()(norm) return f when running…
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/47393356
tagged with: python
has comment: http://stackoverflow.com/comment/89750937

http://stackoverflow.com/a/51443129
has body: With regex the solution is new_text = re.search(r'(.*)\\', text).group(1) But I do agree that regex is unnecessary in your example
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51443048

http://stackoverflow.com/q/51368801
answer count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 3
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/92340180
has body: Assuming I have the following DataFrames: In [86]: d1 Out[86]: Start End 0 2018-01-03 2018-11-30 1 2018-01-06 2018-11-30 In [87]: d2 Out[87]: Document_date 0 2018-10-02 1 2018-10-02 2 2018-06-13 3 2018-06-13 4 2018-03-29 5 2018-04-19 6 2018-06-13 7 2018-03-20 8 2018-06-13 9 2018-01-25 10 2018-05-15 11 2018-04-19 I want to create an IntervalIndex from the first DF: In [88]: idx = pd.IntervalIndex.from_arrays(d1['Start'], d1['End'], closed='both') In [89]: idx Out[89]: IntervalIndex([[2018-01-03, 2018-11-30], [2018-01-06, 2018-11-30]] closed='both', dtype='interval[datetime64[ns]]') and use .get_loc() method: In [92]: idx.get_loc(d2.iat[0,0]) ... skipped ... KeyError: ('datetime64[ns]', 'both') or: In [93]: idx.get_loc(pd.to_datetime('2018-10-02')) ... skipped ... KeyError: ('datetime64[ns]', 'both') or: In [94]: idx.get_loc('2018-10-02') ... skipped ... KeyError: ('datetime64[ns]', 'both') Question: what do I do wrong? Example from the online docs which is using integer intervals is working just fine: In [97]: i1, i2 = pd.Interval(0, 1), pd.Interval(1, 2) ...: index = pd.IntervalIndex([i1, i2]) ...: index.get_loc(1.5) ...: ...: Out[97]: 1 PS I'm using Pandas 0.23.0 (from Anaconda distributive)
has title: How to use pd.IntervalIndex.get_loc() / pd.IntervalIndex.get_indexer() with datetime values?
tagged with: pandas
score: 3
tagged with: intervals
has comment: http://stackoverflow.com/comment/89710161
favorite count: 0

http://stackoverflow.com/a/51384855
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51375587
type: Answer
answers question: http://stackoverflow.com/q/51375587
score: 2
downvote count: 0
has body: The problem was in the byte order of cv2.imread() which is Blue-Green-Red whereas ImageDataGenerator uses Red-Green-Blue. Solution: def prepare_frame(frame): frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # &lt;- correct byte order!!! frame = cv2.resize(frame, (150, 150)) frame = np.expand_dims(frame, axis=0) frame = np.asarray(frame, dtype='int32') frame = frame / 255 return frame Original cats &amp; dogs dataset: still works (I guess the colors just had no impact there - very interesting!) Batch Size: tested with 1 and 20, both work Thanks for all your comments - I really appreciate your help! I hope somebody else finds this useful.
upvote count: 2

http://stackoverflow.com/q/51365408
has comment: http://stackoverflow.com/comment/89707844
answer count: 0
score: 1
upvote count: 1
tagged with: scipy
has title: Scipy Weibull Min Fit bad without forced location
type: Question
has body: I'm currently trying to fit a dataset that I have using the scipy.stats weibull_min.fit function. When I fit the dataset outright, I get the following parameters: (0.10875037748866037, 1.0362199999999999e-05, 1.0709034507962369) This ends up being a very bad fit to the data. However, when I force the location (second parameter) to be the min value of the dataset, I get a much better fit: (1.2295613161155923, 1.03622e-05, 5.8737285599676099e-06) As you can see, the value of my forced location and the auto fit location are very, very close. Is there any reason that fitting the data without forcing the location yields a much worse result? EDIT: Here is the code that I am using: import scipy.stats as st file = open('datafile.csv', 'r') lines = file.readlines() data = [] for ii in range(len(lines)): data.append(float(lines[ii])) distr = getattr(st, "weibull_min") params = distr.fit(data) # params = distr.fit(data, floc=min(data))
tagged with: weibull
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89703392
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/89883413
has text: np.arange(0.0, 1.0, 0.1) is the function I was looking for.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51456917
type: Comment

http://stackoverflow.com/comment/90211652
comment on: http://stackoverflow.com/a/51469761
score: 0
type: AnswerComment
has text: I see now, thanks! So in python syntax I would be "x=a*(ln(time+b))**c" or in wolframalpha syntax "x=a*(ln(time+b))^c". I will play around at zunzun.com to check for other stuff it might help me :)
type: Comment

http://stackoverflow.com/a/51355472
answers question: http://stackoverflow.com/q/51355366
score: 0
has body: I think better here is use vectorized solution with numpy.where by boolean mask created by isin and last multiple column kwh_usage: mask = w1_weekdays['end_time_hour'].isin([0,1,2]) w1_weekdays['cost'] = np.where(mask, onP_price , offP_price) * w1_weekdays['kwh_usage']
type: Answer

http://stackoverflow.com/comment/136534444
score: 0
type: Comment
comment on: http://stackoverflow.com/a/77031113
type: AnswerComment
has text: Thansk @tintin81! That fixed my issue after updating to Sonoma.

http://stackoverflow.com/a/51437478
answers question: http://stackoverflow.com/q/51433645
downvote count: 0
type: Answer
upvote count: 1
has body: I believe when scrapy receives a SIGTERM it tries to shutdown gracefully by first waiting to finished all sent/scheduled requests. Your best bet is to either limit the number or concurrent requests so it finishes quicker (CONCURRENT_REQUESTS/CONCURRENT_REQUESTS_PER_DOMAIN are 16 and 8 respectively by default) or to send two SIGTERM's to instruct scrapy to do unclean immediate exit. OBS : It is possible to fire all spiders inside spiders.py without blocking the main process? process.start() starts twisted reactor (twisted main event loop) which is a blocking call, to circumvent it and run more code after the reactor has been started you can schedule a function be run inside the loop. First snippet from this manual should give you an idea: https://twistedmatrix.com/documents/current/core/howto/time.html. However, if you go that way, you must make sure that the code you schedule have to also be non blocking, otherwise when you pause the execution of the loop for too long bad things can start happening. So things like time.sleep() must be rewritten in a twisted equivalent.
score: 1

http://stackoverflow.com/a/51433858
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89838484
type: Answer
accepted answer of: http://stackoverflow.com/q/51433835
upvote count: 1
answers question: http://stackoverflow.com/q/51433835
has body: Zip files can contain (relative) pathnames, not just filenames. So, the contents of album2.zip are most likely actually: album2/song1.mp3 album2/song2.mp3 album2/song3.mp3 … but album1.zip is just: song1.mp3 song2.mp3 song3.mp3 To test this, you can do unzip -l album1.zip and unzip -l album2.zip from your shell. This is actually a problem that people have been having as long as they've been sharing zipfiles. You usually want to include that album2 in the paths, but sometimes it's missing. You don't want to forcibly add it and end up with album2/album2/song1.mp3, but you don't want to not add it and end up with just song1.mp3 in the top directory. The solution that most GUI tools use nowadays (I think it dates back to the ancient Stuffit Expander) is this: Iterate all of the zip entries and see if the pathnames all start with the same directory. If so, unzip them as-is. If not, create a directory with the same name as the zipfile (minus the .zip), then unzip them into that directory. The one tricky bit is that zipfile paths can be Windows or POSIX format, and they can be absolute paths or UNC paths or even paths starting with .., and the logic for transforming those to usable paths is, while not exactly difficult, more than just a one-liner. So, you have to decide how far you want to go with making your code fully general.
type: AcceptedAnswer

http://stackoverflow.com/q/51407961
has title: Python gunicorn worker exiting due to incorrect arguments?
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
has body: I have a new server being set up, and as part of the process I set up gunicorn to serve the web files. However, when transferring the data, a command that works on the old servers does not work on this server. The gunicorn master process appears to spin up workers, but the workers immediately quit due to "unrecognized arguments". The command is :/home/postgres/venv/bin/gunicorn [app]:app. This is identical to the previous server, except that this server is using a virtualenv instead of the global packages. I suspect this might be the issue, but I'm unsure why or how to fix it. Same Python version, but the gunicorn version is newer (19.4.5 on old vs 19.9.0 on new). I've replaced the the app name with [app] to prevent confusion, but there are no invalid characters or anything in the name. Log: root@ns500738:/home/postgres/[app]# /home/postgres/venv/bin/gunicorn [app]:app [2018-07-18 13:27:56 -0400] [10080] [INFO] Starting gunicorn 19.9.0 [2018-07-18 13:27:56 -0400] [10080] [INFO] Listening at: http://127.0.0.1:8000 (10080) [2018-07-18 13:27:56 -0400] [10080] [INFO] Using worker: sync [2018-07-18 13:27:56 -0400] [10083] [INFO] Booting worker with pid: 10083 usage: gunicorn [-h] [-c] gunicorn: error: unrecognized arguments: [app]:app [2018-07-18 13:27:56 -0400] [10083] [INFO] Worker exiting (pid: 10083) [2018-07-18 13:27:56 -0400] [10085] [INFO] Booting worker with pid: 10085 usage: gunicorn [-h] [-c] gunicorn: error: unrecognized arguments: [app]:app [2018-07-18 13:27:57 -0400] [10085] [INFO] Worker exiting (pid: 10085) [2018-07-18 13:27:57 -0400] [10087] [INFO] Booting worker with pid: 10087 usage: gunicorn [-h] [-c] gunicorn: error: unrecognized arguments: [app]:app [2018-07-18 13:27:57 -0400] [10087] [INFO] Worker exiting (pid: 10087) ^C[2018-07-18 13:27:57 -0400] [10080] [INFO] Handling signal: int [2018-07-18 13:27:57 -0400] [10080] [INFO] Shutting down: Master
type: Question
accepted answer: http://stackoverflow.com/a/51411271
has comment: http://stackoverflow.com/comment/89787149
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89787221
has answer: http://stackoverflow.com/a/51411271
tagged with: virtualenv
favorite count: 0
tagged with: gunicorn

http://stackoverflow.com/comment/89682059
comment on: http://stackoverflow.com/a/51346363
type: Comment
has text: @ThuanN. Read my [comment](https://stackoverflow.com/questions/51344610/how-to-setup-1d-convolution-and-lstm-in-keras/51346363?noredirect=1#comment89665788_51344610) in reply to GurmeetSingh.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89845824
type: AnswerComment
comment on: http://stackoverflow.com/a/51366710
score: 0
type: Comment
has text: will do, can you please link your new q/a so I can link it?

http://stackoverflow.com/comment/89755290
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51391323
has text: @program00, please let me know if my extended answer works

http://stackoverflow.com/q/51355762
type: Question
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51356357
has body: I have various items in menu bar where I am trying to give sign of tick after selecting items in menu bar as shown in Image below. Please give me some idea.
type: UnansweredQuestion
has title: Give tick sign after selecting items of menubar in pyqt5
tagged with: python
has comment: http://stackoverflow.com/comment/89693003
has comment: http://stackoverflow.com/comment/89798300
linked to: http://stackoverflow.com/q/45006166
score: 1
duplicate of: http://stackoverflow.com/q/45006166
tagged with: pyqt5
upvote count: 1

http://stackoverflow.com/a/51359226
answers question: http://stackoverflow.com/q/51359018
score: 0
type: Answer
has body: from What&#39;s the scope of a variable initialized in an if statement? Python variables are scoped to the innermost function, class, or module in which they're assigned. Control blocks like if and while blocks don't count, so a variable assigned inside an if is still scoped to a function, class, or module. So if you are wondering why this works: for i in range(0, 3): a = i print(a) &gt;&gt; 2 and why is a accessible outside the for loop then the answer is, this is python and not c++ or R. Deleting them would be a non-pythonic way of doing things yet you can clearly do so forcefully by looking at the other answers

http://stackoverflow.com/a/51411735
type: Answer
answers question: http://stackoverflow.com/q/51411522
score: 0
has body: as an alternative answer, if this isn't production and you're using an Ubuntu system, I managed to get a Flask app running in a matter of days. Here is a link to the tutorial I followed; https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-16-04 I understand it doesn't answer your question but I found it useful the first time round and it worked without any problems, using forms, requesting API data and printing using Jinja template engine for example. You can also use a whole host of other developed plugins for user management and logins, authentication, but the best part is, anything you can do with Python, can be ordered via a web based application, so when you get a grasp of how it all works, there is very little you CAN'T do. In response to the question, I personally used Gunicorn as a go between and use Nginx as a reverse proxy. But there is no reason why Apache cannot substitute Nginx in that line-up that I'm aware of.

http://stackoverflow.com/comment/89868327
type: QuestionComment
has text: @Const inside: `curl http://localhost:5000/status`, outside: `curl http://localhost:5000/status`, `curl http://127.0.0.1:5000/status` none of them (outside) work
score: 0
comment on: http://stackoverflow.com/q/51448634
type: Comment

http://stackoverflow.com/comment/89669555
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51348463
has text: I have used split (" ") meathod , I could see the same result, my intention is to access values one by one by index

http://stackoverflow.com/q/51457474
tagged with: pandas
downvote count: 0
tagged with: multiple-columns
favorite count: 0
has answer: http://stackoverflow.com/a/51457693
has body: Currently self-teaching Python and running into some issues. My challenge requires me to count the number of unique values in a column of an excel spreadsheet in which the rows have no missing values. Here is what I've got so far but I can't seem to get it to work: import xlrd import pandas as pd workbook = xlrd.open_workbook("*name of excel spreadsheet*") worksheet = workbook.sheet_by_name("*name of specific sheet*") pd.value_counts(df.*name of specific column*) s = pd.value_counts(df.*name of specific column*) s1 = pd.Series({'nunique': len(s), 'unique values': s.index.tolist()}) s.append(s1) print(s) Thanks in advance for any help.
tagged with: python
type: AnsweredQuestion
score: 1
has title: Unique Values Excel Column, no missing info in rows - Python
upvote count: 1
tagged with: excel
accepted answer: http://stackoverflow.com/a/51457693
type: Question
possible better answer: http://stackoverflow.com/a/51457737
tagged with: dataframe
has answer: http://stackoverflow.com/a/51457737
answer count: 2

http://stackoverflow.com/a/51421840
has body: This behavior happens because the class binding that inserts the key in the Entry is executed after the widget's binding. Therefore, when writeWhatYouGet is executed, the Entry does not contains\ the new key yet. You can check this with the following code: from tkinter import * startingWindow = Tk() entry = Entry(startingWindow) entry.grid(row=0, column=0) def writeWhatYouGet(): print('bind', (entry.get()).strip()) def writeWhatYouGet2(): print('bind_class', (entry.get()).strip()) entry.bind('&lt;Key&gt;', lambda event:writeWhatYouGet()) entry.bind_class('Entry', '&lt;Key&gt;', lambda event:writeWhatYouGet2(), True) startingWindow.mainloop() To solve this problem, you can use figbeam solution or you can use the validate command option of the Entry: from tkinter import * startingWindow = Tk() def writeWhatYouGet(text): print(text.strip()) return True validatecmd = startingWindow.register(writeWhatYouGet) entry = Entry(startingWindow, validate='key', validatecommand=(validatecmd, '%P')) # %P means that the value the text will have if the change is allowed is passed to validatecmd. entry.grid(row=0, column=0) startingWindow.mainloop() More details about entry validation: http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/entry-validation.html
upvote count: 1
has comment: http://stackoverflow.com/comment/89816079
accepted answer of: http://stackoverflow.com/q/51421319
score: 1
answers question: http://stackoverflow.com/q/51421319
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/89657402
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51341525
type: Comment
has text: I run the code, but also I find some punctuation in results. How I may remove them as stop words. I get something like: "=="

http://stackoverflow.com/q/51329265
has comment: http://stackoverflow.com/comment/89634800
has body: I'm trying to make a python quiz that asks 25 questions. I've used a dictionary to hold the questions, with a key. I've used the random.randint() function to select a random question from the dictionary, and my aim is to, once the question has been answered, remove the question from the dictionary so that it can't be answered again. I haven't coded the logic that decides whether the answer is correct or not. Here is the code that matters: def delete_question(): try: del questions[chosen_question] except KeyError: pass question_number -= 1 random_question.update() root_win2() def root_win2(): global questions, chosen_question, random_question, question_number question_number = 0 questions = { 1: "Describe what the instruction 'BRP' does.", 2: "Describe what is meant by the term 'Open Source Software'.", 3: "What is meant by the term 'Lossy Compression'?", 4: "What is the number '55' as an 8-bit unsigned integer?", 5: "What might a printer use RAM for?", 6: "Describe the term 'firewall'.", 7: "Describe the Rapid Application Development process." } question_number = 7 If question_number &gt; 0: chosen_question = random.randint(1, question_number) random_question = Label(root, bg="white", text=(questions [chosen_question]), font = ('Courier', 13)) random_question.place(x=10, y=50) delete_button = Button(text="Next", command=delete_question, height=3, width=12) delete_button.place(x=370, y = 420) How should I edit my code so that when the question is asked, it isn't asked again? Here's the full code if anyone needs it: from tkinter import * import time import random def destroy(): random_question = Label() close_button.destroy() about_button.destroy() start_button.destroy() version.destroy() conf.destroy() root.title("Computer Science Quiz") random_question.destroy() root_win2() def delete_question(): question_number = 0 try: del questions[chosen_question] except KeyError: pass question_number -= 1 random_question.update() root_win2() def root_win2(): global questions, c…
answer count: 1
has answer: http://stackoverflow.com/a/51329371
favorite count: 0
type: UnansweredQuestion
score: -3
has comment: http://stackoverflow.com/comment/89634128
tagged with: python
has title: Making sure a quiz doesn't ask the same thing twice
upvote count: 0
tagged with: tkinter
has comment: http://stackoverflow.com/comment/89634217
has comment: http://stackoverflow.com/comment/89634189
downvote count: 3
type: Question

http://stackoverflow.com/a/51399815
downvote count: 0
answers question: http://stackoverflow.com/q/51398004
accepted answer of: http://stackoverflow.com/q/51398004
has comment: http://stackoverflow.com/comment/89771808
type: Answer
has body: Your problem is that you need to have 2 copies of the same data in memory. If you build the array as in test1 you'll need far less memory at once, but at the cost of losing the dictionary. import numpy as np import time def test1(n): a = {x:(x, x, x) for x in range(n)} # Build sample data b = np.array([a.pop(i) for i in range(n)]).reshape(-1) return b def test2(n): a = {x:(x, x, x) for x in range(n)} # Build sample data b = np.concatenate(list(a.values())) return b x1 = test1(1000000) del x1 time.sleep(1) x2 = test2(1000000) Results: test1 : 0.71 s test2 : 1.39 s The first peek is for test1, it's not exactly in place but it reduces the memory usage quite a bit.
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91038069
type: AcceptedAnswer

http://stackoverflow.com/comment/89816813
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51418928
has text: [`EnumChildWindows`](https://msdn.microsoft.com/en-us/library/windows/desktop/ms633494) takes a window handle, not a PID. This should be obvious if you know what a "child window" is actually a child of. It's not a child of a process.
score: 0

http://stackoverflow.com/a/51331165
accepted answer of: http://stackoverflow.com/q/51331102
has body: The &lt; with numpy arrays does an element-wise comparison. That means it returns an array where there is a True where the condition is true and False if not. The np.require line is necessary here so it actually uses NumPy arrays. You could drop the np.require if you converted your data and dt to np.arrays beforehand. Then the result is added (element-wise) to the numeric array. In this context True is equal to 1 and False to zero. &gt;&gt;&gt; dt &lt; b # which elements are smaller than b? array([ True, True, False, False, False]) &gt;&gt;&gt; 0 + (dt &lt; b) # boolean arrays in arithmetic operations with numbers array([1, 1, 0, 0, 0]) So it adds 1 to every element of data where the element in dt is smaller than 8.
answers question: http://stackoverflow.com/q/51331102
type: Answer
downvote count: 0
score: 6
upvote count: 6
type: AcceptedAnswer

http://stackoverflow.com/comment/89648436
has text: Yes worked.. what about my second question is it possible ? example: when we type ?ping @.user1 @.user2 bot should ask a message to send, when we add a message it will forward thet message to tagged user.
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51336742

http://stackoverflow.com/q/51381633
favorite count: 0
answer count: 0
type: UnansweredQuestion
has title: setting set_minor_locator pyplot matplotlib
upvote count: 1
type: Question
tagged with: ticker
has comment: http://stackoverflow.com/comment/89736390
score: 1
tagged with: matplotlib
has body: Hi all I'm discovering the wonderful world of matplotlib, in this context , I didn't figure out how to set the minor_locator .. or better which is the way in order to do it automatically , I'm going to explain the point : this is a fragment of my code (I'm writing a class in order to define my plot style) in order to obtain the minor ticks in the way that I like I set : minorXLocator = MultipleLocator(1) minorYLocator = MultipleLocator(0.05) ax.xaxis.set_minor_locator(minorXLocator) ax.yaxis.set_minor_locator(minorYLocator) the aims of this fragment of code is to have 5 minor ticks between two major ticks (the ticks that have the number) I didn't find the way to automatize this ... is uncomfortable each time modify the value of MultipleLocator in order to get 5 minor ticks ... May somebody light my way ? EDIT sorry but I didn't got the point now I've tried to put = majorLocator = MultipleLocator(10) minorXLocator = MultipleLocator(majorLocator/5) minorYLocator = MultipleLocator(majorLocator/5) but doesn't works it giveme back : File "/home/marco/Programming/Python/Numeric/OdeSystem/makeplot.py", line 349, in plot minorXLocator = MultipleLocator(majorLocator/5) TypeError: unsupported operand type(s) for /: 'MultipleLocator' and 'int' I was looking for a trick in order to automaticly put my set_minor_locator (the minor ticks) = 5 between 2 majorlocator (the ticks containing number) like in the plot here
downvote count: 0
tagged with: python

http://stackoverflow.com/comment/89671262
has text: the output for the type is: "class 'numpy.ndarray'>" and the shape is:(11253, 1)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51349248
type: AnswerComment

http://stackoverflow.com/comment/89906921
score: 0
type: Comment
has text: you can accept an answer if it helped you
type: QuestionComment
comment on: http://stackoverflow.com/q/51458685

http://stackoverflow.com/a/51397658
type: Answer
answers question: http://stackoverflow.com/q/51381335
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51381335
has body: According to your comment, you are using default authentication system, but you authenticate with this line : user = authenticate(email=email , password=password) The fix, according to your question, is : email = request.POST["email"] username = request.POST["name"] user = authenticate(username=username , password=password) By default, django log with username, not with email (Cf : the documentation ). For your question in the comment, it is a duplicate of Django - Login with Email. I invite you to find your solution in the accepted answer.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51400332
tagged with: pymysql
has body: I want the insertion query do nothing if it's nothing new in csv file , In Case it is , i want to insert only this one and not again all the csv, any suggestion would be great! PS: it's not duplicate with other questions because here we have "%s" no stable values and in python it's different the syntax! cursorobject=connection.cursor() sql2="CREATE DATABASE IF NOT EXISTS mydb" cursorobject.execute(sql2) sql1="CREATE TABLE IF NOT EXISTS users(id int(11) NOT NULL AUTO_INCREMENT,first_name varchar(255),last_name varchar(255),company_name varchar(255),address varchar(255),city varchar(255),country varchar(255),postal varchar(255),phone1 varchar(255),phone2 varchar(255),email varchar(255),web varchar(255),PRIMARY KEY(id))" cursorobject.execute(sql1) csvfile=open('Entries.csv','r') reader = csv.reader(csvfile,delimiter=',') for row in reader: cursorobject.execute("INSERT INTO users(first_name,last_name,company_name,address,city,country,postal,phone1,phone2,email,web) VALUES (%s ,%s, %s,%s,%s,%s,%s,%s,%s,%s,%s)",row)
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/89771433
has answer: http://stackoverflow.com/a/51400445
has comment: http://stackoverflow.com/comment/89771496
has title: Insert record if not already exists in the table of CSV records in PYTHON
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51400630
tagged with: python
linked to: http://stackoverflow.com/q/1361340
has comment: http://stackoverflow.com/comment/89772538
tagged with: mysql
type: Question
tagged with: database

relationship
tags question: http://stackoverflow.com/q/51419186
tag name: relationship
type: Tag

http://stackoverflow.com/a/51363700
has body: You can retrieve the array underlying your dataframe columns and update the last n items: list_of_baits = ['Bait #1', 'Bait #2', 'Bait #3'] df = pd.DataFrame(columns=['Customer ID', 'Email', 1, 2, 3]) arr = df.columns.values arr[-3:] = list_of_baits # change -3 to -30 df.columns = arr print(df.columns) Index(['Customer ID', 'Email', 'Bait #1', 'Bait #2', 'Bait #3'], dtype='object') Note you should not attempt to update df.columns directly, since Pandas index objects do not support mutable operations. Nor should you attempt to update df.columns.values directly, as this may have unintended side-effects.
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51363230
downvote count: 0
upvote count: 2

http://stackoverflow.com/q/51351804
answer count: 1
downvote count: 0
has title: Extract CSV file from Github library with python
tagged with: github
score: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/89676158
has answer: http://stackoverflow.com/a/51352060
has comment: http://stackoverflow.com/comment/89676442
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: extract
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89676354
type: Question
has body: I'm looking to pull a specific file from a github repo and load into a dictionary in python and then write the file back to a specific folder in the github repo. Suppose, my folder structure is: Github Repo > files > rawfiles > test.txt Github Repo > files > output > output.txt How would I extract one file from Github and then write it back to Github? Below is what I have created, but the output seems to be including all the HTML tags. import csv import urllib url = 'GithubRepo/rawfiles/test.txt' webpage = urllib.urlopen(url) data = [] datareader = csv.reader(webpage) for row in datareader: data.append(row) print data
upvote count: 4
tagged with: export

http://stackoverflow.com/q/51481545
tagged with: python
linked to: http://stackoverflow.com/q/10667960
downvote count: 0
score: 1
type: Question
has body: At https://myhost.example.com I have a my own site with a certificate signed by my own CA. I am using macOS and I added the custom CA certificate to my macOS Keychain. It works properly in the Apple-provided Python with the following minimal code: import requests r = requests.get('https://myhost.example.com') Now I want to execute the same program in the Miniconda environment (the base one): I added my CA certificate to ~/miniconda2/ssl/cacert.pem with: # cat myownca.pem &gt;&gt; ~/miniconda2/ssl/cacert.pem The certificate starts with the following, so I guess it is the proper PEM format: -----BEGIN CERTIFICATE----- MIIDZzCCAk+gAwIBA... I checked: # python -c "import ssl; print(ssl.get_default_verify_paths())" DefaultVerifyPaths(cafile='/Users/asylumine/miniconda2/ssl/cert.pem', capath='/Users/asylumine/miniconda2/ssl/certs', openssl_cafile_env='SSL_CERT_FILE', openssl_cafile='/Users/asylumine/miniconda2/ssl/cert.pem', openssl_capath_env='SSL_CERT_DIR', openssl_capath='/Users/asylumine/miniconda2/ssl/certs') However the Python program is failing: Traceback (most recent call last): File "testinpy.py", line 2, in &lt;module&gt; r = requests.get('https://myhost.example.com') File "/Users/asylumine/miniconda2/lib/python2.7/site-packages/requests/api.py", line 72, in get return request('get', url, params=params, **kwargs) File "/Users/asylumine/miniconda2/lib/python2.7/site-packages/requests/api.py", line 58, in request return session.request(method=method, url=url, **kwargs) File "/Users/asylumine/miniconda2/lib/python2.7/site-packages/requests/sessions.py", line 508, in request resp = self.send(prep, **send_kwargs) File "/Users/asylumine/miniconda2/lib/python2.7/site-packages/requests/sessions.py", line 618, in send r = adapter.send(request, **kwargs) File "/Users/asylumine/miniconda2/lib/python2.7/site-packages/requests/adapters.py", line 506, in send raise SSLError(e, request=request) requests.exceptions.SSLError: HTTPSConnectionPool(host='myhost.example.com', port=4…
tagged with: ssl
tagged with: conda
has title: Using custom CA certificate with Conda Python on macOS
duplicate of: http://stackoverflow.com/q/10667960
upvote count: 1
favorite count: 0
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/89840593
comment on: http://stackoverflow.com/a/51435014
type: AnswerComment
score: 0
type: Comment
has text: Okay. Then please use padding of zeroes. `str(htval).zfill(3)` . As htval is a real number it will work.

http://stackoverflow.com/comment/89802059
type: QuestionComment
comment on: http://stackoverflow.com/q/51415275
type: Comment
has text: Could you please add an example of "current distribution","adding new data", "new distribution"
score: 0

http://stackoverflow.com/comment/89839431
score: 0
type: Comment
has text: Thanks a lot. It works like a charm. I got it what i expected.. You are brilliant!
type: AnswerComment
comment on: http://stackoverflow.com/a/51434527

http://stackoverflow.com/comment/89781424
has text: For the time being, try using `model.pprint()` instead of `model.display()` for troubleshooting before you call the `solve()` statement. I have raised the `display()` issue on Github. https://github.com/Pyomo/pyomo/issues/616
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51362762

http://stackoverflow.com/comment/89758475
has text: text=str(count) is a line of code serving no purpose here, your suggestion was correct though
comment on: http://stackoverflow.com/a/51393390
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89702922
type: Comment
comment on: http://stackoverflow.com/a/51363203
type: AnswerComment
has text: The fact that you are apparently trying unabashedly to use Kali as a development platform might also mean something... See also https://unix.stackexchange.com/questions/399626/why-is-kali-linux-so-hard-to-set-up-why-wont-people-help-me
score: 0

http://stackoverflow.com/comment/89695078
comment on: http://stackoverflow.com/q/51361420
type: Comment
has text: _"Would it be better to store the results in a list?"_. Excellent question. Go ahead and try it, and let us know if it improves the runtime of your program :^)
type: QuestionComment
score: 0

http://stackoverflow.com/a/51463411
has comment: http://stackoverflow.com/comment/89895729
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89895981
has comment: http://stackoverflow.com/comment/89895694
answers question: http://stackoverflow.com/q/51463341
upvote count: 2
has comment: http://stackoverflow.com/comment/119894865
has body: Although regular Python types do support "chained comparison" like 1 &lt; x &lt; 5, NumPy arrays do not. Perhaps that's unfortunate, but you can work around it easily: x[(-1 &lt;= x) &amp; (x &lt;= 1)]
has comment: http://stackoverflow.com/comment/89895696
type: Answer

http://stackoverflow.com/comment/89679097
type: QuestionComment
score: 0
has text: Okay thank you. I'll give it a look.
comment on: http://stackoverflow.com/q/51353038
type: Comment

http://stackoverflow.com/q/51412137
duplicate of: http://stackoverflow.com/q/20449427
has comment: http://stackoverflow.com/comment/89795892
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89795863
has comment: http://stackoverflow.com/comment/89795874
type: UnansweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/51412201
favorite count: 0
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/89795884
has title: Input() is not working
tagged with: python
linked to: http://stackoverflow.com/q/20449427
score: -1
has comment: http://stackoverflow.com/comment/89835724
has body: I tried to create this rock paper scissors game. But the input isn't working. Anyone know what I'm doing wrong? Every time i tried to enter input it would show think that i didnt enter anything or didn't enter a number 1-3 and go straight to else. import random import time y=3 while y&gt;0: print("Lets play Rock Paper Scissors") print("1 for Rock") print("2 for Paper") print("3 for Scissors") time.sleep(1) print("Rock, Paper, Scissors...") var=input() z=random.randint(1,3) if z==1: print("I play Rock") time.sleep(1) if str(var)==1: print("You played Rock too! TIE") if str(var)==2: print("You played Paper! YOU WIN!!!") if str(var)==3: print("You played Scissors! I WIN!") y=y-1 else: print("ERROR! Pick a number 1-3.") if z==2: print("I play Paper") time.sleep(1) if str(var)==1: print("You played Rock! I WIN!") y=y-1 if str(var)==2: print("You played Paper too! TIE") if str(var)==3: print("You played Scissors! YOU WIN!!!") else: print("ERROR! Pick a number 1-3.") if z==3: print("I play Scissors") time.sleep(1) if str(var)==1: print("You played Rock! YOU WIN!!!") if str(var)==2: print("You played Paper too! I WIN!") y=y-1 if str(var)==3: print("You played Scissors too! TIE") else: print("ERROR! Pick a number 1-3.") else: print("THIS SHOULDN'T BE POSSIBLE BUT OH WELL.... EASTER EGG")

http://stackoverflow.com/comment/89929857
comment on: http://stackoverflow.com/a/51480336
type: AnswerComment
score: 0
type: Comment
has text: Thank you very much, you helped a lot!

deep-learning
tags question: http://stackoverflow.com/q/51351004
tags question: http://stackoverflow.com/q/51390692
tags question: http://stackoverflow.com/q/51336624
tags question: http://stackoverflow.com/q/51465526
tags question: http://stackoverflow.com/q/51366521
tags question: http://stackoverflow.com/q/51433378
tags question: http://stackoverflow.com/q/51373919
tags question: http://stackoverflow.com/q/51361402
tags question: http://stackoverflow.com/q/51410692
tags question: http://stackoverflow.com/q/51463383
tags question: http://stackoverflow.com/q/51343169
tags question: http://stackoverflow.com/q/51337578
tags question: http://stackoverflow.com/q/51469434
tags question: http://stackoverflow.com/q/51473904
tags question: http://stackoverflow.com/q/51360827
tags question: http://stackoverflow.com/q/51329234
tags question: http://stackoverflow.com/q/51359808
tags question: http://stackoverflow.com/q/51328208
tags question: http://stackoverflow.com/q/51371910
tags question: http://stackoverflow.com/q/51369284
tags question: http://stackoverflow.com/q/51346551
tags question: http://stackoverflow.com/q/51475745
tags question: http://stackoverflow.com/q/51476434
tags question: http://stackoverflow.com/q/51469446
tags question: http://stackoverflow.com/q/51340235
type: Tag
tags question: http://stackoverflow.com/q/51409906
tags question: http://stackoverflow.com/q/51405110
tags question: http://stackoverflow.com/q/51453964
tags question: http://stackoverflow.com/q/51480521
tags question: http://stackoverflow.com/q/51331502
tags question: http://stackoverflow.com/q/51408162
tags question: http://stackoverflow.com/q/51329974
tags question: http://stackoverflow.com/q/51408417
tag name: deep-learning
tags question: http://stackoverflow.com/q/51335512
tags question: http://stackoverflow.com/q/51467369
tags question: http://stackoverflow.com/q/51363709
tags question: http://stackoverflow.com/q/51335371
tags question: http://stackoverflow.com/q/51437817
tags question: http://stackoverflow.com/q/51356524

http://stackoverflow.com/q/51411434
has comment: http://stackoverflow.com/comment/89836592
type: UnansweredQuestion
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89794761
has comment: http://stackoverflow.com/comment/89795290
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/89795181
has comment: http://stackoverflow.com/comment/89802314
has title: Textract won't read .doc files in Greek
upvote count: 1
has comment: http://stackoverflow.com/comment/111634996
tagged with: .doc
has body: I am trying to read a bunch of .doc files in Python to run some text analysis. The docs (an example of which is attached here) contain certain non-ascii characters in Greek (for which i do not know the encoding MS Word uses). Code i am using: import textract text = textract.process("path_to_sample.doc", extension = 'doc', encoding = "utf_8") I tried many encoding arguments but non have worked. Any ideas?
answer count: 0
downvote count: 0

http://stackoverflow.com/a/51411667
downvote count: 0
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51411622
has body: You are looking for list.index(value)
accepted answer of: http://stackoverflow.com/q/51411622
type: AcceptedAnswer

http://stackoverflow.com/comment/89842149
type: QuestionComment
comment on: http://stackoverflow.com/q/51417764
score: 0
has text: do one thing, check on global site-package checbox while configuring python interpreter.
type: Comment

http://stackoverflow.com/a/51463291
score: 1
answers question: http://stackoverflow.com/q/51463064
upvote count: 1
downvote count: 0
has body: A bytestring can handle your text independently from your operating system behaviour. Try to write the file also in this filemode by using e.g.: teststring = b'time,Light Level,Air Pressure,Humidity,Temperature,CO2,Pollution,Sound\r\n2017-04-01 06:55:00+00:00,56.0,1004.52001953125,56.7000007629395,20.7999992370605,0.0,0.0,38.2862205505371\r\n2017-04-01 06:56:00+00:00,142.0,1004.53002929688,56.5999984741211,20.7999992370605,0.0,0.0,37.7092018127441\r\n' f = open("testfile.csv", 'ab') # &lt;- 'b' = bytestring f.write(teststring) # &lt;- without converting it to str f.close()
type: Answer

http://stackoverflow.com/a/67818131
upvote count: 6
has body: Using pytest, the solution for me was to add the -s option. For example, in my scenario where I also needed verbose mode on, I had to put pytest -sv.
answers question: http://stackoverflow.com/q/51362213
type: Answer
downvote count: 0
score: 6

http://stackoverflow.com/q/51374900
has title: How to normalize columns with one-hot encoding efficiently in pandas dataframes?
tagged with: one-hot-encoding
has answer: http://stackoverflow.com/a/51374923
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
tagged with: normalization
upvote count: 1
favorite count: 0
has body: A column of an example dataframe is shown: Fruit FruitA FruitB Apple Banana Mango Banana Apple Apple Mango Apple Banana Banana Mango Banana Mango Banana Apple Apple Mango Mango I want to introduce new columns in the dataframe Fruit-Apple, Fruit-Mango, Fruit-Banana with one-hot encoding in the rows they are respectively present. So, the desired output is: Fruit FruitA FruitB Fruit-Apple Fruit-Banana Fruit-Mango Apple Banana Mango 1 1 1 Banana Apple Apple 1 1 0 Mango Apple Banana 1 1 1 Banana Mango Banana 0 1 1 Mango Banana Apple 1 1 1 Apple Mango Mango 1 0 1 My code to do this is: for i in range(len(data)): if (data['Fruits'][i] == 'Apple' or data['FruitsA'][i] == 'Apple' or data['FruitsB'][i] == 'Apple'): data['Fruits-Apple'][i]=1 data['Fruits-Banana'][i]=0 data['Fruits-Mango'][i]=0 elif (data['Fruits'][i] == 'Banana' or data['FruitsA'][i] == 'Banana' or data['FruitsB'][i] == 'Banana'): data['Fruits-Apple'][i]=0 data['Fruits-Banana'][i]=1 data['Fruits-Mango'][i]=0 elif (data['Fruits'][i] == 'Mango' or data['FruitsA'][i] == 'Mango' or data['FruitsB'][i] == 'Mango'): data['Fruits-Apple'][i]=0 data['Fruits-Banana'][i]=0 data['Fruits-Mango'][i]=1 But I notice that the time taken for running this code increases dramatically if there are a lot of types of 'fruits'. In my actual data, there are only 1074 rows, and the column I'm trying to "normalize" with one-hot encoding has 18 different values. So, there are 18 if conditions inside the for loop, and the code hasn't finished running for 15 mins now. That's absurd (It would be great to know why its taking so long - in another column that contained only 6 different types of values, the code took much less time to execute, about 3 mins). So, what's the best (vectorized) way to achieve this output?
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51374923
answer count: 1

http://stackoverflow.com/q/51375833
has title: Multiple headers while I just want to have a single header
score: 0
has body: So I have this chunk script def alltime_tracker(sheet_url,sheet_name,concatfile): temp2 = pd.read_csv(sheet_url) temp2 = temp2[(temp2['Time Complete'] != today)] temp2 = pd.concat([temp2,concatfile]) temp2.to_csv(sheet_name,encoding='utf-8', index=False) sheet1_url = 'https://docs.google.com...' sheet1_name = 'sheet1.csv' alltime_tracker(sheet1_url,sheet1_name,damagedclaim) This intended output is that the tracker will be updated everyday. The sheet1_url is a blank spreadsheet with headers. While, concatfile is a different spreadsheet filled with headers and data from today. I've connected this script to google gdocs/google API so it automates/run the code everyday. However, when the script runs on the second day, it produced multiple headers (three headers in total and the script has been running for two days). Can anybody help me with this issue so that it only produces 1 header whenever the script runs?. Thank you.
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/89726463
has comment: http://stackoverflow.com/comment/89768103
answer count: 0
tagged with: google-api
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89757893
type: Question

http://stackoverflow.com/q/51384413
tagged with: python
linked to: http://stackoverflow.com/q/37317727
has comment: http://stackoverflow.com/comment/89742045
answer count: 0
tagged with: linear-regression
upvote count: 2
has body: I am using TradingView and calculating moving average using linreg(close, 20, 1) # close: current closing price # 20: is the lookback period # 1: is the offset I couldn't find a way to calculate and get their exact result in Pandas. Here is how my dataframe looks like: db['20 Moving Average'] = db['Close'].rolling(20).mean() db'Date', 'Open', 'High', 'Low', 'Close', '20 Moving Average'.tail(10).reset_index(drop=True) Date Open High Low Close 20 Moving Average 0 2018-07-13 11:00:00 1.16311 1.16366 1.16128 1.16268 1.166573 1 2018-07-13 12:00:00 1.16268 1.16380 1.16161 1.16353 1.166384 2 2018-07-13 13:00:00 1.16349 1.16379 1.16213 1.16246 1.166088 3 2018-07-13 14:00:00 1.16247 1.16348 1.16186 1.16266 1.165766 4 2018-07-13 15:00:00 1.16267 1.16469 1.16251 1.16450 1.165579 5 2018-07-13 16:00:00 1.16455 1.16487 1.16373 1.16419 1.165408 6 2018-07-13 17:00:00 1.16418 1.16692 1.16397 1.16667 1.165388 7 2018-07-13 18:00:00 1.16667 1.16731 1.16589 1.16667 1.165350 8 2018-07-13 19:00:00 1.16668 1.16776 1.16652 1.16735 1.165357 9 2018-07-13 20:00:00 1.16734 1.16762 1.16663 1.16762 1.165394 10 2018-07-13 21:00:00 1.16762 1.16829 1.16739 1.16768 1.165459 What i am trying to do is get the 20th Linear moving average of each row. For Simple moving average, i am using the following code: db['20 Moving Average'] = db['Close'].rolling(20).mean() Is there a way to calculate 20 Linear Average same way i did for MA? Thanks EDIT: This is not a duplicate. I am trying to get last 20 days linear regression to each row.
has comment: http://stackoverflow.com/comment/89741079
type: Question
has comment: http://stackoverflow.com/comment/89741506
has comment: http://stackoverflow.com/comment/89741487
tagged with: pandas
has title: How can i calculate Linear Regression moving average for a period in pandas?
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89751601
favorite count: 0
tagged with: moving-average
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89740919

http://stackoverflow.com/a/51367483
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51367022
score: 3
has comment: http://stackoverflow.com/comment/89707692
answers question: http://stackoverflow.com/q/51367022
has body: Your code is attempting to create an infinite number of Label objects, hiding each one behind an infinite stack of other labels. This obviously leads to problems unless you have infinite memory. What you want is just four labels at any given time. You need to keep track of the labels you’ve created and ideally just reuse them, or, if not, destroy them instead of just hiding them behind new ones. Currently, your code is keeping track of the labels in those img1 through img4 variables, except that they don’t get created until the first time they show an image, so you can’t check them. So, before the loop, you’ll either want to create four empty labels, or just set the variables to None. Then, inside the loop, you can do this (assuming you went withNone instead of empty labels): if cam.getPlace() == "FrontYard1": try: if img1 is None: img1 = Label(image=render) img1.grid(row=0, column=0) else: img1.image = render # etc. You could simplify this by storing the labels in a dict instead of four separate variables: imgs = {“Front Yard 1": img1, …} … and then replacing the if/elif chain with a dict lookup: img = imgs.get(cam.getPlace()) Although here, you’re almost certainly going to want to go with empty labels instead of None for the initial values. As a side note, your program has another very serious problem. A while True: loop obviously never returns to the tkinter event loop. This means you don’t give tkinter a chance to update the display, or respond to mouse events or quits or other events from the window system, so your app is going to be nonresponsive and pop up a beach ball or hourglass or whatever. To fix this, you need to remove the loop and instead have your method just retrieve and process one image and then call after to ask tkinter to call it again the next time through the event loop. This will also require changing those local img1 variables (or the dict imgs suggested above) into instance variables. If you were trying to use a background thread for this t…
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/89707384

http://stackoverflow.com/q/51389997
tagged with: pandas
linked to: http://stackoverflow.com/q/10274774
tagged with: python
upvote count: 2
possible better answer: http://stackoverflow.com/a/51390109
downvote count: 1
has answer: http://stackoverflow.com/a/51390109
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51390120
type: Question
tagged with: numpy
answer count: 2
has title: How to show name of predicted classes
favorite count: 0
has body: Predict returns me a numpy array (which consists only from 0 and 1) for every column. How to print names of columns which have 1 and dont show columns which have 0? predict [[0., 0., 0., 0., 0., 0., 0., 0., 1., 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., 0., 0., 0., 0., 0., 0., 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., 1., 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.]] I have list of columns names - columns_names: ['1', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '2', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '3', '30', '31', '32', '33', '34', '4', '5', '6', '7', '8', '9'] type(predict) - numpy.ndarray type(columns_names) - list
accepted answer: http://stackoverflow.com/a/51390120

http://stackoverflow.com/a/51379153
has comment: http://stackoverflow.com/comment/89763309
answers question: http://stackoverflow.com/q/51379017
type: Answer
has comment: http://stackoverflow.com/comment/89730154
has comment: http://stackoverflow.com/comment/89741039
has comment: http://stackoverflow.com/comment/89744377
has body: Have assignment(self) return this_vehicle, then use Plan().assignment() within Draw(). Eg: class Plan(): def assignment(self): # create a vehicle as 'this_vehicle' with id = 0 from class Vehicle() this_vehicle = Vehicle(0) this_vehicle.routes.append(5) this_vehicle.routes.append(8) return this_vehicle def Draw(): vehicle0 = Plan().assignment() # whatever else you want to do Alternatively, store the vehicle within the Plan class. class Plan(): def assignment(self): # create a vehicle as 'this_vehicle' with id = 0 from class Vehicle() self.this_vehicle = Vehicle(0) self.this_vehicle.routes.append(5) self.this_vehicle.routes.append(8) def Draw(): route_plan = Plan() route_plan.assignment() # route_plan.this_vehicle now holds vehicle0 # whatever else you want to do Multiple Vehicles: For this, you'll have to restructure Plan a little, although i feel this is getting a little messy, a dictionary is probably best here. class Plan(): def __init__(self): self.vehicles = dict() def assignment(self, id): # create a vehicle as 'this_vehicle' with id = 0 from class Vehicle() self.vehicles[id] = Vehicle(id) self.vehicles[id].routes.append(5) self.vehicles[id].routes.append(8) def Draw(): route_plan = Plan() route_plan.assignment(0) # route_plan.vehicles[0] now holds vehicle0 # whatever else you want to do
has comment: http://stackoverflow.com/comment/89730578
upvote count: 1
has comment: http://stackoverflow.com/comment/89734877
score: 0
has comment: http://stackoverflow.com/comment/89731179
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/89739294
accepted answer of: http://stackoverflow.com/q/51379017

http://stackoverflow.com/comment/89635225
type: QuestionComment
has text: Knapsack attacks are quite plentiful on this site and elsewhere. How does your variation of these algorithms not fall into any of those categories? Please compare/contrast and show how far you get with those solutions.
comment on: http://stackoverflow.com/q/51329426
score: 0
type: Comment

http://stackoverflow.com/comment/89786074
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51407051
type: Comment
has text: @Abhishek -- Interesting. I don't think it should. Without having a reproducible example, I can't do much either. This approach of checking isgen once upfront, would be much faster than other solutions generally.

http://stackoverflow.com/comment/89828128
type: QuestionComment
has text: Hello Shawn, i added configurations into the post .
score: 0
comment on: http://stackoverflow.com/q/51427540
type: Comment

http://stackoverflow.com/a/51409431
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51406498
has body: import math def main(): numbersFile=open("RandomNumber.txt" , 'r') line=numbersFile.readline() total=0 numberoflines=0 while line != "": numberoflines+=1 total+=float(line) line=numbersFile.readline().rstrip('\n') #had to read the line inside the loop and after converted to float numbersFile.seek(0) #used .seek(0) to go back and read file from beginning average=total/numberoflines #removed from loop to calculate final iteraton, instead of creating a new avg every loop line=numbersFile.readline() total=0 while line !="": #added this while loop to seperatly calculate the standard deviatoin from the average line=float(line)-average a=line**2 total+=a line=numbersFile.readline() std=math.sqrt(total/numberoflines) print("The average is: " , average) print("The standard deviation of the numbers is: " , std) main()

http://stackoverflow.com/q/51330846
downvote count: 1
has answer: http://stackoverflow.com/a/51331326
accepted answer: http://stackoverflow.com/a/51331326
has title: Python accessing attribute of wrong class
has comment: http://stackoverflow.com/comment/89637548
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89637445
tagged with: namespaces
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/89637659
type: Question
has comment: http://stackoverflow.com/comment/89637520
has comment: http://stackoverflow.com/comment/89638254
has body: I am currently facing the issue, that my Python script is accessing an attribute of a wrong class. This is obviously regarding to some namespace conflicts within my project. Let me show you my current implementation: Project structure (everything in the same package): |- bot_test_project |- bot.py |- message.py bot.py: import logging from telegram.ext import Updater, MessageHandler, Filters, CommandHandler API_KEY = "please enter your api key here" logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) class Bot: def __init__(self): updater = Updater(API_KEY) self.__bot = updater.bot dispatcher = updater.dispatcher dispatcher.add_handler(CommandHandler("start", self.receive_command, pass_user_data=True)) dispatcher.add_handler(MessageHandler(Filters.text, self.receive_message, pass_user_data=True)) updater.start_polling() def receive_command(self, bot, update, user_data): print(update.message.id) def receive_message(self, bot, update, user_data): print(update.message.id) Bot() message.py: class Message: def __init__(self, id=None, text=None, photo=None): self.__id = id self.__text = text self.__photo = photo @property def id(self): return self.__id @property def text(self): return self.__text @property def photo(self): return self.__photo However, I am currently getting the following error message: 2018-07-13 23:13:35,915 - telegram.ext.dispatcher - ERROR - An uncaught error was raised while processing the update Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/telegram/ext/dispatcher.py", line 279, in process_update handler.handle_update(update, self) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/telegram/ext/commandhandler.py", line 173, in handle_update return self.callback(dispatcher.bot, update, **optional_args) File "/bot.py", line 23, in receive_command print(update.mes…
has comment: http://stackoverflow.com/comment/89649606
has comment: http://stackoverflow.com/comment/89637660
upvote count: 2
has comment: http://stackoverflow.com/comment/89637866
answer count: 1

http://stackoverflow.com/comment/89793178
score: 2
has text: How long are `x` and `y`? The loops and check will be polynomial complexity, which is not very good. If performance is important, you could probably get it better with an interval tree.
type: QuestionComment
comment on: http://stackoverflow.com/q/51410808
type: Comment

http://stackoverflow.com/q/51430277
linked to: http://stackoverflow.com/q/45946970
score: 0
tagged with: pandas
duplicate of: http://stackoverflow.com/q/25447700
tagged with: python
has title: Annotate pandas Bar plot with reference to another column
has comment: http://stackoverflow.com/comment/89831867
answer count: 0
type: UnansweredQuestion
type: Question
linked to: http://stackoverflow.com/q/25447700
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/89831656
has body: Plot is shown here I'm plotting Column A against B and I want to annotate them by Column C. &gt;&gt;&gt;df=pd.DataFrame({'A':np.random.rand(3),'B':np.random.rand()},index=['value1','value2']) &gt;&gt;&gt; df A B C value1 0.594772 0.483379 0.409961 value2 0.238280 0.321525 0.359370 value3 0.096922 0.226182 0.574583 &gt;&gt;&gt; df.plot.bar(x = 'A', y = 'B')]

http://stackoverflow.com/a/51367081
has body: After quick review if you remove step two to not actual show it and just save it straight to the computer this will help cut down on the ram. Do you have any details on how much RAM you have and how much the computer is using during the process? Another could be adding a step to format the image to a certain size as it might be too large to process large quantities.
type: Answer
has comment: http://stackoverflow.com/comment/89706713
downvote count: 1
answers question: http://stackoverflow.com/q/51367022
score: -1
upvote count: 0

http://stackoverflow.com/q/51415725
has answer: http://stackoverflow.com/a/51415771
type: Question
has comment: http://stackoverflow.com/comment/89802796
has title: How to replace indices values in a cell with the column value in a Pandas dataframe
accepted answer: http://stackoverflow.com/a/51415775
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/89802753
favorite count: 0
has answer: http://stackoverflow.com/a/51415807
tagged with: knn
has body: I have a dataset with unique IDs and few attributes. I executed the k-d tree in Python to get the indices of each id for three nearest neighbors as shown in the following figure: The "Index" in the above figure is the default indices that comes with a Pandas dataframe. I want the output in the format as shown in the figure below: This can be easily accomplished in an excel using vlookup but how to do this in Python?
has answer: http://stackoverflow.com/a/51415775
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/89802681
has answer: http://stackoverflow.com/a/51415824
score: 2
type: AnsweredQuestion
upvote count: 2
possible better answer: http://stackoverflow.com/a/51415771
has comment: http://stackoverflow.com/comment/89802729

http://stackoverflow.com/q/51346410
has comment: http://stackoverflow.com/comment/89667144
has title: How to pass arguments between two spiders with scrapy callback
has comment: http://stackoverflow.com/comment/89683242
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89668134
upvote count: 1
has body: I have two scrapy that the first one crawl a sitemap and extract urls and put it in a txt file and the second one reads it and crawl this urls line by line. my code like bellow : class sitemapSpider(SitemapSpider): name = "filmnetmapSpider" sitemap_urls = ['http://filmnet.ir/sitemap.xml'] sitemap_rules = [ ('/series/', 'parse_item') ] storage_file = 'urls.txt' def parse_item(self, response): videoid = response.url with open(self.storage_file, 'a') as handle: yield handle.writelines(videoid + '\n') second spider : class filmnetSpider(scrapy.Spider): name = 'filmnetSpider' def start_requests(self): with open('urls.txt') as fp: for line in fp: yield Request(line.strip(), callback=self.parse_website) def parse_website(self, response): hxs = HtmlXPathSelector(response) url = hxs.xpath('//script[@type="application/ld+json"]/text()').extract() url = ast.literal_eval(json.dumps(url)) url = url[1] obj = json.loads(url) poster = obj['image'] name = obj['name'] description = obj['description'] How to change the code to delete read/write to the file? How to use callback in it? Note : This code does not work in one scrapy spider ;code is :Two given scrapy + bellow code ,As an example is said in doc process = CrawlerProcess() process.crawl(filmnetSpider) process.crawl(sitemapSpider) process.start()
tagged with: scrapy
has comment: http://stackoverflow.com/comment/89669323
type: Question
score: 1
has answer: http://stackoverflow.com/a/51347937
has comment: http://stackoverflow.com/comment/89669350
downvote count: 0
answer count: 1
tagged with: callback
favorite count: 0
has comment: http://stackoverflow.com/comment/89683313
tagged with: python

http://stackoverflow.com/comment/89884635
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51457536
has text: @ThierryLathuille I understand, and edited the answer

http://stackoverflow.com/a/51452619
type: Answer
has body: Here's a solution that accounts for a couple of edge cases: 1. Non-consecutive groups of descending series 2. Last value being part of a descending series I've updated OP data to create 3 groupings of descending series (see Data section below), to demonstrate edge case coverage. The basic strategy is to create named groups for each descending series, and then use groupby() operations to compute the desired attributes. First create a dec column that tracks descending series: df["dec"] = df["values"].diff().lt(0) Now make group assignments. The assign_group() function basically checks the dec value of its neighbors and determines its group based on neighbor status. groups = ["a", "b", "c", "d", "e"] groups2 = ["a", "b", "c", "d", "e"] orig_len = len(groups) def assign_group(x, prev): ix = orig_len - len(groups2) try: if ~x.dec &amp; df.iloc[x.name + 1].dec: return groups2.pop(0) elif df.iloc[x.name + 1].dec | x.dec &amp; ~df.iloc[x.name + 1].dec: return groups[ix-1] else: return None except IndexError: if df.iloc[x.name - 1].dec: return groups[ix-1] return None df["grp"] = df.apply(assign_group, args=(prev,), axis=1) ^ Note: The groups variable can contain any sequence of values - I've just used a few letters for demonstration, but for a much larger dataset some large sequence of numbers might be more appropriate. Now the final groupby() is simple: df.groupby("grp")["values"].agg(["count", lambda x: x.iloc[-1] / x.iloc[0] * 100]) count &lt;lambda&gt; grp a 10 71.403399 b 8 29.830400 c 2 0.000000 df time values dec grp 0 11:55 0.940353 False a 1 12:00 0.919144 True a 2 12:05 0.909454 True a 3 12:10 0.904968 True a 4 12:15 0.867957 True a 5 12:20 0.801426 True a 6 12:25 0.794733 True a 7 12:30 0.770106 True a 8 12:35 0.741985 True a 9 12:40 0.671444 True a 10 12:45 1.000000 False b 11 12:50 0.496972 True b 12 12:55 0.457803 True b 13 13:00 0.446388 True b 14 13:05 0.430217 True b 15 13:10 0.379902 True b 16 13:15 0.321828 True b 17 13:20 0.298304 True b 18 13:25 0.44207…
answers question: http://stackoverflow.com/q/51452562
has comment: http://stackoverflow.com/comment/89875431
score: 1
has comment: http://stackoverflow.com/comment/89875353
upvote count: 1
has comment: http://stackoverflow.com/comment/89875360
downvote count: 0
has comment: http://stackoverflow.com/comment/89876103
has comment: http://stackoverflow.com/comment/89875334
has comment: http://stackoverflow.com/comment/89875539

http://stackoverflow.com/comment/89756816
type: Comment
score: 0
type: AnswerComment
has text: I just tried this! Still did not resolve. I do not get an error page now though! I can click the link, but it does not take me anywhere, nor does the url change.
comment on: http://stackoverflow.com/a/51392286

http://stackoverflow.com/comment/127318760
type: Comment
comment on: http://stackoverflow.com/a/57793454
type: AnswerComment
score: 0
has text: This is exactly what I'm looking for. I really think that this should be the default behavior of `flatten_json`. Thank you !

http://stackoverflow.com/a/51344881
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51336074
type: Answer
accepted answer of: http://stackoverflow.com/q/51336074
has body: I was able to reverse this and achieve what I wanted to get mask = labels[:-pad_x] == 0 resizedOrig = cv2.resize(frame, (512,384)) resizedOrig[mask] = 0
score: 0

http://stackoverflow.com/comment/89759774
type: Comment
comment on: http://stackoverflow.com/q/51393461
type: QuestionComment
has text: Can you attach sample input and template image as well? [This](https://docs.opencv.org/2.4/doc/tutorials/imgproc/imgtrans/filter_2d/filter_2d.html) is the closest thing I can think as of now
score: 0

http://stackoverflow.com/comment/120620651
score: 0
type: Comment
comment on: http://stackoverflow.com/a/62876618
has text: Tried the useful answer below and it works.
type: AnswerComment

http://stackoverflow.com/q/51443114
has comment: http://stackoverflow.com/comment/89856202
type: AnsweredQuestion
has title: What happens in the backstage when we import a jar to pyspark shell
has comment: http://stackoverflow.com/comment/89859546
linked to: http://stackoverflow.com/q/31684842
upvote count: 1
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51443712
linked to: http://stackoverflow.com/q/3652554
tagged with: pyspark
has comment: http://stackoverflow.com/comment/89861511
has comment: http://stackoverflow.com/comment/89864291
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89859557
score: 0
tagged with: apache-spark
has answer: http://stackoverflow.com/a/51443712
has body: I understand that pyspark shell uses Python interpreter. How is it possible to import a jar to it? What happens in the backstage that makes it possible?
has comment: http://stackoverflow.com/comment/89859588
has comment: http://stackoverflow.com/comment/89859914
tagged with: python
has comment: http://stackoverflow.com/comment/89859477
has comment: http://stackoverflow.com/comment/89857610

http://stackoverflow.com/comment/95079264
has text: What if I have multiple ouputs?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51368861

neural-network
tags question: http://stackoverflow.com/q/51373919
tags question: http://stackoverflow.com/q/51433774
tags question: http://stackoverflow.com/q/51441358
tags question: http://stackoverflow.com/q/51342088
tags question: http://stackoverflow.com/q/51324797
tags question: http://stackoverflow.com/q/51460835
tags question: http://stackoverflow.com/q/51328208
tags question: http://stackoverflow.com/q/51432992
tags question: http://stackoverflow.com/q/51401416
tags question: http://stackoverflow.com/q/51446438
tags question: http://stackoverflow.com/q/51457797
tags question: http://stackoverflow.com/q/51380111
type: Tag
tags question: http://stackoverflow.com/q/51349186
tags question: http://stackoverflow.com/q/51382920
tags question: http://stackoverflow.com/q/51332144
tags question: http://stackoverflow.com/q/51466437
tags question: http://stackoverflow.com/q/51422301
tags question: http://stackoverflow.com/q/51474015
tags question: http://stackoverflow.com/q/51436452
tags question: http://stackoverflow.com/q/51482406
tags question: http://stackoverflow.com/q/51467369
tags question: http://stackoverflow.com/q/51450313
tags question: http://stackoverflow.com/q/51481676
tag name: neural-network
tags question: http://stackoverflow.com/q/51391083
tags question: http://stackoverflow.com/q/51351004
tags question: http://stackoverflow.com/q/51437086
tags question: http://stackoverflow.com/q/51333501
tags question: http://stackoverflow.com/q/51436746
tags question: http://stackoverflow.com/q/51437407

http://stackoverflow.com/q/51420557
has comment: http://stackoverflow.com/comment/89812581
answer count: 1
has answer: http://stackoverflow.com/a/51420652
has comment: http://stackoverflow.com/comment/89812216
tagged with: data-analysis
accepted answer: http://stackoverflow.com/a/51420652
tagged with: pandas
has comment: http://stackoverflow.com/comment/89812282
has comment: http://stackoverflow.com/comment/89812392
tagged with: python
score: 0
has title: How to pivot_table with with duplicated index
has comment: http://stackoverflow.com/comment/89812661
has comment: http://stackoverflow.com/comment/89812459
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89812160
has comment: http://stackoverflow.com/comment/89812238
tagged with: dataframe
has body: I have a df_ like this, name level status yes high open no high closed no med closed yes low open no med rejected no high open I am trying to create a pivot table with index='level',columns='status', values=sum of occurances with respect to the column and index my code: df_['temp']=df_['level'].astype(bool).astype(int) df_.pivot(index='level',columns='status',values='temp') but gives me, ValueError: Index contains duplicate entries, cannot reshape My expected output is, open closed rejected high 2 1 0 med 0 1 1 low 1 0 0 Please check and tell me if there is any other easy way.
type: Question

http://stackoverflow.com/comment/89675147
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51351229
has text: Being able to alter a method's functionality was a push to what I'm used to in C# - it's more of a 'would be nice to have' case. My current approach for allowing pre & post callbacks is to use an injector decorator and pass through the target method, and any args. Not so sure if that's the right way to handle such thing though.
type: AnswerComment

http://stackoverflow.com/a/51354880
downvote count: 0
has body: It seems Google's python library contains a module for id token validation. This can be found at google.oauth2.id_token module. Once validated, it will return the decoded token which you can use to obtain user information. from google.oauth2 import id_token from google.auth.transport import requests request = requests.Request() id_info = id_token.verify_oauth2_token( token, request, 'my-client-id.example.com') if id_info['iss'] != 'https://accounts.google.com': raise ValueError('Wrong issuer.') userid = id_info['sub'] Once you obtain user information, you should follow authentication process as described in Authenticate the user section.
answers question: http://stackoverflow.com/q/51350506
type: Answer
accepted answer of: http://stackoverflow.com/q/51350506
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/89701415
type: AcceptedAnswer

http://stackoverflow.com/comment/89825763
score: 0
type: Comment
type: QuestionComment
has text: You can skip the rest of the loop iteration if `a + b > 100` (assuming c > 0) or if `a + b < 100 + max(c)`. You can also replace the last iteration with `(100 - a - b) in c`, and make `c` a set to reduce from n^3 to n^2 runtime
comment on: http://stackoverflow.com/q/51426623

http://stackoverflow.com/q/51455594
downvote count: 0
has comment: http://stackoverflow.com/comment/89880871
has title: How to do log with 0 values in pandas dataframe
has comment: http://stackoverflow.com/comment/89880869
has comment: http://stackoverflow.com/comment/89880627
has body: How can I apply numpy log function to a panda dataframe that has 0 values in it? This is an example of the series inside the dataframe I want to transform df = pd.DataFrame({'CoapplicantIncome': [0, 1508.0, 0, 2358.0, 0], 'ApplicantIncome': [5849, 4583, 3000, 2583, 6000]}) ApplicantIncome CoapplicantIncome 0 5849 0.0 1 4583 1508.0 2 3000 0.0 3 2583 2358.0 4 6000 0.0 I tried to use df['CoapplicantIncome'] = np.log(df['CoapplicantIncome']) but it says 'cannot convert float NaN to integer' After I do some searching, I've come to this line of code that says it will handle the 0 values. df['CoapplicantIncome'] = np.log(df['CoapplicantIncome'].replace(0, np.nan)) But it still says 'cannot convert float NaN to integer'. So how can I solve this? Interestingly, if I build this dataframe from scratch using pd.DataFramethe problem does not occur, but if I read the dataframe from a csv file, then the problem occur.
tagged with: pandas
answer count: 1
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89880647
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/89880793
tagged with: python
has comment: http://stackoverflow.com/comment/89880779
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/51455820
has comment: http://stackoverflow.com/comment/89880997

http://stackoverflow.com/comment/89825849
has text: Yes, but that is irrelevant. The methods exist on the *class* so even if the object were not full constructed you could still use a method on them.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51425488

http://stackoverflow.com/a/51357635
has body: You can chain startswith and endswith masks or use contains - ^ is for match start of string, .* is for any string and $ for end: mask = data['Safe'].str.startswith("CDS") &amp; data['Safe'].str.endswith("DEFAULT-UNIX-ROOT") Or regex: mask = data['Safe'].str.contains("^CDS-.*DEFAULT-UNIX-ROOT$") Sample: data = pd.DataFrame({'Safe':['CDS-DEFAULT-UNIX-ROOT', 'CDS-NhjghOI-DEFAULT-UNIX-ROOT', 'CDS-NhjghOI-DEFAULT', 'ACDS-DEFAULT-UNIX-ROOT']}) print (data) Safe 0 CDS-DEFAULT-UNIX-ROOT 1 CDS-NhjghOI-DEFAULT-UNIX-ROOT 2 CDS-NhjghOI-DEFAULT 3 ACDS-DEFAULT-UNIX-ROOT mask = data['Safe'].str.contains("^CDS-.*DEFAULT-UNIX-ROOT$") print (mask) 0 True 1 True 2 False 3 False Name: Safe, dtype: bool
accepted answer of: http://stackoverflow.com/q/51357562
answers question: http://stackoverflow.com/q/51357562
score: 9
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89691521
type: Answer
upvote count: 9
downvote count: 0

http://stackoverflow.com/a/68230740
has comment: http://stackoverflow.com/comment/120599803
has body: import nltk from nltk.tokenize import sent_tokenize from nltk.stem import PorterStemmer sentence = """At eight o'clock on Thursday morning, Arthur didn't feel very good. So i take him to hospital.""" sentence = sentence.lower() word_tokens = nltk.word_tokenize(sentence) sent_tokens = sent_tokenize(sentence) stemmer = PorterStemmer() stemmed_word = [] stemmed_sent = [] for token in word_tokens: stemmed_word.append(stemmer.stem(token)) for sent_token in sent_tokens: stemmed_sent.append(stemmer.stem(sent_token)) print(stemmed_word) print(stemmed_sent)
type: Answer
score: -1
downvote count: 1
upvote count: 0
has comment: http://stackoverflow.com/comment/120589785
answers question: http://stackoverflow.com/q/51330099

http://stackoverflow.com/q/51337430
has title: Why is index giving a completely wrong output?
type: Question
has comment: http://stackoverflow.com/comment/89649589
has comment: http://stackoverflow.com/comment/89649475
tagged with: python
has comment: http://stackoverflow.com/comment/89649568
has comment: http://stackoverflow.com/comment/89649552
possible better answer: http://stackoverflow.com/a/51337546
tagged with: list
has answer: http://stackoverflow.com/a/51337546
score: 0
answer count: 2
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/51337621
tagged with: indexing
has comment: http://stackoverflow.com/comment/89649537
has comment: http://stackoverflow.com/comment/89649484
has body: Normally I use index to find the index of an element in a list. I made this really basic program but it's not showing the output as I expected. This is my code: store_1 = [] for i in range(8): mountain_height = int(input()) store_1.append(mountain_height) print(store_1.index(store_1[-1])) Result: 0 [0] Index: 0 0 [0, 0] Index: 0 0 [0, 0, 0] Index: 0 0 [0, 0, 0, 0] Index: 0 6 [0, 0, 0, 0, 6] Index: 4 5 [0, 0, 0, 0, 6, 5] Index: 5 2 [0, 0, 0, 0, 6, 5, 2] Index: 6 4 [0, 0, 0, 0, 6, 5, 2, 4] Index: 7 As you can see the element 1, element 2 and element 3 are giving the wrong index, it's indexes should be 1, 2, 3. I am trying to get the index of the very last element added in the list. Why is this happening and how can i solve this problem?
accepted answer: http://stackoverflow.com/a/51337621
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89649593
has comment: http://stackoverflow.com/comment/89649465
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/89894193
has text: Read [this](https://stackoverflow.com/questions/48304317/how-do-implicit-relative-imports-work-in-python) SO post and [PEP 328](https://www.python.org/dev/peps/pep-0328/).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51462596
score: 0

flask
tags question: http://stackoverflow.com/q/51351469
tags question: http://stackoverflow.com/q/51379705
tags question: http://stackoverflow.com/q/51403532
tags question: http://stackoverflow.com/q/51404129
tags question: http://stackoverflow.com/q/51371759
tags question: http://stackoverflow.com/q/51392243
tags question: http://stackoverflow.com/q/51467036
tags question: http://stackoverflow.com/q/51325774
tags question: http://stackoverflow.com/q/51468046
tags question: http://stackoverflow.com/q/51479198
tags question: http://stackoverflow.com/q/51472680
tags question: http://stackoverflow.com/q/51338206
tags question: http://stackoverflow.com/q/51429593
tags question: http://stackoverflow.com/q/51477004
tags question: http://stackoverflow.com/q/51336349
tags question: http://stackoverflow.com/q/51348028
tags question: http://stackoverflow.com/q/51477800
tags question: http://stackoverflow.com/q/51471599
tags question: http://stackoverflow.com/q/51391867
tags question: http://stackoverflow.com/q/51454964
tags question: http://stackoverflow.com/q/51448741
tags question: http://stackoverflow.com/q/51434190
tags question: http://stackoverflow.com/q/51400048
tags question: http://stackoverflow.com/q/51449302
tags question: http://stackoverflow.com/q/51380749
tags question: http://stackoverflow.com/q/51481105
tags question: http://stackoverflow.com/q/51426767
tags question: http://stackoverflow.com/q/51436112
tags question: http://stackoverflow.com/q/51391407
tags question: http://stackoverflow.com/q/51412396
tags question: http://stackoverflow.com/q/51392232
tags question: http://stackoverflow.com/q/51415879
tags question: http://stackoverflow.com/q/51356287
tags question: http://stackoverflow.com/q/51468834
tags question: http://stackoverflow.com/q/51386742
tags question: http://stackoverflow.com/q/51375888
tags question: http://stackoverflow.com/q/51448734
tags question: http://stackoverflow.com/q/51329811
tags question: http://stackoverflow.com/q/51481755
tags question: http://stackoverflow.com/q/51421239
tags question: http://stackoverflow.com/q/51477961
tags question: http://stackoverflow.com/q/51438715
tags question: http://stackoverflow.com/q/51333442
tags question: http://stackoverflow.com/q/51398355
tags question: http://stackoverflow.com/q/51380417
tags question: http://stackoverflow.com/q/51451768
tags question: http://stackoverflow.com/q/51436382
tags question: http://stackoverflow.com/q/51406743
tags question: http://stackoverflow.com/q/51356402
tags question: http://stackoverflow.com/q/51415865
tags question: http://stackoverflow.com/q/51438283
tags question: http://stackoverflow.com/q/51478869
tags question: http://stackoverflow.com/q/51408025
tags question: http://stackoverflow.com/q/51461102
tags question: http://stackoverflow.com/q/51325583
tags question: http://stackoverflow.com/q/51454176
tags question: http://stackoverflow.com/q/51380752
tags question: http://stackoverflow.com/q/51370889
tags question: http://stackoverflow.com/q/51330473
tags question: http://stackoverflow.com/q/51362902
tags question: http://stackoverflow.com/q/51474159
type: Tag
tags question: http://stackoverflow.com/q/51361412
tags question: http://stackoverflow.com/q/51437205
tags question: http://stackoverflow.com/q/51353549
tags question: http://stackoverflow.com/q/51395250
tags question: http://stackoverflow.com/q/51328747
tags question: http://stackoverflow.com/q/51332848
tags question: http://stackoverflow.com/q/51350198
tags question: http://stackoverflow.com/q/51434711
tags question: http://stackoverflow.com/q/51401455
tags question: http://stackoverflow.com/q/51470200
tags question: http://stackoverflow.com/q/51361990
tags question: http://stackoverflow.com/q/51474661
tags question: http://stackoverflow.com/q/51474011
tags question: http://stackoverflow.com/q/51423240
tags question: http://stackoverflow.com/q/51435649
tags question: http://stackoverflow.com/q/51391065
tags question: http://stackoverflow.com/q/51443011
tags question: http://stackoverflow.com/q/51326940

http://stackoverflow.com/q/51348692
upvote count: 0
type: Question
has comment: http://stackoverflow.com/comment/89669999
has title: Flask - Not found
score: -1
answer count: 2
downvote count: 1
has answer: http://stackoverflow.com/a/51349342
tagged with: flask
favorite count: 0
has body: I've built a small flask app which listens on HTTP POST requests and sends data to MQTT. But I can not get it running on the local network. #!/usr/local/bin/python from flask import Flask, request import paho.mqtt.client as mqtt import paho.mqtt.publish as publish import ssl app = Flask(__name__) @app.run(host = '0.0.0.0', port=5000) @app.route('/mqtt', methods=['GET']) def get_id(): topic = request.args.get('topic') temp = request.args.get('temp') hum = request.args.get('hum') pre = request.args.get('pre') auth = { 'username':"user", 'password':"pw tls = { 'ca_certs':"/etc/ssl/certs/ca-certificates.crt", 'tls_version':ssl.PROTOCOL_TLSv1 } publish.single(topic, payload= temp + " " + hum + " " + pre, hostname="domain", client_id="REST_API", auth=auth, tls=tls, port=8883, protocol=mqtt.MQTTv311) return("OK") if __name__ == '__main__': app.run(debug=True) Query looks like: curl --noproxy -x POST "192.168.2.56:5000/mqtt?topic=simcom7000e1&temp=25&hum=10&pre=99" Error: curl: (6) Could not resolve host: POST 404 Not Found Not Found The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. If I comment out: @app.run(host = '0.0.0.0', port=5000) And run: curl --noproxy -x POST "localhost:5000/mqtt?topic=simcom7000e1&temp=25&hum=10&pre=99" Then it works. To me this is really strange. What could be the issue?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51348870
tagged with: python

http://stackoverflow.com/q/51332411
tagged with: python
accepted answer: http://stackoverflow.com/a/51333575
tagged with: python-3.x
score: 0
has comment: http://stackoverflow.com/comment/89642117
answer count: 1
has comment: http://stackoverflow.com/comment/89644392
has body: In the example problem below, the main program creates a list of random strings of length data_size. Without multi-processing the data is sent directly to Test.iterate() where the class merely adds the string Test- to the beginning of each random string. When run without multiprocessing the code works very well with small values of data_size and large values of data_size. I decided to add a multiprocessing ability to this test problem and broke down the core components of multiprocessing into a class title MultiProc. The member function Multiproc.run_processes() manages all functions in the class. The function assumes that the input list will be divided into x smaller lists depending on how many processes the user wishes to utilize. As a result, the function starts by determining the upper and lower indices for each sub-list relative to the initial list so the code knows which portions to iterate over for each thread. The function then initiates the processes, starts the process, joins the process, extracts the data from Queue, then it re-orders the returned data based on a counter that is passed to the primary function. The MultiProc class works fairly well at small values of data_size, but above a value of ~500, the code never terminates, although I suspect the value will vary from computer to computer depending on memory. However, at some point the multiprocess function stops working and I suspect it has something to do with the way data is returned from multiprocess. Does anyone know what might be causing this problem and how to fix it? from multiprocessing import Process, Queue from itertools import chain import string import random class Test: def __init__(self, array_list): self.array_list = array_list def func(self, names): return 'Test-' + names def iterate(self, upper, lower, counter): output = [self.func(self.array_list[i]) for i in range(lower, upper)] return output, counter class MultiProc: def __init__(self, num_procs, data_array, func): self.num_procs…
tagged with: python-multiprocessing
has answer: http://stackoverflow.com/a/51333575
type: AnsweredQuestion
has title: Python multiprocessing example never terminates when the dataset is too large
type: Question

http://stackoverflow.com/q/51351647
tagged with: list
tagged with: http://stackoverflow.com/tag/json
upvote count: 7
has answer: http://stackoverflow.com/a/54697776
type: Question
has title: Update Sharepoint 2013 using Python3
downvote count: 0
tagged with: sharepoint
has body: I am currently trying to update a Sharepoint 2013 list. This is the module that I am using using to accomplish that task. However, when I run the post task I receive the following error: "b'{"error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"Invalid JSON. A token was not recognized in the JSON content."}}}'" Any idea of what I am doing wrong? def update_item(sharepoint_user, sharepoint_password, ad_domain, site_url, sharepoint_listname): login_user = ad_domain + '\\' + sharepoint_user auth = HttpNtlmAuth(login_user, sharepoint_password) sharepoint_url = site_url + '/_api/web/' sharepoint_contextinfo_url = site_url + '/_api/contextinfo' headers = { 'accept': 'application/json;odata=verbose', 'content-type': 'application/json;odata=verbose', 'odata': 'verbose', 'X-RequestForceAuthentication': 'true' } r = requests.post(sharepoint_contextinfo_url, auth=auth, headers=headers, verify=False) form_digest_value = r.json()['d']['GetContextWebInformation']['FormDigestValue'] item_id = 4991 # This id is one of the Ids returned by the code above api_page = sharepoint_url + "lists/GetByTitle('%s')/items(%d)" % (sharepoint_listname, item_id) update_headers = { "Accept": "application/json; odata=verbose", "Content-Type": "application/json; odata=verbose", "odata": "verbose", "X-RequestForceAuthentication": "true", "X-RequestDigest": form_digest_value, "IF-MATCH": "*", "X-HTTP-Method": "MERGE" } r = requests.post(api_page, {'__metadata': {'type': 'SP.Data.TestListItem'}, 'Title': 'TestUpdated'}, auth=auth, headers=update_headers, verify=False) if r.status_code == 204: print(str('Updated')) else: print(str(r.status_code))
answer count: 1
score: 7
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/89685336
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51325461
has text: This doesn't have anything to do with morphology. You can do this manually super easy just indexing the image with the masks you have. Say you have the connected component labeling of the current frame and previous frame. For each label in the current frame, create a mask for that label, and then mask the previous frame's labeled image with that mask. That should show you the prior label (and probably some zeros) so you can just take the max over that maxed region, and assign it back to the current labeled image at the positions you already have a mask for.
score: 0

http://stackoverflow.com/a/51388564
score: 1
upvote count: 1
has body: The accepted answer is fine, but there is a builtin data structure that is perfect for this task called defaultdict. from collections import defaultdict namecounts = defaultdict(int) print(namecounts) namecounts["Fred"]+=1 print(namecounts) You supply defaultdict a callable, and whenever you search for a key in the dict that is not found, that function is called and set as the corresponding value to the key you looked for. In the above example, you looked for "Fred", which was not found, and therefore int was called with zero arguments returning the identity value of int (zero), which is then incremented to 1 and stored as the value to the key "Fred".
accepted answer of: http://stackoverflow.com/q/51387434
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51387434

http://stackoverflow.com/q/51462905
answer count: 2
has comment: http://stackoverflow.com/comment/89894728
has body: I am learning python.I got this error p1.setFirstName("john") AttributeError: 'User' object has no attribute 'setFirstName' I am not getting where I did mistake.please help me to solve this error.I am lerning setter and getter method.I called the method below but it showing its not attribute.so I am confused what it means. Thank you. User.py import mysql.connector class User: def __init__(self): def setFirstName(self,new_firstname): self._FirstName = new_firstname def setLastName(self,new_lastname): self._LastName = new_lastname def setBirthdate(self,new_birthdate): self._Birthdate = new_birthdate def setMartialStatus(self,new_martialstatus): self._MartialStatus = new_martialstatus def setGender(self,new_gender): self._Gender = new_gender def setHeight(self,new_height): self._Height = new_height def setValidIdType(self,new_valididtype): self._ValidIdType = new_valididtype def setValidIdNumber(self,new_valididnumber): self._ValidIdNumber = new_valididnumber def setNationality(self,new_nationality): self._Nationality = new_nationality def getFirstName(): return self._FirstName def getLastName(): return self._LastName def getBirthdate(): return self._Birthdate def getMartialStatus(): return self._MartialStatus def getGender(): return self._Gender def getHeight(): return self._Height def getValidIdType(): return self._ValidIdType def getValidIdNumber(): return self._ValidIdNumber def getNationality(): return self._Nationality p1=User() p1.setFirstName("john") p1.setLastName("abrahum") p1.setBirthdate("1/1/1996") p1.setMartialStatus("married") p1.setGender("male") p1.setHeight("5ft2inhces") p1.setValidIdType("pancard") p1.setValidIdNumber("123456") p1.setNationality("Indian") name=p1.getFirstName() print(name)
has comment: http://stackoverflow.com/comment/89894729
favorite count: 0
has answer: http://stackoverflow.com/a/51462956
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/6618002
has answer: http://stackoverflow.com/a/51463001
tagged with: python
has title: AttributeError: 'User' object has no attribute 'setFirstName'
score: -1
downvote count: 2
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89894908

http://stackoverflow.com/a/51425876
upvote count: 3
type: Answer
has body: check with the regular float type instead of numpy. Test results below w = isinstance(n, float) # True x = isinstance(n, np.float32) # False y = isinstance(n, np.float64) # False z = type(n) == float # True
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/51425733

http://stackoverflow.com/comment/89870756
has text: Regardless of whether if this solution is optimized in terms of runtime or not you should know that recursive function will cost you a lot of memory which means it's not memory efficient. So if that's an issue by OP your fight is literally meaningless.
type: AnswerComment
comment on: http://stackoverflow.com/a/51449388
type: Comment
score: 0

http://stackoverflow.com/a/66240658
upvote count: 5
score: 3
has body: The current official documentation states the following: This has any [sic] effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g. Dropout, BatchNorm, etc.
downvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/51433378

http://stackoverflow.com/q/51370531
has body: I am working in monitoring team, we do monitor of our client load on our tools. We recorded latency with respective to timeseries. Initially, I kept a static threshold to raise the anomaly detection. However, it doesn't work if seasonality occurs. Now, I am planning to apply ML on my data. My data looks like: volume_nfs_ops timestamp mount_point --------------------------------------------------------- 2103 6/28/2018 3:16 /slowfs/us01dwt2p311 12440 6/28/2018 6:03 /slowfs/us01dwt2p311 14501 6/28/2018 14:20 /slowfs/us01dwt2p311 12482 6/28/2018 14:45 /slowfs/us01dwt2p311 10420 6/28/2018 18:09 /slowfs/us01dwt2p311 7203 6/28/2018 18:34 /slowfs/us01dwt2p311 14104 6/28/2018 21:58 /slowfs/us01dwt2p311 6996 6/29/2018 7:35 /slowfs/us01dwt2p311 11282 6/29/2018 8:39 /slowfs/us01dwt2p311 When I do google, I came up ARIMA is the best model for time series. I am towards mathematics and could figure whether respective ARIMA is good for my data set. My question is which algorithm is best to implement in Python? Which factors should I consider to find an anomaly?
has answer: http://stackoverflow.com/a/51670427
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89714017
favorite count: 0
type: UnansweredQuestion
tagged with: arima
tagged with: python
has title: which algorithm is suited for my time series data?
has comment: http://stackoverflow.com/comment/89713666
downvote count: 3
score: -3
tagged with: anomaly-detection
tagged with: machine-learning
type: Question
tagged with: time-series

scikit-learn
tags question: http://stackoverflow.com/q/51387915
tags question: http://stackoverflow.com/q/51444758
tags question: http://stackoverflow.com/q/51420917
tags question: http://stackoverflow.com/q/51388624
tags question: http://stackoverflow.com/q/51327856
tags question: http://stackoverflow.com/q/51406913
tags question: http://stackoverflow.com/q/51377889
tags question: http://stackoverflow.com/q/51359476
tags question: http://stackoverflow.com/q/51326704
tags question: http://stackoverflow.com/q/51331053
tags question: http://stackoverflow.com/q/51404590
tags question: http://stackoverflow.com/q/51417007
tags question: http://stackoverflow.com/q/51381713
tags question: http://stackoverflow.com/q/51397611
tags question: http://stackoverflow.com/q/51479023
tags question: http://stackoverflow.com/q/51465682
tags question: http://stackoverflow.com/q/51346750
tags question: http://stackoverflow.com/q/51419541
tags question: http://stackoverflow.com/q/51330948
tags question: http://stackoverflow.com/q/51449039
tags question: http://stackoverflow.com/q/51444630
tags question: http://stackoverflow.com/q/51413355
tags question: http://stackoverflow.com/q/51480776
tags question: http://stackoverflow.com/q/51397827
tags question: http://stackoverflow.com/q/51424312
tags question: http://stackoverflow.com/q/51462538
tags question: http://stackoverflow.com/q/51388711
tags question: http://stackoverflow.com/q/51328208
tags question: http://stackoverflow.com/q/51350585
tags question: http://stackoverflow.com/q/51342369
tags question: http://stackoverflow.com/q/51383297
tags question: http://stackoverflow.com/q/51418079
tags question: http://stackoverflow.com/q/51380812
tags question: http://stackoverflow.com/q/51467350
tags question: http://stackoverflow.com/q/51420032
tags question: http://stackoverflow.com/q/51397109
tags question: http://stackoverflow.com/q/51371356
tags question: http://stackoverflow.com/q/51452031
tags question: http://stackoverflow.com/q/51378105
tags question: http://stackoverflow.com/q/51368416
tags question: http://stackoverflow.com/q/51353593
tags question: http://stackoverflow.com/q/51347933
tag name: scikit-learn
tags question: http://stackoverflow.com/q/51335889
tags question: http://stackoverflow.com/q/51454759
tags question: http://stackoverflow.com/q/51371427
tags question: http://stackoverflow.com/q/51430094
tags question: http://stackoverflow.com/q/51402663
tags question: http://stackoverflow.com/q/51392603
tags question: http://stackoverflow.com/q/51451435
tags question: http://stackoverflow.com/q/51428133
tags question: http://stackoverflow.com/q/51407749
tags question: http://stackoverflow.com/q/51407521
tags question: http://stackoverflow.com/q/51430484
tags question: http://stackoverflow.com/q/51341128
tags question: http://stackoverflow.com/q/51337806
type: Tag
tags question: http://stackoverflow.com/q/51457942
tags question: http://stackoverflow.com/q/51429975
tags question: http://stackoverflow.com/q/51472097
tags question: http://stackoverflow.com/q/51359623
tags question: http://stackoverflow.com/q/51369709
tags question: http://stackoverflow.com/q/51327541
tags question: http://stackoverflow.com/q/51368026
tags question: http://stackoverflow.com/q/51364165
tags question: http://stackoverflow.com/q/51365607
tags question: http://stackoverflow.com/q/51456932
tags question: http://stackoverflow.com/q/51470179
tags question: http://stackoverflow.com/q/51465665
tags question: http://stackoverflow.com/q/51480706
tags question: http://stackoverflow.com/q/51367877
tags question: http://stackoverflow.com/q/51434567
tags question: http://stackoverflow.com/q/51346827
tags question: http://stackoverflow.com/q/51435800
tags question: http://stackoverflow.com/q/51459406
tags question: http://stackoverflow.com/q/51418113
tags question: http://stackoverflow.com/q/51382250
tags question: http://stackoverflow.com/q/51453326
tags question: http://stackoverflow.com/q/51423494
tags question: http://stackoverflow.com/q/51372534

http://stackoverflow.com/q/51331994
type: Question
tagged with: mongodb
has comment: http://stackoverflow.com/comment/89643475
score: 0
tagged with: linux
has title: How to fetch data from Elastic Database periodically using python?
has body: I need to fetch data from Elastic database every 4 minutes, but I am facing problems in how to modify the @timestamp variable in the below mentioned query so as I can push the appropriate query to fetch the data from the URL. I am using Python as the language. Curl: curl -XGET "URL" -H 'Content-Type: application/json' -k -u u_name:XXX -d' { "query": { "query_string": { "query": "@timestamp:[2018-06-29T06:47:40.000Z TO *]" } }, "size": 1000 } '|json_pp ) I can use CRON to run the script scheduled every 7 minutes, but I can't understand how can I modify the @timestamp variable in the above query so as I can get every new data since the last run. Any inputs are valuable.
answer count: 1
tagged with: python
type: UnansweredQuestion
tagged with: timestamp
has answer: http://stackoverflow.com/a/51334336
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/89838168
type: Comment
comment on: http://stackoverflow.com/a/51403566
score: 0
type: AnswerComment
has text: How to do that ? is there any such option avl ? i am new to this forum , have no idea ..

http://stackoverflow.com/comment/89815004
comment on: http://stackoverflow.com/q/51422099
type: Comment
type: QuestionComment
has text: `rply_tweet` is *not* a list of twwets, it will have the *latest* tweet, since you constantly overwrite it.
score: 1

http://stackoverflow.com/comment/89634848
comment on: http://stackoverflow.com/a/51327617
score: 1
type: AnswerComment
type: Comment
has text: Yeah, my calculation method was definitely horrible, but I didn't even spot the indentation problem. Again thanks a lot.

http://stackoverflow.com/q/51337944
score: 3
answer count: 1
tagged with: python
favorite count: 0
type: UnansweredQuestion
has title: tf.data.Dataset performance with tf.keras
has body: I am playing with multilabel text classification using tf.keras (tensorflow version 1.9.0). I have a dataset consisting of 185485 train and 46372 validation examples. For the first try (on CPU), I pre-padded the data and fed it to the model: from tensorflow import keras .... X_train = keras.preprocessing.sequence.pad_sequences(X_train, maxlen=2000) inp = keras.Input(shape=(X_train.shape[1], )) x = keras.layers.Embedding(len(tk.word_index) + 1, 256, mask_zero=True)(inp) x = keras.layers.LSTM(128, return_sequences=False)(x) x = keras.layers.Dropout(0.1)(x) x = keras.layers.Dense(y_train.shape[1], activation="sigmoid")(x) model = keras.Model(inputs=inp, outputs=x) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(X_train, y_train, batch_size=128, epochs=300, validation_split=0.2) The model takes ~130 minutes per epoch to train. I then try to do the same with Dataset. Since my data is large, I can't fit in 2GB limit to use Dataset.from_tensor_slices(), and I use Dataset.from_generator() instead X_train = keras.preprocessing.sequence.pad_sequences(X_train, maxlen=2000) X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=777, stratify=y_train) def gen(data, labels): for x, y in zip(data, labels): yield x, y train_dataset = tf.data.Dataset.from_generator( lambda: gen(X_train, y_train), output_types=(tf.int32, tf.int32), output_shapes=([2000], [y_train.shape[1]]), ) train_dataset = train_dataset.batch(128) train_dataset = train_dataset.repeat() val_dataset = ... .... model.fit(train_dataset, epochs=300, steps_per_epoch=len(X_train)//128, validation_data=val_dataset, validation_steps=len(X_val)//128) I expected the performance to be roughly the same, which is not the case, since one epoch took ~280 minutes to train. What am I missing? How do I achieve the same performance using the Dataset input?
upvote count: 3
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/51341908
downvote count: 0
tagged with: keras
tagged with: tensorflow-datasets

http://stackoverflow.com/q/51343544
tagged with: qdockwidget
has body: I have a QDockWidget in a QMainWindow, the QDockWidget contains a stack of QUndoViews containing commands that I want to change the text of in the QUndoView. You accomplish this by doing command.setText(). However, the QUndoView is only showing the updated text when I hover over it with the mouse. Not even will calling the below right after setText work: self.editor().undoView().setFocus() self.editor().undoView().update() self.editor().undoView().hide() self.editor().undoView().show() Here is the minimal code to demonstrate the problem: from PyQt5.QtWidgets import (QMainWindow, QDockWidget, QPushButton, QLabel, \ QStackedWidget, QUndoStack, QUndoCommand, QApplication, \ QUndoView) import sys from PyQt5.QtCore import QObject, pyqtSignal, Qt class Command(QUndoCommand): def __init__(self): super().__init__() def undo(self): print("Command Undone") def redo(self): print("Command Redone") class CommandTimeline(QDockWidget): def __init__(self): super().__init__() self.stackedWidget = QStackedWidget() self.setWidget(self.stackedWidget) def addUndoView(self, stack): view = QUndoView(stack) self.stackedWidget.addWidget(view) return view class Obj(QObject): nameChanged = pyqtSignal(str) def __init__(self, name): super().__init__() self._name = name def setName(self, name): self._name = name self.nameChanged.emit(name) def __str__(self): return self._name class MainWindow(QMainWindow): def __init__(self): super().__init__() self.undoStack = QUndoStack() self.commandTimeline = CommandTimeline() self.commandTimeline.addUndoView(self.undoStack) self.addDockWidget(Qt.LeftDockWidgetArea, self.commandTimeline) button = QPushButton("Click") self.setCentralWidget(button) button.clicked.connect(self.changeObjName) self.obj = Obj("A") self.addCommand() def addCommand(self): def getText(obj): return "The command text: " + str(obj) command = Command() command.setText(getText(self.obj)) self.obj.nameChanged.connect(lambda name: command.setText(getText(self.obj))) self.undoStack.push(comm…
score: 1
has answer: http://stackoverflow.com/a/51343902
tagged with: pyqt5
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51343902
tagged with: pyqt
answer count: 1
downvote count: 0
favorite count: 0
has title: Update a QDockWidget's subwidgets which already happens naturally upon hovering over with mouse
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/51382936
type: AnsweredQuestion
tagged with: network-programming
has comment: http://stackoverflow.com/comment/89744328
accepted answer: http://stackoverflow.com/a/51386374
answer count: 2
has comment: http://stackoverflow.com/comment/89743737
tagged with: udp
has body: I am trying to read packets in a router, like this in python: # (skipping the exception handling code here) s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003)) while True: p = s.recvfrom(2000) pkt = p[0] # process pkt here ... Answers to a related question (36115971) say that parameters and methods for UDP vs TCP data are different (some say recv is for TCP and recvfrom is for UDP, and others say the opposite, similarly some say 1024 as buffer size for TCP and larger for UDP, and again some say the reverse). In my case of reading in a router, I do not have different sockets for TCP and UDP, so I need to read both from the same socket, so I am bit confused regarding how I should read the incoming packets. (1) Should I use recv() or recvfrom(), if I want to read both TCP and UDP packets? (2) Do the calls return data one packet at a time, or do they return after the buffer is filled up? eg, if I have a large buffer of 4096 bytes, and the incoming streaming 2 packets have 2400 bytes each, will the call return as soon as the 1st packet ends, or will it return after filling up the buffer from the 2nd packet also? (2a) same question, but if I have a smaller buffer of 2000 bytes. It is clear that on the 1st call I will get the first 2000 bytes of the 1st packet. But on the next call, will I get the last 400 bytes of the 1st packet, or the first 2000 bytes of the 2nd packet? (3) If I am delayed in making the next call, maybe because I was busy processing the 1st dataset, am I in danger of losing data, or will the OS keep its internal queue of the incoming packets to be given to me when I call the next time? If the OS keeps its internal queue, where can I find information about its size? NOTE: Some of the given replies have been divergent, so let me put in some boundaries to my question. Hopefully these restrictions will help to give more specific answers. (a) My objective is to sniff the incoming packets with python sockets only. So other solutions inv…
has comment: http://stackoverflow.com/comment/89738597
favorite count: 0
tagged with: sockets
tagged with: python
linked to: http://stackoverflow.com/q/5160980
has title: reading both tcp and udp packets from same socket
has answer: http://stackoverflow.com/a/51383208
linked to: http://stackoverflow.com/q/36115971
upvote count: 2
has comment: http://stackoverflow.com/comment/89744618
has answer: http://stackoverflow.com/a/51386374
score: 1
tagged with: tcp
possible better answer: http://stackoverflow.com/a/51383208
downvote count: 1
type: Question

http://stackoverflow.com/comment/89756697
comment on: http://stackoverflow.com/q/51392270
score: 0
has text: Could you post the entire source, or at a minimum a [Minimum Verifiable Code Example](https://stackoverflow.com/help/mcve). Doing so will allow readers here to exactly duplicate the issue you're having, making it much easier for it to be solved.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51392819
type: Answer
score: 3
downvote count: 0
has body: Firstly, You should not write in range(0,5) if you want to iterate through n numbers. Secondly, You do not need to write another while function. You use for loop or while loop for this question. Change for i in range(0,5): while i &lt; 5: print(i ** 2) i += 1 break to for i in range(0,n): print(i ** 2)
has comment: http://stackoverflow.com/comment/89757523
answers question: http://stackoverflow.com/q/51392779
upvote count: 3
has comment: http://stackoverflow.com/comment/89757496
accepted answer of: http://stackoverflow.com/q/51392779
type: AcceptedAnswer

http://stackoverflow.com/comment/89733619
score: 0
type: Comment
type: QuestionComment
has text: Please show what you have already tried. You can read the file by lines and then use split
comment on: http://stackoverflow.com/q/51380949

http://stackoverflow.com/q/51369226
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89710852
type: Question
score: 3
has body: I have a pandas DataFrame that looks something like this: n=pd.DataFrame({1:[1,2,np.NAN,4],2:[5,6,5,8],'info':[5,6,8,7],'moreinfo':[1,2,5,8]}).set_index(['info','moreinfo']) Which looks like this: 1 2 info moreinfo 5 1 1.0 5 6 2 2.0 6 8 5 NaN 5 7 8 4.0 8 How can I line plot this such that: The column labels are used as the xlabels The data is grouped and colored by index The y-axis is the numerical data found within each column. Below is an example of what I'm thinking the plot should look like:
has title: Pandas plotting with multiple index labels
upvote count: 3
has comment: http://stackoverflow.com/comment/89710856
accepted answer: http://stackoverflow.com/a/51369805
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51369805

tensorflow
tags question: http://stackoverflow.com/q/51438511
tags question: http://stackoverflow.com/q/51470332
tags question: http://stackoverflow.com/q/51357223
tags question: http://stackoverflow.com/q/51449236
tags question: http://stackoverflow.com/q/51395855
tags question: http://stackoverflow.com/q/51344694
tags question: http://stackoverflow.com/q/51473224
tags question: http://stackoverflow.com/q/51372223
tags question: http://stackoverflow.com/q/51341613
tags question: http://stackoverflow.com/q/51342528
tags question: http://stackoverflow.com/q/51380832
tags question: http://stackoverflow.com/q/51337939
tags question: http://stackoverflow.com/q/51422833
tags question: http://stackoverflow.com/q/51335371
tags question: http://stackoverflow.com/q/51337944
tags question: http://stackoverflow.com/q/51364077
tags question: http://stackoverflow.com/q/51357584
tags question: http://stackoverflow.com/q/51434792
tags question: http://stackoverflow.com/q/51414808
tags question: http://stackoverflow.com/q/51435117
tags question: http://stackoverflow.com/q/51387063
tags question: http://stackoverflow.com/q/51366031
tags question: http://stackoverflow.com/q/51471168
tags question: http://stackoverflow.com/q/51406104
tags question: http://stackoverflow.com/q/51356524
tags question: http://stackoverflow.com/q/51406206
tags question: http://stackoverflow.com/q/51379506
tags question: http://stackoverflow.com/q/51393213
tags question: http://stackoverflow.com/q/51390692
tags question: http://stackoverflow.com/q/51430062
tags question: http://stackoverflow.com/q/51331474
tags question: http://stackoverflow.com/q/51475082
tags question: http://stackoverflow.com/q/51341092
tags question: http://stackoverflow.com/q/51333501
tags question: http://stackoverflow.com/q/51473904
tags question: http://stackoverflow.com/q/51336624
tags question: http://stackoverflow.com/q/51465526
tags question: http://stackoverflow.com/q/51346771
tags question: http://stackoverflow.com/q/51402207
tags question: http://stackoverflow.com/q/51436007
tags question: http://stackoverflow.com/q/51420048
tags question: http://stackoverflow.com/q/51443898
tags question: http://stackoverflow.com/q/51328263
tags question: http://stackoverflow.com/q/51327737
tags question: http://stackoverflow.com/q/51417764
tags question: http://stackoverflow.com/q/51333061
tags question: http://stackoverflow.com/q/51448428
tags question: http://stackoverflow.com/q/51395853
tags question: http://stackoverflow.com/q/51425449
tags question: http://stackoverflow.com/q/51473977
tags question: http://stackoverflow.com/q/51353522
tags question: http://stackoverflow.com/q/51325424
tags question: http://stackoverflow.com/q/51348246
tags question: http://stackoverflow.com/q/51366871
tags question: http://stackoverflow.com/q/51402053
tags question: http://stackoverflow.com/q/51476568
tags question: http://stackoverflow.com/q/51421251
tags question: http://stackoverflow.com/q/51361402
tags question: http://stackoverflow.com/q/51345440
tags question: http://stackoverflow.com/q/51370733
tags question: http://stackoverflow.com/q/51371910
tags question: http://stackoverflow.com/q/51473643
tags question: http://stackoverflow.com/q/51440475
tags question: http://stackoverflow.com/q/51432661
tags question: http://stackoverflow.com/q/51396366
tags question: http://stackoverflow.com/q/51342354
tags question: http://stackoverflow.com/q/51411212
tags question: http://stackoverflow.com/q/51472625
tags question: http://stackoverflow.com/q/51341998
tags question: http://stackoverflow.com/q/51350847
tag name: tensorflow
tags question: http://stackoverflow.com/q/51426525
tags question: http://stackoverflow.com/q/51366455
tags question: http://stackoverflow.com/q/51382664
tags question: http://stackoverflow.com/q/51444101
tags question: http://stackoverflow.com/q/51475745
tags question: http://stackoverflow.com/q/51452106
tags question: http://stackoverflow.com/q/51405545
tags question: http://stackoverflow.com/q/51342088
tags question: http://stackoverflow.com/q/51373072

http://stackoverflow.com/q/51384137
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89740253
possible better answer: http://stackoverflow.com/a/51384513
type: Question
has answer: http://stackoverflow.com/a/51384513
answer count: 2
has title: How to convert a pandas Dataframe into a sparse matrix?
has body: I have seen a couple of example here, but none of it was on the point. I have a data like countries: usa uk germany india russia user : aaa bbb ccc ddd eee visit: 50 20 9 30 58 So, I want to convert this df into a sparse martix like below: user aaa bbb ccc ddd eee countries usa 50 0 0 0 0 uk 0 20 0 0 0 germany 0 0 9 0 0 india 0 0 0 30 0 russia 0 0 0 0 58 P.S , there are also cases where there are user visitng multiple countries (for eg. zzz - 5 time russia and 4 time usa) So I have tried multiple approx, but nothing work fine. Any help would be appreciated
has comment: http://stackoverflow.com/comment/89740728
has answer: http://stackoverflow.com/a/51385153
score: 0
accepted answer: http://stackoverflow.com/a/51385153
tagged with: pandas
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/51443725
has comment: http://stackoverflow.com/comment/89857595
tagged with: dataframe
tagged with: loops
has answer: http://stackoverflow.com/a/51444845
type: Question
has answer: http://stackoverflow.com/a/51444061
linked to: http://stackoverflow.com/q/52711358
accepted answer: http://stackoverflow.com/a/51444212
has comment: http://stackoverflow.com/comment/106767118
downvote count: 0
possible better answer: http://stackoverflow.com/a/51444845
has comment: http://stackoverflow.com/comment/89857464
has answer: http://stackoverflow.com/a/51443927
tagged with: pandas
has comment: http://stackoverflow.com/comment/89857759
tagged with: python
has title: Pandas iterate over DataFrame row pairs
answer count: 4
favorite count: 0
score: 8
has body: How can I iterate over pairs of rows of a Pandas DataFrame? For example: content = [(1,2,[1,3]),(3,4,[2,4]),(5,6,[6,9]),(7,8,[9,10])] df = pd.DataFrame( content, columns=["a","b","interval"]) print df output: a b interval 0 1 2 [1, 3] 1 3 4 [2, 4] 2 5 6 [6, 9] 3 7 8 [9, 10] Now I would like to do something like for (indx1,row1), (indx2,row2) in df.? print "row1:\n", row1 print "row2:\n", row2 print "\n" which should output row1: a 1 b 2 interval [1,3] Name: 0, dtype: int64 row2: a 3 b 4 interval [2,4] Name: 1, dtype: int64 row1: a 3 b 4 interval [2,4] Name: 1, dtype: int64 row2: a 5 b 6 interval [6,9] Name: 2, dtype: int64 row1: a 5 b 6 interval [6,9] Name: 2, dtype: int64 row2: a 7 b 8 interval [9,10] Name: 3, dtype: int64 Is there a builtin way to achieve this? I looked at df.groupby(df.index // 2) and df.itertuples but none of these methods seems to do what I want. Edit: The overall goal is to get a list of bools indicating whether the intervals in column "interval" overlap. In the above example the list would be overlaps = [True, False, False] So one bool for each pair.
upvote count: 8
has answer: http://stackoverflow.com/a/51444212
has comment: http://stackoverflow.com/comment/89859073
has comment: http://stackoverflow.com/comment/89857690
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89859293

http://stackoverflow.com/a/51352124
has body: As the PIL error message points out, JPEG does not support transparency. To handle images that use transparency you need to paste them onto a RGB background image. That's what your 2nd option does: Image.new("RGB", img.size, (255, 255, 255)) creates a new image of the same size as img, with all the pixels set to (255, 255, 255), which is white. (You can also use strings to specify colors to PIL). So to do this resizing and conversion task correctly you need to determine whether or not the image has transparency. You do that by checking the Image.mode string. If it's "RGBA", then the image has transparency. Here's a short demo, which uses a medium light grey for the background. I use the pathlib module to create the JPEG file name from the input file name. This module is available in Python 3.4+. Update The original version of this code did not handle palette-mapped images, but this new version does, including palette-mapped images with transparency. def resize_to_jpg(fname, newsize, background): img = Image.open(fname) #img.show() print('Resizing', fname, 'Mode =', img.mode) if img.mode == "P": # Handle palette-mapped images if 'transparency' in img.info: img = img.convert('RGBA') else: img = img.convert('RGB') if img.mode == "RGBA": # The image has transparency out = Image.new("RGB", img.size, background) # Use the image's own alpha channel as the mask out.paste(img, mask=img) else: out = img out = out.resize(newsize, Image.ANTIALIAS) #out.show() # Construct output file name outname = str(PurePath(fname).with_suffix('.jpg')) out.save(outname, quality=90, optimize=True) print(outname, 'saved') newsize = (120, 120) background = (192, 192, 192) files = ( 'RhombicPlain.png', 'RhombicAlpha.png', ) for fname in files: resize_to_jpg(fname, newsize, background) output Resizing RhombicPlain.png Mode = RGB RhombicPlain.jpg saved Resizing RhombicAlpha.png Mode = RGBA RhombicAlpha.jpg saved Here are the input images, RhombicPlain.png and RhombicAlpha.png, which I created using…
has comment: http://stackoverflow.com/comment/89678083
upvote count: 2
has comment: http://stackoverflow.com/comment/89678727
score: 2
answers question: http://stackoverflow.com/q/51349907
accepted answer of: http://stackoverflow.com/q/51349907
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/89926895
has text: It does not matter what name you use
comment on: http://stackoverflow.com/q/51479235
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51395569
favorite count: 0
type: UnansweredQuestion
has title: Exporting test case from selenium IDE 3.1.1.0
tagged with: geckodriver
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/52226266
has body: Can't find how to export test case in selenium IDE 3.1.1.0, so I downloaded the 2.9 version and I changed the Firefox browser from version 5.5 to 5.2. After these steps I was able to export the test case but I can't run it in the Firefox because geckodriver needs Firefox 5.5. The question is can I export somehow the test case from selenium IDE 3.1.1.0?
type: Question
linked to: http://stackoverflow.com/q/51106564
tagged with: firefox
tagged with: selenium-firefoxdriver
upvote count: 1
answer count: 1
tagged with: python

http://stackoverflow.com/q/51334487
has comment: http://stackoverflow.com/comment/89652085
type: Question
has answer: http://stackoverflow.com/a/51348897
has title: Django deploying on MySQL gives #1071 error "Specified key was too long"
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89645292
tagged with: django
tagged with: python
has body: I have been trying this problem for a very long time. But I just cannot seem to find the solution. I am trying to deploy my project on pythonanywhere, where I have chosen MySQL. Whenever I try to migrate my models with python manage.py migrate. I get the following error: This is my models. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Thing(models.Model): thing_name = models.CharField(max_length=64, unique=True) def __str__(self): return self.hobby_name class Person(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, ) first_name = models.CharField(max_length=64, null=True, blank=False) last_name = models.CharField(max_length=64, null=True, blank=False) hobbies = models.ManyToManyField(Hobby, blank=False) email = models.EmailField(max_length=64, blank=True, null=True, unique=True) city = models.CharField(max_length=64, null=True, blank=False) zip_code = models.CharField(max_length=10, null=True, blank=False) description = models.TextField(max_length=2048, null=True, blank=True) gender = models.CharField(max_length=1, choices=( ('N', 'No answer'), ('M', 'Male'), ('F', 'Female'), ('O', 'Other') ), null=True, blank=True, default="N" ) bad = models.BooleanField(default=False) good = models.BooleanField(default=True) maximum_hours = models.PositiveIntegerField(default=2) def __str__(self): try: string = self.first_name + " " + self.last_name except: string = "name_error" return string Last note is that I have DROPPED and re-CREATED the database several times. Each time by: CREATE DATABASE database_name DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci; I am deploying all of this to Pythonanywhere. The model Thing actually becomes a table. But the model Person does not. Edit: Here is the full traceback (hobbyin) 01:16 ~/hobbyin (master)$ python manage.py migrate System check identified some issues: WARNINGS: ?: (mysql.W002) MySQL Strict Mode is not set for database conne…
tagged with: pythonanywhere
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51348897
has comment: http://stackoverflow.com/comment/89649381
has comment: http://stackoverflow.com/comment/89652079
has comment: http://stackoverflow.com/comment/89650443
tagged with: mysql
has comment: http://stackoverflow.com/comment/89650418

http://stackoverflow.com/q/51433378
tagged with: python
score: 236
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51433411
downvote count: 1
has comment: http://stackoverflow.com/comment/124068330
type: Question
has comment: http://stackoverflow.com/comment/123076535
has comment: http://stackoverflow.com/comment/124471031
has answer: http://stackoverflow.com/a/68115545
linked to: http://stackoverflow.com/q/60018578
answer count: 6
has title: What does model.train() do in PyTorch?
tagged with: deep-learning
has answer: http://stackoverflow.com/a/66240658
upvote count: 237
has answer: http://stackoverflow.com/a/51596850
has answer: http://stackoverflow.com/a/51433411
has answer: http://stackoverflow.com/a/66526891
linked to: http://stackoverflow.com/q/66534762
possible better answer: http://stackoverflow.com/a/56828547
favorite count: 0
has body: Does it call forward() in nn.Module? I thought when we call the model, forward method is being used. Why do we need to specify train()?
has answer: http://stackoverflow.com/a/56828547
tagged with: pytorch
tagged with: machine-learning

http://stackoverflow.com/comment/89786704
score: 0
comment on: http://stackoverflow.com/q/51407524
has text: @xyzjayne No, the DataFrame if I print df.loc[i] it returns the dataframe for that specific index. And everything is correct.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51336291
upvote count: 5
has body: You can use the following statement: return t[0] if val == 'y' else t[1] You can also index into a tuple: return t[val == 'n']
has comment: http://stackoverflow.com/comment/89647471
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51336271
has comment: http://stackoverflow.com/comment/89647480
answers question: http://stackoverflow.com/q/51336271
type: Answer
score: 5

http://stackoverflow.com/q/51342408
has answer: http://stackoverflow.com/a/51343539
tagged with: jupyter-notebook
favorite count: 0
answer count: 6
tagged with: setup.py
type: Question
upvote count: 181
has answer: http://stackoverflow.com/a/66985666
tagged with: pip
tagged with: python
has answer: http://stackoverflow.com/a/61212861
has answer: http://stackoverflow.com/a/51342586
score: 181
has answer: http://stackoverflow.com/a/55125270
type: UnansweredQuestion
tagged with: google-colaboratory
has title: How do I install Python packages in Google's Colab?
has answer: http://stackoverflow.com/a/58643445
has body: In a project, I have e.g. two different packages, How can I use the setup.py to install these two packages in the Google's Colab, so that I can import the packages?
downvote count: 0

http://stackoverflow.com/q/51454628
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/17921010
downvote count: 0
score: 1
favorite count: 0
duplicate of: http://stackoverflow.com/q/17921010
type: Question
upvote count: 1
tagged with: python
has body: I can print my data frame and see label TSLA but I don't know how to get that string from my variable... &gt;&gt;&gt; t.axes [MultiIndex(levels=[['TSLA'], [2018-07-02 00:00:00, 2018-07-03 00:00:00, 2018-07 -04 00:00:00, 2018-07-05 00:00:00, 2018-07-06 00:00:00, 2018-07-09 00:00:00, 201 8-07-10 00:00:00, 2018-07-11 00:00:00, 2018-07-12 00:00:00, 2018-07-13 00:00:00, 2018-07-16 00:00:00, 2018-07-17 00:00:00, 2018-07-18 00:00:00, 2018-07-19 00:00 :00, 2018-07-20 00:00:00]], labels=[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 2, 3, 4 , 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]], names=['Symbol', 'Date']), Index(['Close', 'High', 'Low', 'Open', 'Vo lume'], dtype='object')] &gt;&gt;&gt;
has comment: http://stackoverflow.com/comment/89878878
has answer: http://stackoverflow.com/a/51454756
answer count: 1
accepted answer: http://stackoverflow.com/a/51454756
has title: get symbol from a pandas dataframe
tagged with: pandas

http://stackoverflow.com/a/51355481
upvote count: 1
has comment: http://stackoverflow.com/comment/89683880
has comment: http://stackoverflow.com/comment/89683587
has comment: http://stackoverflow.com/comment/89683581
has comment: http://stackoverflow.com/comment/89684689
type: Answer
answers question: http://stackoverflow.com/q/51355369
downvote count: 0
has body: This is an optimised version for your data. from itertools import chain v = df.pop('ALT_NAMES').str.split('@') df = pd.DataFrame( df.values.repeat(v.str.len(), axis=0), columns=df.columns) df['ALT_NAMES'] = list(chain.from_iterable(v)) df STATE CITY ALT_NAMES 0 S1 C1 A1 1 S1 C1 A2 2 S2 C2 A3 3 S2 C2 A4 4 S2 C2 A5
score: 1
has comment: http://stackoverflow.com/comment/89683603
has comment: http://stackoverflow.com/comment/89684169

http://stackoverflow.com/q/51411438
upvote count: 0
has answer: http://stackoverflow.com/a/51411778
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
score: -1
tagged with: list
has comment: http://stackoverflow.com/comment/89796903
has title: Trying to print the second largest number in list
downvote count: 1
type: Question
has body: x = input() y = map(int, input().split()) score = list(y) score2 = score.remove(max(score)) print(max(score2)) When I execute the above code with inputs x = 4 and y = 1 2 3 4, it shows an error message 'NoneType value is not iterable'. The last but previous line 'score2 = score.remove(max(score))' returns a None value. Why does this happen? I intend to create code which fetches the second largest number in the list
has answer: http://stackoverflow.com/a/51411465
has comment: http://stackoverflow.com/comment/89795486
answer count: 2

http://stackoverflow.com/comment/89900904
type: Comment
type: QuestionComment
has text: You can create a loop in you python file, which check in the file every 1 second, this is a pretty complex idea, it will need planning to execute
comment on: http://stackoverflow.com/q/51465981
score: 0

http://stackoverflow.com/comment/89850662
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51433227
has text: OK! I don't know if this issue is related: https://github.com/has2k1/plotnine/issues/161 (it might?)
score: 0

http://stackoverflow.com/comment/89911725
comment on: http://stackoverflow.com/a/51469764
score: 0
type: AnswerComment
has text: Great, this seems to fix it, even if I set frame limit as 100, global counter increases. There is one switch on top left to kill the animation but then only way to restart is to run the code again. I will be exporting this as html file as reader will not be able to run code, (but can interact with graph i guess), how do we go about avoiding this?
type: Comment

http://stackoverflow.com/q/51331730
answer count: 2
has title: Connect Python app to Redis on Kubernetes cluster
tagged with: redis
accepted answer: http://stackoverflow.com/a/51346188
tagged with: kubernetes
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/72437938
has answer: http://stackoverflow.com/a/72437938
type: Question
has body: A docker container with a small Python app inside it is deployed to a Kubernetes cluster that has a redis master and a redis slave service running in the cluster. The Python app inside the Docker container is not able to connect to the redis across the cluster because the Python app is not configured properly to find redis on the network. What specific changes need to be made to the code below in order for the Python app in app.py to be able to communicate successfully with the redis running in the same cluster? PYTHON APP CODE Here is app.py from flask import Flask from redis import Redis, RedisError import os import socket # Connect to Redis redis = Redis(host="redis", db=0, socket_connect_timeout=2, socket_timeout=2) app = Flask(__name__) @app.route("/") def hello(): try: visits = redis.incr("counter") except RedisError: visits = "cannot connect to Redis, counter disabled" html = " Hello {name}! " \ "Hostname: {hostname} " \ "Visits: {visits}" return html.format(name=os.getenv("NAME", "world"), hostname=socket.gethostname(), visits=visits) if __name__ == "__main__": app.run(host='0.0.0.0', port=80) REDIS SERVICES IN THE SAME KUBERNETES CLUSTER The redis master and redis slave running in the cluster are from public registries and are brought into the cluster by running kubectl apply -f with the following JSON: Redis Master replication controller JSON from this link. Redis Master service JSON from this link. Redis Slave replication controller JSON from this link. Redis Slave service JSON from this link.
has answer: http://stackoverflow.com/a/51346188
tagged with: docker
score: 0

http://stackoverflow.com/q/51481114
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89934025
type: Question
tagged with: function
tagged with: user-interface
tagged with: button
has comment: http://stackoverflow.com/comment/89933108
score: 0
has body: I am trying to make a very simple GUI with tkinter to operate my python script and what I want to do is to read image files from a folder using a button and after that I want to name this image like "image1" to use in my functions. In my script I have decide() and convert to grayscale() functions which take image as input and make something. How can I proceed this algorithm? my GUI script is that I wrote up to now is below. I created 4 buttons. "import image" is to select image file from the folder. "decide" button needs decide(image) argument and I dont know how can I combine these. from tkinter import * from PIL import Image, ImageTk from tkinter import ttk from tkinter import filedialog window = Tk() window.title("Welcome to LikeGeeks app") window.geometry('350x200') def close_window(): window.destroy() def open_image(): pil_image = Image.open(filedialog.askopenfilename()) #in btn1 when I click button a folder is opening and I can chose image file, but I cant do anything that I explaned above. btn1 = Button(window, text="Import Image") btn1.config( height = 2, width = 15,command=open_image) btn1.grid(column=0, row=0) btn2 = Button(window, background = 'white', foreground = 'black', text="exit") btn2.config( height = 2, width = 15, command = close_window) btn2.grid(column=0, row=3) btn3 = Button(window, text=" decide") btn3.config( height = 2, width = 15 , command = quit) btn3.grid(column=0, row=2) btn4 = Button(window, text=" convert gray scale") btn4.config( height = 2, width = 15 ) btn4.grid(column=0, row=1) window.mainloop()
tagged with: python
has title: how can I assign a function to button from anothor python script in tkinter?
tagged with: tkinter
answer count: 0

http://stackoverflow.com/comment/89724503
score: 0
type: Comment
has text: This is an abstracted example of something much longer. Objects may be added in several ways, and what your suggesting may end up getting complicated.
type: AnswerComment
comment on: http://stackoverflow.com/a/51376492

http://stackoverflow.com/q/51333489
linked to: http://stackoverflow.com/q/606191
answer count: 3
tagged with: encoding
has comment: http://stackoverflow.com/comment/89642419
has comment: http://stackoverflow.com/comment/89642388
tagged with: unicode
favorite count: 0
has answer: http://stackoverflow.com/a/51334137
tagged with: pandas
tagged with: python
has body: When I output some Chinese character in Python (Pandas), it shows as below \xe8\xbf\x99\xe7\xa7\x8d\xe6\x83\x85\xe5\x86\xb5\xe6\x98\xaf\xe6\xb2\xb9\xe6\xb3\xb5\xe6\x95\x85\xe9\x9a\x9c\xe7\x81\xaf\xef\xbc\x8c\xe6\xa3\x80\xe6\x9f\xa5\xe4\xb8\x80\xe4\xb8\x8b\xe6\xb2\xb9\xe6\xb3\xb5\xe6\x8f\x92\xe5\xa4\xb4\xe6\x98\xaf\xe5\x90\xa6\xe6\x8e\xa5\xe8\x99\x9a\xef\xbc\x8c\xe7\x84\xb6\xe5\x90\x8e\xe6\x9f\xa5\xe4\xb8\x80\xe4\xb8\x8b\xe6\xb2\xb9\xe6\xb3\xb5\xe5\x86\x85\xe7\xae\xa1\xe9\x81\x93\xe5\x8e\x8b\xe5\x8a\x9b\xe6\x98\xaf\xe5\x90\xa6\xe7\xac\xa6\xe5\x90\x88\xe6\xad\xa3\xe5\xb8\xb8\xe5\x80\xbc\xe3\x80\x82 What is the encoding format? It is not unicode as I know. Thanks!
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51334070
has title: Chinese encoding in Python
has answer: http://stackoverflow.com/a/51340655
has answer: http://stackoverflow.com/a/51334070
upvote count: 1
tagged with: utf
downvote count: 1
has comment: http://stackoverflow.com/comment/89642456
type: Question
has comment: http://stackoverflow.com/comment/89642455
has comment: http://stackoverflow.com/comment/89642415
has comment: http://stackoverflow.com/comment/89643194
has comment: http://stackoverflow.com/comment/89643513
accepted answer: http://stackoverflow.com/a/51340655
score: 0

http://stackoverflow.com/a/51436479
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/122896646
has comment: http://stackoverflow.com/comment/89860316
type: Answer
has comment: http://stackoverflow.com/comment/89860533
has comment: http://stackoverflow.com/comment/138105492
has comment: http://stackoverflow.com/comment/89869760
has comment: http://stackoverflow.com/comment/89862337
has body: asyncio is about organizing non-blocking code into callbacks and coroutines. Running CPU-intensive code in parallel is a use case for threads: from concurrent.futures import ThreadPoolExecutor with ThreadPoolExecutor() as executor: frames = list(executor.map(extract, all_tables)) Whether this will actually run faster than sequential code depends on whether pd.read_sql releases the GIL.
has comment: http://stackoverflow.com/comment/138257051
accepted answer of: http://stackoverflow.com/q/51426533
answers question: http://stackoverflow.com/q/51426533
score: 4
upvote count: 4

nan
tags question: http://stackoverflow.com/q/51383400
tags question: http://stackoverflow.com/q/51426289
tag name: nan
tags question: http://stackoverflow.com/q/51326825
type: Tag
tags question: http://stackoverflow.com/q/51352305
tags question: http://stackoverflow.com/q/51388690
tags question: http://stackoverflow.com/q/51332972
tags question: http://stackoverflow.com/q/51475126
tags question: http://stackoverflow.com/q/51372166

http://stackoverflow.com/q/51401963
upvote count: 1
answer count: 1
favorite count: 0
has body: I am currently using the following to find if a word or words are within a string: stopwords=set(["Good to Soft","Slow","Standard to Slow","Standard","Standard to Fast","Fast","Heavy","Soft to Heavy","Soft","Yeliding to Soft","Yeilding","Good to Yeilding","Good","Good to Firm","Firm","Hard"]) Going = stopwords.intersection(set(testtext[0].split())) My issue is that if the string has Standard To Slow, then the intersection only seems to pick up Standard, Slow - I want Standard To Slow. Is there anyway I can improve this? To explain more clearly what outcome I need i will use the example below: I have a list of goings ["Good to Soft","Slow","Standard to Slow","Standard","Standard to Fast","Fast","Heavy","Soft to Heavy","Soft","Yeliding to Soft","Yeilding","Good to Yeilding","Good","Good to Firm","Firm","Hard"] I want to find which of these going are within my string so for example: 2:20 - H Brown &amp; Son Recycling Maiden Hurdle (Class4) �4,094 Good 2m3f207y This would return "good" as thats the match 2:20 - H Brown &amp; Son Recycling Maiden Hurdle (Class4) �4,094 Good to Soft 2m3f207y This would return "Good to Soft" as thats the match and NOT "Soft"
has comment: http://stackoverflow.com/comment/89844677
tagged with: python
downvote count: 0
has comment: http://stackoverflow.com/comment/89821510
has comment: http://stackoverflow.com/comment/89775255
has comment: http://stackoverflow.com/comment/89792528
has comment: http://stackoverflow.com/comment/89775223
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51402264
has title: Using intersection within Python to find more then 1 word
accepted answer: http://stackoverflow.com/a/51402264
type: Question

http://stackoverflow.com/q/51424439
has comment: http://stackoverflow.com/comment/89819918
has title: Python and a list index error
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51424542
has body: i begin learning Python and i have a problem at my first steps. I have the following code: f=open("C:\$%$%$%$.csv","r") data=f.read() rows = data.split('\n') final_data = [] for row in rows: split_list = row.split(',') final_data.append(split_list) Until now all good. The result is this: [['product_name', 'prod_orders'], ['Banana', '472565'], ['Bag of Organic Bananas', '379450'], ['Organic Strawberries', '264683'], ['Organic Baby Spinach', '241921'], ['Organic Hass Avocado', '213584'], ['Organic Avocado', '176815'], ['Large Lemon', '152657'], ['Strawberries', '142951'], ['Limes', '140627'], ['Organic Whole Milk', '137905'], ['Organic Raspberries', '137057'], ['Organic Yellow Onion', '113426'], ['Organic Garlic', '109778'], ['Organic Zucchini', '104823'], ['Organic Blueberries', '100060'], ['Cucumber Kirby', '97315'], ['Organic Fuji Apple', '89632'], ['Organic Lemon', '87746'], ['Apple Honeycrisp Organic', '85020'], ['Organic Grape Tomatoes', '84255'], ['Seedless Red Grapes', '82689'], ['Organic Cucumber', '80392'], ['Honeycrisp Apple', '79769'], ['Organic Baby Carrots', '76896'], ['Organic Half &amp; Half', '76360'], ['Sparkling Water Grapefruit', '75886'], ['Organic Large Extra Fancy Fuji Apple', '75165'], ['Yellow Onions', '73167'], ['Organic Gala Apples', '72846'], ['Organic Baby Arugula', '72829'], ['Carrots', '72736'], ['Fresh Cauliflower', '71584'], ['Original Hummus', '71314'], ['Organic Cilantro', '69524'], ['Half &amp; Half', '69217'], ['Organic Small Bunch Celery', '68091'], ['Michigan Organic Kale', '67449'], ['Asparagus', '67283'], ['Organic Red Onion', '66986'], ['Organic Tomato Cluster', '64289'], ['Organic Blackberries', '61746'], ['100% Whole Wheat Bread', '60816'], ['Organic Italian Parsley Bunch', '60621'], ['Organic Whole String Cheese', '59676'], ['Organic Granny Smith Apple', '58779'], ['Organic Unsweetened Almond Milk', '57895'], ['Raspberries', '57640'], ['Organic Red Bell Pepper', '57485'], ['Spring Water', '56087'], ['Blueberries', '55946'],…
accepted answer: http://stackoverflow.com/a/51424542
type: Question
tagged with: python
favorite count: 0
score: 0
upvote count: 1
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/89648241
comment on: http://stackoverflow.com/q/51336374
score: 0
type: Comment
type: QuestionComment
has text: It's not clear what you mean by "a utility". Do you mean something you build in to `TestClass`, or some external tool that reads your Python source code and somehow does something with it (either writing out different code, or modifying the source in place)?

http://stackoverflow.com/q/51382499
tagged with: time-series
has body: I have two data frames df1 with two time series and df2 with a set of intervals. I want to join the two data frames preserving the index of df2 while resampling the time series with an aggregate function, let's say max(). df1 Out[1]: Y X timestamp 1900-01-01 00:00:10.679380200 0.581760 -0.282902 1900-01-01 00:00:10.720490500 0.581732 -0.282616 1900-01-01 00:00:10.762100500 0.578835 -0.281211 1900-01-01 00:00:10.801705300 0.547837 -0.277893 1900-01-01 00:00:10.846323700 0.543433 -0.277881 1900-01-01 00:00:10.889450100 0.538701 -0.279481 1900-01-01 00:00:10.894463800 0.538701 -0.279481 1900-01-01 00:00:10.896958800 0.538701 -0.279481 1900-01-01 00:00:10.897973300 0.536122 -0.278382 1900-01-01 00:00:10.924546500 0.536122 -0.278382 1900-01-01 00:00:10.936062400 0.536122 -0.278382 1900-01-01 00:00:10.980179700 0.536171 -0.278402 1900-01-01 00:00:11.021791100 0.541177 -0.279649 1900-01-01 00:00:11.059391200 0.549314 -0.280842 1900-01-01 00:00:11.104509400 0.559103 -0.281571 1900-01-01 00:00:11.147624400 0.569963 -0.282739 1900-01-01 00:00:11.187731700 0.572123 -0.282897 1900-01-01 00:00:11.227337100 0.574026 -0.283083 1900-01-01 00:00:11.268947200 0.574020 -0.283056 And df2 df2 Out[2]: start end 0 1970-01-01 00:00:10.140 1970-01-01 00:00:10.500 1 1970-01-01 00:00:10.700 1970-01-01 00:00:11.180 2 1970-01-01 00:00:11.320 1970-01-01 00:00:11.780 3 1970-01-01 00:00:11.930 1970-01-01 00:00:12.410 4 1970-01-01 00:00:12.500 1970-01-01 00:00:12.900 5 1970-01-01 00:00:13.080 1970-01-01 00:00:13.530 6 1970-01-01 00:00:13.700 1970-01-01 00:00:14.190 7 1970-01-01 00:00:14.310 1970-01-01 00:00:14.810 And the expected result: df3: start end Ymax Xmax 0 1970-01-01 00:00:10.140 1970-01-01 00:00:10.500 1 1970-01-01 00:00:10.700 1970-01-01 00:00:11.180 0.581760 -0.27789 2 1970-01-01 00:00:11.320 1970-01-01 00:00:11.780 ... ... 3 1970-01-01 00:00:11.930 1970-01-01 00:00:12.410 4 1970-01-01 00:00:12.500 1970-01-01 00:00:12.900 5 1970-01-01 00:00:13.080 1970-01-01 00:00:13.530 6 1970-01-01 00…
tagged with: dataframe
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51384621
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89739951
has title: Joining two pandas dataframes with custom sized intervals and aggregate function
tagged with: python
has comment: http://stackoverflow.com/comment/89737571
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51384621
upvote count: 1
type: Question

http://stackoverflow.com/comment/89902690
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51460128
type: Comment
has text: Had to add that it took 2 seconds to calculate this, over 55 mln rows, on my laptop.

http://stackoverflow.com/comment/89817964
type: Comment
score: 1
has text: On instantiation of the class, it defines all of the methods first, then runs `__init__`, so the order of functions in a class technically doesn't matter
comment on: http://stackoverflow.com/q/51423517
type: QuestionComment

http://stackoverflow.com/a/51453652
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89877055
accepted answer of: http://stackoverflow.com/q/51453603
answers question: http://stackoverflow.com/q/51453603
has body: It's easy. Anything you pass from command line can be put in the args list: pytest.main(args=['-s', 'mytest.py']) From the pytest.main docs: Parameters: args – list of command line arguments.

http://stackoverflow.com/comment/89849399
type: Comment
comment on: http://stackoverflow.com/a/51437911
score: 0
type: AnswerComment
has text: But in this case i can't be sure that the processor works off every Thread in the rate i want the command line to be executed. For small rates like `n = 30`calls per second, there could be a queue which the processor can't come after. whereas i use just the `time.sleep`-method there is only one thread i can be sure the processor can run in the rate i want

google-chrome-extension
tags question: http://stackoverflow.com/q/51397230
tag name: google-chrome-extension
type: Tag

http://stackoverflow.com/q/51468175
has answer: http://stackoverflow.com/a/51468202
tagged with: rename
has body: I am trying to update the names in a pandas dataframe column. I want: [IN] B17.31 107.34 34 B50.56 [OUT] B17.31 B107.34 B34 B50.56 The code I am using is: for file in df1.loc[:, '#filename']: new = str(file) if new[0] != 'B': final = new[:0] + 'B' + new[0:] else: final = new print((final)) df1.replace(new, final) print(df1['#filename']) df1.to_csv('updated_name_data.csv') I can not work out why it will print out the updated name but will not update in the dataframe or csv. Any help or a pointer in the right direction would be greatly appreciated.
has answer: http://stackoverflow.com/a/51468201
answer count: 3
tagged with: pandas
downvote count: 0
favorite count: 0
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51468201
score: 1
accepted answer: http://stackoverflow.com/a/51468202
upvote count: 1
has answer: http://stackoverflow.com/a/51468204
type: Question
has title: Change of element in column not updating in data frame

http://stackoverflow.com/a/51363624
type: Answer
answers question: http://stackoverflow.com/q/51326839
has comment: http://stackoverflow.com/comment/89700056
score: 0
has body: I finally find the answer to my question in the next blog: https://martinfitzpatrick.name/article/multithreading-pyqt-applications-with-qthreadpool/ this is a really great tutorial, after read the documentation in the blog I was able to modify one of the examples to modify the text of a label control in real time; here is the final code: from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtCore import * import time class Worker(QRunnable): def __init__(self, fn, *args, **kwargs): super(Worker, self).__init__() self.args = args self.kwargs = kwargs self.fn = fn @pyqtSlot() def run(self): #print(self.args, self.kwargs) print("Thread start") time.sleep(0.2) self.fn(*self.args, **self.kwargs) #ejecuta la funcion recibida class MainWindow(QMainWindow): def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.threadpool = QThreadPool() print("Multithreading with maximum %d threads" % self.threadpool.maxThreadCount()) self.counter = 0 layout = QVBoxLayout() self.l = QLabel("Start") self.l2 = QLabel("xxxxx") b = QPushButton("DANGER!") b.pressed.connect(self.oh_no) layout.addWidget(self.l) layout.addWidget(self.l2) layout.addWidget(b) w = QWidget() w.setLayout(layout) self.setCentralWidget(w) self.show() self.etiqueta="rrrrrrrrrr" self.timer = QTimer() self.timer.setInterval(500) self.timer.timeout.connect(self.recurring_timer) self.timer.start() def oh_no(self): self.etiqueta="hhhhhhhhhhhhhhhhh" worker = Worker(self.execute_this_fn,'4444') self.threadpool.start(worker) def recurring_timer(self): self.counter +=1 self.l.setText("Counter: %d" % self.counter) def execute_this_fn(self,x): print("Hello!") self.l2.setText(x) app = QApplication([]) window = MainWindow() app.exec_()

http://stackoverflow.com/q/51401557
has body: I have two modules that work together. For example, I have user.py and email.py. user.py have a function to verify a register and email.py have a function to send a email of confirmation. I import in controller user.py, and user.py import email.py. with: from gluon.custom_import import track_changes track_changes(True) I detect changes in user.py, but not in email.py. I tried to put track_changes also in user.py and it doesn't work. Are there something that I can do without restart server/web2py? Web2Py: 2.16.1-stable+timestamp.2017.11.14.05.54.25 (I try with *.exe and *.py) OS: Windows 10 Pro Thanks!
tagged with: module
has title: Web2Py: Not track changes between modules
has comment: http://stackoverflow.com/comment/89776632
tagged with: web2py
has answer: http://stackoverflow.com/a/51432278
accepted answer: http://stackoverflow.com/a/51432278
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/63631763
answer count: 2
has comment: http://stackoverflow.com/comment/89803594
score: 0
possible better answer: http://stackoverflow.com/a/63631763
tagged with: python

http://stackoverflow.com/a/51446780
accepted answer of: http://stackoverflow.com/q/51445711
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51445711
has comment: http://stackoverflow.com/comment/89877181
type: Answer
downvote count: 0
score: 1
has body: Here is one way to convert 4-dimensional coordinates into 3-dimenstional coordinates that will give you a visualization of the distances of the points from the 4D sphere. Since you show no code or equations of your own I'll just give an overview. If you give more details on your own work then you can ask me for more details. Take a point in 4 dimensions, let's say (x, y, z, w). Then convert those Cartesian coordinates to 4D spherical coordinates (r, t1, t2, t3), where r is the distance of the point to the origin and t1, t2, t3 are reference angles. Formulas for the conversion are in Wikipedia's entry for n-sphere, though in my preferred transformation I would reverse the order of the Cartesian coordinates. In other words, we get the relations w = r * cos(t1) z = r * sin(t1) * cos(t2) y = r * sin(t1) * sin(t2) * cos(t3) x = r * sin(t1) * sin(t2) * sin(t3) We now map that point to a point in 3D space by changing angle t1 to 90° (or pi/2 radians). This has the effect of "rotating" the point away from the w axis down into 3D space in regular spherical coordinates. The distances from the origin and from any 4-sphere centered at the origin were not changed. Now convert to 3D Cartesian coordinates with z = r * cos(t2) y = r * sin(t2) * cos(t3) x = r * sin(t2) * sin(t3) Now graph those as usual. Since distances to the origin and to the 4-sphere were not changed, this should be a useful visualization. Looking at those equations, we realize that the values of x, y, and z were all divided by sin(t1). That means you could optimize the calculations by finding only sin(t1) with the formula sin(t1) = sqrt((x*x + y*y + z*z) / (x*x + y*y + z*z + w*w)) There is no need to find r, t2, or t3 or even t1 itself. You need to be careful for the special case sin(t1) == 0.0, which happens only when x == y == z == 0. I would then map the 4D point (0, 0, 0, w) to the 3D point (w, 0, 0) and the visualization should still work well. There are other, similar transformations you could use that may…

http://stackoverflow.com/comment/89645346
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51335064
has text: @suku. That's why I've shown a couple of alternatives. If there was ever a version that didn't use regex, OP's original version should work.
type: AnswerComment

http://stackoverflow.com/comment/89733729
type: Comment
type: QuestionComment
has text: Try `time.clock()`
comment on: http://stackoverflow.com/q/51381010
score: 0

http://stackoverflow.com/comment/89651976
comment on: http://stackoverflow.com/a/51338475
type: Comment
has text: In the code I see two parameters for the generate() function. However you only entered one.
type: AnswerComment
score: 0

http://stackoverflow.com/q/51380591
has title: Get the values of specific rows as output based on user input
upvote count: 0
linked to: http://stackoverflow.com/q/51672531
tagged with: python
has comment: http://stackoverflow.com/comment/89733084
favorite count: 0
score: -1
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89749355
has body: I have a text file data.txt, containing a table whose first few entries look like this: PERIOD CHANNELS 1 2 3 4 5 0 1.51 1.61 1.94 2.13 1.95 5 1.76 1.91 2.29 2.54 2.38 6 2.02 2.22 2.64 2.96 2.81 7 2.27 2.52 2.99 3.37 3.24 8 2.53 2.83 3.35 3.79 3.67 9 2.78 3.13 3.70 4.21 4.09 10 3.04 3.44 4.05 4.63 4.53... The channel column contains the values of channels of an instrument. The other 5 columns contain the values of maximum energies a particular channel can detect in 5 different time periods. I want to write a python program which takes the period, lower energy and higher energy values from the user and based on the period, finds out lower energy channel and higher energy channel corresponding to the lower energy value and higher energy value given by the user. For example: Period = input('Enter the period: ') &gt;&gt; 1 lower_energy = float(input('Enter the lower energy value: ')) &gt;&gt; 2.02 higher_energy = float(input('Enter the higher energy value: ')) &gt;&gt; 2.60 The lower energy channel is 6 The higher energy channel is 9 I can write it using nested if conditions as follows: If period = 1: if lower_energy &lt; 1.51: lower_energy_channel = 0 elif lower_energy &lt; 1.76: lower_energy_channel = 5 elif lower_energy &lt; 2.02: lower_energy_channel = 6 ... If upper_energy &lt; 1.51: upper_energy_channel = 0 elif upper_energy &lt; 1.76: upper_energy_channel = 5 ... Similarly for all periods... But my table is very long and that would be very cumbersome. I am looking for a cleaner solution to this. The solution to this can be found here
type: UnansweredQuestion
downvote count: 1
has answer: http://stackoverflow.com/a/51409186
type: Question
has answer: http://stackoverflow.com/a/51380956
answer count: 2

http://stackoverflow.com/comment/89852262
comment on: http://stackoverflow.com/q/51440116
type: Comment
type: QuestionComment
has text: first fix your code indentation, then learn to avoid globals
score: 2

http://stackoverflow.com/q/51393297
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/51393331
type: UnansweredQuestion
tagged with: python
tagged with: dataframe
has answer: http://stackoverflow.com/a/51393474
has title: Sort and align 2 dataframes by values in corresponding columns
type: Question
answer count: 2
has body: I have 2 dataframes that I want to sort that are similar in structure to what I have shown below, but the rows of values when looking at only the first 3 columns are jumbled. How do I sort the dataframes such that the row indices match? Also it could so happen that there may not be matching rows in which case I want to create a blank entry in the other dataframe at that index. How would I go about doing this? Dataframe1: Col1 Col2 Col3 Col4 0 a b c 1 1 b c d 4 2 f e g 5 Dataframe2: Col1 Col2 Col3 Col4 0 f e g 6 1 a b c 5 2 b c d 3

http://stackoverflow.com/a/51427926
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51427785
type: Answer
score: 1
upvote count: 1
has body: Paths are case-sensitive. Are you sure you're not using Home instead of home? The traceback looks like you are.
answers question: http://stackoverflow.com/q/51427785
type: AcceptedAnswer

http://stackoverflow.com/a/51331991
answers question: http://stackoverflow.com/q/51331775
type: Answer
upvote count: 3
has body: Using count with transform df['count'] = df.groupby('date')['date'].transform('count') date count 0 2017/01/03 2 1 2017/01/03 2 2 2017/01/04 3 3 2017/01/04 3 4 2017/01/04 3 5 2017/01/05 1
has comment: http://stackoverflow.com/comment/89639770
has comment: http://stackoverflow.com/comment/89639573
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/89639579

http://stackoverflow.com/comment/89749298
has text: Rather than focusing on ways to perform this brute-force search more quickly, it sounds like you should be looking for ways to tackle your underlying problem without performing a brute-force search.
type: QuestionComment
comment on: http://stackoverflow.com/q/51387980
score: 0
type: Comment

http://stackoverflow.com/comment/89771448
comment on: http://stackoverflow.com/q/51392167
type: Comment
type: QuestionComment
score: 0
has text: @eyllanesc Agree. I don't expect that. The point is, using `PyQt`, I don't have an explicit destructor or `delete` instruction, as with C++. Do I have to force it manually then ? If so, what's the best PyQt'ish way to do that, instead of using sip or another solution from python (like `del`) ?

http://stackoverflow.com/comment/89841890
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51358426
type: QuestionComment
has text: @KathyWu it seems that lookup table can not have tensors as values, and 'indicator' is a tensor, which can not be used to index a list

pyodbc
tags question: http://stackoverflow.com/q/51423154
tags question: http://stackoverflow.com/q/51446274
tags question: http://stackoverflow.com/q/51376210
tags question: http://stackoverflow.com/q/51366354
tags question: http://stackoverflow.com/q/51418068
type: Tag
tags question: http://stackoverflow.com/q/51446757
tags question: http://stackoverflow.com/q/51399342
tags question: http://stackoverflow.com/q/51447877
tags question: http://stackoverflow.com/q/51413299
tag name: pyodbc
tags question: http://stackoverflow.com/q/51330310

http://stackoverflow.com/a/51388746
has body: And you're sure the page is there when accessed in a different fashion, say, manually? I don't know the API but it's not obvious from what you've written that the page does indeed exist. It just looks like a simple 404 and according to twitter's API reference that's precisely what "code 34" means. In any case, you're likely to encounter non-existent accounts sooner or later. Perhaps you should consider putting your gets inside try-except statements, like so: try: followers_ids = twitterRest.followers_ids(firstName) except TweepError: # log it, try the next guy or do something else entirely
answers question: http://stackoverflow.com/q/51388371
has comment: http://stackoverflow.com/comment/89826547
score: 0
type: Answer

http://stackoverflow.com/q/51386698
linked to: http://stackoverflow.com/q/20617997
downvote count: 1
type: Question
tagged with: continuous-deployment
has comment: http://stackoverflow.com/comment/89746652
has title: Push updates to python desktop apps
accepted answer: http://stackoverflow.com/a/51390671
tagged with: continuous-integration
answer count: 1
has comment: http://stackoverflow.com/comment/129266078
favorite count: 0
has answer: http://stackoverflow.com/a/51390671
upvote count: 2
tagged with: python
tagged with: deployment
type: AnsweredQuestion
has body: I'm working in a small CG animation company that does need small tools for production and CG artists. I'm coming from an animator's background, so my knowledge of code is extremely basic, but I'm learning. Here is the situation: I write python tools, most are using PySide for GUI. Now I need to regularly and easily deploy tools and updates to the machines in our studio (about 20 computers). We do want to do things the right way and are willing to learn, but the amount of information is quite overwhelming for I am a neophyte. I keep reading about various scary keywords that seem to be the answer I'm looking for, such as DevOps, CI/CD, Docker, Kubernetes... We are setting up a Gitlab instance on our local server, and now I'm asking what would be the most suitable way to easily deploy my scripts and their requested environment easily onto the company's computers (MacOs, Windows, and Linux), and how should I package them. I hope my question isn't vague but if so, please tell me and I'll try to be more precise. Thanks a lot
has comment: http://stackoverflow.com/comment/89745852
score: 1
has comment: http://stackoverflow.com/comment/89746138

http://stackoverflow.com/comment/90331825
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51335298
has text: Possible duplicate of [When do I need to use sqlalchemy back\_populates?](https://stackoverflow.com/questions/39869793/when-do-i-need-to-use-sqlalchemy-back-populates)

http://stackoverflow.com/comment/89682524
type: QuestionComment
comment on: http://stackoverflow.com/q/51350013
score: 0
has text: @dmitryro i tried writing the view function as shown above
type: Comment

image
tags question: http://stackoverflow.com/q/51417774
tags question: http://stackoverflow.com/q/51379058
tags question: http://stackoverflow.com/q/51353879
tags question: http://stackoverflow.com/q/51372854
tags question: http://stackoverflow.com/q/51332753
tags question: http://stackoverflow.com/q/51325224
tags question: http://stackoverflow.com/q/51463955
tags question: http://stackoverflow.com/q/51480238
tags question: http://stackoverflow.com/q/51330525
tags question: http://stackoverflow.com/q/51353755
tags question: http://stackoverflow.com/q/51462834
tags question: http://stackoverflow.com/q/51360609
tags question: http://stackoverflow.com/q/51408490
tags question: http://stackoverflow.com/q/51397037
tags question: http://stackoverflow.com/q/51373413
tags question: http://stackoverflow.com/q/51330607
tags question: http://stackoverflow.com/q/51396019
tags question: http://stackoverflow.com/q/51359691
tags question: http://stackoverflow.com/q/51392880
tags question: http://stackoverflow.com/q/51349907
tags question: http://stackoverflow.com/q/51436215
tags question: http://stackoverflow.com/q/51379912
tags question: http://stackoverflow.com/q/51356287
tags question: http://stackoverflow.com/q/51356074
tag name: image
tags question: http://stackoverflow.com/q/51458338
type: Tag
tags question: http://stackoverflow.com/q/51389995
tags question: http://stackoverflow.com/q/51367545
tags question: http://stackoverflow.com/q/51467937

http://stackoverflow.com/q/51458334
has answer: http://stackoverflow.com/a/51458563
has title: By downloading picture's file-header, how to obtain enough information?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89886390
has body: I need to download some pictures from a picture server every day. This server adds thousands of pictures daily, and many pictures have large size. Since the server does not support thumb pics and any pic-description, I have to download the pictures completely to know whether this picture is the one I need. However, my network bandwidth is very low, so it cost considerable time to download every picture. Moreover, the server has strict network flow controlling, thus, I may only download less than 100 pictures every day if the pictures are all large. I search some related articles and find that picture's file-header contains many useful information, so this is my plan: Use python code to download all pictures' file-header. If I only download file-header, the network flow will be very small, so I can download all pictures' file-header on the server. Analyse every pictures' file-header and obtain enough information. From my searching, I know the picture's format(png/jpg/gif), size(XXX,XXX bytes), resolution(XXXX×YYY,such as 1920x1080) can be obtained from picture's file-header which is less than 1000 bytes. Maybe it is possible to get more information from picture's file-header, so if you know more, please help me. Export the result to an Excel file. Could you tell me the effective python code to achieve the above three demands? Added on July 22: This is some information I got from HTTP header HTTP/1.1 200 OK Server: nginx Date: Sun, 22 Jul 2018 15:13:19 GMT Content-Type: image/jpeg Content-Length: 376386 Cache-Control: public,max-age=518400 Expires: Sat, 28 Jul 2018 15:13:19 GMT Last-Modified: Sun, 22 Jul 2018 15:13:19 GMT Vary: Origin ETag: "5be42" Connection: Keep-alive Now I can get Content-Type and Content-Length from HTTP header. But it is not enough for me. I searched and found someone said they could read the image's resolution(XXXX×YYY,such as 1920x1080) from the first 100 bytes of the pic-file data.(100 here is only the maximum number, somebody even said he ca…
has answer: http://stackoverflow.com/a/51458513
tagged with: excel
type: Question
score: 0
answer count: 2

http://stackoverflow.com/q/51327905
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51328002
accepted answer: http://stackoverflow.com/a/51328002
type: Question
score: 0
tagged with: pandas
answer count: 1
has title: How to fill in pandas data frame of unknown size
has body: I am pretty new to Python and I am trying to scrape information of multiple sites which are all of the same structure, but of different length. What I am trying to do is add my information row by row from an empty data frame, like you can do in R by simply calling the indices and R adds a row to the data frame. In pandas however, I can't seem to find a way to create an empty matrix and add a row to it like that, when I try to do df = pd.DataFrame() df.iloc[0] = [1,2,3,4] the program presents me with the error message: IndexError: single positional indexer is out-of-bounds I know there are functions like append but it doesn't seem to do the work for me. I find it very weird that i haven't found any information on this on stackoverflow so this may be a duplicate question. Thanks in advance!
tagged with: python

http://stackoverflow.com/a/71013016
answers question: http://stackoverflow.com/q/51439138
score: 1
has body: Please try the below code : import pytesseract from PIL import Image pytesseract.pytesseract.tesseract_cmd = r'C:/Program Files/Tesseract-OCR/tesseract.exe' tessdata_dir_config = '--tessdata-dir "C:/Program Files/Tesseract-OCR/tessdata"' img = Image.open('images\Capture2.JPG') text = pytesseract.image_to_string(img, config=tessdata_dir_config) print(text)
has comment: http://stackoverflow.com/comment/125643903
downvote count: 0
upvote count: 1
type: Answer

http://stackoverflow.com/comment/89700449
comment on: http://stackoverflow.com/a/51363003
score: 0
type: AnswerComment
has text: i try widget.winId() but its no getting a program(window) its getting the same primaryscreen but crop (im on linux)
type: Comment

http://stackoverflow.com/a/51329781
has comment: http://stackoverflow.com/comment/89637206
has comment: http://stackoverflow.com/comment/89636052
has comment: http://stackoverflow.com/comment/89635604
score: 1
has comment: http://stackoverflow.com/comment/89635984
has comment: http://stackoverflow.com/comment/89635939
upvote count: 1
answers question: http://stackoverflow.com/q/51329742
downvote count: 0
has comment: http://stackoverflow.com/comment/89637097
has comment: http://stackoverflow.com/comment/89636176
has comment: http://stackoverflow.com/comment/89635491
has comment: http://stackoverflow.com/comment/89636010
type: Answer
has body: You can use os.open command to run any script within python script it will run as it would in a command line, for example: import os os.open("echo 7") #this will print 7 on the terminal when you run the script If in case you want to capture output of a script you run and use it in the script then I suggest you use os.popen, for example: import os var=os.popen("cat /path/to/file") print(var) #this will print the file content So in short anything that goes in os.open("here") will run as it would in a command line or terminal of your os. If you want to run applications you will have to sub subprocess: import subprocess subprocess.call("spyder") Alternatively you can use popen as well to open files: import os os.popen("spyder or subl") os.open will not work. In regards to your specific request use the following code: import os os.popen("cd /home/mypc/path ; subl")

http://stackoverflow.com/q/51448385
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51449072
downvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/89867277
answer count: 2
has title: How to get data from django Model
has answer: http://stackoverflow.com/a/51448484
favorite count: 0
has body: Ok so I have this Model in django: class Training(models.Model): url = models.URLField(max_length=100) title = models.CharField(max_length=100) topic = models.CharField(max_length=100) grouping = models.CharField(max_length=100) month = models.CharField(max_length=100) overallOrder = models.CharField(max_length=100) emailSent = models.CharField(max_length=100) but how do I get the data from those fields? If I drop to the sqlite shell this is what I get: In [1]: from myapp.models import Training In [2]: queryset = Training.objects.all() In [3]: print (queryset) &lt;QuerySet [&lt;Training: Training object&gt;]&gt; But I want to be able to look at all the data in that database. I'm not sure how to do that. Any help is appreciated. Thank you.
score: 0
tagged with: python
linked to: http://stackoverflow.com/q/20171736
has comment: http://stackoverflow.com/comment/89868305
upvote count: 3
accepted answer: http://stackoverflow.com/a/51448484
has answer: http://stackoverflow.com/a/51449072
tagged with: django

http://stackoverflow.com/comment/89901655
score: 0
type: Comment
type: QuestionComment
has text: have a look to this python library: https://docs.python.org/2/library/multiprocessing.html
comment on: http://stackoverflow.com/q/51466456

http://stackoverflow.com/comment/89814067
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51420456
has text: @lolnoob: That is an important information that you should have put in the question...
type: Comment

http://stackoverflow.com/comment/89759036
type: Comment
has text: What is your question? Right now all you've said is that you wrote some code. What precisely is it that doesn't work about your code which you need help with?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51393765

windows
tags question: http://stackoverflow.com/q/51408678
tags question: http://stackoverflow.com/q/51378194
tags question: http://stackoverflow.com/q/51426929
tags question: http://stackoverflow.com/q/51335594
tags question: http://stackoverflow.com/q/51331371
tags question: http://stackoverflow.com/q/51462453
tags question: http://stackoverflow.com/q/51326263
tags question: http://stackoverflow.com/q/51451795
tags question: http://stackoverflow.com/q/51473437
tags question: http://stackoverflow.com/q/51340880
tags question: http://stackoverflow.com/q/51334035
tags question: http://stackoverflow.com/q/51465151
tags question: http://stackoverflow.com/q/51345594
tags question: http://stackoverflow.com/q/51372922
tags question: http://stackoverflow.com/q/51374273
tags question: http://stackoverflow.com/q/51461703
tags question: http://stackoverflow.com/q/51350288
tags question: http://stackoverflow.com/q/51419201
tags question: http://stackoverflow.com/q/51336226
tags question: http://stackoverflow.com/q/51479516
type: Tag
tags question: http://stackoverflow.com/q/51356143
tags question: http://stackoverflow.com/q/51354026
tags question: http://stackoverflow.com/q/51329260
tag name: windows
tags question: http://stackoverflow.com/q/51379323
tags question: http://stackoverflow.com/q/51372927

http://stackoverflow.com/comment/89836159
score: 0
comment on: http://stackoverflow.com/q/51425875
type: Comment
has text: The first/last should be similar if you're using `TERM=xterm` and running on the same machine. The second one's never been vetted, so it's out of scope.
type: QuestionComment

http://stackoverflow.com/a/51341903
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/51340219
has body: Another option, since your data is coming from SQL is to convert all date times to dates upfront, in the SQL. For example, using: How to return only the Date from a SQL Server DateTime datatype That would only work if you never needed the full date time in your code - i.e. all logic only used dates. Though I too like the elegance of comprehensions (not having to write for loops!), I sometimes end up feeling they are unwieldy and hard to read, especially with conditional logic, and mapping functions. Also, they are harder error check, as they attempt to apply multiple operations all together. In this case, a simple check and recast is what I use. Generate some testable data: import pandas as pd import numpy as np from datetime import datetime def make_data (n): ts1 = datetime.now().timestamp() + abs(np.random.normal(1000, 30, n)).cumsum() ts2 = datetime.now().timestamp() + abs(np.random.normal(2000, 10, n)).cumsum() df = pd.DataFrame({ 'c1': np.random.choice(list('ABCDEFGH'), n), 'c2': np.random.choice(list('ABCDEFGH'), n), 'c3': np.random.choice(list('ABCDEFGH'), n), 'i1': np.random.randint(1, 20, n), 't1': pd.to_datetime(ts1, unit='s'), 't2': pd.to_datetime(ts2, unit='s'), 'x1': np.random.randn(n), 'x2': np.random.randn(n), 'x3': np.random.randn(n) }) return df df = make_data(100) Then convert all date times to just the date with: # convert datetimes to just the date for col in df.columns: if df[col].dtype == 'datetime64[ns]': df[col] = df[col].dt.date The is more easily turned into a generic function with error checking (try, except), or used to convert objects to category or int to float, or...
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51340219

http://stackoverflow.com/comment/89796900
has text: @KirillBulygin Hello. I did, but I'm new in Python so by now i'm measuring time in the wrong way. I've got 32 threads and the PC is a linux that is just doing that, not even x server loaded, so time() should be a "reliable" measure. I run it 20 times and measure mean and min
type: Comment
comment on: http://stackoverflow.com/q/51409330
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89627476
comment on: http://stackoverflow.com/a/51326130
type: AnswerComment
has text: Note that [multithreading sould work fine too](http://scipy-cookbook.readthedocs.io/items/Multithreading.html) if the computational part is done with numpy.
type: Comment
score: 1

http://stackoverflow.com/q/51442273
tagged with: pandas
answer count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51442354
has title: Assign different values into a new column based on dataframe chunk
tagged with: python
type: Question
has body: I have a dataframe: df = pd.DataFrame({'a':[1,2,3,4,5,6,7,8,9,10],'b':[100,100,100,100,100,100,100,100,100,100]}) a b 0 1 100 1 2 100 2 3 100 3 4 100 4 5 100 5 6 100 6 7 100 7 8 100 8 9 100 9 10 100 I want to create a column c, such that for every chunk of 3 rows it assigns a value. The output i'm looking for: a b c 0 1 100 1 1 2 100 1 2 3 100 1 3 4 100 2 4 5 100 2 5 6 100 2 6 7 100 3 7 8 100 3 8 9 100 3 9 10 100 4 I tried to iterate through the dataframe and then using .loc to assign column values. Is there any better/quick way of doing this?
score: 0

http://stackoverflow.com/a/51402483
has comment: http://stackoverflow.com/comment/89786534
answers question: http://stackoverflow.com/q/51387915
has comment: http://stackoverflow.com/comment/89778277
has comment: http://stackoverflow.com/comment/89786417
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/89786583
has comment: http://stackoverflow.com/comment/89780832
has body: The problem is caused when you define the grid parameters using list comprehension and the float argument. This works fine for me: from sklearn.neural_network import MLPRegressor from sklearn.model_selection import RandomizedSearchCV import pandas as pd import numpy as np from sklearn.model_selection import GridSearchCV X = pd.read_csv('X.csv') Y = pd.read_csv('y.csv') X = X.iloc[1:,1:].values Y = Y.iloc[1:,1].values mlpsgd = MLPRegressor(max_iter = 1000, solver='sgd') alpha = np.arange(0.01, 0.1, 0.01) hidden_layer_sizes = [(int(x),int(y),int(z)) for x in np.logspace(start = 0, stop = 2.2, num = 8) for y in np.logspace(start = 0, stop = 2.2, num = 8) for z in np.logspace(start = 0, stop = 2.2, num = 8)] hidden_layer_sizes.extend((int(x),int(y)) for x in np.logspace(start = 0, stop = 2, num = 25) for y in np.logspace(start = 0, stop = 2, num = 25)) hidden_layer_sizes.extend((int(x),) for x in np.logspace(start = 1, stop = 2, num = 1000)) activation = ['logistic', 'tanh', 'relu'] learning_rate = ['constant', 'invscaling','adaptive'] learning_rate_init = np.arange(0.01, 0.1, 0.01) random_grid3 = {'learning_rate': learning_rate,'activation': activation,'learning_rate_init': learning_rate_init, 'hidden_layer_sizes': hidden_layer_sizes, 'alpha': alpha} mlp_random3 = RandomizedSearchCV(estimator = mlpsgd, param_distributions = random_grid3, n_iter = 350, n_jobs=-1) mlp_random3.fit(X, Y) print(mlp_random3.best_estimator_) MLPRegressor(activation='relu', alpha=0.03, batch_size='auto', beta_1=0.9, beta_2=0.999, early_stopping=False, epsilon=1e-08, hidden_layer_sizes=(4, 18, 1), learning_rate='adaptive', learning_rate_init=0.05, max_iter=1000, momentum=0.9, nesterovs_momentum=True, power_t=0.5, random_state=None, shuffle=True, solver='sgd', tol=0.0001, validation_fraction=0.1, verbose=False, warm_start=False)
has comment: http://stackoverflow.com/comment/89780588
accepted answer of: http://stackoverflow.com/q/51387915
has comment: http://stackoverflow.com/comment/89783088

http://stackoverflow.com/comment/89813690
type: Comment
has text: "most likely because it is not on the same host" oh wow indeed, thanks, that's almost embarrassing ;-)
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51418187

http://stackoverflow.com/q/51367755
answer count: 2
tagged with: h2o
downvote count: 0
possible better answer: http://stackoverflow.com/a/51526227
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51423325
accepted answer: http://stackoverflow.com/a/51423325
type: AnsweredQuestion
has title: Predict classes or class probabilities?
tagged with: classification
linked to: http://stackoverflow.com/q/51190809
has answer: http://stackoverflow.com/a/51526227
has body: I am currently using H2O for a classification problem dataset. I am testing it out with H2ORandomForestEstimator in a python 3.6 environment. I noticed the results of the predict method was giving values between 0 to 1(I am assuming this is the probability). In my data set, the target attribute is numeric i.e. True values are 1 and False values are 0. I made sure I converted the type to category for the target attribute, I was still getting the same result. Then I modified to the code to convert the target column to factor using asfactor() method on the H2OFrame still, there wasn't any change on the result. But when I changed the values in the target attribute to True and False for 1 and 0 respectively, I was getting the expected result(i.e) the output was the classification rather than the probability. What is the right way to get the classified prediction result? If probabilities are the outcomes for numerical target values, then how do I handle it in case of a multiclass classification?
tagged with: machine-learning
type: Question
upvote count: 12
tagged with: random-forest
linked to: http://stackoverflow.com/q/43054383
score: 12

http://stackoverflow.com/q/51326314
favorite count: 0
tagged with: datetime
tagged with: python
upvote count: 4
downvote count: 0
has answer: http://stackoverflow.com/a/51326643
tagged with: django
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51326393
accepted answer: http://stackoverflow.com/a/51326393
possible better answer: http://stackoverflow.com/a/51326643
has title: Changing field in Django Form, overriding clean()
tagged with: http://stackoverflow.com/tag/json
score: 4
type: Question
answer count: 2
tagged with: validation
linked to: http://stackoverflow.com/q/47510752
has body: I have a date, passed as 2019-01-01T00:02. My objective is to replace the T with a whitespace, 2019-01-01 00:02. Using Form, i validate that field and some others.' klientForm = KlientForm(json.loads(request.body.decode())) bokningForm = BokningForm(json.loads(request.body.decode())) if klientForm.is_valid() and bokningForm.is_valid(): #Save model, etc. I'm using DateTimeField, and it will not accept the date unless I change it like above. I implemented my own clean() method, def clean(self): cleaned_data = super(BokningForm, self).clean() pumpStart = self.data['pumpStart'] pumpStart = pumpStart.replace("T", " ") cleaned_data['pumpStart'] = datetime.strptime(pumpStart, "%Y-%m-%d %H:%M") return cleaned_data This successfully converts it to a datetime object, I checked using print(cleaned_data) My issue is that the data is returned to late, as (I think) bokningForm.is_valid() has already failed, resulting in the model not being saved. I tried using clean_pumpStart(self): as in Django Forms but the function was not called when bokningForm.is_valid() failed, resulting in the same issue as above. Any help appreciated!

http://stackoverflow.com/q/51429612
score: 0
has comment: http://stackoverflow.com/comment/89835078
has body: Lets suppose I have a single node with infinite number of CPUs and infinite I/O resources. I would like to write a python script which uses multiprocessing and calculates the total amount of files in a given path and all the subdirectories example: I run a script which generates millions of files in a given path: #!/usr/bin/env bash NUMDIRS=300000 NUMFILES=10 myPath="/tmp/test" echo "Working on path: $myPath" for directory in `seq 1 $NUMDIRS` do mkdir -p "$myPath/$directory" cd $myPath/$directory for file in `seq 1 $NUMFILES` do touch "file_$file.txt" echo "Path: $myPath/$directory" &gt;&gt; file_$file.txt echo "Filename: file_$file.txt" &gt;&gt; file_$file.txt echo "Created on: `date +"%Y%m%d-%H%M%S"`" &gt;&gt; file_$file.txt done done Even if this is not the best example to use multiprocessing, just for learning purposes, I would like to know how I could write a python piece of code to use multiprocessing and return 3000000 following the provided example (300000 directories x 10 files per directory). EDIT: A first unsuccessful approach: #!/usr/bin/env python3 import os import multiprocessing path = "/tmp/test" def count_single_process(path): cpt = sum([len(files) for r, d, files in os.walk(path)]) return cpt def walkingThePath(path): for r, d, f in os.walk(path): return len(f) def main(): cpu_number = multiprocessing.cpu_count() with multiprocessing.Pool(cpu_number) as Pool: print(Pool.map(walkingThePath, path)) if __name__ == '__main__': main()
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89830260
answer count: 0
has comment: http://stackoverflow.com/comment/89831602
type: Question
tagged with: multiprocessing
has title: python - How to count number of files recursively in a path using multiprocessing
has comment: http://stackoverflow.com/comment/89830687

http://stackoverflow.com/a/51380662
type: AcceptedAnswer
has body: Here is the reference code that you can apply, is very self explanatory Function to update record to mongo db def update(): try: criteria = raw_input('\nEnter id to update\n') name = raw_input('\nEnter name to update\n') age = raw_input('\nEnter age to update\n') country = raw_input('\nEnter country to update\n') db.Employees.update_one( {"id": criteria}, { "$set": { "name":name, "age":age, "country":country } } ) Let me clarify that it will only work if the "user_name" is unique. Give it a try and let me know. More reference for all the basic functions are here: https://codehandbook.org/pymongo-tutorial-crud-operation-mongodb/ Regards, DH
type: Answer
accepted answer of: http://stackoverflow.com/q/51380521
answers question: http://stackoverflow.com/q/51380521
score: 0

http://stackoverflow.com/q/51349646
possible better answer: http://stackoverflow.com/a/51349677
has title: Name not defined error in python django
type: Question
has comment: http://stackoverflow.com/comment/89671868
has answer: http://stackoverflow.com/a/51349677
score: 0
answer count: 2
has body: import csv import io import re from django.http import HttpResponse from django.shortcuts import render from django.views import generic from ...forms import CsvUploadForm import pandas as pd class CsvImportView(generic.base.View): def getemailcolumn(self, sample): for key, val in sample: print(key, val) if re.match("^.+@([?)[a-zA-Z0-9-.]+.([a-zA-Z]{2,3}|[0-9]{1,3})(]?)$", val[0]) is not None: return key return None def post(self, request): form = CsvUploadForm(request.POST, request.FILES) if form.is_valid(): fieldnames = ['first_name', 'email', 'last_name'] csv = pd.read_csv(request.FILES['csv']) sample =csv.head(); emailColumn = getemailcolumn(sample) return HttpResponse(sample) else: ... ... when the post method is getting executed, i am getting a name not defined error name 'getemailcolumn' is not defined what am i missing?
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/51350335
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51350335

http://stackoverflow.com/q/51463615
has comment: http://stackoverflow.com/comment/89896463
has body: I'm using a for loop to generate a button for every key in a jsonstore. The buttons are all added to the layout correctly and the button.text is correct but when the button calls the callback, they all link to the same key. (the last key) here is the code: def show_saved_conditions(*args,**kwargs): self.label7 = Label(text = str(self.store[self.btns.text], size_hint = (.3,.3), pos_hint = {'x':.3,'y':.5}, color = (0,0,1,1))) self.layout.add_widget(self.label7) def view_saved_conditions(*args, **kwargs): x = 0 y = 0 for i in self.store.keys(): self.btns = (Button(text = i, size_hint = (.2,.1), pos_hint = {'x':x,'y':y}, on_release = show_saved_conditions)) self.layout.add_widget(self.btns) x +=.2 if x &gt;= 1: y+=.1 x = 0 pretty sure this question has been asked before but i was unable to find a post specific enough for me to relate to. Thank you in advance...
type: Question
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51489458
has title: python kivy generating buttons linked to jsonstore items in a for loop
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51466472
tagged with: python
tagged with: kivy

http://stackoverflow.com/comment/89631325
comment on: http://stackoverflow.com/q/51327948
has text: `df.astype(float).grouby(by=['A']).sum()`
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/89679927
has text: Thank you so much! I am checking the post and videos.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51344740

http://stackoverflow.com/comment/89821767
type: QuestionComment
type: Comment
has text: according to the documentation https://geopy.readthedocs.io/en/stable/index.html?highlight=vincenty#module-geopy.distance vincenty is deprecated, are you aware?
comment on: http://stackoverflow.com/q/51425127
score: 0

http://stackoverflow.com/comment/89788519
comment on: http://stackoverflow.com/q/51408544
score: 0
has text: By importing the execution of all of `modA.py` and running it in `modB.py` as required.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89862465
comment on: http://stackoverflow.com/q/51446082
type: Comment
type: QuestionComment
score: 0
has text: I want to sort the dictionary by value after that if 2 or more keys have the same value I want to sort them according to the key.

http://stackoverflow.com/a/51467965
type: Answer
answers question: http://stackoverflow.com/q/51467820
has body: There is a continue statement to skip the current iteration and continue with the next iteration unlike break statement (which terminates the loop). Here is the code. def a(num): print('a:', str(num)) def b(num): print('b:', str(num)) for x in range(1,10): if x == 2: continue a(x) b(x) Output &raquo; a: 1 b: 1 a: 3 b: 3 a: 4 b: 4 a: 5 b: 5 a: 6 b: 6 a: 7 b: 7 a: 8 b: 8 a: 9 b: 9
score: 0

http://stackoverflow.com/q/51342213
upvote count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/89658096
answer count: 1
has answer: http://stackoverflow.com/a/51367282
accepted answer: http://stackoverflow.com/a/51367282
has comment: http://stackoverflow.com/comment/89659223
favorite count: 0
tagged with: python
type: AnsweredQuestion
downvote count: 0
tagged with: bokeh
type: Question
score: 3
has body: I am trying to implement checkboxes in bokeh where each checkbox should show/hide the line associated with it. I'm aware it's possible to achieve this with legends, but I want this effect to happen in two plots at the same time. Also, the legend should update as well. In the example below the checkboxes appear, but do nothing. I am clearly not grasping how to update de dataframe used as source. Thanks for any help. from bokeh.io import show, curdoc from bokeh.models import HoverTool, ColumnDataSource, Legend from bokeh.plotting import figure from bokeh.palettes import Category10 from bokeh.models.widgets import CheckboxGroup from bokeh.layouts import row import pandas as pd def update(atrr, old, new): lines_to_plot = [checkbox_group.labels[i] for i in checkbox_group.active] cols = ['x'] for label in lines_to_plot: cols += [label + 'y'] cols += [label] newdf = df0[cols] source.data.update(ColumnDataSource(newdf)) df0 = pd.DataFrame({'x': [1, 2, 3], 'Ay' : [1, 5, 3], 'A': [0.2, 0.1, 0.2], 'By' : [2, 4, 3], 'B':[0.1, 0.3, 0.2]}) columns = ['A', 'B'] checkbox_group = CheckboxGroup(labels=columns, active=[0, 1]) tools_to_show = 'box_zoom,save,hover,reset' p = figure(plot_height =300, plot_width = 1200, toolbar_location='above', tools=tools_to_show) legend_it = [] color = Category10[10] columns = ['A', 'B'] source = ColumnDataSource(df0) for i, col in enumerate(columns): c = p.line('x', col, source=source, name=col, color=color[i]) legend_it.append((col, [c])) legend = Legend(items=legend_it, location=(5,114))#(0, -60)) p.add_layout(legend, 'right') hover = p.select(dict(type=HoverTool)) hover.tooltips = [("Name","$name"), ("Aux", "@$name")] hover.mode = 'mouse' layout = row(p,checkbox_group) checkbox_group.on_change('active', update) curdoc().add_root(layout)
has title: How to dynamically hide glyphs and legend items with Bokeh

http://stackoverflow.com/comment/89643783
comment on: http://stackoverflow.com/q/51334116
type: Comment
type: QuestionComment
score: 0
has text: Great! You are allowed – and even encouraged – to [answer your own question](https://stackoverflow.com/help/self-answer), and after a short waiting period you can also accept it. (Just don't make the mistake to edit it into your question.)

http://stackoverflow.com/q/51380372
has answer: http://stackoverflow.com/a/72202652
accepted answer: http://stackoverflow.com/a/51380424
has body: I want to rename rows in python program (version - spyder 3 - python 3.6) . At this point I have something like that: import pandas as pd data = pd.read_csv(filepath, delim_whitespace = True, header = None) Before that i wanted to rename my columns: data.columns = ['A', 'B', 'C'] It gave me something like that. A B C 0 1 n 1 1 1 H 0 2 2 He 1 3 3 Be 2 But now, I want to rename rows. I want: A B C n 1 n 1 H 1 H 0 He 2 He 1 Be 3 Be 2 How can I do it? The main idea is to rename every row created by pd.read by the data in the B column. I tried something like this: for rows in data: data.rename(index={0:'df.loc(index, 'B')', 1:'one'}) but it's not working. Any ideas? Maybe just replace the data frame rows by column B? How?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89732302
has answer: http://stackoverflow.com/a/51380424
tagged with: rows
type: Question
tagged with: for-loop
tagged with: pandas
has answer: http://stackoverflow.com/a/65956639
has comment: http://stackoverflow.com/comment/89733367
downvote count: 0
favorite count: 0
answer count: 3
has title: How to rename the rows in dataframe using pandas read (Python)?
tagged with: python
score: 2
upvote count: 2
possible better answer: http://stackoverflow.com/a/65956639

http://stackoverflow.com/a/51327916
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51327863
score: 2
has body: Use Series built in Series.str.zfill method: df.ColumnName.astype(str).str.zfill(4) #0 100012 #1 225434 #2 0030 #3 0045 #4 0036 #5 80200 #Name: ColumnName, dtype: object
accepted answer of: http://stackoverflow.com/q/51327863
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/89791821
comment on: http://stackoverflow.com/q/51409927
type: Comment
type: QuestionComment
has text: @Matthias I'm looking for the distance between every unique pair, so every possible (n choose 2) way you could pair these points up.
score: 0

http://stackoverflow.com/q/51435505
type: Question
has answer: http://stackoverflow.com/a/51479712
has answer: http://stackoverflow.com/a/51435533
upvote count: 2
answer count: 2
favorite count: 0
has body: I have a list of strings, I want to match a keyword if is not preceded by an "and". However, I would like to include the keyword if the "and" is preceded by another word. Taking into account that the position of the "and" is not the same in all the strings. In my example below I would like to match strings that have the word "book", only if the word "book" is not after "and" unless the "and" is precede by a "tall" (the first and the third item in my list). My attempt was using ^((?!((?&lt;!tall)\band\b)).)*book but it is not working. I'm not sure if I can include a negative look behind inside a negative lookahead is a tall and wide book is a computer and a book of instructions book with a pretty cover 4.computer with nice headphones
type: UnansweredQuestion
tagged with: python
tagged with: regex
score: 2
has title: negative lookahead regular expression python
downvote count: 0
tagged with: regex-negation

http://stackoverflow.com/q/51396047
duplicate of: http://stackoverflow.com/q/38982807
type: Question
has comment: http://stackoverflow.com/comment/89763153
answer count: 1
tagged with: flask
favorite count: 0
has comment: http://stackoverflow.com/comment/89763259
accepted answer: http://stackoverflow.com/a/51396833
tagged with: port
tagged with: python
linked to: http://stackoverflow.com/q/413807
score: 8
linked to: http://stackoverflow.com/q/20212894
has title: Running flask on port 80 in linux
downvote count: 1
has body: There maybe previous answers to this, So redirect me please, if that's the case I was thinking of running flask on port 80, so I checked if anything is using port 80, as it turns out nothing is running of port 80, so when I type this: if __name__ == '__main__': app.run(debug=True, host='192.168.4.1' port=int("8081")) This gives me the web page I want to display, But when I switch to this: if __name__ == '__main__': app.run(debug=True, host='192.168.4.1' port=int("80")) I am getting: PermissionError : [Errno 13] Permission denied Is there any issue with giving flask or python3 root privileges?
type: AnsweredQuestion
upvote count: 9
has comment: http://stackoverflow.com/comment/89763322
has answer: http://stackoverflow.com/a/51396833
duplicate of: http://stackoverflow.com/q/20212894

http://stackoverflow.com/a/51473469
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51469434
answers question: http://stackoverflow.com/q/51469434
score: 2
has body: Define the loss function as follows: def charbonnier(I_x, I_y, I_t, U, V, e) def loss_fun(y_true, y_pred): loss = K.sqrt(K.pow((U*I_x + V*I_y + I_t), 2) + e) return K.sum(loss) return loss_fun
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/109412549

http://stackoverflow.com/a/51353431
downvote count: 0
has body: I like to build a single dataframe shaped and organized for using pandas plot. white_f = gb_gender_race.xs(('F','White'), level=['gender','race']).rename('White F') gender = gb_gender.unstack() overall = gb_overall.rename('Overall') df_chart = pd.concat([white_f, gender, overall], axis=1) axes = df_chart.plot(marker = 'o') axes.set_xlim(left=2012.5) axes.set_title('Year vs. Average Rate', fontsize= 24) axes.set_xlabel('Year', fontsize= 16) axes.set_ylabel('Average Rate', fontsize= 16) axes.legend(['Overall', 'F', 'M', 'White F'], fontsize=14, loc= 'best', frameon= True, edgecolor= 'black') Output:
upvote count: 3
answers question: http://stackoverflow.com/q/51353314
type: Answer
score: 3

http://stackoverflow.com/comment/89970483
comment on: http://stackoverflow.com/a/51441527
has text: My solution is to add `__main__.py` that runs training, zip all related files into an archive file with unique name, then run `python archive.zip`. More details here: https://gist.github.com/rochacbruno/ed19c5d9ba9bb50391a2
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89785465
comment on: http://stackoverflow.com/q/51405496
score: 0
has text: Period is a PeriodIndex, obtained by using the function dt.to_period("M") on the column (it was previously a datetime).
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90153764
comment on: http://stackoverflow.com/q/51405945
type: Comment
type: QuestionComment
has text: @Legion I have no problem installing/using grpc I am just trying to understand how to keep track of multiple clients as in the java example in the video. I don't see any `StreamObserver` or know how to get access to one in python
score: 0

http://stackoverflow.com/q/51428084
has comment: http://stackoverflow.com/comment/89827509
accepted answer: http://stackoverflow.com/a/51428738
favorite count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/51428961
has answer: http://stackoverflow.com/a/51428961
type: AnsweredQuestion
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51428738
tagged with: conditional-statements
score: 1
has title: Select users based on the column values - pandas dataframe
has answer: http://stackoverflow.com/a/51434905
tagged with: dataframe
has body: I am having a problem with selecting IDs that are conforming to some condtions in my dataframe. Here is the problem: My dataframe look like this: index ID score_1 score_2 ... 0 22 0 0 1 22 0 0 2 22 0 0 3 23 1 0 4 23 1 0 5 23 1 0 6 24 0 0 7 24 0 0 8 24 0 1 10 25 0 0 11 25 0 0 12 26 0 1 13 26 0 1 What I want to do is to get the number of IDs that have: score_1 == 0 and score_2 == 0 for all instances - for example ID == 22 and ID == 25 fulfill this requirement. score_1 == 0, but at least one of the rows for a given ID has score_2 == 1 - for example ID == 24 fulfill this requirement score_1 == 0, and ALL of the rows for a given ID has score_2 == 1 - for example ID == 26 fulfill this requirement Each ID should appear only in ONE of these groups. I tried using conditional filtering and groupby, but then I get duplicated IDs as it selects only single rows, instead of 'having in mind' users. Some of the code I tried: # Create a df with only IDs that have score_1 == 0, group by `ID` zero_IDs = df[df['score_1'] == 0].groupby(by = 'ID').nunique() # 'Count' the number of IDs that have only one type of `score_2` # But this does not differentitate between `0` or `1` values for score_2 column zero_IDs[(zero_IDs['score_2'] == 1)].shape[0] # 'Count' the number of IDs that have at leat one `score_2 == 1` zero_IDs[(zero_IDs['score_2'] &gt; 1)].shape[0] Could you please help me with this?
tagged with: numpy
answer count: 3
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/89827912

http://stackoverflow.com/q/51393327
type: Question
score: 0
has comment: http://stackoverflow.com/comment/89759032
tagged with: django-admin
has comment: http://stackoverflow.com/comment/89760219
has comment: http://stackoverflow.com/comment/89758858
answer count: 1
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/51394606
has title: How to add table in Django admin without migrate command
has body: I am using Django 1.10 when I use Django admin but I can not find my table in admin setting, because I just add my table by SQL but not use Django migrate what should I do to add some table in Django admin I use @admin.register() in admin.py so I can see this in the setting because I am superuser it shows in admin index but in User permissions settings it does not show because it does not in DB table auth_permission and some relative table empyt

http://stackoverflow.com/q/51438792
favorite count: 0
has answer: http://stackoverflow.com/a/51438940
has answer: http://stackoverflow.com/a/51439099
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
type: Question
has title: use a variable in multiple file in python ( like extern )with out assigning the variable instead using the input variable( without using files )
accepted answer: http://stackoverflow.com/a/51439099
has body: File 1 ( a1.py ) : a=input("Input : ") b=a print("File1 end") Output : Input : 4 File1 end File 2 ( a2.py ) : import a1 print("Output : "+a1.b) Output : Input : 2 File1 end Output : 2 Expected Output(After Running a2.py ): Output : 4
tagged with: python-2.7
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/51438940

http://stackoverflow.com/a/51348173
has body: You can use the package more_itertools to flatten what you have. import more_itertools lst = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] res = list(more_itertools.flatten(lst)) Then you just need to use the max() function.
has comment: http://stackoverflow.com/comment/89668973
type: Answer
answers question: http://stackoverflow.com/q/51348133
upvote count: 1
downvote count: 1
score: 0

http://stackoverflow.com/comment/89797143
type: Comment
comment on: http://stackoverflow.com/a/51409514
type: AnswerComment
has text: BTW, I gave you a point. Even if your answer doesnt save me time for this, I was looking forward the way to do something like that, so you helped me anyway.
score: 0

http://stackoverflow.com/a/51468953
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89906680
has comment: http://stackoverflow.com/comment/89906998
has comment: http://stackoverflow.com/comment/89907247
has body: You could use the mul function from the built-in audioop module. This is what pydub uses internally, after converting the decibel value to a multiplication factor.
downvote count: 0
has comment: http://stackoverflow.com/comment/89906612
answers question: http://stackoverflow.com/q/51468895

http://stackoverflow.com/comment/89873038
comment on: http://stackoverflow.com/a/51415729
type: AnswerComment
has text: Kasely , again thanks a lot. I looked at the neat function before and worked but failed on the fields Comments , WorkEnviroment and EntryRequirements. Still working on it.
score: 0
type: Comment

http://stackoverflow.com/a/51482440
answers question: http://stackoverflow.com/q/51481884
upvote count: 5
type: Answer
has body: Maybe numpy is good alternative a=df.values.T a = np.ma.masked_equal(a, 0.0, copy=False) a.min(1) Out[755]: masked_array(data=[1, 2, 3], mask=[False, False, False], fill_value=999999, dtype=int64)
downvote count: 0
score: 5

http://stackoverflow.com/q/51439084
has comment: http://stackoverflow.com/comment/89848349
has comment: http://stackoverflow.com/comment/89849835
duplicate of: http://stackoverflow.com/q/22247957
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/89849790
has comment: http://stackoverflow.com/comment/89849920
tagged with: python-3.x
linked to: http://stackoverflow.com/q/22247957
has title: Can't grab some content using regex
has comment: http://stackoverflow.com/comment/89850525
has comment: http://stackoverflow.com/comment/89848856
has comment: http://stackoverflow.com/comment/89850075
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/89848326
type: AnsweredQuestion
type: Question
has body: I've written some code in python in combination with BeautifulSoup to get some addresses within br tag. If it is about parsing the required text using BeautifulSoup alone, I could have done this using .next_sibling which I've shown below. My intention is to scrape the content within br in combination with BeautifulSoup and re. This is my try so far: import re from bs4 import BeautifulSoup content = """ address BLOCK ANG MO KIO AVE address_one BLOCK 407 ANG MO KIO AVE 10 #01-741 address_two NO. 53 ANG MO KIO AVE 3 AMK HUB#B1-82 """ # soup = BeautifulSoup(content,"lxml") # for addr in soup.find_all("b"): # print(addr.next_sibling.next_sibling) soup = BeautifulSoup(content,"lxml") for addr in soup.find_all(text=re.compile(r" (.*?) ")): print(addr) #It prints nothing, no error either FYI, the commented out portion is just working flawlessly if uncommented. As I'm trying to figure out what would be the usage of re in such cases, I would be very happy if someone provided me with a helping hand.
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/51439351
accepted answer: http://stackoverflow.com/a/51439351
score: 0

http://stackoverflow.com/comment/89895367
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51462779
has text: Check my answer, Let me know about any issues, I have not tested the code.

http://stackoverflow.com/a/51377424
type: Answer
answers question: http://stackoverflow.com/q/51374762
has body: Your problem, in a nutshell, is that you're trying to use the ancient mysql-python library, aka MySQLdb. That library was abandoned around the MySQL 5.1 days, so it doesn't support MySQL 6 and later, and you presumably have MySQL 8.0, so the shared library it's looking for doesn't exist, hence the image not found error. Homebrew does include a mysql@5.5 package, which I think has a dylib with the right name, which might be old enough to work with mysql-python, if you really want to go that way, but it isn't going to be supported. Or you can download MySQL 5.0 or 5.1 source and build it yourself (there are no Mac binaries of anything older than 5.6 that will run on a current macOS), and that will definitely work. But a better solution is to use a library that's still maintained. Unfortunately, there are many choices out there, but I get the impression that most people use one of the three big ones: mysqlclient is a fork of mysql-python, which binds to current versions of the C libraries (brew install mysql or download the installer from the MySQL/Oracle website). PyMySQL is a rewrite in pure Python, which doesn't even need C libraries. MySQL Connector/Python is a new implementation written from scratch by MySQL/Oracle. (You probably want the Oracle installer with this one.) PyMySQL is a much better drop-in replacement than mysqlclient, and it plays nice with everything else in the universe, and it's well-written code that's easy to debug if you have a problem… but it can be pretty slow. And unless you've got a whole mess of existing code to maintain, you usually don't need a perfect drop-in replacement, just something with a pretty-close connect call and support for all of DB-API 2, and mysqlclient covers that.
score: 5
upvote count: 5
downvote count: 0

http://stackoverflow.com/comment/89646063
comment on: http://stackoverflow.com/q/51335422
has text: @Jean-FrançoisFabre `O(n + n)` is the same as `O(n)`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51377077
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51377567
tagged with: python
type: AnsweredQuestion
upvote count: 0
type: Question
possible better answer: http://stackoverflow.com/a/51377409
has body: I learning python3.6 document, and when I look at python scopes and namespaces, I'm try running this code, i found in scope_test() call do_local() print result is different with me thought : def scope_test(): def do_local(): spam = "local spam" def do_nonlocal(): nonlocal spam spam = "nonlocal spam" def do_global(): global spam spam = "global spam" spam = "test spam" do_local() print("After local assignment:", spam) do_nonlocal() print("After nonlocal assignment:", spam) do_global() print("After global assignment:", spam) scope_test() print("In global scope:", spam) I think when call do_local() should be find spam in do_local() scope, because of do_local() scope has spam variable, so: do_local() print('After local assignment:', spam) # local spam unless do_local() not has spam variable, and then can find spam in scope_test() but python Interpreter print result is: do_local() print('After local assignment:', spam) # test spam do_local is similarly with when call do_global(), I think in this scope, bacause global spam is global, so: do_global() print("After global assignment:", spam) # test spam but why result is: do_global() print("After global assignment:", spam) # nonlocal spam
score: -1
has answer: http://stackoverflow.com/a/51377409
answer count: 2
accepted answer: http://stackoverflow.com/a/51377567
has title: running python doc example has don't understand something in python scope and namespace chapter?

http://stackoverflow.com/q/51328197
answer count: 2
tagged with: python
has answer: http://stackoverflow.com/a/51328252
has comment: http://stackoverflow.com/comment/89632266
has title: Avoiding UnicodeEncodeError in python
upvote count: 1
possible better answer: http://stackoverflow.com/a/51328255
has body: I tried to parse an html table into csv using python with a following script: from bs4 import BeautifulSoup import requests import csv csvFile = open('log.csv', 'w', newline='') writer = csv.writer(csvFile) def parse(): html = requests.get('https://en.wikipedia.org/wiki/Comparison_of_text_editors') bs = BeautifulSoup(html.text, 'lxml') table = bs.select_one('table.wikitable') rows = table.select('tr') for row in rows: csvRow = [] for cell in row.findAll(['th', 'td']): csvRow.append(cell.getText()) writer.writerow(csvRow) print(csvRow) parse() csvFile.close() This code outputed a clear formated CSV file with no encoding issues. All was just fine before Enrico Tröger's Geany. My script was unable to write ö into a csv file, so i tried this: csvRow.append(cell.text.encode('ascii', 'replace')) instead of that: csvRow.append(cell.getText()) All was fine, despite the fact that each table cell was nested in b''. So, how can i get a clear formated csv file withous encoding issues(like in the first screenshot) and replaced or ignored all non-unicode symbols(like in the second screenshot) using my scipt?
has answer: http://stackoverflow.com/a/51328255
accepted answer: http://stackoverflow.com/a/51328252
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: unicode
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/q/51412473
score: 1
tagged with: keras
has answer: http://stackoverflow.com/a/51428549
favorite count: 0
type: Question
upvote count: 2
tagged with: python
has body: I'm trying to train a model to predict design patterns from web pages. I'm using coordinates of bounding rects given a bunch of element groupings. Patterns look like this: elementId, width, height, x, y so my target would be the x,y given elementId, width, height. Concretely: [[5, 1.0, 1.0], [4, 1.0, 1.0], [2, 175.0, 65.0], [2, 1.0, 1.0], [4, 1.0, 1.0]] -&gt; [[0.0, 0.0], [0.0, 10.0], [3.0, 0.0], [0.0, 68.0], [0.0, 10.0]] [[2, 14.0, 14.0], [2, 14.0, 14.0], [2, 14.0, 14.0]] -&gt; [[0.0, 3.0], [0.0, 3.0], [0.0, 3.0]] Patterns vary in size so I've padded them with [[0,0,0]]. I currently have about 15k of them, but can get more. I was told that seq2seq with attention is the right model for this job. I've started with https://machinelearningmastery.com/develop-encoder-decoder-model-sequence-sequence-prediction-keras/ and achieved horrendous results. Every seq2seq example i can find (searching for keras or pytorch) is used for translation which is categorical and I'm struggling to find a good regression based example. So my questions are: Is this the right model (encoder/decoder LSTM) for what i'm trying to do? Is there any examples if so?
has title: Is Seq2Seq the right model for my data? Any examples?
tagged with: pytorch
accepted answer: http://stackoverflow.com/a/51428549
tagged with: machine-learning
answer count: 1
downvote count: 1
tagged with: data-science
has comment: http://stackoverflow.com/comment/89797253
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89825439

http://stackoverflow.com/comment/89822185
type: QuestionComment
comment on: http://stackoverflow.com/q/51425552
score: 1
has text: @ncfirth or `np.transpose(table_data)`
type: Comment

http://stackoverflow.com/comment/90255836
type: QuestionComment
has text: I think you can actually use python celery for this.
comment on: http://stackoverflow.com/q/51366197
score: 0
type: Comment

http://stackoverflow.com/comment/133438714
type: Comment
comment on: http://stackoverflow.com/a/74636544
has text: I am having the same issue, @fgd. In GCP I've set `Storage Object Admin` permissions, however I am using Firebase Storage instead.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89636706
type: QuestionComment
score: 0
has text: @AfloroaieRobert But I don't think the OP is likely to understand _why_ he should do that, or maybe even how, without at least some explanation.
comment on: http://stackoverflow.com/q/51330279
type: Comment

http://stackoverflow.com/a/51366335
downvote count: 0
has body: You can do this by converting your DataFrame into a dict and then apply dictionary comprehension to get a list of the variables equal to 3. df_dict = df.to_dict(orient="index") {k: [k1 for (k1, v1) in v.items() if v1 == 3] for (k, v) in df_dict.items()}
score: 4
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51366126
accepted answer of: http://stackoverflow.com/q/51366126
type: Answer
upvote count: 4

http://stackoverflow.com/q/51417246
accepted answer: http://stackoverflow.com/a/51428114
answer count: 2
has comment: http://stackoverflow.com/comment/89808826
has answer: http://stackoverflow.com/a/51419782
downvote count: 0
tagged with: kafka-consumer-api
favorite count: 0
possible better answer: http://stackoverflow.com/a/51419782
tagged with: python
has answer: http://stackoverflow.com/a/51428114
upvote count: 1
has title: Kafka-Python consume last unread message
tagged with: apache-kafka
type: AnsweredQuestion
has body: I have two microservices. MProducer - sending messages to kafka queue MConsumer - reading messages from kafka queue When consumer crashes and restart, I want to continue consuming from last message. consumer = KafkaConsumer(bootstrap_servers='localhost:9092', auto_offset_reset='latest', enable_auto_commit=False)
score: 1
type: Question

http://stackoverflow.com/comment/89723065
score: 0
type: AnswerComment
has text: there might be multiple `AND` which is not in above example, so `k, v = row.split("AND")` may not work. Can we split like `k, v = row.split("type_list")` because that will be there only once
comment on: http://stackoverflow.com/a/51375361
type: Comment

http://stackoverflow.com/a/51353119
answers question: http://stackoverflow.com/q/51353078
score: 2
has body: You'd do the equivalent thing in C with: temp = p - x / y * q; p = q; q = temp; But what's really going on is that the right hand side creates a tuple, with the tuple items being built left to right: t = (q, p - x // y * q) And then that tuple gets unpacked on the left hand side: p = t[0] q = t[1] This use of tuples for essentially parallel assignment comes in very handy. And I'm sure you'll get used to it very quickly. But one thing that may take a little longer to get used to is Python's data model, which works rather differently to C's. You may find this article helpful: Facts and myths about Python names and values, which was written by SO veteran Ned Batchelder.
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/comment/89706595
has text: Thanks to you both. I will try the method CaitLAN describes.
score: 0
comment on: http://stackoverflow.com/a/51367060
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89923261
has text: Okay, I took your code and instead of using session I passed session headers into my request separately and it worked! It just doesn't work when I call same request with my session, which is odd. Marked as answer, thanks!
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51477410

http://stackoverflow.com/comment/89772199
comment on: http://stackoverflow.com/q/51399180
score: 0
type: QuestionComment
type: Comment
has text: Can you analyze cluster resources use in Spark UI ? Do you see something strange (failing tasks, resource peaks, ...) ? Maybe your cluster composition is totally fine and the data is not distributed evenly and one of nodes takes more than the rest and it fails ?

http://stackoverflow.com/comment/89647820
type: QuestionComment
comment on: http://stackoverflow.com/q/51336103
type: Comment
score: 0
has text: If the site is fundamentally broken, all I can come up with is a brute-force search. Figure out a way to partition the result in (say) five sets which are each less than 200 records, perhaps by adding something to the query. Does the site allow you to seach by postal code, for example? (How many ZIP codes are there in Orange County?) Or by truncating a search term, like `lastname=a*` through `lastname=z*`

oop
tags question: http://stackoverflow.com/q/51462482
tags question: http://stackoverflow.com/q/51480392
tags question: http://stackoverflow.com/q/51369440
tags question: http://stackoverflow.com/q/51450293
tags question: http://stackoverflow.com/q/51369643
tag name: oop
tags question: http://stackoverflow.com/q/51461210
tags question: http://stackoverflow.com/q/51391079
tags question: http://stackoverflow.com/q/51360294
tags question: http://stackoverflow.com/q/51423959
tags question: http://stackoverflow.com/q/51328784
tags question: http://stackoverflow.com/q/51446207
tags question: http://stackoverflow.com/q/51438898
tags question: http://stackoverflow.com/q/51384403
tags question: http://stackoverflow.com/q/51389769
tags question: http://stackoverflow.com/q/51479908
tags question: http://stackoverflow.com/q/51382120
tags question: http://stackoverflow.com/q/51324530
tags question: http://stackoverflow.com/q/51460718
tags question: http://stackoverflow.com/q/51378776
tags question: http://stackoverflow.com/q/51390918
tags question: http://stackoverflow.com/q/51464548
type: Tag
tags question: http://stackoverflow.com/q/51432300
tags question: http://stackoverflow.com/q/51353218

http://stackoverflow.com/comment/89748171
type: QuestionComment
score: 0
has text: Not everyone that knows python will know matlab and vice-versa. Post a sample input/output or a [mcve]
comment on: http://stackoverflow.com/q/51388178
type: Comment

http://stackoverflow.com/a/51327154
upvote count: 4
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51327113
score: 4
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51327113
has body: Check reindex df_out_desired = df_in.reindex(indices_needed_list) df_out_desired Out[177]: A B 1 2 20 2 3 30 3 4 40 3 4 40 3 4 40
type: Answer
has comment: http://stackoverflow.com/comment/129609174

http://stackoverflow.com/comment/89650002
type: Comment
type: QuestionComment
has text: Review the following: https://kivy.org/docs/guide/events.html, As noted tasks such as repainting (when you put a new text is repainted) is performed when synchronous tasks do not occupy the loop.
score: 0
comment on: http://stackoverflow.com/q/51337666

http://stackoverflow.com/comment/89823630
has text: @MoxieBall yes, piece by piece, while he's appending the individual codes - then the string being held in memory never gets really big. Actually it can be done with integer arithmetic too instead of strings, then there is no conversion at all any more
comment on: http://stackoverflow.com/q/51425638
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89875343
type: Comment
comment on: http://stackoverflow.com/a/51451948
score: 2
has text: FWIW "SF 502085" appears to refer to https://bugs.python.org/issue502085 ... Maybe this bug tracker was hosted on Source Forge at the time?
type: AnswerComment

http://stackoverflow.com/a/53679646
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51371219
has body: This doesn't exactly address the question, but this technique is applicable. I used a variation on Ykh's answer that allows the same permission class to be used broadly across many views which display a variety of different models. In my view class I added an attribute to distinguish the originating view, thus allowing the appropriate object comparison to determine permissions # views.py class SomeView(ListAPIView): permission_classes = (IsPermd, ) is_some_view = True class SomeOtherView(RetrieveAPIView permission_classes = (IsPermd, ) is_some_other_view = True # permissions.py class IsPermd(BasePermission): def has_object_permissions(self, request, view, obj): if hasattr(view, 'is_some_view'): # whatever special considerations if hasattr(view, 'is_some_other_view'): # whatever other special considerations This feels a little clunky, but until I find a better way I'll stick with it.

http://stackoverflow.com/comment/89626132
has text: actually, I am using python 2.7
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51325541
type: Comment

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

http://stackoverflow.com/q/51330017
upvote count: 1
tagged with: python-3.x
downvote count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89636235
score: 1
has title: Print statistics for every character in a file in python
has comment: http://stackoverflow.com/comment/89636016
has answer: http://stackoverflow.com/a/51330148
type: Question
has body: What I am trying to do is to take a file's data and print out the percentage of each character in file but I don't want to use duplicates. I need to print just one character with a relevant percentage point. Below is the snippet. for all_char in text: char_counter = 0 if count_char(text, all_char) &gt; 1: perc1 = 100 / len(text) * count_char(text, all_char) print("{0} - {1}%".format(all_char, round(perc1, 2))) with open(filename, "w") as w: #&lt;-------- I need a code to remove a single character w.truncate(char_counter) char_counter += 1 elif count_char(text, all_char) == 1: perc2 = 100 * count_char(text, all_char) / len(text) print("{0} - {1}%".format(all_char, round(perc2, 2))) char_counter += 1 Above I made a variable called char_counter which will be increased after every iteration and the function called count_char will tell, how many times each character is used in file and if that number is higher than 1 the character must be deleted from the file means that it will print only once. This is the base idea but the code gives me an error.
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/89699759
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51363727
has text: Your `filename` string is bad; make it a raw string to avoid the backslashes being interpreted as escapes.

http://stackoverflow.com/q/51428388
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89828196
accepted answer: http://stackoverflow.com/a/51428489
tagged with: tkinter
has comment: http://stackoverflow.com/comment/89828095
type: Question
has comment: http://stackoverflow.com/comment/89828063
has comment: http://stackoverflow.com/comment/89828031
has body: Currently receiving an error when trying to display Database data on tkinter GUI. The error is Method is not iterable, i get what the error means but have no idea as to how i would go about fixing it. Here is the class i am returning all the infromation from: class Database: def __init__(self, master): self.master = master self.conn = sqlite3.connect(':memory:') self.c = self.conn.cursor() self.c.execute("""CREATE TABLE Employees ( FirstName text, Surname text, Age Integer, Postcode VARCHAR, Wage Integer, Email VARCHAR, Hours Integer )""") #Creation of Database self.conn.commit() self.addEmployees() # running the function, need to fix this, Only run when "add employee" button is pressed! def ReadData(self): self.c.execute("SELECT * FROM Employees") return self.c.fetchall() # this reads and returns all the data. def addEmployees(self): # This function adds all the info the users have put into the entry in new EmployeeEmail self.c.execute("INSERT INTO Employees VALUES (:FirstName, :Surname, :Age, :Postcode, :Wage, :Email, :Hours)", {'FirstName':"Sharjeel" , 'Surname':"Jan" , 'Age':"21" , 'Postcode':"aa" , 'Wage':"1220000" , 'Email':"aa" , 'Hours':"230"}) self.conn.commit() Fairly simple, here is where im trying to actually display the data when a button is pressed: class MainPageGUI: def __init__(self, master): self.master = master self.master.title("Jans Corp") self.master.configure(background='lightgrey') self.master.geometry("1200x800") def DisplayData(self): self.TheData = Database(self.master) self.ReturnedData = getattr(self.TheData, 'ReadData') &lt;------ Here is where i am receiving the error. for data in enumerate(self.ReturnedData): tk.Label(self.master, text = data[0]).grid(row = 1, column = 0) tk.Label(self.master, text = data[1]).grid(row = 1, column = 1) tk.Label(self.master, text = data[2]).grid(row = 1, column = 2) tk.Label(self.master, text = data[3]).grid(row = 1, column = 3) tk.Label(self.master, text = data[4]).grid(row = 1, column = 4) tk.Label(se…
score: 0
has answer: http://stackoverflow.com/a/51428489
has comment: http://stackoverflow.com/comment/89828020
answer count: 1
has comment: http://stackoverflow.com/comment/89828150
has title: 'Method' Object not iterable error
tagged with: python-3.x
tagged with: python
tagged with: tkinter-entry

http://stackoverflow.com/a/51449942
score: 0
has body: First of all, the fact that page has multiple elements with the same ID is a bug on its own. The whole point of ID is to be unique for each element on the page. According to HTML specs: id = name This attribute assigns a name to an element. This name must be unique in a document. A lengthy discussion is here. Since ID is supposed to be unique, most (all?) implementations of Selenium will only have function to look for one element with given ID (e.g. find_element_by_id). I have never seen a function for finding multiple elements by ID. So you cannot use ID as your locator directly, you need to use one of the existing functions that allows location of multiple elements, and use ID as just some attribute which allows you to select a group of elements. Your choices are: find_elements_by_xpath find_elements_by_css_selector For example, you could change your search like this: links = driver.find_elements_by_xpath("//a[@id='LinkNoticia']"); That would give you the whole set of links, and you'd need to loop through them to retrieve the actual link (href). Note that if you just click on each link, you navigate away from the page and references in links will no longer be valid. So instead you can do this: Build list of hrefs from the links: hrefs=[] for link in links: hrefs.append(link.get_attribute("href")) Navigate to eachhref to check its title: for href in hrefs: driver.get(href); title = driver.find_element_by_id("cuDetalle_cuTitular_tituloNoticia") # etc
has comment: http://stackoverflow.com/comment/89871074
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89871417
has comment: http://stackoverflow.com/comment/89871467
type: Answer
answers question: http://stackoverflow.com/q/51448711
accepted answer of: http://stackoverflow.com/q/51448711

http://stackoverflow.com/comment/128952253
comment on: http://stackoverflow.com/q/51335298
score: 1
type: Comment
type: QuestionComment
has text: @Stonecraft - We are in the process of updating the documentation, e.g., [here](https://docs.sqlalchemy.org/en/14/orm/backref.html)

http://stackoverflow.com/comment/89856697
has text: It's better to use [PyYAML](https://pyyaml.org/wiki/PyYAMLDocumentation) for parsing the input, given its structure.
type: Comment
score: 2
comment on: http://stackoverflow.com/a/51442805
type: AnswerComment

http://stackoverflow.com/q/51455622
score: 7
has comment: http://stackoverflow.com/comment/89995596
tagged with: image-processing
possible better answer: http://stackoverflow.com/a/51540436
has comment: http://stackoverflow.com/comment/89891982
has answer: http://stackoverflow.com/a/51540436
has comment: http://stackoverflow.com/comment/90074465
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/89994471
has comment: http://stackoverflow.com/comment/90048312
downvote count: 0
has answer: http://stackoverflow.com/a/51572486
has comment: http://stackoverflow.com/comment/90047952
has body: Context: I am performing Object Localisation and wanting to implement an Inhibition of Return mechanism (i.e. drawing a black cross on the image where the red bounding box is after a trigger action.) Problem: I do not know how to accurately scale the bounding box (red) in relation to the original input (init_input). If this scaling is understood, then the black cross should be accurately placed in the middle of the red bounding box. My current code for this function is as follows: def IoR(b, init_input, prev_coord): """ Inhibition-of-Return mechanism. Marks the region of the image covered by the bounding box with a black cross. :param b: The current bounding box represented as [x1, y1, x2, y2]. :param init_input: The initial input volume of the current episode. :param prev_coord: The previous state's bounding box coordinates (x1, y1, x2, y2) """ x1, y1, x2, y2 = prev_coord width = 12 x_mid = (b[2] + b[0]) // 2 y_mid = (b[3] + b[1]) // 2 # Define vertical rectangle coordinates ver_x1 = int(((x_mid) * IMG_SIZE / (x2 - x1)) - width) ver_x2 = int(((x_mid) * IMG_SIZE / (x2 - x1)) + width) ver_y1 = int((b[1]) * IMG_SIZE / (y2 - y1)) ver_y2 = int((b[3]) * IMG_SIZE / (y2 - y1)) # Define horizontal rectangle coordinates hor_x1 = int((b[0]) * IMG_SIZE / (x2 - x1)) hor_x2 = int((b[2]) * IMG_SIZE / (x2 - x1)) hor_y1 = int(((y_mid) * IMG_SIZE / (y2 - y1)) - width) hor_y2 = int(((y_mid) * IMG_SIZE / (y2 - y1)) + width) # Draw vertical rectangle cv2.rectangle(init_input, (ver_x1, ver_y1), (ver_x2, ver_y2), (0, 0, 0), -1) # Draw horizontal rectangle cv2.rectangle(init_input, (hor_x1, hor_y1), (hor_x2, hor_y2), (0, 0, 0), -1) The desired effect can be seen below: Note: I believe the complexity in this problem arises due to the image being resized (to 224, 224, 3) each time I take an action (and consequently move onto the next state). Therefore, the "anchor" to determine the scaling must be extracted from the previous states scaling, which is shown in the following code: def next_sta…
has comment: http://stackoverflow.com/comment/89995639
favorite count: 0
accepted answer: http://stackoverflow.com/a/51572486
tagged with: python
upvote count: 7
tagged with: opencv
type: AnsweredQuestion
has title: Drawing a cross on an image with OpenCV
has comment: http://stackoverflow.com/comment/89884967

http://stackoverflow.com/comment/89781601
type: QuestionComment
has text: So is `amounts` a dictionary, or a list of dictionaries?
comment on: http://stackoverflow.com/q/51405006
score: 0
type: Comment

http://stackoverflow.com/comment/89730001
has text: @Anonymousmiliana: good one too. we could make a list of all possible ways
comment on: http://stackoverflow.com/a/51379203
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51392944
type: Question
has answer: http://stackoverflow.com/a/51393786
has answer: http://stackoverflow.com/a/51393027
tagged with: dataframe
has title: Pandas multiple column intersection ignoring na values
possible better answer: http://stackoverflow.com/a/51393027
score: 0
answer count: 2
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51393786
tagged with: python
has body: I have a data frame with multiple columns, data={'NAME':['A','B','C'], 'A':[[1,2,3],[np.nan],[3,4,5]], 'B':[[2,3,4],[3,4,5],[np.nan]], 'C':[[2,4],[3],[6,7]] } df=pd.DataFrame(data) df=df'A','B','C' I can take the intersection of columns using, df.assign(D=df.apply( lambda x: list(set(x.A).intersection(set(x.B)).intersection(set(x.C))), axis=1)) This creates a column D with, D [2] [] [] But I want to ignore cells with na values and get the intersection, Expected output is, D [2] [3] [] How to do this? Thanks for the help.
type: AnsweredQuestion

http://stackoverflow.com/q/51354505
favorite count: 0
tagged with: python-3.x
tagged with: tuples
has answer: http://stackoverflow.com/a/51354626
answer count: 5
has body: So I'm trying to get my count to add 1 whenever it sees the yea in the tuple. my issue is it still returns 0. Should I use a for loop to go through each item? year = input ("enter a year") count = 0 t = (("Steve"), ("Carell"), (16, "August", 1962), "Actor", ("Concord", "Massachusetts")) if year in t: count += 1 print(count) print (t) #just a check expected results input: 1962 output: 1
has comment: http://stackoverflow.com/comment/89681544
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89681605
type: AnsweredQuestion
score: 1
possible better answer: http://stackoverflow.com/a/51354845
has answer: http://stackoverflow.com/a/51354845
accepted answer: http://stackoverflow.com/a/51354626
type: Question
has title: finding a element within a tuple
has answer: http://stackoverflow.com/a/51356105
has answer: http://stackoverflow.com/a/51355165
has comment: http://stackoverflow.com/comment/89681633
downvote count: 0
has answer: http://stackoverflow.com/a/51354625
has comment: http://stackoverflow.com/comment/89681582

http://stackoverflow.com/q/51402053
type: Question
has answer: http://stackoverflow.com/a/56815975
has comment: http://stackoverflow.com/comment/89775003
tagged with: python
score: -2
has answer: http://stackoverflow.com/a/51402290
downvote count: 2
answer count: 2
tagged with: tensorflow
has body: Please help I am able to import tensortflow when in python 2.7 but when importing into python 3.5, it fails with: ImportError: No module named 'tensorflow'. the {pip show tensorflow} command shows the following: Name: tensorflow Version: 1.9.0 Summary: TensorFlow is an open source machine learning framework for everyone. Home-page: https://www.tensorflow.org/ Author: Google Inc. Author-email: opensource@google.com License: Apache 2.0 Location: /usr/local/lib/python2.7/dist-packages Requires: setuptools, astor, protobuf, gast, enum34, six, wheel, absl-py, backports.weakref, tensorboard, termcolor, numpy, grpcio, mock Required-by:
has comment: http://stackoverflow.com/comment/89774946
type: UnansweredQuestion
has title: Cannot import tensorflow to python 3.5 (imports successfully in 2.7)
upvote count: 0
favorite count: 0
tagged with: importerror

http://stackoverflow.com/q/51453590
type: UnansweredQuestion
tagged with: python
tagged with: list
answer count: 0
upvote count: 1
linked to: http://stackoverflow.com/q/6294179
has comment: http://stackoverflow.com/comment/89876796
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89876785
has title: Find place of all same objects in list
tagged with: python-2.7
score: 0
duplicate of: http://stackoverflow.com/q/6294179
favorite count: 0
has body: How i can find all place of a same objects in list like : &gt;&gt;&gt;a=['a','a','b','c','a'] &gt;&gt;&gt;findplace('a') &gt;&gt;&gt;[0,1,4]

http://stackoverflow.com/comment/89776352
comment on: http://stackoverflow.com/q/51399274
score: 0
type: Comment
type: QuestionComment
has text: @Sunreef Nah, this is all the task I need the script to do, just output images, 10 a second, between a set of timecodes in a video. I wont be processing them afterwards, just a simple save an image.

http://stackoverflow.com/a/51469764
has comment: http://stackoverflow.com/comment/89917753
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89917493
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/89917567
upvote count: 2
answers question: http://stackoverflow.com/q/51466462
has body: ani.to_html5_video() creates a file. For this file to be created, all frames need to be known in advance. Hence the animation is run once in completeness, then those frames are saved and converted to html5 video. If you want to see the animation live, you may use the %matplotlib notebook backend without saving the animation. As for the 1000 frames, you are setting that number yourself in the third argument to FuncAnimation, np.arange(1,1000). Either remove that argument or chose a different number here, e.g. frames =20000.
accepted answer of: http://stackoverflow.com/q/51466462
has comment: http://stackoverflow.com/comment/89911725

http://stackoverflow.com/a/51414809
has body: Because to build scipy wheel you need to have numpy installed. However, only numpy wheel build was complete by the time pip attempts to build scipy wheel. You will have to install the dependencies first. There are multiple ways to do this. 1) Use a shell script like the one below, copy it and RUN it instead of RUN pip install -r requirements.txt: #!/bin/sh while read module; do pip install $module done &lt; requirements.txt 2) Install scipy in a seperate RUN command. 3) apk add py-numpy@community as discussed in this answer.
answers question: http://stackoverflow.com/q/51399515
type: Answer
has comment: http://stackoverflow.com/comment/98349336
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/98576206
has comment: http://stackoverflow.com/comment/89820281
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51399515

http://stackoverflow.com/q/51413968
has body: I'm following a tutorial and it has this code. I understood why I have used set() but I don't get the use of putting an X in issubset(). Is the last x representing that I'm subsetting first x i.e. lambda x:? Kindly help. lambda_x = lambda x: set(['Romance','Comedy', 'Action', 'Thriller']).issubset(x)
type: UnansweredQuestion
upvote count: 1
tagged with: lambda
has answer: http://stackoverflow.com/a/51414046
score: 1
has title: Why there should be an x in .issubset(x) while using this lambda function?
type: Question
has answer: http://stackoverflow.com/a/51414021
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89799516
has answer: http://stackoverflow.com/a/51414068
tagged with: python
has answer: http://stackoverflow.com/a/51414036
answer count: 4

http://stackoverflow.com/comment/89704986
type: QuestionComment
comment on: http://stackoverflow.com/q/51365581
type: Comment
has text: Your link to the equations didn't come through. Try again.
score: 0

http://stackoverflow.com/a/51479303
has body: There's no technical reason why you should't use it, yet I'd strongly suggest to get rid of habit of naming variables like i or f or so, instead of number_of_beds_in_reserved_room (or camelCase if you prefer so :). By keeping bad habits with short variable names you save nothing nowadays, yet risk a lot of stepping of variable name shadowing which may be pretty damn hard to debug. RAM is cheap. Your time is not.
type: Answer
accepted answer of: http://stackoverflow.com/q/51479235
has comment: http://stackoverflow.com/comment/89928880
score: 0
answers question: http://stackoverflow.com/q/51479235
type: AcceptedAnswer

http://stackoverflow.com/q/51457942
tagged with: python
has answer: http://stackoverflow.com/a/51458209
has title: Regression plot is wrong (python)
accepted answer: http://stackoverflow.com/a/51458209
has comment: http://stackoverflow.com/comment/89885212
has comment: http://stackoverflow.com/comment/89885345
linked to: http://stackoverflow.com/q/37414916
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/89885370
type: Question
type: AnsweredQuestion
score: -1
has body: So my program reads MPG vs weight relationship and draws a graph of what it is suppose to look like but as you can see the graph is not looking right. import numpy as np import pandas as pd import matplotlib.pyplot as plt #read txt file dataframe= pd.read_table('auto_data71.txt',delim_whitespace=True,names=['MPG','Cylinder','Displacement','Horsepower','Weight','acceleration','Model year','Origin','Car Name']) dataframe.dropna(inplace=True) #filter the un-necessary columns X = dataframe.iloc[:,4:5].values Y = dataframe.iloc[:,0:1].values #scale data from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() sc_Y= StandardScaler() X = sc_X.fit_transform(X) Y = sc_Y.fit_transform(Y) #split data into train and test set from sklearn.model_selection import train_test_split x_train,x_test,y_train,y_test = train_test_split(X,Y,test_size=0.2) #create model from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression poly_reg = PolynomialFeatures(degree=2) poly_X = poly_reg.fit_transform(x_train) poly_reg.fit(poly_X,y_train) regressor2= LinearRegression() regressor2.fit(poly_X,y_train) #graph result = regressor2.predict(poly_X) plt.scatter(x_train,y_train,color='red') plt.plot(x_train, result,color='blue') plt.show() the output is this: As you can see the regression line does not look right. Any help will be much appreciated. #auto_data.txt(part of data...) ****NOTE:i am only using weight and mpg column for this code file(mpg,cylinder,distance,horsepower,weight,acceleration,year,origin,name) 27.0 4. 97.00 88.00 2130. 14.5 71. 3. "datsun pl510" 28.0 4. 140.0 90.00 2264. 15.5 71. 1. "chevrolet vega 2300" 25.0 4. 113.0 95.00 2228. 14.0 71. 3. "toyota corona" 25.0 4. 98.00 NA 2046. 19.0 71. 1. "ford pinto" NA 4. 97.00 48.00 1978. 20.0 71. 2. "volkswagen super beetle 117" 19.0 6. 232.0 100.0 2634. 13.0 71. 1. "amc gremlin" 16.0 6. 225.0 105.0 3439. 15.5 71. 1. "plymouth satellite custom" 17.0 6. 250.0 100.0 3329. 15.5 71. 1. …
tagged with: pandas
answer count: 1
tagged with: scikit-learn
duplicate of: http://stackoverflow.com/q/37414916
favorite count: 0
has comment: http://stackoverflow.com/comment/89885587
has comment: http://stackoverflow.com/comment/89886011
has comment: http://stackoverflow.com/comment/89885964

http://stackoverflow.com/comment/89729886
has text: Why is it that way..?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51378942

http://stackoverflow.com/a/51397507
upvote count: 1
type: Answer
downvote count: 0
score: 1
has body: There should be no indentation for the function name in the next line after @staticmethod &gt;class Employee: &gt; @staticmethod &gt; def dayIsWorkday(day): &gt; if day.weekday() == 5 or day.weekday() == 6: &gt; return False &gt; return True &gt; &gt; &gt;import datetime &gt;my_date = datetime.date(2018, 12, 5) &gt; &gt;print(Employee.dayIsWorkday(my_date))
answers question: http://stackoverflow.com/q/51397439

http://stackoverflow.com/a/51335820
answers question: http://stackoverflow.com/q/51335411
has body: The variables 'version2' and 'version3' will result in a syntax error. This syntax error is caused by the fact that Python does not know of any (number) type that has several points in its value. In essence you are trying to use certain types in a way that they are not meant to be used. More specifically the floating point number is not suitable for your goals. As the name suggests a floating point number, only contains one point and that point can be placed anywhere between its digits (floating). My advice would be to create your own type/class. This would enable you to store the version number in a way that allows for easy modification of its values and better separation of concerns in your code (i.e. that each part of your code is only concerned with one thing). Example class VersionNumber: """Represents a version number that can contain parts (major, minor, etc).""" def __init__(self, *argv): """This is the constructor, i.e. a function that is called when you create a new VersionNumber. The '*argv' allows the user of this class to give a variable amount of arguments. This is why you can have a version number with only 1 number, and one with 4. The '*argv' is iterable.""" #Create a class specific field, that stores all the version number parts in a list. self.Parts = [] #Fill it with the supplied arguments. for part in argv: self.Parts.append(part) def __repr__(self): """This function is called when the VersionNumber needs to be displayed in the console""" return str(self) def __str__(self): """This function is called when the VersionNumber is parsed to a string""" return '.'.join(map(str,self.Parts)) def incrementVersion(self, position, incrementAmount): """This function allows you to increment the version number. It does this by adjusting the list we have set in the constructor.""" self.Parts[position] += incrementAmount version1 = VersionNumber(1, 23, 45, 0) print(version1) #Position -1, takes the last (most right) version number part from the version number. …
score: 0
type: Answer

http://stackoverflow.com/comment/89825674
has text: Python 2.x or 3.x?
type: Comment
comment on: http://stackoverflow.com/q/51427261
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89763949
has text: @pyd You're welcome. In fact, if there's always a `'\n'` before each date/time, you might as well use `str.split('\n')`` to get what you want.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51395834
type: Comment

http://stackoverflow.com/comment/89637867
has text: You still haven't provided an example of input and expected output. Also, you included the tag "dynamic-programming", even though this problem is not an example of dynamic programming.
comment on: http://stackoverflow.com/q/51331018
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/51398217
score: 0
answers question: http://stackoverflow.com/q/51393816
type: Answer
has body: In order to vectorize this fully you have to adapt the function f so that it works on the whole array A. In your example you want the sum of x*sin(x) across all rows in the array. The multiplication and sin function works elementwise so doesn't need to be changed. But you have to specify to np.sum that you want to sum across rows; this is done by setting the 'axis=-1'. def f_vec(x): return np.sum(x*np.sin(x), axis=-1) You can pass the whole array A to this function and get X as before: In [39]: X_vec = f_vec(A) In [40]: np.all(X_vec == X) Out[40]: True

http://stackoverflow.com/a/51486188
type: Answer
has body: I finally was able to make this work. I've updated ajax to below: var answers = response; $('#messageText').val(); I was also printing the response function, instead of returning it; reason I am seeing the response in the console and not in the view. This was the main culprit.
score: 0
answers question: http://stackoverflow.com/q/51394093

http://stackoverflow.com/comment/89870366
comment on: http://stackoverflow.com/q/51448711
type: QuestionComment
type: Comment
has text: @JeffC: not entirely his fault, that page is f... umm... uses non-standard HTML.
score: 0

http://stackoverflow.com/comment/89689336
comment on: http://stackoverflow.com/q/51358494
type: Comment
type: QuestionComment
score: 1
has text: You can use [`$map`](https://docs.mongodb.com/manual/reference/operator/aggregation/map/) aggregation to iterate over the array and can easily add the fields you want

http://stackoverflow.com/a/51388359
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51388281
type: Answer
accepted answer of: http://stackoverflow.com/q/51388281
has body: You need to set the seed import numpy as np np.random.seed(42) print(np.random.rand()) # will return same result so long as seed is set to 42

http://stackoverflow.com/comment/89863300
type: AnswerComment
has text: ValueError: invalid literal for int() with base 10: '#VALUE!' The problem is its not converting it due to this error.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51446536

http://stackoverflow.com/q/51470071
has title: drop duplicates pandas dataframe
has answer: http://stackoverflow.com/a/51470114
upvote count: 2
has body: I am getting an error message when using drop_duplicates to drop duplicate columns from my dataframe. ValueError: Buffer has wrong number of dimensions (expected 1, got 2) Below is a min example (notice that I don't have duplicate column names here, since that column won't be added then, so I var1 would be called var0 in my actual dataframe) dict1 = [{'var0': 0, 'var1': 0, 'var2': 2}, {'var0': 0, 'var1': 0, 'var2': 4}, {'var0': 0, 'var1': 0, 'var2': 8}, {'var0':0, 'var1': 0, 'var2': 12},] df = pd.DataFrame(dict1, index=['s1', 's2','s1','s2']) df.T.drop_duplicates().T
accepted answer: http://stackoverflow.com/a/51470114
score: 2
type: AnsweredQuestion
tagged with: duplicates
type: Question
answer count: 1
downvote count: 0
favorite count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/89909553
tagged with: python

http://stackoverflow.com/comment/138242563
type: Comment
comment on: http://stackoverflow.com/a/51373548
has text: Update for selenium 4.18.1 driver.find_element(by=By.XPATH, value="//a[contains(@href, '/mathscinet/search/mscdoc.html')]").text
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89635514
comment on: http://stackoverflow.com/a/51329895
type: AnswerComment
score: 0
type: Comment
has text: thanks, but thats just not possible for me. i can't code in C and i need definitely python run do_stuff_before_python_terminates() on every sigterm or sigint (shutdown or ctr+l).

http://stackoverflow.com/q/51390141
favorite count: 0
has comment: http://stackoverflow.com/comment/89752744
tagged with: python
type: AnsweredQuestion
has title: SQLAlchemy returns weird data
downvote count: 0
has body: I am trying to export a date from a table. I want to just pull the raw created object out. I am running the query below: return model.Session.query(cls).filter(cls.issue_id == issue_id).order_by(desc("created")).first() But it returns the entire record as so and I have no idea how to export created out. &lt;IssueComment id=32 comment=ay user_id=578042a3-d879-4b32-96a9-10f9aabe152c issue_id=19 created=2018-07-17 20:17:09.653809 visibility=visible abuse_status=0&gt; If i try calling created in cls.created as so return model.Session.query(cls.created).filter(cls.issue_id == issue_id).order_by(desc("created")).first() and it exports a weird datetime version. I just want the raw version (datetime.datetime(2018, 7, 17, 20, 17, 9, 653809),) How can i export the value for created out as the raw string?
score: 1
has comment: http://stackoverflow.com/comment/89754565
possible better answer: http://stackoverflow.com/a/51390310
has comment: http://stackoverflow.com/comment/89760911
type: Question
accepted answer: http://stackoverflow.com/a/51394413
has comment: http://stackoverflow.com/comment/89771134
tagged with: sqlalchemy
has answer: http://stackoverflow.com/a/51394413
answer count: 2
has answer: http://stackoverflow.com/a/51390310
upvote count: 1

http://stackoverflow.com/a/56337662
score: 2
downvote count: 0
type: Answer
upvote count: 2
has body: parmap author here By default, both in multiprocessing and in parmap, tasks are divided in chunks and chunks are sent to each multiprocessing process (see the multiprocessing documentation). The reason behind this is that sending tasks individually to a process would introduce significant computational overhead in many situations. The overhead is reduced if several tasks are sent at once, in chunks. The number of tasks on each chunk is controlled with chunksize in multiprocessing (and pm_chunksize in parmap). By default, chunksize is computed as "number of tasks"/(4*"pool size"), rounded up (see the multiprocessing source code). So for your case, 1000/(4*4) = 62.5 -> 63 tasks per chunk. If, as in your case, many computationally expensive tasks fall into the same chunk, that chunk will take a long time to finish. One "cheap and easy" way to workaround this is to pass a smaller chunksize value. Note that using the extreme chunksize=1 may introduce undesired larger cpu overhead. A proper queuing system as suggested in other answers is a better solution on the long term, but maybe an overkill for a one-time problem.
answers question: http://stackoverflow.com/q/51403964

http://stackoverflow.com/comment/89934299
type: QuestionComment
comment on: http://stackoverflow.com/q/51481884
score: 0
type: Comment
has text: Possible duplicate of [Extracting the n-th maximum/minimum value in Pandas DataFrame](https://stackoverflow.com/questions/48026397/extracting-the-n-th-maximum-minimum-value-in-pandas-dataframe)

http://stackoverflow.com/comment/89668937
comment on: http://stackoverflow.com/q/51348008
has text: Possible duplicate of [How to get full path of current file's directory in Python?](https://stackoverflow.com/questions/3430372/how-to-get-full-path-of-current-files-directory-in-python)
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51341226
upvote count: 3
type: Question
score: 3
has title: Cannot access to_attr attribute in annotate()
has comment: http://stackoverflow.com/comment/89656055
has body: I have the following code: queue = Queue_item.objects.prefetch_related(Prefetch('queue_item_id', queryset=Platform.objects.all().order_by('-time'), to_attr='platforms')) queue = queue.annotate(first_time=Min('platforms__time')).order_by('first_time') When I run it, I get an error message that says that in the queue.annotate, it cannot find platforms, even though I set it right before in the prefetch_related. What am I missing? [EDIT] #models.py import django from django.db import models class Queue_item(models.Model): caption = models.TextField(max_length=1000) path_to_picture = models.CharField(max_length=255) def create(self): self.save() def __str__(self): return self.caption.split(' ')[0] class Platform(models.Model): queue_item_id = models.ForeignKey( Queue_item, on_delete=models.CASCADE ) time = models.DateTimeField(default=django.utils.timezone.now) INSTAGRAM = 'IG' FACEBOOK = 'FB' TWITTER = 'TW' PLATFORM_CHOICES = ( (INSTAGRAM, 'Instagram'), (FACEBOOK, 'Facebook'), (TWITTER, 'Twitter'), ) platform = models.CharField( max_length=2, choices=PLATFORM_CHOICES, default=INSTAGRAM ) Thanks!
tagged with: prefetch
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89656161
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51341791
tagged with: django
tagged with: python
tagged with: annotate
has comment: http://stackoverflow.com/comment/89656095

http://stackoverflow.com/comment/89683062
type: Comment
has text: @coldspeed posted! I hope it explains fully how I ran the tests. Do let me know if it was done correctly.
comment on: http://stackoverflow.com/a/51355115
score: 0
type: AnswerComment

http://stackoverflow.com/q/51371030
type: AnsweredQuestion
has title: Uploading .csv to Google Sheets via Gspread
upvote count: 1
type: Question
tagged with: google-sheets-api
accepted answer: http://stackoverflow.com/a/51371961
has body: I am using gspread to refresh a worksheet in Google Sheets with data from a .CSV file. As much as I've looked around the web, I'm having a hard time finding what I think should be a clean answer to my question. I have the .CSV file in my project directory. Here's my code thus far: import gspread from oauth2client.service_account import ServiceAccountCredentials import csv scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope) client = gspread.authorize(creds) sheet = client.open_by_key('Spreadsheet Key') worksheet = sheet.worksheet('Worksheet Name') worksheet.clear() At this point, I'm not sure what method I should use to mass-upload all the data in the .CSV. I've read that .update_cells() in gspread will only use a single call to the Google Sheets API and is the fastest method, so my question is this: Using .update_cells(), how can I iterate through my .CSV to be able to post to Sheets? Some info about my .CSV file is that it has 9 columns, but I need the code to handle any changes in the quantity of rows. Any help is greatly appreciated!
answer count: 1
downvote count: 0
score: 1
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/51371961
tagged with: python
tagged with: gspread

http://stackoverflow.com/a/51452385
has body: How about this. In [15]: data.groupby(['id']).apply(lambda d: pd.Series(np.arange(len(d))).apply(lambda x: d'seed', 'time_spent'.iloc[:x+1].to_dict())) Out[15]: id 1 0 {'seed': {0: '1'}, 'time_spent': {0: 0.3}} 1 {'seed': {0: '1', 1: '2'}, 'time_spent': {0: 0... 2 {'seed': {0: '1', 1: '2', 2: '3'}, 'time_spent... 3 {'seed': {0: '1', 1: '2', 2: '3', 3: '4'}, 'ti... 4 {'seed': {0: '1', 1: '2', 2: '3', 3: '4', 4: '... 2 0 {'seed': {5: '10'}, 'time_spent': {5: 10.1}} 1 {'seed': {5: '10', 6: '11'}, 'time_spent': {5:... 2 {'seed': {5: '10', 6: '11', 7: '12'}, 'time_sp... 3 {'seed': {5: '10', 6: '11', 7: '12', 8: '13'},... dtype: object additionally, you can modify the parameter of .to_dict() method to change the output dict style, refer to: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_dict.html or maybe this is what you want: In [18]: data.groupby(['id']).apply(lambda d: pd.Series(np.arange(len(d))).apply(lambda x: dict(zip(d['seed'].iloc[:x+1], d['time_spent'].iloc[:x+1])))) Out[18]: id 1 0 {'1': 0.3} 1 {'1': 0.3, '2': 0.4} 2 {'1': 0.3, '2': 0.4, '3': 0.5} 3 {'1': 0.3, '2': 0.4, '3': 0.5, '4': 0.6} 4 {'1': 0.3, '2': 0.4, '3': 0.5, '4': 0.6, '5': ... 2 0 {'10': 10.1} 1 {'10': 10.1, '11': 11.1} 2 {'10': 10.1, '11': 11.1, '12': 12.1} 3 {'10': 10.1, '11': 11.1, '12': 12.1, '13': 13.1} dtype: object
answers question: http://stackoverflow.com/q/51452281
score: 0
type: Answer

http://stackoverflow.com/q/51449543
accepted answer: http://stackoverflow.com/a/51449602
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/51449678
has comment: http://stackoverflow.com/comment/89869681
has comment: http://stackoverflow.com/comment/89869881
type: Question
has body: I have multiple csv files in a folder (file1, file2, file3, file4, file5,....) I only know how to import one file, run the command and output the converted file as shown in below code. I would like to run the command in multiple csv files at once. Can someone please help? convert.py: import pandas as pd import numpy as np #read file df = pd.read_csv("file1.csv") #make conversion df['Time taken'] = pd.to_datetime(df['Time taken']) df['Time taken'] = df['Time taken'].dt.hour + df['Time taken'].dt.minute / 60 #output file df.to_csv('file1_converted.csv', index = False) I started with a code as shown below but it gave only one output(*.csv) from one random csv file. I would like separate output for each file. import glob import pandas as pd import numpy as np files = glob.glob('folder/*.csv') for file in files: df = pd.read_csv(file) #make conversion df['Time taken'] = pd.to_datetime(df['Time taken']) df['Time taken'] = df['Time taken'].dt.hour + df['Time taken'].dt.minute / 60 #output file df.to_csv('*.csv', index = False)
has answer: http://stackoverflow.com/a/51449653
tagged with: pandas
downvote count: 0
possible better answer: http://stackoverflow.com/a/51449621
favorite count: 0
has answer: http://stackoverflow.com/a/51449621
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/51449602
has title: Run Python script over multiple files in a folder
tagged with: python
answer count: 4
type: AnsweredQuestion

http://stackoverflow.com/comment/89849154
comment on: http://stackoverflow.com/q/51439215
type: Comment
has text: What do you mean by "`np.reshape` changes the data structure"?
type: QuestionComment
score: 0

http://stackoverflow.com/a/51365454
accepted answer of: http://stackoverflow.com/q/51362419
has body: No, this is not possible. ModelCheckpoint with save_weights_only=False only saves the topology, the weights and the optimizer's state (if any) of the model. The training data is not saved along with the model, and model.inputs is just the list of the model's placeholders. See also the source code for ModelCheckpoint.
score: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51362419
has comment: http://stackoverflow.com/comment/89704750
type: Answer
upvote count: 3

http://stackoverflow.com/comment/89733399
comment on: http://stackoverflow.com/q/51380386
type: QuestionComment
score: 2
has text: @Scotty1- You can just copy it and do `df = pd.read_clipboard()`
type: Comment

http://stackoverflow.com/comment/89735680
type: Comment
type: QuestionComment
has text: BTW you can simplify some of your logic, your `if` conditions are unnecessarily complex.
comment on: http://stackoverflow.com/q/51381874
score: 0

http://stackoverflow.com/comment/89674708
score: 0
type: Comment
type: QuestionComment
has text: @TomášKubát where are you saving them
comment on: http://stackoverflow.com/q/51350907

http://stackoverflow.com/comment/89806846
type: Comment
type: QuestionComment
score: 2
has text: your xG function does not use the formula for logistic regression, hence the weird results. You are treating a logistic regression as a linear regression in xG. The formula for logistic regression is 1/(1+e**(insert what you return in xG here))
comment on: http://stackoverflow.com/q/51417007

http://stackoverflow.com/a/51415891
has body: This would do the job def multiple_input(): try: while True: data=input() if not data: break yield data except KeyboardInterrupt: return if __name__=='__main__': u=list(multiple_input()) print(u) for i in u: print(i)
type: Answer
answers question: http://stackoverflow.com/q/51415573
score: 0

http://stackoverflow.com/comment/89852774
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51441167
has text: For a binary file I would expect intensive usage of `struct`module instead of `split()` and `strip()`calls.
type: Comment

http://stackoverflow.com/q/51444493
has answer: http://stackoverflow.com/a/51444964
type: Question
answer count: 1
favorite count: 0
tagged with: pandas
has title: How do I create a purchase activity plot using matplotlib?
score: -5
accepted answer: http://stackoverflow.com/a/51444964
tagged with: python
tagged with: python-3.x
upvote count: 1
downvote count: 6
type: AnsweredQuestion
has body: How do I create an user activity plot using matplotlib. I have looked at other similar answers on stack overflow but none of them answer my question well. My pandas data frame looks something like below: user | purchase date | item ------------------------------- x | 7/1/2010 | AAA y | 8/2/2010 | BBB x | 7/2/2010 | CCC z | 8/4/2010 | AAA z | 8/1/2010 | DDD I want something like this: (users on y-axis) x: |----X-X---------------------------------------- y: |-----------------X----------------------------- z: |---------------X----X-------------------------- ---|-------------------------------------------------------&gt; time(I want dates to be in my x-axis) My aim is to visualize customer's purchase activities. Thank you.
tagged with: matplotlib

http://stackoverflow.com/comment/89750934
type: QuestionComment
has text: provide a [mcve]
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51389423

http://stackoverflow.com/q/51443416
has answer: http://stackoverflow.com/a/51445438
has title: How to retrieve last log when grouped by a specific attribute in elasticsearch_dsl?
answer count: 1
tagged with: elasticsearch
has body: Need to get the last log (based on timestamp) for each server using python elasticsearch_dsl for example here are the logs: Server Hour CPU% server1 8AM 19 server1 9AM 19 server1 10AM 29 server2 8AM 19 server2 9AM 13 server2 10AM 21 server3 8AM 1 server3 9AM 11 server3 10AM 2 What I want to extract: server1 10AM 29 server2 10AM 21 server3 10AM 2 I thought starting with something like s.aggs.bucket('server_bucket','terms', field='server') but I'm kind of stuck because I don't want a metric, only the last record for each server. How can I do this?
type: UnansweredQuestion
tagged with: python
tagged with: elasticsearch-dsl-py
score: 0
tagged with: elasticsearch-dsl
type: Question

http://stackoverflow.com/comment/89896994
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51463977
has text: I see. Thank you for your explanations. How can I round in the "common" way then?

http://stackoverflow.com/comment/89821060
type: AnswerComment
has text: Sorry about that. I fixed the code to reflect what I mean with "getting the same value".
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51425032

http://stackoverflow.com/q/51379050
tagged with: regex
type: AnsweredQuestion
downvote count: 1
has comment: http://stackoverflow.com/comment/89729950
type: Question
has title: Replacing string if it contains specified pattern
has body: I need to replace ravi.jhon@piramal.com| or sam.jennifer@piramal.com| to ''(empty strings).I have written following regex but its unable to deal with . - emptyspace in the strings. my regex is \w+@ongoose.com["|"] now question is how to include ., empty space,- along with alpha numeric characters my final output should be : ravi.jhon@piramal.com| to ``
score: -1
has answer: http://stackoverflow.com/a/51379661
accepted answer: http://stackoverflow.com/a/51379661
upvote count: 0
has comment: http://stackoverflow.com/comment/89729578
answer count: 1
has comment: http://stackoverflow.com/comment/89730125
favorite count: 0
has comment: http://stackoverflow.com/comment/89731347
tagged with: python

http://stackoverflow.com/a/51472119
answers question: http://stackoverflow.com/q/51468532
type: Answer
has body: Use GroupBy.transform + GroupBy.first for find first non NaNs value and then remove duplicated values by mask and duplicated: cols = ['Q', 'R', 'T'] #repalce emty strings to NaNs data[cols] = data[cols].astype(str).replace('', np.nan) print (data) ID Series Status Q R T 0 A 1 Begin 9 NaN NaN 1 A 1 Begin NaN 8 NaN 2 A 1 End NaN NaN 12 3 B 1 Begin 30 NaN NaN 4 B 1 End NaN NaN 38 5 B 2 Begin 14 NaN NaN 6 B 2 End NaN NaN 21 7 C 1 Begin 3 NaN NaN 8 C 1 End NaN NaN 6 9 C 2 Begin 17 NaN NaN 10 C 2 Begin NaN 7 NaN 11 C 2 End NaN NaN 35 12 D 1 Begin 1 NaN NaN 13 D 1 End NaN NaN 5 g = data.groupby(['ID', 'Series']) for c in cols: data[c] = g[c].transform('first') print (data) ID Series Status Q R T 0 A 1 Begin 9 8 12 1 A 1 Begin 9 8 12 2 A 1 End 9 8 12 3 B 1 Begin 30 NaN 38 4 B 1 End 30 NaN 38 5 B 2 Begin 14 NaN 21 6 B 2 End 14 NaN 21 7 C 1 Begin 3 NaN 6 8 C 1 End 3 NaN 6 9 C 2 Begin 17 7 35 10 C 2 Begin 17 7 35 11 C 2 End 17 7 35 12 D 1 Begin 1 NaN 5 13 D 1 End 1 NaN 5 data[cols] = data[cols].mask(data.duplicated(['ID','Series'], keep='last'), '').fillna('') print (data) ID Series Status Q R T 0 A 1 Begin 1 A 1 Begin 2 A 1 End 9 8 12 3 B 1 Begin 4 B 1 End 30 38 5 B 2 Begin 6 B 2 End 14 21 7 C 1 Begin 8 C 1 End 3 6 9 C 2 Begin 10 C 2 Begin 11 C 2 End 17 7 35 12 D 1 Begin 13 D 1 End 1 5
score: 0

http://stackoverflow.com/a/51395910
score: 0
has comment: http://stackoverflow.com/comment/89771854
type: Answer
has comment: http://stackoverflow.com/comment/89778473
has comment: http://stackoverflow.com/comment/89780040
has comment: http://stackoverflow.com/comment/89779409
has body: You can do this with Automator: Start up Automator Choose application In the Actions bar, select Library, and search for Shell Drag "Run Shell Script" to the right pane. Change pass input to "as arguments" Change the script to for f in "$@" do python "$f" done Save it (possibly in the application folder, but can be anywhere) as Python.app Now if you want .py files to always launch with python: Select a .py file File -> Get Info In the Open with selection, choose Other, and select the Python.app you created. Click Change All You may also have to set the shebang for it to pick your virtualenv: If you want to run it from the terminal without using the python command, you can set the shebang to your anaconda environment as below: #!/usr/bin/python &lt;- ADD Your Anaconda environment path here then in terminal do this: chmod +x ./myfile.py And then you can just execute it as ./myfile.py if it is executable.
accepted answer of: http://stackoverflow.com/q/51395744
answers question: http://stackoverflow.com/q/51395744
type: AcceptedAnswer

http://stackoverflow.com/comment/89863050
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51446207
has text: `self.deck.deal(self.players + [self.dealer], per_hand = 2)` combines two lists into one and passes that to the `deal` function. (Assuming `self.players` is a list).
type: Comment

http://stackoverflow.com/q/51459940
tagged with: django
tagged with: python
type: AnsweredQuestion
has body: I have a model that contains a filefield and am using a modelform to add instances. When I come to modify an instance the form shows the current file and displays the file path ie library/filename. Is there a way to show just the filename in the form? Thanks
accepted answer: http://stackoverflow.com/a/51465131
type: Question
possible better answer: http://stackoverflow.com/a/51460838
has answer: http://stackoverflow.com/a/51465131
linked to: http://stackoverflow.com/q/2200100
score: 0
answer count: 2
has title: Filename only in django form field
has answer: http://stackoverflow.com/a/51460838

http://stackoverflow.com/comment/89906539
type: QuestionComment
has text: Is it possible the matlab engine was not installed in your conda environment but within your other python interpreter? There's a post here about running matlab with conda: https://groups.google.com/a/continuum.io/forum/#!topic/anaconda/aaUAMIwlWRc
comment on: http://stackoverflow.com/q/51443081
score: 0
type: Comment

http://stackoverflow.com/comment/89633080
comment on: http://stackoverflow.com/q/51328169
score: 0
type: Comment
type: QuestionComment
has text: @musikreck I get these two lines printed 5 times in a row: <win32com.gen_py.Microsoft Outlook 14.0 Object Library.AddressList instance at 0x54383024> <win32com.gen_py.Microsoft Outlook 14.0 Object Library.AddressList instance at 0x54384368>

http://stackoverflow.com/comment/89764016
type: Comment
comment on: http://stackoverflow.com/a/51384075
has text: it seems to be some good additional features but allone you are missing absolute values. Meaning if you sold 1 in the first week and 2 in the next, you have a 100% increase. if you sell 1000 and 1500 in the next week its only 50%. Another question to ask yourself: do you need machine learning to accomplish your goal or would some easy rule do the job. (e.g. if you sold more than X Articles in the summer months its a good summer selling article?)
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89814881
type: AnswerComment
comment on: http://stackoverflow.com/a/51421608
score: 0
type: Comment
has text: You are sorting a list and not a dictionary...so I dnt think you need `OrderedDict`

http://stackoverflow.com/a/51477471
has body: I can suggest you two options. First is to remove it from the dict- x = [b'1020569383', b'X012312', b'42132LVPG0U', b'Glow', b'Sports', b'Glow', b'Amazon', b'18.85', b'18.85', b'11.61', b'10.67', b'1.54', b'36.02', b'inches', b'0.52', b'pounds', b'Lg-Std-Non-Media', b'USD', b'6.02', b'2.83', b'0.00', b'--', b'--', b'--', b'3.19'] final_list = [i for i in x if i != b"--"] Or replace it with '' - final_list = [i.replace(b"--", b"") for i in x] What's that b in front of these texts? If you do type(x[0]) you get &lt;class 'bytes'&gt;. So you need to perform your operations in byte string also, hence the b""
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51477346
downvote count: 0
score: 1

http://stackoverflow.com/q/51452263
has answer: http://stackoverflow.com/a/51452442
accepted answer: http://stackoverflow.com/a/51455047
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/89874806
has comment: http://stackoverflow.com/comment/89874794
has title: Skip Over Item if element doesn't exist on page
score: 0
tagged with: beautifulsoup
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51455047
has body: I have a script that loops through multiple pages of a website and I want to skip over or add a blank space for the item that might not be on certain pages. For example, there are some pages that do not contain a description about the book. When I run into one of those pages I get an attribute error. My script below loops through the first two pages with no problem, but when it hits the third page it stops. Here is the traceback item['description'] = about.h2.nextSibling.nextSibling.nextSibling.text File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/beautifulsoup4-4.6.0-py3.6.egg/bs4/element.py", line 737, in __getattr__ AttributeError: 'NavigableString' object has no attribute 'text' How can I fix this? Here is my script: from bs4 import BeautifulSoup as soup import requests import json base_url = "https://open.umn.edu/opentextbooks/" data = [] n = 30 for i in range(4, n+1): response = requests.get(base_url + "BookDetail.aspx?bookId=" + str(i)) #html parsing page_soup = soup(response.content, "html5lib") #grabs info for each textbook containers = page_soup.findAll("div",{"class":"LongDescription"}) author = page_soup.select("p") about = page_soup.find("div",{"id":"AboutBook"}) for container in containers: item = {} item['type'] = "Textbook" item['title'] = container.find("div",{"class":"twothird"}).h1.text item['author'] = author[3].get_text(separator=', ') if item['author'] == " ": item['author'] = "University of Minnesota Libraries Publishing" item['link'] = "https://open.umn.edu/opentextbooks/BookDetail.aspx?bookId=" + str(i) if not container.find(string="Publisher: "): item['publisher_url'] = item['publisher'] = "" else: item['publisher'] = container.find(text="Publisher: ").nextSibling.text item['publisher_url'] = container.find(text="Publisher: ").nextSibling['href'] item['source'] = "Open Textbook Library" if not about.h2.nextSibling.nextSibling.nextSibling: item['description'] = "" else: item['description'] = about.h2.nextSi…
has comment: http://stackoverflow.com/comment/89883263
tagged with: python
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
possible better answer: http://stackoverflow.com/a/51452442

conv-neural-network
tags question: http://stackoverflow.com/q/51460835
tags question: http://stackoverflow.com/q/51378648
tags question: http://stackoverflow.com/q/51345440
tags question: http://stackoverflow.com/q/51324797
tags question: http://stackoverflow.com/q/51340107
tags question: http://stackoverflow.com/q/51456613
tags question: http://stackoverflow.com/q/51380111
type: Tag
tags question: http://stackoverflow.com/q/51453964
tags question: http://stackoverflow.com/q/51376802
tags question: http://stackoverflow.com/q/51426481
tags question: http://stackoverflow.com/q/51344610
tag name: conv-neural-network
tags question: http://stackoverflow.com/q/51479832
tags question: http://stackoverflow.com/q/51462603
tags question: http://stackoverflow.com/q/51444059
tags question: http://stackoverflow.com/q/51343169
tags question: http://stackoverflow.com/q/51406104
tags question: http://stackoverflow.com/q/51453506
tags question: http://stackoverflow.com/q/51369419
tags question: http://stackoverflow.com/q/51420217
tags question: http://stackoverflow.com/q/51341613
tags question: http://stackoverflow.com/q/51444101
tags question: http://stackoverflow.com/q/51447071
tags question: http://stackoverflow.com/q/51429593
tags question: http://stackoverflow.com/q/51431051

http://stackoverflow.com/a/51418056
has comment: http://stackoverflow.com/comment/89807550
downvote count: 0
has comment: http://stackoverflow.com/comment/89807316
type: Answer
has body: I could not reproduce the error, so I am guessing that it is due to how you call the sayHello method. Most likely, the the object on which you try to call sayHello is not of the class you created. import pandas as pd class Your_pd_class(pd.DataFrame): @property def sayHello(self): print('hello') x = Your_pd_class() x.sayHello The code snippet above will print 'hello' to the output. Note two things here: First of all it is bad practice to give a custom class the same name as an imported module as this can cause confusion, hence I changed the name of the class pd into your_pd_class. I suggest you give it a name you can remember, but not something that is already being used by another module used in the same program. The variable x in this example is created as the Your_pd_class, if you create the variable x = pd.DataFrame(), x will be of class dataframe and you will get the error you got. This is probably the case in your piece of code. If you want to use the extended pd class, you should create it as the Your_pd_class instead of pd.DataFrame. I hope this helps. Edit A hack to 'extend' the pd.DataFrame class would be to refer all pd.DataFrame to Your_pd_class: import pandas as pd class Your_pd_class(pd.DataFrame): @property def sayHello(self): print('hello') pd.DataFrame = Your_pd_class x = pd.DataFrame() x.sayHello
answers question: http://stackoverflow.com/q/51417411
score: 1
upvote count: 1

http://stackoverflow.com/comment/89797017
type: QuestionComment
score: 1
has text: there's a squiggly line making it hard to read what's on the line `exclude = ...` Is it `exclude = ('_created__')` ? What are the parentheses and the underscores for? Is it supposed to be `exclude = ('created',)` ? The comma is required in a single item tuple. If there's no comma the parenthesis will be parsed as a grouping operator.
comment on: http://stackoverflow.com/q/51411892
type: Comment

http://stackoverflow.com/a/51392927
has body: When you read your csv , you can using parse_dates df = pd.read_csv('yourcsv.csv',parse_dates = date_column) Then let us using converters pd.read_csv('yourcsv.csv', converters={'date_column':lambda x : pd.to_datetime(x,errors = 'coerce')})
has comment: http://stackoverflow.com/comment/89757670
has comment: http://stackoverflow.com/comment/89782227
answers question: http://stackoverflow.com/q/51392909
has comment: http://stackoverflow.com/comment/89757621
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/51392909
upvote count: 2

http://stackoverflow.com/q/51425215
tagged with: matplotlib
upvote count: 1
has title: Pyplot to show only the last 60 seconds of a plot graph
has comment: http://stackoverflow.com/comment/89822004
type: Question
has comment: http://stackoverflow.com/comment/89821670
has body: I´m new to matplotlib and python in general. I'm on windows running typeperf.exe to basically reads processor information in real time using cli: C:\&gt;typeperf "\Procesador(_Total)\% de tiempo de procesador" &gt; C:\Users\hb\Documents\Scripts\log.csv The data structure at the CSV is as follows: "07/18/2018 15:50:55.574","3.429826" "07/18/2018 15:50:56.577","0.307183" "07/18/2018 15:50:57.589","18.932128" At the same time - same machine - I run a code which basically reads that CSV producing a live plot ( it works! ) The plot is being drawn with a new line every 1 second. Objective: make the graph to show only the last 60 seconds of capture and continue moving forward with the new data in the CSV. I've read pyplot documentation and tried .clf() and .clear() with no luck. Here's just the portion of code where I´m having a hard time: def animate(i): with open(data_in, 'r', newline='') as f_input: x, y = [], [] end_t = time.time() + 60 while time.time() &lt; end_t: for line in range(2): next(f_input) for row in csv.reader(f_input): if row: x.append(datetime.strptime(row[0], '%m/%d/%Y %H:%M:%S.%f')) y.append(float(row[1])) ax1.clear() plt.title('system\n') plt.xlabel('Current Time') plt.ylabel('Current HTTP Connections\n') ax1.plot(x,y) time_format = DateFormatter('%H:%M:%S') plt.gca().xaxis.set_major_formatter(time_format) start += 1 data_out = animation.FuncAnimation(fig, animate, interval=1000) plt.show() I tried the while loop in an attempt to make the plot read just for that amount of time. It doesn't work. Would you please point me out to the right path? Thanks,
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51425578
score: 1

http://stackoverflow.com/comment/89837484
score: 0
type: QuestionComment
type: Comment
has text: You could show a picture of what you want to get.
comment on: http://stackoverflow.com/q/51433403

http://stackoverflow.com/q/51468492
tagged with: dictionary
has answer: http://stackoverflow.com/a/51468614
type: AnsweredQuestion
score: 1
has title: How do I get the value inside the dictionary if it's key is stored inside a variable?
tagged with: loops
type: Question
tagged with: function
accepted answer: http://stackoverflow.com/a/51468614
downvote count: 0
answer count: 1
has body: I need to get a value of the key that I've stored inside a variable. The value of the variable varies and the output pattern should vary according to this. Please check the code below I don't seem to get the output. I could get them only if I could pass the value for the key given. It would be nice if you point out any other errors in this programs since I'm very NEW to this. Thanks :) self = { "1" : None, "0" : "", "2" : "abc", "3" : "def", "4" : "ghi", "5" : "jkl", "6" : "mno", "7" : "pqrs", "8" : "uvw", "9" : "wxyz" } def rec(rest_of_no, path): if not rest_of_no: combinations.add(path) return first, rest = rest_of_no[0], rest_of_no[1:] letters = self.get[int(first)] for letter in letters: rec(rest_of_no, path) return combinations t = int(input()) for i in range(t): n = int(input()) ar = list(map(int, input().split())) combinations = set() rec(ar, "") print (combinations) This is the error that I get: Runtime Error: Runtime ErrorTraceback (most recent call last): File "/home/66ec1f75836d265709dd36b77f69f071.py", line 30, in &lt;module&gt; rec(ar, "") File "/home/66ec1f75836d265709dd36b77f69f071.py", line 19, in rec letters=self[int(first)] KeyError: 2
favorite count: 0
tagged with: python-3.x
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/89714336
has text: Now, I understand your 2nd point - not all price package is available in all data center. Thank you. Also, when the data center ID is assigned to location, it works. But, it appears that I can assign a string such as "AMSTERDAM" to the location. What is "AMSTERDAM" in SL? Is it one of attributes?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51367828
score: 0

http://stackoverflow.com/a/51430003
type: AcceptedAnswer
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51429286
accepted answer of: http://stackoverflow.com/q/51429286
has body: Note that in Pandas you can index in ways other than elementwisely with at. In the four-liner below, index is a list which can then be used for indexing with loc. for parameter in dictionary_of_parameters: index = df[df[parameter].isin(dictionary_of_parameters[parameter]['target'])].index df.loc[index,'financialliteracyscore'] += dictionary_of_parameters[parameter]['score'] df['financialliteracyscore'] = df['financialliteracyscore'] /27.0*100 Here's a reference although I personally never found it useful in my earlier days of programming... https://pandas.pydata.org/pandas-docs/stable/indexing.html

http://stackoverflow.com/q/51368630
favorite count: 0
score: 8
has comment: http://stackoverflow.com/comment/89709701
upvote count: 9
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51368920
tagged with: http://stackoverflow.com/tag/json
has body: I have a standard nested json file which looks like the below: They are multi level nested and I have to eliminate all the nesting by creating new objects. Nested json file. { "persons": [{ "id": "f4d322fa8f552", "address": { "building": "710", "coord": "[123, 465]", "street": "Avenue Road", "zipcode": "12345" }, "cuisine": "Chinese", "grades": [{ "date": "2013-03-03T00:00:00.000Z", "grade": "B", "score": { "x": 3, "y": 2 } }, { "date": "2012-11-23T00:00:00.000Z", "grade": "C", "score": { "x": 1, "y": 22 } }], "name": "Shash" }] } The new objects that needs to be created persons [ { "id": "f4d322fa8f552", "cuisine": "Chinese", "name": "Shash" } ] persons_address [ { "id": "f4d322fa8f552", "building": "710", "coord": "[123, 465]", "street": "Avenue Road", "zipcode": "12345" } ] persons_grade [ { "id": "f4d322fa8f552", "__index": "0", "date": "2013-03-03T00:00:00.000Z", "grade": "B" }, { "id": "f4d322fa8f552", "__index": "1", "date": "2012-11-23T00:00:00.000Z", "grade": "C" }, ] persons_grade_score [ { "id": "f4d322fa8f552", "__index": "0", "x": "3", "y": "2" }, { "id": "f4d322fa8f552", "__index": "1", "x": "1", "y": "22" }, ] My approach : I used a normalise function to make all the lists into dicts. Added another function which can add id to all the nested dicts. Now I am not able to traverse each level and create new objects. Is there any way to get to this. The whole idea after new objects are created we can load it into a database.
has comment: http://stackoverflow.com/comment/89709773
has answer: http://stackoverflow.com/a/51368920
has answer: http://stackoverflow.com/a/51505127
accepted answer: http://stackoverflow.com/a/51505127
type: Question
has comment: http://stackoverflow.com/comment/89709663
has title: Eliminate nesting by creating new objects from json
linked to: http://stackoverflow.com/q/2835559
answer count: 3
downvote count: 1
has answer: http://stackoverflow.com/a/51368851

http://stackoverflow.com/a/55847158
score: 9
downvote count: 0
has body: it's not relating to hardware RAM or GPU capacity. Keras framework has a limitation for showing output info in console. when you see this message, your process is going on in background but you can't see it. If you use tensorflow as backend, write a Tensorboard callback in your Keras to see detailed output of your network. https://keras.io/callbacks/#tensorboard
type: Answer
upvote count: 9
answers question: http://stackoverflow.com/q/51463383

http://stackoverflow.com/a/51439618
has body: The question at the end was how can I get a table containing all the edges out of a subgraph that matches a certain query. The Cypher that does the trick is: MATCH (source:Skill)-[:BROADER*0..7]-&gt;(dest:Skill) WHERE source.label_en in ['skill1','skill2'] WITH COLLECT(DISTINCT source)+COLLECT(dest) AS myNodes UNWIND myNodes as myNode MATCH p=(myNode)-[:BROADER]-&gt;(neighbor) WHERE neighbor in myNodes RETURN myNode.label_en as child ,neighbor.label_en as parent The first two lines get the nodes belonging to said subgraph. The last five unwind it as pairs of nodes connected by a directed edge. The 0 in the second MATCH allows for collecting isolated nodes that belong to the original list. as in 2019, with current py2neopackages, a way that this thing would work is query = ''' MATCH (source:Skill)-[:BROADER*0..7]-&gt;(dest:Skill) WHERE source.label_en in ['skill1','skill2'] WITH COLLECT(DISTINCT source)+COLLECT(dest) AS myNodes UNWIND myNodes as myNode MATCH p=(myNode)-[:BROADER]-&gt;(neighbor) WHERE neighbor in myNodes RETURN myNode.label_en as child ,neighbor.label_en as parent ''' df = pd.DataFrame(graph.run(query).data()) G=nx.DiGraph() G.add_nodes_from(list(set(list(df['child']) + list(df.loc['parent'])))) #Add edges tuples = [tuple(x) for x in df.values] G.add_edges_from(tuples) G.number_of_edges() #Perform Graph Drawing #A star network (sort of) nx.draw_networkx(G) plt.show()
score: 0
answers question: http://stackoverflow.com/q/51406761
type: Answer
has comment: http://stackoverflow.com/comment/104377374
has comment: http://stackoverflow.com/comment/104382225

http://stackoverflow.com/q/51378442
has comment: http://stackoverflow.com/comment/89731592
has comment: http://stackoverflow.com/comment/89731717
duplicate of: http://stackoverflow.com/q/379906
score: 0
has title: PyQt5 ValueError: could not convert string to float:
has comment: http://stackoverflow.com/comment/89730016
tagged with: qt-designer
linked to: http://stackoverflow.com/q/22251354
has comment: http://stackoverflow.com/comment/89729196
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89731465
tagged with: python
linked to: http://stackoverflow.com/q/379906
tagged with: qt
has body: Since yesterday I'm facing this issue I can't solve by myself. Can anyone please suggest a solution ? File "C:/Myproj_python/pertesCVS.py", line 67, in recupVariables Eon1 = float((self.Eon1_lineEdit.text())) As shown in the code, I'm importing a GUI called pertesCVSUI parametres generated by Qt designer. In the method defined as RecupeVariables I'm trying to store as variables what the user writes in some QlineEdits and to do calculation on those float values in the method defined as fitenergy. import numpy as np import pertesCVSUI from PyQt5 import QtGui, QtWidgets class PertesCVS(pertesCVSUI.Ui_PertesCVS): def __init__(self, parent=None): # super(PertesCVS, self).__init__(parent) self.setupUi(parent) self.recupVariables() self.btnstate() self.fitenergy() def setupUi(self, parent): super(PertesCVS, self).setupUi(parent) # setup validators self.Eon1_lineEdit.setValidator(QtGui.QDoubleValidator(0.99, 99.99, 3)) self.Eon2_lineEdit.setValidator(QtGui.QDoubleValidator(0.99, 99.99, 3)) self.Eon3_lineEdit.setValidator(QtGui.QDoubleValidator(0.99, 99.99, 3)) self.Ion1_lineEdit.setValidator(QtGui.QDoubleValidator(0.99, 99.99, 3)) self.Ion2_lineEdit.setValidator(QtGui.QDoubleValidator(0.99, 99.99, 3)) self.Ion3_lineEdit.setValidator(QtGui.QDoubleValidator(0.99, 99.99, 3)) self.Eoff1_lineEdit.setValidator(QtGui.QDoubleValidator(0.99, 99.99, 3)) self.Eoff2_lineEdit.setValidator(QtGui.QDoubleValidator(0.99, 99.99, 3)) self.Eoff3_lineEdit.setValidator(QtGui.QDoubleValidator(0.99, 99.99, 3)) self.Ioff1_lineEdit.setValidator(QtGui.QDoubleValidator(0.99, 99.99, 3)) self.Ioff2_lineEdit.setValidator(QtGui.QDoubleValidator(0.99, 99.99, 3)) self.Ioff3_lineEdit.setValidator(QtGui.QDoubleValidator(0.99, 99.99, 3)) self.Vcc_lineEdit.setValidator(QtGui.QDoubleValidator(0.99, 99.99, 3)) self.Imax_lineEdit.setValidator(QtGui.QDoubleValidator(0.99, 99.99, 3)) self.Fd_lineEdit.setValidator(QtGui.QDoubleValidator(0.99, 99.99, 3)) self.Mod_lineEdit.setValidator(QtGui.QDoubleValidator(0.99, 99.9…
has comment: http://stackoverflow.com/comment/89729987
answer count: 0
has comment: http://stackoverflow.com/comment/89730946
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/89732205
type: Question
has comment: http://stackoverflow.com/comment/89731804
tagged with: pyqt4

http://stackoverflow.com/q/51396019
has comment: http://stackoverflow.com/comment/89783953
tagged with: image
score: 0
answer count: 1
has title: Grouping images by time interval starting with specific position
has body: I have a script which takes exif data from images, and puts it into to a list. Then I sort my list and that's what I have. It's a two dimensional array, where the first element is the timestamp and the second element is the image path: My img list: [[32372, 'F:\\rubish\\VOL1\\cam\\G0013025.JPG'], [32373, 'F:\\rubish\\VOL1\\cam\\G0013026.JPG'], [32373, 'F:\\rubish\\VOL1\\cam\\G0013027.JPG'],.... etc etc etc The following script was made by @blhsing and groups my images. It works great, but I would like to group my images not starting from the first image, but starting from any given position. This is the script by @blhsing: groups = [] for r in img: if groups and r[0] - groups[-1][-1][0] &lt;= 5: groups[-1].append(r) else: groups.append([r]) for g in groups: print(g[0][1], g[0][0], g[-1][0], g[-1][1]) And this is what I have come up with so far. It does not work well, it only takes one image and does not create a group. Could anyone help me fix it? groups = [] print(iii, "iii") #print(min_list, " my min list ") img.sort() cnt = 0 mili = [32372, 34880] for n in mili: #print(n, "mili") for i in img: #print(i[0]) if n == i[0]: if groups and i[0] - groups[-1][-1][0] &lt;= 5: groups[-1].append(i) else: groups.append([i]) for ii in groups: print(ii[0][1], ii[0][0], ii[-1][0], ii[-1][1]) My iii is a list of temps: [32372, 32373, 32373, 32374, 32374, 32375, 32375, 34880, 34880, 34881, 34881, 34882, 34882, 34883, 34883, 36505, 36505...etc In this example I have my min_list with 2 positions, which means I want to create only 2 groups and classify only images starting from those 2 positions, with the same interval of 5 seconds as before. Ps. Thank You @pasch013 it works but check this please , why the results its like this , I get mili from min_list like this: min_list.sort() print(min_list, " min list") interval = 5 groups = [] #mili = [1, 99] for start_time in min_list: i = 0 while i &lt; len(img) and img[i][0] &lt; start_time: i += 1 groups.append([]) while i &lt; len(img) a…
tagged with: time
accepted answer: http://stackoverflow.com/a/51396413
tagged with: python
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51396413

http://stackoverflow.com/a/51423663
accepted answer of: http://stackoverflow.com/q/51423494
has comment: http://stackoverflow.com/comment/89819565
answers question: http://stackoverflow.com/q/51423494
type: Answer
upvote count: 4
downvote count: 0
score: 4
has body: I suspect you used the RandomForestClassifier.predict() method which results in either 0 or 1 depending on the predicted class. To get the probability, which is the fraction of trees voted for a specific class, you have to use the RandomForestClassifier.predict_proba() method. Using these probabilities as input for your curve calculations should fix the problem. EDIT: The curve creation methods of scikit-learn sort the predictions first according to the prediction score, then according to their real/observed value, therefore the curves have these "bends".
type: AcceptedAnswer

http://stackoverflow.com/a/51357322
score: 4
accepted answer of: http://stackoverflow.com/q/51357272
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/51357272
downvote count: 0
type: AcceptedAnswer
has body: def common_pos(doc, n, pos=None): words = [ token.lemma_ for token in doc if ( token.is_stop != True and token.is_punct != True and (not pos or token.pos_ == pos) ) ] word_freq = Counter(words) common_words =word_freq.most_common(n) print(common_words) Basically only filter by pos if it is truthy.

http://stackoverflow.com/comment/89785271
has text: It is a *positional* parameter.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51407043

http://stackoverflow.com/q/51462703
tagged with: lxml
type: UnansweredQuestion
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/89903441
has answer: http://stackoverflow.com/a/51481336
score: 0
has title: Can I convert an lxml div object to a string?
answer count: 1
has comment: http://stackoverflow.com/comment/89894395
has body: I'm making a program to scrape text from a website. But the website puts its text in a div tag and sometimes the text is inside a p tag inside the div tag. Is it possible to convert this div tag into a string so that it would be simpler to format? from lxml import etree import requests element = etree.HTML(requests.get('a website')).xpath('//div')

http://stackoverflow.com/comment/89830318
has text: I am using the example also given in the question: `Params = [[0.0, 23.0], [22.0, 88.0], [0.0, 23.0], [0.0, 12.0], [0.0, 9.0], [0.0, 2.0], [0.0, 10.0], [0.0, 8.0], [0.0, 32.0], [0.0]]` but removed to lists with `[0]`
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51427897

http://stackoverflow.com/comment/89912391
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51472097
score: 0
has text: myListOfPoint is a list which by default supports iteration .

http://stackoverflow.com/comment/128295576
score: 0
type: Comment
type: QuestionComment
has text: OH great... Another env variable (and appears to not work if importing mixer from) -- Time for a new library
comment on: http://stackoverflow.com/q/51464455

http://stackoverflow.com/a/51372237
answers question: http://stackoverflow.com/q/51372225
has body: Gnome Keyring Command Line Tools (check/lock/unlock) Sources &amp; Release : https://github.com/intika/gnome-keyring-tools Check Keyring - gkey-check.c #include &lt;stdio.h&gt; #include &lt;gnome-keyring.h&gt; int main() { GnomeKeyringInfo *info; GnomeKeyringResult gkr; gkr = gnome_keyring_get_info_sync(NULL, &amp;info); if (gkr != GNOME_KEYRING_RESULT_OK) { printf("error\n"); return -1; } if (gnome_keyring_info_get_is_locked(info)) { printf("locked\n"); return 0; } else { printf("unlocked\n"); return -1; } gnome_keyring_info_free(info); } Check With Python - gkey-check.py import gnomekeyring print gnomekeyring.get_info_sync(gnomekeyring.get_default_keyring_sync()).get_is_locked() How to build cc gkey-check.c -o gkey-check -Wall -I/usr/include/gnome-keyring-1 -I/usr/include/glib-2.0 -I/usr/lib64/glib-2.0/include -lgnome-keyring -lglib-2.0
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51372225

http://stackoverflow.com/q/51394080
type: Question
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/51395978
tagged with: python-2.7
tagged with: python
tagged with: python-2.x
has title: Weird Python Date Comparison Behaviour
has comment: http://stackoverflow.com/comment/89765172
has body: I am facing weird Python Date Time Comparison issue. I am getting two date times in string format (From REST Call, JSON) start date time and end date time. I have to compare current date time and if it falls within this rage (start date time and end date time) take some action. It is known that the time zone of these dates is US/Eastern (USA North Carolina). Here is the code, from pytz import timezone from datetime import datetime def main(): # All the dates are in US/Eastern time zone. Time zone for USA, North Carolina # These dates are received from REST call in JSON # I need to compare the current date time, if that falls within this range take some action start_date_str = "7/17/2018 11:30:00 AM" end_date_str = "7/17/2018 2:30:00 PM" # To simulate current date time within the range, I will update the current date time value. current_est_time = datetime.now(tz=timezone('US/Eastern')) current_est_time = current_est_time.replace(year=2018, month=7, day=17, hour=12, minute=26) print current_est_time start_date = datetime.strptime(start_date_str,"%m/%d/%Y %I:%M:%S %p").replace(tzinfo=timezone('US/Eastern')) end_date = datetime.strptime(end_date_str, "%m/%d/%Y %I:%M:%S %p").replace(tzinfo=timezone('US/Eastern')) print start_date &lt;= current_est_time &lt;= end_date if __name__ == '__main__': main() If minute value is 26, comparison prints True, if it is 25, it prints False. Output of the above code sample is 2018-07-17 12:26:06.646643-04:00 True If you change the minute value for current_est_time variable to 25, output is 2018-07-17 12:25:16.582573-04:00 False Can somebody please help me, where I am going wrong here ?
has comment: http://stackoverflow.com/comment/89759569
tagged with: pytz
favorite count: 0
accepted answer: http://stackoverflow.com/a/51398561
downvote count: 0
has comment: http://stackoverflow.com/comment/89759703
score: 2
possible better answer: http://stackoverflow.com/a/51395978
has comment: http://stackoverflow.com/comment/89768174
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51398561
tagged with: python-datetime
linked to: http://stackoverflow.com/q/24359540

http://stackoverflow.com/comment/89807532
comment on: http://stackoverflow.com/a/51403575
type: Comment
score: 1
type: AnswerComment
has text: Can't you use old style annotation with `#type LOGGER: PxLogger` ?

http://stackoverflow.com/q/51455408
upvote count: 4
answer count: 2
tagged with: pandas
downvote count: 0
tagged with: date-range
has comment: http://stackoverflow.com/comment/89880250
favorite count: 0
has body: I am trying to sum the values of colA, over a date range based on "date" column, and store this rolling value in the new column "sum_col" But I am getting the sum of all rows (=100), not just those in the date range. I can't use rolling or groupby by as my dates (in the real data) are not sequential (some days are missing) Amy idea how to do this? Thanks. # Create data frame df = pd.DataFrame() # Create datetimes and data df['date'] = pd.date_range('1/1/2018', periods=100, freq='D') df['colA']= 1 df['colB']= 2 df['colC']= 3 StartDate = df.date- pd.to_timedelta(5, unit='D') EndDate= df.date dfx=df dfx['StartDate'] = StartDate dfx['EndDate'] = EndDate dfx['sum_col']=df[(df['date'] &gt; StartDate) &amp; (df['date'] &lt;= EndDate)].sum()['colA'] dfx.head(50)
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51455557
has title: Pandas : How to sum column values over a date range
tagged with: python
has answer: http://stackoverflow.com/a/51455573
type: Question
tagged with: sum
score: 4

http://stackoverflow.com/comment/89711552
has text: @CalumYou thanks, the output of `str(xchest_data)` is: `'data.frame': 2163 obs. of 2362 variables: $ V1 : num 8 8 8 8 8 13 23 36 38 34 ... $ V2 : num 8 8 8 10 8 15 20 23 36 34 ... $ V3 : num 8 8 8 11 8 15 21 24 36 35 ... $ V4 : num 8 8 8 11 8 17 21 27 37 35 ... $ V5 : num 8 8 8 11 8 16 21 26 40 39 ... $ V6 : num 8 8 8 12 8 14 20 26 39 35 ... $ V7 : num 8 8 8 12 8 17 18 31 41 42 ... $ V8 : num 8 8 8 12 8 17 23 32 40 39 ... $ V9 : num 8 8 8 12 8 14 23 29 39 39 ... $ V10 : num 8 8 8 12 8 16 23 25 37 36 ...` and continues until is truncated.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51365660

http://stackoverflow.com/a/51388023
score: 1
has body: It's because of Pycharm doesn't know where to find out selenium, or which python interpreter you are using. Please select correct Python version. You can found them in Settings | Project Interpreter > Wheel - More > Show Paths for the selected interpreter"
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51387186
upvote count: 1

http://stackoverflow.com/q/51324754
has answer: http://stackoverflow.com/a/72312980
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51330788
has comment: http://stackoverflow.com/comment/89624626
possible better answer: http://stackoverflow.com/a/72312980
type: Question
has title: Python 3.6.x PyInstaller gives error "No module named 'PyQt5.sip'"
has answer: http://stackoverflow.com/a/51330788
answer count: 2
has body: I developed a few programs that runs well on Python 3.5.4, but because of some errors about win32 made me go to Python 3.6.4, but when I build my project with pyinstaller, I get: C:\Users\User\Desktop\dist\mycommentator&gt;mycommentator.exe Traceback (most recent call last): File "mycommentator.py", line 6, in &lt;module&gt; File "c:\users\user\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 714, in load_module module = loader.load_module(fullname) ModuleNotFoundError: No module named 'PyQt5.sip' [1532] Failed to execute script mycommentator I tried to reinstall python, so I installed Python 3.6.4/Python 3.6.5, that error happened to me too. No matter what code in PyQt5 I build, every time this error. I also tried to move sip.pyd to the project folder, but error still happens. I also tried pip install --upgrade sip, that didn't help. I also tried to install the develop version of the pyinstaller, that didn't help too.
tagged with: sip
favorite count: 0
tagged with: pyinstaller
downvote count: 1
upvote count: 12
has comment: http://stackoverflow.com/comment/89624557
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/92424359
tagged with: python
score: 11

http://stackoverflow.com/q/51384261
type: Question
accepted answer: http://stackoverflow.com/a/51384285
upvote count: 1
answer count: 1
tagged with: influxdb-python
favorite count: 0
has answer: http://stackoverflow.com/a/51384285
tagged with: python
downvote count: 0
has body: I am using influxdbClient to query the Influxdb through python. the simple query works well as: from influxdb import InfluxDBClient client = InfluxDBClient(host='192.168.1.104', port=8086) client.get_list_database() client.switch_database('Mlogi_ALL') res= client.query('SELECT * FROM n') But when I query : client.query('SELECT * FROM n WHERE (time &gt;= 2018-06-01T00:00:00Z AND time &lt;= 2018-07-30T00:00:00Z') it gives error : InfluxDBClientError: 400: {"error":"error parsing query: found -06, expected ) at line 1, char 36"} where I am going wrong ?
score: 1
type: AnsweredQuestion
has title: InfluxDBClientError: 400: {"error":"error parsing query: found -06, expected ; at line 1, char 35"}

http://stackoverflow.com/comment/89860065
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51444958
has text: Pip is just calling python -m pip... the reason its safer to just call python -m pip, is that you know for sure which python will get the install... where if you have multiple python installed who knows which one just pip installs to
score: 0

http://stackoverflow.com/q/51392889
type: AnsweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/78652079
accepted answer: http://stackoverflow.com/a/51392934
favorite count: 0
answer count: 6
type: Question
score: 20
has answer: http://stackoverflow.com/a/75803927
tagged with: unit-testing
tagged with: pytest
has title: python pytest occasionally fails with OSError: reading from stdin while output is captured
has answer: http://stackoverflow.com/a/65659315
tagged with: python-unittest
has answer: http://stackoverflow.com/a/51392934
has answer: http://stackoverflow.com/a/79185829
possible better answer: http://stackoverflow.com/a/65659315
upvote count: 20
has answer: http://stackoverflow.com/a/64352447
downvote count: 0
has body: While running a particular unittest with pytest, it occasionally fails with this error (mentioned in the title) and from the stack trace it happens on the line choice = input().lower() when the control reaches this statement, the entire function is: def prompt_to_activate(bear, printer): PROMPT_TO_ACTIVATE_STR = ('program has found {} to be useful ' 'based of dependencies discovered from your ' 'project files. \n Would you like to activate ' 'it? (y/n)') printer.print(PROMPT_TO_ACTIVATE_STR) choice = input().lower() if choice.startswith('y'): return True elif choice.startswith('n'): return False else: return prompt_to_activate(bear, printer) for i in range(0, 3): a = i print(a) I tried adding some time.sleep(x) before that statement but that wouldn't fix it. Can somebody tell me the exact reason why this is happening and how to fix it?

http://stackoverflow.com/q/51401380
tagged with: c++
tagged with: opencv
type: AnsweredQuestion
score: 1
possible better answer: http://stackoverflow.com/a/51401790
type: Question
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51401790
tagged with: matrix-indexing
has answer: http://stackoverflow.com/a/51402963
accepted answer: http://stackoverflow.com/a/51402963
has title: Fast indexing in C++ OpenCV
favorite count: 0
has body: I am quite comfortable with OpenCV in Python. I recently switched to the C++ version, and I keep having problems with the cv::Mat indexing, since I'm too used to numpy's arrays. In particular, I am trying to find if there is a better way of acting on a restricted area of an array without iterating through it. For example, let's say I have a 10x15 unitary matrix and I would like to put everything but the last row to zero (or to another random number); in Python, I would do something like this: import numpy as np a = np.ones([10,15]) a[:-1,:-1] = 0 How can I achieve that in C++, having defined cv::Mat a = cv::Mat::ones(10, 15, CV_32FC1);?
upvote count: 1
tagged with: python

http://stackoverflow.com/a/52962950
score: 0
answers question: http://stackoverflow.com/q/51470023
type: Answer
has body: Share an experience that imports BeautifulSoup from bs4. Hope to help you. Downloading beautifulsoup4 source code, unzip the code and copy the "bs4" folder to Anki Add-On folder C:\Users\Admin\AppData\Roaming\Anki2\addons\. Then restart Anki. My akPlugin.py script can find BeautifulSoup from bs4. λ ls -al addons total 56 drwxr-xr-x 1 Admin 197121 0 Aug 30 09:12 ./ drwxr-xr-x 1 Admin 197121 0 Oct 22 18:28 ../ -rw-r--r-- 1 Admin 197121 37794 Jul 18 10:11 akPlugin.py drwxr-xr-x 1 Admin 197121 0 Sep 29 2015 bs4/

http://stackoverflow.com/comment/89886055
comment on: http://stackoverflow.com/q/51458290
has text: Try `print("abc|def|ghi|xyz".split('|'))`
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89851446
has text: Rename `textForm` to `TextForm` first letter should be capital. And rename `Request` to `request`. It will not solve your problem, but it good style.
type: Comment
comment on: http://stackoverflow.com/q/51440566
score: 1
type: QuestionComment

http://stackoverflow.com/q/51458798
answer count: 0
downvote count: 0
has title: Troubleshooting timer delay between Javascript frontend and Python backend
score: 1
has comment: http://stackoverflow.com/comment/89888522
favorite count: 0
type: Question
tagged with: python
upvote count: 1
has comment: http://stackoverflow.com/comment/89889043
has comment: http://stackoverflow.com/comment/89887062
has comment: http://stackoverflow.com/comment/89890881
tagged with: javascript
type: UnansweredQuestion
tagged with: date
has body: I have a JS frontend app making API calls to a Python backend API. To combat replay-later attacks, every HTTP request from the frontend app has a header with the time of the request (in milliseconds from epoch). headers['request-epoch'] = Date.now() The Python backend also calculates its own current time (in seconds from epoch): dt = datetime.datetime.utcnow() seconds_from_epoch = int((dt - datetime.datetime.utcfromtimestamp(0)).total_seconds()) Then it compares the difference: request_timestamp = self.request.headers.get('request-timestamp', 0) request_seconds_from_epoch = int(request_timestamp) / 1000 seconds_elapsed = abs(seconds_from_epoch - request_seconds_from_epoch) Here is the weird thing: Once is a while, seconds_elapsed is over 60 seconds, while I am testing the frontend. The interaction on the frontend returns in less than a second, so the request / response is definitely taking less than 60 seconds. Therefore, I am trying to figure out why the timestamp discrepancy is anything more than a second. It is hard to reproduce, but I a log whenever this happens, which is how I noticed the problem. Any ideas on why this could be happening?

http://stackoverflow.com/comment/89754938
comment on: http://stackoverflow.com/q/51390918
type: QuestionComment
has text: Duplicate of [What is a clean, pythonic way to have multiple constructors in Python?](https://stackoverflow.com/questions/682504/what-is-a-clean-pythonic-way-to-have-multiple-constructors-in-python). In this case you don't even need a separate classmethod, you can just have `__init__` use random coords, when called with no args.
score: 0
type: Comment

http://stackoverflow.com/comment/89850568
has text: @stonerock: The `n` value is the number of values you have. So, either `len(A)` or `len(F)`. Just be sure they are equal
score: 1
comment on: http://stackoverflow.com/a/51440114
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51480504
answer count: 0
has title: Share data between serializes fields
has body: I have a ModelSerializer class which implements some fields with SerializerMethodField. There are a few fields which calculates currency data according to the rates retrieved from a database if there are, otherwise from a bank API. With current implementation there are a lot of short queries to the database just to retrieve or check a rate. I'm thinking of reducing the number of queries by sharing already calculated data between fields. The code will explain the idea better: class CalcualteSomethingSerializer(ModelSerializer): currency_value_1 = serializers.SerializerMethodField() currency_value_2 = serializers.SerializerMethodField() def get_currency_value_1(obj): if obj.currency_code != 'USD': rate = get_rates('USD', obj.currency_code, obj.date) return calculation_logic1(obj.value, rate) def get_currency_value_2(obj): if obj.currency_code != 'USD': rate = get_rates('USD', obj.currency_code, obj.date) return calculation_logic2(obj.value, rate) I've tried to save the rates into self._kwargs but it reduced a number of queries only for 5 queries.
type: Question
has comment: http://stackoverflow.com/comment/89929673
score: 0
tagged with: serialization
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/89930026
tagged with: python

http://stackoverflow.com/q/51400404
score: 1
favorite count: 0
has body: A short time ago I had an almost identical problem to this one and it was fixed by using string literals instead of literal strings. This time, I took care to use string literals but it didn't fix the problem. I am trying to extract a section from a string and the results I get from Python are different than what regex101 shows I should be getting. I'm using this Supersedes:?[\\r\\n ]+(?:[A-Za-z\-0-9])*[\\w\-\\s]+[\\r\n ]+(.*)[\\r\\n ]+Serial Numbers:? to match this text: \r\n\r\nSupersedes\r\nNone\r\n\r\nChanges to VGA-77 gas module assembly (0110444290)\r\n\r\nService Serial Numbers:\r\nUS00000000-US99999999\r\n\r I'm expecting the first captured group to give me n\r\nChanges to VGA-77 gas module assembly (0110444290)\r\n\r\nService https://regex101.com/r/eHdhBV/2 But when I try this in Python: rx = r'Supersedes:?[\r\n ]+(?:[A-Za-z\-0-9])*[\w\-\s]+[\r\n ]+(.*)[\r\n ]+Serial Numbers:?' string = '\r\n\r\nSupersedes\r\nNone\r\n\r\nChanges to VGA-77 gas module assembly (0110444290)\r\n\r\nService Serial Numbers:\r\nUS00000000-US99999999\r\n\r' result = re.search(rx, string, re.M|re.S) result[1] '(0110444290)\r\n\r\nService' The result is not the same as what is shown on regex101. What's causing this?
has comment: http://stackoverflow.com/comment/89771545
has comment: http://stackoverflow.com/comment/89771443
type: Question
linked to: http://stackoverflow.com/q/51397205
has title: Python 3.6 Regex Producing Unexpected Results (despite using string literals)
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89771777
accepted answer: http://stackoverflow.com/a/51401386
tagged with: regex
answer count: 1
has comment: http://stackoverflow.com/comment/89771708
has comment: http://stackoverflow.com/comment/89771535
downvote count: 0
has answer: http://stackoverflow.com/a/51401386
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89771639

http://stackoverflow.com/q/51443620
type: Question
score: 3
has body: I saw a piece of code that was like this: class Car: def __init__(self,color,mileage): self.color = color self.mileage = mileage def __str__(self): return 'a {self.color} car'.format(self=self) my_car = Car('blue', 13585) print(my_car) How does the self=self that is used in the str method work?
has answer: http://stackoverflow.com/a/51443747
tagged with: class
upvote count: 3
answer count: 3
has comment: http://stackoverflow.com/comment/89857209
has title: How is .format(self=self) used?
favorite count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 0
linked to: http://stackoverflow.com/q/2709821
has answer: http://stackoverflow.com/a/51443758
has answer: http://stackoverflow.com/a/51443754

http://stackoverflow.com/a/51371238
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51370256
has body: you could do something like: df.groupby('Version').resample('M').nunique() or: df.resample('d')['Version'].unique()

http://stackoverflow.com/a/51471613
has comment: http://stackoverflow.com/comment/89917336
answers question: http://stackoverflow.com/q/51471228
upvote count: 3
has comment: http://stackoverflow.com/comment/89927109
type: Answer
downvote count: 0
has body: Re-Calculating Array Size Per Iteration It looks like we have a couple issues here. The first issue is that you can't update the "stop" value in your inner loop (the range function). So first off, let's remove that and use another while loop to give us the ability to re-calculate our array size every iteration. Re-Checking Values Shifted Into Removed List Spot Next, after you fix that you will run into a larger issue. When you use remove it moves a value from the end of the list or shifts the entire list to the left to use the removed spot, and you are not re-checking the value that got moved into the old values removed spot. To resolve this, we need to decrement i whenever we remove an element, this makes sure we are checking the value that gets placed into the removed elements spot. remove vs del You should use del over remove in this case. remove iterates over the list and removes the first occurrence of the value and it looks like we already know the exact index of the value we want to remove. remove might work, but it's usage here over complicates things a bit. Functional Code with Minimal Changeset def dup(a): i = 0 arraySize = len(a) print(arraySize) while i &lt; arraySize: k = i + 1 while k &lt; arraySize: # CHANGE: use a while loop to have greater control over the array size. if a[i] == a[k]: print("Duplicate found at indexes %d and %d." % (i, k)) del a[i] # CHANGE: used del instead of remove. i -= 1 # CHANGE: you need to recheck the new value that got placed into the old removed spot. arraySize -= 1 break k += 1 i += 1 return a Now, I'd like to note that we have some readability and maintainability issues with the code above. Iterating through an array and manipulating the iterator in the way we are doing is a bit messy and could be prone to simple mistakes. Below are a couple ways I'd implement this problem in a more readable and maintainable manner. Simple Readable Alternative def remove_duplicates(old_numbers): """ Simple/naive implementation to remove …
has comment: http://stackoverflow.com/comment/89912750
score: 3

http://stackoverflow.com/comment/89795105
has text: The answer to the other question only returns the first index. For all the indices, you can do `[index for index,value in enumerate(c) if value == target]`. Note that this will return a list, even if there is only one such value.
comment on: http://stackoverflow.com/q/51411622
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89767923
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51398090
has text: Thanks! It worked! My problems are sending object not class_name, and not sending all kwargs ? but what the mean of TypeError?

http://stackoverflow.com/q/51428183
has comment: http://stackoverflow.com/comment/89828430
upvote count: 1
accepted answer: http://stackoverflow.com/a/51428995
has comment: http://stackoverflow.com/comment/89827989
downvote count: 1
linked to: http://stackoverflow.com/q/1207406
type: Question
has comment: http://stackoverflow.com/comment/89830669
has comment: http://stackoverflow.com/comment/89827691
linked to: http://stackoverflow.com/q/6260089
score: 0
has comment: http://stackoverflow.com/comment/89827966
has comment: http://stackoverflow.com/comment/89828202
has comment: http://stackoverflow.com/comment/89830628
has comment: http://stackoverflow.com/comment/89827832
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89828299
has comment: http://stackoverflow.com/comment/89830014
tagged with: python
has comment: http://stackoverflow.com/comment/89828407
has comment: http://stackoverflow.com/comment/89827873
has answer: http://stackoverflow.com/a/51428995
type: AnsweredQuestion
has title: One-line foreach loop removes alternative elements in list
has body: How come one-line foreach removes alternative elements in list and not removes everything? or how is the implementation of the foreach loop? aList = ['xyz', 1, 'zara', 2, 'xyz'] for i, ele in enumerate(aList): print(i, ele) aList.remove(ele) print(aList) 0 xyz 1 zara 2 xyz [1, 2]

http://stackoverflow.com/q/51481884
has title: Min value in each column of a data frame excluding zeros
linked to: http://stackoverflow.com/q/50586146
score: 6
has comment: http://stackoverflow.com/comment/89932550
has answer: http://stackoverflow.com/a/51482030
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51481962
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89934299
has body: The original dataframe is a table like this: S1_r1_ctrl/ S1_r2_ctrl/ S1_r3_ctrl/ sp|P38646|GRP75_HUMAN 2.960000e-06 5.680000e-06 0.000000e+00 sp|O75694-2|NU155_HUMAN 2.710000e-07 0.000000e+00 2.180000e-07 sp|Q05397-2|FAK1_HUMAN 0.000000e+00 2.380000e-07 7.330000e-06 sp|O60671-2|RAD1_HUMAN NaN NaN NaN I am looking for the smallest value in each column of a dataframe greater than zero. I was trying to use this example to answer my question. My code looks like: df.ne(0).idxmin().to_frame('pos').assign(value=lambda d: df.lookup(d.pos, d.index)) but still I get only zeros and my result looks like this: pos value S1_r1_ctrl/ sp|Q05397-2|FAK1_HUMAN 0.0 S1_r2_ctrl/ sp|O75694-2|NU155_HUMAN 0.0 S1_r3_ctrl/ sp|P38646|GRP75_HUMAN 0.0 instead of this: pos value S1_r1_ctrl/ sp|O75694-2|NU155_HUMAN 2.710000e-07 S1_r2_ctrl/ sp|Q05397-2|FAK1_HUMAN 2.380000e-07 S1_r3_ctrl/ sp|O75694-2|NU155_HUMAN 2.180000e-07 I guess there might be a problem in data types but I'm not sure. I assumed ne(0) would ignore zeros but it doesn't so I am confused why. And perhaps there's a more intelligent way to find what I need.
linked to: http://stackoverflow.com/q/48026397
type: Question
possible better answer: http://stackoverflow.com/a/51482440
tagged with: types
upvote count: 6
favorite count: 0
tagged with: pandas
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/51482242
has answer: http://stackoverflow.com/a/51482440
accepted answer: http://stackoverflow.com/a/51482030
has answer: http://stackoverflow.com/a/51482132
downvote count: 0

http://stackoverflow.com/comment/89904139
comment on: http://stackoverflow.com/a/51466815
type: AnswerComment
score: 0
type: Comment
has text: Thanks, that worked

http://stackoverflow.com/comment/89680365
score: 1
type: AnswerComment
has text: Well, `random.choice` would actually be the method to go for. In any case, answer updated.
type: Comment
comment on: http://stackoverflow.com/a/51353852

http://stackoverflow.com/comment/89783272
type: Comment
has text: Will that interact oddly with double-quotes contained within the variable value, though?
type: AnswerComment
comment on: http://stackoverflow.com/a/51406086
score: 0

http://stackoverflow.com/a/51417421
downvote count: 0
upvote count: 28
has body: I believe this does what you want. You can create a custom Transformer, and add that to the stages in the Pipeline. Note that I slightly changed your functions because we do not have access to all variables you mentioned, but the concept remains the same. Hope this helps! import pyspark.sql.functions as F from pyspark.ml import Pipeline, Transformer from pyspark.ml.feature import Bucketizer from pyspark.sql import DataFrame from typing import Iterable import pandas as pd # CUSTOM TRANSFORMER ---------------------------------------------------------------- class ColumnDropper(Transformer): """ A custom Transformer which drops all columns that have at least one of the words from the banned_list in the name. """ def __init__(self, banned_list: Iterable[str]): super(ColumnDropper, self).__init__() self.banned_list = banned_list def _transform(self, df: DataFrame) -&gt; DataFrame: df = df.drop(*[x for x in df.columns if any(y in x for y in self.banned_list)]) return df # SAMPLE DATA ----------------------------------------------------------------------- df = pd.DataFrame({'ball_column': [0,1,2,3,4,5,6], 'keep_the': [6,5,4,3,2,1,0], 'hall_column': [2,2,2,2,2,2,2] }) df = spark.createDataFrame(df) # EXAMPLE 1: USE THE TRANSFORMER WITHOUT PIPELINE ----------------------------------- column_dropper = ColumnDropper(banned_list = ["ball","fall","hall"]) df_example = column_dropper.transform(df) # EXAMPLE 2: USE THE TRANSFORMER WITH PIPELINE -------------------------------------- column_dropper = ColumnDropper(banned_list = ["ball","fall","hall"]) bagging = Bucketizer( splits=[-float("inf"), 3, float("inf")], inputCol= 'keep_the', outputCol="keep_the_bucket") model = Pipeline(stages=[column_dropper,bagging]).fit(df) bucketedData = model.transform(df) bucketedData.show() Output: +--------+---------------+ |keep_the|keep_the_bucket| +--------+---------------+ | 6| 1.0| | 5| 1.0| | 4| 1.0| | 3| 1.0| | 2| 0.0| | 1| 0.0| | 0| 0.0| +--------+---------------+ Also, note that if your c…
has comment: http://stackoverflow.com/comment/89806753
accepted answer of: http://stackoverflow.com/q/51415784
has comment: http://stackoverflow.com/comment/89807071
score: 28
has comment: http://stackoverflow.com/comment/89876725
has comment: http://stackoverflow.com/comment/89806552
type: Answer
has comment: http://stackoverflow.com/comment/89806666
has comment: http://stackoverflow.com/comment/89877549
has comment: http://stackoverflow.com/comment/89855512
has comment: http://stackoverflow.com/comment/98137698
has comment: http://stackoverflow.com/comment/121173866
answers question: http://stackoverflow.com/q/51415784
has comment: http://stackoverflow.com/comment/89807019
has comment: http://stackoverflow.com/comment/89864039
has comment: http://stackoverflow.com/comment/89855172
has comment: http://stackoverflow.com/comment/89806325
type: AcceptedAnswer

http://stackoverflow.com/a/51352314
has body: This seems to be problem specific to numpy as without it, pickle works just fine in python 3.6.6: import pickle def f(): return [1,2,3] a = f() b = f() c = pickle.loads(pickle.dumps(f())) print(id(a), id(b), id(c)) # 1900503702728 1900503865288 1900503976328 print('[a]==[b]', pickle.dumps([a]) == pickle.dumps([b])) # True print('[a]==[c]', pickle.dumps([a]) == pickle.dumps([c])) # True print('[b]==[c]', pickle.dumps([b]) == pickle.dumps([c])) # True print('[a,b]==[a,c]', pickle.dumps([a,b]) == pickle.dumps([a,c])) # True numpy python pickle nondeterministic python3
type: Answer
answers question: http://stackoverflow.com/q/51351508
score: 0

http://stackoverflow.com/comment/89821031
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51423859
has text: For cheesy reasons x:

http://stackoverflow.com/q/51450041
has comment: http://stackoverflow.com/comment/89871888
has answer: http://stackoverflow.com/a/51450518
has answer: http://stackoverflow.com/a/51450995
type: Question
answer count: 2
tagged with: encoding
score: 0
has title: Translating Unicode Values
tagged with: utf-8
has body: This is a strange question but some time ago, and I don't know where I found this, I was able to add a line in Python using the following code: unicode("\xc4", "cp437") And I don't know how I got to that. I know it's decoding that as a code page 437 and that \xc4 is a line but can find no reference to that - I only know what the output is. Now I want to do the same thing but with a star symbol. The symbol, according to https://www.toptal.com/designers/htmlarrows/symbols/ is: U+0272A (unicode) &amp;#x272A; (hex) &amp;#10026; (html) How do I convert one or more of those values into a similar command to get the star symbol that I'm after? Essentially this is a Python program that interfaces with a Mac software program and I don't know how they interpret all of this once they read and execute the Python script but, as I said, I know the example I posted allows that software to add a solid line to the user interface.
tagged with: python
accepted answer: http://stackoverflow.com/a/51450995
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51450518

http://stackoverflow.com/a/51470114
accepted answer of: http://stackoverflow.com/q/51470071
score: 2
has comment: http://stackoverflow.com/comment/89908577
upvote count: 2
has body: The problem is with your indexing, when you transpose your DataFrame you will get duplicate column names which are messing it up. See below dict1 = [{'var0': 0, 'var1': 0, 'var2': 2}, {'var0': 0, 'var1': 0, 'var2': 4}, {'var0': 0, 'var1': 0, 'var2': 8}, {'var0':0, 'var1': 0, 'var2': 12},] df = pd.DataFrame(dict1, index=['s1', 's2','s1','s2']) df.reset_index().T.drop_duplicates().T.set_index('index')
has comment: http://stackoverflow.com/comment/89908643
answers question: http://stackoverflow.com/q/51470071
has comment: http://stackoverflow.com/comment/89908589
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/51347862
downvote count: 0
score: 1
type: AcceptedAnswer
has body: As far as I understand your problem, I think that computing semantic similarity measure is the solution is what you are looking for. Semantic similarity is a scalar value reporting distance between words (or other linguistic units) based on the likeness of their meaning (you could actually call it relevance). E.g. for words harassment and bullying such value would be high, while for words harassment and programming it would be low. There are different ways to compute semantic similarity. One of the simplest ones based on distance in WordNet graph structure. It is implemented in NLTK. Some toy examples could be fount at NLTK documentation. More effective methods based on machine learning and corpus statistics are called distributional semantic models (Word2Vec is the most ubiquitous one). They represent words with real-valued vectors, and compute similarity between words as a distance between corresponding vectors. Install gensim, download a pre-trained distributional semantic model (for instance, from here), and you will be able to compute similarity value for words (gensim documentation should help). Finally, if you are able to compute a similarity value for a pair words, you can set a heuristic threshold for similarity value when you will be seeking through you dictionary. If the similarity for a suspended word from a sentence will be lower than the threshold for all words in you dictionary, then, probably, it will not be related to harassment. You could also experiment with other measures, e.g. consider word vectors from you dictionary as a cluster, and compute similarity to the centroid of the cluster.
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/51345806
answers question: http://stackoverflow.com/q/51345806

http://stackoverflow.com/a/51417858
has body: Reading the length of a sliced list is complicated. Try this, no hardcode: def myList(list): if len(list) &lt;= 2: print(' and '.join(list)) else: print(', '.join(list[:-1]) + ', and ' + list[-1])
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51417424

http://stackoverflow.com/q/51370602
has answer: http://stackoverflow.com/a/51371149
tagged with: python-3.x
upvote count: 5
has comment: http://stackoverflow.com/comment/89713487
has comment: http://stackoverflow.com/comment/89713661
has title: Inconsistency with `sys.getsizeof`
tagged with: python
has comment: http://stackoverflow.com/comment/89713823
has comment: http://stackoverflow.com/comment/89713471
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/89713791
has comment: http://stackoverflow.com/comment/89713568
has comment: http://stackoverflow.com/comment/89713518
type: Question
possible better answer: http://stackoverflow.com/a/51370746
score: 5
has answer: http://stackoverflow.com/a/51370746
has comment: http://stackoverflow.com/comment/89713753
has comment: http://stackoverflow.com/comment/89713486
has comment: http://stackoverflow.com/comment/89713600
has comment: http://stackoverflow.com/comment/89713541
accepted answer: http://stackoverflow.com/a/51371149
has body: Why is sys.getsizeof() larger for a Python str of length 1 than for a string of length 2? (For length > 2, the relationship seems to increase monotonically as expected.) Example: >>> from string import ascii_lowercase >>> import sys >>> strings = [ascii_lowercase[:i] for i, _ in enumerate(ascii_lowercase, 1)] >>> strings ['a', 'ab', 'abc', 'abcd', 'abcde', 'abcdef', 'abcdefg', # ... >>> sizes = dict(enumerate(map(sys.getsizeof, strings), 1)) >>> sizes {1: 58, # <--- ?? 2: 51, 3: 52, 4: 53, 5: 54, 6: 55, 7: 56, 8: 57, 9: 58, 10: 59, 11: 60, 12: 61, 13: 62, 14: 63, 15: 64, 16: 65, # ... It seems it has to do with str.__sizeof__, but I don't know C well enough at all to dig into what's going on in this case. Edit: This appears to be related to a single Pandas import in an IPython startup file. I can reproduce the behavior in a plain Python session also: ~$ python Python 3.6.6 |Anaconda, Inc.| (default, Jun 28 2018, 11:07:29) [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from string import ascii_lowercase >>> import sys >>> strings = [ascii_lowercase[:i] for i, _ in enumerate(ascii_lowercase, 1)] >>> sizes = dict(enumerate(map(sys.getsizeof, strings), 1)) >>> sizes {1: 50, 2: 51, 3: 52, 4: 53, 5: 54, 6: 55, 7: 56, 8: 57, 9: 58, 10: 59, 11: 60, 12: 61, 13: 62, 14: 63, 15: 64, 16: 65, 17: 66, 18: 67, 19: 68, 20: 69, 21: 70, 22: 71, 23: 72, 24: 73, 25: 74, 26: 75} >>> import pandas as pd >>> sizes = dict(enumerate(map(sys.getsizeof, strings), 1)) >>> sizes {1: 58, 2: 51, 3: 52, 4: 53, 5: 54, 6: 55, 7: 56, 8: 57, 9: 58, 10: 59, 11: 60, 12: 61, 13: 62, 14: 63, 15: 64, 16: 65, 17: 66, 18: 67, 19: 68, 20: 69, 21: 70, 22: 71, 23: 72, 24: 73, 25: 74, 26: 75} >>> pd.__version__ '0.23.2'
has comment: http://stackoverflow.com/comment/89713815
answer count: 2
has comment: http://stackoverflow.com/comment/89713590
tagged with: pandas
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/89713635
has comment: http://stackoverflow.com/comment/89713632

http://stackoverflow.com/a/51429499
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/89857440
answers question: http://stackoverflow.com/q/51423517
downvote count: 0
has comment: http://stackoverflow.com/comment/90261062
type: Answer
has comment: http://stackoverflow.com/comment/89857017
has body: While all that @scharette says is likely true (I don't know enough of Python internals to agree with confidence :) ), I'd like to propose an alternative explanation as to why one can instantiate Test and call foo(): The method's body is not executed until you actually call it. It does not matter if foo() contains references to undefined attributes, it will be parsed fine. As long as you create moo before you call foo, you're ok. Try entering a truncated Test class in your interpreter: class Test(): def __init__(self): self.printer = None def foo(self): self.printer = self.moo self.printer() No moo, so we get this: &gt;&gt;&gt; test = Test() &gt;&gt;&gt; test.foo() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 5, in foo Let's add moo to the class now: &gt;&gt;&gt; def moo(self): ... print("Y u printing?") ... &gt;&gt;&gt; Test.moo = moo &gt;&gt;&gt; test1 = Test() &gt;&gt;&gt; test1.foo() Y u printing? &gt;&gt;&gt; Alternatively, you can add moo directly to the instance: &gt;&gt;&gt; def moo(): ... print("Y u printing?") ... &gt;&gt;&gt; test.moo = moo &gt;&gt;&gt; test.foo() Y u printing? The only difference is that the instance's moo does not take a self (see here for explanation).

http://stackoverflow.com/comment/89860370
has text: im running it on linux virtual machine on aws but when i run the scrapy shell 'http://localhost:8050/render.html?url=https://www6.hertsmere.gov.uk/online-applications/pagedSearchResults.do?action=page&searchCriteria.page=2' i get just some of the html and not the div that holds the planning application details
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51442071
type: AnswerComment

http://stackoverflow.com/a/51372428
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51372389
downvote count: 0
has body: Use sort=False (reference) pd.concat([df4a,df5], sort=False) C B D A E 0 -2.089701 -0.485516 1.610569 -1.048672 NaN 1 -0.675452 -0.367919 -1.610718 -1.624306 NaN
type: Answer
has comment: http://stackoverflow.com/comment/89718170

http://stackoverflow.com/a/51376327
type: AcceptedAnswer
has body: The problem is that you do not change the justify setting each time the option changes. Initializing with .get does not make the value update when the StringVar value changes. One way of applying the new justify setting to the text is to use the command option of the OptionMenu to do it: import tkinter as tk def justify_text(option): """Change text justify setting.""" text.tag_configure('justify', justify=option) # make sure all text has the tag text.tag_add('justify', '1.0', 'end') root = tk.Tk() options = ["right", "center", "left"] var = tk.StringVar(root, options[0]) menu = tk.OptionMenu(root, var, *options, command=justify_text) menu.pack() text = tk.Text(root) text.insert('1.0', "Please enter your notes here", 'justify') text.tag_configure('justify', justify=options[0]) text.pack() root.mainloop()
type: Answer
accepted answer of: http://stackoverflow.com/q/51363285
answers question: http://stackoverflow.com/q/51363285
score: 0

http://stackoverflow.com/comment/89850386
type: Comment
comment on: http://stackoverflow.com/a/51440192
type: AnswerComment
has text: And if you do both it isn't 'TCP only' or 'UDP only'.
score: 0

http://stackoverflow.com/q/51444121
answer count: 2
score: 0
has answer: http://stackoverflow.com/a/51445602
tagged with: http://stackoverflow.com/tag/csv
has title: Python: Parse CSV Data Between 2 Dates and Print in Ascending Order:
has comment: http://stackoverflow.com/comment/89860360
tagged with: parsing
type: UnansweredQuestion
has body: I'm fairly new to Python so please excuse me if this question may be a simple fix or mistake. If you look at the code below i'm trying to parse data from a CSV file. Specially, i'm trying to parse the users created between two dates in ascending order. Any users created in between those two dates, should get printed out in ascending order. My date column row[1] in unix time. There is a word column row[8] that should also be printed. The goal is when the dates are parsed in ascending order the printed word column row[8] forms a specific phrase. The problem is when I execute the code as it is currently in Pycharm I receive an IndexError: list out of range at line 15 creation_date = date.fromtimestamp(int(row[1])). I'm aware that Panda handles CSV files better, but i'm trying to avoid learning Panda for this one task. import csv from datetime import datetime, date import sys start_date = date(2014, 6, 22) end_date = date(2014, 7, 22) # Read csv data into memory filtering rows by the date in column 2 (row[1]). csv_data = [] with open('sample.csv', newline='') as f: reader = csv.reader(f, delimiter='\t') header = next(reader) csv_data.append(header) for row in reader: creation_date = date.fromtimestamp(int(row[1])) if start_date &lt;= creation_date &lt;= end_date: csv_data.append(row) if csv_data: # Anything found? # Print the results in ascending date order. print(" ".join(csv_data[0])) # Converting the timestamp to int may not be necessary (but doesn't hurt) for row in sorted(csv_data[1:], key=lambda r: int(r[1])): print(" ".join(row))
has answer: http://stackoverflow.com/a/51444300
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/89858398
type: Question

http://stackoverflow.com/q/51378645
has answer: http://stackoverflow.com/a/51378712
score: 1
type: Question
has title: LSTM with multiple input attributes, in keras
tagged with: recurrent-neural-network
has body: I'm a quite beginner to RNN, and I'm studying on LSTM. So I'm following the tutorial here. The tutorial uses a input, which has only one attribute other than to the time period. What I'm asking is how can we model if we have multiple attributes as inputs(like in regression). Note that, even if we have multiple attributes, the main attribute(which is going to predicted) is the given attribute called "number of passengers". I really appreciate if you can post examples..
tagged with: lstm
upvote count: 1
answer count: 1
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/89728905
type: UnansweredQuestion
tagged with: python
downvote count: 0

http://stackoverflow.com/q/51417472
favorite count: 0
linked to: http://stackoverflow.com/q/26659142
possible better answer: http://stackoverflow.com/a/51417594
has answer: http://stackoverflow.com/a/51417594
tagged with: python
has comment: http://stackoverflow.com/comment/89805956
duplicate of: http://stackoverflow.com/q/26659142
tagged with: python-3.x
upvote count: 3
has answer: http://stackoverflow.com/a/51417546
type: Question
type: AnsweredQuestion
score: 3
has body: How do I print n lines before a matched string from a file using python? man grep -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. I have code for grep -A: def grepA(word,file,num=0): with open(file) as f: for line in f: if word in line: print(line + ''.join(islice(file, num))) print('---')
has title: What is the code equivalent to grep -B in python?
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/51417546

http://stackoverflow.com/comment/89787484
type: AnswerComment
comment on: http://stackoverflow.com/a/51407236
type: Comment
has text: Can you share the full trace for that example? The only way I get `cypher() missing 1 required positional argument: 'query'` is to call `cypher` with no arguments at all.
score: 0

http://stackoverflow.com/a/51365106
accepted answer of: http://stackoverflow.com/q/51364933
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89702792
has body: Try using the '|' character to join your separate terms in the search string. At the moment your code attempts to match the entire 'cliente problema' string, which none of your rows contain. df = pd.DataFrame(data = ['accensione del drive ribobinatrice ho', 'actions urgente proporre al cliente', 'al cliente upgrade del drive', 'al drive con una smontata', 'causa di un problema di',], columns = ['Name']) Term = 'cliente problema' x_word = df.Name[df.Name.str.contains('|'.join(Term.split(' ')))]
upvote count: 1
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/51364933

http://stackoverflow.com/a/51418187
score: 2
has body: The error message appears to indicate the problem is not with the API version - docker was not even able to connect to your registry (dial tcp 127.0.0.1:5000: getsockopt: connection refused). This means that your registry is simply not reachable at the given address, most likely because it is not on the same host. Note that if you are running k8s in anything other than minikube (where everything is on the same host), you probably have multiple hosts and a 'local' registry is not a solution at all - you would have to have a copy of that registry on every host that is part of your cluster. If you are running minikube (or otherwise have just a single host where kubernetes runs AND that's the same host where you ran the registry), check that the registry is actually on port 5000 and that the port is exposed to the host network (if you started it with a docker command, it should have been with -p 5000:5000 option).
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51406299
type: Answer
has comment: http://stackoverflow.com/comment/89813690
accepted answer of: http://stackoverflow.com/q/51406299

http://stackoverflow.com/comment/89797667
comment on: http://stackoverflow.com/a/51411689
type: Comment
has text: To put it in plain english, bisection returns the index of where to insert the new element. In case of a tie, `bisect_left` would insert it to the left of the equal element, and `bisect_right` to the right. `f<=min_x` prevents the possibility of a tie occurring at index 0, so yes, it fixes.
type: AnswerComment
score: 0

http://stackoverflow.com/q/51422840
has comment: http://stackoverflow.com/comment/89824593
tagged with: sparse-matrix
score: 0
has body: I'm facing a probleme. The folowing code works well but runs slow: I have got 2 scipy LIL matrix one with value stored in and the ozer empty but with a specific shape A.shape --&gt; (X,Y) B.shape --&gt; (Y,Y) with X &lt; Y and a paring dict P = {X1:Y1 ....... X(X):Y(X)} I'm doing set process(A,B,P): for i in P.keys(): B[P[i]]=A[i] any idea how to make this process run faster ? example : A=[[1,2,3,4] [1,2,3,4] [1,2,3,4]] B=[[0,0,0,0] [0,0,0,0] [0,0,0,0] [0,0,0,0]] P={0:0,1:2,2:3} in the end : process(A,B,P)=[[1,2,3,4] [0,0,0,0] [1,2,3,4] [1,2,3,4]] thank you !
has comment: http://stackoverflow.com/comment/89831718
tagged with: python
has title: Efficently copy i'th row of A lil matrix to j'th of B lil matrix
answer count: 0
type: UnansweredQuestion
tagged with: scipy
type: Question

http://stackoverflow.com/comment/89878711
has text: so you want a new column that has tuple of all the unique values???
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51454544
type: QuestionComment

http://stackoverflow.com/comment/115917178
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51481077
has text: @c2huc2hu you are the only one who gave a fix to the issue at hand thanks

http://stackoverflow.com/q/51324463
possible better answer: http://stackoverflow.com/a/51324619
has answer: http://stackoverflow.com/a/51324812
has body: I have two dataframes, df1 and df2, each containing different information and of different length, but with a column 'DAY' in common, though not always with the same value. For context, one data frame contains a record of precipitation, the other contains a record of flood events and their size. I would like to combine them so that I can easily compare what precipitation conditions are associated with flood events. df1 (precipitation) looks like this: D M Y DAY Tpcp MaxInt 30 9 2010 5553 20.8 2.2 1 10 2010 5554 14 1.8 2 10 2010 5555 61.8 1.8 3 10 2010 5556 30 1.2 4 10 2010 5557 68.4 1 5 10 2010 5558 10.2 1 6 10 2010 5559 82.8 2.2 7 10 2010 5560 54.6 2.2 10 10 2010 5563 11.4 1.8 df2 (floods) looks like this: D M Y DAY Size 12 5 2009 5047 2 3 9 2009 5161 2 13 4 2010 5383 3 14 4 2010 5384 3 16 7 2010 5477 2 4 10 2010 5557 3 6 10 2010 5559 3 30 4 2011 5765 2 22 5 2011 5787 2 27 5 2011 5792 2 9 11 2011 5958 2 Floods do not occur on all days with rain, so what I am aiming for looks like this, with zeros for when no event occurs: D M Y DAY Tpcp MaxInt FldSz 30 9 2010 5553 20.8 2.2 0 1 10 2010 5554 14 1.8 0 2 10 2010 5555 61.8 1.8 0 3 10 2010 5556 30 1.2 0 4 10 2010 5557 68.4 1 3 5 10 2010 5558 10.2 1 3 6 10 2010 5559 82.8 2.2 0 7 10 2010 5560 54.6 2.2 0 10 10 2010 5563 11.4 1.8 0 Again, I think the easiest way is to merge/combine according to 'DAY'. Perhaps this is a really obvious task, apologies if so (I am new to this), but I could not find any answers that I thought suited the problem and wondered whether there may be some suggestions out there... thanks in advance for any thoughts and contributions :)
has answer: http://stackoverflow.com/a/51324619
has answer: http://stackoverflow.com/a/51324655
type: AnsweredQuestion
tagged with: dataframe
type: Question
accepted answer: http://stackoverflow.com/a/51324812
score: 0
has title: PANDAS: Combining data frames with IDs in common
has answer: http://stackoverflow.com/a/51324744
tagged with: pandas
tagged with: python
tagged with: merge
answer count: 4

http://stackoverflow.com/comment/89891579
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51461137
has text: change `def hola(): menu.suma()` to `def hola(self): self.suma()`
type: Comment

http://stackoverflow.com/comment/89799966
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51414331
score: 3
has text: Possible duplicate of [How to print dataframe without index](https://stackoverflow.com/questions/24644656/how-to-print-dataframe-without-index). Try `table[[1]].to_string(index=False)`

http://stackoverflow.com/comment/89629058
comment on: http://stackoverflow.com/q/51325193
score: 0
type: Comment
has text: @Mr.T print(Y[0]) returns 8 and print(type(Y[0])) returns <class 'int'>.
type: QuestionComment

http://stackoverflow.com/q/51451006
tagged with: pycharm
type: Question
has answer: http://stackoverflow.com/a/57900289
has title: Keyboard messed up when using Pycharm as an IDE?
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51451123
type: UnansweredQuestion
tagged with: python
has body: Don't get me wrong, Pycharm is an amazing IDE, and with its faults, I've still continued to use it and adapt to its way of working. But its getting pretty tedious not being able to do what I want. Like in other IDE's, I can CTRL+A to select all the text, somehow it almost always messed up in Pycharm, copying all text will result in what ever the INSERT key does, and deletes my content. Clicking backspace doesn't delete the highlighted content, instead I have to deliperatly click the delete key, and this isn't exactly wrong, but it doesn't fit in with other IDE's. I noticed when switching from Pycharm to another IDE, I was doing what I did in Pycharm and it just felt unnatural, is there a way to make Pycharm work like other IDE's?

http://stackoverflow.com/a/51409066
has comment: http://stackoverflow.com/comment/89789776
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89789565
type: Answer
has body: You could do join/apply/rename: In [188]: df.join(df.apply(odds).rename(columns={"mu_post": "odds"})) Out[188]: mu_post odds c t c t 0 0.0 0.0 0.042824 0.051212 0.044740 0.053977 0.5 0.5 0.048293 0.058130 0.050743 0.061718 1.0 1.0 0.047267 0.074043 0.049612 0.079964 1 0.0 0.0 0.058205 0.054106 0.061802 0.057201 0.5 0.5 0.064153 0.063573 0.068551 0.067889 1.0 1.0 0.056918 0.059572 0.060353 0.063346 2 0.0 0.0 0.059032 0.052211 0.062735 0.055087 0.5 0.5 0.070616 0.066792 0.075982 0.071573 1.0 1.0 0.056892 0.045061 0.060324 0.047187
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51408970
score: 3
answers question: http://stackoverflow.com/q/51408970

http://stackoverflow.com/a/51468089
score: 2
accepted answer of: http://stackoverflow.com/q/51468057
answers question: http://stackoverflow.com/q/51468057
has body: I think is necessary convert column INCIDENT_DATE to datetimes by to_datetime and then add DispatchTime column, because timedeltas: print (dfdate.dtypes) INCIDENT_DATE object DispatchTime timedelta64[ns] dtype: object dfdate['date'] = pd.to_datetime(dfdate['INCIDENT_DATE']) + dfdate['DispatchTime'] print (dfdate) INCIDENT_DATE DispatchTime date 720344 31/12/2016 00:15:04 2016-12-31 00:15:04 720345 31/12/2016 00:12:20 2016-12-31 00:12:20 720346 31/12/2016 00:14:37 2016-12-31 00:14:37 720347 31/12/2016 00:18:42 2016-12-31 00:18:42
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/comment/89817385
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51422883
has text: Ok, I'm sorry, I thought you were somehow getting the column header mixed up in your data, as opposed to having a "wrong" row in there. Wald's answer is probably what you're looking for.
type: Comment

http://stackoverflow.com/q/51362412
has title: exchangelib: looking for winkerberos on an OS X system
answer count: 1
tagged with: python
favorite count: 0
has body: I am attempting to install exchangelib on a Mac (OS X 10.13.5). I was having issues with the install, so I created a minimal environment in which to work: pushd /tmp curl -SLO https://repo.continuum.io/miniconda/Miniconda3-latest-MacOSX-x86_64.sh bash ./Miniconda3-latest-MacOSX-x86_64.sh -b -p /tmp/lxml source /tmp/lxml/bin/activate conda create -n py35 python=3.5 lxml -y source activate py35 I then installed exchangelib within that environment. When I attempt to use it, though, I find that it's trying to load winkerberos instead of pykerberos. &gt;&gt;&gt; import exchangelib Traceback (most recent call last): File "/tmp/lxml/envs/py35/lib/python3.5/site-packages/requests_kerberos/kerberos_.py", line 2, in &lt;module&gt; import kerberos ImportError: dlopen(/tmp/lxml/envs/py35/lib/python3.5/site-packages/kerberos.cpython-35m-darwin.so, 2): Symbol not found: _mempcpy Referenced from: /tmp/lxml/envs/py35/lib/python3.5/site-packages/kerberos.cpython-35m-darwin.so Expected in: flat namespace in /tmp/lxml/envs/py35/lib/python3.5/site-packages/kerberos.cpython-35m-darwin.so During handling of the above exception, another exception occurred: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/tmp/lxml/envs/py35/lib/python3.5/site-packages/exchangelib/__init__.py", line 4, in &lt;module&gt; from .account import Account File "/tmp/lxml/envs/py35/lib/python3.5/site-packages/exchangelib/account.py", line 12, in &lt;module&gt; from exchangelib.services import GetUserOofSettings, SetUserOofSettings File "/tmp/lxml/envs/py35/lib/python3.5/site-packages/exchangelib/services.py", line 37, in &lt;module&gt; from .transport import wrap, extra_headers, SOAPNS, TNS, MNS, ENS File "/tmp/lxml/envs/py35/lib/python3.5/site-packages/exchangelib/transport.py", line 9, in &lt;module&gt; import requests_kerberos File "/tmp/lxml/envs/py35/lib/python3.5/site-packages/requests_kerberos/__init__.py", line 17, in &lt;module&gt; from .kerberos_ import HTTPKerbero…
type: UnansweredQuestion
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/52469212
type: Question
tagged with: exchange-server
downvote count: 0

http://stackoverflow.com/comment/89770375
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51372009
has text: @abarnert Ok, I will download these files again tonight. Its a 7.5GB tarball (25GB untarred) according to the README on GitHub, it might take some time and I wonder this huge size to download is related to the issue

http://stackoverflow.com/comment/89895902
type: QuestionComment
comment on: http://stackoverflow.com/q/51463406
score: 1
has text: Welcome to Stackoverflow, I understand this is your first question, but it doesn't meet the standard quality expected, please read stackoverflow.com/help/how-to-ask to have some guidance. For instance you don't provide the error you actually get, and the language you use, so edit the question (don't add comments) and fix that.
type: Comment

http://stackoverflow.com/comment/104030553
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51424857
has text: I believe OP is saying if you run the seed cell and then immediately call choice() in another cell you get some value X but _even after you re-run the seed cell_ re-running the choice() cell gives a different value Y.
type: QuestionComment

http://stackoverflow.com/comment/89716259
type: QuestionComment
has text: Yes, this is an approach. Please consider factor since it is going to be a video processing. Lets go a step back, how connected components at opencv labelling work? What about hacking it? So it's get updated instead of recalculated?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51325461

http://stackoverflow.com/comment/89914885
has text: Are you trying to query the sqlite table by the help of a custom library? Can you share the docs which led you to try `acf1 = KAch.query.order_by(KAch.reg.desc()).all()`?
score: 0
comment on: http://stackoverflow.com/q/51473281
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89757124
type: QuestionComment
comment on: http://stackoverflow.com/q/51392643
has text: Welcome to stackoverflow, Please see [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) before asking a question and, see [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)
score: 0
type: Comment

http://stackoverflow.com/a/60067426
type: Answer
has body: It looks like you are using the embeddable distribution of CPython rather than one of the regular installers. As described on the documentation page: The embedded distribution is a ZIP file containing a minimal Python environment. It is intended for acting as part of another application, rather than being directly accessed by end-users. Since you seem to be directly accessing Python rather than embedding it, you should consider using the regular (or Microsoft Store) installer (also described on the page I linked above).
answers question: http://stackoverflow.com/q/51403126
score: 0

http://stackoverflow.com/comment/89684201
score: 2
has text: First of all I would suggest to add a relation between LinuxJobTable and UseridUsername tables. Once a relation is there, you won't need to explicitly make a join between these two tables.
comment on: http://stackoverflow.com/q/51355922
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89704187
comment on: http://stackoverflow.com/q/51365661
score: 0
type: Comment
type: QuestionComment
has text: SO is *not* a tutorial service, and your question is not about programming (i.e. it is arguably off-topic here); before starting to implement such things, it is expected that you are familiar with some basic concepts, at least at an elementary level. Keep googling (and notice that Keras has an early stopping option)...

http://stackoverflow.com/comment/89903047
comment on: http://stackoverflow.com/q/51467270
has text: So what's your question? This is obviously JSON, what's preventing you from using it?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51409773
has comment: http://stackoverflow.com/comment/89980479
type: Answer
has comment: http://stackoverflow.com/comment/89980528
has comment: http://stackoverflow.com/comment/89979999
has comment: http://stackoverflow.com/comment/89980653
has comment: http://stackoverflow.com/comment/89980352
has comment: http://stackoverflow.com/comment/89980737
has body: The error occurred because you were passing a Unicode object to be read as an image file. The line img = easygui.fileopenbox() returned img as a Unicode not an image array as expected. How do you convert this? First convert the unicode to a string. There is a library, unicodedatafor just this purpose. (I have shown how to use it in the code below) Next read this string and store the resulting image file as an array. The following code will help you out Code: import numpy as np import cv2 import easygui import unicodedata path = 'C:/Users/Jackson/Desktop/Stack/face_detection/' face_cascade = cv2.CascadeClassifier(path + 'haarcascade_frontalface_default.xml') uni_img = easygui.fileopenbox() img_path = unicodedata.normalize('NFKD', uni_img).encode('ascii','ignore') img = cv2.imread(img_path, 1) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x,y,w,h) in faces: cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) roi_gray = gray[y:y+h, x:x+w] roi_color = img[y:y+h, x:x+w] cv2.imshow('img',img) cv2.waitKey(0) cv2.destroyAllWindows() UPDATE: I have made necessary modifications to the code provided by you. Just copy the following and execute it: import numpy as np import cv2 as cv import easygui face_cascade = cv.CascadeClassifier('face.xml') def todo(): #--- returns the Unicode --- uni_code = easygui.fileopenbox() #--- converting unicode to string --- img_path = unicodedata.normalize('NFKD', uni_code).encode('ascii','ignore') img = cv2.imread(img_path, 1) gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 7, 7) for (x,y,w,h) in faces: cv.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) roi_gray = gray[y:y+h, x:x+w] roi_color = img[y:y+h, x:x+w] cv.imshow('img',img) cv.waitKey(0) cv.destroyAllWindows() todo()
downvote count: 1
has comment: http://stackoverflow.com/comment/89979452
score: 1
accepted answer of: http://stackoverflow.com/q/51408987
has comment: http://stackoverflow.com/comment/89979722
upvote count: 2
answers question: http://stackoverflow.com/q/51408987
has comment: http://stackoverflow.com/comment/89980183
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89980662

http://stackoverflow.com/q/51465483
score: 1
has answer: http://stackoverflow.com/a/51465559
has comment: http://stackoverflow.com/comment/89899733
favorite count: 0
has title: What's wrong with my solution about Sqrt(x)
type: Question
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89899617
has body: The webpage to test the code is here: https://leetcode.com/problems/sqrtx/description/ I handed in these code and passed: class Solution(object): def mySqrt(self, x): """ :type x: int :rtype: int """ if x==1: return 1 lowest=0.0 uppest=x*1.0 count=1 middle=(lowest+uppest)*0.5 while (abs(middle*middle-x)&gt;0.001) and (count&lt;=10000): if middle*middle&gt;x: uppest=middle else: lowest=middle middle=(lowest+uppest)*0.5 count=count+1 return int(middle) but when I change while (abs(middle*middle-x)&gt;0.001) and (count&lt;=10000): into while (abs(middle*middle-x)&gt;0.0001) and (count&lt;=10000): or add more '0' like 0.00000000001 and use '9' as an input to test, it gets wrong The output should be 3, but I got 2 How can I solve this kind of problem while using the Bisection Method? I don't want to use the library (I know that using library is the easiest way but I want to learn more)
accepted answer: http://stackoverflow.com/a/51465559
answer count: 3
has comment: http://stackoverflow.com/comment/89899580
possible better answer: http://stackoverflow.com/a/51465562
has answer: http://stackoverflow.com/a/51465577
has answer: http://stackoverflow.com/a/51465562
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/89899889

http://stackoverflow.com/comment/89836674
type: Comment
comment on: http://stackoverflow.com/a/51388163
type: AnswerComment
has text: Yeah, that's the approach suggested by Andrej Kesey. And it seems to work as expected. I had hope to find some faster way to do it. But maybe that's as good as Pillow can go.
score: 0

http://stackoverflow.com/q/51350506
has body: I am evaluating different options for authentication in a python App Engine flex environment, for apps that run within a G Suite domain. I am trying to put together the OpenID Connect "Server flow" instructions here with how google-auth-library-python implements the general OAuth2 instructions here. I kind of follow things up until 4. Exchange code for access token and ID token, which looks like flow.fetch_token, except it says "response to this request contains the following fields in a JSON array," and it includes not just the access token but the id token and other things. I did see this patch to the library. Does that mean I could use some flow.fetch_token to create an IDTokenCredentials (how?) and then use this to build an OpenID Connect API client (and where is that API documented)? And what about validating the id token, is there a separate python library to help with that or is that part of the API library? It is all very confusing. A great deal would be cleared up with some actual "soup to nuts" example code but I haven't found anything anywhere on the internet, which makes me think (a) perhaps this is not a viable way to do authentication, or (b) it is so recent the python libraries have not caught up? I would however much rather do authentication on the server than in the client with Google Sign-In. Any suggestions or links to code are much appreciated.
answer count: 2
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/51365692
has title: How to use google python oauth libraries to implement OpenID Connect?
tagged with: google-app-engine
tagged with: openid-connect
tagged with: python
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/51354880
accepted answer: http://stackoverflow.com/a/51354880
type: Question
has answer: http://stackoverflow.com/a/51365692
tagged with: google-oauth
upvote count: 2

http://stackoverflow.com/q/51471128
type: AnsweredQuestion
score: 1
tagged with: dialogflow-es
tagged with: mysql
type: Question
has title: Possibility of connecting MySQL database to Google Assistant
upvote count: 1
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51471645
tagged with: python
has body: What I want to implement is at least a working prototype of a Google Assistant Action with the use of local MySQL database. What I've taught of is MySQL DB-> Google Cloud Platform-> DialogFlow -> Google Assistant. So the end product would be for example, I say: "What is my total sales" and Google Assistant would retrieve the data from MySQL. I've been trying to look for solutions online and none seem to match what I am looking for. Would this solution be theoretically possible? and how would I be able to integrate the cloud platform into the Google Assistant Action through DialogFlow? Thanks!
downvote count: 0
has answer: http://stackoverflow.com/a/51471645
tagged with: actions-on-google

http://stackoverflow.com/a/51457365
has comment: http://stackoverflow.com/comment/89884402
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51457267
accepted answer of: http://stackoverflow.com/q/51457267
type: Answer
upvote count: 3
has body: A few issues with your current solution: Your exponentiation operator should be ** not ^ which is XOR. You should start range from 0 not 1 (then first multiplier is -1**0 = 1) Change one of the numbers in the division to float, to avoid integer division in Python 2. def main(n, x): g = 0 for i in range(n): g += ((-1)**i) * (x**(2*i+1))/float(2*i+1) return g
score: 3
has comment: http://stackoverflow.com/comment/89884647

http://stackoverflow.com/q/51468317
tagged with: python
has comment: http://stackoverflow.com/comment/89905121
has comment: http://stackoverflow.com/comment/89905120
score: 1
upvote count: 5
type: Question
tagged with: split
has answer: http://stackoverflow.com/a/51468354
answer count: 1
linked to: http://stackoverflow.com/q/16645083
has title: Why do Python " ".split() and " ".split(" ") produce different result?
downvote count: 4
duplicate of: http://stackoverflow.com/q/16645083
tagged with: string
has body: This is the result when I apply split() against an empty string with default delimiter and with a " " as delimiter in Python. &gt;&gt;&gt; print(" ".split(" ")) ['',''] &gt;&gt;&gt; print(" ".split()) [] Can somebody please explain?
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89905118
type: UnansweredQuestion

http://stackoverflow.com/a/51354974
type: Answer
has comment: http://stackoverflow.com/comment/89688179
has body: Your code should be like this: from requests import get from bs4 import BeautifulSoup # lists to store data names = [] gp = [] arenaRank = [] url = 'https://swgoh.gg/g/21284/gid-1-800-druidia/' response = get(url) soup = BeautifulSoup(response.text, 'html.parser') type(soup) members = soup.find_all('tr') members.sort() for users in members: name = users.td.a.strong.text names.append(name) print(names) You can change count to 0 because python indexing starts from 0, but best is still to directly do it from the iterator users
score: 0
answers question: http://stackoverflow.com/q/51354714

http://stackoverflow.com/a/51367747
has body: Let me start with a small clarification. Actors in VTK are simple container objects that combine geometric data and visualization properties for rendering. VTK does not offer much functionality on the level of actors. If you want to detect colliding objects, you need to solve this for the geometries (vtkPolyData). There is no generic collision-detection- or body-intersection-engine in VTK. What you can do in VTK is to apply boolean operations. However, this is not easy to achieve robustly. There are two main approaches: Method A: Boolean operations on the mesh Use [vtkBooleanOperationPolyDataFilter][1] to apply boolean operations directly on the mesh. See here for an example. Unfortunately, this will fail in your case because of the mesh properties of your surfaces (hit key W when looking at the surface in the RenderWindow to inspect the wireframe of your mesh). vtkBooleanOperationPolyDataFilter will perform best if the mesh's triangles are small and have decent condition numbers, that is, if the triangles are not too spiky. (See the manual of the Verdict toolbox for some triangle metrics.) The mesh of your extruded disks, however, consists of very long, spiky triangles. What you would need to do is to first remesh the surface. VTK does not offer remeshing facilities out of the box, but related toolboxes such as VMTK do. Getting approach (A) right for generic geometries is tricky, because you may end up with non-manifold or leaky surfaces. Also, vtkBooleanOperationPolyDataFilter is known to have some bugs (see here or here). Let's hope that these problems will be fixed some day. Method B: Boolean operations on implicit functions A second approach is to work with implicit functions. For instance, you can represent your tubes as implicit cylinders, and intersect these using [vtkImplicitBoolean][7]. See here for an example. The problem with this approach is that you need to convert the implicit representation of the objects to yield the resulting surface mesh. The marc…
has comment: http://stackoverflow.com/comment/89744930
type: Answer
accepted answer of: http://stackoverflow.com/q/51357557
score: 3
answers question: http://stackoverflow.com/q/51357557
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/89720385
type: AcceptedAnswer

http://stackoverflow.com/comment/131447980
type: Comment
has text: Hey! I found the problem of using next() in a lambda interesting, so I looked around a bit for a solution akin to the dict. get()'s default value argument, which substitutes the exception with a default return. I don't know whether this was already the case when you posted, but next() actually works the same. So you could even drop the separate error handling function and reduce your solution to next((n for n in lst if n%5==0), None)
type: AnswerComment
comment on: http://stackoverflow.com/a/51411190
score: 0

http://stackoverflow.com/q/51457286
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51457556
has body: I am trying to build a neural network to predict 3 output values out of 63 inputs. I have a dataset containing two numpy arrays with the shape of [8100, 63] and [8100, 3] but when I try to feed them to Keras the model does not converge and the mean squared error is in the area of 10^11. The function i used to calculate the Data does not have any non-linear properties so i first thought that one or two layers should be enough. with three layers the MSE is still in the area of 10^10 and I am not sure what I am doing wrong. The regression should return three absolute Values which can be bigger than 1 - this is the reason why I didn't use softmax layers. I would be really grateful for any input or help! import numpy as np from keras.models import * from keras.layers import Dense from keras import optimizers from keras.utils import plot_model np.random.seed(7) #Define Input tf_features_64 = np.load("IN.npy") tf_labels_64 = np.load("OUT.npy") tf_features_32 = tf_features_64.astype(np.float32) tf_labels_32 = tf_labels_64.astype(np.float32) X = tf_features_32 Y = tf_labels_32 #create Layers visible = Input(shape=(63,)) x = Dense(100, activation='relu')(visible) x = Dense(100, activation='relu')(x) x = Dense(100, activation='relu')(x) x = Dense(70, activation='relu')(x) x = Dense(30, activation='relu')(x) output = Dense(3)(x) Optimizer = optimizers.adam(lr=0.001) model = Model(inputs=visible, outputs = output) model.compile(optimizer=Optimizer, loss='categorical_crossentropy', metrics=['mse'] ) model.fit(X, Y, epochs=400, batch_size=300, shuffle=True) print(model.summary)
type: Question
score: 0
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/51457556
tagged with: keras
favorite count: 0
tagged with: python
has title: Does my Keras multiple output NN not converge because i have not sufficient layers?
tagged with: regression
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/89884339
downvote count: 1

http://stackoverflow.com/comment/89937167
type: Comment
type: QuestionComment
has text: Well I guess I have to live with this. My use case is that I modify some records on button click (e.g. add records to many2many, clear the filter as shown above). But these actions cannot be undone which breaks with the normal user expectations
score: 0
comment on: http://stackoverflow.com/q/51446084

http://stackoverflow.com/comment/89717783
score: 0
type: Comment
has text: `infinite q` does not sound appropriate. The way to loop over a queue remains the same to python's basics. If the answer helped, appreciate if you could accept it. Thanks
comment on: http://stackoverflow.com/a/51371704
type: AnswerComment

http://stackoverflow.com/a/51466273
upvote count: 1
answers question: http://stackoverflow.com/q/51466153
type: Answer
downvote count: 0
score: 1
has body: Python has a built-in csv module. This section's example gives a simple example on how to use a writer to write rows to your csv.

http://stackoverflow.com/q/51371444
answer count: 4
downvote count: 0
has answer: http://stackoverflow.com/a/71237136
linked to: http://stackoverflow.com/q/42391598
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/70233779
has answer: http://stackoverflow.com/a/59799960
has answer: http://stackoverflow.com/a/59187688
score: 5
has body: I have a series of 1D time series that, through a series of convolutional layers, end up in the form of: (batch_size, time_series_length, num_filters) I would like to manually upsample the tensors by inserting alternating zeros (much like a tranposed convolution), such that the new dimensionality becomes (batch_size, 2*time_series_length, num_filters) in order to be able to include an additional step before a convolutional layer. It is simple to do this in numpy, for example, with np.insert, but how does one do it with tensors? I have looked at a few similar posts such as this, but I don't understand how to do this with multiple dimensions while preserving the other dimensions. Any thoughts?
has title: Tensorflow upsampling by zero insertion with multiple dimensions
favorite count: 0
upvote count: 5
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51411971
has comment: http://stackoverflow.com/comment/89795902
tagged with: datetime
tagged with: python
type: AnsweredQuestion
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/89797534
type: Question
has answer: http://stackoverflow.com/a/51413311
tagged with: dataframe
linked to: http://stackoverflow.com/q/24567078
has body: I'm using/learning Pandas to load a csv style dataset where I have a time column that can be used as index. The data is sampled roughly at 100Hz. Here is a simplified snippet of the data: Time (sec) Col_A Col_B Col_C 0.0100 14.175 -29.97 -22.68 0.0200 13.905 -29.835 -22.68 0.0300 12.257 -29.32 -22.67 ... ... 1259.98 -0.405 2.205 3.825 1259.99 -0.495 2.115 3.735 There are 20 min of data, resulting in about 120,000 rows at 100 Hz. My goal is to select those rows within a certain time range, say 100-200 sec. Here is what I've figured out import panda as pd df = pd.DataFrame(my_data) # my_data is a numpy array df.set_index(0, inplace=True) df.columns = ['Col_A', 'Col_B', 'Col_C'] df.index = pd.to_datetime(df.index, unit='s', origin='1900-1-1') # the date in origin is just a space-holder My dataset doesn't include the date. How to avoid setting a fake date like I did above? It feels wrong, and also is quite annoying when I plot the data against time. I know there are ways to remove date from the datatime object like here. But my goal is to select some rows that are in a certain time range, which means I need to use pd.date_range(). This function does not seem to work without date. It's not the end of the world if I just use a fake date throughout my project. But I'd like to know if there are more elegant ways around it.
has title: Select a time range in DataFrame without date
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51413311

http://stackoverflow.com/a/51436394
accepted answer of: http://stackoverflow.com/q/51431160
has body: Make a structured array and write it to csv: In [131]: arr=np.ones((3,), dtype='i,f,U10,i,f') In [132]: arr['f2']=['a','bc','def'] In [133]: arr Out[133]: array([(1, 1., 'a', 1, 1.), (1, 1., 'bc', 1, 1.), (1, 1., 'def', 1, 1.)], dtype=[('f0', '&lt;i4'), ('f1', '&lt;f4'), ('f2', '&lt;U10'), ('f3', '&lt;i4'), ('f4', '&lt;f4')]) In [134]: np.savetxt('test',arr,fmt='%d,%e,%s,%d,%f') In [135]: cat test 1,1.000000e+00,a,1,1.000000 1,1.000000e+00,bc,1,1.000000 1,1.000000e+00,def,1,1.000000 load all columns with dtype=None: In [137]: np.genfromtxt('test',delimiter=',',dtype=None,encoding=None) Out[137]: array([(1, 1., 'a', 1, 1.), (1, 1., 'bc', 1, 1.), (1, 1., 'def', 1, 1.)], dtype=[('f0', '&lt;i8'), ('f1', '&lt;f8'), ('f2', '&lt;U3'), ('f3', '&lt;i8'), ('f4', '&lt;f8')]) load a subset of the columns: In [138]: np.genfromtxt('test',delimiter=',',dtype=None,encoding=None,usecols= ...: (1,2,4)) Out[138]: array([(1., 'a', 1.), (1., 'bc', 1.), (1., 'def', 1.)], dtype=[('f0', '&lt;f8'), ('f1', '&lt;U3'), ('f2', '&lt;f8')])
answers question: http://stackoverflow.com/q/51431160
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89867293
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89869316
has comment: http://stackoverflow.com/comment/89868759
type: Answer

http://stackoverflow.com/q/51395250
has body: Trying to take a Json input from user and display it with proper json formatting: Below is the python code: @app.route('/') def my_form(): return render_template('my-form.html') @app.route('/', methods=['POST']) def my_form_post(): text = request.form['text'] return jsonify(request.form) if __name__ == '__main__': app.run(host='0.0.0.0') Here is the html code: &lt;form method="POST"&gt; &lt;input name="text"&gt; &lt;input type="submit"&gt; &lt;/form&gt; Here is the output: What mistake am I doing here to get the result on the flask page in proper json format ? This is the output i'm getting: text "{\"a\":1,\"b\":2,\"c\":3}" Desired Op: { "a":1, "b":2, "c":3 }
answer count: 1
has comment: http://stackoverflow.com/comment/89767618
has answer: http://stackoverflow.com/a/51395465
tagged with: flask
favorite count: 0
tagged with: python
has title: Display Json formatted input from Flask in python
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89767932
downvote count: 1
score: 2
has comment: http://stackoverflow.com/comment/89763354
has comment: http://stackoverflow.com/comment/89762226
type: Question
has comment: http://stackoverflow.com/comment/89761953

http://stackoverflow.com/comment/89708201
score: 0
type: Comment
type: QuestionComment
has text: You need to add `random_state` into your regression model
comment on: http://stackoverflow.com/q/51367877

http://stackoverflow.com/a/51373620
upvote count: 1
answers question: http://stackoverflow.com/q/51373567
has comment: http://stackoverflow.com/comment/89735398
has comment: http://stackoverflow.com/comment/89720920
downvote count: 0
has body: You can use the dir method to get the last modified timestamps from the file listing, and parse the 6th to 8th fields on your own. Note that the 8th field can be either a year or a time of the day, in which case the year is the current year. But then again you don't necessarily have to parse the date/time at all since all you need is to detect change. &gt;&gt;&gt; from ftplib import FTP &gt;&gt;&gt; ftp = FTP('ftp.redhat.com') &gt;&gt;&gt; ftp.login() '230 Login successful.' &gt;&gt;&gt; ftp.dir() lrwxrwxrwx 1 ftp ftp 1 Dec 19 2009 pub -&gt; . drwxr-xr-x 45 ftp ftp 4096 Jul 05 16:46 redhat &gt;&gt;&gt; l=[] &gt;&gt;&gt; ftp.dir(lambda x: l.append(x)) &gt;&gt;&gt; l ['lrwxrwxrwx 1 ftp ftp 1 Dec 19 2009 pub -&gt; .', 'drwxr-xr-x 45 ftp ftp 4096 Jul 05 16:46 redhat'] &gt;&gt;&gt;
accepted answer of: http://stackoverflow.com/q/51373567
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89735729
type: Answer
has comment: http://stackoverflow.com/comment/89735149
has comment: http://stackoverflow.com/comment/89735472
score: 1

http://stackoverflow.com/q/51390551
has answer: http://stackoverflow.com/a/55840400
accepted answer: http://stackoverflow.com/a/55840400
favorite count: 0
has title: What are all the fields in a Python ntplib response, and how are they used?
tagged with: python
score: 8
possible better answer: http://stackoverflow.com/a/67233421
downvote count: 0
has answer: http://stackoverflow.com/a/69378633
has answer: http://stackoverflow.com/a/67233421
has body: I'd like to make a measurement of the difference between a local clock, and a remote processor running an NTP server. I can get the tx_time of the response, as shown below, but a better estimate would include some estimate of the network delays. There are other fields in the NTP response message which should be used, as well. import ntplib from time import ctime,time addr_remote = '128.128.204.207' c = ntplib.NTPClient() remote = c.request(addr_remote) local = time() print("REMOTE: " + ctime(remote.tx_time) + " &lt;reference clock&gt; ") print("LOCAL: " + ctime(local) + " delta: " + str(local - remote.tx_time )) If I look at "remote": for attr in dir(remote): print("remote.%s = %r" % (attr, getattr(remote, attr))) I see: remote.delay = 0.0 remote.dest_time = 1531863145.9309998 remote.dest_timestamp = 3740851945.9309998 remote.from_data = &lt;bound method NTPPacket.from_data of &lt;ntplib.NTPStats object at 0x000000000265B2E8&gt;&gt; remote.leap = 0 remote.mode = 4 remote.offset = -1.8789582252502441 remote.orig_time = 1531863145.9309998 remote.orig_timestamp = 3740851945.9309998 remote.poll = 0 remote.precision = -7 remote.recv_time = 1531863144.0520415 remote.recv_timestamp = 3740851944.0520415 remote.ref_id = 0 remote.ref_time = 0.0 remote.ref_timestamp = 2208988800.0 remote.root_delay = 0.0 remote.root_dispersion = 0.0 remote.stratum = 9 remote.to_data = &lt;bound method NTPPacket.to_data of &lt;ntplib.NTPStats object at 0x000000000265B2E8&gt;&gt; remote.tx_time = 1531863144.0520415 remote.tx_timestamp = 3740851944.0520415 So, how do I use these: dest_time orig_time recv_time tx_time to remove the network delays, and get a better estimate of the clock difference?
tagged with: ntp
upvote count: 8
type: Question
type: AnsweredQuestion
answer count: 3

http://stackoverflow.com/comment/89749641
score: 1
comment on: http://stackoverflow.com/q/51388818
type: Comment
type: QuestionComment
has text: There is a datatype `set` in python generally supporting usual set operations.

http://stackoverflow.com/a/68003607
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51369663
type: Answer
has body: @chrisb has a great answer above. This answer should add a bit of clarification for those newer to vectorization. In terms of vectorization (in numpy and numba), you pass vectors of inputs. For example: import numpy as np a=[1,2] b=[3,4] @np.vectorize def f(x_1,x_2): return x_1+x_2 print(f(a,b)) #-&gt; [4,6] In numba, you would traditionally need to pass in input types to the vectorize decorator. In more recent versions of numba, you do not need to specify vector input types if you pass in numpy arrays as inputs to a generically vectorized function. For example: import numpy as np import numba as nb a=np.array([1,2]) b=np.array([3,4]) # Note a generic vectorize decorator with input types not specified @nb.vectorize def f(x_1,x_2): return x_1+x_2 print(f(a,b)) #-&gt; [4,6] So far, variables are simple single objects that get passed into the function from the input arrays. This makes it possible for numba to convert the python code to simple ufuncs that can operate on the numpy arrays. In your example of summing up a vector, you would need to pass data as a single vector of vectors. To do this you need to create ufuncs that operate on vectors themselves. This requires a bit more work and specification for how you want the arbitrary outputs to be created Enter the guvectorize function (docs here and here). Since you are providing a vector of vectors. Your outer vector is approached similar to how you use vectorize above. Now you need to specify what each inner vector looks like for your input values. EG adding an arbitrary vector of integers. (This will not work for a few reasons explained below) @nb.guvectorize([(nb.int64[:])]) def f(x): return x.sum() Now you will also need to add an extra input to your function and decorator. This allows you to specify an arbitrary type to store the output of your function. Instead of returning output, you will now update this input variable. Think of this final variable as a custom variable numba uses to generate an arbitrary outpu…
score: 2
downvote count: 0
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51369663

http://stackoverflow.com/a/51350716
type: Answer
downvote count: 0
score: 1
has body: As you're using python-slackclient, that's pretty straight forward. Currently you call postMessage with the following parameters: slack_client.api_call( "chat.postMessage", channel=channel, text=response or default_response ) You simply need to add the desired parameters to your code like: slack_client.api_call( "chat.postMessage", channel=channel, text=response or default_response, icon_url='https://example.tld/icon.png', username='gallagherbot', as_user=False ) Mind that it's as_user and not is_user as stated in your question. Also mind that as_user must be omitted if you're building a Slack app for the previewed new workspace-style.
upvote count: 1
answers question: http://stackoverflow.com/q/51350538

http://stackoverflow.com/q/51396471
has body: airflow task is unable to connect to remote oracle database but i am able to connect to the same remote oracle database using the same code from python shell. i checked running environment is same for both the shell and airflow. i am attaching the log error which i am getting. [2018-07-18 13:12:11,037] {models.py:1428} INFO - Executing &lt;Task(AadharNumberValidation): validating_data&gt; on 2018-07-18 07:42:05.573491 [2018-07-18 13:12:11,037] {base_task_runner.py:115} INFO - Running: ['bash', '-c', 'airflow run data_validation validating_data 2018-07-18T07:42:05.573491 --job_id 206 --raw -sd /Users/b0204890/Desktop/python/airflow_home/dags/data_validaton.py'] [2018-07-18 13:12:11,531] {base_task_runner.py:98} INFO - Subtask: [2018-07-18 13:12:11,531] {__init__.py:45} INFO - Using executor SequentialExecutor [2018-07-18 13:12:11,588] {base_task_runner.py:98} INFO - Subtask: [2018-07-18 13:12:11,588] {models.py:189} INFO - Filling up the DagBag from /Users/b0204890/Desktop/python/airflow_home/dags/data_validaton.py [2018-07-18 13:12:11,661] {cli.py:374} INFO - Running on host LTB0204890-Mac.local [2018-07-18 13:12:11,669] {base_task_runner.py:98} INFO - Subtask: [2018-07-18 13:12:11,669] {validation_operators.py:37} INFO - operator_param yadav: Script one validation [2018-07-18 13:12:11,678] {models.py:1595} ERROR - DPI-1047: 64-bit Oracle Client library cannot be loaded: "dlopen(libclntsh.dylib, 1): image not found". See https://oracle.github.io/odpi/doc/installation.html#macos for help Traceback (most recent call last): File "/Users/b0204890/venv/python3/lib/python3.6/site-packages/airflow/models.py", line 1493, in _run_raw_task result = task_copy.execute(context=context) File "/Users/b0204890/Desktop/python//airflow_home/plugins/validation_operators.py", line 38, in execute cursor = create_connection(user="USERNAME",port="PORT",host="HOST",pwd="password",sid="SID") File "/Users/b0204890/Desktop/python/airflow_home/utility/validation.py", line 30, in create_connect…
type: Question
score: 1
tagged with: airflow
upvote count: 1
tagged with: cx-oracle
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89766467
tagged with: oracle-database
tagged with: python
has title: airflow task is unable to connect to remote oracle database
has answer: http://stackoverflow.com/a/51398655
tagged with: python-3.x
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89766990

http://stackoverflow.com/comment/89903274
has text: @Phteven: what do you call "drops off" ? It is important to use meaningful and unambiguous descriptions otherwise we waste time making irrelevant suggestions.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51426519

http://stackoverflow.com/a/51382271
has comment: http://stackoverflow.com/comment/89736450
answers question: http://stackoverflow.com/q/51382183
type: Answer
has comment: http://stackoverflow.com/comment/89737086
downvote count: 0
has comment: http://stackoverflow.com/comment/89736735
has comment: http://stackoverflow.com/comment/89736343
score: 3
has comment: http://stackoverflow.com/comment/89736644
has comment: http://stackoverflow.com/comment/89736411
has body: x[:1] is a list and x[-5] is a str in your case. If you want the index 0 and 3 you can do: a = [x[0], x[3]]
has comment: http://stackoverflow.com/comment/89736528
upvote count: 3

http://stackoverflow.com/comment/104223519
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51349905
score: 1
has text: is `bouncer` before your app in the installed apps list? From the question it's not totally obvious when you are actually calling `get_user_model`, but if it is happening while django is loading your app then `bouncer` would have to be loaded first.

http://stackoverflow.com/comment/94765810
score: 0
type: AnswerComment
type: Comment
has text: I've put the code after STATICFILES_DIRS, at the end of settings.py, and nothing is change. Is too hard explane in wich part of that file is correct to put the code? Between MIDDLEWARE and ROOT_URLCONF, for example??
comment on: http://stackoverflow.com/a/51440015

http://stackoverflow.com/comment/89835383
comment on: http://stackoverflow.com/q/51432215
score: 0
type: Comment
type: QuestionComment
has text: Just to check, are you referring to a Pandas dataframe here?

http://stackoverflow.com/comment/89675740
has text: Also, if your problem is a circular import, did you read the question I linked above? You need to read at least the top two answers (and maybe skim the top comments underneath them), but between them, they should cover what's happening, why it's happening, and the various ways can you fix it. If that solves your problem, just say so and we can close your question as a dup. If not, explain why it doesn't. (If your problem isn't a circular important, of course, ignore all of this.)
type: QuestionComment
comment on: http://stackoverflow.com/q/51335018
score: 0
type: Comment

http://stackoverflow.com/comment/89699248
type: Comment
has text: What's the size of the newly generated encrypted file? If it's zero bytes, then it is empty indeed.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51362868

http://stackoverflow.com/comment/89681679
score: 0
has text: @busybear I tried to do that but I was getting different outcome like this [(D, 0), (D, 1), (D, 2), (D, 3), (D, 4), (D, 5), (D, 6), (D, 7), (D, 8), (D, 9), (E, 0), (E, 1), (E, 2), (E, 3), (E, 4), (E, 5), (E, 6), (E, 7), (E, 8), (E, 9), (F, 0), (F, 1), (F, 2), (F, 3), (F, 4), (F, 5), (F, 6), (F, 7), (F, 8), (F, 9)] I am not sure if this outcome will help me to get the solution which I want.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51354586

http://stackoverflow.com/q/51396389
has answer: http://stackoverflow.com/a/51396419
tagged with: pandas
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
has body: I've curious about rank in Python. How did the output arrive as printed below? What did rank do the data? Input obj = pd.Series([7,-5,7,4,2,0,4]) Output: print(obj) 0 7 1 -5 2 7 3 4 4 2 5 0 6 4 Rank print(obj.rank()) 0 6.5 1 1.0 2 6.5 3 4.5 4 3.0 5 2.0 6 4.5
upvote count: 5
type: UnansweredQuestion
tagged with: python
has title: What is rank in Python?
tagged with: rank
type: Question
score: 5

http://stackoverflow.com/comment/89791090
comment on: http://stackoverflow.com/q/51409824
score: 1
has text: Have a look at `[w for w in stop_words if w not in word_index]`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89817539
score: 0
comment on: http://stackoverflow.com/a/51423297
type: Comment
has text: Have you tried running this code? Does it produce the output the OP wants?
type: AnswerComment

http://stackoverflow.com/comment/89927970
comment on: http://stackoverflow.com/q/51479360
score: 0
type: Comment
type: QuestionComment
has text: I guess rabbitmq is not behind

http://stackoverflow.com/a/51436995
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89858012
type: Answer
has comment: http://stackoverflow.com/comment/89853667
has comment: http://stackoverflow.com/comment/89844576
accepted answer of: http://stackoverflow.com/q/51436215
answers question: http://stackoverflow.com/q/51436215
has comment: http://stackoverflow.com/comment/89853983
has body: An image can be represented as a list of 2D arrays for each elementary colors (Red, Green, Blue). For instance, you can load an image using scipy.misc.imread: from scipy.misc import imread img_rgb = imread("sample.jpg") For each color array, you can successively use np.array_split (NumPy function) to split your array along a given dimension, following def split_img(img, num): # Here, img is a 2D array img_split = [ np.array_split(A, num, axis = 0) for A in np.array_split(img, num, axis = 1) ] # Flatten the output into a list of 2D arrays return [ item for sublist in img_split for item in sublist ] num = 4 img_r_split = split_img(img_rgb[:,:,0], num) img_g_split = split_img(img_rgb[:,:,1], num) img_b_split = split_img(img_rgb[:,:,2], num) Finally, you must gather the split color arrays into an RGB array, following img_rgb_split = [ np.stack((r, g, b), axis = -1) for r, g, b in zip(img_r_split, img_g_split, img_b_split) ] You can use plt.imshow to display your split images, for instance plt.imshow(img_rgb_split[0])
has comment: http://stackoverflow.com/comment/89846187
has comment: http://stackoverflow.com/comment/89854097
score: 0

http://stackoverflow.com/comment/89766619
has text: Thanks. I need to randomly order `sampledSentances`. I currently use `random.shuffle(sampledSentances)` to shuffled the sentences before I iterate over them. How can I implement this approach with shuffled sentences (but keep the correct associations with `book` and `page`)?
comment on: http://stackoverflow.com/a/51397762
score: 0
type: AnswerComment
type: Comment

template-matching
tags question: http://stackoverflow.com/q/51393461
type: Tag
tag name: template-matching

http://stackoverflow.com/comment/89794960
type: Comment
has text: So after testing it, I don't think it is... I've run the following code: my_df = pd.DataFrame(data=['a', 'a', 'b', 'c', 'a', 'a', 'b', 'v', 'v', 'f'], columns=['A']) def iter_dataframe(dataframe, chunk_size): for chunk_index, df_chunk in dataframe.groupby(np.arange(len(dataframe)) // chunk_size): yield chunk_index, df_chunk for group in iter_dataframe(my_df, 2): print(my_df) It appears to split it into equal dataframes, but I need to split it into smaller chunks by group (I hope I'm being clear).
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51411561

http://stackoverflow.com/q/51352538
tagged with: scipy
type: Question
has answer: http://stackoverflow.com/a/51362240
tagged with: minimize
tagged with: optimization
accepted answer: http://stackoverflow.com/a/51362240
downvote count: 0
answer count: 1
favorite count: 0
has title: Python optimization with a solver
tagged with: python
has body: I have a question about solvers. I've read a lot about them and also here on stackoverflow, but I have stil some questions about the mode of operation. I wanna start with a simple scipy.optimize.minimize. Therefore I use the following code: p_min = minimize(fun, p_start, method='BFGS', jac=None, hess=None, tol=None, options={ 'maxiter': 1000}) I use the BFGS method with 1000 iterations. p_start is my start value. My function is a full cash flow calculation, where I must find the minimum price, with the adjusted present value equal to zero. I need a solver for this case since I have a forcasted price and at all times compare my price with the forecast and use the higher one. My question is, how can I define the function? Should my entire cash flow calculation be the function? And how can I define it that way? I am grateful for your help!
type: AnsweredQuestion
tagged with: solver
score: 1
upvote count: 1

http://stackoverflow.com/q/51406299
downvote count: 0
has answer: http://stackoverflow.com/a/51418187
tagged with: kubernetes
answer count: 1
has comment: http://stackoverflow.com/comment/89801555
favorite count: 0
accepted answer: http://stackoverflow.com/a/51418187
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
has body: I am using the official Python Kubernetes client to create Pods dynamically: kube_api.create_namespaced_pod(body=pod_spec, namespace='default') However it looks like Kubernetes tries to pull the image assuming my local registry is using v1: Failed to pull image "localhost:5000/foo:bar": rpc error: code = Unknown desc = Error while pulling image: Get http://localhost:5000/v1/repositories/foo/images: dial tcp 127.0.0.1:5000: getsockopt: connection refused This doesn't work, as my local registry is using v2 and apparently it is not backward compatible. To fix this I see two solutions: Changing Kubernetes' (or Docker's?) config to change the API to v2. I've been searching a lot but can't find how to do that. Creating a v1 registry. But I couldn't find any docker image for it, and this sounds like a bad solution as v1 is deprecated.
type: Question
tagged with: docker-registry
has title: Using Kubernetes Python Client with a v2 Docker Registry

http://stackoverflow.com/comment/89910370
has text: I did the import sys and print sys.executable. I got /Users/babsii/Library/Enthought/Canopy/edm/envs/User/Resources/Python.app/Contents/MacOS/Python. When I do all the 42 upgrades, quit and restart Canopy and the jupyter notebook, I get the same result for the sys.executable. One of the package upgrades is pip, however, when I do in the Canopy Terminal shell a "which pip", I get /Users/babsii/Library/Enthought/Canopy/edm/envs/User/bin/pip, not the Apple version. I'm not sure why I would only get the problem when I use the jupyter notebook and not in both the Canopy editor and the notebook.
type: QuestionComment
comment on: http://stackoverflow.com/q/51470373
score: 0
type: Comment

http://stackoverflow.com/comment/114218291
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51329914
type: AnswerComment
has text: OK update! I went ahead and removed `Pipfile` and `Piplock` in my home directory. After then, when I ran `pipenv install` in a subdirectory where I have my new project, it created environment files in my project folder. It was referring to the `Pipfile` in my home directory whenever I run `pipenv install` in any new project. Also now it is assigning the project name as an environment name!

http://stackoverflow.com/comment/89831667
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51430304
has text: @dfundako: I tried to accomplish your request (see edited code), but: a. `A()` is somehow too complex, b. `A()` is not yet written :-)
score: 0

http://stackoverflow.com/q/51365472
tagged with: pandas
has answer: http://stackoverflow.com/a/51376483
tagged with: python
has title: Convert Precipitation Data netcdf file to csv Using Python
type: UnansweredQuestion
has body: I'm attempting to convert a netcdf (*.nc) (classic format) to CSV. This file is taken from the NOAA precipitation data set. I found helpful code in this post; however, when I run it I get this exception: Traceback (most recent call last): File "./test2.py", line 31, in precip_ts = pd.Series(precip, index=dtime) File "/usr/local/lib/python2.7/site-packages/pandas/core/series.py", line 275, in init raise_cast_failure=True) File "/usr/local/lib/python2.7/site-packages/pandas/core/series.py", line 4165, in _sanitize_array raise Exception('Data must be 1-dimensional') Exception: Data must be 1-dimensional Here is the test2.py script (same as post referenced above): #!/usr/local/bin/python2.7 import netCDF4 import pandas as pd precip_nc_file = 'precip.V1.0.2006.nc' nc = netCDF4.Dataset(precip_nc_file, mode='r') nc.variables.keys() lat = nc.variables['lat'][:] lon = nc.variables['lon'][:] time_var = nc.variables['time'] dtime = netCDF4.num2date(time_var[:],time_var.units) precip = nc.variables['precip'][:] # a pandas.Series designed for time series of a 2D lat,lon grid precip_ts = pd.Series(precip, index=dtime) precip_ts.to_csv('precip.csv',index=True, header=True) It is failing at the Pandas Series call. Can you give me any guidance why the pandas is failing; I thought it is supposed to handle 2D data! The end result I'm looking for is a CSV file with each line having lon, lat, datetime, precip value
tagged with: netcdf4
type: Question
tagged with: python-2.7
answer count: 1
linked to: http://stackoverflow.com/q/44359869
score: 0

http://stackoverflow.com/comment/89715053
score: 0
type: QuestionComment
has text: Almost right, but you want [`Any`](https://docs.python.org/3/library/typing.html#typing.Any), not `any`. (Or you can just use `List` without any element spec.)
type: Comment
comment on: http://stackoverflow.com/q/51371482

http://stackoverflow.com/a/51473460
has body: You don't need to do this at all. You can follow the relationship in the template. {% for part in object.relatedparts_set.all %}{{ part.name }}{% endfor %} You don't need any code in the view to enable this.
downvote count: 0
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51471061

http://stackoverflow.com/comment/89903898
type: Comment
type: QuestionComment
has text: I only know how pcts come out, it is list comprehension.
comment on: http://stackoverflow.com/q/51467669
score: 0

http://stackoverflow.com/q/51408975
has answer: http://stackoverflow.com/a/51409331
type: Question
answer count: 3
upvote count: 0
score: -2
has answer: http://stackoverflow.com/a/51409575
has comment: http://stackoverflow.com/comment/89789300
favorite count: 0
has comment: http://stackoverflow.com/comment/89789625
tagged with: python
has answer: http://stackoverflow.com/a/51408999
type: UnansweredQuestion
downvote count: 2
has body: I want to convert this format: ['1', '1', ',', 'V', 'e', 'r', 'n', 'a', ' ', 'F', 'r', 'a', 'n', 'k', 'l', 'i', 'n', ',', 'v', '.', 'f', 'r', 'a', 'n', 'k', 'l', 'i', 'n', '@', 'g', 'm', 'a', 'i', 'l', '.', 'c', 'o', 'm', ',', '1'] into this format: [11, Verna Franklin, v.franklin@gmail.com, 1]
has title: Combine list of chars into list of strings that are split by a comma
tagged with: list
has comment: http://stackoverflow.com/comment/89789333

if-statement
tags question: http://stackoverflow.com/q/51442075
tags question: http://stackoverflow.com/q/51469993
tag name: if-statement
type: Tag
tags question: http://stackoverflow.com/q/51410961
tags question: http://stackoverflow.com/q/51481077
tags question: http://stackoverflow.com/q/51419598
tags question: http://stackoverflow.com/q/51380278
tags question: http://stackoverflow.com/q/51412726
tags question: http://stackoverflow.com/q/51351936
tags question: http://stackoverflow.com/q/51363120
tags question: http://stackoverflow.com/q/51369083
tags question: http://stackoverflow.com/q/51470100
tags question: http://stackoverflow.com/q/51360548
tags question: http://stackoverflow.com/q/51406506
tags question: http://stackoverflow.com/q/51417508
tags question: http://stackoverflow.com/q/51350890

http://stackoverflow.com/q/51387359
tagged with: sqlalchemy
type: Question
answer count: 2
score: 0
tagged with: python
tagged with: dictionary
has title: Nested loop does not convert strings to datetime.date object or quits midway
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51387452
has body: I have a list of dictionaries called measures where each dictionary contains a date key with a date value in string format: measures= [{'date': '2010-01-01', 'prcp': 0.15142857142857144, 'tobs': 69.71428571428571}, {'date': '2010-01-02', 'prcp': 0.002857142857142857, 'tobs': 67.0}, {'date': '2010-01-03', 'prcp': 0.0, 'tobs': 74.0}, {'date': '2010-01-04', 'prcp': 0.0014285714285714286, 'tobs': 75.0}, {'date': '2010- 01-05', 'prcp': 0.005, 'tobs': 74.5}] I would like to convert the date strings to datetime.date objects specifically as I need the exact format for sqlalchemy. I do not want a datetime.datetime format and I am positive the current format is string format. When I use the following nested loop: for record in measures: for key, val in record.items(): record['date']=datetime.strptime(record['date'],'%Y-%m-%d').date() print(type(record['date'])) I get the error: TypeError: strptime() argument 1 must be str, not datetime.date but commenting out the conversion code and checking to see type of each date record after running the conversion, I see that 4 records get converted to datetime.date but quits after that: for record in measures: for key, val in record.items(): ##record['date']=datetime.strptime(record['date'],'%Y-%m-%d').date() print(type(record['date'])) Output: &lt;class 'datetime.date'&gt; &lt;class 'datetime.date'&gt; &lt;class 'datetime.date'&gt; &lt;class 'str'&gt; &lt;class 'str'&gt; Any idea how I can fix this? I have 20000 items in the original dictionary.
has answer: http://stackoverflow.com/a/51387466

http://stackoverflow.com/q/51386670
has comment: http://stackoverflow.com/comment/89745621
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89745385
has comment: http://stackoverflow.com/comment/89745549
has comment: http://stackoverflow.com/comment/89745314
linked to: http://stackoverflow.com/q/19192268
has body: I do not know how exactly to ask this question, as I can't share API access. If someone could help with the correct way of asking, will appreciate it. I have a code which works perfectly fine and executes what I need, BUT when I use this API request code inside the DEF function, it returns with nothing or error... The error is simple that I cannot get the output, or return with 0 values This is the code: def sm_main_data(): #DATA PROCESSING - Impression|Engagements|VideoViews urlMain = "https://api.simplymeasured.com/v1/analytics/" + key.accountId + "/posts/metrics?\ filter=analytics.timeseries_key.gte(" + config.start + ").lte(" + config.end + ")&amp;\ filter=channel.eq(" + config.which_social_media + ")&amp;\ metrics=analytics.engagement_total,analytics.video.views_count,analytics.impressions&amp;\ dimensions=data_source_id,channel,analytics.timeseries_key.by(" + config.per_what + ")" headers = {'content-type': 'application/json', 'Authorization': 'Bearer ' + key.token} #Receive data from SM (main data) / modified it and save as JSON file responseMain = requests.get(urlMain, headers=headers).json() pprint.pprint(responseMain) pass sm_main_data() I have tried to print variables inside def: print(key.accountId) print(config.start) print(config.end) print(config.which_social_media) print(config.per_what) Which all printed correctly. Currently I'm lost... and cannot get an even theoretical idea about what could go wrong. Why this code does not work inside def function??? Edit 1.0 Error {u'errors': [{u'detail': u'` filter` parameter is not supported.,` metrics` parameter is not supported.,` dimensions` parameter is not supported.', u'status': u'422', u'title': u'Unprocessable Entity'}]} Edit 1.1 Code without def #DATA PROCESSING - Impression|Engagements|VideoViews urlMain = "https://api.simplymeasured.com/v1/analytics/" + key.accountId + "/posts/metrics?\ filter=analytics.timeseries_key.gte(" + config.start + ").lte(" + config.end + ")&amp;\ filter=channel.eq(" + confi…
has title: Python when using "def" API - return nothing (or error)
has comment: http://stackoverflow.com/comment/89745290
has answer: http://stackoverflow.com/a/51386953
tagged with: function
answer count: 1
has comment: http://stackoverflow.com/comment/89745487
favorite count: 0
has comment: http://stackoverflow.com/comment/89745656
score: -1
has comment: http://stackoverflow.com/comment/89745592
tagged with: python
accepted answer: http://stackoverflow.com/a/51386953
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89746265
has comment: http://stackoverflow.com/comment/89745784
downvote count: 2
has comment: http://stackoverflow.com/comment/89745253

http://stackoverflow.com/a/51430974
score: 0
type: Answer
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/51430293
has body: This will definitely resolve your problem Your Code is correct nothing to worry because it will gives correct output in interpreter. This problem is happening because you installed two versions of python on your machine and by default the path of python 2 is set in the priority in your Environment Variable. The Script gives correct output in interpreter because priority of path is not required for interpreter but when you run it from browser or command-prompt or console then path is required and it search the path of python from system environment variable.In your case, First it got the path of python 2 ,so that its show the version of python 2 Their will be two solution for your problem, You can do anyone. Uninstall python 2 from your system. This will resolve your problem instantly. If you want to keep both version of python then for resolving this problem you should have to set the path of python 3 in the priority from environment variable. Like This See in the Screenshot, Path of Python 2 is Upper in the Environment Variable should be below the Path of Python 3 Like This This is the correct and static way to set the path in priority Thank you, Expecting This will resolve your problem

http://stackoverflow.com/q/51453936
tagged with: python-2.7
upvote count: 1
answer count: 1
tagged with: github
favorite count: 0
has body: There is a python module to generate IPSec packets using scapy in GitHub, but that file is not in its own .git extension to download. Please find the link for the code:https://github.com/secdev/scapy/blob/master/scapy/layers/ipsec.py How can I use that script?
tagged with: python
has title: I see scapy ipsec.py python code in GitHub: how do I install and use it?
has answer: http://stackoverflow.com/a/51453987
downvote count: 0
type: UnansweredQuestion
score: 1
tagged with: scapy
tagged with: gitpython
type: Question

http://stackoverflow.com/a/51418846
type: Answer
has body: Make a copy of the list and iterate through the copy and delete the item from orginal. for i in info[:]: info.remove(i)
answers question: http://stackoverflow.com/q/51418579
score: 0

http://stackoverflow.com/comment/105442991
type: AnswerComment
comment on: http://stackoverflow.com/a/59253571
score: 0
type: Comment
has text: I cannot even upvote your answer. Please let me know what is wrong and what you fixed. The code is must here. Secondly, people might downvote you if it remains without code. As the question is regarding the code.

http://stackoverflow.com/comment/89845784
type: Comment
has text: Figures as much thought that it would need to require some sort of processing with AI to actually do autonomous scraping. Haha. Just that its going to take me awhile to learn how to use beautifulsoup on other sites. Too troublesome to ask again on this platform
comment on: http://stackoverflow.com/a/51436875
score: 0
type: AnswerComment

convolution
tags question: http://stackoverflow.com/q/51430538
tags question: http://stackoverflow.com/q/51368151
tag name: convolution
tags question: http://stackoverflow.com/q/51406199
tags question: http://stackoverflow.com/q/51345535
tags question: http://stackoverflow.com/q/51336584
type: Tag

http://stackoverflow.com/q/51475299
upvote count: 2
score: 0
downvote count: 2
type: Question
has title: Extract name between a word and comma from text with regex
has comment: http://stackoverflow.com/comment/89919185
has answer: http://stackoverflow.com/a/51475423
has body: I have a thousands .txt files with a large text. I want to extract some information from these files, like some names, numbers and dates. There are fields that follow a pattern to be able to extract the information, but others do not. I attach three examples of text. The problem comes when I need to extract the name of the creator of a company and the name of that company. To extract the name of the creator, there is a pattern in the text. To extract the name of the company no. The pattern is: start with the words "ante mí:" followed by a name with last names and ending in comma. I am using the following code: # Libreria RegEx de Python. # coding=utf-8 import re f = open ('/Users/anna/PycharmProjects/extractData/DiarioOficial/aaa1381582.pdf.txt','r') mensaje = f.read() mensaje = mensaje.replace("\n","") print re.findall(r'\s ante mí,+[a-zA-Z]{6-24}\s', mensaje) But I think that the regular expression is wrong. Can someone help me? CVE 1381582 | Director: Juan Jorge Lazo Rodríguez Sitio Web: www.diarioficial.cl | Mesa Central: +562 2486 3600 Email: consultas@diarioficial.cl Dirección: Dr. Torres Boonen N°511, Providencia, Santiago, Chile. Este documento ha sido firmado electrónicamente de acuerdo con la ley N°19.799 e incluye sellado de tiempo y firma electrónica avanzada. Para verificar la autenticidad de una representación impresa del mismo, ingrese este código en el sitio web www.diarioficial.cl DIARIO OFICIAL DE LA REPUBLICA DE CHILE Ministerio del Interior y Seguridad Pública V SECCIÓN CONSTITUCIONES, MODIFICACIONES Y DISOLUCIONES DE SOCIEDADES Y COOPERATIVAS Núm. 42.031 | Viernes 13 de Abril de 2018 | Página 1 de 1 Empresas y Cooperativas CVE 1381582 EXTRACTO VALERIA RONCHERA FLORES, Notario Titular Décima Notaría Santiago, oficio Agustinas 1235, piso 2, CERTIFICO: Por escritura pública hoy ante mí: DANIEL ROLANDO CORNEJO GALLARDO, chileno, soltero, factor de comercio, con domicilio en Pueblo Hundido sin número, comuna de Rengo, Sexta Región del Libertador Bern…
has comment: http://stackoverflow.com/comment/89919010
answer count: 1
accepted answer: http://stackoverflow.com/a/51475423
favorite count: 0
tagged with: extract
tagged with: python
tagged with: regex
tagged with: text
type: AnsweredQuestion

http://stackoverflow.com/comment/89864928
comment on: http://stackoverflow.com/q/51447318
type: QuestionComment
score: 1
has text: but but the loop stops at the first iteration when `mysum == 5`
type: Comment

http://stackoverflow.com/q/51421251
tagged with: python
answer count: 0
score: 1
has body: I have seen that with tf.contrib.data.sample_from_datasets() now one can sample from different datasets according to a given probability distribution. However, I'm interested in sampling random chunks of data within a single Dataset. At the moment I'm using a tf.data iterator and I'm initializing it from a generator that makes use of np.random.choice() to produce the first indices of the chunks to sample, as np.random.choice() accepts a custom probability distribution as input. This method is clunky and I think not as fast as it could be if I could use tensorflow's Datasets for all the steps. Is there a known way of achieving this?
upvote count: 1
tagged with: tensorflow
type: Question
has title: How can I sample from one tensorflow Dataset according to a given probability distribution?
downvote count: 0
tagged with: tensorflow-datasets
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/51423139
favorite count: 0
tagged with: python-3.x
tagged with: python-telegram-bot
tagged with: telegram
score: 5
tagged with: python
accepted answer: http://stackoverflow.com/a/51448521
type: AnsweredQuestion
has body: I develop telegram bot using python-telegram-bot. Despite the usage of MessageQueue (just as mentioned in the docs) I keep getting telegram.error.RetryAfter: Flood control exceeded. Retry in N seconds when I flooding from the client (by pressing reply keyboard buttons really-really quickly) to my bot and it answers me. MessageQueue actually works, I can see the delay during sending big number of messages at once (with for loop). I've tried different values for message queue but none of those helped. Seems like the bot gets ban from telegram regardless of number of messages it actually send. Method threading (sync or async) does not change anything. How can I prevent users from flooding or avoid banning my bot when this is happening?
has title: Python telegram bot flood control exceeded
type: Question
upvote count: 5
has answer: http://stackoverflow.com/a/51448521
answer count: 2
possible better answer: http://stackoverflow.com/a/79110143
downvote count: 0
has answer: http://stackoverflow.com/a/79110143

http://stackoverflow.com/comment/89780783
type: Comment
has text: Now the same line throws: TypeError: object of type 'PhotoImage' has no len()
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51404545

http://stackoverflow.com/comment/89837008
score: 1
type: AnswerComment
has text: Well, It seems to add a lot of complexity on setting the environment, at least if compared with apex, but it may be worthy, as it also handles other infra components, as API Gateways. I'll give it a try! Thanks!
type: Comment
comment on: http://stackoverflow.com/a/51432918

http://stackoverflow.com/comment/95906170
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51464790
has text: Core `execute()` does not by default handle named [paramstyle](https://www.python.org/dev/peps/pep-0249/#paramstyle) (the `:search`), but passes the query string as is to the underlying DB-API method – which usually does not support named style either. [`text()`](https://docs.sqlalchemy.org/en/latest/core/sqlelement.html#sqlalchemy.sql.expression.text) constructs on the other hand translate named style to what ever the DB-API is using.
type: AnswerComment

http://stackoverflow.com/comment/89837625
score: 0
has text: Ok, feel free to close question or I will delete my answer. Glad you got it resolved!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51433394

http://stackoverflow.com/comment/89864428
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51446568
has text: I wonder if it could be from a different field. It doesn't match at all the string values in `state_msg`, obviously, and there are other columns with similar 10-digit values. There is the possibility that the directory I'm globbing from has some CSVs with 15 columns while others have the same 15 plus 2 at the end. I wonder if this could be an issue, but my testing whether it would be has been inconclusive...

http://stackoverflow.com/q/51410949
has comment: http://stackoverflow.com/comment/89793434
tagged with: python
type: AnsweredQuestion
downvote count: 0
has title: I/O operation on closed file on csv python
score: 1
has answer: http://stackoverflow.com/a/51410994
accepted answer: http://stackoverflow.com/a/51410994
has body: Im working on python3 project and I am getting error when trying to write on CSV file. with open('infile.csv', 'r') as f: reader = csv.reader(f) # manipulate the data with open('outfile.csv', 'w') as fl: writer = csv.writer(fl) for row in reader: writer.writerow(row) Im getting I/O operation on closed file on csv python issues. Do I need to create outfile.csv first? Im not sure?
type: Question
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/89668500
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51347948
type: Comment
has text: Just changed the naming of variables in my code to make it easier for people to understand.

http://stackoverflow.com/comment/89708674
type: Comment
comment on: http://stackoverflow.com/q/51335390
has text: It seems there is no way. I tried using the tqdm module for each image but it threw error. I have no clue. I checked the documentation and there is nothing to see the progress
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89833139
type: Comment
type: QuestionComment
score: 1
has text: Have you tried adding a method for filling that field (in models.py) and redefining save() to call it?
comment on: http://stackoverflow.com/q/51426968

http://stackoverflow.com/a/51461647
type: AcceptedAnswer
has body: Solved by below: def Getting_SPO(): ftp = FTP(ip) ftp.login('nmcman',password) directory ="/opt/mv36/core/nmc/hist/raw" #dir i want to download files from, can be changed or left for user input filematch = "*NE:12057.HUB0012-5GATH-SPO1_1_1*"# a match for any file in this case, can be changed or left for user to input ftp.cwd(directory) for Spo_file in ftp.nlst(filematch): # Loop - looking for matching files x =ftp.nlst(filematch) x=(x[0].replace(":", "_"), 'wb') print(x) global fname fhandle = open(x[0].replace("all.cdb", "rar"), 'wb') fname=x[0].replace("all.cdb", "rar") Getting_SPO.fhandle=fhandle print( ' \n Getting ' + Spo_file )#for confort sake, shows the file that's being retrieved ftp.retrbinary('RETR ' + Spo_file, fhandle.write) fhandle.close() return Spo_file
type: Answer
answers question: http://stackoverflow.com/q/51354019
accepted answer of: http://stackoverflow.com/q/51354019
score: 0

http://stackoverflow.com/comment/89933353
type: Comment
type: QuestionComment
has text: Can you post your current code for moving the subarray, along with some benchmarks showing why it is inefficient?
comment on: http://stackoverflow.com/q/51482178
score: 1

http://stackoverflow.com/a/51371827
answers question: http://stackoverflow.com/q/51371706
downvote count: 0
score: 1
upvote count: 1
type: Answer
has body: Have you already gone through the Installation, Quickstarts and Tutorials here: https://learn.microsoft.com/en-us/visualstudio/python/overview-of-python-tools-for-visual-studio Make sure the simple hello_world.py file with one line works: print("Hello World") If you still have problems, it may be that Visual Studio does not realize you have Python installed (i.e. if python is not in your path variables).

http://stackoverflow.com/q/51460923
has comment: http://stackoverflow.com/comment/89891192
answer count: 0
tagged with: subprocess
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90046738
has comment: http://stackoverflow.com/comment/89891211
has comment: http://stackoverflow.com/comment/90046818
score: 1
has title: program throwing error when called through subprocess
has comment: http://stackoverflow.com/comment/91011254
type: Question
has comment: http://stackoverflow.com/comment/89891179
upvote count: 1
has comment: http://stackoverflow.com/comment/89891237
has comment: http://stackoverflow.com/comment/89891197
favorite count: 0
tagged with: python
has body: Summary I am trying to call an external program through subprocess call commands. My program runs fine when called directly from the terminal. However, when called through subprocess, the program throws an error. Details I am trying to call the program Zimpl in Python. Zimpl is a program that reads a model file, as well as two input files and produces an output file. When I call Zimpl through the command line here's the output: **************************************************** * Zuse Institute Mathematical Programming Language * * Release 3.3.2 Copyright (C)2012 by Thorsten Koch * **************************************************** * This is free software and you are welcome to * * redistribute it under certain conditions * * ZIMPL comes with ABSOLUTELY NO WARRANTY * **************************************************** Reading model.zpl Reading parfile.par Reading values.txt Instructions evaluated: 103351 Name: model.zpl Variables: 156 Constraints: 546 Non Zeros: 2280 Writing [model.lp] Writing [model.tbl] When I call through the subprocess library with the command: s = subprocess.check_call(['zimpl', 'model.zpl']) print(s) here is what I get instead: **************************************************** * Zuse Institute Mathematical Programming Language * * Release 3.3.2 Copyright (C)2012 by Thorsten Koch * **************************************************** * This is free software and you are welcome to * * redistribute it under certain conditions * * ZIMPL comes with ABSOLUTELY NO WARRANTY * **************************************************** Reading model.zpl Reading parfile.par Reading values.txt *** Error 800: File model.zpl Line 24 : Symbol "VALUE" not initialised *** ximize obj : sum &lt;i,j&gt; in Particles : (x[i,j] * VALUE[i,j]); *** ^^^ Traceback (most recent call last): File "./runscript.py", line 153, in &lt;module&gt; evaluateLevel(0, sublevels[0], values) File "./runscript.py", line 111, in evaluateLevel s = subprocess.check_call(['zimpl', 'mode…

http://stackoverflow.com/comment/89757137
has text: What's in `numbers.txt`?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51392643

http://stackoverflow.com/comment/98906428
score: 0
has text: @laike9m Did you ever find out how to find out what the current opcode is?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51349074

http://stackoverflow.com/q/51454343
score: 0
tagged with: datetime
tagged with: sqlite
tagged with: python
has answer: http://stackoverflow.com/a/51459696
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/89878294
downvote count: 2
type: AnsweredQuestion
has body: I've got the following code: import sqlite3 conn = sqlite3.connect('wereldzaak.sqlite') curs = conn.cursor() x = curs.execute('''SELECT SUM(price) FROM purchase, product WHERE dt_iso BETWEEN ‘2015-01-01' AND ‘2015-12-31’ ''') But when I run it, I get the following error: WHERE dt_iso BETWEEN ‘2015-01-01' AND ‘2015-12-31’ ''') sqlite3.OperationalError: unrecognized token: "' AND ‘2015-12-31’ " I looked it up on the internet, but I still don't know what's wrong with my code
accepted answer: http://stackoverflow.com/a/51459696
has title: SQLite BETWEEN dates error
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/89878173
tagged with: between
has comment: http://stackoverflow.com/comment/89878427
has comment: http://stackoverflow.com/comment/89878184
has comment: http://stackoverflow.com/comment/89878385
has comment: http://stackoverflow.com/comment/89878257

http://stackoverflow.com/comment/89718905
type: Comment
type: QuestionComment
has text: try looking at this:https://github.com/tensorflow/tensorflow/issues/2502
score: 0
comment on: http://stackoverflow.com/q/51373463

http://stackoverflow.com/comment/89654846
has text: Could you include a [mcve] that makes sense with the numbers. It seems like you want `2 + 3 + 2 + ... + 4` to return `1340` but without having the actual numbers that is just an educated guess. For example you could omit the sublists from index 4 onwards and adapt the numbers accordingly?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51340470

http://stackoverflow.com/q/51358293
has title: Extracting multiple URLs - Python
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51358799
has answer: http://stackoverflow.com/a/51358799
tagged with: dataframe
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51358652
downvote count: 0
has body: I want to extract several links from a text (comments), which are stored in a panda dataframe. My goal is to add the extracted URLs in a new column of the original dataset. By using the following method applied to my text, I am able to extract the comments and store it in the variable URL and transform it into another pandas dataframe. In this case, I am not sure if this is the efficient way to extract the necessary information. URL = (ALL.textOriginal.str.extractall("(?P&lt;URL&gt;(https?://(?:www)?(?:[\w-]{2,255}(?:\.\w{2,6}){1,2})(?:/[\w&amp;%?#-]{1,300})))").reset_index('match', drop=True)) URL_df = pd.DataFrame(data=URL) URL_df.drop([1],axis=1) gives me: 596 https://www.tag24.de/nachrichten 596 http://www.tt.com/panorama 596 http://www.wz.de/lokales 666 https://www.svz.de/regionales 666 https://www.watson.ch/Leben ... ... The dataframe contains only the indices and the hyperlinks. The problem with this method is, that some of the indices are duplicated because one comment can exist several URLs, which will be extracted. I tried different ways to solve this problem such as: pd.concat([ALL, URL_df.drop], axis=1).sort_index() I also tried to store it the URLs directly to the original dataframe by applying: ALL['URL'] = ALL.textOriginal.str.extractall("(?P&lt;URL&gt;(https?://(?:www)?(?:[\w-]{2,255}(?:\.\w{2,6}){1,2})(?:/[\w&amp;%?#-]{1,300})))").reset_index('match', drop=True)) but I only received this error message: "incompatible index of the inserted column with frame index" As I said before my goal is to store the extracted URLs in a new column like: text URL "blablabla link1, link2, link3" [https://www.tag24.de/nachrichten, http://www.tt.com/panorama, http://www.wz.de/lokales] "blablabla link1, link2" [https://www.svz.de/regionales, https://www.watson.ch/Leben] ... ...
favorite count: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51358652
tagged with: python-3.x
upvote count: 2
tagged with: python

http://stackoverflow.com/comment/89822860
has text: you are amazing!!! btw, any idea why in this case g returns a df and not a groupby object?
score: 1
comment on: http://stackoverflow.com/a/51425752
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89630806
type: QuestionComment
comment on: http://stackoverflow.com/q/51327630
type: Comment
score: 0
has text: `try: int(input("what is your name: ")) except e: print("That's not an age")` Or something to that extent.

http://stackoverflow.com/q/51442456
tagged with: python
upvote count: 4
duplicate of: http://stackoverflow.com/q/7610001
has body: What does the -m mean while creating a virtual environment? For example, py -3 -m venv env. What does the -m mean? What's the difference of venv and virtualenv? Thanks.
type: Question
downvote count: 5
score: -1
linked to: http://stackoverflow.com/q/7610001
has answer: http://stackoverflow.com/a/51442647
answer count: 1
tagged with: virtualenv
favorite count: 0
has title: What does the option -m mean in python?
has comment: http://stackoverflow.com/comment/89854758
type: UnansweredQuestion

http://stackoverflow.com/comment/89779485
type: QuestionComment
has text: is there a way to run a js file within templates folder
comment on: http://stackoverflow.com/q/51404129
score: 0
type: Comment

http://stackoverflow.com/q/51346030
has title: How to append/extend multiple elements into an Array?
tagged with: python-2.7
score: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51346183
answer count: 1
tagged with: python
type: AnsweredQuestion
tagged with: list
tagged with: http://stackoverflow.com/tag/json
has body: I'm having issues trying to input headers into my array, I cannot append the array with headers of the values within the array. I've also attempted to use .extend, but it's also giving me issues. mylist = [] for i in jsonResponse['M']: if i['x'] == 'n': x = ((i['x'])) y = ((i['x']['y'])) z = ((i['x']['z'])) mylist.append([x,y,z]) import pandas as pd #panda related stuff df0 = pd.DataFrame(data=mylist) df0.to_excel(writer, sheet_name='Sheet1', header=True, index=False) I'm trying to have: mylist.append('Header1': [x],['Header2': [y],['Header3': [z]) I've tried using the .extend as I would think it's the most appropriate, but it's giving me error. The purpose of this is when I write the data to excel, it would be most ideal to have a header. The problem stems from opening the array from the very beginning above the JSON pull, I think i have to open the array, because it's a means to allocate memory to store the values. I was thinking as a solution would be to create an array for value from the JSON pull meaning: x = [] y = [] z = [] for i in jsonResponse['M']: if i['x'] == 'n': x = ((i['x'])) y = ((i['x']['y'])) z = ((i['x']['z'])) x.append('header1':[x]) y.append('header2':[y]) z.append('header3':[z]) But I don't know if that's going to work; I really don't want to go through that as it's a bit labor intensive, because I have a lot of json objects. I'm new to Python and never wrote anything in a language before. I'm trying, I've spent most my time copying script from the documentation and other users attempting to parse together a workable code and at the same time trying to understand what i'm trying to do.
has answer: http://stackoverflow.com/a/51346183
type: Question

http://stackoverflow.com/q/51369089
has answer: http://stackoverflow.com/a/51369506
tagged with: kivy
tagged with: python-3.x
tagged with: python
accepted answer: http://stackoverflow.com/a/51369506
type: AnsweredQuestion
has body: So I am just starting out with Kivy, and want to know how to A: get the dimensions of the window (based on the platform) The end goal is to launch the app on iOS, and there are multiple sized iPhones out there. How would I get the size of the screen of the device? and B: somehow be able to refer to it If I want to create a button that is centered on the screen, I need some way of getting the width_of_the_window and the length_of_the_window (these are obviously just made up variables). Here is the code I am working on, although it is really basic so it probably won't provide much insight. # Importing os import os # Importing Kivy, making sure its up to date, and importing App import kivy kivy.require('1.10.1') from kivy.app import App # Importing widgets, like buttons, drop down menus, etc from kivy.uix.widget import Widget from kivy.uix.dropdown import DropDown from kivy.uix.button import Button from kivy.uix.label import Label from kivy.uix.textinput import TextInput from kivy.uix.boxlayout import BoxLayout button_one = Button(text='Test', font_size = 20, pos = (root.width-100, 100), size_hint = (.06, .06)) class calculator_app(App): def build(self): return button_one calculator_object = calculator_app() calculator_object.run()
type: Question
has title: How to dynamically change Kivy window dimensions based on platform
answer count: 1
score: 0

http://stackoverflow.com/a/51389032
upvote count: 2
downvote count: 0
has body: Look in pandas documentation df.to_json(orient='records') '[{"col 1":"a","col 2":"b"},{"col 1":"c","col 2":"d"}]' Encoding/decoding a Dataframe using 'index' formatted JSON: df.to_json(orient='index') '{"row 1":{"col 1":"a","col 2":"b"},"row 2":{"col 1":"c","col 2":"d"}}' Encoding/decoding a Dataframe using 'columns' formatted JSON: df.to_json(orient='columns') '{"col 1":{"row 1":"a","row 2":"c"},"col 2":{"row 1":"b","row 2":"d"}}' Encoding/decoding a Dataframe using 'values' formatted JSON: df.to_json(orient='values') '[["a","b"],["c","d"]]'
answers question: http://stackoverflow.com/q/51378617
type: Answer
score: 2

http://stackoverflow.com/a/51380925
score: 3
answers question: http://stackoverflow.com/q/51380812
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51380812
type: AcceptedAnswer
type: Answer
downvote count: 0
has body: There's a kneighbors() method in KNeighborsClassifier which you can use. It will return the indices of the training data (which you used in fit()), along with the distances which are closest to the points you supply in it. Example: from sklearn import datasets from sklearn.neighbors import KNeighborsClassifier iris = datasets.load_iris() X = iris.data y = iris.target clf = KNeighborsClassifier() clf.fit(X, y) # here I am taking a single point only distances, indices = clf.kneighbors(X[[0]], n_neighbors=2) print(distances, indices) #Output: array([[0., 0.]]), array([[17, 0]]) Here first output is the distances, and second is the indices of X which are nearest to X[[0]]

http://stackoverflow.com/comment/89788585
has text: elasticsearch.exceptions.NotFoundError: TransportError(404, '{"_index":"index1","_type":"*","_id":"*","found":false}')
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51408567

http://stackoverflow.com/q/51335787
type: Question
accepted answer: http://stackoverflow.com/a/51335836
upvote count: 6
tagged with: dataframe
has body: i want to write a program that drops a column if it exceeds a specific number of NA values .This is what i did. def check(x): for column in df: if df.column.isnull().sum() &gt; 2: df.drop(column,axis=1) there is no error in executing the above code , but while doing df.apply(check), there are a ton of errors. P.S:I know about the thresh arguement in df.dropna(thresh,axis) Any tips?Why isnt my code working? Thanks
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/51335836
downvote count: 0
possible better answer: http://stackoverflow.com/a/51336434
favorite count: 0
tagged with: python-3.x
tagged with: data-analysis
score: 6
tagged with: python
has answer: http://stackoverflow.com/a/51336434
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89647622
has title: drops a column if it exceeds a specific number of NA values
has answer: http://stackoverflow.com/a/51337025

http://stackoverflow.com/comment/89789155
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51408860
has text: Your code opens the file, but doesn't read anything. `word_list` is the file handle (a.k.a. descriptor). Check a tutorial on file handling.

http://stackoverflow.com/comment/89839643
score: 0
type: Comment
type: QuestionComment
has text: What have you tried so far? Can you [create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)?
comment on: http://stackoverflow.com/q/51434567

http://stackoverflow.com/comment/89647173
score: 0
comment on: http://stackoverflow.com/q/51336074
type: Comment
type: QuestionComment
has text: So you see that there is a mask for Dog and a Cat in yellow color Instead of that yellow color I need to show the real dog and cat Hope it makes sense?

http://stackoverflow.com/comment/89676713
type: QuestionComment
has text: I wouldn't pass a python list of strings as command line arguments of a python program. check for the doc of pdfmerge.
comment on: http://stackoverflow.com/q/51352013
score: 0
type: Comment

http://stackoverflow.com/q/51383793
tagged with: python
has comment: http://stackoverflow.com/comment/89741016
has body: Having spent the past few days trying to get the Qualys API to work with python, I am usually running into errors such as 401 and errors of that sort, due to the fact that python code examples say they are unsupported. Since Qualys API is written with curl, I used Curl.trillworks.com to convert curl to python. The code I used was: (curl) curl -u "USERNAME:PASSWD" -H "X-Requested-With: Curl" -X "POST" -d "action=create&title=My+Dynamic+Search+List&global=1&published_dat e_within_last_days=7&patch_available=1" "https://qualysapi.qualys.com/api/2.0/fo/qid/search_list/dynamic/" and converted it into python: import requests headers = { 'X-Requested-With': 'Curl', } data = [ ('published_date_within_last_days', '7'), ('patch_available', '1'), ] response = requests.post('https://qualysapi.qualys.com/api/2.0/fo/qid/search_list/dynamic/', headers=headers, data=data, auth=('USRNAME', 'PASSWORD')) print (response) And got a 401 response. Any ideas or any more clarifications I should add? Thanks UPDATE - 12/27/2020 Its been a while since I had this problem. Not sure what the issue was but for anyone else having the same issue, I would recommend plugging in the CURL statements into tools like Insomnia or Postman which convert these into any language. That would help you get more accurate conversions.
has answer: http://stackoverflow.com/a/64253952
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/89740356
tagged with: api
has answer: http://stackoverflow.com/a/70505980
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/124610059
has title: Qualys API Integration with Python
tagged with: curl
type: Question
tagged with: qualys
has answer: http://stackoverflow.com/a/71334549

http://stackoverflow.com/comment/89762912
score: 1
has text: By the way, if you use one of the latest Jupyter versions, you don't have to import `display`, it is already available.
type: QuestionComment
comment on: http://stackoverflow.com/q/51395008
type: Comment

http://stackoverflow.com/comment/89712516
has text: *I need to get this file into a pandas dataframe so that I can view the data and manipulate it* ... you can view and manipulate within a database. Consider importing file into MySQL or MariaDB (both free and compatible) and if needed import table/queries in pandas using `read_sql`.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51368733

http://stackoverflow.com/comment/89802073
score: 0
type: QuestionComment
has text: You can try using the following link https://stackoverflow.com/questions/32759318/how-to-escape-single-quote-in-xpath-1-0-in-selenium-for-python
type: Comment
comment on: http://stackoverflow.com/q/51413646

http://stackoverflow.com/tag/xml
tags question: http://stackoverflow.com/q/51435571
tags question: http://stackoverflow.com/q/51482151
tags question: http://stackoverflow.com/q/51420110
tags question: http://stackoverflow.com/q/51426267
tags question: http://stackoverflow.com/q/51421654
tags question: http://stackoverflow.com/q/51353867
tags question: http://stackoverflow.com/q/51445374
tags question: http://stackoverflow.com/q/51420925
type: Tag
tags question: http://stackoverflow.com/q/51423807
tags question: http://stackoverflow.com/q/51352002
tags question: http://stackoverflow.com/q/51401826
tags question: http://stackoverflow.com/q/51337274
tags question: http://stackoverflow.com/q/51469680
tags question: http://stackoverflow.com/q/51392270
tags question: http://stackoverflow.com/q/51363720
tags question: http://stackoverflow.com/q/51376820
tags question: http://stackoverflow.com/q/51349893
tags question: http://stackoverflow.com/q/51364892
tags question: http://stackoverflow.com/q/51364741
tags question: http://stackoverflow.com/q/51406268
tags question: http://stackoverflow.com/q/51479281
tags question: http://stackoverflow.com/q/51431048
tags question: http://stackoverflow.com/q/51329504
tag name: xml
tags question: http://stackoverflow.com/q/51475929
tags question: http://stackoverflow.com/q/51377908
tags question: http://stackoverflow.com/q/51401704
tags question: http://stackoverflow.com/q/51388124
tags question: http://stackoverflow.com/q/51348996
tags question: http://stackoverflow.com/q/51395399
tags question: http://stackoverflow.com/q/51428390
tags question: http://stackoverflow.com/q/51436936
tags question: http://stackoverflow.com/q/51431774
tags question: http://stackoverflow.com/q/51477245
tags question: http://stackoverflow.com/q/51462535
tags question: http://stackoverflow.com/q/51358511
tags question: http://stackoverflow.com/q/51479952
tags question: http://stackoverflow.com/q/51414920
tags question: http://stackoverflow.com/q/51449851
tags question: http://stackoverflow.com/q/51437560
tags question: http://stackoverflow.com/q/51471692

http://stackoverflow.com/comment/89653190
comment on: http://stackoverflow.com/q/51338717
score: 0
type: QuestionComment
type: Comment
has text: The error basically means that your file `python_repos.svg` doesn't contain anything

raspberry-pi3
tags question: http://stackoverflow.com/q/51437961
tags question: http://stackoverflow.com/q/51392915
tags question: http://stackoverflow.com/q/51395070
tags question: http://stackoverflow.com/q/51365111
tags question: http://stackoverflow.com/q/51482271
tag name: raspberry-pi3
type: Tag
tags question: http://stackoverflow.com/q/51475504
tags question: http://stackoverflow.com/q/51473411

http://stackoverflow.com/comment/89701044
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51363980
has text: @Antoine: you're sytem is probably in state that would be very hard for us here to understand and debug. i'm marking this as off-topic, please don't take it personally. try asking on IRC (#python on freenode is usually quite helpful) or maybe at a local user group. for now, my best "guess" would be to clean up `/Library/Python/2.7/site-packages` (probably remove everythin there) and `~/.local/` by whatever means necessary and start over - at least with _always_ using `pip install --user`.

http://stackoverflow.com/q/51382409
has answer: http://stackoverflow.com/a/51431679
tagged with: python
possible better answer: http://stackoverflow.com/a/63848711
has answer: http://stackoverflow.com/a/63848711
accepted answer: http://stackoverflow.com/a/51431679
tagged with: geojson
downvote count: 1
type: AnsweredQuestion
upvote count: 5
has title: Programmatically render GeoJSON to image file
score: 4
type: Question
answer count: 2
has body: I have a series of GeoJSON objects that I wish to render on a map programatically. I can use http://geojson.io and upload my GeoJSON but how do I programatically do this and export a PNG or other image file? https://github.com/mapbox/geojson.io looked great, but it posts publicly to the geojson.io site.
favorite count: 0

http://stackoverflow.com/comment/89795536
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51411950
score: 0
has text: `IntFlag` is indeed missing from `enum43`. Check the source yourself: https://bitbucket.org/stoneleaf/enum34/src/default/enum/__init__.py

http://stackoverflow.com/q/51434949
has answer: http://stackoverflow.com/a/51436875
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has title: BeautifulSoup Scraping Formatting
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51435432
upvote count: 2
tagged with: web-scraping
type: Question
accepted answer: http://stackoverflow.com/a/51435432
has body: This is my first time using BeautifulSoup and I am attempting to scrap store location data from a local convenience store. However I'm running into some issues on trying to remove empty lines when data is being passed into a CSV file, I've tried .replace('\n','') and .strip() both did not worked. Also I'm having problems with splitting data that is scraped and contained in the same sibling method. I've added the script below: from bs4 import BeautifulSoup from requests import get import urllib.request import sched, time import csv url = 'http://www.cheers.com.sg/web/store_location.jsp' response = get(url) soup = BeautifulSoup(response.text, 'html.parser') #print (soup.prettify()) #open a file for writing location_data = open('data/soupdata.csv', 'w', newline='') #create the csv writer object csvwriter = csv.writer(location_data) cheers = soup.find('div' , id="store_container") count = 0 #Loop for Header tags for paragraph in cheers.find_all('b'): header1 = paragraph.text.replace(':' , '') header2 = paragraph.find_next('b').text.replace(':' , '') header3 = paragraph.find_next_siblings('b')[1].text.replace(':' , '') if count == 0: csvwriter.writerow([header1, header2, header3]) count += 1 break for paragraph in cheers.find_all('br'): brnext = paragraph.next_sibling.strip() brnext1 = paragraph.next_sibling test1 = brnext1.next_sibling.next_sibling print(test1) csvwriter.writerow([brnext, test1]) location_data.close() Sample of output generated: Sample of what output should look like: How can I achieve this? Thanks in advance.
possible better answer: http://stackoverflow.com/a/51436875
answer count: 2

http://stackoverflow.com/q/51398638
has body: I have a wheel built on MS Windows running in a very restricted environment, (cannot connect to internet). I can copy it to my machine running Linux. Then, I'd like to upload it to private PyPi. I don't want to use twine. I had too much bad experience with Python infrastructure tools, so would like to avoid them as much as possible, but if this is not reason enough for you, think about it as "learning experience": I just really want to know what API do I need to use in order to put a file on PyPi server. To spare you some more effort: https://pypiserver.readthedocs.io/en/latest/ I also read this, and there's no useful info here as well. The only thing I could find in terms of documentation is this: https://www.python.org/dev/peps/pep-0503/ which is useless for my case. This is the closest I've gotten so far: https://github.com/python/cpython/blob/master/Lib/distutils/command/upload.py#L92 though it still leaves a lot to be desired, as in: what fields are actually necessary and the restrictions on the contents of the fields.
tagged with: pypi
type: Question
has comment: http://stackoverflow.com/comment/89768370
score: 0
has title: Upload a wheel to private PyPi using curl
has comment: http://stackoverflow.com/comment/89768700
type: UnansweredQuestion
tagged with: python
answer count: 0

http://stackoverflow.com/q/51463872
score: 1
type: Question
has answer: http://stackoverflow.com/a/51463928
has title: How can I save the state of python code?
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89896804
favorite count: 0
tagged with: dynamic-programming
has comment: http://stackoverflow.com/comment/89896558
tagged with: code-generation
upvote count: 1
tagged with: python
has body: def function: x=100 var1=type("Myclass",(),{"fucntion":function}) print(var1) The type() function will generate a class of name Myclass and now I can call it from a object but now I want to save the state of the program.To simply put Myclass is generated when type() function runs and I want somehow when I again run the program Myclass should already be declared without running type() function.Its like a code that changes itself and saves itself and when again launched runs from the last saved state.
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51463928

http://stackoverflow.com/a/51330401
has comment: http://stackoverflow.com/comment/89638888
has comment: http://stackoverflow.com/comment/89637426
accepted answer of: http://stackoverflow.com/q/51330279
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89651787
type: Answer
upvote count: 2
has body: Your first problem is just that you're not calling main(). And normally, I'd just add a comment to tell you that and close the question as a typo, but you don't want to fix that until you first fix your bigger problem. Your code tries to create and call a new timeout function over and over, as fast as possible. And the first thing that timeout function does is to create a new Timer object. Which is a new thread. So you're spawning new threads as fast as Python will let you, which means in a very short time you're going to have more threads than your OS can handle. If you're lucky, that will mean you get an exception and your program quits. If you're unlucky, that will mean your system slows to a crawl as the kernel starts swapping thread stacks out to disk, and, even after you manage to kill the program, it may still take minutes to recover. And really, there's no reason for the while loop here. Each Timer schedules the next Timer, so it will keep running forever. And there's only ever 2 threads alive at a time that way. But there's not even a reason for a Timer in the first place. You don't want to do anything while waiting 10 seconds between requests, so why not just sleep? import time import requests def main(): flag = 0 while True: print("New Request") statuscode = requests.get("http://google.de").status_code if statuscode == 200 and flag == 0: print("Service available") # etc. time.sleep(10) main() Your code had another problem: you're defining a local variable named flag in timeout, but then you're trying to use it, in that flag == 0 check, before you ever assign to it. That would raise an UnboundLocalError. The fact that you happen to also have a local variable named flag in main doesn't make a difference. To fix this, you'd have to do one of these: Pass flag in as an argument for Timer to pass to each timeout call as a parameter. (Probably best.) Add a nonlocal flag declaration to timeout, so it becomes a closure cell shared by all of the timeout functions y…
has comment: http://stackoverflow.com/comment/89636976
score: 2
answers question: http://stackoverflow.com/q/51330279
has comment: http://stackoverflow.com/comment/89637689

http://stackoverflow.com/a/51414372
upvote count: 2
has body: This is pretty simple, for each key there is a list of values, note all values will be in string form. You enter the information like this. Key; Number of values for that key; Enter each value seperately Repeat for each key Code: def inputDict(numKeys=10): #if you want you could make numKeys an input too(numKeys = int(input("Numkeys?"))) desiredDict = {} #ask key and value for the numKeys for nameValuePair in range(numKeys): key = input("NextKey:\n") numVals = int(input("How many values for that key?\n")) valList = [] for value in range(numVals): valList.append(input("Next value\n")) desiredDict[key] = valList return desiredDict
has comment: http://stackoverflow.com/comment/91014940
answers question: http://stackoverflow.com/q/51414098
accepted answer of: http://stackoverflow.com/q/51414098
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/q/51433630
score: 1
has answer: http://stackoverflow.com/a/51433731
type: Question
has comment: http://stackoverflow.com/comment/89837890
accepted answer: http://stackoverflow.com/a/51433756
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/89837907
has title: how to split string into array on commas but ignore commas in parentheses
has comment: http://stackoverflow.com/comment/89841646
has answer: http://stackoverflow.com/a/51433746
has answer: http://stackoverflow.com/a/51434104
answer count: 4
favorite count: 0
has body: I have a string with 3 lines: a VARCHAR(20), b FLOAT, c FLOAT, d NUMBER(38,0), e NUMBER(38,0) Need to split a string into array based on comma delimiter but to ignore commas in parentheses. Final output is array with 5 elements: s_arr = ['a VARCHAR(20)', 'b FLOAT', 'c FLOAT', 'd NUMBER(38,0)', 'e NUMBER(38,0)'] So far I have s_arr = s.split(",") How to achieve that?
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51433756
tagged with: regex
has comment: http://stackoverflow.com/comment/89837877
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51433731

http://stackoverflow.com/comment/89860015
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51444626
has text: It seems you are trying to create new model fields via forms. I strongly discourage the parametric definition of new fields, as they will need migrations. Anyway, if you want to save both null and blank values, I suggest creating string variables named 'null' and 'blank' and then convert them during instance creation and retrieval.

http://stackoverflow.com/q/51326825
favorite count: 0
has answer: http://stackoverflow.com/a/51326938
answer count: 3
tagged with: pandas
tagged with: nan
has body: df = pd.DataFrame({'b':[False,True,False,True,False]}) # changes all False values to NaN df.loc[~df['b'], 'b'] = np.nan print(df.to_dict()) # {'b': {0: nan, 1: 1.0, 2: nan, 3: 1.0, 4: nan}} Since loc only changes specific values in the column, I would expect something like {'b': {0: nan, 1: True, 2: nan, 3: True, 4: nan}}, which is not the case. Why does .loc change booleans to floats, and what's a good workaround for this?
upvote count: 3
type: UnansweredQuestion
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/51326917
has comment: http://stackoverflow.com/comment/89628811
has answer: http://stackoverflow.com/a/51326934
type: Question
tagged with: numpy
has title: Pandas .loc[] side effect changes bools to floats
score: 2

http://stackoverflow.com/comment/89726463
score: 0
comment on: http://stackoverflow.com/q/51375833
type: QuestionComment
type: Comment
has text: Your question isn't totally clear, but are you sure you're concatenating on the right axes? By default `axes=0` (rows), which shouldn't add headers, but maybe if you explained more it would be clearer.

http://stackoverflow.com/comment/89839973
type: Comment
comment on: http://stackoverflow.com/a/51434865
score: 0
type: AnswerComment
has text: `Index(['Word', 'Row ID', 'Remark'], dtype='object')`

http://stackoverflow.com/comment/89643611
type: QuestionComment
score: 0
has text: In general, this is exactly why Python strings have the `startswith` method, so you don't make silly off-by-one errors like this. (But in this case, you probably should be using a URL parser, as @PeterWood suggests.)
comment on: http://stackoverflow.com/q/51334045
type: Comment

http://stackoverflow.com/comment/89799818
has text: I'm trying to write up some info on accessing the server via Python. Your time should not be that slow, when I parsed Spanish sentences via the server it only took ~2 minutes to do 6500. I'll write more soon.
comment on: http://stackoverflow.com/q/51366811
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/51481544
has comment: http://stackoverflow.com/comment/89932137
has title: opencv - Polyline and rectangle intersection
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/3252194
tagged with: python
has answer: http://stackoverflow.com/a/51482103
type: UnansweredQuestion
type: Question
tagged with: opencv
has body: I would like to get if a polyline and rectangle intersect on opencv+Python: A = cv2.rectangle(frame,(384,0),(510,128),(0,255,0),3) pts = np.array([[1300,900],[1750,700],[1000,200],[600,200]], np.int32) pts = pts.reshape((-1,1,2)) B = cv2.polylines(frame,[pts],True,(244,66,66),7) How can I find if A intersect with B? Thank you

http://stackoverflow.com/comment/89891661
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51461208
type: AnswerComment
has text: On round-tripping: I was searching for another example that would make it obvious, but `float(str(-0.0))` yields ... `-0.0`. So much for that.

http://stackoverflow.com/comment/89751796
type: QuestionComment
comment on: http://stackoverflow.com/q/51389851
has text: What do you mean by "a class that accepts an object"? Can you show us what you want the interface of the class to be like? How will you construct instances? What methods will you call on them or what attributes will you access or set?
score: 1
type: Comment

http://stackoverflow.com/q/51469814
answer count: 1
has title: Is it possible to highlight the combobox when we hover over it using mouse ? Like the activebackground for menu button?
score: 0
tagged with: tkinter
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89910064
tagged with: tkinter-layout
tagged with: tkinter-menu
has body: a. Is it possible to highlight the combobox when we hover the mouse over the button ? b. Because if its menu button we have the option like activebackground which helps to highlight the menu button when the mouse is hovered over it. I tried someoptions for the combobox but its just changing the color of the selection or listbox etc but unable to highlight the combobox when mouse moves over it. Can anyone provide some suggestion or comments for the same ? #!/usr/intel/bin/python2.7 import Tkinter from Tkinter import * from Tkinter import Tk, StringVar import ttk import tkFont try: import Tkinter as tk import Tkinter.ttk as ttk except ImportError: import Tkinter as tk import ttk class Application: def __init__(self, parent): self.parent = parent self.combo() def combo(self): MyFontBtn = tkFont.Font(family='courier', size=20, weight=tkFont.BOLD) self.box_value = StringVar() self.box = ttk.Combobox(self.parent, textvariable=self.box_value, state='readonly', width=39, font=MyFontBtn) self.box['values'] = ('Default', 'User Defined', 'Load From SS') self.box.set("Hello Click Drop Down") self.box['state'] = 'readonly' self.box.bind("&lt;&lt;ComboboxSelected&gt;&gt;", self.print_selected_value) self.box.option_add('*TCombobox*Listbox.selectBackground', 'gray50') self.box.option_add('*TCombobox*Listbox.font', MyFontBtn) #self.box.option_add('TCombobox.background', 'gray50') style1 = ttk.Style() style1.map('TCombobox', selectbackground=[('readonly', 'red')]) #style1.map('TCombobox', selectforeground=[('readonly', 'blue')]) style1.map("self.box", foreground=[('pressed', 'red'), ('active', 'blue')] #background=[('pressed', '!disabled', 'black'), ('active', 'white')] ) self.box.grid(column=0, row=0) def print_selected_value(self, *args): print "Vaue selected is:", self.box.get()
has answer: http://stackoverflow.com/a/51470273
type: Question

http://stackoverflow.com/comment/91462617
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52118007
type: Comment
has text: If your company uses google to manage users and emails (GSuite) it's really easy to use Flask-Dance with Google OAuth2.0 and add a condition on user registration to make sure he's part of the domain of the company. On OAUTH authorized signal, you can do something like : if "hd" in google_info and google_info["hd"] == "YOUR_COMPANY_DOMAIN.com": and then authorize the user. This makes the login easier for the users.

http://stackoverflow.com/comment/89819756
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51424138
type: AnswerComment
has text: First thank you , with the first point your are right. The bash command works exactly the same without the the second cat. On the second point I just delete the ssh command by error as as I was changing the name of the remote machine.

http://stackoverflow.com/q/51458886
score: -1
type: Question
answer count: 1
favorite count: 0
tagged with: pandas
downvote count: 1
tagged with: python
tagged with: python-3.x
upvote count: 0
has title: Make column values to new columns and fill it will another columns, If the value not present, replace with zero
accepted answer: http://stackoverflow.com/a/51458953
has body: I have a dataset like this: col1 col2 col3 a ex1 102 a ex2 25 a ex3 50 a ex4 66 b ex2 45 b ex5 20 c ex1 30 I want col2 valus to be the new columns and the col3 valus will be the values like following: col1 ex1 ex2 ex3 ex4 ex5 a 102 25 50 66 0 b 0 45 0 0 20 c 30 0 0 0 0 If the value is not present, It will be zero like the output
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51458953
tagged with: dataframe

http://stackoverflow.com/q/51365273
has answer: http://stackoverflow.com/a/51365679
tagged with: django
tagged with: python
type: AnsweredQuestion
type: Question
tagged with: django-authentication
has title: Changing a default model field name that django class based views look for
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51365679
has body: I am using PasswordResetView (the class-based view in Django 2.0) to implement Forgot Password functionality into my app. I am new to class based views and by default it looks for is_active in my user model. However, I overrode the default user model and my model instead contains the field with the name active. How do I change this behavior? FieldError at /account/reset-Password/ Cannot resolve keyword 'is_active' into field. Choices are: active, admin, confirm, email, full_name, id, last_login, logentry, password, social_auth, staff, timestamp, userlogin, username Request Method: POST Request URL: http://127.0.0.1:8000/account/reset-Password/ Django Version: 2.0.5 Exception Type: FieldError Exception Value: Cannot resolve keyword 'is_active' into field. Choices are: active, admin, confirm, email, full_name, id, last_login, logentry, password, social_auth, staff, timestamp, userlogin, username Exception Location: /home/yash/Desktop/ltigo/lib/python3.6/site-packages/django/db/models/sql/query.py in names_to_path, line 1379 Python Executable: /home/yash/Desktop/ltigo/bin/python Python Version: 3.6.5 Python Path: ['/home/yash/Desktop/ltigo/src', '/home/yash/Desktop/ltigo', '/home/yash/Desktop/ltigo/lib/python36.zip', '/home/yash/Desktop/ltigo/lib/python3.6', '/home/yash/Desktop/ltigo/lib/python3.6/lib-dynload', '/usr/lib/python3.6', '/home/yash/Desktop/ltigo/lib/python3.6/site-packages', '/snap/pycharm-professional/68/helpers/pycharm_matplotlib_backend'] Server time: Mon, 16 Jul 2018 15:18:07 +0000

http://stackoverflow.com/comment/89677202
type: AnswerComment
score: 0
type: Comment
has text: Yes, I'm sure because if I don't pass any code, it works as expected setting Coupon = Null. The problem is when a wrong code is entered, then the Exception Object Does Not Exist.
comment on: http://stackoverflow.com/a/51342742

http://stackoverflow.com/q/51355282
answer count: 1
accepted answer: http://stackoverflow.com/a/51355314
tagged with: excel
upvote count: 5
downvote count: 0
has title: Add percentage column to panda dataframe with percent sign
has answer: http://stackoverflow.com/a/51355314
tagged with: pandas
type: AnsweredQuestion
tagged with: python
has body: For the below excel which will be used as panda dataframe df['% '] = (df['Code Lines'] / df['Code Lines'].sum())*100 Output comes Language # of Files Blank Lines Comment Lines Code Lines % C++ 15 66 35 354 3.064935065 C/C++ Header 1 3 7 4 0.034632035 Markdown 6 73 0 142 1.229437229 Python 110 1998 2086 4982 43.13419913 Tcl/Tk 1 14 18 273 2.363636364 YAML 1 0 6 20 0.173160173 Total 134 2154 2152 5775 50 I am trying to get % column should be of only 2 decimal places with a percent sign Something like this Language # of Files Blank Lines Comment Lines Code Lines % C++ 15 66 35 354 3.06% C/C++ Header 1 3 7 4 0.03% Markdown 6 73 0 142 1.22%
favorite count: 0
type: Question
score: 5

twilio
tag name: twilio
tags question: http://stackoverflow.com/q/51407854
tags question: http://stackoverflow.com/q/51331013
type: Tag

http://stackoverflow.com/comment/89694889
type: Comment
has text: to point 2: the dataset during test/validation is not shuffled
type: AnswerComment
comment on: http://stackoverflow.com/a/51361104
score: 0

http://stackoverflow.com/q/51442952
has answer: http://stackoverflow.com/a/51443664
tagged with: python
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/51443664
has body: The matrix a has shape (4,3) and z has shape (4,). My intent is I want to divide every 3 dim vector in a with scalar in z. Consider the below example: Input: a = [[1,1,1], [2,2,2], [2,2,2], [5,5,5]] z = [10,10,10,5] Expected Output: [[.1,.1,.1], [.2,.2,.2], [.2,.2,.2], [1,1,1]] Below is my attempt to do the same using keras Lambda layer where K.sum(xin[0], axis=1) would be a and xin[1] would be z x = Lambda(lambda xin: K.sum(xin[0], axis=1) / xin[1], name='mean')([x1,x2]) But when I run this code, I am getting the following error: InvalidArgumentError (see above for traceback): Incompatible shapes: [4,3] vs. [4]
score: 0
has title: Unable to divide a matrix and vector in keras
tagged with: array-broadcasting
answer count: 1
tagged with: keras

http://stackoverflow.com/q/51351918
answer count: 1
has body: I am using scrapy to scrape a specific site. After a few requests, the site tries to redirect my requests to my own IP. At this point, I wish to change my credentials with login function. But I am unable to do it anyway. I have tried errback to call the login, but I don't know how to properly trigger an error for such redirections. can anyone please provide a solution for this? Thanks!
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89691929
has comment: http://stackoverflow.com/comment/89686897
score: 0
tagged with: web-scraping
tagged with: scrapy
has title: How to handel redirects in scrapy?
type: Question
has answer: http://stackoverflow.com/a/51360056

http://stackoverflow.com/comment/89689940
type: QuestionComment
type: Comment
has text: Sorry to be pedantic but can you formulate `as near as possible to each other` (preferably with a formula)? Are we talking about rounding errors, e.g. 1.0 vs 1.00001 ?
score: 0
comment on: http://stackoverflow.com/q/51358770

http://stackoverflow.com/comment/89838933
type: QuestionComment
comment on: http://stackoverflow.com/q/51434225
score: 0
has text: @RafaelC : thanks Bro. I got the answer down here.
type: Comment

http://stackoverflow.com/q/51389961
possible better answer: http://stackoverflow.com/a/51390070
score: -1
has answer: http://stackoverflow.com/a/51390070
has comment: http://stackoverflow.com/comment/89752229
answer count: 2
tagged with: pandas
upvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51390106
has comment: http://stackoverflow.com/comment/89752385
has body: Let's suppose we have following Dataframe. tempDataframe = Col1 Col2 1 2 1 4 2 5 After running the following code I expect this result: tempDataframe = tempDataframe.set_index('Col1') tempDataframe.loc[[1,2]] Col1 Col2 1 2 1 4 2 5 2 0 For each index, there should be at-least two results. For entries which has less than two values should return an extra entry with zeros.
tagged with: python
has comment: http://stackoverflow.com/comment/89752171
has comment: http://stackoverflow.com/comment/89752307
has comment: http://stackoverflow.com/comment/89752262
has title: Pandas: Getting fixed number of rows by using loc
downvote count: 1
has comment: http://stackoverflow.com/comment/89752270
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51390106

http://stackoverflow.com/a/51344585
has body: You're on Python 2.7, which uses a unicode type to store Unicode strings (e.g. the strings that are stored in JSON). The repr for the unicode type prints all non-ASCII characters with Unicode escapes (\uXXXX), and that's what you're seeing in the pprint output. You'll need to print the value separately to see the characters: &gt;&gt;&gt; print repr(u'\u8fdd\u89c4 \u539f\u6599\u836f') u'\u8fdd\u89c4 \u539f\u6599\u836f' &gt;&gt;&gt; print u'\u8fdd\u89c4 \u539f\u6599\u836f' 违规 原料药 Thus, in your case, you might do something like for article in response.json()['articles']: print article['description']
answers question: http://stackoverflow.com/q/51343702
upvote count: 1
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/q/51457367
accepted answer: http://stackoverflow.com/a/51457413
downvote count: 3
has comment: http://stackoverflow.com/comment/89884587
possible better answer: http://stackoverflow.com/a/51457467
type: Question
has answer: http://stackoverflow.com/a/51457467
has title: Pair two lists in inverse order
has comment: http://stackoverflow.com/comment/89884160
score: 0
answer count: 3
has body: What I want to do is to choose one item in list A and another one in list B, pair them like: A[0]+B[n], A[1]+B[n-1],.....,A[n]+B[1] I use two for loops but it doesn't work: class Solution(object): def plusOne(self, digits): sum=0 for j in range(len(digits)-1,0,-1) : for i in range(0,len(digits),1): sum=sum+digits[i]*pow(10,j) return sum+1 I inputted [1,2,3] and what I want to get is 124, but I got 661. Edit: Sorry, the example I gave above is not so clear. Let us think about A[1,2,3] and B[6,5,4]. I want output [5,7,9], because 5 is 1+4, 7 is 2+5, 9 is 3+6
has answer: http://stackoverflow.com/a/51457413
favorite count: 0
has comment: http://stackoverflow.com/comment/89884431
tagged with: python
has answer: http://stackoverflow.com/a/51457643
has comment: http://stackoverflow.com/comment/89884384
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89884191
upvote count: 3
has comment: http://stackoverflow.com/comment/89884177

http://stackoverflow.com/comment/89887795
comment on: http://stackoverflow.com/a/51458953
has text: Thanks, Any idea how to reset columns like for this example, The columns will be: col1, ex1, ex2, ex3, ex4, ex5
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51383404
has answer: http://stackoverflow.com/a/51383584
has title: Pass arguments only when needed
score: 0
answer count: 3
tagged with: functional-programming
accepted answer: http://stackoverflow.com/a/51384820
has body: As an example I have a function f and a variable a=1. Sometimes f needs a and I want to call f(a=a) and other times f has no arguments. How can I deal with that? When I try to call f(a=a) (expecting that it will silently ignore the case where a is not used in f), I get the following TypeError: f got an unexpected keyword argument 'a' Edit I want to implement a function g such that, given: def f1(a): return a def f2(): return 1 we have: g(f1, a) == a g(f2, a) == 1
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51383584
has answer: http://stackoverflow.com/a/51383523
tagged with: python
has answer: http://stackoverflow.com/a/51384820
type: AnsweredQuestion
type: Question

http://stackoverflow.com/comment/89701420
score: 0
type: Comment
has text: Thank you. That worked. Tesseract is having a very low accuracy is there any other method to identify characters in an image in python?
type: QuestionComment
comment on: http://stackoverflow.com/q/51364353

memoization
type: Tag
tags question: http://stackoverflow.com/q/51459221
tag name: memoization

http://stackoverflow.com/comment/89910663
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51471061
has text: What is `relatedparts_list`? It looks like you should simply use `% for parts in relatedparts %}`.
score: 0

webpage-screenshot
type: Tag
tag name: webpage-screenshot
tags question: http://stackoverflow.com/q/51400933

http://stackoverflow.com/comment/89784453
score: 0
type: QuestionComment
type: Comment
has text: Do you want to effectively mask your data set, or do you want to only evaluate the convolution at certain locations?
comment on: http://stackoverflow.com/q/51406199

http://stackoverflow.com/q/51466922
tagged with: heroku-cli
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90090032
has comment: http://stackoverflow.com/comment/89941765
has comment: http://stackoverflow.com/comment/90177631
has title: Using heroku repo to reduce slug size but keep getting a "Cannot run one-off process at this time. Please try again later." message
type: Question
tagged with: python
answer count: 1
tagged with: git
tagged with: heroku
score: 0
has answer: http://stackoverflow.com/a/52106708
has body: We have been trying to deploy our Flask app using heroku but keep getting slug size too large errors that cause the build logs to fail. In order to reduce the slug size, we have been trying to use heroku repo's $ heroku repo:gc -a appname and $ heroku repo:purge_cache -a appname commands, but we always get a "Cannot run one-off process at this time. Please try again later." message. We tried over several days and even tried creating new apps, but we still keep getting the same error message. We have been googling ways to reduce slug size but found that the best method is to use gc and purge_cache. Is there any other way to reduce the slug size? This is the GitHub repo we have been trying to deploy on heroku.

http://stackoverflow.com/a/51433281
upvote count: 1
has body: Using shift df.loc[(df.Code!='X')&amp;(df.Code.shift()!='X'),] Out[99]: Code Int 0 A 0 1 A 1 2 B 1 3 C 2 6 B 4 7 A 5
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51433017
type: Answer
answers question: http://stackoverflow.com/q/51433017

http://stackoverflow.com/q/51407237
has comment: http://stackoverflow.com/comment/89786030
tagged with: python
has body: Here is my code side = max(df['col1'].max(), df['col2'].max())+1 data = np.ones(2*len(df)) print (sum(data), 2*len(df), max(data)) # prints 738 738 1.0 x = list(df['col1']) + list(df['col2']) y = list(df['col2']) + list(df['col1']) mat = scipy.sparse.coo_matrix((data,(x,y)), shape=(side, side)) print (mat.sum(), mat.max()) # prints 738 2 I don't understand how can the value 2 get into the mat sparse matrix?
answer count: 0
tagged with: scipy
type: Question
tagged with: sparse-matrix
has title: Populating scipy.sparse.coo_matrix with 1s, getting a 2 in there
score: 0
has comment: http://stackoverflow.com/comment/89786163
type: UnansweredQuestion

http://stackoverflow.com/comment/89637431
comment on: http://stackoverflow.com/q/51330863
has text: Note that the ForeignKey indicates a *parent* relationship, not a child one, since it can only point to one element. So it should be called something like "parent_component" and the related_name can be "subcomponents".
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/a/51370189
has body: You need to assign the return value to the variable UsrDict when you call CreateDict. Try this: import csv def CreateDict(filename): UsrDict = {} with open(filename) as csvfile: readCSV = csv.reader(csvfile, delimiter=':') for row in readCSV: UsrDict[row[0]]=row[1] return UsrDict def CreateHumanUsrNameDict(UsrDict): HumanUsrDict={} for k, v in HumanUsrDict.items(): if v == len(4): HumanUsrDict[k:v] print(HumanUsrDict) if __name__=='__main__': UsrDict = CreateDict('Book1.csv') CreateHumanUsrNameDict(UsrDict)
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51370082
type: Answer
answers question: http://stackoverflow.com/q/51370082
has comment: http://stackoverflow.com/comment/89712643
score: 0

http://stackoverflow.com/a/51419172
has comment: http://stackoverflow.com/comment/89813830
score: 0
has comment: http://stackoverflow.com/comment/89813706
has comment: http://stackoverflow.com/comment/89817735
has comment: http://stackoverflow.com/comment/89822423
has comment: http://stackoverflow.com/comment/89812642
has comment: http://stackoverflow.com/comment/89811811
has comment: http://stackoverflow.com/comment/89811055
has comment: http://stackoverflow.com/comment/89813677
has comment: http://stackoverflow.com/comment/89810921
has comment: http://stackoverflow.com/comment/89812226
type: Answer
has comment: http://stackoverflow.com/comment/89813384
has comment: http://stackoverflow.com/comment/89811070
has comment: http://stackoverflow.com/comment/89811557
has comment: http://stackoverflow.com/comment/89811893
answers question: http://stackoverflow.com/q/51418152
has comment: http://stackoverflow.com/comment/89813317
has comment: http://stackoverflow.com/comment/89813465
has comment: http://stackoverflow.com/comment/89812476
has comment: http://stackoverflow.com/comment/89812940
has comment: http://stackoverflow.com/comment/89812874
has comment: http://stackoverflow.com/comment/89811989
has body: Field mapping is not correct here. Name field is not getting proper. update = {'Id': acct['Id'].iloc[i], 'name': acct['user_count'].iloc[i]} Please try below code: if len(acct) &gt; 0: list = [] for i in range(len(acct)): update = {'Id': acct['Id'].iloc[i], 'name': acct['Name'].iloc[i]} list.append(update) sf_data_cursor.bulk.Account.update(list) Let me know if this solves your issue.
has comment: http://stackoverflow.com/comment/89811897

http://stackoverflow.com/comment/89870774
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51449912
has text: They are available in the Available package list : http://prntscr.com/k919ng

http://stackoverflow.com/q/51401953
has comment: http://stackoverflow.com/comment/89776128
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/51402083
accepted answer: http://stackoverflow.com/a/51402083
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
has body: As newbie to python trying to understand how i can achieve below transformation: Date Name Value 20180101 Dto 801 20180102 Dto 80 20180101 Rnc 501 20180102 Rnc 50 to Dto Rnc 20180101 801 501 20180102 501 50
type: Question
has comment: http://stackoverflow.com/comment/89774741
has title: Transpose column value as unique column header more like matrix
tagged with: dataframe
score: 0

http://stackoverflow.com/q/51348833
type: Question
has body: I'm getting a runtime error: RuntimeError: Dimension out of range (expected to be in range of [-1, 0], but got 1)` and can't figure out how to fix it. The error appears to refer to the line: i_enc = F.normalize(input =i_batch, p=2, dim=1, eps=1e-12) # (batch, K, feat_dim) I'm trying to encode image features (batch x 36 x 2038) by applying a L2 norm. Below is the full code for the section. def forward(self, q_batch, i_batch): # batch size = 512 # q -&gt; 512(batch)x14(length) # i -&gt; 512(batch)x36(K)x2048(f_dim) # one-hot -&gt; glove emb = self.embed(q_batch) output, hn = self.gru(emb.permute(1, 0, 2)) q_enc = hn.view(-1,self.h_dim) # image encoding with l2 norm i_enc = F.normalize(input =i_batch, p=2, dim=1, eps=1e-12) # (batch, K, feat_dim) q_enc_copy = q_enc.repeat(1, self.K).view(-1, self.K, self.h_dim) q_i_concat = torch.cat((i_enc, q_enc_copy), -1) q_i_concat = self.non_linear(q_i_concat, self.td_W, self.td_W2 )#512 x 36 x 512 i_attention = self.att_w(q_i_concat) #512x36x1 i_attention = F.softmax(i_attention.squeeze(),1) #weighted sum i_enc = torch.bmm(i_attention.unsqueeze(1), i_enc).squeeze() # (batch, feat_dim) # element-wise multiplication q = self.non_linear(q_enc, self.q_W, self.q_W2) i = self.non_linear(i_enc, self.i_W, self.i_W2) h = torch.mul(q, i) # (batch, hid_dim) # output classifier # BCE with logitsloss score = self.c_Wo(self.non_linear(h, self.c_W, self.c_W2)) return score I would appreciate any help. Thanks
tagged with: normalization
tagged with: dimensions
tagged with: outofrangeexception
accepted answer: http://stackoverflow.com/a/51350259
score: 0
has title: Dimension out of range when applying l2 normalization in Pytorch
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51350259
type: AnsweredQuestion
tagged with: pytorch

http://stackoverflow.com/a/51593605
downvote count: 1
answers question: http://stackoverflow.com/q/51395567
has body: Mate I've seen another way of finding this, and when I've seen that, you have come to my mind and I wanted to share it with you, because, I thought like, you might be searching for this solution: With code that've written below you can reach both same named variables with underscoring first one. class myclass: __myvar = "class variable" def __init__(self): self.myvar = "instance variable" pass def test(self): # difference between self.myvar and myclass.myvar return self.myvar class_instance = myclass() print(class_instance.test()) print(class_instance._myclass__myvar)
score: 0
upvote count: 1
type: Answer

http://stackoverflow.com/q/51461102
downvote count: 0
score: 1
type: Question
has body: I am trying to use a value (n) from a form (ProjectForm) to generate a second form (StepForm) n times in a loop. The ProjectForm works, creates a project and then sends me to the StepForm, but on submit the StepForm does not update and the loop never stops. @app.route("/new_project", methods=("POST", "GET")) @login_required def post_project(): form = forms.ProjectForm() if form.validate_on_submit(): models.Project.create(user=g.user.id, title=form.title.data, steps_number = form.steps_number.data, description=form.description.data.strip()) flash("Project created", "success") if form.steps_number.data != 0: project = models.Project.select().where(models.Project.title == form.title.data).get() return redirect(url_for("add_step",project_id=project.id)) if form.steps_number.data == 0: return redirect(url_for("projects")) return render_template("post_project.html", form=form) @app.route("/new_step/&lt;int:project_id&gt;", methods=("POST", "GET")) @login_required def add_step(project_id): form = forms.StepForm() project = models.Project.select().where(models.Project.id == project_id).get() steps = 0 for i in range(0,project.steps_number): steps+=1 if form.validate_on_submit(): models.Step.create(project=project.id, title=form.title.data.strip(), instruction=form.instruction.data.strip()) flash("Step Added", "success") if project.steps_number == steps: return redirect(url_for("projects")) return render_template("add_step.html", form=form, step=steps) SOLVED see answer bellow @app.route("/new_project", methods=("POST", "GET")) @login_required def post_project(): form = forms.ProjectForm() if form.validate_on_submit(): models.Project.create(user=g.user.id, title=form.title.data, steps_number = form.steps_number.data, description=form.description.data.strip()) flash("Project created", "success") if form.steps_number.data != 0: project = models.Project.select().where(models.Project.title == form.title.data).get() return redirect(url_for("add_step",project_id=project.id,step_id…
has answer: http://stackoverflow.com/a/51525325
accepted answer: http://stackoverflow.com/a/51525325
tagged with: peewee
answer count: 1
tagged with: flask
upvote count: 1
has title: Repeat flask form in loop based on other form's value
favorite count: 0
tagged with: flask-wtforms
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/51477735
tagged with: pandas
has comment: http://stackoverflow.com/comment/89923893
answer count: 1
has comment: http://stackoverflow.com/comment/89925423
has body: I checked w_table.iloc[i,4] and didn't find NoneType objects in it. What's the matter could it be? check = ['word'] for i in range(len(w_table)): if w_table.iloc[i, 4] != 'Null': if w_table.iloc[i, 4] in check: w_table = w_table.drop(w_table.index[i]) else: check = check.append(w_table.iloc[i, 4]) w_table.index = np.arange(len(w_table)) After executing above code I am getting following TypeError TypeError Traceback (most recent call last) &lt;ipython-input-74-40b9156195fa&gt; in &lt;module&gt;() 2 for i in range(len(w_table)): 3 if w_table.iloc[i, 4] != 'Null': 4 if w_table.iloc[i, 4] in check: 5 w_table = w_table.drop(w_table.index[i]) 6 else: TypeError: argument of type 'NoneType' is not iterable
has comment: http://stackoverflow.com/comment/89923804
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/20109391
has comment: http://stackoverflow.com/comment/89923921
has comment: http://stackoverflow.com/comment/89923841
has answer: http://stackoverflow.com/a/51477833
tagged with: ipython
has comment: http://stackoverflow.com/comment/89923941
has comment: http://stackoverflow.com/comment/89923771
type: Question
has comment: http://stackoverflow.com/comment/89923781
tagged with: nonetype
score: 0
has comment: http://stackoverflow.com/comment/89923872
has title: Why does the type error appear if the column is clear?
accepted answer: http://stackoverflow.com/a/51477833

http://stackoverflow.com/comment/89863839
type: Comment
comment on: http://stackoverflow.com/q/51446696
has text: @Mr.T for example, for the first row of 'out' we have id1='a', id2='c', col='col1', level='e'. So in the value column you would want the sum of df.value where id1='a', id2='b', col1='e'.
score: 0
type: QuestionComment

http://stackoverflow.com/q/51389298
score: -2
has comment: http://stackoverflow.com/comment/89750654
has comment: http://stackoverflow.com/comment/89750623
has comment: http://stackoverflow.com/comment/89750583
downvote count: 2
has body: I am currently using nested for loops to add data to two lists at once. See below code. headers, in the code below is a beautiful soup object. openData = [] count = 0 openC = 7 closeData = [] closeC = 10 for j in headers: for z in j: for data in z: count += 1 if count == 1: openData.append(data) elif count == openC: openData.append(data) openC += 6 if count == 4: closeData.append(data) elif closeC == count: closeData.append(data) closeC += 6 The two lists here are openData and closeData. As a rough example, I know I could do something like openData = [data for j in headers for z in j for data in z] closeData = [data for j in headers for z in j for data in z] I am worried that this would take roughly twice as long since the looping operations are being carried out twice. but is there a way to combine both statements like openData, closeData = [list comprehension] I am also confused about how to incorporate the if, elif logic into the list comprehension. Finally, is this something I should be doing? or would doing so be an abuse of list comprehensions. The above code I wrote works, but it looks ugly. My goal is better code than what I have.
answer count: 1
has comment: http://stackoverflow.com/comment/89750613
has answer: http://stackoverflow.com/a/51389397
accepted answer: http://stackoverflow.com/a/51389397
favorite count: 0
has comment: http://stackoverflow.com/comment/89751762
has comment: http://stackoverflow.com/comment/89751676
tagged with: python
type: AnsweredQuestion
upvote count: 0
has title: Python create two lists with one list comprehension
tagged with: performance
tagged with: list-comprehension
type: Question

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/51381112
tags question: http://stackoverflow.com/q/51363196
type: Tag
tags question: http://stackoverflow.com/q/51333806
tags question: http://stackoverflow.com/q/51431769
tags question: http://stackoverflow.com/q/51342010
tags question: http://stackoverflow.com/q/51448587
tags question: http://stackoverflow.com/q/51414775
tags question: http://stackoverflow.com/q/51327216
tags question: http://stackoverflow.com/q/51376353
tags question: http://stackoverflow.com/q/51463216
tag name: csv
tags question: http://stackoverflow.com/q/51421079
tags question: http://stackoverflow.com/q/51363749
tags question: http://stackoverflow.com/q/51448734
tags question: http://stackoverflow.com/q/51343721
tags question: http://stackoverflow.com/q/51362069
tags question: http://stackoverflow.com/q/51448616
tags question: http://stackoverflow.com/q/51441450
tags question: http://stackoverflow.com/q/51368284
tags question: http://stackoverflow.com/q/51328454
tags question: http://stackoverflow.com/q/51333007
tags question: http://stackoverflow.com/q/51411809
tags question: http://stackoverflow.com/q/51414103
tags question: http://stackoverflow.com/q/51383150
tags question: http://stackoverflow.com/q/51449242
tags question: http://stackoverflow.com/q/51478623
tags question: http://stackoverflow.com/q/51440540
tags question: http://stackoverflow.com/q/51398310
tags question: http://stackoverflow.com/q/51434949
tags question: http://stackoverflow.com/q/51462871
tags question: http://stackoverflow.com/q/51369229
tags question: http://stackoverflow.com/q/51430675
tags question: http://stackoverflow.com/q/51330211
tags question: http://stackoverflow.com/q/51463064
tags question: http://stackoverflow.com/q/51481923
tags question: http://stackoverflow.com/q/51478739
tags question: http://stackoverflow.com/q/51371030
tags question: http://stackoverflow.com/q/51449543
tags question: http://stackoverflow.com/q/51329549
tags question: http://stackoverflow.com/q/51351804
tags question: http://stackoverflow.com/q/51424295
tags question: http://stackoverflow.com/q/51418830
tags question: http://stackoverflow.com/q/51460366
tags question: http://stackoverflow.com/q/51443807
tags question: http://stackoverflow.com/q/51444121
tags question: http://stackoverflow.com/q/51330932
tags question: http://stackoverflow.com/q/51416983
tags question: http://stackoverflow.com/q/51394701
tags question: http://stackoverflow.com/q/51397083
tags question: http://stackoverflow.com/q/51352928
tags question: http://stackoverflow.com/q/51445860
tags question: http://stackoverflow.com/q/51378065
tags question: http://stackoverflow.com/q/51328197
tags question: http://stackoverflow.com/q/51430672
tags question: http://stackoverflow.com/q/51429236
tags question: http://stackoverflow.com/q/51480139
tags question: http://stackoverflow.com/q/51344821
tags question: http://stackoverflow.com/q/51342528
tags question: http://stackoverflow.com/q/51475919
tags question: http://stackoverflow.com/q/51381334
tags question: http://stackoverflow.com/q/51463449
tags question: http://stackoverflow.com/q/51426267
tags question: http://stackoverflow.com/q/51391188
tags question: http://stackoverflow.com/q/51329666
tags question: http://stackoverflow.com/q/51441167

http://stackoverflow.com/comment/89846733
comment on: http://stackoverflow.com/q/51437280
score: 0
type: Comment
has text: Just googling around gave me (https://github.com/WoLpH/numpy-stl), (http://python-stl.readthedocs.io/en/latest/) and (https://pymesh.readthedocs.io/en/latest/)
type: QuestionComment

http://stackoverflow.com/q/51325476
tagged with: dictionary
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51327078
tagged with: django
has comment: http://stackoverflow.com/comment/89628558
type: Question
has answer: http://stackoverflow.com/a/51325764
has title: Storing a function call in a Django model
tagged with: django-models
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/89628607
has body: Currently I am storing a series of objects as a dictionary of dictionaries, and within this I store calls to functions defined outside of the dictionary. These functions are specific to the objects, and cannot be generalised. In the dictionary I can refer to the function directly eg: 'some_property': function_name, and when I call that later on dictionary['some_property'](arg_1, arg_2)and the function gets called. I am looking migrate this dictionary of dictionaries to a django model, but I cannot see how I can replicate this functionality from a model. What I currently have: dictionaries.py def year_camel_month(filename, **kwargs): month = kwargs['month'].title() return filename.format(str(kwargs['year']), month) def year_month(filename, **kwargs): month = kwargs['month'] return filename.format(str(kwargs['year']), month.lower()) data_source_families = { 'dataset_1': { 'source_url': 'https://example.org/url/subfolder', 'slug': 'slug_that_changes_predictably_over_time{}-{}', 'slug_treatment': year_camel_month }, 'dataset_2': { 'source_url': 'https://example2.org/url/subfolder', 'slug': 'slug_that_changes_predictably_over_time{}-{}', 'slug_treatment': year_month }, } Which then gets called when combined with a user-defined time frame later on: get_data.py from .dictionaries import data_source_families slug = data_source_families[selected_dataset]['slug'] processed_slug = data_source_families[selected_dataset]['slug_treatment'](slug, some_kwargs) url = data_source_families[selected_dataset]['source_url'] + processed_slug And this is working fine. I am looking to develop functionality to improve consistency (and make these data available to another programme) by creating a django model that replicates this, something like this: models.py def year_camel_month(filename, **kwargs): month = kwargs['month'].title() return filename.format(str(kwargs['year']), month) def year_month(filename, **kwargs): month = kwargs['month'] return filename.format(str(kwargs['year']), month.…
accepted answer: http://stackoverflow.com/a/51325764
possible better answer: http://stackoverflow.com/a/51325721
has answer: http://stackoverflow.com/a/51325721
tagged with: python

http://stackoverflow.com/q/51421885
tagged with: python
has title: expected dense to have shape but got array with shape
has body: I am getting the following error while calling the model.predict function when running a text classification model in keras. I searched the everywhere but it isn't working for me. ValueError: Error when checking input: expected dense_1_input to have shape (100,) but got array with shape (1,) My data has 5 classes and has a total of 15 examples only. Below is the dataset query tags 0 hi intro 1 how are you wellb 2 hello intro 3 what's up wellb 4 how's life wellb 5 bye gb 6 see you later gb 7 good bye gb 8 thanks gratitude 9 thank you gratitude 10 that's helpful gratitude 11 I am great revertfine 12 fine revertfine 13 I am fine revertfine 14 good revertfine This is the code of my model from keras.preprocessing.text import Tokenizer from sklearn.preprocessing import LabelBinarizer from keras.models import Sequential import pandas as pd from keras.layers import Dense, Activation data = pd.read_csv('text_class.csv') train_text = data['query'] train_labels = data['tags'] tokenize = Tokenizer(num_words=100) tokenize.fit_on_texts(train_text) x_data = tokenize.texts_to_matrix(train_text) encoder = LabelBinarizer() encoder.fit(train_labels) y_data = encoder.transform(train_labels) model = Sequential() model.add(Dense(512, input_shape=(100,))) model.add(Activation('relu')) model.add(Dense(5)) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['acc']) model.fit(x_data, y_data, batch_size=8, epochs=10) predictions = model.predict(x_data[0]) tag_labels = encoder.classes_ predicted_tags = tag_labels[np.argmax(predictions)] print (predicted_tags) I am not able to figure out where the problem lies and how to fix it.
tagged with: shapes
tagged with: text-classification
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89815116
possible better answer: http://stackoverflow.com/a/51422287
score: 12
has answer: http://stackoverflow.com/a/51432523
has answer: http://stackoverflow.com/a/51422287
answer count: 2
upvote count: 12
downvote count: 0
tagged with: keras
accepted answer: http://stackoverflow.com/a/51432523
favorite count: 0
has comment: http://stackoverflow.com/comment/89819043

http://stackoverflow.com/comment/89691056
has text: You seem to be using IPython or Juypter Notebook. Such information is utterly important and should not be left out from the question.
comment on: http://stackoverflow.com/q/51353865
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89791927
has text: thanks for your attention, i run it with your sample and here is my error: ValueError: Error when checking input: expected conv1d_1_input to have 3 dimensions, but got array with shape (3, 1)
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51410081

http://stackoverflow.com/comment/89654296
type: AnswerComment
type: Comment
has text: Two questions 1. Does this move my actual mouse 2. If not, would this get detected as regular mouse movements by a given website?
comment on: http://stackoverflow.com/a/51340364
score: 0

http://stackoverflow.com/comment/89864965
type: Comment
comment on: http://stackoverflow.com/a/51447180
score: 0
type: AnswerComment
has text: thanks for your solution- since I'm kinda new to this field would you please explain a little about this sentence: you need to add 1 more dimension to your tensor

http://stackoverflow.com/a/51439143
upvote count: 7
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51390568
has comment: http://stackoverflow.com/comment/89994365
accepted answer of: http://stackoverflow.com/q/51390568
type: Answer
has comment: http://stackoverflow.com/comment/89973258
downvote count: 0
has comment: http://stackoverflow.com/comment/89979346
has body: extract_rels (doc) checks that arguments subjclass and objclass are known NE tags, hence the error with NPH. The easy, ad hoc, way is to rewrite a customized extract_rels function (example below). import nltk import re grammar = r""" NPH: {&lt;DT|JJ|NN.*&gt;+} # Chunk sequences of DT, JJ, NN PPH: {&lt;IN&gt;&lt;NP&gt;} # Chunk prepositions followed by NP VPH: {&lt;VB.*&gt;&lt;NP|PP|CLAUSE&gt;+$} # Chunk verbs and their arguments CLAUSE: {&lt;NP&gt;&lt;VP&gt;} # Chunk NP, VP """ cp = nltk.RegexpParser(grammar) sentence = [("Mary", "NN"), ("saw", "VBD"), ("the", "DT"), ("cat", "NN"), ("sit", "VB"), ("on", "IN"), ("the", "DT"), ("mat", "NN")] chunked = cp.parse(sentence) IN = re.compile(r'.*\bon\b') def extract_rels(subjclass, objclass, chunked, pattern): # padding because this function checks right context pairs = nltk.sem.relextract.tree2semi_rel(chunked) + [[[]]] reldicts = nltk.sem.relextract.semi_rel2reldict(pairs) relfilter = lambda x: (x['subjclass'] == subjclass and pattern.match(x['filler']) and x['objclass'] == objclass) return list(filter(relfilter, reldicts)) for e in extract_rels('NPH', 'NPH', chunked, pattern=IN): print(nltk.sem.rtuple(e)) Output: [NPH: 'the/DT cat/NN'] 'sit/VB on/IN' [NPH: 'the/DT mat/NN']
score: 7
has comment: http://stackoverflow.com/comment/89972029

http://stackoverflow.com/q/51404817
answer count: 2
upvote count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/89780720
accepted answer: http://stackoverflow.com/a/51404913
has comment: http://stackoverflow.com/comment/89780603
has comment: http://stackoverflow.com/comment/89780895
favorite count: 0
possible better answer: http://stackoverflow.com/a/51404914
linked to: http://stackoverflow.com/q/14657241
has answer: http://stackoverflow.com/a/51404914
tagged with: python
linked to: http://stackoverflow.com/q/19960077
has body: I have written code where I have a dataframe containing all types of food. I have then split it into fruit and veg series using str.contains. I have written code where I append any food which is common in both series to a list: fruit = fruit_2.tolist()#converting the series to a list veg = veg_2.tolist()#converting the series to a list for x in range (len(fruit)): for y in range (len(veg)): if fruit[x] == veg[y]: both.append(fruit[x]) print(both) This works just wondering if someone has a solution which utilised pandas and doesn't use a for loop. Thanks
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/18079563
has comment: http://stackoverflow.com/comment/89780710
has answer: http://stackoverflow.com/a/51404913
score: -1
has title: Pandas - how to compare 2 series and append the values which are in both to a list
downvote count: 1
type: Question

http://stackoverflow.com/a/51428961
answers question: http://stackoverflow.com/q/51428084
type: Answer
score: 0
has body: Newbie here. Tried my best... df['dummy'] = list(range(0,len(df))) #added a column for looping grp = df.groupby('ID').agg({'score_1' : 'sum' , 'score_2' : 'sum', 'dummy' : 'count'}).reset_index(level=[0]) instance_1 = [] instance_2 = [] instance_3 = [] i = 0 while i &lt; len(grp): if(grp.score_1[i] == 0 and grp.score_2[i] == 0): instance_1.append(grp.ID[i]) elif(grp.score_1[i] == 0 and grp.score_2[i] &gt;= 1 and grp.score_2[i] &lt; grp.dummy[i]): instance_2.append(grp.ID[i]) elif(grp.score_1[i] == 0 and grp.score_2[i] == grp.dummy[i]): instance_3.append(grp.ID[i]) i += 1

http://stackoverflow.com/q/51355926
type: UnansweredQuestion
has title: send PIL.Image to django server side and get it back
tagged with: python-3.x
type: Question
answer count: 2
tagged with: django
tagged with: python
tagged with: python-imaging-library
has answer: http://stackoverflow.com/a/51363364
score: 0
has answer: http://stackoverflow.com/a/51453785
has body: I don't know what's under the hood of sending an image from client side to server side, so stuck by the following scenario. I want to send a PIL.Image object to django server side using the Python requests lib and get it back in order to use the PIL.Image object on server side. As I have tested , if sent the PIL.Image object without any conversion , that is r = requests.post(SERVER_URL, data={ 'image': PILimage,#PILimage is of type PIL.Image 'wordPos':(86,23) }, ) then I just got a str object with value &lt;PIL.PngImagePlugin.PngImageFile image mode=RGB size=149x49 at 0x13F25D0&gt; on server side, I guess it was caused by requests, which converted the PIL.Image object to a str object before sending, so why requestsdo the conversion ? why cannot we send the PIL.Image object without any conversion over the Internet ? please give some explanation here, thanks! Someone told me I could convert the PIL.Image object to bytes form then do the sending , that is r = requests.post(SERVER_URL, data={ 'image': PILimage.tobytes(),#PILimage is of type PIL.Image 'wordPos':(86,23) }, ) but then how to get the image back to PIL.Image object on server side? It seems PIL.Image.frombytes() won't help.

http://stackoverflow.com/q/51339986
downvote count: 0
answer count: 1
score: 1
favorite count: 0
type: UnansweredQuestion
has title: Anaconda don't install navigator
tagged with: python
upvote count: 1
has answer: http://stackoverflow.com/a/51340064
type: Question
has comment: http://stackoverflow.com/comment/89653727
tagged with: anaconda
has body: I installed anaconda on windows10. Anaconda prompt emerge in menu, but other programs like navigator, spider, jupiter weren't installed (I can't find their .exe on laptop). And prompt doesn't work correctly. log("C:\Users\Vl\Anaconda3\Scripts\activate.bat" isn't internal or external comand).

http://stackoverflow.com/a/51464054
type: Answer
answers question: http://stackoverflow.com/q/51464020
score: 4
upvote count: 4
downvote count: 0
has body: You can use iteration with a dictionary to construct a mapping. Then apply this mapping to your original list. omg = ['a', 'b', 'c', 'a', 'b', 1] d = {} for i in omg: if i not in d: d[i] = len(d) omg_id = list(map(d.get, omg)) print(omg_id) [0, 1, 2, 0, 1, 3] Here's an alternative solution using toolz.unique [equivalent to the unique_everseen recipe in the itertools docs]: from toolz import unique d = {v: k for k, v in enumerate(unique(omg))} omg_id = list(map(d.get, omg)) Both solutions have the following features: O(n) complexity. Require elements of omg to be hashable.

http://stackoverflow.com/a/51356400
has body: The code below uses nquad() from scipy library and is based on equation in question and examples here. The result and abserr (absolute error) are stored in a dataframe. Import libraries import pandas as pd import numpy as np from scipy import integrate Set values for global variables a = 0 b = 10 r = 10 d_list = [1,2,3,4,5] Define functions def f(x, y): return x*y def bounds_y(): return [a, b] def bounds_x(y): return [0, np.sqrt(r**2 - (y-d)**2)] Iterate over values in 'd' temp = [] for i in d_list: d = i # re-set global value of 'd' temp.append(integrate.nquad(f, [bounds_x, bounds_y])) Save result and error values in a dataframe temp = pd.DataFrame(temp, columns=['result', 'abserr']) temp
answers question: http://stackoverflow.com/q/51354298
has comment: http://stackoverflow.com/comment/89691833
downvote count: 0
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/a/51414032
has comment: http://stackoverflow.com/comment/89799963
answers question: http://stackoverflow.com/q/51412849
has comment: http://stackoverflow.com/comment/89800086
has comment: http://stackoverflow.com/comment/89799462
has comment: http://stackoverflow.com/comment/89800074
accepted answer of: http://stackoverflow.com/q/51412849
has comment: http://stackoverflow.com/comment/89799938
has comment: http://stackoverflow.com/comment/89799999
upvote count: 1
has comment: http://stackoverflow.com/comment/89799447
type: AcceptedAnswer
has body: You could use any of the following packages, 1. django-url-filter 2. django-filter I think, the first one will more apt for your requirement. Follow the instructions and you will get what you are searching for
has comment: http://stackoverflow.com/comment/89800012
has comment: http://stackoverflow.com/comment/89800048
has comment: http://stackoverflow.com/comment/89799627
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/89799515
score: 1

http://stackoverflow.com/comment/89824996
type: Comment
type: QuestionComment
score: 0
has text: Yeah, sorry. I've tried that and it still just put the data side by side
comment on: http://stackoverflow.com/q/51426471

http://stackoverflow.com/comment/89756130
type: QuestionComment
comment on: http://stackoverflow.com/q/51392058
score: 0
type: Comment
has text: For the record, I think the downvotes are harsh for a first post. This isn't too bad as far as first questions go, it at least includes an error and the code. I'd at least give the OP a chance to respond to comments...

http://stackoverflow.com/comment/89634542
has text: I mean that some of the functions that are called may interfere with the exception raise and catch mechanism you are relying upon. Maybe it isn't the case, I cannot know, but you can test and rule it out by minimizing the code.
comment on: http://stackoverflow.com/q/51327461
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/51478687
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51473291
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/51473291
upvote count: 2
has body: There is not a gradient for round since the function is piecewise-constant and non-continuous. That is, for any range where the result would be the same (e.g. the range (0.5, 1.5)) the gradient would be 0, and it would be undefined at the border values (0.5, 1.5 etc.). In any case, a gradient of 0 is not useful. I think you are mixing up some stuff in your code. In binary classification, you do want class outputs at the end (i.e. 0 or 1), but for training you will generally want to use the continous probabilities. That is, the sigmoid outputs without rounding. In addition to that, the built-in Tensorflow cross-entropy losses actually apply the sigmoid internally and expect the pre-sigmoid values (logits), which is sorta implied by their names (e.g. tf.nn.sigmoid_cross_entropy_with_logits). So in your snippet you should pass logits = pred_raw to the loss. BTW you also mixed up labels and logits -- logits are your model outputs, labels the real labels.

http://stackoverflow.com/a/51373538
has body: A flag is meant to be a Boolean value, and argparse by default adds arguments as a string. What you can do instead is to use action='store_true' when adding arguments. See: https://docs.python.org/2/library/argparse.html#action parser = argparse.ArgumentParser() parser.add_argument('-w','--words', action='store_true', help='Words') parser.add_argument('-l','--len', action='store_true', help='len') parser.add_argument('-u','--unique', action='store_true', help='unique') args = parser.parse_args() if args.words: if test_words_containing() == True: print('words_containing pass') else: print('words_containing fail') if args.len: if test_len_safe() == False: print('len_safe fail') else: print('len_safe pass')
has comment: http://stackoverflow.com/comment/89718769
answers question: http://stackoverflow.com/q/51373456
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51373456
has comment: http://stackoverflow.com/comment/89718762
type: Answer

http://stackoverflow.com/q/51469194
has comment: http://stackoverflow.com/comment/89907475
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/54476537
upvote count: 9
tagged with: installation
downvote count: 0
tagged with: pytorch
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51486141
has answer: http://stackoverflow.com/a/51478787
has answer: http://stackoverflow.com/a/55213605
tagged with: conda
type: Question
score: 9
has body: I'd like to use PyTorch in a Python program. The instructions for installing it require conda. After installing Conda I ran: &gt;conda install -c pytorch pytorch (as instructed on the PyTorch [page][1]) It looked promising -- until the end. Solving environment: done ## Package Plan ## environment location: C:\ProgramData\Miniconda3 added / updated specs: - pytorch The following packages will be downloaded: package | build ---------------------------|----------------- icc_rt-2017.0.4 | h97af966_0 8.0 MB vs2015_runtime-15.5.2 | 3 2.2 MB pytorch-0.4.0 |py36_cuda80_cudnn7he774522_1 529.2 MB pytorch mkl-2018.0.3 | 1 178.1 MB numpy-1.14.5 | py36h9fa60d3_4 35 KB intel-openmp-2018.0.3 | 0 1.7 MB numpy-base-1.14.5 | py36h5c71026_4 3.8 MB vc-14.1 | h0510ff6_3 5 KB blas-1.0 | mkl 6 KB conda-4.5.8 | py36_0 1.0 MB mkl_fft-1.0.2 | py36hb217b18_0 113 KB mkl_random-1.0.1 | py36h77b88f5_1 268 KB ------------------------------------------------------------ Total: 724.4 MB The following NEW packages will be INSTALLED: blas: 1.0-mkl icc_rt: 2017.0.4-h97af966_0 intel-openmp: 2018.0.3-0 mkl: 2018.0.3-1 mkl_fft: 1.0.2-py36hb217b18_0 mkl_random: 1.0.1-py36h77b88f5_1 numpy: 1.14.5-py36h9fa60d3_4 numpy-base: 1.14.5-py36h5c71026_4 pytorch: 0.4.0-py36_cuda80_cudnn7he774522_1 pytorch The following packages will be UPDATED: conda: 4.5.4-py36_0 --&gt; 4.5.8-py36_0 vc: 14-h0510ff6_3 --&gt; 14.1-h0510ff6_3 vs2015_runtime: 14.0.25123-3 --&gt; 15.5.2-3 Proceed ([y]/n)? y Downloading and Extracting Packages icc_rt-2017.0.4 | 8.0 MB | ############################################################################## | 100% vs2015_runtime-15.5. | 2.2 MB | ############################################################################## | 100% pytorch-0.4.0 | 529.2 MB | ############################################################################# | 100% mkl-2018.0.3 | 178.1 MB | ############################################################################# | 100% numpy-1.14.5 | 35 KB | ##########################…
has title: Installing PyTorch under conda fails with permissions error and Rolling back transaction
has answer: http://stackoverflow.com/a/64873683

http://stackoverflow.com/q/51464031
has answer: http://stackoverflow.com/a/51464394
favorite count: 0
tagged with: beautifulsoup
type: Question
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/89897237
score: -2
accepted answer: http://stackoverflow.com/a/51464394
downvote count: 2
tagged with: web-scraping
has title: How to create DataFrame with scraped data in python?
answer count: 1
has comment: http://stackoverflow.com/comment/89897058
has body: I am trying to make a web scraper that pulls data and categorizes it in pandas data frame. All of my code: import requests from bs4 import BeautifulSoup as soup from urllib.request import urlopen as uReq import numpy as np import pandas as pd class CaseCrawler: def __init__(self, starting_url, depth): self.starting_url = starting_url self.depth = depth self.cases = [] def crawl(self): self.get_case_info(self.starting_url) return def get_case_info(self, link): # opening up connection uClient = uReq(link) page_html = uClient.read() uClient.close() # html parsing page_soup = soup(page_html, "html.parser") case = page_soup.findAll("div", {"class":"bbWrapper"}) for point in case: name = point.b.text body = point.text tag_block = page_soup.findAll("div", {"class":"blockStatus-message"}) for tagger in tag_block: tag_title = tagger.findAll("dl", {"class":"pairs pairs--columns pairs--spaced pairs--fixedSmall"}) #pandas dataframe ##tag_df = pd.DataFrame(tag_title, index=tag_title.dt) print(tag_title[0]) tag_df.to_csv("temp.csv") crawler = CaseCrawler('https://www.yargikararlari.net/konu/iikya-gore-ortakligin-giderilmesi-davasi-acilabilmesi-icin-usulune-gore-borclu-ortagin-alacaklisi-iik-m-121.350/', 0) crawler.crawl() In the end of the code I want to scrape a block of info in a data frame with pandas Here is the my problematic part of this website: 2rows 2columns When I run the code it creates indented and unnecessary spaced csv file: csv file Thanks in advance...
has comment: http://stackoverflow.com/comment/89896937
type: AnsweredQuestion
upvote count: 0

http://stackoverflow.com/a/51381093
answers question: http://stackoverflow.com/q/51381010
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89733931
accepted answer of: http://stackoverflow.com/q/51381010
has body: time.perf_counter(), available since Python 3.3, lets you access a high-resolution wallclock. t0 = time.perf_counter() time.sleep(.1) print(time.perf_counter() - t0)
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/89734411

http://stackoverflow.com/q/51364784
downvote count: 0
has body: I have two dataframes with a common column called 'upc' as such: df1: upc 23456793749 78907809834 35894796324 67382808404 93743008374 df2: upc 4567937 9078098 8947963 3828084 7430083 Notice that df2 'upc' values are the innermost 7 values of df1 'upc' values. Note that both df1 and df2 have other columns not shown above. What I want to do is do an inner merge on 'upc' but only on the innermost 7 values. How can I achieve this?
answer count: 3
tagged with: pandas
tagged with: python
tagged with: merge
favorite count: 0
accepted answer: http://stackoverflow.com/a/51364986
has answer: http://stackoverflow.com/a/51364951
has title: Pandas merge on part of two columns
upvote count: 2
possible better answer: http://stackoverflow.com/a/51364951
type: AnsweredQuestion
score: 2
type: Question
has answer: http://stackoverflow.com/a/51365031
has answer: http://stackoverflow.com/a/51364986

http://stackoverflow.com/comment/89852555
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51440678
has text: Your image show the unexpected behavior. It should be displayed as Projects 3e. I edited my question because the "error" I'm getting was not displayed as expected

http://stackoverflow.com/q/51423517
downvote count: 3
upvote count: 4
answer count: 2
has answer: http://stackoverflow.com/a/51429499
favorite count: 0
tagged with: scope
has comment: http://stackoverflow.com/comment/89861718
has answer: http://stackoverflow.com/a/51648708
has comment: http://stackoverflow.com/comment/89863171
possible better answer: http://stackoverflow.com/a/51429499
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89822814
has comment: http://stackoverflow.com/comment/89842920
has comment: http://stackoverflow.com/comment/89817964
has body: I created some test code, but I can't really understand why it works. Shouldn't moo be defined before we can use it? #!/usr/bin/python3 class Test(): def __init__(self): self.printer = None def foo(self): self.printer = self.moo self.printer() def moo(self): print("Y u printing?") test = Test() test.foo() Output: $ python test.py Y u printing? I know that the rule is define earlier, not higher, but in this case it's neither of those.
has comment: http://stackoverflow.com/comment/89863143
type: Question
has title: Why is this code not throwing a 'not defined' error?
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/972
accepted answer: http://stackoverflow.com/a/51648708
score: 1

http://stackoverflow.com/q/51466462
favorite count: 0
tagged with: python-3.x
tagged with: animation
has answer: http://stackoverflow.com/a/51469764
tagged with: python
has body: I am trying to recreate a population variance graph in python In that example, as soon as we start, the function runs immediately to I guess the limit of the environment set by the website. I have managed to create similar graphs, but for animation I am stuck. Below is my code. import matplotlib.animation as animation fig, ax = plt.subplots(1,1,figsize=(5,4)) plt.close() frameRate = 30 global_counter = 0 def animate(i): ax.clear() global global_counter ax.text(0.5,0.5, 'test:{}'.format(global_counter)) global_counter += 1 ani = animation.FuncAnimation(fig, animate, np.arange(1,1000), interval=frameRate) plt.tight_layout() from IPython.display import HTML HTML(ani.to_html5_video()) Output: The problem is, the execution time is directly proportional to the number of times and then the graph is generated. So if 1000 as above or more, it takes considerable time before generating the graph. Looks like it generates all 1000 frames before outputting the graph. I would need about at least 20000 frames this way. Instead, it should be live and update as long as the website is opened or to an upper limit set without compile-time compromise. And the next problem is, after 1000, the counter starts all over again. Shouldn't the global counter continue to increase? I want Program to start immediately and then update dynamically like in the example I quoted. Program to continue increasing counter or not resetting variables after frames count is over. If not matplotlib, seaborn or plotly or any other lib could help here? I am using Python 3.x in ipython notebook (anaconda environment).
score: 4
type: AnsweredQuestion
tagged with: matplotlib
type: Question
upvote count: 4
accepted answer: http://stackoverflow.com/a/51469764
has title: How to create indefinite funcanimation frames dynamically updating in real time?
answer count: 1
downvote count: 0
tagged with: frame

http://stackoverflow.com/comment/108113942
type: Comment
type: QuestionComment
has text: :) You're Java dev who's been coerced into doing Python right? Did you get an answer for this? I suspect it has something to do with multithreading.
comment on: http://stackoverflow.com/q/51363497
score: 0

http://stackoverflow.com/comment/89948762
type: Comment
has text: Thanks Martin. It works now after adding the project interpreter
type: AnswerComment
comment on: http://stackoverflow.com/a/51441954
score: 0

http://stackoverflow.com/q/51354856
tagged with: cython
linked to: http://stackoverflow.com/q/50248524
tagged with: pypi
type: Question
score: 4
has title: Pypi and Cython
upvote count: 4
has answer: http://stackoverflow.com/a/51360687
answer count: 1
downvote count: 0
favorite count: 0
has body: I'm trying to put together my first PyPi package and am growing confused about some basic aspects of it. My package depends on SNPknock. When I try to install it on a fresh system (Ubuntu 18.04), I get: pip install snpknock Collecting snpknock Using cached https://files.pythonhosted.org/packages/68/a0/ceb6adc2b7f1a3009f2077c157a99640094021a66f881cb678ecf4 78887f/SNPknock-0.5.2.tar.gz Complete output from command python setup.py egg_info: You don't seem to have Cython installed. Please get a copy from www.cython.org and install it I've extracted the setup.py from the tarball here, which includes that error message. Here is my confusion. The setup.py file specifies Cython as a dependency: DEPENDENCIES = ['Cython&gt;='+CYTHON_MIN_VERSION, 'numpy&gt;='+NUMPY_MIN_VERSION] However, it also imports Cython, but it seems that it needs to do that in order to cythonize some modules. It all seems a little circular, but I suspect that either I (or the author of this package) are missing something about this process.
tagged with: python
accepted answer: http://stackoverflow.com/a/51360687
type: AnsweredQuestion
tagged with: installation

http://stackoverflow.com/q/51404984
score: 1
tagged with: pip
downvote count: 1
has comment: http://stackoverflow.com/comment/89780919
type: Question
upvote count: 2
has title: Unable to use pip3 with sudo
has comment: http://stackoverflow.com/comment/89781188
answer count: 1
has comment: http://stackoverflow.com/comment/89782351
favorite count: 0
tagged with: python-3.x
tagged with: linux
has body: I am unable to use pip3 as sudo. Currently if I don't use sudo, my computer assumes that I want to use python3 but if I include sudo my computer assumes I want to use python2. I want to be able to use both pip and pip3 with sudo. If I attempt to install a library as both sudo and with pip3 I get an ImportError. Currently the way around this for me is to use the --user flag without sudo. Is there a way I can use pip and pip3 with sudo? The only reason why I ask this is because I was looking at installation instructions for a library called Tensorflow and they specifically include sudo. sudo pip install -U tensorflow # Python 2.7 sudo pip3 install -U tensorflow # Python 3.n As I wanted to use tensorflow with python3, I used pip3 and --user without sudo to get around this. Is that an issue or is it bad practice to use --user ? EDIT: I am not sure why I received a negative rating - if there is an edit I need to make please comment.
has comment: http://stackoverflow.com/comment/89781320
has answer: http://stackoverflow.com/a/51405744
accepted answer: http://stackoverflow.com/a/51405744
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/51341050
has comment: http://stackoverflow.com/comment/89655699
has answer: http://stackoverflow.com/a/51617305
accepted answer: http://stackoverflow.com/a/51617305
has comment: http://stackoverflow.com/comment/89655714
tagged with: python
tagged with: tkinter
has body: I am building an interactive Tkinter GUI wherein a blank pyplot figure and axes are drawn in the GUI along with some buttons, where the user can click, drag, and delete points to form a custom point plot. The coordinates of these points can then be printed in a particular format used as Input in a much more complex Fortran code. I have gotten almost everything to work, except for the initial interactivity of the figure/axes space. I am heavily relying on a wonderful Draggable-Plot object code I found on GitHub by user yuma-m, link below: https://github.com/yuma-m/matplotlib-draggable-plot/blob/master/draggable_plot.py After much tweaking of the original Draggable-Plot object I was able to get the interactive plot integrated into my GUI; HOWEVER the bug comes in when I generate the plot for the first time. After setting the correct axes bounds, and clicking 'Update Axes' for the FIRST time, the figure and plot are drawn but do NOT register any MouseEvents. My guess is that when the event.inaxes in [self._axes] condition is checked in the _on_click function, the existence/placement of self._axes is being blocked in some way. The best part happens when you click the 'Update Axes' button a second time, and a new axes object is plotted directly below the first. When this occurs, the script will begin to register MouseEvents in the INITIAL plot, but will draw all corresponding points in the new SECOND plot. When I restrict the placement of the second plot in the same grid position as the first, no interactivity is registered, as I'm guessing the new axes overlaps the first. I'm simply looking for a solution to this bizarre problem; obviously the ideal functionality of this GUI would be initial interactivity of the first generated plot, with any subsequently generated axes behaving the same. Thank you! Image of Two Axes state of GUI import math import matplotlib from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg import matplotlib.pyplo…
has comment: http://stackoverflow.com/comment/89676632
type: Question
type: AnsweredQuestion
tagged with: matplotlib
tagged with: mouseevent
score: 0
answer count: 1
tagged with: interactive
has title: Interactive PyPlot Figure in Tkinter not registering MouseEvents

http://stackoverflow.com/comment/89713907
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51369886
has text: @LearningToPython updated my answer, hope that hleps

http://stackoverflow.com/q/51370484
has comment: http://stackoverflow.com/comment/89713185
score: 0
tagged with: numpy
accepted answer: http://stackoverflow.com/a/51370742
type: AnsweredQuestion
has body: I know this question might be trivial but I am in the learning process. Given numpy 2D array, I want to take a block of rows using slicing approach. For instance, from the following matrix, I want to extract only the first three rows, so from: [[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12] [ 28 9 203 102] [577 902 11 101]] I want: [[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12]] My code here actually still missing something. I appreciate any hint. X = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [28, 9, 203, 102], [577, 902, 11, 101]] X = np.array(X) X_sliced = X[3,:] print(X_sliced)
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89713160
type: Question
has answer: http://stackoverflow.com/a/51370742
tagged with: python
has title: Extract a block of rows from 2D numpy
answer count: 1

http://stackoverflow.com/a/51335268
accepted answer of: http://stackoverflow.com/q/51332961
answers question: http://stackoverflow.com/q/51332961
upvote count: 1
has body: Issue was something like this: I have a "BASE" multi-input model, where all inputs are identical, as this "BASE" model was just a combination of multiple models which happens to share identical type input! Now, when using this "BASE" model for classification, I had to provide [input_data x "total_inputs"] for each input layer, which is something I don't wanted to do, say when classifying millions of sentences! So, the ideal solution was to just have a single input which is connected with all "BASE" model inputs!! Alrighty, so here is how it's done: Create a new top_model which will take single input and generate multiple identical outputs. This can be done with Lambda layer. single_input = layers.Input(input_shape) multi_output = layers.Lambda(lambda x: [x] * total_numbers_of_base_inputs)(single_input) top_model = Model(inputs=single_input, outputs=multi_output) Use the top_model input and your multi_input_base_model like below to create new single_input model. new_model = Model(inputs=top_model.input, outputs=multi_input_base_model(top_model.output))
score: 1
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/89709251
score: 1
comment on: http://stackoverflow.com/q/51368443
has text: You can't use `else:` for this. `else` is specifically about `break`. It removes the need for a "found" flag in _many_ cases, but not in _every possible_ case, and your case is one that it doesn't help.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51339840
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51339887
tagged with: python
has comment: http://stackoverflow.com/comment/89653152
has comment: http://stackoverflow.com/comment/89653506
has comment: http://stackoverflow.com/comment/89653982
tagged with: file
tagged with: file-writing
has answer: http://stackoverflow.com/a/51339899
type: Question
has comment: http://stackoverflow.com/comment/89653374
score: 0
has title: How to update the file size on desk while python file writing program runs
has comment: http://stackoverflow.com/comment/89653691
has answer: http://stackoverflow.com/a/51339885
answer count: 3
has body: I have a python program that performs a socket connection, get some data and writes them to a file. The data is quite large. I need to make sure that the writing is in a good progress while the program is running by clicking of the file properties to see the size increases as the program runs for more time. To simplify, the main logic of the issue appears in this simple example: myfile = open ("test.txt","w") x = 0 while x &lt; 1000000: myfile.write("line:"+str(x)) print("line",str(x)) x+=1 This program writes 1 million line. During the writing, I check the file size and it is always 0 KB. Only when the program finishes, I can see the file size. This is inconvenient for me. 1) What is the reason for that? I recall that I had run programs but I was able to see file size progress while the program runs? I am not sure if it was python program but I used to do this usually to monitor progress. 2) How can I reflect the file writing progress so when I click on the file properties while the python program runs, I can see the file size increases. UPDATE: Unfortunately none of the solutions seem to be practical. First, I do fresh writing with "w" in purpose. The program should write new fresh data every run. I do not want to append. Second, the program should write the data at onece in the loop. At the end, I should close the file (which I missed). What I need is something like synchronization or flushing. I do not thing it is practical to close the file for a loop that take 100 thousands iterations.
tagged with: python-3.x

http://stackoverflow.com/comment/89673908
comment on: http://stackoverflow.com/q/51350462
has text: No thanks, I’m not that invested in your problem.
type: Comment
type: QuestionComment
score: 1

function
tags question: http://stackoverflow.com/q/51370979
tags question: http://stackoverflow.com/q/51439032
tags question: http://stackoverflow.com/q/51403918
tags question: http://stackoverflow.com/q/51412549
tag name: function
tags question: http://stackoverflow.com/q/51481025
tags question: http://stackoverflow.com/q/51353519
tags question: http://stackoverflow.com/q/51380949
tags question: http://stackoverflow.com/q/51449914
tags question: http://stackoverflow.com/q/51381874
tags question: http://stackoverflow.com/q/51447968
tags question: http://stackoverflow.com/q/51460441
tags question: http://stackoverflow.com/q/51398843
tags question: http://stackoverflow.com/q/51479235
tags question: http://stackoverflow.com/q/51481114
tags question: http://stackoverflow.com/q/51394631
tags question: http://stackoverflow.com/q/51377272
tags question: http://stackoverflow.com/q/51391438
tags question: http://stackoverflow.com/q/51468492
tags question: http://stackoverflow.com/q/51325979
tags question: http://stackoverflow.com/q/51363208
tags question: http://stackoverflow.com/q/51359446
tags question: http://stackoverflow.com/q/51387762
tags question: http://stackoverflow.com/q/51400001
tags question: http://stackoverflow.com/q/51436042
tags question: http://stackoverflow.com/q/51444898
tags question: http://stackoverflow.com/q/51457267
tags question: http://stackoverflow.com/q/51327332
tags question: http://stackoverflow.com/q/51344120
tags question: http://stackoverflow.com/q/51334924
tags question: http://stackoverflow.com/q/51386324
tags question: http://stackoverflow.com/q/51439359
tags question: http://stackoverflow.com/q/51459242
type: Tag
tags question: http://stackoverflow.com/q/51432604
tags question: http://stackoverflow.com/q/51458881
tags question: http://stackoverflow.com/q/51386670
tags question: http://stackoverflow.com/q/51393610
tags question: http://stackoverflow.com/q/51470334
tags question: http://stackoverflow.com/q/51393216
tags question: http://stackoverflow.com/q/51422537
tags question: http://stackoverflow.com/q/51353162
tags question: http://stackoverflow.com/q/51455109
tags question: http://stackoverflow.com/q/51369440
tags question: http://stackoverflow.com/q/51477283
tags question: http://stackoverflow.com/q/51396342
tags question: http://stackoverflow.com/q/51435407
tags question: http://stackoverflow.com/q/51414262
tags question: http://stackoverflow.com/q/51370082
tags question: http://stackoverflow.com/q/51325127
tags question: http://stackoverflow.com/q/51435095
tags question: http://stackoverflow.com/q/51432553
tags question: http://stackoverflow.com/q/51433768
tags question: http://stackoverflow.com/q/51473799
tags question: http://stackoverflow.com/q/51456897
tags question: http://stackoverflow.com/q/51432414
tags question: http://stackoverflow.com/q/51448331
tags question: http://stackoverflow.com/q/51419169
tags question: http://stackoverflow.com/q/51455651
tags question: http://stackoverflow.com/q/51360294

http://stackoverflow.com/comment/89839069
score: 0
has text: Python is indentation sensitive, `i += 1` needs to be inside the while loop. Also, you haven't clarified as to what a *missing* positive integer even means?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51434350

http://stackoverflow.com/comment/89818762
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51423509
has text: I re installed python2 just to be sure. But in anycase I knew its not the issue, since I do not have python3 on my machine. Looks like docker has its own python enviroment .. distiller is not a user i have on my machine
score: 0

http://stackoverflow.com/comment/89770903
comment on: http://stackoverflow.com/a/51400069
score: 0
type: Comment
has text: your functions are missing the `self` parameter. You need to declare it as `def myinput(self):`
type: AnswerComment

http://stackoverflow.com/q/51405822
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51407666
has answer: http://stackoverflow.com/a/51406596
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/51427526
has comment: http://stackoverflow.com/comment/89783589
type: Question
has comment: http://stackoverflow.com/comment/89784267
tagged with: matplotlib
has title: Dictionary in python for implementing the 37% Rule
has comment: http://stackoverflow.com/comment/89786370
answer count: 3
has comment: http://stackoverflow.com/comment/89783082
has comment: http://stackoverflow.com/comment/89826422
downvote count: 0
accepted answer: http://stackoverflow.com/a/51427526
favorite count: 0
tagged with: python-3.x
has body: I am trying the famous 37% rule from the book- "Algorithms to live by" by Brian Christian. The 37% Rule basically says that when you need to screen a range of options in a limited amount of time - be they candidates for a job, new apartments, or potential romantic partners - the best time to make a decision is when you've looked at 37% of those options. At that point in a selection process, you'll have gathered enough information to make an informed decision, but you won't have wasted too much time looking at more options than necessary. At the 37% mark, you're in a good place to pick the best of the bunch. A common thought experiment to demonstrate this theory - developed by non-PC math guys in the 1960s - is called "The Secretary Problem." The program is running but I wanted to start to consider selecting the candidates after 37% of the candidates. Since I am using dictionary, I do not get to access the elements after a specified number of candidates. How can I make this possible? import matplotlib.pyplot as plt # for visualising scores def initiate(candidates): print("Total candidates are : ",len(candidates)) lookup_num=int(len(candidates) *0.37) #finds 37% of the candidates average=lookup(candidates) # returns average of lookup phase chosen=select_cad(candidates,lookup_num,average) # selects a candidate based on lookUp average print("The chosen candidate is : {} ".format(chosen)) def lookup(candidates): average_score=0 for cands,score in candidates.items(): average_score+=score average_score=int(average_score/len(candidates)) print("The average score in lookup is : ",average_score) #return the average score to average local variable return average_score def select_cad(candidates,lookup_num,average): for cands,score in candidates.items(): if(score&gt;average): return cands else: continue print("Something went wrong!") quit candidates={"Husain":85, "Chirag":94 ,"Asim":70,"Ankit":65 ,"Saiteja":65 ,"Absar":75 ,"Premraj":70 ,"Sagar":75 ,"Himani":75 ,"Parth":76 ,"Sume…
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/89783019
possible better answer: http://stackoverflow.com/a/51406596

http://stackoverflow.com/a/51436372
upvote count: 6
has comment: http://stackoverflow.com/comment/89867106
has comment: http://stackoverflow.com/comment/89846053
score: 6
answers question: http://stackoverflow.com/q/51367567
has body: Code below creates an interactive plot in plotly and Dash. It takes two inputs: slider and text box. When the code below saved as a '.py' and the file is run in terminal, it should run a local server in the terminal. Next, copy the * Running on http:// address from this server and paste it in browser to open the plot. Most likely it would be http://127.0.0.1:8050/. Resources: 1, 2, 3 . (Python 3.6.6) Important: Please note that for the slider to work, the text box value has to be reset to '0' (zero). Import libraries import numpy as np import pandas as pd from plotly import __version__ import plotly.offline as pyo import plotly.graph_objs as go import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output Create Dash app app = dash.Dash() app.layout = html.Div( html.Div([ html.Div([html.H5("Level"), dcc.Slider(id='slider_input', min=0, max=1, step=0.005, value=0.1, )],style={'width': '200'} ), html.Div(style={'height': '10'}), html.Div(dcc.Input( id='text_input', placeholder='Enter a value...', type='text', value=0.0 ),style={'width': '50'}), dcc.Graph(id='example', figure={'data':[{'x':[1,2], 'y':[0,1], 'type':'bar', 'marker':dict(color='#ffbf00') }], 'layout': go.Layout(title='Plot', #xaxis = list(range = c(2, 5)), yaxis=dict(range=[0, 1]) ) }) ], style={'width':'500', 'height':'200','display':'inline-block'}) ) # callback - 1 (from slider) @app.callback(Output('example', 'figure'), [Input('slider_input', 'value'), Input('text_input', 'value')]) def update_plot(slider_input, text_input): if (float(text_input)==0.0): q = float(slider_input) else: q = float(text_input) figure = {'data': [go.Bar(x=[1,2], y=[q, 1-q], marker=dict(color='#ffbf00'), width=0.5 )], 'layout': go.Layout(title='plot', #xaxis = list(range = c(2, 5)), yaxis=dict(range=[0, 1]) ) } return figure Run server if __name__ == '__main__': app.run_server() Output Edit - 1 ............................. Plot with slider only The code below u…
downvote count: 0
type: Answer

http://stackoverflow.com/q/51343097
tagged with: python
tagged with: list
has answer: http://stackoverflow.com/a/51343164
has answer: http://stackoverflow.com/a/51344403
type: Question
upvote count: 2
downvote count: 2
has title: What's the difference between [] and list
has comment: http://stackoverflow.com/comment/89659600
score: 0
has body: &gt;&gt;&gt;list(123) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'int' object is not iterable &gt;&gt;&gt;[123] [123] why the list(123) results to an Exception while the [] works ??
answer count: 4
has answer: http://stackoverflow.com/a/51343159
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89659583
has answer: http://stackoverflow.com/a/51343219

http://stackoverflow.com/a/51413702
type: Answer
has comment: http://stackoverflow.com/comment/89835604
score: 7
upvote count: 7
has body: EDIT: Cris Luengo is right. Ignore the part about edge detector. Laplacian of Gaussian(LoG) can be used as both edge detector and blob detector. I will skip the detailed mathematics and rationale, I think you can read them on a book or some websites here, here and here. To see why it can be used as both, let's look at its plot and kernel. If you have a blob with radius of 3 and value 1 centered at the kernel, and the background has value 0, you will have a very strong (negative) response. It is clear why it can do blob detection if the radius is set properly. How about edge detection? Well it is not like Sobel operator which gives you gradient and strong response for edges. Sobel operator does not give you accurate edges as the gradient usually rise and fall across a few pixels. Your edge would then be several pixels wide. To make it localize more accurate, we can find the pixel with maximum (or minimum) gradient locally. This implies its second derivative (Laplacian) should equal zero, or has a zero-crossing at that point. You can see the processed image has both a light and dark band. The zero-crossing is the edge. To see this with a kernel, try sliding a perfect step edge across the kernel manually to see how the respond changes. For you second question, I guess the absolute is trying to find both light and dark blob (light blob, dark background; dark blob, light background) as they gives strong negative and strong positive response respectively. It then find the max across all images at each pixel location. For each output pixel, it uses the pixel at the image with the maximum response as output. I think his rationale is that pixels with strong impulse (small blob) are in-focus. He is using bitwise_not as a copy mechanism. It sets some pixels, specified by the mask, to the bitwise not of the source image. At the end, you would have output consisting of pixels from different sources, except that all of them have undergone bitwise not. To recover the true image, s…
has comment: http://stackoverflow.com/comment/89866619
answers question: http://stackoverflow.com/q/51411156
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89828212
accepted answer of: http://stackoverflow.com/q/51411156

http://stackoverflow.com/q/51394864
has answer: http://stackoverflow.com/a/51395049
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89761178
has body: I am making a jquery ajax POST request and passing the data to backend python code in Django framework. I need to return the zip file as httpresponse which should be automatically downloaded in browser. object_body = request.body.decode('utf-8') loaded_json = json.loads(object_body) json_obj = ast.literal_eval(str(loaded_json)) zip_file_path = importexport.download(json_obj,user) zip_filename = os.path.basename(zip_file_path) with open(zip_file_path, 'rb') as zip: response = HttpResponse(zip.read(), content_type = 'application/x-zip') response['Content-Disposition'] = 'attachment; filename=' + zip_filename return response
tagged with: python
has answer: http://stackoverflow.com/a/51395013
has comment: http://stackoverflow.com/comment/89760994
linked to: http://stackoverflow.com/q/12881294
tagged with: django
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89765882
has comment: http://stackoverflow.com/comment/89761200
has comment: http://stackoverflow.com/comment/89765797
score: 0
answer count: 2
favorite count: 0
has title: How to send zip file in httpresponse attachment in python

http://stackoverflow.com/comment/89735200
type: Comment
type: QuestionComment
has text: Any delimiters?
score: 0
comment on: http://stackoverflow.com/q/51381550

http://stackoverflow.com/comment/89807251
score: 0
has text: e3 = e1.get()+ " key="+e2.get()
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51417901

http://stackoverflow.com/comment/89878345
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51454363
has text: It would help if you included directory listings for the files and directories that you're running this script on, as well as the actual arguments.
type: Comment

http://stackoverflow.com/a/51464759
type: Answer
has body: It's not a standard function, so it is hard to tell what it is expected to do. The most common implementation seems to be part of the Pyramid framework, and you could import it with: from pyramid.scripts.common import parse_vars But it is hard to tell whether it will do what you need.
score: 0
answers question: http://stackoverflow.com/q/51464681

http://stackoverflow.com/q/51393049
has comment: http://stackoverflow.com/comment/89807422
has body: I want to convert county state name to coordinates. county: fips state_fips county_fips state county 1000 1 0 Alabama Alabama 1005 1 5 Alabama Barbour County 1007 1 7 Alabama Bibb County 1009 1 9 Alabama Blount County 1011 1 11 Alabama Bullock County 6085 6 85 California Santa Clara County 6089 6 89 California Shasta County 6091 6 91 California Sierra County 32021 32 21 Nevada Mineral County 32023 32 23 Nevada Nye County 32027 32 27 Nevada Pershing County 32029 32 29 Nevada Storey County I want to use python geopy package. from geopy.geocoders import Nominatim import pandas as pd import numpy as np geolocator = Nominatim() county['coord'] = county['county'].apply(geolocator.geocode) I got the error: socket.timeout: timed out During handling of the above exception, another exception occurred: urllib.error.URLError: &lt;urlopen error timed out&gt; During handling of the above exception, another exception occurred: geopy.exc.GeocoderTimedOut: Service timed out How should I fix it? thanks
type: Question
tagged with: geopy
has answer: http://stackoverflow.com/a/78207173
has comment: http://stackoverflow.com/comment/89758413
has comment: http://stackoverflow.com/comment/89758387
has comment: http://stackoverflow.com/comment/89765015
score: 0
linked to: http://stackoverflow.com/q/38031705
answer count: 2
has comment: http://stackoverflow.com/comment/89758131
has comment: http://stackoverflow.com/comment/89758237
has comment: http://stackoverflow.com/comment/89807246
has title: convert county state names to coordinates
has comment: http://stackoverflow.com/comment/89845721
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89758292
has comment: http://stackoverflow.com/comment/89758305
has comment: http://stackoverflow.com/comment/89758200
has answer: http://stackoverflow.com/a/51454898

http://stackoverflow.com/a/51346823
type: Answer
answers question: http://stackoverflow.com/q/51338079
accepted answer of: http://stackoverflow.com/q/51338079
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89667536
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89685004
has body: I just rearranged your code a bit, moved the mouse press event in the window class. The label starts as None, and when the left mouse button is pressed, the label will become a Label object. In the draw method added a simple if check, so that the label is only drawn when it is not None. And it works now. import pyglet from pyglet.gl import * from pyglet.window import mouse class Drainage_Window(pyglet.window.Window): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.set_minimum_size(300, 300) self.label = None def on_mouse_press(self, x, y, button, modifiers): if button == mouse.LEFT: self.label = pyglet.text.Label('Click!', font_name='Times New Roman', font_size=16, x=x, y=y, anchor_x='center', anchor_y='center') def on_draw(self): self.clear() if self.label: self.label.draw() if __name__ == '__main__': window = Drainage_Window(width=1920 // 4, height=1080//4, caption="Drainage Network", resizable=True) glClearColor(0.7, 0.7, 1, 1) pyglet.app.run()
has comment: http://stackoverflow.com/comment/89676929

http://stackoverflow.com/comment/89854167
comment on: http://stackoverflow.com/q/51442148
type: Comment
type: QuestionComment
score: 2
has text: You find out what packages the applications use and reinstall them. In the future, use Python virtual environments.

http://stackoverflow.com/a/56867370
upvote count: 9
type: Answer
answers question: http://stackoverflow.com/q/51433227
downvote count: 0
has body: I had the same problem. It looks like for me, my notebook in Jupyter Lab was running the base kernel and not the kernel of the virtual environment. Type import sys sys.executable into your notebook. For me, I got the result '/anaconda3/bin/python' instead of the desired '/anaconda3/envs/myenv/bin/python' I solved it by following the instructions in the iPython documentation. In summary, you need to install a new iPython kernel for your new environment. Run: conda install -n myenv ipython conda activate myenv python -m ipykernel install --user --name myenv --display-name "Python (myenv)" Then, to run Jupyter Lab in the new environment: conda activate myenv jupyter lab And you should be able to select the kernel "Python (myenv)" when you open a new notebook (also in the top right of an existing notebook).
score: 9

countvectorizer
type: Tag
tags question: http://stackoverflow.com/q/51353593
tag name: countvectorizer
tags question: http://stackoverflow.com/q/51430484

http://stackoverflow.com/a/51386209
has comment: http://stackoverflow.com/comment/89777258
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/126708547
downvote count: 0
answers question: http://stackoverflow.com/q/51380692
has body: Jeru's answer already gives you what you want. But I wanted to add an alternative that is maybe a bit more general than what you have so far. You are converting the color image to gray-value, then apply adaptive threshold in an attempt to find lines. You filter this to get only the long horizontal and vertical lines, then use that mask to paint the original image white at those locations. Here we look for all lines, and remove them from the image making painting them with whatever the surrounding color is. This process does not involve thresholding at all, all morphological operations are applied to the channels of the color image. Ideally we'd use color morphology, but implementations of that are rare. Mathematical morphology is based on maximum and minimum operations, and the maximum or minimum of a color triplet (i.e. a vector) is not well defined. So instead we apply the following procedure to each of the three color channels independently. This should produce results that are good enough for this application: Extract the red channel: take the input RGB image, and extract the first channel. This is a gray-value image. We'll call this image channel. Apply a top-hat filter to detect the thin structures: the difference between a closing with a small structuring element (SE) applied to channel, and channel (a closing is a dilation followed by an erosion with the same SE, you're using this to find lines as well). We'll call this output thin. thin = closing(channel)-channel. This step is similar to your local thresholding, but no actual threshold is applied. The resulting intensities indicate how dark the lines are w.r.t. to background. If you add thin to channel, you'll fill in these thin structures. The size of the SE here determines what is considered "thin". Filter out the short lines, to keep only the long ones: apply an opening with a long horizontal SE to thin, and an opening with a long vertical SE to thin, and take the maximum of the two result. We'll call th…
has comment: http://stackoverflow.com/comment/89792308
type: Answer

http://stackoverflow.com/comment/89645180
score: 2
has text: Please read [How to Answer](https://stackoverflow.com/help/how-to-answer). Your solution doesn't address the OP problem, that is, exceeding the recursion limit. The code you have provide is not valid Python code.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51334978

http://stackoverflow.com/q/51470373
has comment: http://stackoverflow.com/comment/99223356
type: Question
tagged with: canopy
has answer: http://stackoverflow.com/a/51885467
upvote count: 9
has comment: http://stackoverflow.com/comment/89909600
has comment: http://stackoverflow.com/comment/89909093
has comment: http://stackoverflow.com/comment/89909109
has title: dateutil 2.5.0 is the minimum required version
has answer: http://stackoverflow.com/a/55159160
tagged with: pandas
has comment: http://stackoverflow.com/comment/89909042
favorite count: 0
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/89909669
has comment: http://stackoverflow.com/comment/89909642
has answer: http://stackoverflow.com/a/64066254
answer count: 5
type: UnansweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/52767855
tagged with: python
has body: I'm running the jupyter notebook (Enthought Canopy python distribution 2.7) on Mac OSX (v 10.13.6). When I try to import pandas (import pandas as pd), I am getting the complaint: ImportError: dateutil 2.5.0 is the minimum required version. I have these package versions: Canopy version 2.1.3.3542 (64 bit) jupyter version 1.0.0-25 pandas version 0.23.1-1 python_dateutil version 2.6.0-1 I'm not getting this complaint when I run with the Canopy Editor so it must be some jupyter compatibility problem. Does anyone have a solution on how to fix this? All was well a few months ago until I recently (and mindlessly) allowed an update of my packages.
has comment: http://stackoverflow.com/comment/89909260
has answer: http://stackoverflow.com/a/51471337
has comment: http://stackoverflow.com/comment/89910370
score: 7
tagged with: python-dateutil
has comment: http://stackoverflow.com/comment/89909215

http://stackoverflow.com/a/51393541
answers question: http://stackoverflow.com/q/51393437
type: Answer
has body: import os all_list = os.listdir('.') numbers = list( map(lambda x: int(x[6:]), filter(lambda x: os.path.isdir(x) and x.startswith("ABCDE_"), all_list)) ) # python3 print(numbers) # python2 print numbers
score: 0

http://stackoverflow.com/comment/89716129
type: AnswerComment
has text: this is the code link https://github.com/asross/cs265/blob/master/simulations/run1.py
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51372084

http://stackoverflow.com/q/51428027
has answer: http://stackoverflow.com/a/51428166
linked to: http://stackoverflow.com/q/15456158
tagged with: python-3.x
has body: When i try to run below program i get error message in the second loop saying second func got multiple values, i expect this program runs in a loop. my assumption is Kwargs Rude is not getting updated again with the same value. Qus1: is kwargs.update(animal = "Lion") is right approch to modify value? Ques2: why i am getting error message? This below code is just for Learning purpose, No other intention. any help is appreciated. I use Python 3.6 Error Message Below Second_Func(variable1,**kwargs,Rude="leone") TypeError: Second_Func() got multiple values for keyword argument 'Rude' NiceVar = "Buddy" def First_Func(variable1,**kwargs): for name,value in kwargs.items(): print("First man",name) kwargs.update(animal = "Lion") Second_Func(variable1,**kwargs,Rude="leone") def Second_Func(value1,**kwargs): for name,value in kwargs.items(): print("Second man",value) Third_Func(value1,**kwargs,band="martin") def Third_Func(google,**kwargs): for name,value in kwargs.items(): print("Third man",value) print("my Third Function",google) First_Func(google,**kwargs) First_Func(NiceVar,Animal ="man")
tagged with: python
type: AnsweredQuestion
score: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/51428166
type: Question
possible better answer: http://stackoverflow.com/a/51428193
has answer: http://stackoverflow.com/a/51428193
answer count: 2
downvote count: 0
has title: Python **kwargs modification in loop
favorite count: 0

http://stackoverflow.com/q/51465203
has answer: http://stackoverflow.com/a/51465342
type: AnsweredQuestion
has title: Live graph with ultrasonic sensor on arduino and matplotlib pyqt to show graph
tagged with: matplotlib
tagged with: pyqt5
type: Question
has body: I stuck on my code. I want to have GUI on PyQt5 to show my graph. I have working code in matplot, but I cannot transform it to PyQT. I'm a beginner at this. I tried to find working similar code but I only did this. This works on matplotlib, but i want to have it on my GUI. import serial import numpy import matplotlib.pyplot as plt from drawnow import * distance =[] arduinoData=serial.Serial('COM4',115200) plt.ion() cnt=0 def makeFig(): plt.ylim(2,20) plt.title('Plot ') plt.grid(True) plt.ylabel('Distance cm') plt.plot(distance, 'ro-', label='Distance ') plt.legend(loc='upper left') while True: # While loop that loops forever while (arduinoData.inWaiting()==0): #Wait here until there is data pass #do nothing arduinoString = arduinoData.readline() #read the line of text from the serial port measurement = int(arduinoString) #Convert first element to floating number and put in measurement distance.append(measurement) #Build our distance array by appending temp readings drawnow(makeFig) #Call drawnow to update our live graph plt.pause(.000001) #Pause Briefly. Important to keep drawnow from crashing cnt=cnt+1 if(cnt&gt;50): #If you have 50 or more points, delete the first one from the array distance.pop(0) #This allows us to just see the last 50 data points #This allows us to just see the last 50 data points My PyQt and Matplot. I want to click on the button and show this graph. I got error that " in line 51, in plot measurement=int(arduinoString) ValueError: invalid literal for int() with base 10: b'\n' " and "Backend TkAgg is interactive backend. Turning interactive mode on." I'm sending data that are simple distance like 5, 10 and so on from my sensor. import sys 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 import random import serial impor…
accepted answer: http://stackoverflow.com/a/51465342
score: 0
answer count: 1
tagged with: arduino
tagged with: python

http://stackoverflow.com/q/51414920
type: UnansweredQuestion
tagged with: code-generation
has answer: http://stackoverflow.com/a/51418004
has comment: http://stackoverflow.com/comment/89801119
has title: Write JSON for corresponding XML
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/89801894
type: Question
tagged with: xml-parsing
answer count: 1
score: 0
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
has body: I want to write JSON code which can be converted in fix format kind of XML foo uint32_t count uint32_t I have tried multiple ways to develop a JSON which can be formatted like as in above but failed to get perfection because no separate key is required for foo and count which are orphan values otherwise. Tried ways: Way 1: { "function" : {"foo": {"return":"uint32_t"}, "param": {"count": {"type":"uint32_t"} } } } Way 2: { "function" : ["foo",{"return":"uint32_t"}], "param": ["count",{"type":"uint32_t"}] } Way 3: But i do not need name tag :( { "function": {"name": "foo", "return": "uint32_t", "param": "count", "type": "uint32_t" } } For generating output and testing please use: JSON to XML convertor Requesting your help.. I later have a script to convert the formatted excel to C header files.
has comment: http://stackoverflow.com/comment/89801024

http://stackoverflow.com/comment/89902265
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51414757
has text: You could try this: `join -1 2 -2 1 <(sed -e 's/\t/ /g' sample1.txt | sort -k 1) <(sort -k 1 sample2.txt)`. It did'nt work because you need to specify, in this case, columns to join.

http://stackoverflow.com/a/51374881
score: 2
has comment: http://stackoverflow.com/comment/89721444
accepted answer of: http://stackoverflow.com/q/51374862
has body: Convert boolean mask to integer: #for better performance convert to numpy array df['Map'] = (df['Amount'].values &gt;= 3).astype(int) #pure pandas solution df['Map'] = (df['Amount'] &gt;= 3).astype(int) print (df) Id Amount Map 0 1 6 1 1 2 2 0 2 3 0 0 3 4 6 1 Performance: #[400000 rows x 3 columns] df = pd.concat([df] * 100000, ignore_index=True) In [133]: %timeit df['Map'] = (df['Amount'].values &gt;= 3).astype(int) 2.44 ms ± 97.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [134]: %timeit df['Map'] = (df['Amount'] &gt;= 3).astype(int) 2.6 ms ± 66.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
downvote count: 0
answers question: http://stackoverflow.com/q/51374862
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89721412
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/89721163

http://stackoverflow.com/q/51332986
accepted answer: http://stackoverflow.com/a/51333294
tagged with: python
possible better answer: http://stackoverflow.com/a/51333887
has body: I've created this code that updates a label every second to indicate that something is loading (run the code to see what I mean). I'm using the threading module with tkinter but I feel like there must be a more efficient way to do this. Here is my code: from tkinter import * from time import sleep import threading root = Tk() new_var = StringVar() new_var.set('Loading') def change_text(): array = [".", "..", "...", ""] while True: for num in range(4): sleep(1) new_var.set(f"Loading{array[num]}") root.update_idletasks() l = Label(root, textvariable = new_var) l.pack() Loading_animation = threading.Thread(target=change_text) Loading_animation.start() root.mainloop() Also, if there isn't a better way to do this how do I prevent the error that I keep receiving whenever I close the root window? Thank you!
tagged with: tkinter
tagged with: multithreading
has answer: http://stackoverflow.com/a/51333294
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/89641493
score: 0
answer count: 2
has title: How to update labels in tkinter dynamically?
upvote count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51333887

http://stackoverflow.com/a/51392934
accepted answer of: http://stackoverflow.com/q/51392889
type: Answer
answers question: http://stackoverflow.com/q/51392889
has comment: http://stackoverflow.com/comment/137965752
has body: Since input() is an interactive function, you'll want to mock out the return value in your automated tests. Something like this: def test_prompt(capsys, monkeypatch): monkeypatch.setattr('path.to.yourmodule.input', lambda prompt="", /: "no") val = prompt_to_activate(bear=..., printer=...) assert not val
score: 12
upvote count: 12
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51450293
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/89871472
answer count: 2
has comment: http://stackoverflow.com/comment/89871035
linked to: http://stackoverflow.com/q/2564140
has comment: http://stackoverflow.com/comment/89872296
favorite count: 0
has body: So I have a class with the following method: def Add(self,new_name): self.new_name=.... I want to add an attribute with the title "new_name" that will be passed from somewhere else. Obviously, in the above program I simply created an attribute with the string "new_name" instead of the actual argument input. How should I go about making sure the attribute's name is the actual parameter? I believe in C++ it's easy to use c_str() here, but with Python I'm not sure. ex. Add('hello') should create a new attribute self.hello which I can then store with information. Thank you. EDIT: Ok I see I should use setattr() now. However, I seem to not be getting the expected results. Is this how I would use it where the initialization is a list comprehension? I tried the two ways and neither worked as shown below: def Add(self,new_name): #also doesn't work setattr(self, new_name,[API(self.var1,str(new_name),i) for i in range(self._NumRows)]) def Add(self,new_name): #also doesn't work setattr(self, new_name,[]) self.new_name=[API(self.var1,str(new_name),i) for i in range(self._NumRows)]) where API takes 3 arguments (I know this isn't the problem because this works fine as long as I don't use setattr() and the name is already known so it's nothing with the API. EDIT: For those suggesting dictionary, I'm not storing data with these attributes. I'm creating a method which creates a new attribute for users who are creating derived classes of my base class. It's to abstract away the creation of additional attributes because I was told my code would likely be adopted in the future when I leave (I'm an intern) and to make it as easy as possible to create derived classes. EDIT: Nevermind, I mislabeled a variable. It works! Thank you.
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89871171
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89871356
has comment: http://stackoverflow.com/comment/89871162
tagged with: python
has comment: http://stackoverflow.com/comment/89871202
has comment: http://stackoverflow.com/comment/89871761
tagged with: oop
score: 1
upvote count: 1
has title: In python, how do you create a new variable with a name unspecified until runtime (Edit: How do you use setattr() with a list compehension)?
has comment: http://stackoverflow.com/comment/89871430
type: Question
tagged with: object
has comment: http://stackoverflow.com/comment/89871545
downvote count: 0
has comment: http://stackoverflow.com/comment/89871301
has answer: http://stackoverflow.com/a/51450439
has answer: http://stackoverflow.com/a/51450421
has comment: http://stackoverflow.com/comment/89871247

http://stackoverflow.com/a/51383433
has comment: http://stackoverflow.com/comment/89739182
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51383095
score: 3
answers question: http://stackoverflow.com/q/51383095
type: AcceptedAnswer
downvote count: 0
has body: You need a format like - [(411, 113), (158, 169), (344, 364)] But you are passing tuple of tuple- ((411, 113),), ((158, 169),), ((344, 364),)] Try this structure - [(432, 224), (196, 245), (268, 379)] Or a straight list is also fine - [432, 224, 196, 245, 268, 379] Look at the documentation here Tuple of tuple becomes one argument for the function when it's expecting two. You don't need to zip(poly), just passing numberofPoint should work. Let me know if that helps
type: Answer
has comment: http://stackoverflow.com/comment/89738937

http://stackoverflow.com/q/51384890
tagged with: http://stackoverflow.com/tag/json
downvote count: 3
has comment: http://stackoverflow.com/comment/89742062
type: Question
has title: Python - Search and export information from JSON
has answer: http://stackoverflow.com/a/51385343
has body: This is the structure of my json file }, "client1": { "description": "blabla", "contact name": "", "contact email": "", "third party organisation": "", "third party contact name": "", "third party contact email": "", "ranges": [ "1.1.1.1", "2.2.2.2", "3.3.3.3" ] }, "client2": { "description": "blabla", "contact name": "", "contact email": "", "third party organisation": "", "third party contact name": "", "third party contact email": "", "ranges": [ "4.4.4.4", "2.2.2.2" ] }, I've seen ways to export specific parts of this json file but not everything. Basically all I want to do is search through the file using user input. All I'm struggling with is how I actually use the user input to search and print everything under either client1 or client2 based on the input? I am sure this is only 1 or 2 lines of code but cannot figure it out. New to python. This is my code data = json.load(open('clients.json')) def client(): searchq = input('Client to export: '.capitalize()) search = ('""'+searchq+'"') a = open('Log.json', 'a+') a.write('Client: \n') client()
has answer: http://stackoverflow.com/a/51385406
answer count: 3
has comment: http://stackoverflow.com/comment/89741776
favorite count: 0
type: UnansweredQuestion
score: -3
has answer: http://stackoverflow.com/a/51385479
tagged with: python
upvote count: 0
has comment: http://stackoverflow.com/comment/89742477
has comment: http://stackoverflow.com/comment/89742176

http://stackoverflow.com/q/51347800
has title: How to pass an entire column as a parameter to tldextract function?
upvote count: 5
downvote count: 0
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/51347816
tagged with: pandas
has body: tldextract is used to extract domain names from the URLs. Here, 'url' is one of the column name in the data frame 'df'. It is possible to pass one value of 'url' as a parameter. However, I am not able to pass the entire column as a parameter. The url being passed here is 'https://www.google.com/search?source=hp&amp;ei=7iE' listed = tldextract.extract(df['url'][0]) dom_name = listed.domain print(dom_name) Output: google What I want is to create a new column in the data frame named 'Domain' having the extracted domain names from the URL. Something like: df['Domain'] = tldextract.extract(df['url']) But this isn't working Here is the code: # IMPORTING PANDAS import pandas as pd from IPython.display import display import tldextract # Read data sample df = pd.read_csv("bookcsv.csv") df['Domain'] = df['url'].apply(lambda url: tldextract.extract(url).domain) Here is the input data: The dataframe looks like this I am not able to put the data directly here. So, I am posting a snapshot.
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/78903621
has answer: http://stackoverflow.com/a/78903621
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51347816
type: Question
answer count: 2
score: 5

http://stackoverflow.com/a/51473485
has comment: http://stackoverflow.com/comment/89916066
score: 1
answers question: http://stackoverflow.com/q/51473273
upvote count: 1
has comment: http://stackoverflow.com/comment/89915307
downvote count: 0
has comment: http://stackoverflow.com/comment/89915550
type: Answer
has body: You replace the whole string because .* matches any character zero or more times. If your special values are always at the end of the string you might use: .str.replace(r'@$', "Can be improve") .str.replace(r'\*$', "Very Poor")
has comment: http://stackoverflow.com/comment/89915469

http://stackoverflow.com/comment/90185948
comment on: http://stackoverflow.com/a/51505603
score: 0
type: AnswerComment
has text: I'm glad to hear! Thanks.
type: Comment

http://stackoverflow.com/comment/89834253
score: 2
has text: Haha creative ;)
type: AnswerComment
comment on: http://stackoverflow.com/a/51431646
type: Comment

http://stackoverflow.com/comment/89805365
comment on: http://stackoverflow.com/q/51417126
score: 0
has text: You could pickle the output from the first stage and then provide a command-line parameter to say "load the output from the first stage". https://docs.python.org/2/library/pickle.html
type: Comment
type: QuestionComment

pyqt5
tags question: http://stackoverflow.com/q/51430586
tags question: http://stackoverflow.com/q/51338059
type: Tag
tags question: http://stackoverflow.com/q/51372928
tags question: http://stackoverflow.com/q/51355762
tags question: http://stackoverflow.com/q/51459736
tags question: http://stackoverflow.com/q/51465203
tags question: http://stackoverflow.com/q/51459982
tags question: http://stackoverflow.com/q/51392167
tags question: http://stackoverflow.com/q/51331387
tags question: http://stackoverflow.com/q/51326839
tags question: http://stackoverflow.com/q/51344147
tags question: http://stackoverflow.com/q/51333771
tags question: http://stackoverflow.com/q/51425354
tags question: http://stackoverflow.com/q/51329489
tags question: http://stackoverflow.com/q/51364552
tags question: http://stackoverflow.com/q/51357642
tags question: http://stackoverflow.com/q/51353162
tags question: http://stackoverflow.com/q/51338580
tags question: http://stackoverflow.com/q/51360031
tags question: http://stackoverflow.com/q/51369081
tags question: http://stackoverflow.com/q/51442487
tags question: http://stackoverflow.com/q/51459331
tags question: http://stackoverflow.com/q/51349538
tags question: http://stackoverflow.com/q/51343544
tags question: http://stackoverflow.com/q/51335526
tags question: http://stackoverflow.com/q/51332260
tags question: http://stackoverflow.com/q/51404102
tags question: http://stackoverflow.com/q/51343109
tags question: http://stackoverflow.com/q/51409228
tags question: http://stackoverflow.com/q/51465953
tags question: http://stackoverflow.com/q/51392915
tags question: http://stackoverflow.com/q/51464962
tags question: http://stackoverflow.com/q/51336612
tags question: http://stackoverflow.com/q/51346961
tags question: http://stackoverflow.com/q/51419048
tags question: http://stackoverflow.com/q/51345105
tags question: http://stackoverflow.com/q/51433403
tags question: http://stackoverflow.com/q/51455765
tags question: http://stackoverflow.com/q/51452668
tags question: http://stackoverflow.com/q/51442769
tags question: http://stackoverflow.com/q/51379323
tags question: http://stackoverflow.com/q/51408490
tags question: http://stackoverflow.com/q/51330113
tags question: http://stackoverflow.com/q/51359162
tags question: http://stackoverflow.com/q/51420099
tags question: http://stackoverflow.com/q/51361674
tags question: http://stackoverflow.com/q/51428867
tags question: http://stackoverflow.com/q/51371421
tags question: http://stackoverflow.com/q/51456403
tags question: http://stackoverflow.com/q/51341158
tags question: http://stackoverflow.com/q/51443461
tags question: http://stackoverflow.com/q/51464209
tags question: http://stackoverflow.com/q/51326230
tag name: pyqt5
tags question: http://stackoverflow.com/q/51413254
tags question: http://stackoverflow.com/q/51442896
tags question: http://stackoverflow.com/q/51388443
tags question: http://stackoverflow.com/q/51405824
tags question: http://stackoverflow.com/q/51443198
tags question: http://stackoverflow.com/q/51371660
tags question: http://stackoverflow.com/q/51334861
tags question: http://stackoverflow.com/q/51328745
tags question: http://stackoverflow.com/q/51324754
tags question: http://stackoverflow.com/q/51413170
tags question: http://stackoverflow.com/q/51396555
tags question: http://stackoverflow.com/q/51475306
tags question: http://stackoverflow.com/q/51378442

http://stackoverflow.com/q/51330796
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: php
has body: I want to build a very simple web page running LOCALLY on my computer, displaying results from a Python script. I have tried using HTML and PHP but without any luck. Please bear in mind that I'm a complete newbie in web development. Let's say I want to very simply print some text on the web page. This is what "helloworld.py" looks like: print("hello world") This is what helloworld.html looks like: &lt;html&gt; &lt;body&gt; &lt;?php $message = exec('helloworld.py'); print_r($message);?&gt; &lt;/body&gt; &lt;/html&gt; However, when I open the HTML file in the browser I just get an empty screen. Can someone tell me how to do this?
type: Question
has title: Show result of Python script in basic HTML page running locally
score: 0
linked to: http://stackoverflow.com/q/1678010
answer count: 1
has answer: http://stackoverflow.com/a/51331005
type: UnansweredQuestion

http://stackoverflow.com/comment/89751752
has text: Well, `dtype=object` will blunt the advantages of vectorization significantly. It removes the locality of reference which is probably the major source of speed improvements. However, the looping is pushed down into the C-level, so it should be faster, but not the 50x or 100x (or more) speed ups you'd expect with primitive numerical types.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51389408
type: Comment

http://stackoverflow.com/q/51396547
has comment: http://stackoverflow.com/comment/89764525
possible better answer: http://stackoverflow.com/a/51396864
answer count: 3
has answer: http://stackoverflow.com/a/51396864
favorite count: 0
tagged with: python-3.x
score: 2
tagged with: nested-lists
upvote count: 2
accepted answer: http://stackoverflow.com/a/51396798
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
type: Question
has body: So i have a list with nested dictionaries inside them and what i want to do is read the values of views from the dictionaries and put them through a multiplier. video_ads=({'title': 'Healthy Living', 'company': 'Health Promotion Board','views': 15934}, {'title': 'Get a ride, anytime anywhere', 'company': 'Uber', 'views': 923834}, {'title': 'Send money with GrabPay', 'company': 'Grab', 'views': 23466}, {'title': 'Ubereats now delivers nationwide', 'company': 'Uber', 'views': 1337}, {'title': 'Get cabs now with UberFlash', 'company': 'Uber', 'views': 90234}) so what i am trying to do is get the title together with the views mulitiplied by a certain factor, this is what i've written so far def payment_for_views(x): for x in range(0,5): x = x+1 if video_ads[x]['views'] &gt;= 50000: payment = video_ads[x]['views']*0.55 elif views &lt;50000 and video_ads[x]['views'] &gt;=10000: payment=video_ads[x]['views']*0.68 else: payment = video_ads[x]['views']*0.82 #print(x) print(video_ads[x]['title'] + ': $'+ str(payment)) print(video_ads[x]['title'] + ': $'+ str(payment)) print(video_ads[x]['title'] + ': $'+ str(payment)) print(video_ads[x]['title'] + ': $'+ str(payment)) print(video_ads[x]['title'] + ': $'+ str(payment)) But it seems to be printing only one line for example: Get cabs now with UberFlash: $49628.700000000004 Get cabs now with UberFlash: $49628.700000000004 Get cabs now with UberFlash: $49628.700000000004 Get cabs now with UberFlash: $49628.700000000004 Get cabs now with UberFlash: $49628.700000000004 that is all i get. I need 5 lines all of them with the various titles and various amounts. Help!!! and thanks in advance!
has title: How to iterate through a list with nested dictionaries?
tagged with: nested-loops
downvote count: 0
has answer: http://stackoverflow.com/a/51396719
has answer: http://stackoverflow.com/a/51396798

http://stackoverflow.com/q/51418113
answer count: 1
downvote count: 0
tagged with: scikit-learn
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89809090
type: UnansweredQuestion
has body: I have created a weighted graph of k-Neighbors using scikit-learn, I'm wondering if there is any way to plot it as a graph. Here is the result of computation in form of array which I want to plot: array([[0. , 2.08243189, 0. , 3.42661108], [2.08243189, 0. , 3.27141008, 0. ], [0. , 3.27141008, 0. , 1.57294787], [0. , 3.29779083, 1.57294787, 0. ]]) I just need to get some visualization of data, that's all I need. More details about the array: Each row represents a node and each column represents the weight of connectivity of that node with the other nodes. For example: second column of first row (2.08243189) is the weight of connectivity from first node to second node. Another example: second row, second column (0): the weight of connectivity from node 2 to itself. The numbers represents euclidean distance.
tagged with: python
has answer: http://stackoverflow.com/a/51423621
has title: How to plot a weighted graph of k-Neighbors in Python
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89819999
has comment: http://stackoverflow.com/comment/89810561
has comment: http://stackoverflow.com/comment/89853966
type: Question
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/89809693
has comment: http://stackoverflow.com/comment/89808538
has comment: http://stackoverflow.com/comment/89853731

http://stackoverflow.com/a/51340887
has comment: http://stackoverflow.com/comment/89692114
has comment: http://stackoverflow.com/comment/89669739
has comment: http://stackoverflow.com/comment/89670261
downvote count: 0
has body: the extension doesn't tell the contents. Program author used .dat so you cannot open it (easily) with a text editor and see or even change the apparent garbage inside (which is partly ASCII, and partly non-ASCII) which would destroy/corrupt the data. As long as you open the file in binary, any file "type" will work. Opening in text mode can "corrupt" the file in some cases of line-termination conversion (happens a lot on windows) Note that pickle is not the best choice when you're dumping native python structures such as lists and dictionaries. In that case, you're better off with json format, which requires text mode, and has the nice advantage to be readable and even editable as long as you respect the original structures.
answers question: http://stackoverflow.com/q/51340840
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/51432960
tagged with: python
has body: I am making a program where I can count the number of a in a string. This is my Code: def repeatedString(s, n): converged = s*n got_it = converged[0:n] count = 0 for x in got_it: if "a" in x: count += 1 return count s = input() n = int(input()) result = repeatedString(s, n) print(result) The variable s is where the string is entered, and variable n is for upto how long the string will repeat. My Code works OK, but for some reason when I give a bigger integer, it falls apart and gives me a Memory Error. For example, my input is: a 1000000000000 It gives me this error: Traceback (most recent call last): File "programs.py", line 11, in &lt;module&gt; result = repeatedString(s, n) File "programs.py", line 2, in repeatedString converged = s*n MemoryError How can I fix this Memory Error? If there's a better way to do it, it would also be helpful.
answer count: 4
has comment: http://stackoverflow.com/comment/89836742
has answer: http://stackoverflow.com/a/51433091
has answer: http://stackoverflow.com/a/51433215
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89836746
has answer: http://stackoverflow.com/a/58937037
tagged with: memory
type: Question
has title: Why is my code giving memory error?
has comment: http://stackoverflow.com/comment/89836717
upvote count: 2
possible better answer: http://stackoverflow.com/a/51433091
score: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/89836840
tagged with: string
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51433215
has answer: http://stackoverflow.com/a/51433427

http://stackoverflow.com/q/51403126
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92070059
tagged with: python
score: 13
has comment: http://stackoverflow.com/comment/89778270
has comment: http://stackoverflow.com/comment/89777523
upvote count: 13
has title: Why is my script's directory not in the Python sys.path?
has comment: http://stackoverflow.com/comment/89777105
has comment: http://stackoverflow.com/comment/89778210
has answer: http://stackoverflow.com/a/52566528
has comment: http://stackoverflow.com/comment/89778336
has comment: http://stackoverflow.com/comment/89779709
has answer: http://stackoverflow.com/a/60067426
linked to: http://stackoverflow.com/q/6416424
has comment: http://stackoverflow.com/comment/89777255
linked to: http://stackoverflow.com/q/38564382
tagged with: import
has comment: http://stackoverflow.com/comment/89778397
has answer: http://stackoverflow.com/a/51403510
type: Question
has comment: http://stackoverflow.com/comment/89778008
tagged with: python-import
has comment: http://stackoverflow.com/comment/89777863
has comment: http://stackoverflow.com/comment/89778101
downvote count: 0
has body: Python 3.6.5 I am aware of this one: Why does my python not add current working directory to the path? But the problem there is that he's doing something more complicated (referring to a sub-folder but executing from a main folder). The answers there are to either simplify things or to add package definitions. And the selected answer even says: "It is the script's directory that is added" However, my problem is really more simple: My script's directory ISN'T added. Basically, all the tutorials on the internet say: import mymodule When I do that, I get a name error... My folder structure: C:/Projects/interner interner.py # this is the main program body aux.py # this is the auxiliary file I would like to import into the above I've tried both coding 'import aux' inside interner.py, and also using the interactive console: cd c:/Projects/interner python import aux To no avail (ModuleNotFoundError: No module named 'aux') My sys.path: ['C:\\Tools\\Python\\python365\\python36.zip', 'C:\\Tools\\Python\\python365'] (both from inside the script and from interactive console) Could you please tell me why I can't import local scripts? Is it because my sys.path is missing the PWD? If so, why is it missing it? Edit: Doing this to help investigation: &gt;&gt;&gt; import os; print(os.listdir(".")) ['aux.py', 'hw.py', 'interner.py', 'my_funcs.py']
has comment: http://stackoverflow.com/comment/89780023
has comment: http://stackoverflow.com/comment/89779225
linked to: http://stackoverflow.com/q/14216200
has answer: http://stackoverflow.com/a/51404896
has comment: http://stackoverflow.com/comment/89779764
answer count: 4
favorite count: 0
tagged with: python-3.x

interactive
tags question: http://stackoverflow.com/q/51348988
type: Tag
tags question: http://stackoverflow.com/q/51341050
tag name: interactive

http://stackoverflow.com/q/51451435
tagged with: python
has answer: http://stackoverflow.com/a/51467212
tagged with: python-install
type: UnansweredQuestion
type: Question
upvote count: 5
has body: I am using Google Colaboratory, which seems to have sk-learn built-in already somehow, because all you have to do to import the TSNE module is from sklearn.manifold import TSNE I have forked a version of sklearn from their github that I am trying to install, but it is failing to install. To isolate the problem I am just trying to install sk-learn directly from Github, and figuring out why it is failing to install. Here is the code I used !pip install https://github.com/scikit-learn/scikit-learn/archive/master.zip Here is the output Collecting https://github.com/Santosh-Gupta/scikit-learn/archive/master.zip Downloading https://github.com/Santosh-Gupta/scikit-learn/archive/master.zip (6.6MB) 100% |████████████████████████████████| 6.6MB 3.8MB/s Requirement already satisfied: numpy&gt;=1.8.2 in /usr/local/lib/python3.6/dist-packages (from scikit-learn==0.20.dev0) (1.14.5) Requirement already satisfied: scipy&gt;=0.13.3 in /usr/local/lib/python3.6/dist-packages (from scikit-learn==0.20.dev0) (0.19.1) Building wheels for collected packages: scikit-learn Running setup.py bdist_wheel for scikit-learn ... error Complete output from command /usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-req-build-j3idof1a/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/pip-wheel-wvc5lddz --python-tag cp36: Partial import of sklearn during the build process. blas_opt_info: blas_mkl_info: customize UnixCCompiler libraries mkl_rt not found in ['/usr/local/lib', '/usr/lib', '/usr/lib/x86_64-linux-gnu'] NOT AVAILABLE blis_info: customize UnixCCompiler libraries blis not found in ['/usr/local/lib', '/usr/lib', '/usr/lib/x86_64-linux-gnu'] NOT AVAILABLE openblas_info: customize UnixCCompiler customize UnixCCompiler libraries openblas not found in ['/usr/local/lib', '/usr/lib', '/usr/lib/x86_64-linux-gnu'] NOT AVAILABLE atlas_3_10_blas_threads_info: Setting PTATLAS=A…
score: 5
has title: Failing to install Sk-learn (scikit-learn) in Google Colab directly from Github
downvote count: 0
answer count: 1
tagged with: scikit-learn
tagged with: github
tagged with: google-colaboratory
favorite count: 0

http://stackoverflow.com/comment/89838549
score: 0
has text: it breaks the loop but exits the script. Im trying to make it go back to the main menu so i can select option 1 again.
comment on: http://stackoverflow.com/q/51433946
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51406467
tagged with: python-3.x
has body: This is not a duplicate of creating a function object from a string because that is a Python 2 solution with exec not as a function() Trying to implement that solution in Python 3 gets this: d = {} exec("def f(x): return x")in d print(d) returns: {} So the question is, how do I create a function in Python 3 from an arbitrary string? (In my case read in from a YAML file, but that's a side issue.)
has comment: http://stackoverflow.com/comment/89784379
has comment: http://stackoverflow.com/comment/89784045
score: 1
upvote count: 1
has title: Creating a Python Object from a String in Python 3
type: Question
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/6098073
has comment: http://stackoverflow.com/comment/89784096
accepted answer: http://stackoverflow.com/a/51406580
has comment: http://stackoverflow.com/comment/89784106
has comment: http://stackoverflow.com/comment/89784140
has comment: http://stackoverflow.com/comment/89784206
answer count: 2
has comment: http://stackoverflow.com/comment/89784128
possible better answer: http://stackoverflow.com/a/51406607
downvote count: 0
has answer: http://stackoverflow.com/a/51406607
favorite count: 0
has comment: http://stackoverflow.com/comment/89784251
has comment: http://stackoverflow.com/comment/89784317
has answer: http://stackoverflow.com/a/51406580
tagged with: python
has comment: http://stackoverflow.com/comment/89784130

http://stackoverflow.com/q/51331050
score: 0
has comment: http://stackoverflow.com/comment/89649534
linked to: http://stackoverflow.com/q/50864254
tagged with: python
linked to: http://stackoverflow.com/q/46630060
tagged with: adafruit
has comment: http://stackoverflow.com/comment/89639070
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89655516
type: Question
tagged with: raspberry-pi
has body: I tried to write a script that would output the dht 11 sensor data to a .txt file. I reviewed the standard examples given for the Adafruit library. My code: import time import Adafruit_DHT # infinite while loop while True: sensor = Adafruit_DHT.DHT11 pin = 4 humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) if humidity is not None and temperature is not None: print('Temp={0:0.1f}* Humidity{1:0.1f}%'.format(temperature,humidity)) else: print('Failed to get reading. Try again!') time.sleep(5) When I run it with Thonny IDE, I get the following error message: Traceback (most recent call last): File "/home/pi/Downloads/Sensor1/Adafruit_Python_DHT/examples/simpletest2loop.py", line 5, in &lt;module&gt; import Adafruit_DHT ImportError: No module named 'Adafruit_DHT' I'm able to read the sensor from terminal using the command: sudo ./AdafruitDHT.py 11 4 with another script listed in: https://tutorials-raspberrypi.com/raspberry-pi-measure-humidity-temperature-dht11-dht22/ I did some research, but I can't figure it out, I kindly ask if someone can help me to troubleshoot this. Research: importing dht11 Adafruit python DHT11 Adafruit Library: Is this parameter necessary? Trouble installing Adafruit&#39;s DHT11 Python library I tried moving the file, but still doesn't work - GPIO Error on Raspberry Pi when following Adafruit Tutorial pi@raspberrypi:~/Downloads/Sensor1/Adafruit_Python_DHT/examples $ ls -altr total 28 -rw-r--r-- 1 pi pi 2035 Jul 5 15:28 simpletest.py -rwxr-xr-x 1 pi pi 5715 Jul 5 15:28 google_spreadsheet.py drwxr-xr-x 10 pi pi 4096 Jul 5 15:28 .. -rwxr-xr-x 1 pi pi 2340 Jul 6 13:19 AdafruitDHT.py drwxr-xr-x 2 pi pi 4096 Jul 13 14:08 . -rwxrwxrwx 1 pi pi 1037 Jul 13 14:19 simpletest2loop.py &lt;code&gt; Seems they are under same user and group. Do i have to copy the library to some folder?
answer count: 1
has answer: http://stackoverflow.com/a/51338594
linked to: http://stackoverflow.com/q/32107770
has title: Troubleshooting Adafruit library issues on raspberry pi
linked to: http://stackoverflow.com/q/35995195

http://stackoverflow.com/q/51449636
has answer: http://stackoverflow.com/a/51449705
tagged with: python
possible better answer: http://stackoverflow.com/a/51450056
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51450056
accepted answer: http://stackoverflow.com/a/51449705
score: 1
upvote count: 3
has comment: http://stackoverflow.com/comment/89872241
has title: Colored output python
type: Question
has comment: http://stackoverflow.com/comment/89873607
answer count: 2
has comment: http://stackoverflow.com/comment/89881023
tagged with: colors
favorite count: 0
tagged with: python-3.x
downvote count: 2
has body: So I found some code that formatted a 2048 Game Board so that it didn't look messy when there was more than 1 digit to a number: nlist = [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 128, 2, 2, 16, 16] widths = [max(len(str(nlist[row * 4 + col])) for row in range(4)) + 2 for col in range(4)] width = sum(widths) + 5 count = 0 for i in range(16): print('|{:^{width}}'.format(nlist[i], width=widths[i % 4]), end = '') count += 1 if count == 4: print("|\n" + '-' * width) count = 0 print("") Run this code to make things more clear and change values of nlist to see how the formatting works. So anyways, after I finished the game, I wanted to add colors to make the game easier to understand in terminal so I edited my code to look like this: clist = nlist.copy() for x in range(16): if clist[x] == 2: clist[x] = ' \033[1;37;106m' + str(clist[x]) + '\033[0m ' if clist[x] == 4: clist[x] = ' \033[1;37;105m' + str(clist[x]) + '\033[0m ' if clist[x] == 8: clist[x] = ' \033[1;37;104m' + str(clist[x]) + '\033[0m ' if clist[x] == 16: clist[x] = ' \033[1;37;106m' + str(clist[x]) + '\033[0m ' if clist[x] == 32: clist[x] = ' \033[1;37;106m' + str(clist[x]) + '\033[0m ' if clist[x] == 64: clist[x] = ' \033[1;37;106m' + str(clist[x]) + '\033[0m ' if clist[x] == 128: clist[x] = ' \033[1;37;106m' + str(clist[x]) + '\033[0m ' if clist[x] == 256: clist[x] = ' \033[1;37;106m' + str(clist[x]) + '\033[0m ' if clist[x] == 512: clist[x] = ' \033[1;37;106m' + str(clist[x]) + '\033[0m ' if clist[x] == 1024: clist[x] = ' \033[1;37;106m' + str(clist[x]) + '\033[0m ' if clist[x] == 2048: clist[x] = ' \033[1;37;106m' + str(clist[x]) + '\033[0m ' if clist[x] == 4096: clist[x] = ' \033[1;37;106m' + str(clist[x]) + '\033[0m ' widths = [max(len(str(nlist[row * 4 + col])) for row in range(4)) + 2 for col in range(4)] width = sum(widths) + 5 count = 0 for i in range(16): print('|{:^{width}}'.format(clist[i], width=widths[i % 4]), end = '') count += 1 if count == 4: print("|\n" + '-' * width) count = 0 B…

http://stackoverflow.com/comment/89887229
comment on: http://stackoverflow.com/a/51458931
type: AnswerComment
has text: But, in this case, float() recognizes.
score: 0
type: Comment

http://stackoverflow.com/q/51329529
has comment: http://stackoverflow.com/comment/89635149
has comment: http://stackoverflow.com/comment/89636273
has title: Read() / Readline() UnicodeDecode Error in same column location over .txt file Directory
has comment: http://stackoverflow.com/comment/89635006
has body: I have a directory of .txt files Each .txt file has the same formatting and I am only interested in a specific column range, of the first line, of each .txt file in the directory. I've attempted using read(150 - 139), where those numbers represent the column range I am interested in, and readline(). The problem encountered with read(150 - 139) is that it outputs the entire .txt file or throws the UnicodeDecodeError. The problem encountered with readline() is that it throws the UnicodeDecodeError. PLEASE NOTE: The column range of each .txt file in the directory are readable characters, ANSI encoding for each file. [Mud, Sample, Resistivity, Neutron, or Gamma]. OBJECTIVE: Append the characters, at the same column range, across all .txt files within the directory to a list --> lst_2 Code: import os #import numpy as np #A string array containing all file names in a directory names = os.listdir('c:\\users\Admin\Documents\Exm_3') lst=[] lst_2=[] for name in names: if name.endswith(".txt"): lst.append(name)# append the names with open(os.path.join('c:\\users\Admin\Documents\Exm_3', name)) as file: c = file.read(150 - 139) lst_2.append(c) print(lst) print(lst_2) Output: ['j.txt', 'n.txt', 'q.txt', 'test.txt', 'y.txt'] ['A2D 3.1.0 C', 'A2D 3.1.0 C', 'A2D 3.1.0 C', ' ', 'A2D 3.1.0 C'] A2D 3.1.0.C represents the range [0 - 10], not [139 - 150]
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89702379
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89635101
type: Question

http://stackoverflow.com/comment/89712970
has text: Try File -> Invalidate cache and restart And see if you still have the issue.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51370035

http://stackoverflow.com/q/51405824
has comment: http://stackoverflow.com/comment/89787215
score: 2
tagged with: python-3.x
downvote count: 0
has answer: http://stackoverflow.com/a/51408197
accepted answer: http://stackoverflow.com/a/51408197
tagged with: pyqt5
type: Question
type: AnsweredQuestion
has title: PyQt5: Check the existance of dynamically created Checkboxes and Refer them
upvote count: 2
tagged with: pyqt
answer count: 1
favorite count: 0
has body: Basic Layout of the Code Here, every time the user clicks on the PushButton 'Press me', a new CheckBox will be generated. from PyQt5 import QtWidgets, QtGui, QtCore count = 1 class Window(QtWidgets.QWidget): def __init__(self, parent=None): super(Window, self).__init__(parent) self.vlayout = QtWidgets.QVBoxLayout() self.pushButton1 = QtWidgets.QPushButton("Press me", self) self.pushButton1.clicked.connect(self.addCheckbox(count)) self.pushButton2 = QtWidgets.QPushButton("OK", self) self.vlayout.addWidget(self.pushButton1) self.vlayout.addWidget(self.pushButton2) self.setLayout(self.vlayout) def addCheckbox(self,count): global count self.vlayout.addWidget(str(count),QtWidgets.QCheckBox()) count = count +1 application = QtWidgets.QApplication(sys.argv) window = Window() window.setWindowTitle('Hello') window.resize(250, 180) window.show() sys.exit(application.exec_()) What I wish to do? Now you will have unique check boxes, each with a different number, I want to add further functionality. Every time the user chooses specific checkboxes, I want to know which checkbox did the user click after he clicks the PushButton OK. Eg: I click on checkbox 1 -> OK -> print 1 on the screen How can I do this? PS: We need to consider the possibility that the user never clicks Press me, so no ckeckboxes will be generated and straightaway clicks on OK
has comment: http://stackoverflow.com/comment/89784449
tagged with: python

http://stackoverflow.com/comment/89804349
score: 2
comment on: http://stackoverflow.com/q/51416622
has text: Is `IP_list` a Python list? Is `IPNetwork` a Python class or function? Or is the complete input just text?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89756293
type: AnswerComment
has text: I am not necessarily trying to remove a newline. I am trying to format array_1 such that we can work around creating the newline.
comment on: http://stackoverflow.com/a/51392031
type: Comment
score: 0

http://stackoverflow.com/comment/89648689
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51336897
has text: 32 bit, I belive I don't use Apache
score: 0

http://stackoverflow.com/a/51349926
upvote count: 3
has comment: http://stackoverflow.com/comment/136543240
answers question: http://stackoverflow.com/q/51349895
score: 3
downvote count: 0
type: Answer
has body: MD5 hashes of frames aren't going to work, since the videos are compressed, and compression inevitably causes differences in the frame. You might want some sort of image hash instead, like phash for instance.
has comment: http://stackoverflow.com/comment/89672414

http://stackoverflow.com/comment/89673295
has text: Please post a [MCVE], emphasis on *minimal*. Your code has too much noise that has nothing to do with the question.
type: QuestionComment
score: 6
type: Comment
comment on: http://stackoverflow.com/q/51350349

http://stackoverflow.com/a/51334023
score: 0
answers question: http://stackoverflow.com/q/51332260
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51332260
type: Answer
has body: In general you could create a null property, and use the signal that is emited when there is a change to invoke requestPaint(), and in onPaint() you draw a circle that emulates the point. import QtQuick 2.0 import QtQuick.Controls 2.1 import QtQuick.Layouts 1.2 ApplicationWindow { visible: true width: 640 height: 480 property var drawPoint: null onDrawPointChanged: canv.requestPaint() ColumnLayout { anchors.fill: parent anchors.margins: 9 Button { height: 40 Layout.fillWidth: true text: qsTr("Random Point") onClicked: drawPoint = Qt.point(Math.random()*canv.width ,Math.random()*canv.height); } Canvas { id: canv Layout.fillWidth: true Layout.fillHeight: true onPaint: { var ctx = getContext("2d"); ctx.fillStyle = Qt.rgba(1, 1, 1, 1); ctx.fillRect(0, 0, width, height); if(drawPoint !== null){ ctx.beginPath(); ctx.arc(drawPoint.x, drawPoint.y, 5, 0, 2 * Math.PI); ctx.fillStyle = Qt.rgba(1, 0, 0, 1); ctx.fill() ctx.strokeStyle = Qt.rgba(1, 0, 0, 1); ctx.stroke(); } } } } }

http://stackoverflow.com/q/51376060
upvote count: 1
tagged with: python
score: 1
tagged with: eclipse
type: Question
has title: Importing a .dll library in python using eclipse
downvote count: 0
favorite count: 0
has body: I'm fairly new to Python and I'm trying to use ctypes to use a .dll library It comes out with error " winerror 193 1 is not a valid win32 application" This is the c code that I use to create the .dll __declspec(dllexport) int sum(int a, int b) { return a + b; } and this is the python code where I'm trying to import the dll from ctypes import cdll mydll = cdll.LoadLibrary('libTest.dll') if __name__ == '__main__': pass It's fairly simple, but when I try to run it I get all this bunch of errors Traceback (most recent call last): File "C:\Users\robertodg\.p2\pool\plugins\org.python.pydev.core_6.4.3.201807050139\pysrc\_pydev_runfiles\pydev_runfiles.py", line 468, in __get_module_from_str mod = __import__(modname) File "C:\Users\robertodg\eclipse-workspace\LetsHope\Hope.py", line 8, in &lt;module&gt; mydll = cdll.LoadLibrary('libTest.dll') File "C:\Users\robertodg\AppData\Local\Programs\Python\Python37-32\lib\ctypes\__init__.py", line 434, in LoadLibrary return self._dlltype(name) File "C:\Users\robertodg\AppData\Local\Programs\Python\Python37-32\lib\ctypes\__init__.py", line 356, in __init__ self._handle = _dlopen(self._name, mode) OSError: [WinError 193] %1 is not a valid win32 application I'm using eclipse on windows with the c and python prospective and I'm using and this is the python that I'm running Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32 I know that it's prob something really simple, but I've been banging my head for 2 days now. thanks in advance
linked to: http://stackoverflow.com/q/19849077
has comment: http://stackoverflow.com/comment/89735302
has comment: http://stackoverflow.com/comment/89724885
tagged with: dllimport
duplicate of: http://stackoverflow.com/q/19849077
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/51473097
type: Question
has body: I am having a problem and need your help. I am making a django website, following information need to be verified. If it pass registration will be success and fail notice will show up. But Mean while there are no problem with success, but Notice won't show up if fail. Here are my form.py, could anyone help me? Much Thanks. if settings.VERIFY_BY_SFID and all([i in cleaned_data for i in fields]): number = cleaned_data["mobile_number"] verified =SignUpFailureAttemptService.verify_mobile_number(number) if not verified: self.add_error(None, _("Your application was rejected.")) Template {% extends 'accounts/login_base.html' %} {% load i18n %} {% load staticfiles %} {% load semanticui %} {% load common_templatetags %} {% block welcome_text %} {% trans 'Create your personal E-wallet account.' %} {% endblock %} {% block slogan_text %} {% trans 'Buy and sell with protection Easy and secure to send and receive money' %} {% endblock %} {% block bigger_text %} {% blocktrans %}Already have an account?{% endblocktrans %} {% trans 'Sign in' %} {% endblock %} {% block left_content %} STEPS: {% include 'accounts/signup/steps.html' with active_step=step steps=5 %} {% block form_title %} {{ form_title }} {% endblock %} {% if messages %} {% for message in messages %} {{ message }} {% endfor %} {% endif %} {% block form_block %} {% csrf_token %} {{ form.non_field_errors }} {% for hidden_field in form.hidden_fields %} {{ hidden_field.errors }} {{ hidden_field }} {% endfor %} {% for field in form.visible_fields %} {% if field.name == 'date_of_birth' %} {{ field.label }}* {% endif %} {% if field.name == 'tos' %} {% blocktrans %} I agree to {% endblocktrans %} PDS and FSG {{ field }} {% else %} {{ field }} {% endif %} {{ field.help_text }} {{ field.errors }} {% endfor %} {% if prev_step %} « {% trans 'Back' %} {% endif %} {% if next_step_title %} {% trans 'NEXT STEP:' %} {{ next_step_title }} {% endif %} {% endblock %} {% endblock %} {% block scripts_end %} {% endblock %}
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89926014
has comment: http://stackoverflow.com/comment/89914672
score: 0
tagged with: error-handling
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89925860
has title: Unable to show Error with self.add_error()
answer count: 0

http://stackoverflow.com/a/51479495
upvote count: 3
has comment: http://stackoverflow.com/comment/89927644
has comment: http://stackoverflow.com/comment/89927311
score: 3
has comment: http://stackoverflow.com/comment/89927348
has comment: http://stackoverflow.com/comment/89927684
has comment: http://stackoverflow.com/comment/103565387
accepted answer of: http://stackoverflow.com/q/51479444
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51479444
has comment: http://stackoverflow.com/comment/89927488
has body: Pyinstaller --onefile mainImpactTool.py Try this it will work. Pyinstaller will recurse over all your imports(impactTool.py) and include it in the .exe.
has comment: http://stackoverflow.com/comment/89927327
type: Answer
has comment: http://stackoverflow.com/comment/103582531
has comment: http://stackoverflow.com/comment/89927568

http://stackoverflow.com/comment/89757896
type: Comment
type: QuestionComment
has text: Use a for loop. Have you tried....it is not difficult
comment on: http://stackoverflow.com/q/51393081
score: 0

http://stackoverflow.com/q/51341613
tagged with: concatenation
answer count: 1
downvote count: 0
tagged with: keras
favorite count: 0
has body: I use Keras for a CNN and have two types of Inputs: Images of objects, and one or two more parameters describing the object (e.g. weight). How can I train my network with both data sources? Concatenation doesn't seem to work because the inputs have different dimensions. My idea was to concatenate the output of the image analysis and the parameters somehow, before sending it into the dense layers, but I'm not sure how. Or is it possible to merge two classifications in Keras, i.e. classifying the image and the parameter and then merging the classification somehow?
has title: Multiple Inputs for CNN: images and parameters, how to merge
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51341789
tagged with: conv-neural-network
upvote count: 2
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/51341789

http://stackoverflow.com/comment/89761643
type: Comment
has text: Okay, I'll check the cluster total memory of the 4 GPUs and try to run my code on this cluster, if it doesn't fit on its memory, I'll have to find the way to generate data in another way. Thanks.
comment on: http://stackoverflow.com/a/51383650
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89871325
comment on: http://stackoverflow.com/a/51449587
has text: Correct. Don’t count on scapy to receive high packet rates... that’s a python restriction. I would however note that you could use a `L2ListenTcpdump` socket which calls tcpdump for the capture, then handles the packet in scapy
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51371679
tagged with: python
tagged with: excel
has comment: http://stackoverflow.com/comment/92827743
has title: Change XLS cell value in Linux CLI without breaking format
has body: I am attempting to automate edits to a cell from a pre-provided spreadsheet. I need to adjust a single value in a single cell without breaking the formatting. I have tried pyexcel, xlutils and openpyxl to no avail; they can change data but break the formatting of the document. I have also tried placing dummy text in the file and using sed to change that; sed -i 's/changethisvalue/thisischangevalue/g' file-name.xls I find that this simple replacement breaks the formatting of the document when I attempt to open it in LibreCalc. My question is; does an XLS document contain specific formatting data that's sensitive to cell content, and is there a way to 'hack' this to work?
has comment: http://stackoverflow.com/comment/90248708
type: Question
has comment: http://stackoverflow.com/comment/89715976
has comment: http://stackoverflow.com/comment/89949798
has comment: http://stackoverflow.com/comment/89717525
score: 0
tagged with: linux
answer count: 0
type: UnansweredQuestion
tagged with: libreoffice-calc

http://stackoverflow.com/comment/89911269
comment on: http://stackoverflow.com/a/51469832
type: AnswerComment
has text: Thanks, I am aware of the cursor capabilities; although I have to tell Selenium what to look for, and there is no way to query the OS and ask "is it a button" or "is it a textfield". I can assume that at one point in time, something will happen and I will click on a specific location, but that is not really ideal for writing tests.
score: 0
type: Comment

http://stackoverflow.com/comment/89705573
type: AnswerComment
comment on: http://stackoverflow.com/a/51364340
score: 0
type: Comment
has text: @FrontEnd-Python What he meant by removing the `mouse_pos()` method is that it's *unnecessary* to write a separate method to get mouse position when there's already one built-in, the `pygame.mouse.get_pos()` function (which never returns `None` so your error would technically be nullified if you refactor your code this way). If you put it in the main update loop, it will perform the intended task — getting the mouse position over and over again, once on each loop iteration. The event queue is just a bunch of `pygame.event.Event` objects retrieved on a `pygame.event.get()` call.

http://stackoverflow.com/a/51423297
has body: [item for item in pt[0]] [item for item in pt[1]] The item is generated in in that scope, while pt isn't, even though you're enumerating a dict, you may want to do something like this: {key: value for key, value in pt[0].items()} {key: value for key, value in pt[1].items()}
has comment: http://stackoverflow.com/comment/89817539
has comment: http://stackoverflow.com/comment/89817845
has comment: http://stackoverflow.com/comment/89818379
has comment: http://stackoverflow.com/comment/89818184
answers question: http://stackoverflow.com/q/51423255
score: 0
accepted answer of: http://stackoverflow.com/q/51423255
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/89817874
has comment: http://stackoverflow.com/comment/89817694

http://stackoverflow.com/a/51622198
has body: You should override celery signal methods. Signal list; http://docs.celeryproject.org/en/latest/userguide/signals.html Create a model for celery tasks. For example it's name is CeleryTask. Before task is run, create new task object in CeleryTask model. When celery restarted and when worker is ready, tasks are run again. tasks.py from celery.signals import worker_ready, task_prerun def on_task_prerun(*args, **kwargs): from .models import CeleryTask task_properties = kwargs['task'] ctask = CeleryTask.objects.create( task_name=task_properties.name, task_args=task_properties.request.args ) def on_worker_ready(*args, **kwargs): from .models import CeleryTask from celery.execute import send_task tasks = CeleryTask.objects.all() for ctask in tasks: send_task(ctask.task_name, ctask.task_args) worker_ready.connect(on_worker_ready, dispatch_uid='on_worker_ready') task_prerun.connect(on_task_prerun, dispatch_uid='on_task_prerun')
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51408605

http://stackoverflow.com/q/51480276
tagged with: violin-plot
has body: I want to create a violinplot using seaborn and I am a little confused on how to use the parameters. I have my data stored in 6 lists (all having the same length): file1_score &amp; file1_rms * - the 2 lists for file 1* file2_score &amp; file2_rms * - the 2 lists for file 2* file3_score &amp; file3_rms * - the 2 lists for file 3* I want to observe the distributions of scores at distinct rms for the three different files. My output should look like this: Can someone please help me with the code? Thank you in advance.
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/51482467
tagged with: python-3.x
type: UnansweredQuestion
tagged with: seaborn
has title: Create violinplots in seaborn using data from lists
has comment: http://stackoverflow.com/comment/89930283
type: Question
has comment: http://stackoverflow.com/comment/89929968
has comment: http://stackoverflow.com/comment/89929810
answer count: 1

http://stackoverflow.com/a/51406782
has comment: http://stackoverflow.com/comment/89789010
has comment: http://stackoverflow.com/comment/89789069
type: Answer
has comment: http://stackoverflow.com/comment/89789180
answers question: http://stackoverflow.com/q/51387726
score: 0
has body: If you have two python scripts located in the same directory ie: # first_script.py def foo(): print("stuff") then you simply import the first script into the one your working on: # second_script.py import first_script first_script.foo() # prints "stuff" That should be working. It gets a bit more complicated when these scripts are located in different directories. If they are located in different directories you are going to need a __init__.py in the directory you are pulling from; that much I am sure of. However, beyond that I am not so sure. This compounds btw. So, if you have scripts a, b, c...n and a pulls from b which pulls from c which pulls from... n then a also pulls from n.

http://stackoverflow.com/comment/89750629
score: 1
type: Comment
comment on: http://stackoverflow.com/q/51388938
type: QuestionComment
has text: Sorry, I don't know matplotlib, but shouldn't you be converting those number strings into actual numbers, eg floats?

http://stackoverflow.com/q/51464260
type: Question
has title: ValueError: script 'filename.py' not found when using pyinstaller to edit a .spec file
downvote count: 0
has comment: http://stackoverflow.com/comment/89897472
score: 1
favorite count: 0
tagged with: pyinstaller
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89897342
has body: So i'm trying to change something in the .spec file which i've named "filename.py", although pyinstaller can never find the file even if i open the command prompt from within the folder that contains the file. I've even tried inserting the whole file path but still received the same error. PS C:\Users\S3401\Desktop\New folder&gt; pyi-makespec filename.py wrote C:\Users\S3401\Desktop\New folder\filename.spec now run pyinstaller.py to build the executable PS C:\Users\S3401\Desktop\New folder&gt; pyinstaller .\filename.spec 46 INFO: PyInstaller: 3.3.1 46 INFO: Python: 3.6.6 46 INFO: Platform: Windows-10-10.0.17134-SP0 47 INFO: UPX is not available. Traceback (most recent call last): File "C:\Program Files\Python36\Scripts\pyinstaller-script.py", line 11, in &lt;module&gt; load_entry_point('PyInstaller==3.3.1', 'console_scripts', 'pyinstaller')() File "c:\program files\python36\lib\site-packages\PyInstaller\__main__.py", line 94, in run run_build(pyi_config, spec_file, **vars(args)) File "c:\program files\python36\lib\site-packages\PyInstaller\__main__.py", line 46, in run_build PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs) File "c:\program files\python36\lib\site-packages\PyInstaller\building\build_main.py", line 791, in main build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build')) File "c:\program files\python36\lib\site-packages\PyInstaller\building\build_main.py", line 737, in build exec(text, spec_namespace) File "&lt;string&gt;", line 16, in &lt;module&gt; File "c:\program files\python36\lib\site-packages\PyInstaller\building\build_main.py", line 162, in __init__ raise ValueError("script '%s' not found" % script) ValueError: script 'filename.py' not found
answer count: 0

http://stackoverflow.com/q/51472977
has title: How to save small png images to Mongodb database using pymongo
score: 0
has body: I want to save png file to my Mongodb Database. I am trying this with code like this: with open(SCREENCAP_FILE_NAME, 'rb') as f: page_info_tuple = { "page_hash": _page_hash, "ativity_name": _activity_name, "screen_shot": f } Mongo.coll_pageinfo.insert_one(page_info_tuple) However, it gives me bson.errors.InvalidDocument: Cannot encode object: open file 'screen.png', mode 'rb' at 0x109d3ced0
answer count: 1
type: UnansweredQuestion
tagged with: python
tagged with: pymongo
type: Question
has answer: http://stackoverflow.com/a/51489565
tagged with: mongodb

http://stackoverflow.com/comment/89869812
has text: Sure. If you decorate `foo`, call it a few million times, then define a new function afterwards named `bar` and decorate that too, then your previous counts of `foo` will disappear.
score: 0
comment on: http://stackoverflow.com/q/51449615
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51384417
downvote count: 0
score: 3
has body: If you have valid cookies you can add them to your session, cookies = dict(security='high', PHPSESSID='o9m7jgcspe02h9rffj9g7cv0t5') with requests.Session() as c: c.cookies.update(cookies) and now you can access /dvwa/vulnerabilities/exec. If you don't have cookies then you can use the login page to get them. In the login form there is token in a hidden input field that you have to submit. You can get its value with bs4 or re. import requests import re payload = { 'username': 'admin', 'password': 'password', 'Login': 'Login' } with requests.Session() as c: r = c.get('http://127.0.0.1/dvwa/login.php') token = re.search("user_token'\s*value='(.*?)'", r.text).group(1) payload['user_token'] = token p = c.post('http://127.0.0.1/dvwa/login.php', data=payload) r = c.get('http://127.0.0.1/dvwa/vulnerabilities/exec') print(r.text) I'm using re because it's a standard library, but it's best to use bs4 for html parsing. If you have bs4 installed you can get the token with this selector: 'input[name=user_token]'.
type: Answer
answers question: http://stackoverflow.com/q/51381302
upvote count: 3

http://stackoverflow.com/comment/89805509
type: QuestionComment
comment on: http://stackoverflow.com/q/51417135
has text: For cumulative sums there is a `cumsum` function available in pandas. Can you provide your input data as text?
score: 0
type: Comment

http://stackoverflow.com/a/51505603
score: 2
answers question: http://stackoverflow.com/q/51449038
downvote count: 0
type: Answer
upvote count: 2
has body: Since you have not changed the code and errors you shared shows that it's a network related problem. It's most probably a DNS issue. In your settings.py you have specified the EMAIL_HOST, which is i believe a hostname. You need to check you server's DNS server. You are mentioning about checking your firewall settings but what you are doing wrong is not checking the actual connection. To address the problem you can use couple of command line utilities like telnet or nslookup. You can check if you can resolve a hostname: nslookup smptp.mail_host.com This command will fail most probably. I would like to point what you did wrong in your steps: 1) You have tried to get your services getaddrinfo in which you needed to put your smtp servers hostname, which would result with the same error. Sockets are the very primitive part of the connection on the application layer, you don't really need to dig in to that. 2) Checking firewall settings is OK. 3) This is a good step which shows that there is a problem with your servers network connection. 4) That is another evidence :) 5) You have got it wrong, if you have a proxy server on your network to connect external networks, than you use this settings. But you have configured it wrong. You should not set your projects url as proxy server. 6) This is another deep level coding. You should not use such low level script, which will cause you numerious problems, which would have been handled in high level modules.
has comment: http://stackoverflow.com/comment/90185948
has comment: http://stackoverflow.com/comment/90151585

http://stackoverflow.com/q/51353945
accepted answer: http://stackoverflow.com/a/51354040
has body: I'm trying to connect my flask app with a mysql db. Python Version: Python 2.7.11 I'm trying to install flask_mysqldb by pip install flask_mysqldb, but I get this error: Collecting flask_mysqldb Requirement already satisfied: Flask&gt;=0.10 in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages (from flask_mysqldb) (1.0.2) Collecting mysqlclient (from flask_mysqldb) Using cached https://files.pythonhosted.org/packages/ec/fd/83329b9d3e14f7344d1cb31f128e6dbba70c5975c9e57896815dbb1988ad/mysqlclient-1.3.13.tar.gz Requirement already satisfied: itsdangerous&gt;=0.24 in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages (from Flask&gt;=0.10-&gt;flask_mysqldb) (0.24) Requirement already satisfied: Jinja2&gt;=2.10 in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages (from Flask&gt;=0.10-&gt;flask_mysqldb) (2.10) Requirement already satisfied: Werkzeug&gt;=0.14 in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages (from Flask&gt;=0.10-&gt;flask_mysqldb) (0.14.1) Requirement already satisfied: click&gt;=5.1 in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages (from Flask&gt;=0.10-&gt;flask_mysqldb) (6.7) Requirement already satisfied: MarkupSafe&gt;=0.23 in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages (from Jinja2&gt;=2.10-&gt;Flask&gt;=0.10-&gt;flask_mysqldb) (1.0) Building wheels for collected packages: mysqlclient Running setup.py bdist_wheel for mysqlclient ... error Complete output from command /Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python -u -c "import setuptools, tokenize;__file__='/private/var/folders/k0/j8c755m50dndbzkv7fdtj5hh0000gn/T/pip-install-lffPsc/mysqlclient/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 /private/var/folders/k0/j8c755m50dndbz…
type: AnsweredQuestion
has title: `pip install flask_mysqldb` fails due to clang: error: linker command failed with exit code 1
upvote count: 1
type: Question
tagged with: mysql
has answer: http://stackoverflow.com/a/51354040
downvote count: 0
answer count: 1
score: 1
favorite count: 0
tagged with: python

http://stackoverflow.com/a/51413279
downvote count: 0
has comment: http://stackoverflow.com/comment/89798630
has body: linspace gives better control of the end point when dealing with floats: In [84]: [np.linspace(0,x,11) for x in [.1,.2,.3]] Out[84]: [array([0. , 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1 ]), array([0. , 0.02, 0.04, 0.06, 0.08, 0.1 , 0.12, 0.14, 0.16, 0.18, 0.2 ]), array([0. , 0.03, 0.06, 0.09, 0.12, 0.15, 0.18, 0.21, 0.24, 0.27, 0.3 ])] Or we could scale just one array (arange with integers is predictable): In [86]: np.array([.1,.2,.3])[:,None]*np.arange(0,11) Out[86]: array([[0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ], [0. , 0.2, 0.4, 0.6, 0.8, 1. , 1.2, 1.4, 1.6, 1.8, 2. ], [0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1, 2.4, 2.7, 3. ]])
type: Answer
has comment: http://stackoverflow.com/comment/89798969
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51413076

http://stackoverflow.com/q/51354805
answer count: 2
has title: How to pre-process ordinal feature where feature values are range of numbers and rank or encode them accordingly
score: 0
tagged with: categorical-data
tagged with: python
has comment: http://stackoverflow.com/comment/89682202
type: UnansweredQuestion
tagged with: machine-learning
tagged with: feature-engineering
has body: I have the following feature column in my dataset: +-----------+ | size | +-----------+ | 10-90 | | &lt;10 | | 100-200 | | 10-90 | | 500-800 | | 10000+ | | &lt;10 | | 1000-4999 | +-----------+ I am a novice in machine learning, and am finding it difficult to deal with such a feature set. When I do: import pandas as pd y = pd.Categorical(train['size'],ordered=True) The output of y is : [10-90, &lt;10, 100-200, 10-90, 500-800, 10000+, &lt;10, 1000-4999] Categories (6, object): [10-90 &lt; 100-200 &lt; 1000-4999 &lt; 10000+ &lt; 500-800 &lt; &lt;10] which is wrong, since &lt;10 should get the lowest rank, and also 500-800 gets a wrong rank. According to this feature set >10000 or 10000+ should have gotten the highest rank. I need to rank or encode this data accordingly, such that if my test data gets the value 5, or &lt;5 it should get the same rank or encoding as &lt;10, since that's the nearest one. Is there any method/package in python or R that can help me achieve this? Kindly help.
has answer: http://stackoverflow.com/a/51354844
has answer: http://stackoverflow.com/a/51355032
type: Question

http://stackoverflow.com/a/51372689
type: Answer
has comment: http://stackoverflow.com/comment/89724941
score: 2
downvote count: 0
has body: IIUC, given array = [[[0,0,1,0],[0,0,0,1],[1,0,0,0],[0,1,0,0]], [[0,1,0],[1,0,0],[0,0,1],[0,0,1]], [[0],[1],[0],[1]], [[1],[1],[0],[1]]] Do import numpy as np &gt;&gt;&gt; np.array(array).T array([[list([0, 0, 1, 0]), list([0, 1, 0]), list([0]), list([1])], [list([0, 0, 0, 1]), list([1, 0, 0]), list([1]), list([1])], [list([1, 0, 0, 0]), list([0, 0, 1]), list([0]), list([0])], [list([0, 1, 0, 0]), list([0, 0, 1]), list([1]), list([1])]],
has comment: http://stackoverflow.com/comment/89717186
answers question: http://stackoverflow.com/q/51372651
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51372651

http://stackoverflow.com/q/51366310
has answer: http://stackoverflow.com/a/51366470
accepted answer: http://stackoverflow.com/a/51366470
possible better answer: http://stackoverflow.com/a/51366371
has title: I need help to understand logic and solve code using python
type: Question
has comment: http://stackoverflow.com/comment/89704910
answer count: 2
downvote count: 4
has answer: http://stackoverflow.com/a/51366371
favorite count: 0
score: -4
tagged with: python
has body: My background: I am a Network Engineer and started learning python to automate tasks. I don't have much experience in coding. I need help to understand and solve the coding issue, I've spent numerous hours to solve this coding problem using python but no luck. I have attached what I have done so far on this problem. # read file with open("C:\py\logfile.txt") as file: next(file) lines = file.read().splitlines() file.close() matchEst = [] matchFail = [] matchSyn = [] counterEst = 0 counterFail = 0 counterSyn = 0 for line in lines: line = line.strip() if line.find('Established') != -1: matchEst.append(line) elif line.find('Failed') != -1: matchFail.append(line) elif line.find('Syn') != -1: matchSyn.append(line) print(matchEst) print(matchFail) print(matchSyn) OUTPUT: ['9/1/2013 1.1.1.1 0:10 Established', '9/1/2013 1.1.1.1 0:10 Established', '9/2/2013 1.1.1.1 0:10 Established', '9/2/2013 1.1.1.1 0:10 Established', '9/2/2013 1.1.1.2 0:10 Established', '9/2/2013 1.1.1.1 0:10 Established', '9/2/2013 1.1.1.1 0:10 Established'] ['9/1/2013 1.1.1.2 0:10 Failed', '9/2/2013 1.1.1.1 0:10 Failed', '9/2/2013 1.1.1.1 0:10 Failed', '9/2/2013 1.1.1.1 0:10 Failed'] ['9/1/2013 1.1.1.1 0:10 Syn', '9/2/2013 1.1.1.1 0:10 Syn', '9/2/2013 1.1.1.1 0:10 Syn'] Code Description: To parse file "logfile.txt" and print the counts of the status for every IP per day. cat logfile.txt ----------------- Date IP Time State 9/1/2013 1.1.1.1 0:10 Established 9/1/2013 1.1.1.2 0:10 Failed 9/1/2013 1.1.1.1 0:10 Syn 9/1/2013 1.1.1.1 0:10 Established 9/2/2013 1.1.1.1 0:10 Established 9/2/2013 1.1.1.1 0:10 Failed 9/2/2013 1.1.1.1 0:10 Failed 9/2/2013 1.1.1.1 0:10 Established 9/2/2013 1.1.1.2 0:10 Established 9/2/2013 1.1.1.1 0:10 Established 9/2/2013 1.1.1.1 0:10 Failed 9/2/2013 1.1.1.1 0:10 Established 9/2/2013 1.1.1.1 0:10 Syn 9/2/2013 1.1.1.1 0:10 Syn Output should look like: 9/1/2013 1.1.1.1 Established 2 9/1/2013 1.1.1.2 Failed 1 9/1/2013 1.1.1.1 Syn 1 9/2/2013 1.1.1.1 Established 4 9/2/2013 1.1.1.1 Failed …
type: AnsweredQuestion
upvote count: 0

http://stackoverflow.com/comment/89837329
score: 0
has text: @VitorBaptista I linked to that answer in my question, it only works on subclasses of ChoiceEnum (and there are a lot of them). If possible, I'd like a more global solution (other than disabling the warning entirely).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51428697

http://stackoverflow.com/a/51326444
has body: You're trying to do print( raw_message['altitude'] ) and getting the error message string indices must be integers So, the logical conclusions is that raw_message is a String, not a dictionary. You can use raw_message['altitude'] to get the altitude key of a dictionary, but a String doesn't have keys - only indices. Additionally, keep in mind where this error is occurring. It's inside of an except block, and specifically only runs when you can't parse a raw message (and I'm assuming that the "raw message" is, indeed, just a regular string of text). Try doing print( raw_message ) instead for the debug information you need. Or, at least, treat it as a string instead of as a dictionary. It's possible that the real cause of your error is that parse(raw_message) is throwing an error and it's not supposed to, in which case you might want to do step-by-step debugging with a tool like PDB to figure out where it's failing.
has comment: http://stackoverflow.com/comment/89628058
upvote count: 1
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/51326285
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51326285

http://stackoverflow.com/comment/89873643
comment on: http://stackoverflow.com/a/51409978
type: AnswerComment
score: 1
has text: @SeyiShoboyejo Probably. It would mutate the dictionary though, which isn't what someone would expect this to do. I'm happier trading a little speed for referential transparency.
type: Comment

http://stackoverflow.com/q/51437654
favorite count: 0
has comment: http://stackoverflow.com/comment/89845373
has comment: http://stackoverflow.com/comment/89845179
has body: I want to run a script in .py with cmd or anaconda prompt but says pandas can't be recognized. 'pandas' in sys.modules False the version of python is the correct where these libraries are installed. The correct path is somehow not in connection with the cmd and all the libraries installed with the anaconda are not seen. How to make it work without installing all the modules again?
tagged with: python
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/89845349
has answer: http://stackoverflow.com/a/51438021
has comment: http://stackoverflow.com/comment/89845288
tagged with: anaconda
type: Question
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/51437753
has comment: http://stackoverflow.com/comment/89845423
tagged with: pandas
has comment: http://stackoverflow.com/comment/89845239
has comment: http://stackoverflow.com/comment/89845483
has title: pandas work on jupyter but not recognized in cmd or anaconda prompt
has comment: http://stackoverflow.com/comment/89845299
downvote count: 1

http://stackoverflow.com/comment/89763259
score: 0
has text: oh ok.. got it..
comment on: http://stackoverflow.com/q/51396047
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51393388
has body: The reason is explained in the comments: def main(): read() def read(): fileName=input("Enter the file you want to count: ") infile=open(fileName , "r") text=infile.readline() ##Reading the first line here but not printing count=0 while text != "": text=str(count) count+=1 text=infile.readline() ##Reading the 2nd line here print(str(count)+ ": " + text) ##Printing the 2nd line here, missed the first ##line infile.close() main() Modify the program as: def main(): read() def read(): fileName= input("Enter the file you want to count: ") infile = open(fileName , "r") text = infile.readline() count = 1 # Set count to 1 while text != "": print(str(count)+ ": " + str(text)) # Print 1st line here count = count + 1 # Increment count to 2 text = infile.readline() # Read 2nd line infile.close() # Close the file main()
answers question: http://stackoverflow.com/q/51393333
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51393333
score: 2

http://stackoverflow.com/a/51375226
type: Answer
has comment: http://stackoverflow.com/comment/89733852
has comment: http://stackoverflow.com/comment/89757316
has comment: http://stackoverflow.com/comment/89757770
answers question: http://stackoverflow.com/q/51374627
score: 0
has body: You might use readlines() instead of read() to get all lines in a file and then iterate all lines: lines = f.readlines() for s in lines: # To get the Xtalk # xtalk = re.search(r"Xtalk", s) if xtalk is not None: = re.split(' ', xtalk.string) num = int(a[1][1]) ... m = re.search("GHz\s+\=(.*)dB",s) ...

http://stackoverflow.com/comment/89755849
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51391713
score: 0
has text: @Code-Apprentice You can get 2-3 orders of magnitude by switching from `savetxt` to `save`. The throughput for a large contiguous write on an SSD vs. an HDD is usually more like 1 order of magnitude. (Of course seek times are hugely better on SSDs, but that isn't relevant here.)

http://stackoverflow.com/q/51425330
tagged with: filter
type: Question
tagged with: django-queryset
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89822289
has body: I have the follow models: class FactoryDevice(models.Model) ... class InspectionRegister(models.Model) factory_device = models.ForeignKey(FactoryDevice) inspection_date = models.DateTimeField() status = models.CharField(choices=choices.STATUS) This is the scenario: In a factory, every week devices are inspected. I want filter only FactoryDevices that the last five related InspectionRegisters have status as choices.REPPROVED. If one of the last five InspectionRegister in a FactoryDevice not has status as choices.REPPROVED so this FactoryDevice must not be in the results.
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89822322
answer count: 1
has answer: http://stackoverflow.com/a/51429527
has title: Filter objects in Django 2 if all objects in subquery have specific value
score: 0
has comment: http://stackoverflow.com/comment/89821678
accepted answer: http://stackoverflow.com/a/51429527
has comment: http://stackoverflow.com/comment/89821713
tagged with: subquery

http://stackoverflow.com/comment/89894059
comment on: http://stackoverflow.com/q/51461341
type: Comment
type: QuestionComment
score: 0
has text: python2 or python3? Assuming pip actually did something, where did it install the files?

http://stackoverflow.com/comment/89654364
has text: By using this you are simulating the mouse actions such as right click or double click. Ideally you should let your script run without using actual keyboard and actual mouse. Ans 1. It's simulation of your actual mouse.You can still use your mouse , However I would not recommend that. 2. If the website is too restrictive i.e it is able to catch your regular mouse , I am afraid this will be detected by website.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51340364

rest
tags question: http://stackoverflow.com/q/51433725
tags question: http://stackoverflow.com/q/51399222
tags question: http://stackoverflow.com/q/51332141
tags question: http://stackoverflow.com/q/51446540
type: Tag
tags question: http://stackoverflow.com/q/51360970
tags question: http://stackoverflow.com/q/51469536
tags question: http://stackoverflow.com/q/51344934
tag name: rest
tags question: http://stackoverflow.com/q/51431392

http://stackoverflow.com/comment/89645052
type: Comment
has text: You don't have to make it that complicated! I'm just saying that is the theoretical maximum for efficiency. In practice, you may want to make it more like 1 = magenta, 2 = cyan, 3 = yellow, and 4 = white. Before continuing on however, I would suggest you read up on [Color Depth](https://en.wikipedia.org/wiki/Color_depth) and also read through some of the docs for PIL.
comment on: http://stackoverflow.com/a/51334528
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89692600
type: Comment
has text: Yes that works. The file was definitely there. I'll start using the os.path methods. Thanks!
comment on: http://stackoverflow.com/a/51325194
score: 1
type: AnswerComment

http://stackoverflow.com/q/51417774
has body: I'm mostly using Pillow library but I can use something else. I can extract the color layer including the alpha one. I'm wondering if there is a way to quickly define if a picture use transparency or not. pic = Image.open(path) red, green, blue, alpha = pic.split() Is there a way to see if the alpha is really used or only available because the format support it (e.g.: PNG)
type: UnansweredQuestion
score: 1
upvote count: 1
has title: How to determine if a png picture has a transparency layer in Python
linked to: http://stackoverflow.com/q/43864101
type: Question
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/89807033
tagged with: image
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90104097
favorite count: 0
has answer: http://stackoverflow.com/a/51417989
linked to: http://stackoverflow.com/q/10689512
tagged with: python

http://stackoverflow.com/q/51478631
upvote count: 0
has answer: http://stackoverflow.com/a/51478742
possible better answer: http://stackoverflow.com/a/51478685
accepted answer: http://stackoverflow.com/a/51478705
favorite count: 0
tagged with: python
answer count: 4
type: AnsweredQuestion
score: -5
has title: Min valule in dict
has body: my function return a dict {1: 10.0, 2: 9.0, 3: 2.5} so i did try a = {1: 10.0, 2: 9.0, 3: 2.5} for i in a.keys() prin min(i) but getting TypeError: 'int' object is not iterable can someone explain me how can I get a value that is minimal in this dict?
type: Question
has answer: http://stackoverflow.com/a/51478705
has comment: http://stackoverflow.com/comment/89925655
downvote count: 5
has comment: http://stackoverflow.com/comment/89925690
has answer: http://stackoverflow.com/a/51478811
has comment: http://stackoverflow.com/comment/89925623
has comment: http://stackoverflow.com/comment/89925608
has answer: http://stackoverflow.com/a/51478685

http://stackoverflow.com/comment/89932605
has text: Where do you create a MyForm object?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51472956
score: 1

http://stackoverflow.com/comment/89669345
comment on: http://stackoverflow.com/q/51343961
score: 0
type: Comment
type: QuestionComment
has text: Have you seen [this GitHUb issue](https://github.com/ywangd/stash/issues/309)? It looks like that should already have been fixed though. Are you using the latest version of StaSH?

http://stackoverflow.com/q/51366455
answer count: 1
tagged with: python
has body: The documentation for tf.contrib.cudnn_rnn.CudnnGRU states that call returns rnn_output, rnn_state. RNN state is a tuple, where in non-LSTM cases like GRU, it has a single element-- a tensor of shape [num_layers * num_dirs, batch_size, num_units] (where num_dirs is 2 in this case, for a bidirectional GRU). However, the documentation does not specify the order of the outer shape. Succinctly, given an n-layer bidirectional GRU, is this tensor [final_state_fw_1, ..., final_state_fw_n, final_state_bw_1, ..., final_state_bw_n] OR [final_state_fw_1, final_state_bw_1, ..., final_state_fw_n, final_state_bw_n] ?
favorite count: 0
type: UnansweredQuestion
upvote count: 1
score: 1
tagged with: tensorflow
type: Question
downvote count: 0
has title: TensorFlow bidirectional CudnnGRU ambiguous final state format
has answer: http://stackoverflow.com/a/51387257

http://stackoverflow.com/q/51451966
has comment: http://stackoverflow.com/comment/89877548
has answer: http://stackoverflow.com/a/53926978
score: 22
upvote count: 22
answer count: 3
has comment: http://stackoverflow.com/comment/89883545
downvote count: 0
has comment: http://stackoverflow.com/comment/89883233
has comment: http://stackoverflow.com/comment/89883520
favorite count: 0
has title: twine not found (-bash: twine: command not found)
accepted answer: http://stackoverflow.com/a/53926978
has comment: http://stackoverflow.com/comment/89883309
tagged with: python
has answer: http://stackoverflow.com/a/54044091
has answer: http://stackoverflow.com/a/74603676
has body: I am trying to use twine to publish my first python package on pypi (of course will add on test-pypi first). I followed the official guideline on https://packaging.python.org/tutorials/packaging-projects/. But for some reason, twine is not found or not properly installed. I installed twine using: pip install twine "pip list" says twine is installed on pip. After I upgraded twine and everything, when I tried to run: twine upload --repository-url https://test.pypi.org/legacy/ dist/* then it says that twine is not found at all: -bash: twine: command not found . My system is mac (high sierra) and I am using python2.7 by conda. Pip is also configured to conda python: &gt;&gt;pip -V &gt;&gt;pip 10.0.1 from /anaconda2/lib/python2.7/site-packages/pip (python 2.7) I would appreciate your help.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89883236
possible better answer: http://stackoverflow.com/a/54044091
has comment: http://stackoverflow.com/comment/89874119
tagged with: pip
has comment: http://stackoverflow.com/comment/89883294
tagged with: pypi
type: Question
has comment: http://stackoverflow.com/comment/89883409
tagged with: twine
has comment: http://stackoverflow.com/comment/89878180

http://stackoverflow.com/comment/89926387
has text: you want to decode the hexadecimal number and you are trying to decode string i think that could be the problem.
score: 0
comment on: http://stackoverflow.com/q/51478951
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51375389
downvote count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/89725794
type: Question
has comment: http://stackoverflow.com/comment/89722416
score: -2
has title: Creating/accessing/modifying nested Python lists of unspecified dimension
answer count: 2
has comment: http://stackoverflow.com/comment/89728642
possible better answer: http://stackoverflow.com/a/51375813
has comment: http://stackoverflow.com/comment/89728471
favorite count: 0
tagged with: python-3.x
has body: An API call of mine returns a dict of multi-dimensional data. Each item in the dict is a piece of data and which corresponds to a key of the form "index1:index2: ... :indexN" This is a string of integers separated by colons and it indicates that the data item occurs at position index1 in the first dimension, index2 in the second dimension, etc, up to indexN in the Nth dimension. I would like to take this dictionary of data and use it to populate a multi-dimensional list for further analysis. Ideally this would mean iterating over the dict and interpreting the key as a list of indices, a la index_list = [int(i) for i in key.split(':')] Unfortunately I am automating several related (but different) API calls to populate several different instances of a Data wrapper class, and the datasets are not of fixed dimension. I therefore can't hard code an assignment like data[index1][index2]...[indexN] = dict[key] Is there a Pythonic way to create, access, and modify a multi-list using a second list as index values? Something which "feels like" data[*args] = dict[key] with args = index_list maybe (even though this is obviously nonsense pseudocode)?
tagged with: multidimensional-array
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89722362
has answer: http://stackoverflow.com/a/51375813
has answer: http://stackoverflow.com/a/51375510
accepted answer: http://stackoverflow.com/a/51375510

http://stackoverflow.com/comment/89678475
score: 0
comment on: http://stackoverflow.com/q/51346750
type: QuestionComment
type: Comment
has text: oh by the way if I print out n_classes. The system told me it's "1". I'm not sure if that's where the problem is.

http://stackoverflow.com/q/51448012
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51448527
has body: I am doing neutrino research that requires me to do data analysis by overlaying histograms. We are using ROOT. I am currently trying to convert the following code from C++ to pyroot: #include "TFile.h" #include "TH1F.h" #include "TCanvas.h" #include "TString.h" void myscript() { //get a histogram named vtx_0 from the file 5A_data TFile* file = TFile::Open("5A_data"); TH1F* hist = file-&gt;Get("vtx_0"); TCanvas* canvas = new TCanvas("c1", "Dynamic Filling Example", 200, 10, 700,500); hist-&gt;Draw(); } This is the code I have so far, re-written in python: from ROOT import TFile, TH1F, TCanvas, TString def myscript(): #get vtx_0 from 5A_data TFile file1 = open("5A_data") TH1F hist = I have had limited exposure to Python. The Python code above was created mostly from looking at various online examples, and so I am not even sure if what I have written up to this point is correct. What I am most in need of, and what I have been unable to find online, is how to covert the following line in C++ to its equivalent in Python. TH1F* hist = file-&gt;Get("vtx_0"); How does one do this? In addition, if you see anything amiss with the Python code I have written so far, please tell me what I did wrong and how I might fix it. Thank you.
tagged with: root-framework
downvote count: 0
answer count: 1
favorite count: 0
tagged with: pyroot
type: UnansweredQuestion
tagged with: python
tagged with: c++
has title: Converting C++ to pyroot: How to get a file object from a file in pyroot?
score: 1

http://stackoverflow.com/comment/89921848
score: 0
type: AnswerComment
has text: Good day, i applied this " issueLst = ['lesson learnt','other issues','risk event'] statusLst = ['Open','Open - Actions Completed'] df2 = df1.loc[df['Issue Type'].isin(issueLst) & df1['Status'].isin(statusLst)] ' i got an error
type: Comment
comment on: http://stackoverflow.com/a/51445059

http://stackoverflow.com/q/51394253
downvote count: 1
has title: Divide an hour of sensor data into 10-minute intervals in Python?
upvote count: 0
type: UnansweredQuestion
tagged with: counting
has answer: http://stackoverflow.com/a/51394942
tagged with: sensors
has body: I’m analyzing sensor data from a text file and creating bar charts of activated sensors in an hour using Python. I’m curious to know how can I divide an hour into 10-minute intervals on the x-axis and then count the sensors that are “ON”, and how many times they are on for? I would then like to divide this frequency by the total number of sensors that are on, so that I can get a fraction. I have created a filter that only checks and plots a bar chart of sensors that are “ON” between 07 AM and 08 AM, but I just don’t know how to divide this hour 10-minute interval. This is what I’ve tried so far: #Import libraries import collections import matplotlib.pyplot as plt from datetime import datetime #Get user input file_name = input('Enter File name: ') file = open(file_name) #Array of sensors sensors = [] #Iterate through the file line by line for line in file: words = line.split() #This line filters out the sensor data for the required time interval if (datetime.strptime (words[1][0:7], "%H:%M:%S")) &gt; (datetime.strptime ("07:00:00", "%H:%M:%S")) and (datetime.strptime (words[1][0:7], "%H:%M:%S")) &lt; (datetime.strptime ("08:00:00", "%H:%M:%S")): if words[3] == "ON": sensors.append(words[2]) count = collections.Counter(sensors) print(count) # Plot Graph and Set Y labels and X Labels plt.bar(range(len(count)),count.values(),align='center') plt.xticks(range(len(count)),count.keys()) plt.ylabel('Count') plt.xlabel('Sensors') plt.title('Motion Sensor Data') plt.show() The data in the text file looks like this: 2009-02-02 07:15:16.575809 M35 ON R1_Bed_to_Toilet begin 2009-02-02 07:15:21.408519 AD1-A 2.82231 2009-02-02 07:15:22.532789 M35 OFF 2009-02-02 07:15:23.345479 M35 ON 2009-02-02 07:15:27.529299 AD1-A 2.79926 2009-02-02 07:15:28.655329 M34 ON 2009-02-02 07:15:32.57429 M34 OFF 2009-02-02 07:15:32.739629 M35 OFF 2009-02-02 07:15:32.931449 M34 OFF 2009-02-02 07:15:33.07573 M35 OFF
score: -1
favorite count: 0
has answer: http://stackoverflow.com/a/51395396
type: Question
answer count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/89761082

http://stackoverflow.com/comment/89716297
score: 0
type: QuestionComment
has text: @JohnKugelman I agree. The only time I've had an issue like this was when my script was executing things requiring root permissions on a remote machine via SSH.
comment on: http://stackoverflow.com/q/51372094
type: Comment

http://stackoverflow.com/q/51481948
tagged with: jupyter-notebook
answer count: 0
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89932746
has comment: http://stackoverflow.com/comment/89936166
has comment: http://stackoverflow.com/comment/89965812
has comment: http://stackoverflow.com/comment/89934894
has comment: http://stackoverflow.com/comment/89934921
type: Question
has comment: http://stackoverflow.com/comment/89935806
has title: MySQLdb downloaded but not accessible through Jupyter
has body: I am using Ubuntu 16.04 &amp; have installed anaconda2. Everything is working fine &amp; I can access python packeges(Pandas, numpy, scipy, sklearn, pyodbc) through Jupyter notebook. I wanted to connect mysql through python, so I tried installing MySQLdb via pip. I upgraded pip to 18.0. From terminal, when I am providing the administrator right using sudo su I could able to import MySQLdb &amp; connect to the DB I wished. But surprisingly I could not import MySQLdb in Jupyter notebook despite multiple attempts. I really need to connect mysql from jupyter using any python-mysql connector. As MySQLdb is not working, following other links I tried installing pymysql. But no luck. PFA the screenshots &amp; please let me know how will I get my jupyter working with MySQLdb. I truly need that to happen!!! Please help.
has comment: http://stackoverflow.com/comment/89936982
has comment: http://stackoverflow.com/comment/89951583
has comment: http://stackoverflow.com/comment/89932730
tagged with: mysql-python
tagged with: python

http://stackoverflow.com/comment/89655013
score: 0
comment on: http://stackoverflow.com/a/51340638
type: AnswerComment
type: Comment
has text: That sounds like it would work however I only want to sort on the current page, if I don't split out the page results. It sorts the entire database and I only want to have sorting for the current page (not every entry). Is that possible?

http://stackoverflow.com/q/51443795
has answer: http://stackoverflow.com/a/51443999
has body: I have a loop: for x in itertools.repeat(1) Depending on the cmd line parameters I need this to be infinite or x number of times. So this for x in itertools.repeat(1) or this for x in itertools.repeat(1, x) How can I do this?
has comment: http://stackoverflow.com/comment/106107600
accepted answer: http://stackoverflow.com/a/51443986
has answer: http://stackoverflow.com/a/59997945
type: Question
has answer: http://stackoverflow.com/a/51444239
has title: itertools.repeat(object[, times]) How do I optionally set the times option at runtime?
score: 0
has comment: http://stackoverflow.com/comment/89858296
answer count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/51443986
has comment: http://stackoverflow.com/comment/89858424
has comment: http://stackoverflow.com/comment/89857571
upvote count: 2
downvote count: 2
tagged with: python
possible better answer: http://stackoverflow.com/a/51443999
type: AnsweredQuestion

http://stackoverflow.com/comment/89780260
score: 0
has text: I would **highly recommend** you **not** to use a regular expression. Parse the HTML first using `bs4` (or similar) and then extract the dates using a simple string manipulation (they have a single format) it seems.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51404540

http://stackoverflow.com/comment/89859695
type: Comment
type: QuestionComment
has text: You need to make a prediction and assign it to a variable; otherwise you have nothing to compare against in the SMAPE...
comment on: http://stackoverflow.com/q/51444630
score: 0

http://stackoverflow.com/a/51404986
type: Answer
answers question: http://stackoverflow.com/q/51404873
score: 0
has body: Your code is correct. There are lots of ways to get all prime numbers and you are using the most basic definition, and that's why your code is slow. You can refer to this post (There are lots of ways to get all prime numbers and you are using the most basic definition, and that's why your code is slow. You can refer to this post Fastest way to list all primes below N to ) for more advanced and efficient ways to calculate prime numbers and that should speed up your code a lot. Though you will need to learn and understand lots of mathematical principles and details.

qwidget
tag name: qwidget
tags question: http://stackoverflow.com/q/51433523
type: Tag

http://stackoverflow.com/q/51368984
type: AnsweredQuestion
tagged with: install.packages
accepted answer: http://stackoverflow.com/a/51369625
has body: I want to run a Python script in RShiny. I'm doing this by source() function but it is giving me error. I'm very new to R. Do anyone know how can I run task1 in Server.R? My OS is Windows. server.R: library(shiny) #library library(shinydashboard) #library library(devtools) shinyServer(function(input, output) { observeEvent(input$actionID,{ source("task1.py") }) }) task1.py: from PIL import Image print("Mayday! Mayday!") Error that I'm getting is: Warning: Error in source: task1.py:6:6: unexpected input 5: 6: from PIL ^ 73: source
has title: Running a Python script in R Script is giving error
type: Question
linked to: http://stackoverflow.com/q/18649549
tagged with: http://stackoverflow.com/tag/r
tagged with: shiny
score: 2
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51369625
favorite count: 0
upvote count: 2
tagged with: python

http://stackoverflow.com/a/51429368
upvote count: 3
has body: The issue with your code is here: for i in word_list: if i in joined: pass else: unknown_row.append(joined) Right now, if a word from word_list is not found in joined, it will continue the loop, so it will still add the row unless all the words from word_list are found in the row (This wouldn't prevent your code from working with a single "bad word", which you experienced). Instead, you want to short-circuit the loop to break if any word from word_list is found in the row. You can make use of any here: if not any(i in joined for i in word_list): unknown_row.append(joined) This way, if a single word from word_list is found in joined, the row will not be added.
answers question: http://stackoverflow.com/q/51429236
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51429236
score: 3

http://stackoverflow.com/comment/89833204
type: AnswerComment
has text: I did try this as well using the .encode() .encode('utf-8') and .encode('Latin-1') variations and all continued to result in the "TypeError, Unicode-objects must be encoded before hashing" problem
type: Comment
comment on: http://stackoverflow.com/a/51430505
score: 0

http://stackoverflow.com/a/51443986
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/89858870
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51443795
answers question: http://stackoverflow.com/q/51443795
has comment: http://stackoverflow.com/comment/89857979
has body: itertools.repeat returns an iterable, so you can do this: import sys import itertools if len(sys.argv) &gt; 1: repeater = itertools.repeat(1, int(sys.argv[1])) else: repeater = itertools.repeat(1) for x in repeater: print x sys.argv is the cli inputs; argv[0] will always be the script name, so I'm assuming argv[1] will be your input.

http://stackoverflow.com/comment/90079895
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/51460002
has text: As a potential workaround, this [jupyter extension](http://jupyter-contrib-nbextensions.readthedocs.io/en/latest/nbextensions/highlighter/readme.html) can highlight markdown cells.
type: Comment

http://stackoverflow.com/comment/89954742
type: AnswerComment
score: 0
type: Comment
has text: Hi Andrej Kesely. I write my script as : `infile = open("ALL.xml","r")` `contents = infile.read()` `soup = BeautifulSoup(contents,'xml')` then this error gives out : **UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 2034240: character maps to <undefined>** Im sorry Idont have any idea about this.. Do you ever face it before?
comment on: http://stackoverflow.com/a/51480460

http://stackoverflow.com/q/51478623
has body: I am having a lot of csv files, from which I have to extract the path and the headers. The python script that I am using for this purpose works like a charm: #!/usr/bin/python import os import csv thisdir = os.getcwd() # Create empty list for csvfiles csvfiles = [] # Extract file-paths and append them to "csvfiles" for r, d, f in os.walk(thisdir): # r=root, d=directories, f = files for file in f: if ".csv" in file: csvfiles.append(os.path.join(r, file)) # Create header-extraction function: def get_csv_headers(filename): with open(filename) as f: reader = csv.reader(f, delimiter=",") return next(reader) # Create empty list for headers headers=[] # Extract headers with the function and append them to "headers" list for l in csvfiles: headers.append(get_csv_headers(l)) with open('text.csv', 'w') as f: writer = csv.writer(f, delimiter=',') # In EU: use semicolon; else comma for path, header in zip(csvfiles, headers): writer.writerow(list(path.split("/")[1:]) + header) But! I just realized that some of the csv files is containing multiple tables! There is no consistency in how the tables is "separated" - some have multiple rows of space, and some none. The headers all contain letters and the table rows numbers (some followed by letters). It seems like a tedious task to go through all the +200 csv files to check if there is multiple tables in single csv files. Are you aware of any way where I quickly can identify which csv files contains multiple tables (command line or similar), extract headers of multiple tables in one csv - or other creative ideas where I don't have to open and go through all csv files. Any ideas (command line/python) are very (!) welcome! Thank you! Cheers, Birgitte
tagged with: unix
has answer: http://stackoverflow.com/a/51481560
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: command-line
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89951699
has comment: http://stackoverflow.com/comment/89932107
has title: Quickly identify multiple tables in csv-files?
type: Question
accepted answer: http://stackoverflow.com/a/51481560
score: 0
has comment: http://stackoverflow.com/comment/89929764
answer count: 1

http://stackoverflow.com/comment/89933968
has text: First impulse: use [`if __name__ == "__main__":`](https://stackoverflow.com/questions/419163/what-does-if-name-main-do) for your main thread, you may be creating more threads than you intend.
comment on: http://stackoverflow.com/q/51482153
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/57106028
answers question: http://stackoverflow.com/q/51425127
score: 4
upvote count: 4
has body: See here a variation on the one of sechilds. The site_coords are an input to the def. The apply function now uses 2 arguments: the row from the DataFrame and site_coords: import pandas as pd import numpy as np import geopy.distance def calc_distance(row, site_coords): station_coords = (row['lat'], row['lon']) d = geopy.distance.distance(site_coords, station_coords).km return(d) df['distance'] = df.apply(calc_distance, site_coords=(38.898556, -77.037852), axis=1)
downvote count: 0
type: Answer

http://stackoverflow.com/comment/90733244
score: 0
type: AnswerComment
has text: Note that this question is about macOS while your image is a Windows screenshot.
type: Comment
comment on: http://stackoverflow.com/a/51449121

http://stackoverflow.com/comment/89697947
type: Comment
has text: I should have clarified: `python -m pylint foo.py` was already working, but not `pylint foo.py`. Thanks for formulating the problem for me: "The command line entry point is not installed"! Anything I can do now that `pylint` is installed? I have tried reinstalling it, but the problem seems to persist. I guess now is the time for to actually start using virtual environments...
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51359991

http://stackoverflow.com/a/51330358
downvote count: 0
score: 1
has body: You can use str.join on the value in your dict before writing it to the csv. Ex: data_list_of_dx = [{'a_id':['NC01'],'org_id':['FX0'],'status':['Active','Current']}, {'a_id':['bC01'],'org_id':['dr0'],'status':['Dormant','Current']},{'a_id':['NC02'],'org_id':['TX0'],'status':['Active','Late']}, {'a_id':['ty01'],'org_id':['t00r0'],'status':['New','Current']}] fieldnames = ['a_id','org_id','status'] g_n = 'test_ct_data_2.csv' g = open( g_n , 'w', encoding = 'utf-8' , newline ='') writer = csv.DictWriter( g , fieldnames = fieldnames ) writer.writeheader() for row in data_list_of_dx: val = dict((k, ",".join(v)) for k, v in row.items()) writer.writerow(val) g.close() It is better to use with open() Ex: with open( g_n , 'w', encoding = 'utf-8' , newline ='') as g:
type: Answer
accepted answer of: http://stackoverflow.com/q/51330211
answers question: http://stackoverflow.com/q/51330211
has comment: http://stackoverflow.com/comment/89636761
upvote count: 1
has comment: http://stackoverflow.com/comment/89636806
has comment: http://stackoverflow.com/comment/89636627
type: AcceptedAnswer

http://stackoverflow.com/q/51477643
tagged with: dataflow
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has title: Getting an Error while trying to write data from Google PubSub to GCS using Apache Beam in Dataflow
tagged with: apache-beam
tagged with: python
tagged with: publish-subscribe
has body: I have written the below code to write the streaming data from pub sub and write it into google cloud storage. def run(): argv = [ '--project={0}'.format(PROJECT), '--job_name=mypubsubsample40', # '--save_main_session', '--staging_location=gs://abc/staging/', '--temp_location=gs://abc/staging/', '--runner=DataflowRunner', '--streaming' ] p = beam.Pipeline(argv=argv) lines = p | 'read_stream' &gt;&gt; beam.io.ReadStringsFromPubSub(subscription='projects/myprojectid 209306/subscriptions/mysub1',id_label="MESSAGE_ID") | 'write to file' &gt;&gt; beam.io.WriteToText('gs://bagdfs2/myout')` When i execute the same program as 'DirectRunner' then the files are created in GCS but when i execute the program using 'DataFlowRunner' it is not working. Moreover , when the pipeline is running in cloud dataflow , after a minute or so , im getting the below error in logs : java.util.concurrent.ExecutionException: java.lang.RuntimeException: Error received from SDK harness for instruction -1775: Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/apache_beam/runners/worker/sdk_worker.py", line 127, in _execute response = task() File "/usr/local/lib/python2.7/dist-packages/apache_beam/runners/worker/sdk_worker.py", line 162, in &lt;lambda&gt; self._execute(lambda: worker.do_instruction(work), work) File "/usr/local/lib/python2.7/dist-packages/apache_beam/runners/worker/sdk_worker.py", line 208, in do_instruction request.instruction_id) File "/usr/local/lib/python2.7/dist-packages/apache_beam/runners/worker/sdk_worker.py", line 227, in process_bundle self.data_channel_factory) File "/usr/local/lib/python2.7/dist-packages/apache_beam/runners/worker/bundle_processor.py", line 227, in __init__ self.ops = self.create_execution_tree(self.process_bundle_descriptor) File "/usr/local/lib/python2.7/dist-packages/apache_beam/runners/worker/bundle_processor.py", line 269, in create_execution_tree descriptor.transforms, key=topological_height, reverse=True)]) File "/usr/…
type: Question
has answer: http://stackoverflow.com/a/51680837
downvote count: 0
answer count: 1
tagged with: google-cloud-platform
score: 2

http://stackoverflow.com/a/51388356
has comment: http://stackoverflow.com/comment/89749347
accepted answer of: http://stackoverflow.com/q/51388327
has body: Since you already have a recursive function, you don't need to index the top-level nested list from the top, you just need to index the current ls parameter. For example, on the first match, ls is the same list as list1[0], so ls[2] = … does the same thing as list1[0][2] = …. So: def searchlist(ls): for i, element in enumerate(ls): if isinstance(element,list): searchlist(element) elif (element == 2): element += 3 ls[i] = element If you really did want to get a whole sequence of indexes, you'd need to build that up recursively, and then apply it either recursively or in a loop. Something like this: def searchlist(ls, *, _top=None, _indexes=()): if _top is None: _top = ls for i, element in enumerate(ls): if isinstance(element,list): searchlist(element, _top=_top, _indexes=_indexes + (i,)) elif (element == 2): element += 3 node = _top for index in _indexes: node = node[index] node[i] = element To understand this, notice that a multiple-indexed list as an assignment target is a little weird: lst[a][b][c] = d What this actually does is something like this: _tmp = lst[a][b] _tmp.__setitem__(c, d) In other words, the very last index is special, but all of the indices before it are treated as in a normal expression. So, that's why looping over node = node[index] for all indexes but the last one gives us the right thing to use with node[i] = ….
score: 3
answers question: http://stackoverflow.com/q/51388327
downvote count: 0
has comment: http://stackoverflow.com/comment/89750394
type: AcceptedAnswer
upvote count: 3
type: Answer

http://stackoverflow.com/comment/89758178
has text: Well I don't know about reducing the complexity, but given that you know N and M at runtime, you could generate a matrix for each point (which would be 40^2) of size N^2 and compute the value for each matrix. ***However***, like @unutbu pointed out, you did not mention the corner cases. Also, what happens to the future points if you toggle one of the values? Do you use the old one or the new toggled one? If the old one, my suggestion of making it embarrassingly parallel works, otherwise it breaks. So you may want to state that in your problem question.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51392673

http://stackoverflow.com/a/57446798
upvote count: 2
type: Answer
has body: I get the same error. after I searched in stackoverflow, but i can't find the answer. I copy the base.html file to templates/base.html and in all file call extends base.html. I writes {% extends '../base.html' %}.it run good for me. I hope everyone have same error can fix it (sorry about my english)
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51383786

http://stackoverflow.com/q/51423379
accepted answer: http://stackoverflow.com/a/51479588
type: AnsweredQuestion
tagged with: docker-compose
downvote count: 0
possible better answer: http://stackoverflow.com/a/67704710
has answer: http://stackoverflow.com/a/67704710
type: Question
score: 4
tagged with: docker
has body: Everytime I run docker-compose up on my machine (macOS 10.13.5, latest docker version) I get this error Traceback (most recent call last): File "docker-compose", line 6, in File "compose/cli/main.py", line 71, in main File "compose/cli/main.py", line 124, in perform_command File "compose/cli/command.py", line 41, in project_from_options File "compose/cli/command.py", line 126, in get_project File "compose/project.py", line 96, in from_config File "compose/network.py", line 320, in get_networks File "compose/network.py", line 125, in true_name File "compose/network.py", line 146, in _set_legacy_flag File "compose/network.py", line 106, in inspect File "site-packages/docker/utils/decorators.py", line 19, in wrapped File "site-packages/docker/api/network.py", line 211, in inspect_network File "site-packages/docker/utils/decorators.py", line 46, in inner File "site-packages/docker/api/client.py", line 194, in _get File "site-packages/requests/sessions.py", line 521, in get File "site-packages/requests/sessions.py", line 494, in request File "site-packages/requests/sessions.py", line 424, in prepare_request File "site-packages/requests/utils.py", line 195, in get_netrc_auth File "netrc.py", line 33, in init File "netrc.py", line 42, in _parse File "shlex.py", line 105, in get_token File "shlex.py", line 136, in read_token File "/Users/distiller/compose-osx-release/compose/venv/lib/python3.6/codecs.py", line 321, in decode UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 33: invalid start byte
linked to: http://stackoverflow.com/q/10418975
has answer: http://stackoverflow.com/a/73575291
has title: docker-compose up: utf-8 codec can't decode byte X
has answer: http://stackoverflow.com/a/51423509
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/60111921
answer count: 5
has comment: http://stackoverflow.com/comment/89825804
tagged with: python
upvote count: 4
has answer: http://stackoverflow.com/a/51479588

http://stackoverflow.com/a/51435432
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89842570
type: Answer
answers question: http://stackoverflow.com/q/51434949
has body: You just need to change the way of extracting address, tel and store hours import csv from bs4 import BeautifulSoup from requests import get url = 'http://www.cheers.com.sg/web/store_location.jsp' response = get(url) soup = BeautifulSoup(response.text, 'html.parser') # print (soup.prettify()) # open a file for writing location_data = open('data/soupdata.csv', 'w', newline='') # create the csv writer object csvwriter = csv.writer(location_data) cheers = soup.find('div', id="store_container") count = 0 # Loop for Header tags for paragraph in cheers.find_all('b'): header1 = paragraph.text.replace(':', '') header2 = paragraph.find_next('b').text.replace(':', '') header3 = paragraph.find_next_siblings('b')[1].text.replace(':', '') if count == 0: csvwriter.writerow([header1, header2, header3]) count += 1 break for paragraph in cheers.find_all('div'): label = paragraph.find_all('b') if len(label) == 3: print(label) address = label[0].next_sibling.next_sibling tel = label[1].next_sibling hours = label[2].next_sibling csvwriter.writerow([address, tel, hours]) location_data.close()
accepted answer of: http://stackoverflow.com/q/51434949

http://stackoverflow.com/a/53442311
type: Answer
has body: My answer might be a bit late since you have mentioned that your company decided to allow users only registered on your domain. However, I am still posting this for other users who might have this question. To solve this problem, you will need to have a basic login page that first stores the next_url that the user should be redirected to once the login is complete via your domain login or the OAuth login. Flask adds the next parameter in the URL when you use @login_required on the URL which should be allowed only for logged in users. You need to add session['next_url'] = request.args.get('next') in your login route to capture the next parameter and store it in the session as next_url. Now, in case of the OAuth login, once the user is redirected to the default redirect_url after successful login, you will read the next_url value from the session and redirect the user to that URL if it exists or else render the default page (usually the home page.) I am assuming 2 things, 1. that your default URL after OAuth login is successful is /home. This is set using the redirect_url of the make_provider_blueprint function in your case it is make_github_blueprint. Secondly, I am assuming your login page is the landing page for the user when they are not logged and it displays the GitHub login button which starts the OAuth login procedure. You might have to modify this flow slightly for your case to capture the next_url accordingly. I have shared the minimal code required to handle this situation below. Note that I pop the next_url value from the session before redirecting. This is so that in case the user tries to access the home page after the login, they should not be always redirected to the next_url if it exists in the session. bp_github = make_github_blueprint( client_id="...", client_secret="...", redirect_url="/home" ) @app.route("/login", methods=['GET', 'POST']) def login(): if current_user.is_authenticated: return flask.redirect(flask.url_for('/')) session['next_url'] =…
upvote count: 4
answers question: http://stackoverflow.com/q/51401455
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/93808642

http://stackoverflow.com/comment/89637664
score: 1
has text: There are additional questions to ask. What do you do if one or both lines contain duplicate rows, or if two rows have the same `Name` but different `City`s? What do you do if the order has changed?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51330932

http://stackoverflow.com/comment/89894395
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51462703
score: 0
has text: Little bit more information will make it a good question I am sure.

selenium-webdriver
tags question: http://stackoverflow.com/q/51387897
tags question: http://stackoverflow.com/q/51378032
tags question: http://stackoverflow.com/q/51470453
tags question: http://stackoverflow.com/q/51415674
tags question: http://stackoverflow.com/q/51349410
tags question: http://stackoverflow.com/q/51371495
tags question: http://stackoverflow.com/q/51418240
tags question: http://stackoverflow.com/q/51449271
tags question: http://stackoverflow.com/q/51327306
tags question: http://stackoverflow.com/q/51413646
tags question: http://stackoverflow.com/q/51388221
tags question: http://stackoverflow.com/q/51481989
tags question: http://stackoverflow.com/q/51476952
tags question: http://stackoverflow.com/q/51341655
tags question: http://stackoverflow.com/q/51448664
tags question: http://stackoverflow.com/q/51347987
tags question: http://stackoverflow.com/q/51468665
tags question: http://stackoverflow.com/q/51462870
tags question: http://stackoverflow.com/q/51372549
tags question: http://stackoverflow.com/q/51455748
tag name: selenium-webdriver
tags question: http://stackoverflow.com/q/51446471
tags question: http://stackoverflow.com/q/51435570
tags question: http://stackoverflow.com/q/51439377
tags question: http://stackoverflow.com/q/51402601
tags question: http://stackoverflow.com/q/51394441
tags question: http://stackoverflow.com/q/51448711
tags question: http://stackoverflow.com/q/51396727
tags question: http://stackoverflow.com/q/51377987
tags question: http://stackoverflow.com/q/51379181
tags question: http://stackoverflow.com/q/51470128
tags question: http://stackoverflow.com/q/51370650
tags question: http://stackoverflow.com/q/51419229
tags question: http://stackoverflow.com/q/51446521
tags question: http://stackoverflow.com/q/51326388
tags question: http://stackoverflow.com/q/51421807
tags question: http://stackoverflow.com/q/51346347
tags question: http://stackoverflow.com/q/51450667
tags question: http://stackoverflow.com/q/51375321
tags question: http://stackoverflow.com/q/51427008
tags question: http://stackoverflow.com/q/51359119
type: Tag
tags question: http://stackoverflow.com/q/51442191
tags question: http://stackoverflow.com/q/51411414
tags question: http://stackoverflow.com/q/51468802
tags question: http://stackoverflow.com/q/51405048
tags question: http://stackoverflow.com/q/51478583
tags question: http://stackoverflow.com/q/51366984
tags question: http://stackoverflow.com/q/51398848
tags question: http://stackoverflow.com/q/51418354

http://stackoverflow.com/q/51461115
tagged with: input
tagged with: python
tagged with: utf-8
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89892891
upvote count: 3
type: Question
score: 3
has answer: http://stackoverflow.com/a/51461734
has title: Python Strings, Default Encoding and Decoding (UTF-8?)
answer count: 1
downvote count: 0
tagged with: string
tagged with: unicode
favorite count: 0
accepted answer: http://stackoverflow.com/a/51461734
has body: Based on my own readings (including this article), it seems that by default Python encodes with UTF-8. Strings are read in under the assumption that they're in UTF-8 encoding (more source). Those strings are then translated to plain Unicode, using Latin-1, UCS-2, or UCS-4 for the entire string depending on the highest code point of UTF-8 it encounters. This seems to match what I've done on the terminal. The character Ǧ has Unicode code point of 486, and can only be fit in UCS-2. string1 = "Ǧ" sys.getsizeof(string1) # This prints 76 string1 = "Ǧa" sys.getsizeof(string1) # This prints 78, as if 'a' takes two bytes string2 = "a" sys.getsizeof(string2) # This prints 50 string2 = "aa" sys.getsizeof(string2) # This prints 51, as if 'a' takes one byte I have two questions. First off, when printing to terminal, what is the process with which strings are encoded and decoded? If we call print(), are the strings first encoded to UTF-8 (from UCS-2 or Latin-1 in our examples), where the system decodes it to print to screen? Second off, what's with the large initial increment in the size? Why do strings represented with Latin-1 have an initial size of 49, while strings with UCS-2 have an initial size of 74? Thanks!

http://stackoverflow.com/comment/89760818
comment on: http://stackoverflow.com/a/51394825
score: 0
type: AnswerComment
has text: Can you explain the logic?
type: Comment

http://stackoverflow.com/comment/89920881
type: QuestionComment
has text: That looks good already. You could use tensordot at the last step for possibly some improvement, but that's not the bottleneck, so won't change the timings much.
comment on: http://stackoverflow.com/q/51475114
score: 0
type: Comment

http://stackoverflow.com/comment/89894069
has text: Also note that Using range(1,int(round((prod+1)**0.5))) will /not/ work for edge cases. For instance, when prod=36, we want to iterate over the elements 1 through 6 inclusive; however, prod+1 == 37, and the square root of that rounds to 6, which range will /exclude/.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51457261
type: Comment

http://stackoverflow.com/q/51375447
type: Question
has body: i am working with raspberry pi (python), i wanted to start reading a file at specific time of the the day, but the problem every time i try to compare between real time and my required time i don't get any thing and sometimes i get. typeerror:c an't compare datetime.time to str import datetime import time timee = (" %s" %time.strftime("%H:%M:%S")) t = datetime.time(14, 30, 00) t1 = datetime.time(15, 30, 00) if (timee &gt;= t and timee &lt;= t1): print ('this is right')
has answer: http://stackoverflow.com/a/51375603
has title: how to compare between now time and chosen time
answer count: 3
tagged with: compare
downvote count: 0
linked to: http://stackoverflow.com/q/415511
favorite count: 0
linked to: http://stackoverflow.com/q/10048249
has answer: http://stackoverflow.com/a/51375772
tagged with: time
tagged with: python
duplicate of: http://stackoverflow.com/q/10048249
accepted answer: http://stackoverflow.com/a/51375603
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51375547
score: 1
has answer: http://stackoverflow.com/a/51375547
upvote count: 1
has comment: http://stackoverflow.com/comment/89723667

http://stackoverflow.com/q/51439138
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/58703430
tagged with: python
has answer: http://stackoverflow.com/a/56223263
answer count: 4
tagged with: python-tesseract
upvote count: 3
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/71013016
has title: raise "pytesseract.pytesseract.TesseractError: (3221225477, '')"
has body: I got the following error when I tried to find out the Chinese words in a picture by python: (By the way, I had already had "chi_sim.traineddata" training file in tessdata directory and got a successful try to find out English sentences in a picture, so this error really confused me.) *C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\python.exe E:/PKU1.3/python_math/set_for_recognition.py Traceback (most recent call last): File "E:/PKU1.3/python_math/set_for_recognition.py", line 5, in &lt;module&gt; text=pytesseract.image_to_string(Image.open('climb_high.jpeg'),lang='chi_sim') File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pytesseract\pytesseract.py", line 295, in image_to_string return run_and_get_output(*args) File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pytesseract\pytesseract.py", line 203, in run_and_get_output run_tesseract(**kwargs) File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pytesseract\pytesseract.py", line 179, in run_tesseract raise TesseractError(status_code, get_errors(error_string)) pytesseract.pytesseract.TesseractError: (3221225477, '')*
has answer: http://stackoverflow.com/a/51664412
score: 3
type: Question

http://stackoverflow.com/a/51926441
has body: You can use regular expressions to define a search pattern that contains multiple keywords. import re pattern = r"\beye\s?bleach|\bcat\b|\dog\b" match = r.search(pattern, comment.body) if match: do stuff This example searches 'comment.body' for the keywords "eyebleach", "eye bleach", "cat" and "dog". '\b' is for a whitespace character, so we are actually looking for " eyebleach " surrounded by spaces. match = True if any one of these words is found.
answers question: http://stackoverflow.com/q/51462727
score: 0
type: Answer

http://stackoverflow.com/q/51432860
has comment: http://stackoverflow.com/comment/89840202
type: Question
has answer: http://stackoverflow.com/a/51466232
answer count: 1
tagged with: django-rest-framework
score: 0
has body: I've started a new Django project and like the documentation recommends I've created a custom user model just in case it's needed and made sure to set AUTH_USER_MODEL in settings. from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass I notice that when you do this you cannot run python manage.py makemigrations you actually have to specify the app the custom user model is in python manage.py makemigrations &lt;appname&gt;. Once I do that I'm able to start the server. I followed this post to integrate JWT into my new project: Django React JWT Without the custom user model the post works great but once I add in a custom user model I start getting these errors: Traceback (most recent call last): File "/Users/.local/share/virtualenvs/api-RqAznZCl/lib/python3.7/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/Users/.local/share/virtualenvs/api-RqAznZCl/lib/python3.7/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/.local/share/virtualenvs/api-RqAznZCl/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/.local/share/virtualenvs/api-RqAznZCl/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/.local/share/virtualenvs/api-RqAznZCl/lib/python3.7/site-packages/django/views/generic/base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "/Users/.local/share/virtualenvs/api-RqAznZCl/lib/python3.7/site-packages/rest_framework/views.py", line 483, in dispatch response = self.handle_exception(exc) File "/Users/.local/share/virtualenvs/api-RqAznZCl/lib/python3.7/site-packages/rest_framework/views.py", line 443, in handle_exception self.raise_uncaught_exception(exc) File "/Users/.loc…
tagged with: django-rest-framework-jwt
tagged with: python
type: UnansweredQuestion
has title: Having trouble using JWT with a custom User model in Django
tagged with: django
has comment: http://stackoverflow.com/comment/95937522

http://stackoverflow.com/comment/89841173
comment on: http://stackoverflow.com/a/51435444
has text: so when i unpack the dict via `**{u:q}` it basically converts it to `u=q`??? instead of writing `timedelta(**{unit_of_measurement: quantity_of_units} = quantity_of_units)`, i can just write `timedelta(**{unit_of_measurement: quantity_of_units})`??
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51342354
upvote count: 1
tagged with: tensorflow
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51343368
tagged with: linear-regression
has comment: http://stackoverflow.com/comment/89658498
score: 1
tagged with: numpy
has answer: http://stackoverflow.com/a/51343368
answer count: 1
downvote count: 0
has title: ValueError: Cannot feed value of shape (2,) for Tensor 'Placeholder:0', which has shape '(1, 2)'
has comment: http://stackoverflow.com/comment/89659958
tagged with: python
has comment: http://stackoverflow.com/comment/89659240
favorite count: 0
has body: I'm new to tensorflow and trying to create a linear regression model. My code is import numpy as np import tensorflow as tf bias = np.ones((50, 1)) trainX = np.arange(0, 10, 0.2).reshape(50, 1) trainY = (3 * trainX + np.random.rand(trainX.shape[0]) * 20 - 10) + 10 trainX = np.append(bias, trainX, axis=1) X = tf.placeholder("float", shape=(1, 2)) Y = tf.placeholder("float") w = tf.Variable([[0.0, 0.0]], name="weights") model = tf.matmul(X, tf.transpose(w)) cost = tf.pow((Y - model), 2) init = tf.global_variables_initializer() train_op = tf.train.GradientDescentOptimizer(0.01).minimize(cost) with tf.Session() as sess: sess.run(init) for i in range(50): for (x, y) in zip(trainX, trainY): sess.run(train_op, feed_dict={X: x, Y: y}) print(sess.run(w)) I don't know what I'm doing wrong. I think the problem is in initializing weights. The idea is simple to predict two weight constants which best predict the line fitting the data. I'm getting this error in colaboratory notebook
tagged with: machine-learning

http://stackoverflow.com/q/51419598
answer count: 4
has comment: http://stackoverflow.com/comment/89810252
favorite count: 0
has answer: http://stackoverflow.com/a/51419909
has answer: http://stackoverflow.com/a/51419893
has comment: http://stackoverflow.com/comment/89810296
type: UnansweredQuestion
downvote count: 2
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51419808
tagged with: conditional-statements
has body: I am making a login page in which I have to cover all the login test scenarios. I am am validating all type of input the user is putting, but the problem is when a while condition handles one test condition, that same while condition is not repeated after the another while condition runs. if the same test condition occurs again after user puts the same input value after another type of input value. Here is my code: import re userDetails=[] accountDetails= {"FirstName": "Ajay", "LastName": "Kumar","DateOfBirth":"24-07-1992","Account Number":"4242342345234","Balance Currency":"Rs","Balance Amount":"5000"} specialCharacters = re.compile('[@_!#$%^&amp;*()&lt;&gt;?/\|}{~:]') firstName=str(input("Enter First Name")) while True: if firstName=="": print("Name cannot be blank") firstName=str(input("Enter First Name")) while True: if firstName.isdigit(): print("Name cannot be in digits") firstName=str(input("Enter First Name")) while True: if specialCharacters.search(firstName) != None: print("Please don't enter special characters") firstName=str(input("Enter First Name")) while True: if firstName!=accountDetails.get("FirstName"): print("The account does not exist with the given details, please try again") print("Enter valid first name") firstName=str(input("Enter First Name")) else: userDetails.append(firstName)
score: -1
tagged with: loops
has title: Repeat a while condition in python
type: Question
tagged with: if-statement
tagged with: while-loop
has answer: http://stackoverflow.com/a/51419762

http://stackoverflow.com/q/51327767
tagged with: python
has comment: http://stackoverflow.com/comment/89630914
possible better answer: http://stackoverflow.com/a/58581266
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89662492
has answer: http://stackoverflow.com/a/58581266
has body: I'm about to start some Python Data analysis unlike anything I've done before. I'm currently studying numpy, but so far it doesn't give me insight on how to do this. I'm using python 2.7.14 Anaconda with cx_Oracle to Query complex records. Each record will be a unique individual with a column for Employee ID, Relationship Tuples (Relationship Type Code paired with Department number, may contain multiple), Account Flags (Flag strings, may contain multiple). (3 columns total) so one record might be: [(123456), (135:2345678, 212:4354670, 198:9876545), (Flag1, Flag2, Flag3)] I need to develop a python script that will take these records and create various counts. The example record would be counted in at least 9 different counts How many with relationship: 135 How many with relationship: 212 How many with relationship: 198 How many in Department: 2345678 How many in Department: 4354670 How many in Department: 9876545 How many with Flag: Flag1 How many with Flag: Flag2 How many with Flag: Flag3 The other tricky part of this, is I can't pre-define the relationship codes, departments, or flags What I'm counting for has to be determined by the data retrieved from the query. Once I understand how to do that, hopefully the next step to also get how many relationship X has Flag y, etc., will be intuitive. I know this is a lot to ask about, but If someone could just point me in the right direction so I can research or try some tutorials that would be very helpful. Thank you!
type: Question
tagged with: numpy
has title: Python Data Analysis from SQL Query
tagged with: analytics
accepted answer: http://stackoverflow.com/a/51328129
score: 0
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/89633930
has answer: http://stackoverflow.com/a/51328129

http://stackoverflow.com/q/51411837
upvote count: 3
tagged with: python
accepted answer: http://stackoverflow.com/a/51411918
downvote count: 1
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/51398353
has title: How do I keep a Python application running in an EC2 instance?
has answer: http://stackoverflow.com/a/51411918
type: Question
possible better answer: http://stackoverflow.com/a/51411889
answer count: 2
tagged with: amazon-ec2
favorite count: 0
has body: I have a python application which I uploaded to an EC2 instance as a file named "example.py". I want this code to be running continuously, as it has a while loop that calls a 3rd party Twitter API every minute. If I run "python3 example.py", and close the terminal, the SSH session terminates. Will the python application continue running in that EC2 instance? How can I make that sure? Thanks.
tagged with: terminal
has comment: http://stackoverflow.com/comment/89797861
tagged with: ssh
has answer: http://stackoverflow.com/a/51411889

http://stackoverflow.com/comment/89717741
type: QuestionComment
type: Comment
has text: Yeah I have files which ends with .jpg in C:\NONE directory. I have called send in main function. Still I am not able to send mail. -- abarnert
score: 0
comment on: http://stackoverflow.com/q/51372927

gmail
type: Tag
tags question: http://stackoverflow.com/q/51388607
tags question: http://stackoverflow.com/q/51374839
tags question: http://stackoverflow.com/q/51387353
tags question: http://stackoverflow.com/q/51468295
tag name: gmail

http://stackoverflow.com/q/51425642
has answer: http://stackoverflow.com/a/51426173
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/89822545
has answer: http://stackoverflow.com/a/51425816
has answer: http://stackoverflow.com/a/51425862
has body: I have a vector of growing integers: data = np.arange(6) + 1 I want to organize it in a bigger vector to the following indices: dataIdx = np.array([1, 1, 0, 1, 1, 0, 0, 1, 1]) The result would then be: array([1, 2, 0, 3, 4, 0, 0, 5, 6]) I can use a for-loop, but I am looking for a one-liner or two-liners.
tagged with: numpy
answer count: 4
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51426924
has title: vector manipulation in python
has comment: http://stackoverflow.com/comment/89822758
has comment: http://stackoverflow.com/comment/89822414
has comment: http://stackoverflow.com/comment/89822425
type: Question

http://stackoverflow.com/q/51340223
score: 2
has answer: http://stackoverflow.com/a/51417343
downvote count: 0
tagged with: django
has title: Django sort on paginated results
type: Question
tagged with: pagination
has body: I am creating a list view in Django 2 using CBV. The pagination is working however I am now trying to add sorting to my pagination. This sorting will work whereby when the user selects a column, it will append a GET query string and then when I render my view, I will order_by the QueryResult. This is working however I am now only fetching 4 entries (my current page) as opposed to the entire set. My problem is that I need it to filter only on the current page results but then return the current page and the rest of the results. This is my current solution: class AccountList(ListView): ordering_dict = { 'pk':'asc', 'is_active':'asc','created':'asc' } template_name = "marketing/comm_list.html" context_object_name = 'comms' paginate_by = 4 def get_queryset(self): type_filter = self.request.GET.get('type', 'all') queryset = Comm.objects.values('pk', 'name', 'is_active', 'created') page_field = self.request.GET.get('page') paginator = Paginator(queryset, 4) try: pages = paginator.page(page_field) except PageNotAnInteger: pages = paginator.page(1) except EmptyPage: pages = paginator.page(paginator.num_pages) start_index = pages.start_index() end_index = pages.end_index() queryset = Comm.objects.values('pk', 'name', 'is_active', 'created').filter(pk__gte=start_index, pk__lte=end_index) order_by_field = self.request.GET.get('order_by') if order_by_field: if self.ordering_dict[order_by_field] == 'asc': self.ordering_dict[order_by_field] = 'desc' else: self.ordering_dict[order_by_field] = 'asc' order_by_field = '-'+order_by_field queryset = queryset.order_by(order_by_field) else: queryset = queryset.order_by('-created') return queryset Any help is appreciated, I am using Django 2 and Python 3.6. Thanks! The general issue is that I want to be able to sort by column only on the current page of my paginated results
upvote count: 2
answer count: 2
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51340638
tagged with: python
has comment: http://stackoverflow.com/comment/89805808

http://stackoverflow.com/a/51345815
score: 0
answers question: http://stackoverflow.com/q/51345748
type: Answer
has body: "python filename.py" should run your python code. If you wish to specifically run the program using python 3.6 then it would be "python3.6 filename.py".

http://stackoverflow.com/q/51369083
has body: I try to raise more than one exception in an if-else branch: The code is the following: x = input() try: if int(x) &lt; 0: # the number should not be a negative number raise("This is a negative number.") if int(x) &gt;= 4: print("That a lot.") else: print("That is not so much.") except ValueError: # the input should be a other than a number print("You did not entered a number.") The following error message occurs: TypeError: exceptions must derive from BaseException
answer count: 1
downvote count: 1
favorite count: 0
tagged with: exception
has comment: http://stackoverflow.com/comment/89710490
tagged with: python
upvote count: 0
type: UnansweredQuestion
has title: How to raise more than one exception in python
has answer: http://stackoverflow.com/a/51369168
tagged with: if-statement
score: -1
type: Question

http://stackoverflow.com/a/51338557
type: Answer
has comment: http://stackoverflow.com/comment/89655836
upvote count: 1
has body: I took a look at the code and it doesn't seem to account for bits past the b'th bit. So, I added another addition. (Unless all you want is up to the b'th bit): def bit_rev (x, b): # reverse b lower bits of x return (x &gt;&gt; b &lt;&lt; b) + sum(1 &lt;&lt; (b - 1 - i) for i in range (0, b) if (x &gt;&gt; i) &amp; 1) Now for the explaining the logic. x &gt;&gt; b &lt;&lt; b So, let's say we're using 5 (as x) in this example with 2 as b. The binary representation of 5 is 101. So, we want to switch only the last 2 bits. Which is 01. However, in our other code we are swapping them, but we are ignoring the bits past b. So, we are ignoring the first (from left to right) 1. Now the first operations: x &gt;&gt; b in our case is 5 &gt;&gt; 2. 101 moving to the right 2 is 1, since we end up chopping off the 01. Next we shift it back. We are guaranteed (in Python) to get 0's back from the bit shift, so we now have 100, or 4. Now for the meaty part, sum(1 &lt;&lt; (b - 1 - i) for i in range (0, b) if (x &gt;&gt; i) &amp; 1) It's probably would be easier to understand this outside of a list comprehension, so I rewrote it as a for-loop. summation = 0 for i in range (0, b): if (x &gt;&gt; i) &amp; 1: summation += 1 &lt;&lt; (b - 1 - i) Basically on each iteration we are finding the reverse bit an then adding it to the total (summation). This code seems to be kind of difficult to understand because there is a lot going on. Let's start with the for loop itself. for i in range (0, b) is iterating over all values between 0 and b. (Or the last bit you want to change). All the reversing happens later on in the code. Next we check to see if the bit we are going to swap is a 1. In binary only 1's add value to the total number, so its logical to ignore all 0's. In if (x &gt;&gt; i) &amp; 1:. We bitshift x to the right i bits. So, 101 bit shifted to the right 1 bit is 10. We now check to see if that last bit is a 1 by doing &amp; 1. Basically what &amp; 1 does in this program is ignore all…
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51334865
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51334865

http://stackoverflow.com/comment/89833464
comment on: http://stackoverflow.com/a/51430917
has text: Please, take a look at my answer, I edit it to do what you want
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89784266
has text: Oh thank you so much that's interesting how you've done cuz I tried multidimensional loop.First loop for members then for profile and then status text
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51404425
type: AnswerComment

enums
tags question: http://stackoverflow.com/q/51419590
tag name: enums
tags question: http://stackoverflow.com/q/51410366
tags question: http://stackoverflow.com/q/51428697
type: Tag

http://stackoverflow.com/q/51330856
has body: I am working with a very large set of data (Leukemia Cancer) for my thesis and i have to process all of them. The condition is something like i have an excel file where there are 20 patients name in the columns, and they have 2000 rows of data for each of them, now i have to find the maximum and minimum value in each column meaning for each patient, Then subtract the minimum value from the maximum and then divide it by .5 and export the value for each patient, I am using Pandas. i was able to find the max and min value using data.max(), data.min() for exporting the values i used - data.min().to_csv('min.csv') and data.max().to_csv('max.csv') which is two separate file. Now what i need to do is make sure there is only one file with two column showing maximum and minimum value side by side and also the value after subtraction in the third column and the final value after dividing in the last. Sample data: Patient No Patient1 Patient2 Patient3 Patient4 gene data1 5614.705569 6446.177102 5756.830799 5498.327075 gene data2 592.8588927 401.8615001 459.7095671 619.2129817 gene data3 246.4022014 238.535468 261.7679828 207.4747361 gene data4 1273.25497 1318.80054 1338.271733 1221.564705 gene data5 51.0906811 37.07419033 26.28092875 37.12742504 gene data6 756.0119839 867.248239 956.754366 864.2708979 gene data7 168.4100068 153.3151275 136.5111169 205.8874617 gene data8 183.0011027 277.4930516 191.5097325 140.7178783 gene data9 1334.627713 1480.547871 688.3688018 3269.536931 Final output: I hope This clear what i am trying to Do. Finding the Maximum and Minimum value for Each Patient Column From 2000 Rows of Data, Then Using this formula 0.9/Max-Min and export all the data for each patient in a csv in column. I am sorry i just started using Python. So any help will be highly appreciated.
score: 0
has title: Subtracting values of one column from another using Pandas
tagged with: pandas
answer count: 1
tagged with: jupyter
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51331213
has comment: http://stackoverflow.com/comment/89637400
has comment: http://stackoverflow.com/comment/89637706
type: Question

http://stackoverflow.com/q/51344930
has title: Can't run exe file which is created by pyinstaller
answer count: 2
score: 0
has answer: http://stackoverflow.com/a/51345069
tagged with: python-3.7
tagged with: pyinstaller
tagged with: python
has body: I use Pycharm to write the .py source code, it works fine when I use "Run" in Pycharm. After I finishing writing the source code, I want to use Pyinstaller to pack the code to the executable file, the packing process works fine and the .exe file is created. But when I double-click the executable file, there is no any reaction. Don't know what's wrong, please help me. Pyinstaller created a warning report in txt file, but I don't think that's the main reason, I attached it at the bottom anyway. (venv) D:\Dropbox\Project\Pycharm Projects\biaobai&gt;pyinstaller -F -w -i aixin.ico main.py 1405 INFO: PyInstaller: 3.3.1 1411 INFO: Python: 3.7.0 1413 INFO: Platform: Windows-10-10.0.17134-SP0 1418 INFO: wrote D:\Dropbox\Project\Pycharm Projects\biaobai\main.spec 1431 INFO: UPX is not available. 1448 INFO: Extending PYTHONPATH with paths ['D:\\Dropbox\\Project\\Pycharm Projects\\biaobai', 'D:\\Dropbox\\Project\\Pycharm Projects\\biaobai'] 1449 INFO: checking Analysis 1449 INFO: Building Analysis because out00-Analysis.toc is non existent 1450 INFO: Initializing module dependency graph... 1455 INFO: Initializing module graph hooks... 1458 INFO: Analyzing base_library.zip ... 6290 INFO: running Analysis out00-Analysis.toc 6321 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable required by D:\Dropbox\Project\Pycharm Projects\biaobai\venv\Scripts\python.exe 8194 INFO: Caching module hooks... 8206 INFO: Analyzing D:\Dropbox\Project\Pycharm Projects\biaobai\main.py 9513 INFO: Loading module hooks... 9513 INFO: Loading module hook "hook-encodings.py"... 9628 INFO: Loading module hook "hook-PIL.Image.py"... 10335 INFO: Processing pre-find module path hook distutils 10591 INFO: Loading module hook "hook-PIL.py"... 10607 INFO: Excluding import 'PySide' 10609 INFO: Removing import of PySide from module PIL.ImageQt 10611 INFO: Import to be excluded not found: 'FixTk' 10612 INFO: Excluding import 'tkinter' 10614 INFO: Removing import of tkinter from…
has comment: http://stackoverflow.com/comment/89671664
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51349871
linked to: http://stackoverflow.com/q/48872724
has comment: http://stackoverflow.com/comment/89671603

http://stackoverflow.com/comment/95274951
score: 0
type: Comment
type: QuestionComment
has text: @sona no. The question was also posted to the QtForum but this forum currently appears to be down: https://forum.qt.io/topic/93012/how-do-i-specify-which-of-2-versions-of-the-qt-libs-should-be-used
comment on: http://stackoverflow.com/q/51371421

http://stackoverflow.com/a/51537498
accepted answer of: http://stackoverflow.com/q/51376652
answers question: http://stackoverflow.com/q/51376652
has comment: http://stackoverflow.com/comment/90065005
type: Answer
has body: SQLAlchemy does not immediately update Foreign Key fields when relationship attributes are changed. So the answer to your question is that the before_flush event is triggered before SQLAlchemy updates the Foreign Key value of the Employee instance as part of the flush operation. In the case where you specifically update the manager_id attribute yourself, the attribute is altered prior to the before_flush event being triggered which is why you see the change in your _emp_history_update function in that case. You can still do everything that you want using the after_flush event as session.dirty hasn't been cleared out by that point. So I changed your event listener to this: @event.listens_for(session, 'after_flush') def _emp_history_update(session, flush_context): for instance in session.dirty: if not isinstance(instance, Employee): continue man_hist = get_history(instance, 'manager_id') if man_hist.added: if man_hist.deleted: man_deleted = str(man_hist.deleted[0]) else: man_deleted = None emp_man_hist = EmpManHist(emp_id=instance.emp_id, man_id_from=man_deleted, man_id_to=str(man_hist.added[0])) session.add(emp_man_hist) And this was the test code: emp1 = Employee(emp_id='1', name="AAA") emp2 = Employee(emp_id='2', name="BBB", manager_id='1') emp3 = Employee(emp_id='3', name="CCC", manager_id='1') # I'm not using your DataAccessLayer object but that doesn't change anything session.add_all([emp1, emp2, emp3]) # i've not explicitly called session.flush() as it's called by session.commit() anyway session.commit() # change the emp2's manager through relationship attribute emp2.manager = emp3 # no need to re-add the Employee objects to the session session.commit() for change in session.query(EmpManHist).all(): print(f'Employee {change.emp_id} changed to mgr_id {change.man_id_to}') Which outputs: Employee 2 changed to mgr_id 3 One more thing that I've noticed is that in this section of your event listener: if man_hist.added: if man_hist.deleted: man_deleted = str(man_hist.…
score: 9
upvote count: 9
has comment: http://stackoverflow.com/comment/90060430
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89926543
type: QuestionComment
comment on: http://stackoverflow.com/q/51478980
score: 0
type: Comment
has text: I don't think this is specific to Python. If I understand correctly, the shell decides how characters sent to stdout are displayed. You'd see the same behavior in a C or Java program.

http://stackoverflow.com/a/51351765
score: 3
has body: Well, at first I thought that's impossible to do because pytest-django imports a lot of django stuff on module level already, and you can't beat that by plugging yourself via hooks - they are all executed after the plugins are loaded via entry points, so django will be already imported by then. However, looking at pytest --help, notice a rarely used option that turns out to be helpful in this case: $ pytest --help ... test session debugging and configuration: -p name early-load given plugin (multi-allowed). To avoid loading of plugins, use the `no:` prefix, e.g. `no:doctest`. Run pymysql configuration via plugin early loading So custom plugins passed via -p arg will be imported earlier than the ones loaded via entrypoints. The solution is now easy: write a small module that imports and configures pymysql and pass it via -p arg: # rematch/pymysql_hack.py import pymysql pymysql.install_as_MySQLdb() Tests invocation: $ PYTHONPATH=. pytest -p pymysql_hack -rapP server tests/server I forked the rematch project to test this out, the jobs are looking good (the first job fails because I was too lazy to add pymysql in all the requirements files). Give up pytest, use manage.py test Alternatively (this was my first solution proposal), you can run tests via manage.py, so you could add the pymysql configuration lines on top of manage.py, implement a custom test runner as described in pytest-django's FAQ: pytest-django is designed to work with the pytest command, but if you really need integration with manage.py test, you can create a simple test runner like this: class PytestTestRunner(object): """Runs pytest to discover and run tests.""" def __init__(self, verbosity=1, failfast=False, keepdb=False, **kwargs): self.verbosity = verbosity self.failfast = failfast self.keepdb = keepdb def run_tests(self, test_labels): """Run pytest and return the exitcode. It translates some of Django's test command option to pytest's. """ import pytest argv = [] if self.verbosity == 0: argv.append…
has comment: http://stackoverflow.com/comment/89725069
accepted answer of: http://stackoverflow.com/q/51350559
upvote count: 3
answers question: http://stackoverflow.com/q/51350559
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89690682
has comment: http://stackoverflow.com/comment/89723854
type: Answer
has comment: http://stackoverflow.com/comment/89685598
has comment: http://stackoverflow.com/comment/89726123

http://stackoverflow.com/q/51335911
has answer: http://stackoverflow.com/a/51344513
upvote count: 1
possible better answer: http://stackoverflow.com/a/51336073
type: AnsweredQuestion
has body: I am developing a application in python which gives job recommendation based on the resume uploaded. I am trying to tokenize resume before processing further. I want to tokenize group of words. For example Data Science is a keyword when i tokenize i will get data and science separately. How to overcome this situation. Is there any library which does these extraction in python?
tagged with: tokenize
score: 1
type: Question
answer count: 2
has title: How to Tokenize group of words in Python
downvote count: 0
has answer: http://stackoverflow.com/a/51336073
accepted answer: http://stackoverflow.com/a/51344513
tagged with: python
tagged with: nlp
favorite count: 0

http://stackoverflow.com/a/51340714
downvote count: 0
has body: I think you need: df2 = pd.DataFrame({'Average Monthly Wage $': ['736[4]','7336[445]', '[4]345[5]']}) print (df2) Average Monthly Wage $ 0 736[4] 1 7336[445] 2 [4]345[5] df2['Average Monthly Wage $'] = df2['Average Monthly Wage $'].str.replace(r'\[.*?\]','') print (df2) Average Monthly Wage $ 0 736 1 7336 2 345 regex101.
accepted answer of: http://stackoverflow.com/q/51340686
type: AcceptedAnswer
type: Answer
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/89655029
answers question: http://stackoverflow.com/q/51340686

http://stackoverflow.com/comment/90204381
score: 0
comment on: http://stackoverflow.com/q/51401442
has text: I have the impression the last plot shown in the answer is what you're asking about. Should this not be the case, would you be able to point more prominently to where exactly the problem lies or what should be different?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51408615
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51408724
accepted answer: http://stackoverflow.com/a/51408724
type: Question
has body: I'm trying to call the video contact sheet module from within a python script, but for my life of it, I can't figure it out. When I call it through command line, it works fine: vcsi "C:\Users\testuser\Dropbox\Python\TestData\test.mp4" -t -w 850 -g 3x5 --end-delay-percent 20 -o c:\temp\output.png How would I call the same process from with my python script (Python 3.5)? I tried calling through subprocess, exec, etc, but I can't get it to run. Thanks for all your help!
score: 0
answer count: 1
has title: using vcsi (video contact sheets) from within python code
tagged with: command-line

http://stackoverflow.com/q/51480756
has body: I'm new to programming. I have written code for the rock paper scissors game but there is one bug that I can't seem to fix. When the game closes, the user is asked if he wants to play again. If the user answers yes the first time, then plays again then answers no the second time, the computer for some reason asks the user again if he wanted to play again. The user must enter no in this case. This is because although the user answers no, the answer gets reset to yes and goes over again. How can this be fixed? # This code shall simulate a game of rock-paper-scissors. from random import randint from time import sleep print "Welcome to the game of Rock, Paper, Scissors." sleep(1) def theGame(): playerNumber = 4 while playerNumber == 4: computerPick = randint(0,2) sleep(1) playerChoice = raw_input("Pick Rock, Paper, or Scissors. Choose wisely.: ").lower() sleep(1) if playerChoice == "rock": playerNumber = 0 elif playerChoice == "paper": playerNumber = 1 elif playerChoice == "scissors": playerNumber = 2 else: playerNumber = 4 sleep(1) print "You cookoo for coco puffs." print "You picked " + playerChoice + "!" sleep(1) print "Computer is thinking..." sleep(1) if computerPick == 0: print "The Computer chooses rock!" elif computerPick == 1: print "The Computer chooses paper!" else: print "The Computer chooses scissors!" sleep(1) if playerNumber == computerPick: print "it's a tie!" else: if playerNumber &lt; computerPick: if playerNumber == 0 and computerPick == 2: print "You win!" else: print "You lose!" elif playerNumber &gt; computerPick: if playerNumber == 2 and computerPick == 0: print "You lose!" else: print "You win!" replay() def replay(): sleep(1) playAgain = "rerun" while playAgain != "no": playAgain = raw_input("Would you like to play again?: ").lower() if playAgain == "yes": sleep(1) print "Alright then brotha." sleep(1) theGame() elif playAgain == "no": sleep(1) print "Have a good day." sleep(1) print "Computer shutting down..." sleep(1) else: sleep(1) print "Wha…
type: AnsweredQuestion
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51480908
accepted answer: http://stackoverflow.com/a/51480908
score: -1
has comment: http://stackoverflow.com/comment/89930591
answer count: 2
has title: Rock Paper Scissors Running Twice Error
upvote count: 0
has answer: http://stackoverflow.com/a/51480852
has comment: http://stackoverflow.com/comment/89930240
favorite count: 0
possible better answer: http://stackoverflow.com/a/51480852
tagged with: python
has comment: http://stackoverflow.com/comment/89931185

http://stackoverflow.com/comment/110115479
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51341124
has text: for page break you can use css page-break-after:always; give this to one dive which has all content end it when you want new page
score: 0

http://stackoverflow.com/comment/89628112
has text: Thanks, that is very useful but I have a problem with the first example, returns: `UnsortedIndexError: 'MultiIndex Slicing requires the index to be fully lexsorted tuple len (3), lexsort depth (1)'`. Could you also write code for a loop? I want to make some calculations over columns without making new data structures.
comment on: http://stackoverflow.com/a/51326399
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51462940
answers question: http://stackoverflow.com/q/51462870
type: AcceptedAnswer
downvote count: 0
has body: You need to update your chromedriver.exe to latest version. Now you are using old chromedriver version (Session info: chrome=67.0.3396.99) (Driver info: chromedriver=2.27.440174) You need to use : (ChromeDriver 2.39) (Supports Chrome v66-68) Please refe this link :- chroemdriver latest version updates
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51462870

http://stackoverflow.com/a/51377714
score: 1
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51376792
has comment: http://stackoverflow.com/comment/89727188
has body: Do you mean that the last NaNs(one or more) should be remained? How about this. Find the last valid arg index and split and interpolate and append. valargmax=np.max(np.where((df.isnull().eq(False).values==True).flatten()==True)) r = df[0:(valargmax+1)].interpolate(method='index').append(df[(valargmax+1):]) print(r)
downvote count: 0

http://stackoverflow.com/comment/89685635
type: Comment
type: QuestionComment
has text: I don't understand exactly. Could you add your models?
score: 0
comment on: http://stackoverflow.com/q/51356650

http://stackoverflow.com/q/51464455
has answer: http://stackoverflow.com/a/55769463
answer count: 14
has comment: http://stackoverflow.com/comment/128295576
score: 108
upvote count: 111
has title: How to disable welcome message when importing pygame
tagged with: python
tagged with: pygame
has answer: http://stackoverflow.com/a/57745495
has answer: http://stackoverflow.com/a/69009120
has answer: http://stackoverflow.com/a/78709209
has answer: http://stackoverflow.com/a/76135445
has body: When I import pygame, it prints the version and welcome message. The message reads: pygame 1.9.4 Hello from the pygame community. https://www.pygame.org/contribute.html Why is this printed? How can I disable this message?
has answer: http://stackoverflow.com/a/51845301
has answer: http://stackoverflow.com/a/72049206
has comment: http://stackoverflow.com/comment/94940858
accepted answer: http://stackoverflow.com/a/55769463
has answer: http://stackoverflow.com/a/55257724
possible better answer: http://stackoverflow.com/a/51470016
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51470016
has answer: http://stackoverflow.com/a/54906316
has comment: http://stackoverflow.com/comment/134922204
has answer: http://stackoverflow.com/a/72668002
downvote count: 3
has comment: http://stackoverflow.com/comment/138539038
has answer: http://stackoverflow.com/a/54533290
linked to: http://stackoverflow.com/q/8391411
has comment: http://stackoverflow.com/comment/104854051
has answer: http://stackoverflow.com/a/63928650
favorite count: 0
has answer: http://stackoverflow.com/a/54543843

http://stackoverflow.com/a/51416630
has body: Try to put this in your legend: import matplotlib.cm as cm And then you just need to figure out how many different colours you want - to be honest, I did not quite get what defines the numebr of colours in your example, hence I will just give a general expression. NrCol = #Enter formula or methode to calculate total number of colours needed colour = cm.rainbow(np.linspace(0,1,NrCol)) This is an colour array and now you can access the colours with an index like this: color = colour[j] I don't get what you want, but if you say that you can hardcode it, you should be able to replace your hardcoded colour with this colour and it should be fine. Hope that helps! Cheers
has comment: http://stackoverflow.com/comment/89834222
has comment: http://stackoverflow.com/comment/89843606
answers question: http://stackoverflow.com/q/51416407
score: 0
type: Answer

http://stackoverflow.com/a/51410081
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89794062
answers question: http://stackoverflow.com/q/51400185
downvote count: 0
has comment: http://stackoverflow.com/comment/89792093
has comment: http://stackoverflow.com/comment/89794408
accepted answer of: http://stackoverflow.com/q/51400185
has comment: http://stackoverflow.com/comment/89791927
has comment: http://stackoverflow.com/comment/89860510
has comment: http://stackoverflow.com/comment/89794908
has comment: http://stackoverflow.com/comment/89794350
type: Answer
has comment: http://stackoverflow.com/comment/89793072
has body: Remove your code, add this code after the code present in that link from nltk import word_tokenize import numpy as np vector_size=512 padding=np.zeros((vector_size )) sentences=['im so happy','you are beautiful','i got scolded today'] final=[] for sentence in sentences: temp=[] words=word_tokenize(sentence) for word in words: if word in X_vecs: temp.append(X_vecs[words]) #padding to get length of 15 for i in range(15-len(temp)): temp.append(padding) final.append(temp) predictions = model.predict(np.array(final)) for prediction in predictions: print("%s sentiment; %f%% confidence" % (labels[np.argmax(prediction)], prediction[np.argmax(prediction)] * 100)) Could you please run this and report me back? If it works, I'll explain the code.
has comment: http://stackoverflow.com/comment/89792462
has comment: http://stackoverflow.com/comment/89794142
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89793895
has comment: http://stackoverflow.com/comment/89793954
has comment: http://stackoverflow.com/comment/89794526
has comment: http://stackoverflow.com/comment/89794105

http://stackoverflow.com/comment/89914507
has text: Hey I still get index out of range exception
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51472559

http://stackoverflow.com/comment/89733459
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51380858
score: 0
has text: mean you dont know how put url in action and how it works?

http://stackoverflow.com/comment/89688837
type: Comment
comment on: http://stackoverflow.com/a/51355821
score: 0
type: AnswerComment
has text: That`s just the encoding part.I have edited the answer for the same!

http://stackoverflow.com/a/75517723
score: 0
answers question: http://stackoverflow.com/q/51360649
has comment: http://stackoverflow.com/comment/133955435
type: Answer
has body: import docx.oxml.ns as ns def update_table_of_contents(doc): # Find the settings element in the document settings_element = doc.settings.element # Create an "updateFields" element and set its "val" attribute to "true" update_fields_element = docx.oxml.shared.OxmlElement('w:updateFields') update_fields_element.set(ns.qn('w:val'), 'true') # Add the "updateFields" element to the settings element settings_element.append(update_fields_element)

http://stackoverflow.com/comment/89779311
score: 1
type: AnswerComment
has text: wow, thank you so much, I was not aware of split capabilities.
type: Comment
comment on: http://stackoverflow.com/a/51404186

http://stackoverflow.com/comment/89675951
has text: I got that error: type object 'Lookups' has no attribute 'object'
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51351667
type: Comment

http://stackoverflow.com/q/51481018
has comment: http://stackoverflow.com/comment/89931690
has title: Creating self contained wheel
accepted answer: http://stackoverflow.com/a/51524574
tagged with: pyrfc
tagged with: saprfc
has comment: http://stackoverflow.com/comment/89995771
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/47042483
has comment: http://stackoverflow.com/comment/89977499
favorite count: 0
type: Question
score: 3
tagged with: python
has comment: http://stackoverflow.com/comment/89931848
tagged with: setup.py
upvote count: 3
tagged with: python-wheel
has answer: http://stackoverflow.com/a/51524574
has body: I try to create a self contained wheel for pyRFC: http://sap.github.io/PyRFC/install.html I have the needed (closed sourced) libraries and header files. Installing pyRFC works, if I copy the libraries and headers to $VIRTUAL_ENV/lib and $VIRTUAL_ENV/include. Now I try to create a wheel which contains the closed source library files. But I am failing. If I unzip the wheel it only contains this: (pypi)pypi@pypiserver:~&gt; unzip -l packages/pyrfc-1.9.91-cp27-cp27mu-linux_x86_64.whl Archive: packages/pyrfc-1.9.91-cp27-cp27mu-linux_x86_64.whl Length Date Time Name --------- ---------- ----- ---- 5366 2018-07-23 13:38 pyrfc/_exception.py 1045 2018-07-23 13:38 pyrfc/__init__.py 1610216 2018-07-23 14:10 pyrfc/_pyrfc.so 3835 2018-07-23 14:10 pyrfc-1.9.91.dist-info/DESCRIPTION.rst 990 2018-07-23 14:10 pyrfc-1.9.91.dist-info/metadata.json 6 2018-07-23 14:10 pyrfc-1.9.91.dist-info/top_level.txt 105 2018-07-23 14:10 pyrfc-1.9.91.dist-info/WHEEL 4666 2018-07-23 14:10 pyrfc-1.9.91.dist-info/METADATA 715 2018-07-23 14:10 pyrfc-1.9.91.dist-info/RECORD --------- ------- 1626944 9 files The extra_objects (see below) are missing. How can I modify the setup.py of pyRFC to make the wheel contain the libraries from $VIRTUAL_ENV/lib? Here is the setup.py: https://github.com/SAP/PyRFC/blob/master/setup.py I tried this patch for setup.py @@ -48,7 +49,9 @@ PYRFC_EXT = Extension( , libraries=LIBS , define_macros=MACROS , extra_compile_args=COMPILE_ARGS - , extra_link_args=LINK_ARGS + , extra_link_args=LINK_ARGS, + library_dirs=['lib'], + extra_objects = ['lib/libicudata.so.50', 'lib/libsapnwrfc.so', 'lib/libicui18n.so.50', 'lib/libicuuc.so.50', 'lib/libicudecnumber.so', 'lib/libsapucum.so'], ) If I install and run the library without libsapnwrfc.so I get this error: Traceback (most recent call last): File "test-pyrfc.py", line 1, in &lt;module&gt; from pyrfc import Connection File "/home/other/lib/python2.7/site-packages/pyrfc/__init__.py", line 22, in &lt;module&gt; from pyrfc._pyrfc import …
answer count: 1

http://stackoverflow.com/comment/89763895
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51396340
has text: Yes, the problem is that how to extract the identifying features from the image portion. SURF, SIFT and OBR are some basic approaches but they are both overwhelming and time consuming algorithms but can extract some storable data about the detected object from the CNN. Thanks for the reply

http://stackoverflow.com/a/51337415
score: 1
upvote count: 1
downvote count: 0
has body: This is a possible solution ... a_list = [[7], [4, 3, 5, 8], [1, 3]] new_list = [] for sub_list in a_list: sublistsum = 0 for i, value in enumerate(sub_list): sublistsum = sublistsum + i * value new_list.append([sublistsum]) print(new_list)
type: Answer
answers question: http://stackoverflow.com/q/51337313

http://stackoverflow.com/q/51366058
has comment: http://stackoverflow.com/comment/89705402
has answer: http://stackoverflow.com/a/51366237
has comment: http://stackoverflow.com/comment/89704397
accepted answer: http://stackoverflow.com/a/51366237
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51366422
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51366178
has answer: http://stackoverflow.com/a/51366315
has body: How do I get total number of single words in a list. There are 8 elements in a list below. However, some elements have more than single words in them 'apples are delicious', how to do I just capture just the number of single word from list? list = ['apples', 'apples', 'apples are delicious', 'oranges', 'fruits', 'kiwi', 'fruit festivals', 'festivals'] len(list) # total number of elements in a list list.count("apples") # only counts a specific word but not a element single words # total 8 elements # how many are only 1 word? # results: 6/8 are 1 words
type: Question
has title: Python - How many are just a single word in a list
downvote count: 0
answer count: 7
has answer: http://stackoverflow.com/a/51366239
possible better answer: http://stackoverflow.com/a/51366116
has answer: http://stackoverflow.com/a/51366106
favorite count: 0
has answer: http://stackoverflow.com/a/51366116

http://stackoverflow.com/q/51366888
type: UnansweredQuestion
tagged with: python
has body: I am trying to fetch data from this website: https://fortnitetracker.com/site-api and I'm having some issues with authenticating my get request; keep getting error 403. My code: import requests headers = {'TRN-Api-Key':'*My API Key*','User-Agent': '*My user Agent*'} r = requests.get("https://api.fortnitetracker.com/v1/profile/pc/*My Username*",headers=headers) print(r) I have checked that the key is correct and have passed a valid User-Agent. So yeah, I'm probably doing something very silly or perhaps there is a bug with authentication on the website, any help is very appreciated!
has comment: http://stackoverflow.com/comment/89706552
type: Question
tagged with: api
has comment: http://stackoverflow.com/comment/89707190
has title: Tracker Network Python API key error
score: 0
answer count: 0

http://stackoverflow.com/comment/90512519
comment on: http://stackoverflow.com/a/51777025
type: AnswerComment
has text: Actually, I do have 1 more: how did you get this info about why 3 isn’t supported? Before I started this thread, I did a little bit of searching as to why 3 isn’t supported, and a potential reason. Can u send a link for where you found this info, or is it just general knowledge with regular Livy users?
score: 0
type: Comment

http://stackoverflow.com/q/51416277
has answer: http://stackoverflow.com/a/51416377
tagged with: nltk
has title: Selecting a sublist from list of lists after using Sentence Tokenizer
has comment: http://stackoverflow.com/comment/89803834
tagged with: sentence
type: AnsweredQuestion
has body: So i have some sentences in a list like: some_list = ['Joe is travelling via train.' 'Joe waited for the train, but the train was late.' 'Even after an hour, there was no sign of the train. Joe then went to talk to station master about the train's situation.'] Then i used nltk's Sentence tokenizer, because i want to analyse each sentence in a full sentence individually. So now the O/P looks something like this in lists of lists format : sent_tokenize_list = [['Joe is travelling via train.'], ['Joe waited for the train,', 'but the train was late.'], ['Even after an hour,', 'there was no sign of the train.', 'Joe then went to talk to station master about the train's situation.']] Now from this list of lists how can i select only the lists which have more than 1 sentence i.e 2nd and 3rd list in my example and have them in only list format as separate lists. i.e O/P Should be ['Joe waited for the train,','but the train was late.'] ['Even after an hour,','there was no sign of the train.', 'Joe then went to talk to station master about the train's situation.']
accepted answer: http://stackoverflow.com/a/51416377
type: Question
tagged with: python
tagged with: tokenize
score: 0
answer count: 1

http://stackoverflow.com/q/51470955
has title: Pandas overwriting different data frame when adding new column
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89910266
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/89910601
has body: All I want to do is make two data frames (A and B) based off of one original data frame. Then I want to add a new column to each data frame "LABEL" and have each row in that data frame = AVN_DEL_1_A or AVN_DEL_1_B relative to data frame name... Simple.. WTF is going on? why is modifying dataframeA messing up dataframeB. track CHROMOSOME START END 7 chr1 56365453 56369289 trackA = track trackA.head() CHROMOSOME START END 7 chr1 56365453 56369289 trackA.assign(LABEL = str("AVN_DEL_" + str(1) + "_A")) CHROMOSOME START END LABEL 7 chr1 56365453 56369289 AVN_DEL_1_A trackB = track trackA.head() CHROMOSOME START END 7 chr1 56365453 56369289
score: 0
has comment: http://stackoverflow.com/comment/89910200
tagged with: pandas
has comment: http://stackoverflow.com/comment/89910365

http://stackoverflow.com/a/60554863
type: Answer
answers question: http://stackoverflow.com/q/51417424
score: 0
has body: Here is how I ended up solving this: def listToString (list): output = '' for items in list[:-1]: # Grabs all items from the list except the final one output+= items + ', ' output+= 'and ' + list[-1] + '.' # Adds the final value of the list. print(output) testList = ['Apples','Oranges', 'Pears', 'Bananas'] listToString(testList)

http://stackoverflow.com/q/51461388
tagged with: python
has title: Effective algorithms to find k clique communities
tagged with: networkx
has body: I am running k_cliques_communities from networkX on my network data, which has ~600 nodes and ~10,000 edges, and I run into memory error. The same code can be applied to a similar network which has ~600 nodes and ~9000 edges without errors. The number of nodes and edges are quite the same but the first encounter a memory error. What might cause this issue and how can I solve it? Is it because of the effectiveness?
score: 0
has comment: http://stackoverflow.com/comment/89892193
has comment: http://stackoverflow.com/comment/89892763
type: Question
has comment: http://stackoverflow.com/comment/89891986
has comment: http://stackoverflow.com/comment/89891987
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/89830636
has text: this looks like an interesting approach but it's not working. 2014 Estimate is a column in a data frame
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51416837

http://stackoverflow.com/a/51400103
downvote count: 0
answers question: http://stackoverflow.com/q/51400001
type: Answer
upvote count: 1
score: 1
has body: Your class should be like this: class Average() : def myinput(self): n=0 mylist=[] #will be ended when input = -1 while n !='-1' : n=raw_input('&gt;&gt;&gt;') if n!='-1' : mylist.append(n) print self.lol(mylist) def lol(self, mylist): try: mysum=0.0 for i in mylist : mysum = mysum + int(i) return mysum/len(mylist) except: return 'please don\'t Enter charecters just Number' ave = Average() ave.myinput() This first argument should be class instance itself.

http://stackoverflow.com/q/51391271
downvote count: 0
has answer: http://stackoverflow.com/a/51391305
favorite count: 0
has body: I have a .txt file formatted like a dictionary is, for example: {'planet': 'earth', "country": "uk"} Just that, that's all. I would want to add more to this later. At the moment, I can save more keys to it and have it saved but... How can I import this .txt file and use it as a dictionary?
linked to: http://stackoverflow.com/q/15197673
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/89754673
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51391305
score: 1
tagged with: file
upvote count: 1
has title: Using .txt file as a Dictionary
type: Question
has comment: http://stackoverflow.com/comment/89754676
answer count: 1

http://stackoverflow.com/q/51372765
has body: In the following code: with open("output", "w") as f: print &gt;&gt; f, "foo" print &gt;&gt; f, "bar" The 'output' file will be: foo bar How to avoid newline and white spaces using print &gt;&gt;? P.S.: I'm actually wanting to know if it is possible to do it using print &gt;&gt;. I know other ways in which I can avoid the '\n', such as f.write("foo") and f.write("bar"). Also, I know about the trailing comma. But that prints foo bar, instead of foobar.
score: 2
upvote count: 2
type: Question
has answer: http://stackoverflow.com/a/51372938
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/89717788
answer count: 1
downvote count: 0
tagged with: python-2.x
linked to: http://stackoverflow.com/q/493386
has comment: http://stackoverflow.com/comment/89717484
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Is it possible to use 'print >>' in Python 2 without newline and white spaces?

http://stackoverflow.com/comment/89648327
type: Comment
type: QuestionComment
score: 0
has text: You have to add the full error traceback to the question
comment on: http://stackoverflow.com/q/51336785

http://stackoverflow.com/comment/89928158
comment on: http://stackoverflow.com/q/51479608
score: 0
has text: @WiktorStribiżew That gives me the same result.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89632328
comment on: http://stackoverflow.com/q/51325187
type: Comment
score: 0
has text: It probably prints to standard error rather than standard output. The general principle is independent of the command you are running but there are minor complications like this.
type: QuestionComment

http://stackoverflow.com/a/51478014
upvote count: 4
has body: There is a strong difference between an output stream (used by print) and a message log. The stream is a sequence of characters (or bytes for binary strings) that may happen to contain newline characters. Those newlines characters are then interpreted when you display them on a terminal (or when you print them). A log is a sequence of messages, and each message is supposed to be atomic. Once a message has been logged, you cannot add anything to it but can only log new messages. So you have to first fully build your message and then log it: num_list = [1, 2, 3, 4, 5] msg = "Numbers in num_list are: " + " ".join(num_list) # fully build the message logger.info(msg) # and then log it
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/51477200
type: Answer

http://stackoverflow.com/comment/105034366
type: Comment
type: QuestionComment
has text: I didn't found comfortable sollution. But you can use duckduckgo, when you ask `tensorflow r1.15 <searching term>` then with high probability you will get proper page of tensorflow documentation
comment on: http://stackoverflow.com/q/51327224
score: 0

http://stackoverflow.com/comment/89829685
type: Comment
has text: Ok! almost works, what I want is when editing the course, the user has the same `deadline time` 2 minutes after his first vote on the course edited to get hist vote locked... with your example, after the edit, the user can vote once, and after vote is locked, whereas I need to give the user another 2 minutes
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51428812

http://stackoverflow.com/q/51436280
type: UnansweredQuestion
tagged with: python
tagged with: mouse
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51436684
tagged with: pynput
type: Question
tagged with: pyautogui
upvote count: 2
has answer: http://stackoverflow.com/a/57406039
has title: pynput mouse position coordinate to variable and use of variable on a global scale
answer count: 2
has body: I'm trying to save the mouse's x and y coordinates when the mouse button is pressed and, separately, when it is released. I am able to print them but unable to save them to variables. Here's what I got: from pynput.mouse import Listener def on_click(x, y, button, pressed): print('{0} at {1}'.format( 'Pressed' if pressed else 'Released', (x, y))) if not pressed: # Stop listener return False with Listener(on_click=on_click) as listener: listener.join() And then how would I call these variables on a global scale to use with another module (e.g. pyautogui?)
favorite count: 0

http://stackoverflow.com/q/51470277
tagged with: tkinter-layout
has answer: http://stackoverflow.com/a/51470387
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/51470387
tagged with: python
has title: Tkinter/ttk - treeview does not take up the full frame
tagged with: tkinter
has body: I'm trying out my first application in Tkinter/ttk. I'm running into a minor formatting problem that I am unable to resolve. I'm creating a tree view of a list of stock symbols in a frame. When I run the application only the first 10 symbols are displayed in the table although the frame is large enough to display all 20 symbols in the list. I have to scroll down to see the rest of the list. I've researched other answers, but nothing seems to give the correct answer. I also tried different combinations of sticky, fill, align, and height settings without success. Can anyone help me figure out what I need to do to get the tree to fill up the frame? Here is a minimal version of the code which shows the issue. A png of the output is attached. Thanks for your help! #!/usr/local/bin/python3.6 import tkinter as tk from tkinter import ttk class ss: def __init__(self, root): left_frame = tk.Frame(root, height = 8000, width = 1000) right_frame = tk.Frame(root, height = 5000, width = 1000) left_top = tk.Frame(left_frame, height = 300, width = 1000) left_bottom = tk.Frame(left_frame, height = 2000) left_frame.grid(row = 0, column = 0, sticky = 'ns') right_frame.grid(row = 0, column = 1, sticky = 'ns') left_top.grid(row = 0, column = 0, sticky = 'ew') left_bottom.grid(row = 1, column = 0, sticky = 'sew') left_frame.rowconfigure(1, weight = 1) tk.Label(left_top, text = "Sort by:").grid(row = 0, column = 0) self.tree = ttk.Treeview(left_bottom, selectmode = 'browse') self.tree.pack(side = 'left', expand = 1, fill = 'both') scrollbar = ttk.Scrollbar(left_bottom, orient = "vertical", command = self.tree.yview) scrollbar.pack(side = 'left', expand = 1, fill = 'y') self.current_symbol = "" self.stock_label = tk.Label(right_frame, text = self.current_symbol, anchor = 'n') self.stock_label.pack(side = 'top') self.tree.configure(yscrollcommand = scrollbar.set) self.tree\["columns"\] = ("1") self.tree\['show'\] = 'headings' self.tree.column("1", width = 100, anchor = 'w') self.tree.heading…
upvote count: 1
answer count: 1

http://stackoverflow.com/a/51416131
has body: I think it's better to define 3 separate functions for the calculations as you've done first. However, I would give them more descriptive names according to what they do. This way you'll be able to combine them as you want or even call them from other modules. For instance: def solar_current(G): return 0.03*G # Solar cell photo current in A def shorcircuit_current(G,T): return (G/1000)*(T-25) # short circuit current def f3(G): # Whatever name it describes a bit better what it does. return G/800 T1, I1, I2 = [], [], [] for G in range(100, 1100, 100): T1.append(solar_current(G)) I1.append(shortcircuit_current(G, 25)) I2.append(f3(G)) PS: I assume the 25 you're passing as T value is an example. With the calculations done in shortcuit_current() it will always return 0
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51415599

http://stackoverflow.com/a/51422751
answers question: http://stackoverflow.com/q/51421079
type: AcceptedAnswer
has body: Your data looks a bit odd. Perhaps simplify it. With your data in a file called timesheet.txt: ;;;;;;1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16;17;18;19;20;21;22;23;24;25;26;27;28;29;30;;;;;;; Person Name;;;;;;A;DS;DS;C;C;C;C;C;DS;DS;B;DS;B;B;B;B;B;DS;B;B;B;B;DS;DS;A;A;A;A;A;DS;;;;;;; This will read the data in produce a useful output: with open('timesheet.txt', 'r') as file: # read each line in and label them days = next(file).strip().split(';') persons = next(file).strip().split(';') for i in range(len(days)): if days[i]: print("Day: %s, Person: %s" % (days[i], persons[i]))
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51421079

http://stackoverflow.com/q/51355495
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51355685
has answer: http://stackoverflow.com/a/51355538
has answer: http://stackoverflow.com/a/76373216
has title: Python - Invalid JSON format - how to parse
type: Question
has answer: http://stackoverflow.com/a/73401625
accepted answer: http://stackoverflow.com/a/51355553
score: 4
upvote count: 4
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/89683264
has answer: http://stackoverflow.com/a/51355685
has answer: http://stackoverflow.com/a/51355553
downvote count: 0
favorite count: 0
has body: I am getting data in the following JSON format: { address:[ "test1" ], city:"test2", country:"test3", postal_code:"test4", state:"test5" } While I am trying to parse it via: json.loads(data) I am receiving an error: Expecting property name enclosed in double quotes Is there a way to parse it in python ? Thanks in advance,
linked to: http://stackoverflow.com/q/39491420
answer count: 5
tagged with: python

http://stackoverflow.com/q/51365527
score: 1
has title: Can't find span tag on quora website using beautifulsoup search by class
has answer: http://stackoverflow.com/a/51365721
type: Question
answer count: 1
tagged with: quora
upvote count: 1
tagged with: http://stackoverflow.com/tag/html
favorite count: 0
tagged with: beautifulsoup
linked to: http://stackoverflow.com/q/23102833
has body: I am using beautifulsoup to parse quora urls and retrive upvotes counts for each answer, by looking for tags containing "icon_action_bar-count" Class. The problem is that the result is always empty or 'None' despite that the class can be found manually in the original page (using mozilla developer interface), I am using this simple beautifulsoup command: upvote =soup.findAll("span",{"class":"icon_action_bar-count"}) below the html span tag i am trying to retrieve,and the quora url containg this html code: · 610 https://www.quora.com/Why-do-a-lot-of-rich-people-say-rent-instead-of-buy-property
downvote count: 0
type: UnansweredQuestion
tagged with: web-scraping
tagged with: python

http://stackoverflow.com/comment/89823433
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51406902
has text: also if I try making it a function and I call it appropriately on my Python code (the same way you did in your code) I get this error: error: invalid call to script /Users/gnss_user/Documents/PMTest.m, where PMTest.m is the name of my matlab file

http://stackoverflow.com/comment/89911657
comment on: http://stackoverflow.com/q/51470574
score: 0
type: QuestionComment
has text: Hi, which version of Pandas are you using, your code works fine with me. `y = pd.read_hdf('append.h5', key='part1', mode='r')` produces the desired result. ` a b c d e f \ 2017-12-23 0.043948 0.260736 0.194791 0.775708 0.013273 0.137011 2017-12-24 0.133136 0.052005 0.105792 0.218531 0.489121 0.688763 2017-12-25 0.422981 0.217906 0.834061 0.422932 0.636758 0.888885 .... g h i j ... ` I'm using pandas 0.22, and it works perfectly.
type: Comment

http://stackoverflow.com/q/51378207
tagged with: python
tagged with: jupyter-notebook
has body: I'm trying to create a gantt chart with plotly in an offline Jupyter notebook, mashing together the Gantt chart tutorial and the offline tutorial, I tried this: import plotly.plotly as py import plotly.figure_factory as ff from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot init_notebook_mode(connected=True) dfoo = [dict(Task="Job A", Start='2009-01-01', Finish='2009-02-28'), dict(Task="Job B", Start='2009-03-05', Finish='2009-04-15'), dict(Task="Job C", Start='2009-02-20', Finish='2009-05-30')] fig = ff.create_gantt(dfoo) py.iplot(fig) But this only returns an error about the plotly API, which shouldn't happen if I'm offline... PlotlyRequestError: Aw, snap! You tried to use our API as the user ___, but the supplied API key doesn't match our records. I can plot other charts offline, is there a way to use figure factory and plot offline?
type: AnsweredQuestion
tagged with: plotly
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51523532
has answer: http://stackoverflow.com/a/51378680
answer count: 2
has title: Can I use plotly figure factory offline in python?
possible better answer: http://stackoverflow.com/a/51523532
downvote count: 0
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51378680

http://stackoverflow.com/comment/89756212
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51391852
type: Comment
has text: @Onyambu, Oh, that makes sense. Maybe adding this to your answer might help other readers looking for the count instead.

http://stackoverflow.com/comment/89780667
type: AnswerComment
has text: @speedymcs: my mistake. That should be `itemconfigure` along with `image=self.photo`. I've updated my answer.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51404545

http://stackoverflow.com/comment/89785692
score: 0
has text: @HansOlsson I based that statement on the fact that after hundreds of thousands of runs on simulated data I have never observed a local solver to converge somewhere other than a global minimum (within the preset tolerance of it anyway). It might not be true, but it seems true enough for my use case.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51394973

http://stackoverflow.com/comment/89682711
has text: Define "mean" with respect to 3 lists.
score: 1
comment on: http://stackoverflow.com/q/51355151
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51463449
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51463474
linked to: http://stackoverflow.com/q/3191528
upvote count: 3
has comment: http://stackoverflow.com/comment/89896482
downvote count: 1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51463964
has body: I want to replace the header row of a cvs file text.csv. header_list = ['column_1', 'column_2', 'column_3'] The header will look like this; column_1, column_2, column_3 Here is my code; import csv with open('text.csv', 'w') as csvfile: writer = csv.writer(csvfile) writer.writerow(header_list) The header of the csv file was replaced correctly. However, the rest of the rows in the csv file were deleted. How do I replace only the header leaving the other rows intact? I am using python v3.6
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51463964
has title: Replace csv header without deleting the other rows
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/51463474
tagged with: python
score: 2

http://stackoverflow.com/q/51435095
has comment: http://stackoverflow.com/comment/89841655
has title: How does Python assign function to classes and instances?
score: 1
tagged with: methods
type: Question
has body: I'm quite confused about Python's behavior when I assign function to classes and instances: class A: def printf(*args): print(args) def printff(*args): print(args) a = A() a.printf() print('-'*5, a.printf) print('-'*5, A.printf) A.printf = printff a.printf() print('-'*5, a.printf) print('-'*5, A.printf) a.printf = printff a.printf() print('-'*5, a.printf) print('-'*5, A.printf) A.printf = printff a.printf() print('-'*5, a.printf) print('-'*5, A.printf) ##Output ##(&lt;__main__.A object at 0x7b3b140e80&gt;,) ##----- &lt;bound method A.printf of &lt;__main__.A object at 0x7b3b140e80&gt;&gt; ##----- &lt;function A.printf at 0x7b3b148048&gt; ##(&lt;__main__.A object at 0x7b3b140e80&gt;,) ##----- &lt;bound method printff of &lt;__main__.A object at 0x7b3b140e80&gt;&gt; ##----- &lt;function printff at 0x7b3b2fce18&gt; ##() ##----- &lt;function printff at 0x7b3b2fce18&gt; ##----- &lt;function printff at 0x7b3b2fce18&gt; ##() ##----- &lt;function printff at 0x7b3b2fce18&gt; ##----- &lt;function printff at 0x7b3b2fce18&gt; Could anyone tell me : What's the difference between &lt;bound method A.printf&gt; and &lt;bound method printff&gt;? Why when I run A.printf=printff again and the output becomes different? Or, how to understand this behavior? I'm using Python 3.6 if it makes any difference. UPDATE: I'm sorry that I didn't make it clear. For Q1, I want to know is there any difference between &lt;bound method A.printf&gt; and &lt;bound method printff&gt; not bound and unbound. For Q2, I'm wondering is that because I have assigned specifically to the instance that it didn' t work again and how to understand it.
has answer: http://stackoverflow.com/a/51435303
linked to: http://stackoverflow.com/q/1015307
tagged with: function
has answer: http://stackoverflow.com/a/51435256
downvote count: 0
tagged with: class
answer count: 3
possible better answer: http://stackoverflow.com/a/51435256
linked to: http://stackoverflow.com/q/6478371
tagged with: python
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51436921
upvote count: 1
accepted answer: http://stackoverflow.com/a/51436921
type: AnsweredQuestion

http://stackoverflow.com/comment/89881999
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51456271
type: Comment
has text: Thanks a lot for your help ! :) The `get_group()` method is already implemented on my side.

matplotlib
tags question: http://stackoverflow.com/q/51420311
tags question: http://stackoverflow.com/q/51338249
tags question: http://stackoverflow.com/q/51350872
tags question: http://stackoverflow.com/q/51473032
tags question: http://stackoverflow.com/q/51330028
tags question: http://stackoverflow.com/q/51464527
tags question: http://stackoverflow.com/q/51374539
tags question: http://stackoverflow.com/q/51425354
tags question: http://stackoverflow.com/q/51401442
tags question: http://stackoverflow.com/q/51479822
tags question: http://stackoverflow.com/q/51458185
tags question: http://stackoverflow.com/q/51341050
tags question: http://stackoverflow.com/q/51412569
tags question: http://stackoverflow.com/q/51378878
tags question: http://stackoverflow.com/q/51438472
tags question: http://stackoverflow.com/q/51444009
tags question: http://stackoverflow.com/q/51325193
tags question: http://stackoverflow.com/q/51467170
tags question: http://stackoverflow.com/q/51466462
tags question: http://stackoverflow.com/q/51457342
tags question: http://stackoverflow.com/q/51434567
tags question: http://stackoverflow.com/q/51428129
tags question: http://stackoverflow.com/q/51426766
tags question: http://stackoverflow.com/q/51328098
tags question: http://stackoverflow.com/q/51452112
tags question: http://stackoverflow.com/q/51429465
tags question: http://stackoverflow.com/q/51431719
tags question: http://stackoverflow.com/q/51446966
tags question: http://stackoverflow.com/q/51464528
tags question: http://stackoverflow.com/q/51385545
tags question: http://stackoverflow.com/q/51386697
tags question: http://stackoverflow.com/q/51411090
tags question: http://stackoverflow.com/q/51368110
tags question: http://stackoverflow.com/q/51349254
tag name: matplotlib
tags question: http://stackoverflow.com/q/51432498
tags question: http://stackoverflow.com/q/51333891
tags question: http://stackoverflow.com/q/51329159
tags question: http://stackoverflow.com/q/51353314
tags question: http://stackoverflow.com/q/51397212
tags question: http://stackoverflow.com/q/51409295
tags question: http://stackoverflow.com/q/51382053
tags question: http://stackoverflow.com/q/51433620
tags question: http://stackoverflow.com/q/51477357
tags question: http://stackoverflow.com/q/51470408
tags question: http://stackoverflow.com/q/51482079
tags question: http://stackoverflow.com/q/51371755
tags question: http://stackoverflow.com/q/51463955
tags question: http://stackoverflow.com/q/51382736
tags question: http://stackoverflow.com/q/51466467
tags question: http://stackoverflow.com/q/51368471
tags question: http://stackoverflow.com/q/51448825
tags question: http://stackoverflow.com/q/51368187
tags question: http://stackoverflow.com/q/51351817
tags question: http://stackoverflow.com/q/51351129
tags question: http://stackoverflow.com/q/51391797
tags question: http://stackoverflow.com/q/51341717
tags question: http://stackoverflow.com/q/51464999
tags question: http://stackoverflow.com/q/51441594
tags question: http://stackoverflow.com/q/51468583
tags question: http://stackoverflow.com/q/51353755
tags question: http://stackoverflow.com/q/51456343
tags question: http://stackoverflow.com/q/51418113
tags question: http://stackoverflow.com/q/51451046
tags question: http://stackoverflow.com/q/51386947
tags question: http://stackoverflow.com/q/51390884
tags question: http://stackoverflow.com/q/51478441
tags question: http://stackoverflow.com/q/51347692
tags question: http://stackoverflow.com/q/51386761
tags question: http://stackoverflow.com/q/51461382
tags question: http://stackoverflow.com/q/51340015
tags question: http://stackoverflow.com/q/51409257
tags question: http://stackoverflow.com/q/51352115
tags question: http://stackoverflow.com/q/51468670
tags question: http://stackoverflow.com/q/51481397
tags question: http://stackoverflow.com/q/51417483
tags question: http://stackoverflow.com/q/51385626
tags question: http://stackoverflow.com/q/51347398
tags question: http://stackoverflow.com/q/51389793
tags question: http://stackoverflow.com/q/51365529

http://stackoverflow.com/q/51360513
type: Question
has comment: http://stackoverflow.com/comment/89693170
linked to: http://stackoverflow.com/q/26477866
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51360923
has comment: http://stackoverflow.com/comment/89693408
favorite count: 0
has comment: http://stackoverflow.com/comment/89693556
has title: Unable to print after 1076 digits using decimal data type
upvote count: 2
accepted answer: http://stackoverflow.com/a/51360923
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89693176
has body: I wrote a Python program to print n digits of pi after the decimal place using decimal data type. The algorithm I used was the Bailey-Borwein-Plouffe formula. The program prints up to 1076 total digits and stops printing no matter what the given precision limit is. from decimal import * def nthdigit(n): final = 0 for k in range(0,n): calc =Decimal((16**-k)*(4/(8*k+1) - 2/(8*k+4) - 1/(8*k+5) - 1/(8*k+6))) #THE BAILEY-BORWEIN-PLOUFFE FORMULA final = Decimal(final+calc) print(final) n=100000 n=n+1 getcontext().prec = n nthdigit(n) I was wondering if it was a default setting in the Decimal datatype, and if so is there a way to go past that precision limit??

subscript
tags question: http://stackoverflow.com/q/51482079
type: Tag
tag name: subscript

http://stackoverflow.com/comment/89781045
comment on: http://stackoverflow.com/q/51393471
type: QuestionComment
type: Comment
has text: Yes, there was a bug there. That was fixed in CPLEX 12.7, I believe. Which version are you using?
score: 0

http://stackoverflow.com/comment/89794785
comment on: http://stackoverflow.com/q/51410366
has text: Parallel data structures are a capital sin in my book :) Currently looking at a list of `(value,label)` tuples in a class with a few methods for access but it looks a bit clumsy.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89843143
type: AnswerComment
has text: Nothing special. Sorry for the confusion, the code I posted is just what I typed for test -- and I wanted to type less. sechilds's answer is definitely better.
type: Comment
comment on: http://stackoverflow.com/a/51435272
score: 0

http://stackoverflow.com/comment/89796226
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51412210
type: QuestionComment
has text: The error is: No such file or directory: '"a.xlsx"\r\n'

permissions
tag name: permissions
type: Tag
tags question: http://stackoverflow.com/q/51353827
tags question: http://stackoverflow.com/q/51410089
tags question: http://stackoverflow.com/q/51371219

http://stackoverflow.com/q/51427008
has comment: http://stackoverflow.com/comment/89825442
linked to: http://stackoverflow.com/q/21350605
has comment: http://stackoverflow.com/comment/89825309
has comment: http://stackoverflow.com/comment/89842136
possible better answer: http://stackoverflow.com/a/51427220
tagged with: selenium
tagged with: google-chrome-headless
has title: Selecting button using Selenium in Python 2.7
type: Question
has comment: http://stackoverflow.com/comment/89825400
has answer: http://stackoverflow.com/a/51427476
has body: A site I'm scraping recently changed the button ID I was using. For some reason, I can't find the new element. I've read through multiple sites (including Stack Overflow) on selecting a button, nothing I try works. I'm pretty much a newbie at Selenium. Here's the HTML extract: Store Number: {{=storeId}} {{ if (closeForEcommerce == 0 ) { }} <button id="store-search-modal-make-this-my-store-{{=storeId}}" class="btn btn-make-this-my-store btn-block btn-primary-2 {{ if (ResultDisplayHelper.isMyStore(storeId)) { print("hidden"); } }}" onclick="ResultDisplayHelper.setMyStoreMarker({{=storeId}});ResultDisplayHelper.setMyStore('store-search-modal-abc-store-card-info-', 'store-search-modal-make-this-my-store-', 'store-search-modal-my-store-', {{=storeId}})"> Make This My Store {{ } }} {{ if (closeForEcommerce != 0 ) { }} Store Temporarily Closed {{ } }} My Store Visit Store Page {{ if (dist != null) { }} Miles: {{=ResultDisplayHelper.metersToMiles(dist)}} {{ } }} {{ if (shoppingcenter) { }} {{=shoppingcenter}} {{ } }} {{=address1}} {{ if (address2) { }} {{=address2}} {{ } }} {{=city}}, {{=state}} {{=zip}} I've tried button_id = 'store-search-modal-make-this-my-store-'+shop make_my_store = driver.find_element_by_id(button_id) and make_my_store = driver.find_element_by_xpath("//button[contains(text(),'Make This My Store')]") with the results: NoSuchElementException: no such element: Unable to locate element: {"method":"id","selector":"store-search-modal-make-this-my-store-231"} (Session info: headless chrome=67.0.3396.99) (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.17134 x86_64) and NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"button[onclick^=ResultDisplayHelper]"} (Session info: headless chrome=67.0.3396.99) (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.17134 x86_64) What am I missing? UPDATE: Th…
linked to: http://stackoverflow.com/q/16788310
tagged with: python-2.7
score: 0
accepted answer: http://stackoverflow.com/a/51427209
has answer: http://stackoverflow.com/a/51427220
has comment: http://stackoverflow.com/comment/89827166
has answer: http://stackoverflow.com/a/51427209
tagged with: python
has answer: http://stackoverflow.com/a/51427364
answer count: 4
tagged with: selenium-webdriver
type: AnsweredQuestion

http://stackoverflow.com/q/51354140
accepted answer: http://stackoverflow.com/a/51354197
tagged with: recurrent-neural-network
has body: I'm trying to do classification of a list X of vectors of length 200 that contain integer values chosen from a dictionary vocab of length 100 features as either belonging to class 0 or 1. Here's an example of my input data: X=[[1,22,77,54,51,...],[2,3,1,41,3,...],[12,17,31,4,12,...],...] y=[0,1,1,...] So for example np.array(X).shape=(1000,200) and y.shape=(200,). The classes are split 50-50. I did a standard train_test split into (X,y) and (X_test,y_test). My model is: from keras import layers as L model = keras.models.Sequential() model.add(L.Embedding(input_dim=100+1,output_dim=32,\ input_length=200)) model.add(L.SimpleRNN(64)) model.add(L.Dense(1,activation='sigmoid')) model.compile(optimizer='adam',loss='binary_crossentropy',\ metrics=['accuracy']) model.fit(X,y,batch_size=128,epochs=20,validation_data=(X_test,y_text)) This works fairly well when I fit it to training and testing data. However, I wanted to try skipping the embedding, since I have a "small" space of features (9026). I normalized the training data by dividing by 9206. and tried to build the simple RNN model as follows: model = keras.models.Sequential() model.add(L.InputLayer(200,1)) model.add(L.SimpleRNN(64)) model.add(L.Dense(1,activation='sigmoid')) model.compile(optimizer='adam',loss='binary_crossentropy',\ metrics=['accuracy']) model.fit(X[:,:,np.newaxis],y,batch_size=128,epochs=20,validation_data=(X_test[:,:,np.newaxis],y_text)) I have to add the np.newaxis to get the model to compile. When I fit this to the data, I always get training and validation accuracies of 0.5, which is my fraction of class 0 to class 1. I've tried different activations, different optimizers, different numbers of units in the RNN, different batch sizes, LSTM, GRU, adding dropout, multiple layers....nothing works. My questions are: I have vectors of fixed length (200) to classify, with a vocabulary of just 100 features. Shouldn't one be able to do this without an embedding? Does anyone have useful advice for getting th…
answer count: 1
tagged with: tensorflow
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/29831489
tagged with: keras
has answer: http://stackoverflow.com/a/51354197
type: Question
tagged with: python
has title: RNN classification fails unless I use an embedding. Without embedding, all predictions are the same class
score: 0

http://stackoverflow.com/a/51453766
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51453695
upvote count: 2
has body: And order it: &gt;&gt;&gt; A=[['Hello', 'world'], ['how','are','you'], ['have','a','good','day']] &gt;&gt;&gt; sorted(A,key=len) [['Hello', 'world'], ['how', 'are', 'you'], ['have', 'a', 'good', 'day']] &gt;&gt;&gt;

http://stackoverflow.com/q/51363727
upvote count: 1
type: Question
score: -2
has body: import subprocess import os filename="D:\MAINTRUNK\ar_ctrl_handle_ar_expand_menu.ptu" r = subprocess.Popen("open " + filename, stdout=subprocess.PIPE, shell=True, universal_newlines=True) stdout, stderr = r.communicate() print stdout
has comment: http://stackoverflow.com/comment/89699857
answer count: 2
has answer: http://stackoverflow.com/a/51363901
has title: How can i read file contents(ex: doc file)?
linked to: http://stackoverflow.com/q/36001482
favorite count: 0
has comment: http://stackoverflow.com/comment/89699759
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89699745
tagged with: python
has comment: http://stackoverflow.com/comment/89700080
has answer: http://stackoverflow.com/a/51364026
downvote count: 3
has comment: http://stackoverflow.com/comment/89699700

sensors
type: Tag
tag name: sensors
tags question: http://stackoverflow.com/q/51394253
tags question: http://stackoverflow.com/q/51416407

http://stackoverflow.com/q/51327600
has comment: http://stackoverflow.com/comment/89632416
has comment: http://stackoverflow.com/comment/89631862
has comment: http://stackoverflow.com/comment/89631394
has comment: http://stackoverflow.com/comment/89630595
answer count: 1
has comment: http://stackoverflow.com/comment/89631856
favorite count: 0
has comment: http://stackoverflow.com/comment/89631742
has comment: http://stackoverflow.com/comment/89631122
accepted answer: http://stackoverflow.com/a/51369193
has comment: http://stackoverflow.com/comment/89631391
has comment: http://stackoverflow.com/comment/89631073
tagged with: python
has comment: http://stackoverflow.com/comment/89631430
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89632056
has comment: http://stackoverflow.com/comment/89630444
has comment: http://stackoverflow.com/comment/89633079
score: 1
has comment: http://stackoverflow.com/comment/89630775
has comment: http://stackoverflow.com/comment/89631753
tagged with: mysql
has body: ...without making unnecessary comparisons I want to get an md5 hash of a range of rows. Due to bandwidth limitations, I want it to happen server-side. This works: create table some_table (id int auto_increment, col1 varchar(1), col2 int, primary key (id)); insert into some_table (col1, col2) values ('a', 1), ('b', 11), ('c', 12), ('d', 25), ('e', 50); select group_concat(id,col1,col2) from (select * from some_table where id &gt;= 2 and id &lt; 5 order by id desc) as some_table group by 1 = 1; Output: +----------------------------+ | group_concat(id,col1,col2) | +----------------------------+ | 2b11,3c12,4d25 | +----------------------------+ And with the hash: select md5(group_concat(id,col1,col2)) from (select * from some_table where id &gt;= 2 and id &lt; 5 order by id desc) as some_table group by 1 = 1; Output: +----------------------------------+ | md5(group_concat(id,col1,col2)) | +----------------------------------+ | 32c1f1dd34d3ebd33ca7d95f3411888e | +----------------------------------+ But I feel like there should be a better way. Particularly, I want to avoid comparing 1 with 1 millions of times, something I found necessary in order to get the row range into a group, which I needed in order to use group_concat, which I needed in order to use md5 on mutiple rows. Is there a way to use group_concat (or similar) on a row range, without the needless comparison? Edit I want to hash multiple rows so that I can compare the resulting hashes on different servers. If they are different I can conclude that there is a difference in the rows returned by the subquery.
upvote count: 1
has comment: http://stackoverflow.com/comment/89630927
has comment: http://stackoverflow.com/comment/89631817
type: Question
has comment: http://stackoverflow.com/comment/89631931
has comment: http://stackoverflow.com/comment/89631510
downvote count: 0
has title: How can I use group_concat on an entire subquery?
has answer: http://stackoverflow.com/a/51369193
has comment: http://stackoverflow.com/comment/89631442
has comment: http://stackoverflow.com/comment/89632299

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/51361426
tags question: http://stackoverflow.com/q/51327140
tags question: http://stackoverflow.com/q/51470218
tags question: http://stackoverflow.com/q/51410391
tags question: http://stackoverflow.com/q/51332803
tags question: http://stackoverflow.com/q/51333520
tags question: http://stackoverflow.com/q/51362044
tags question: http://stackoverflow.com/q/51336853
tags question: http://stackoverflow.com/q/51394906
tags question: http://stackoverflow.com/q/51433040
tags question: http://stackoverflow.com/q/51360569
type: Tag

http://stackoverflow.com/comment/89703065
type: Comment
comment on: http://stackoverflow.com/q/51364913
has text: yes MyController is a class `class MyController():` give me a second and i'll ask your first question
score: 0
type: QuestionComment

ssh
tags question: http://stackoverflow.com/q/51450575
tags question: http://stackoverflow.com/q/51472136
tags question: http://stackoverflow.com/q/51411837
tags question: http://stackoverflow.com/q/51333185
tags question: http://stackoverflow.com/q/51444515
type: Tag
tag name: ssh

http://stackoverflow.com/q/51471914
linked to: http://stackoverflow.com/q/629551
has title: Group by on_related() queryset
tagged with: python
has comment: http://stackoverflow.com/comment/89913820
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89912867
tagged with: django
has body: I've look at this How to query as GROUP BY in django? but I can't seem to get it to work. I have a queryset which brings in 4 related tables. I would like to return values from the 'top table' and group them together. Columns to group on are: area_easting(E), area_northing(N), context_number(C), sample_number(S) example current data output E |N |C |S |material 99|526|101|1 ... |seed 99|526|101|1 ... |grain 99|526|101|1 ... |pip 99|526|101|2 ... |seed 99|526|101|2 ... |grain 99|526|101|2 ... |pip I only want to return the E|N|C|S once but still be able to list each material associated with it. Is this possible without having to create another def? #views.py def botany(request): botany = FractionMaterialsPresent.objects.select_related() template = 'botany/test.html' return render(request, template, {'botany': botany}) #models.py class Botany(models.Model): botany_id = models.AutoField(primary_key=True) sample_id = models.IntegerField(blank=True, null=True) area_easting = models.IntegerField(blank=True, null=True) area_northing = models.IntegerField(blank=True, null=True) context_number = models.IntegerField(blank=True, null=True) sample_number = models.IntegerField(blank=True, null=True) entry_date = models.DateTimeField(auto_now_add=True) analysis_date = models.DateTimeField(auto_now=True) analyst = models.CharField(max_length=200, default='') notes = models.CharField(max_length=600, default='') class Fraction(models.Model): fraction_id = models.AutoField(primary_key=True) botany_id = models.ForeignKey(Botany, db_column='botany_id', on_delete = models.PROTECT) proportion_analysed = models.DecimalField(max_digits=5, decimal_places=3) soil_volume = models.DecimalField(max_digits=15, decimal_places=4) sample_volume = models.DecimalField(max_digits=15, decimal_places=4) sample_weight = models.DecimalField(max_digits=15, decimal_places=4) class FractionMaterialsPresent(models.Model): material_id = models.AutoField(primary_key=True) fraction_id = models.ForeignKey(Fraction…
tagged with: group-by
type: Question
score: 0

http://stackoverflow.com/q/51334793
answer count: 1
has comment: http://stackoverflow.com/comment/89650911
tagged with: python
type: UnansweredQuestion
score: 0
tagged with: scrapy
has title: Scrapy - Error while creating project - DDL Load failed
has body: I am trying for a longer time.Please do help. I installed scrapy using conda. I tested pip show scrapy in the command line and it is working perfectly. While i type import scrapy in the python terminal it is not showing any error. But if i create a project or execute an existing project of scrapy i get the following error: C:\Users\Nikeshh\Anaconda2\lib\site-packages\scrapy\commands\deploy.py:16: ScrapyDeprecationWarning: Module `scrapy.command` is deprecated, use `scrapy.commands` instead from scrapy.command import ScrapyCommand Traceback (most recent call last): File "C:\Users\Nikeshh\Anaconda2\Scripts\scrapy-script.py", line 10, in &lt;module&gt; sys.exit(execute()) File "C:\Users\Nikeshh\Anaconda2\lib\site-packages\scrapy\cmdline.py", line 149, in execute cmd.crawler_process = CrawlerProcess(settings) File "C:\Users\Nikeshh\Anaconda2\lib\site-packages\scrapy\crawler.py", line 252, in __init__ log_scrapy_info(self.settings) File "C:\Users\Nikeshh\Anaconda2\lib\site-packages\scrapy\utils\log.py", line 149, in log_scrapy_info for name, version in scrapy_components_versions() File "C:\Users\Nikeshh\Anaconda2\lib\site-packages\scrapy\utils\versions.py", line 35, in scrapy_components_versions ("pyOpenSSL", _get_openssl_version()), File "C:\Users\Nikeshh\Anaconda2\lib\site-packages\scrapy\utils\versions.py", line 43, in _get_openssl_version import OpenSSL File "C:\Users\Nikeshh\Anaconda2\lib\site-packages\OpenSSL\__init__.py", line 8, in &lt;module&gt; from OpenSSL import crypto, SSL File "C:\Users\Nikeshh\Anaconda2\lib\site-packages\OpenSSL\crypto.py", line 16, in &lt;module&gt; from OpenSSL._util import ( File "C:\Users\Nikeshh\Anaconda2\lib\site-packages\OpenSSL\_util.py", line 6, in &lt;module&gt; from cryptography.hazmat.bindings.openssl.binding import Binding File "C:\Users\Nikeshh\Anaconda2\lib\site-packages\cryptography\hazmat\bindings\openssl\binding.py", line 13, in &lt;module&gt; from cryptography.hazmat.bindings._openssl import ffi, lib ImportError: DLL loa…
type: Question
has answer: http://stackoverflow.com/a/51335016

http://stackoverflow.com/a/78619698
type: Answer
score: 0
has body: If your looking to ignore this, you can use this function. def exists(path: pathlib.Path): return path.exists() and str(path).replace(" ", "") not in ["", ".", "\\"] This will exclude the current directory by use of any spaces, dots, or slashes.
answers question: http://stackoverflow.com/q/51330297

http://stackoverflow.com/comment/89664766
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51341124
score: 0
has text: obviously it makes outer table cell either collapse or shrink to the page itself, is there a better way to handle inner table? and sorry i didn't mention outer table in previous code!

http://stackoverflow.com/comment/89847732
type: Comment
type: QuestionComment
has text: `"557e155fc5f0": "calls":{1}` is not valid syntax. What's the `:{1}` supposed to be?
score: 0
comment on: http://stackoverflow.com/q/51438810

http://stackoverflow.com/q/51361689
has answer: http://stackoverflow.com/a/51362136
has comment: http://stackoverflow.com/comment/89696141
score: 0
has answer: http://stackoverflow.com/a/73083960
has comment: http://stackoverflow.com/comment/107547076
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/43758508
tagged with: sqlalchemy
has title: FLASK After commit causes odd IntegrityError violates unique constraint
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/89706890
has body: UPDATE / CLARIFICATION I confirmed that this strange behavior only occurs on the macOS machine, moving everything to a windows machine (using sqlite and doing a fresh init and migrate) doesn't cause the error... doing the same on my High Sierra box does cause the odd error. Is anyone familiar with some known difference between sqlalchemy on Windows and macOS that might help? Short version... I'm getting an integrity error (unique constraint) after I try to commit ANY entry to the DB, even if there are NO EXISTING entries at all in the table... why? DETAILS I've built a FLASK project (roughly based on the Miguel Grinberg Flask Maga Tutorial) using postgresql and sqlalchemy, the front-end has a page to register a user with a confirmation email (which works fine)... to save time I've written a route (see below) which pre-loads a confirmed user to the Users database, this user is the ONLY user in the Users table and I only visit the route ONE TIME. After a successful commit I get an IntegrityError "duplicate key value violates unique constraint". This route only adds ONE user to an existing EMPTY Users table. The data IS successfully saved to the DB, the user can log in, but an error gets thrown. I get a similar error (see below) but am focusing on this route as an example because it is shorter than other views I've written. EXAMPLE OF ROUTE CAUSING UNIQUE CONSTRAINT ERROR @main.route('/popme') #@login_required def popme(): ## add user u1 = User() u1.email = 'user@domain.com' u1.username = 'someuser' u1.password_hash = 'REMOVED' u1.confirmed = '1' u1.role_id = 3 u1.name = 'Some User' db.session.add(u1) db.session.commit() flash('User someuser can now login!') return redirect(url_for('main.index')) I only started getting this error after moving the entire project from a Windows machine to a MacOS machine. I'm running Python 3.6 in a virtual environment, this error occurs if I'm using sqlite3 or postgresql. I've written a much longer route which pre-fills in about 20 othe…

http://stackoverflow.com/q/51377543
tagged with: python
has title: Why are complex arithmetic operation not allowed in the while condition in python
score: 0
type: Question
has body: This function finds the number of digits in a number def getNumOfDigits(i): num = i count = 1 num = num // 10 while num != 0: count += 1 num //= 10 return count If I try to modify the while condition to divide num by 10 and check if it is not equal to 0 it throws up a syntax error. Why is this so in python? def getNumOfDigits(i): num = i count = 1 while (num //= 10)!= 0: count += 1 return count
linked to: http://stackoverflow.com/q/2603956
answer count: 1
duplicate of: http://stackoverflow.com/q/2603956
has answer: http://stackoverflow.com/a/51377617
type: UnansweredQuestion

http://stackoverflow.com/comment/89892498
type: AnswerComment
score: 0
type: Comment
has text: @NLR glad I could help. Dictionaries are bread and butter in Python, they're extremely flexible and can be applied to solve endless numbers of problems.
comment on: http://stackoverflow.com/a/51461316

http://stackoverflow.com/a/51346140
type: Answer
answers question: http://stackoverflow.com/q/51345385
has comment: http://stackoverflow.com/comment/89666426
has body: I really have no idea what you are trying to do, because your example (text) doesn't match the example (code screenshots). From your code screenshot it seems that if lookup is CRS_CTGRY, this is the main category, and if lookup is CRS_SUB_CTGRY, then this is a sub category, and the parent category id is stored in attr3. Now you want you get a dictionary object for this structure. Assuming you have all the data in your model: combined = [] lookup_indices = {} # stores parents lookup for easier access. for obj in Lookups.objects.filter(lookup='CRS_CTGY').values(): obj['subcategories'] = [] combined.append(obj) lookup_indicies[obj.pk] = len(combined) - 1 for obj in Lookups.objects.filter(lookup='CRS_SUB_CTGRY').values(): try: combined[lookup_indicies[int(obj['attr3'])]]['subcategories'].append(obj) except KeyError: print('No parent id {} found for sub cat {}'.format(obj['attr3'], obj)) print(combined)
score: 0

http://stackoverflow.com/q/51439723
tagged with: python
type: AnsweredQuestion
has title: How to read data only for a specified period with netCDF4 module?
has comment: http://stackoverflow.com/comment/89854384
tagged with: netcdf
has comment: http://stackoverflow.com/comment/89854520
accepted answer: http://stackoverflow.com/a/51444903
type: Question
tagged with: netcdf4
has comment: http://stackoverflow.com/comment/89850636
score: 0
linked to: http://stackoverflow.com/q/51323528
answer count: 1
has body: I'd like to read netCDF data for a specified period. What I try to read ncfile is named file.nc and the part of information of ncdump -c file.nc is dimensions: lat = 1 ; lon = 1 ; time = UNLIMITED ; // (744 currently) variables: float lat(lat) ; lat:units = "degrees_north" ; lat:long_name = "latitude" ; float lon(lon) ; lon:units = "degrees_east" ; lon:long_name = "longitude" ; double time(time) ; time:units = "hours since 2015-07-01 01:00:00" ; time:long_name = "time" ; double rain(time, lat, lon) ; rain:_FillValue = -999000000. ; rain:units = "K" ; rain:standard_name = "temperature" data: lat = 1 ; lon = 1 ; time = -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, ... 737, 738, 739, 740, 741, 742 ; And here is my script for reading this ncfile. import netCDF4 nc = netCDF4.Dataset(file.nc, 'r') data = nc.variables['temperature'][:] #I want to read between 2015-07-20 00:00 to 2015-07-24 23:00 I want to read between specific period with detecting the start date and end date. How to go abount it ?
has comment: http://stackoverflow.com/comment/89850821
has comment: http://stackoverflow.com/comment/89853849
has answer: http://stackoverflow.com/a/51444903

http://stackoverflow.com/q/51411713
linked to: http://stackoverflow.com/q/30720665
has body: In a pygame code I wannted to do a title that changes colors. I tried to do a simple title that changes colors, but it not even turned the color to blue (or do it for a second), and the program crash. The code: title_font = pygame.font.SysFont("monospace", TITLE_SIZE) while True: title = title_font.render("game", 5, RED) game_display.blit(title, TITLE_POS) pygame.display.update() pygame.time.wait(2000) title = title_font.render("game", 5, BLUE) game_display.blit(title, TITLE_POS) pygame.display.update() pygame.time.wait(3000) title = title_font.render("game", 5, RED) game_display.blit(title, TITLE_POS) pygame.display.update() pygame.time.wait(2000) It also happens with pygame.time.delay(), and I don't know where is the problem...
answer count: 1
tagged with: python
tagged with: pygame
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51412997
upvote count: 3
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51412997
type: Question
has title: pygame.time.wait() crashes the program
downvote count: 0

beautifulsoup
tags question: http://stackoverflow.com/q/51444908
tags question: http://stackoverflow.com/q/51439084
tags question: http://stackoverflow.com/q/51407233
tags question: http://stackoverflow.com/q/51340868
tags question: http://stackoverflow.com/q/51334779
tags question: http://stackoverflow.com/q/51346298
tags question: http://stackoverflow.com/q/51334045
tags question: http://stackoverflow.com/q/51381774
tags question: http://stackoverflow.com/q/51340386
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/51410127
tags question: http://stackoverflow.com/q/51465148
tags question: http://stackoverflow.com/q/51459586
tags question: http://stackoverflow.com/q/51371150
tags question: http://stackoverflow.com/q/51364142
tags question: http://stackoverflow.com/q/51343217
tags question: http://stackoverflow.com/q/51429760
tags question: http://stackoverflow.com/q/51360522
tags question: http://stackoverflow.com/q/51460053
tags question: http://stackoverflow.com/q/51409289
tags question: http://stackoverflow.com/q/51366006
tags question: http://stackoverflow.com/q/51330761
tags question: http://stackoverflow.com/q/51432887
tags question: http://stackoverflow.com/q/51434949
tags question: http://stackoverflow.com/q/51344407
tags question: http://stackoverflow.com/q/51369628
tags question: http://stackoverflow.com/q/51343017
tags question: http://stackoverflow.com/q/51402315
tags question: http://stackoverflow.com/q/51464031
tags question: http://stackoverflow.com/q/51414216
tags question: http://stackoverflow.com/q/51450243
tags question: http://stackoverflow.com/q/51340812
tags question: http://stackoverflow.com/q/51392166
tags question: http://stackoverflow.com/q/51348996
tags question: http://stackoverflow.com/q/51395399
tags question: http://stackoverflow.com/q/51469628
type: Tag
tags question: http://stackoverflow.com/q/51453469
tags question: http://stackoverflow.com/q/51482378
tags question: http://stackoverflow.com/q/51469860
tags question: http://stackoverflow.com/q/51433739
tags question: http://stackoverflow.com/q/51389843
tags question: http://stackoverflow.com/q/51328381
tags question: http://stackoverflow.com/q/51401638
tags question: http://stackoverflow.com/q/51419625
tags question: http://stackoverflow.com/q/51351341
tags question: http://stackoverflow.com/q/51437855
tags question: http://stackoverflow.com/q/51365527
tags question: http://stackoverflow.com/q/51352928
tags question: http://stackoverflow.com/q/51369889
tags question: http://stackoverflow.com/q/51461701
tags question: http://stackoverflow.com/q/51382162
tags question: http://stackoverflow.com/q/51372158
tags question: http://stackoverflow.com/q/51389443
tags question: http://stackoverflow.com/q/51344740
tags question: http://stackoverflow.com/q/51413605
tags question: http://stackoverflow.com/q/51481690
tags question: http://stackoverflow.com/q/51344556
tags question: http://stackoverflow.com/q/51389783
tags question: http://stackoverflow.com/q/51455383
tags question: http://stackoverflow.com/q/51344081
tags question: http://stackoverflow.com/q/51390462
tags question: http://stackoverflow.com/q/51419743
tags question: http://stackoverflow.com/q/51391618
tags question: http://stackoverflow.com/q/51389107
tags question: http://stackoverflow.com/q/51374189
tags question: http://stackoverflow.com/q/51417399
tags question: http://stackoverflow.com/q/51480109
tags question: http://stackoverflow.com/q/51464939
tags question: http://stackoverflow.com/q/51452263
tags question: http://stackoverflow.com/q/51461463
tags question: http://stackoverflow.com/q/51428057
tags question: http://stackoverflow.com/q/51354714
tags question: http://stackoverflow.com/q/51331028
tags question: http://stackoverflow.com/q/51332185
tags question: http://stackoverflow.com/q/51384570

http://stackoverflow.com/q/51333107
has answer: http://stackoverflow.com/a/51365593
tagged with: python
tagged with: css
has comment: http://stackoverflow.com/comment/89642084
has comment: http://stackoverflow.com/comment/89642327
has body: I am figuring out how to use django, and this is my first project (other than the tutorial). I am trying to apply some css to my html using static files, but I see no change in the html. I tried displaying an image just to see if there was something wrong with my css, but that didn't work either. When I run python manage.py collectstatic it is collecting my files so I know that it can find them. What am I doing wrong? Here is the head of my html file: {% load static %} &lt;html&gt; &lt;head&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;link rel="stylesheet" href="{% static 'mainpage/mainpage.css' %}"&gt; &lt;/head&gt; And here is where I try to load the image: &lt;img src="{% static 'mainpage/example.jpg' %}" alt="Example Image"&gt; The css file (this is just the mainpage one, but the others are similar): h1 { color: green; } li a { color: green; } header { background-color: black; } And my file structure: abstract | |---mainpage | | | |--- static | | | | | |---mainpage | | | | | | | |---mainpage.css | | | | | | | |---example.jpg Again, it can find the files, so that is not the problem. Any help would be greatly appreciated.
upvote count: 2
has comment: http://stackoverflow.com/comment/89703481
has title: Django not applying css files or displaying image
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89642461
tagged with: django
type: Question
answer count: 2
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51333635
favorite count: 0

http://stackoverflow.com/a/51424542
accepted answer of: http://stackoverflow.com/q/51424439
answers question: http://stackoverflow.com/q/51424439
score: 0
type: AcceptedAnswer
type: Answer
has body: As was told in the comments, you have empty string at the end of the data. You can filter all empty strings out in loading phase like this: f=open("C:\$%$%$%$.csv","r") data=f.read() rows = data.split('\n') final_data = [] for row in rows: split_list = row.split(',') if len(split_list) == 1: continue final_data.append(split_list)

http://stackoverflow.com/a/51438975
downvote count: 0
has body: If I understood you correctly, you can use this: df = df.groupby('d').filter(lambda x: any(x['status'] == True)) df = df.groupby('d').filter(lambda x: any(x['status'] == False)) Output: d name status 0 1 test True 3 1 test False And in case after apply drop_duplicates: df = df.drop_duplicates(subset=['d'])
answers question: http://stackoverflow.com/q/51438813
type: Answer
accepted answer of: http://stackoverflow.com/q/51438813
has comment: http://stackoverflow.com/comment/89848317
score: 1
has comment: http://stackoverflow.com/comment/89848278
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/89775667
score: 0
has text: @RenanB, my bad you are absolutely right.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51392673

http://stackoverflow.com/a/51389900
has body: A ternary statement is of the form: &lt;object&gt; = &lt;object&gt; if &lt;boolean expression&gt; else &lt;object&gt; But pass is not an &lt;object&gt;! pass is a keyword, and it is used for flow control (NOOP). For instance, you can't assign pass to a variable: &gt;&gt;&gt; x = pass Syntax Error In the same way, you can't assign other keywords such as while to variables either: &gt;&gt;&gt; x = while Syntax Error Also, append returns None, which is certainly an &lt;object&gt;. &gt;&gt;&gt; print([].append(420)) None
downvote count: 0
has comment: http://stackoverflow.com/comment/89752123
has comment: http://stackoverflow.com/comment/89752204
upvote count: 6
accepted answer of: http://stackoverflow.com/q/51389834
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51389834
has comment: http://stackoverflow.com/comment/89754426
type: Answer
score: 6

http://stackoverflow.com/q/51412396
has comment: http://stackoverflow.com/comment/89797124
tagged with: heroku
upvote count: 5
answer count: 2
score: 5
has comment: http://stackoverflow.com/comment/89796718
downvote count: 0
has answer: http://stackoverflow.com/a/73054618
tagged with: websocket
has title: ModuleNotFoundError: No module named 'geventwebsocket'
tagged with: flask
favorite count: 0
tagged with: gunicorn
has answer: http://stackoverflow.com/a/62426926
type: UnansweredQuestion
tagged with: python
has body: Can't run my web-socket site on Heroku cloud with gunicorn. Locally ('heroku local') its working fine, but when i try to acess my site URL it gets crashed. Logs: 2018-07-18T20:45:32.563241+00:00 app[web.1]: Error: class uri 'geventwebsocket.gunicorn.workers.GeventWebSocketWorker' invalid or not found: 2018-07-18T20:45:32.563242+00:00 app[web.1]: 2018-07-18T20:45:32.563244+00:00 app[web.1]: [Traceback (most recent call last): 2018-07-18T20:45:32.563246+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 132, in load_class 2018-07-18T20:45:32.563247+00:00 app[web.1]: mod = import('.'.join(components)) 2018-07-18T20:45:32.563249+00:00 app[web.1]: ModuleNotFoundError: No module named 'geventwebsocket' 2018-07-18T20:45:32.563250+00:00 app[web.1]: ]
has comment: http://stackoverflow.com/comment/89837283
type: Question

http://stackoverflow.com/q/51407938
has comment: http://stackoverflow.com/comment/89790841
has comment: http://stackoverflow.com/comment/89789929
has answer: http://stackoverflow.com/a/66809647
answer count: 1
has title: Using sympy for symbolic math, the code runs forever
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89787851
has comment: http://stackoverflow.com/comment/89788267
tagged with: python
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/118099400
has body: I am trying to solve simultaneous equations for x and y, I am not getting any result (code just keeps on running). I feel the error is related to using sqrt in the equations but not sure. Can someone help me figure this out? from __future__ import division from sympy import Symbol,sqrt,solve x = Symbol('x') y = Symbol('y') z = Symbol('z') a = Symbol('a') b = Symbol('b') c = Symbol('c') d = Symbol('d') e = Symbol('e') f = Symbol('f') g = Symbol('g') h = Symbol('h') print (solve((sqrt((c-a)**2+(d-b)**2)+sqrt((x-c)**2+(y-d)**2)-2*sqrt((x-a)**2+(y-b)**2),(y-b)*(e-a)-(x-a)*(f-b)) ,x,y))
tagged with: sympy
downvote count: 0
score: 4

http://stackoverflow.com/comment/89718198
comment on: http://stackoverflow.com/q/51344293
score: 0
type: Comment
type: QuestionComment
has text: Hello @BryanOakley, when I asked possible I meant that I want to find possible English word(s) from a Bitcoin address. It is like those puzzle where you see bunch of alphabets in a square and whatever word you see first is reflects your personality or you want in life etc. So for a bitcoin address you might see a word, I might see different word and some other person might see both of our words and may be one or two more different words.

http://stackoverflow.com/q/51342724
answer count: 1
has comment: http://stackoverflow.com/comment/89659066
has comment: http://stackoverflow.com/comment/89659469
has title: How to estimate gaussian distribution parameters using MLE in Python
favorite count: 0
has body: I've got a set of data with Gaussian distribution, here is a histogram that shows how they actually look like: I have to classify these data into two class using bayesian classifier, which I'm doing that using sklearn and it's working fine. However as a part of job I have to estimate the distribution parameters of data (σ, μ) using MLE and use them in my classifier. So is there any python library or pseudo code that can estimate the gaussian distribution parameters using maximum likelihood method so I can use the estimated values in my classifier? I'm looking for something like mle(data,'distribution',dist) from Matlab. phat = mle(MPG,'distribution','burr') phat = 34.6447 3.7898 3.5722
tagged with: pattern-recognition
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89659233
tagged with: machine-learning
has answer: http://stackoverflow.com/a/51342995
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/89659045
downvote count: 0
has comment: http://stackoverflow.com/comment/89659655
has comment: http://stackoverflow.com/comment/89659541
has comment: http://stackoverflow.com/comment/89658998
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/89659364
has comment: http://stackoverflow.com/comment/89659152
tagged with: statistics
has comment: http://stackoverflow.com/comment/89659089

ipython-parallel
type: Tag
tag name: ipython-parallel
tags question: http://stackoverflow.com/q/51335889

http://stackoverflow.com/comment/89891346
comment on: http://stackoverflow.com/q/51460718
has text: @juanpa. Not to mention being very opinion/situation based. In most cases both approaches can be made to yield identical results.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89881429
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51455934
has text: Which file has all the imports ? run it on that file

http://stackoverflow.com/a/51473839
has body: You can pass the years as options, and then use these when filtering: from django.db.models.functions import ExtractYear class SearchByYear(admin.SimpleListFilter): title = _('title') parameter_name = 'year' def lookups(self, request, model_admin): year_list = models.Event.objects.annotate( y=ExtractYear('date') ).order_by('y').values_list('y', flat=True).distinct() return [ (str(y), _(str(y))) for y in year_list ] def queryset(self, request, queryset): if self.value() is not None: return queryset.filter(date__year=self.value()) return queryset We thus use the lookups to fetch the different years, later we then filter on the selected year, with a .filter(date__year=self.value()) query. The translation _(str(y)) is not strictly necessary. It could be useful if years are translated differently in some cultures (for example Chinese/Japanese/Roman years). But there is usually no problem translating years, since if no translation is found, the translation will perform a "fallback" to the original value.
type: Answer
has comment: http://stackoverflow.com/comment/89916450
has comment: http://stackoverflow.com/comment/89916186
has comment: http://stackoverflow.com/comment/89916505
answers question: http://stackoverflow.com/q/51473652
score: 5
accepted answer of: http://stackoverflow.com/q/51473652
type: AcceptedAnswer
upvote count: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/89916005

http://stackoverflow.com/comment/89722416
has text: No, it is a dict. The string annotated with colons is the key which corresponds to a data entry in the dict. The dict looks like many hundreds of entries of {"index1:index2:...:indexN" : data_val}
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51375389
score: 0

http://stackoverflow.com/a/51478135
answers question: http://stackoverflow.com/q/51477926
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51477926
type: Answer
downvote count: 1
score: -1
has comment: http://stackoverflow.com/comment/89924953
has body: Try this: conda config --add channels conda-forge conda install r-boruta Source: https://github.com/conda-forge/r-boruta-feedstock
has comment: http://stackoverflow.com/comment/89925389
has comment: http://stackoverflow.com/comment/89924888
upvote count: 0
has comment: http://stackoverflow.com/comment/89925264

http://stackoverflow.com/q/51432962
has answer: http://stackoverflow.com/a/54933629
tagged with: sqlalchemy
type: Question
score: 5
has body: I'm triying to display results from a firebird 3.x database, but get: File "/...../Envs/pos/lib/python3.6/site-packages/fdb/fbcore.py", line 479, in b2u return st.decode(charset) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd1 in position 9: invalid continuation byte Despite I set utf-8 everywhere: # -- coding: UTF-8 -- import os os.environ["PYTHONIOENCODING"] = "utf8" from sqlalchemy import * SERVIDOR = "localhost" BASEDATOS_1 = "db.fdb" PARAMS = dict( user="SYSDBA", pwd="masterkey", host="localhost", port=3050, path=BASEDATOS_1, charset='utf-8' ) firebird = create_engine("firebird+fdb://%(user)s:%(pwd)s@%(host)s:%(port)d/%(path)s?charset=%(charset)s" % PARAMS, encoding=PARAMS['charset']) def select(eng, sql): with eng.connect() as con: return eng.execute(sql) for row in select(firebird, "SELECT * from clientes"): print(row)
answer count: 2
tagged with: unicode
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92741989
upvote count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/57809876
tagged with: python
has title: UnicodeError with SqlAlchemy + Firebird + FDB
downvote count: 0
has comment: http://stackoverflow.com/comment/96544244

http://stackoverflow.com/a/51359991
has comment: http://stackoverflow.com/comment/89697561
accepted answer of: http://stackoverflow.com/q/51358987
answers question: http://stackoverflow.com/q/51358987
has comment: http://stackoverflow.com/comment/89710997
has comment: http://stackoverflow.com/comment/114780258
downvote count: 0
has comment: http://stackoverflow.com/comment/89697947
score: 1
has body: It could be more helpful if errors/output from your pip run was shared, I guess there are more details in pip logs. Usually something like this is a good hint where you can find the errors: Command "python setup.py egg_info" failed with error code 1 in /some/path I'd first check if pylint is actually installed pip list | grep pylint If not, then follow the errors from pip install. But if pylint is available yet running pylint is the problem (command not found), it's because the command line entry point is not installed properly. Then it may be run like this: python -m pylint --help On a side note, generally using virtual environments are a nice way to install packages/software on user accessible paths, and to install executable programs (as opposed to library packages) to local user accessible paths, I suggest using something like pipsi instead of pip, which handles creating/activating the virtualenv automatically. Update As discussed on the comments, since your current installation is OK and it's just the command line entry point missing, you could add a Python file (with exec permissions) somewhere in your path for each of the entry points, like this: #!/usr/bin/env python from pylint import run_pylint if __name__ == '__main__': run_pylint()
type: AcceptedAnswer
upvote count: 1
has comment: http://stackoverflow.com/comment/89721112
type: Answer

http://stackoverflow.com/q/51443154
type: UnansweredQuestion
tagged with: python
has body: Here is my problem : I have a mongodb database with +1 million entries and I have to count distinct entries. Every entry has a doc_id composed of the communication number and the document number, here is an example : EGNG9876543219876543219-000.pdf The part composed of 4 capital letters and 19 digits is the communication number. The thing is that for each communication number there are multiple documents (the "-000.pdf part). I tried to do it this way : docIds=list(collection.find({}, {"doc_id" : 1,"_id":0})) comIds=[] for i in range (docIds.count("doc_id")): comIds.append(docIds[i][:-8]) print(len(set(comIds))) I would like to know if there is a way in mongodb to count how many distinct communication numbers there are.
type: Question
tagged with: mongodb
has comment: http://stackoverflow.com/comment/89856322
has title: Mongodb/python Count different rows containing different values
has comment: http://stackoverflow.com/comment/89856523
score: 0
tagged with: distinct
answer count: 0

http://stackoverflow.com/q/51355719
type: UnansweredQuestion
score: 1
has body: one day I just wonder how to implement str, list and map methods in python. when I tried to "go to definition" for split() and the code seems like def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__ """ S.split(sep=None, maxsplit=-1) -&gt; list of strings Return a list of the words in S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result. """ return [] How can I find those method's codes?
downvote count: 1
has comment: http://stackoverflow.com/comment/89684055
type: Question
has comment: http://stackoverflow.com/comment/89683921
favorite count: 0
has title: where can I find implementation of str method in python?
linked to: http://stackoverflow.com/q/40332743
tagged with: python
duplicate of: http://stackoverflow.com/q/40332743
answer count: 0
upvote count: 2

http://stackoverflow.com/q/51420715
answer count: 3
has comment: http://stackoverflow.com/comment/89812568
has answer: http://stackoverflow.com/a/51421092
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51421649
type: Question
has answer: http://stackoverflow.com/a/51421116
accepted answer: http://stackoverflow.com/a/51421092
has body: I did this, &gt;&gt;&gt; d1 = datetime.date(2018, 7, 26) &gt;&gt;&gt; d2 = datetime.date(2018, 10, 14) &gt;&gt;&gt; dif = d2 - d1 &gt;&gt;&gt; start_mon =(d1 - datetime.timedelta(days=d1.weekday())) &gt;&gt;&gt; num_of_weeks = math.ceil((d2 - start_mon).days / 7.0) &gt;&gt;&gt; num_of_weeks 12 &gt;&gt;&gt;xp = [d1 + datetime.timedelta(i) for i in range( math.ceil((D2 - start_mon).days / 7.0))] &gt;&gt;&gt; [datetime.date(2018, 7, 26), datetime.date(2018, 7, 27), datetime.date(2018, 7, 28), datetime.date(2018, 7, 29), datetime.date(2018, 7, 30), datetime.date(2018, 7, 31), datetime.date(2018, 8, 1), datetime.date(2018, 8, 2), datetime.date(2018, 8, 3), datetime.date(2018, 8, 4), datetime.date(2018, 8, 5), datetime.date(2018, 8, 6)] I want python to give me the weekdays between 12 weeks. So since the start date is 2018-07-26, the next date should be 2018-08-02, next should also be 2018-07-09 till it ends at 2018-10-11 . and if if after count it's 12 weeks. e.g 2018-07-26 2018-08-02 2018-08-09 2018-08-16 2018-08-23 2018-08-30 2018-09-06 2018-09-13 2018-09-20 2018-09-27 2018-10-04 2018-10-11 what am I missing?
possible better answer: http://stackoverflow.com/a/51421116
has title: Add days and loop over dates for a number of weeks
score: 0
has comment: http://stackoverflow.com/comment/89812490

http://stackoverflow.com/q/51335930
has comment: http://stackoverflow.com/comment/89657728
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has title: Read text file and format data using python, dict or list
upvote count: 0
tagged with: list
has answer: http://stackoverflow.com/a/51336136
type: Question
has comment: http://stackoverflow.com/comment/89647061
score: -1
has body: Hi I need help parsing following data from text file and reformating it to the way the output is shown, so it basically counts the state and adds its number in the new column, also it removes duplicate address (if they have same date and IP) Sample Input Data to read 11/11/2015 9.9.9.9 30s success 11/11/2015 9.9.9.8 30s stuck 11/11/2015 9.9.9.9 30s Sync 11/11/2015 9.9.9.9 30s success 11/12/2015 9.9.9.9 30s success 11/12/2015 9.9.9.9 30s stuck 11/12/2015 9.9.9.9 30s stuck 11/12/2015 9.9.9.9 30s success 11/12/2015 9.9.9.8 30s success 11/12/2015 9.9.9.9 30s success 11/12/2015 9.9.9.9 30s stuck 11/12/2015 9.9.9.9 30s success 11/12/2015 9.9.9.9 30s Sync 11/12/2015 9.9.9.9 30s Sync Output Data to print 11/11/2015 9.9.9.9 success 2 11/11/2015 9.9.9.8 stuck 1 11/11/2015 9.9.9.9 Sync 1 11/12/2015 9.9.9.9 success 4 11/12/2015 9.9.9.9 stuck 3 11/12/2015 9.9.9.9 Sync 2 11/12/2015 9.9.9.8 success 1 I tried to load my file using following, but failed to reformat it correct. file=open('logfile.txt' , 'r') contents=file.readlines() for line in contents:
answer count: 2
has comment: http://stackoverflow.com/comment/89646987
downvote count: 1
has comment: http://stackoverflow.com/comment/89647144
favorite count: 0
has answer: http://stackoverflow.com/a/51336176

http://stackoverflow.com/comment/89662711
comment on: http://stackoverflow.com/q/51337067
type: QuestionComment
score: 0
has text: @Tonechas check the code on the above link
type: Comment

http://stackoverflow.com/comment/89628092
score: 0
type: Comment
type: QuestionComment
has text: If you are trying to export a graph, this might help: https://stackoverflow.com/questions/35634238/how-to-save-a-pandas-dataframe-table-as-a-png
comment on: http://stackoverflow.com/q/51325601

http://stackoverflow.com/q/51479503
score: 3
has body: I have two pandas DataFrame, which called df1 and df2. I want to sum the list values in df2 which the list's values come from df1. For example: df1: df1 = pd.DataFrame([['a',11],['b',13],['c',45],['d',88]],columns=['name1','data1']) df1 name1 data1 0 a 11 1 b 13 2 c 45 3 d 88 and df2: df2 = pd.DataFrame([['a',['b','c','d']],['b',['a','c']]],columns=['name2','data2']) df2 name2 data2 0 a [b, c, d] 1 b [a, c] Finally, I want this: name2 data2 0 a 146 1 b 56 How? Thanks a lot.
has title: How to sum the values of a list's elements which elements' values come from anthor dataframe in pandas?
has answer: http://stackoverflow.com/a/51479771
tagged with: pandas
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51479747
tagged with: python
answer count: 4
linked to: http://stackoverflow.com/q/11620914
has answer: http://stackoverflow.com/a/51479673
has answer: http://stackoverflow.com/a/51479557
upvote count: 3
type: UnansweredQuestion
type: Question

http://stackoverflow.com/comment/89649094
comment on: http://stackoverflow.com/q/51336897
score: 0
has text: When Pandas reads a JSON file, it loads it into memory using Python's `json` module (the relevant line from your stacktrace is https://github.com/pandas-dev/pandas/blob/v0.23.3/pandas/io/json/json.py#L853, which calls through to `json.loads`). If loading your data into a plain dictionary with `json.load()` gives the same error, then you can rule out Pandas the problem. There are a few questions on SO about problems with loading large JSON files (e.g. https://stackoverflow.com/questions/10382253/reading-rather-large-json-files-in-python) - so this is the first thing to try.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89868555
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51439004
has text: This would work similar to how word2vec often achieves good vectors for common-misspellings. As long as your downstream applications perform the same kind of naive dehyphenization on other texts you're analyzing, you'd plausibly get some value from these frankenstein-tokens – possibly more than the alternate naive policy of "doing nothing with trailing-hyphen prefixes".
type: AnswerComment

http://stackoverflow.com/q/51393270
has answer: http://stackoverflow.com/a/51393305
score: 1
has title: How to properly delete data from json with python
favorite count: 0
upvote count: 2
tagged with: python
has body: Im trying to find the proper way to delete json data with python. My goal with the python script is to remove the contact that the user inputs. I want to remove their email, number, and name but keep the rest of my contacts. My json looks like this: { "contacts": { "example_contact": { "email": "email@domain.com", "number": "phone number" } } }
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51393305
tagged with: http://stackoverflow.com/tag/json
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89758331
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/89797895
answer count: 1

http://stackoverflow.com/comment/89689458
has text: perfect answer thankyou! so i guess the order in which the coordinates is listed in a rectangle is important to know, which seemed to be difficult for me to find but i guess i was searching the wrong thing...
type: AnswerComment
comment on: http://stackoverflow.com/a/51358557
score: 0
type: Comment

http://stackoverflow.com/a/51351746
has comment: http://stackoverflow.com/comment/89676203
has comment: http://stackoverflow.com/comment/89676270
accepted answer of: http://stackoverflow.com/q/51351705
has comment: http://stackoverflow.com/comment/89676201
answers question: http://stackoverflow.com/q/51351705
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89676168
downvote count: 0
has body: In fact this looks like a comma separated list of JSON blobs. We can convert this to a list as follows: from json import loads as jsonload data = jsonload('[{}]'.format(request.POST[manager_type_item])) These are JSON blobs, so we can decode these with json.loads, and then process these, like: for itm in data: Tag.objects.create(**itm) or in case the dictionaries contain other elements that do not belong to the model: for itm in data: Tag.objects.create(id=itm['id'], title=itm['title']) We thus use a mapping to convert these JSON blobs first to there relevant vanilla Python objects (here dictionaries that map strings to strings), and then turn the given elements into a Tag (or something else). Or in bulk: Tag.objects.bulk_create([Tag(**itm) for itm in data])
type: Answer
has comment: http://stackoverflow.com/comment/89676219
has comment: http://stackoverflow.com/comment/89676231
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/89676299
has comment: http://stackoverflow.com/comment/89676341

http://stackoverflow.com/comment/89879733
score: 2
has text: @Aprillion No they won't. Python lists cannot be added with numericals. Works for numpy arrays as arrays can be broadcasted with scalars.
type: Comment
comment on: http://stackoverflow.com/q/51455074
type: QuestionComment

mfcc
type: Tag
tag name: mfcc
tags question: http://stackoverflow.com/q/51329234

http://stackoverflow.com/comment/89923778
comment on: http://stackoverflow.com/a/51475924
type: Comment
has text: Hey, if you come up with a better solution, multi-processed or multi-threaded or something of that kind, let me know! I'll also do the same if I develop one.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89686193
type: Comment
comment on: http://stackoverflow.com/a/51356971
has text: Btw, it should work if you add 'client' to the Meta.fields tuple. In that case, you should not need to set it in the create and it should be handled for you automatically.
score: 0
type: AnswerComment

joystick
type: Tag
tags question: http://stackoverflow.com/q/51327011
tag name: joystick
tags question: http://stackoverflow.com/q/51467197

http://stackoverflow.com/a/51470515
answers question: http://stackoverflow.com/q/51470408
type: Answer
has body: You can use set_xticklabels import matplotlib.pyplot as plt import numpy as np star_masses = np.array([0.359, 0.325,0.842, 0.359, 0.245, 0.445, 0.558, 0.117, 0.245, 0.177, 0.558, 0.058, 0.637, 0.222, 0.245, 0.039, 0.177]) star_names= ['star%i'%ii for ii in range(13)] M2 = [] M12 = [] K7 = [] M6 = [] M1 = [] M0 = [] M5 = [] M35 = [] M42 = [] M625 = [] M37 = [] T6 = [] M8 = [] for i in star_masses: if i == 0.359: M2.append(i) if i == 0.325: M12.append(i) if i == 0.842: K7.append(i) if i == 0.245: M6.append(i) if i == 0.445: M1.append(i) if i == 0.558 or 0.637: M0.append(i) if i == 0.117: M5.append(i) if i == 0.245: M35.append(i) if i == 0.058: M625.append(i) if i == 0.222: M37.append(i) if i == 0.039: T6.append(i) if i == 0.177: M8.append(i) f, ax = plt.subplots() ax.hist(star_masses, bins = 15) ax.set_xlabel('Stellar Mass') ax.set_xticklabels(star_names) ax.set_ylabel('# of Stars') ax.set_title ('Stellar Mass') plt.show()
score: 0

http://stackoverflow.com/comment/89630907
comment on: http://stackoverflow.com/q/51324477
score: 0
type: QuestionComment
type: Comment
has text: You may want to open a different question for other parts, also note that if your Fortran code does use arrays elsewhere, Fortran arrays are 1-indexed instead of 0-indexed as Python/C/Java/most other languages I use are

http://stackoverflow.com/comment/89745605
score: 0
type: Comment
type: QuestionComment
has text: Tried what? The linked question has half a dozen answers, and your code doesn't implement any one of them.
comment on: http://stackoverflow.com/q/51386585

http://stackoverflow.com/comment/89907879
has text: @Xzm Sure, I've updated my answer to include a symbolic version of the function.
type: Comment
comment on: http://stackoverflow.com/a/51452053
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89693238
type: Comment
type: QuestionComment
has text: @brunodesthuilliers: Sorry, my bad. I think I must have meant that requests calls `loads` from the `json` library.
comment on: http://stackoverflow.com/q/51360372
score: 0

http://stackoverflow.com/q/51345579
upvote count: 3
has answer: http://stackoverflow.com/a/51346284
answer count: 1
accepted answer: http://stackoverflow.com/a/51346284
tagged with: grouping
tagged with: python
has comment: http://stackoverflow.com/comment/89664916
has body: I have a list of sets of the form animals[0] = {'cat', 'cow', 'dog'} animals[1] = {'cat', 'cow', 'pig'} animals[2] = {'cat', 'dog', 'fish'} animals[3] = {'tiger', 'fish', 'pig'} animals[4] = {'dog', 'fish', 'pig'} How can I group sets that have at least 2 similar items ? To make it simple, I will use a dict whose key is the first element of the overlapping set and do not care if some of the items belonging to that key have lesser than 2 similar items. For example, g['cat'] = [0,1,2] g['fish'] = [2,3,4] because list 0 and 1 have the overlapping items cat and cow and list 0 and 2 have the overlapping items cat and dog. list 1 and 2 however, only have the overlapping item cat but are still included in the dict. A simple brute force approach would be to iterate through the entire list and check each list with every other list. for i,x in enumerate(animals): for j,y in enumerate(animals): intersection = x &amp; y if(len(intersection)&gt;=2): dict[list(intersection)[0]].append(j) But this is very time consuming if I have a very large list I think and so I would like to learn a better way to do this. If anyone has any function to recommend.
type: AnsweredQuestion
score: 3
downvote count: 0
tagged with: set
has comment: http://stackoverflow.com/comment/89664644
type: Question
has comment: http://stackoverflow.com/comment/89665194
has title: Efficiently grouping sets based on number of similar items
has comment: http://stackoverflow.com/comment/89664684
favorite count: 0

http://stackoverflow.com/q/51330932
has comment: http://stackoverflow.com/comment/89639107
has comment: http://stackoverflow.com/comment/89637918
type: Question
has comment: http://stackoverflow.com/comment/89638971
has comment: http://stackoverflow.com/comment/89637664
has comment: http://stackoverflow.com/comment/89639317
has comment: http://stackoverflow.com/comment/89639049
linked to: http://stackoverflow.com/q/50651406
has comment: http://stackoverflow.com/comment/89637694
has comment: http://stackoverflow.com/comment/89637755
upvote count: 2
answer count: 1
downvote count: 1
has title: find the differences between two csv files and mark em
favorite count: 0
has comment: http://stackoverflow.com/comment/89637949
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/89638955
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89637806
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51361583
accepted answer: http://stackoverflow.com/a/51361583
has body: I'm making a website using Django ,the website allows users to upload 2 csv files , then the website will find the differences between those 2 files, print the differences and add a new "Changes" column. In that new column which will be for every record, every row gets a new "changes" or "addition" or "deletion" new record. Assuming there is no duplication. Here is views.py code so far. from django.shortcuts import render from django.http import HttpResponse import difflib import datetime import csv from django.http import HttpResponseRedirect from django.http import FileResponse from .forms import FileForm from .forms import UploadFileForm def handle_uploaded_file(filename_1, filename_2): """ handle_uploaded_file is a function that takes 2 files uploaded by the users """ with open(filename_1, newline='') as f_old: csv_old = csv.reader(f_old, delimiter='\t') header = next(csv_old) old_data = {row[0] : row for row in csv_old} with open(filename_2, newline='') as f_new: csv_new = csv.reader(f_new, delimiter='\t') header = next(csv_new) new_data = {row[0] : row for row in csv_new} set_new_data = set(new_data) set_old_data = set(old_data) added = [['Added'] + new_data[v] for v in set_new_data - set_old_data] deleted = [['Deleted'] + old_data[v] for v in set_old_data - set_new_data] in_both = set_old_data &amp; set_new_data changed = [['Changed'] + new_data[v] for v in in_both if old_data[v] != new_data[v]] with open('difference.csv', 'w', newline='') as f_output: csv_output = csv.writer(f_output, delimiter='\t') csv_output.writerow(['History'] + header) csv_output.writerows(sorted(added + deleted + changed, key=lambda x: x[1:])) def index(request): # index is a function for the upload button if request.method == 'POST': # POST method inserts something to the server print(request.FILES) form = UploadFileForm(request.POST, request.FILES) print(form.errors) if form.is_valid(): print("cool") handle_uploaded_file(request.FILES.get('file1'),request.FILES.get('file2')) return …

shell
tags question: http://stackoverflow.com/q/51467101
tags question: http://stackoverflow.com/q/51426929
tags question: http://stackoverflow.com/q/51472136
tags question: http://stackoverflow.com/q/51372094
tags question: http://stackoverflow.com/q/51394107
tag name: shell
tags question: http://stackoverflow.com/q/51328566
tags question: http://stackoverflow.com/q/51452342
tags question: http://stackoverflow.com/q/51384221
tags question: http://stackoverflow.com/q/51400077
tags question: http://stackoverflow.com/q/51415997
tags question: http://stackoverflow.com/q/51469569
tags question: http://stackoverflow.com/q/51336226
tags question: http://stackoverflow.com/q/51462330
type: Tag
tags question: http://stackoverflow.com/q/51329742
tags question: http://stackoverflow.com/q/51452931
tags question: http://stackoverflow.com/q/51469341
tags question: http://stackoverflow.com/q/51345198

http://stackoverflow.com/comment/89883681
has text: I think you should also have `if request.method=='GET'` to get the form data back.
comment on: http://stackoverflow.com/q/51455027
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51334551
has body: I suspect you want to encode different characters into different colour channels: for row in range(0, size[0]): for col in range(0, size[1]): if ind &gt;= text_length : break # only change pixel value for length of text r = convert_char_to_int(text[ind], limit=limit) ind = max( ind+1, text_length - 1) # don't go beyond text length g = convert_char_to_int(text[ind], limit=limit) ind = max( ind+1, text_length - 1) b = convert_char_to_int(text[ind], limit=limit) ind += 1 img.putpixel((row, col), (r,g,b))
has comment: http://stackoverflow.com/comment/89644503
answers question: http://stackoverflow.com/q/51334345
type: Answer
score: 0

http://stackoverflow.com/comment/89776061
score: 0
type: QuestionComment
has text: If by app you are referring to a Mobile APP, then YOLO does work in Android. You could use the Annotated data made for ssd architecture to YOLO too
type: Comment
comment on: http://stackoverflow.com/q/51402207

http://stackoverflow.com/comment/89641045
has text: Is finding local minima of such smoothed graph sufficient for you?
score: 0
comment on: http://stackoverflow.com/q/51331764
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51405279
has title: Substracting a date from a pandas dataframe column in linux
has answer: http://stackoverflow.com/a/51405778
tagged with: python
has comment: http://stackoverflow.com/comment/89781654
linked to: http://stackoverflow.com/q/43506680
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/89782055
upvote count: 1
type: Question
has body: I have the following datetime date value: a_date = datetime.date(2018,9,13) And a pandas dataframe df with the following column: df['somedates'] 0 2010-07-27 1 1999-02-15 2 1997-07-15 3 2012-11-15 4 1999-02-17 5 1999-02-16 6 1999-02-17 7 2012-10-12 8 1999-09-22 9 1998-05-09 10 1998-05-09 Name: somedates, Length: 11, dtype: datetime64[ns] I can do the following on my Windows machine and it works fine df['somedates'] = a_date - df['somedates'] However on ubuntu it raises the following error: unsupported operand type(s) for -: 'DatetimeIndex' and 'datetime.date Can someone point me in the right the direction on this ? Why is it running on windows but not in Linux ? More detailed info print(type(a_date)) &lt;class 'datetime.date'&gt; print(type(df['somedates'])) &lt;class 'pandas.core.series.Series'&gt; print(type(df['somedates'][0])) &lt;class 'pandas._libs.tslib.Timestamp'&gt;
accepted answer: http://stackoverflow.com/a/51405778
has comment: http://stackoverflow.com/comment/89782021
tagged with: pandas
has comment: http://stackoverflow.com/comment/89781531
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89782071
tagged with: linux
has comment: http://stackoverflow.com/comment/89781963

multi-gpu
type: Tag
tag name: multi-gpu
tags question: http://stackoverflow.com/q/51341998

http://stackoverflow.com/a/51359516
accepted answer of: http://stackoverflow.com/q/51359473
answers question: http://stackoverflow.com/q/51359473
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 6
has body: The best way is still a dictionary, but: &gt;&gt;&gt; import builtins &gt;&gt;&gt; getattr(builtins, 'int') &lt;class 'int'&gt;
score: 6

http://stackoverflow.com/a/51375911
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51375632
has comment: http://stackoverflow.com/comment/89723454
has body: I think below script work for it import pandas as pd dfd = pd.DataFrame({'A': ['Apple','Apple', 'Apple','Orange','Orange','Orange','Pears','Pears'], 'B': [1,2,9,6,4,3,2,1] }) dfd_1 = dfd.groupby(['A'], as_index=False).agg({'B': 'min'}) dfd = pd.merge(dfd_1, dfd, how='left', left_on=['A'], right_on=['A']) dfd.columns = ['A', 'new_B','old_B']
downvote count: 0

computer-vision
tags question: http://stackoverflow.com/q/51422301
tags question: http://stackoverflow.com/q/51343689
tags question: http://stackoverflow.com/q/51380692
tags question: http://stackoverflow.com/q/51467026
tags question: http://stackoverflow.com/q/51411156
tags question: http://stackoverflow.com/q/51457734
tags question: http://stackoverflow.com/q/51480396
tags question: http://stackoverflow.com/q/51465794
tags question: http://stackoverflow.com/q/51448049
tags question: http://stackoverflow.com/q/51328263
tags question: http://stackoverflow.com/q/51362927
tags question: http://stackoverflow.com/q/51369284
tags question: http://stackoverflow.com/q/51395132
tags question: http://stackoverflow.com/q/51379058
tags question: http://stackoverflow.com/q/51437992
tags question: http://stackoverflow.com/q/51420188
tags question: http://stackoverflow.com/q/51373533
tags question: http://stackoverflow.com/q/51441690
type: Tag
tags question: http://stackoverflow.com/q/51393104
tag name: computer-vision
tags question: http://stackoverflow.com/q/51421007
tags question: http://stackoverflow.com/q/51470948
tags question: http://stackoverflow.com/q/51351315
tags question: http://stackoverflow.com/q/51448085

http://stackoverflow.com/comment/89815914
has text: I am not sure where this derivation for RK4 comes from but it looks completely wrong. It looks like you are treating it as a multi-step method, but it is not.
comment on: http://stackoverflow.com/q/51422369
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51446322
tagged with: flask-sqlalchemy
favorite count: 0
has comment: http://stackoverflow.com/comment/89863321
tagged with: python
has title: Flask SQLAlchemy - set expire_on_commit=False only for current session
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89863034
upvote count: 18
has answer: http://stackoverflow.com/a/51452451
tagged with: sqlalchemy
has body: How can I set the option expire_on_commit=False only for the current session in Flask-SQLAlchemy? I can set the option at the inizialization of the SQLAlchemy object with: db = SQLAlchemy(app, session_options={"expire_on_commit": False}) but in this way all sessions created by Flask-SQLAlchemy will have the option set to False, instead i want to set it only for one session. I tried db.session.expire_on_commit = False but it does not seem to have any effect.
type: Question
downvote count: 0
score: 18
tagged with: flask
accepted answer: http://stackoverflow.com/a/51452451
answer count: 1

http://stackoverflow.com/comment/89713788
type: AnswerComment
comment on: http://stackoverflow.com/a/51370746
has text: Yes, pandas & numpy. It's [here](https://github.com/bsolomon1124/config/blob/master/ipython/startup.py) in its entirety. But please don't trouble yourself, as you said this is a minor thing and seems specific to my setup.
type: Comment
score: 0

http://stackoverflow.com/q/51369210
has body: The brill tagger in nltk, has errors when tagging the instruction data. For example: "heat until brown", would be tagged as "('heat', 'NN'), ('until', 'IN'), ('brown', 'JJ')". Most of the verbs in the instruction dataset would be tagged as 'NN'. So I want to modify the rules in the brill tagger, and to change the tag according to my cooking verb list. For example: if the there is no 'VB' before 'IN', and there is a token before 'IN', and tagged as 'NN' in my cooking verb list, then change 'NN' to 'VB'. However, I don't know how to insert my own rules in the brill tagger (specifically, I am looking at the nltk source code: https://www.nltk.org/_modules/nltk/tbl/template.html). Could anyone help with this? Thanks!
type: UnansweredQuestion
tagged with: python
tagged with: nlp
answer count: 0
score: 1
upvote count: 1
has title: How to modify rules in Brill tagger, NLTK
type: Question
tagged with: brill-tagger
tagged with: nltk
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/51388163
answers question: http://stackoverflow.com/q/51387662
score: 0
type: Answer
has body: Is it possible to list the pixel RGBs and scan through that? As John Anderson said, you can use Image.getcolors to get that. But to get the number of unique variables, you can convert it to a set, which removes duplicates, then get the length of that, with len(set(list)).
has comment: http://stackoverflow.com/comment/89836674

http://stackoverflow.com/comment/89971117
type: QuestionComment
score: 0
has text: With regard to segmentation by color, there are some options [here](https://stackoverflow.com/q/4063965/52738) you could try.
comment on: http://stackoverflow.com/q/51475343
type: Comment

http://stackoverflow.com/q/51334265
favorite count: 0
tagged with: python
linked to: http://stackoverflow.com/q/41923428
has body: I'm making a random password generator and in my script I have the following bit of code. for x in range (0, pl): y=random.randint(0,len(List)) passLet=(List[y]) password +=passLet Whenever I run the script, an error pops up stating that y is out of List's index. To add to the confusion, I have the same for statement earlier in the script that uses a random integer to retrieve a value from the exact same list but that has never had this issue. I could really use some help.
score: 2
has title: issue where len(list) is coming back as out of index
tagged with: list
answer count: 0
upvote count: 2
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/33450694
type: Question
has comment: http://stackoverflow.com/comment/89643937
duplicate of: http://stackoverflow.com/q/41923428
downvote count: 0
duplicate of: http://stackoverflow.com/q/50808055
has comment: http://stackoverflow.com/comment/89643877

http://stackoverflow.com/comment/89814126
score: 1
type: AnswerComment
has text: awesome thanks! Can't upvote. But your solution works. Thanks
comment on: http://stackoverflow.com/a/51421116
type: Comment

http://stackoverflow.com/q/51379448
has comment: http://stackoverflow.com/comment/89731054
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89731836
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: Python script execution on Apache server
score: 1
has body: So I have an Apache 2.4.6 @ CentOS 7 and I want to run a specific python script using some data from a post request from that server but I don't want for anyone to be able to look in the python source. My webdev experience in backend is minimal and by my searches so far I've figured that my options are: enabling mod_wsgi (I've already done that to test the execution of simple script without any parameters but I don't see how I connect my script functions to the form) Django application (but I don't have any experience on that and it seems like a lot of work for my purpose) I don't know any php and I am wondering what's the simplest way to perform that task without having to take up a whole new stack.
tagged with: post
type: Question
tagged with: apache
has answer: http://stackoverflow.com/a/51379585

http://stackoverflow.com/q/51362419
type: AnsweredQuestion
score: 3
downvote count: 0
type: Question
accepted answer: http://stackoverflow.com/a/51365454
has body: Is it even possible? The model is saved by ModelCheckpoint(model_path, save_best_only=True, monitor='val_acc', mode='max', save_weights_only=False) Can I do something like this? from keras.models import load_model model = load_model(model_path) X_train = model.inputs
answer count: 1
tagged with: keras
favorite count: 0
has title: Keras: get training data from a saved model
upvote count: 3
has answer: http://stackoverflow.com/a/51365454
tagged with: keras-2
tagged with: python

http://stackoverflow.com/comment/99574942
has text: worked for me too. question: should I be using `ModelViewSet`?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51396509
score: 0

http://stackoverflow.com/comment/89916215
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51440522
has text: That does exactly what i was looking for, thank you!

http://stackoverflow.com/comment/89852115
score: 0
has text: Can you edit your question and fix the part following "the struct function is". Theres no function definition and what is `Struct`?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51441050

http://stackoverflow.com/q/51334226
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89643860
type: UnansweredQuestion
tagged with: python
score: 11
tagged with: urlencode
downvote count: 0
has body: The most recent documentation for urllib states: Changed in version 3.7: Moved from RFC 2396 to RFC 3986 for quoting URL strings. “~” is now included in the set of reserved characters. Why is this the case? In RFC 3986, ~ is not a reserved character: reserved = gen-delims / sub-delims gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@" sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" Explicitly in the next section it is included as an unreserved character: 2.3. Unreserved Characters Characters that are allowed in a URI but do not have a reserved purpose are called unreserved. These include uppercase and lowercase letters, decimal digits, hyphen, period, underscore, and tilde. unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" Furthermore, later on, the RFC states that (emphasis mine): For example, the octet corresponding to the tilde ("~") character is often encoded as "%7E" by older URI processing implementations; So it seems like 3.7 is inconsistent: it asserts the support for the newer RFC while simultaneously regressing the processing of ~. (In fact, in the older RFC, ~ is also not reserved nor 'unwise')
has comment: http://stackoverflow.com/comment/89644251
type: Question
upvote count: 11
has title: Python: Why is “~” now included in the set of reserved characters in urllib.parse.quote()?
answer count: 1
has answer: http://stackoverflow.com/a/51798860
has comment: http://stackoverflow.com/comment/89643888
favorite count: 0

http://stackoverflow.com/comment/89916005
has text: Do you even need the `int` cast in the last filter statement? Those tend to be very robust.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51473839
type: AnswerComment

http://stackoverflow.com/q/51440166
has comment: http://stackoverflow.com/comment/89850653
has body: I am doing a script that sends a message each 1 minute(aprox) to a bot, but over 2 hours the client telegram api blocks my script for 8 hours. Which is the max rate for this? I read the API FAQS Telegram but it talks with 1 message/second and 20 messages/minutes How could I fix this?
score: 0
tagged with: telegram
tagged with: python
answer count: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/89850854
has title: Getting banned with python script using API Telegram
has comment: http://stackoverflow.com/comment/91454553
tagged with: api

http://stackoverflow.com/a/51354366
answers question: http://stackoverflow.com/q/51354348
score: 0
type: AcceptedAnswer
type: Answer
has body: imputer= Imputer(missing_vaules='NaN',strategy='mean',axix=0) Yas=veriler.iloc[:,1:4].values should be imputer= Imputer(missing_values='NaN',strategy='mean',axix=0) Yas=veriler.iloc[:,1:4].values with the misspelling of values repaired.
accepted answer of: http://stackoverflow.com/q/51354348

http://stackoverflow.com/q/51364552
has answer: http://stackoverflow.com/a/51378298
upvote count: 4
type: AnsweredQuestion
has title: How do I queue QProcesses in PyQt5?
tagged with: qprocess
type: Question
has comment: http://stackoverflow.com/comment/89725355
tagged with: pyqt
has comment: http://stackoverflow.com/comment/89724143
answer count: 1
score: 4
has comment: http://stackoverflow.com/comment/89725519
has comment: http://stackoverflow.com/comment/89724706
has body: I want to queue QProcess in PyQt5 or simply block while still reading the stdout with readAll(). The equivalent of subprocess.call instead of subprocess.Pop. When using waitForFinished() the stdout with readAll() will all come at once when the process is ended instead of flowing out while it's processing. Example script: from PIL import Image import numpy as np import sys from PyQt5 import QtGui,QtCore, QtWidgets class gui(QtWidgets.QMainWindow): def __init__(self): super(gui, self).__init__() self.initUI() def dataReady(self): cursor = self.output.textCursor() cursor.movePosition(cursor.End) cursor.insertText(str(self.process.readAll(), "utf-8")) self.output.ensureCursorVisible() def callProgram(self): # run the process # `start` takes the exec and a list of argument filepath = 'path\image.tif' self.process.start('some_command filepath']) # This will output a file image.tif specified by filepath: # Import file and do stuff to it: # E.g. im = Image.open('filepath') imarray = np.array(im) # Get image extents as argument to next process: ext = str(imarray.size) imarray[imarray == 10] = 5 # Save changes im = Image.fromarray(imarray) im.save(filepath) # Now the image has been updated and should be in a new process below cmd = 'some_other_command' + filepath + ext self.process.start(cmd) # Same thing goes on here: self.process.start('some_command filepath') # Import file once again im = Image.open('filepath') imarray[imarray == 10] = 5 # Save changes im = Image.fromarray(imarray) im.save(filepath) def initUI(self): layout = QtWidgets.QHBoxLayout() self.runButton = QtWidgets.QPushButton('Run') self.runButton.clicked.connect(self.callProgram) self.output = QtWidgets.QTextEdit() layout.addWidget(self.output) layout.addWidget(self.runButton) centralWidget = QtWidgets.QWidget() centralWidget.setLayout(layout) self.setCentralWidget(centralWidget) # QProcess object for external app self.process = QtCore.QProcess(self) # QProcess emits `readyRead` when there is data to be read s…
has comment: http://stackoverflow.com/comment/89724284
tagged with: python
accepted answer: http://stackoverflow.com/a/51378298
favorite count: 0
has comment: http://stackoverflow.com/comment/89724414
downvote count: 0
has comment: http://stackoverflow.com/comment/89723897
tagged with: pyqt5

http://stackoverflow.com/comment/89838030
comment on: http://stackoverflow.com/a/51433731
type: Comment
score: 0
type: AnswerComment
has text: Don't use `str` as a variable name

http://stackoverflow.com/comment/89649802
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51329802
score: 0
has text: @MatrixManAtYrService Thanks for the pointer. I was looking more for an option that can be used to control the behavior. Maybe Anti-aliasing = True or something.

http://stackoverflow.com/a/51412025
accepted answer of: http://stackoverflow.com/q/51411950
answers question: http://stackoverflow.com/q/51411950
has comment: http://stackoverflow.com/comment/89826554
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/89826404
has body: If you look at the docs for 3.4 enum, you'll see that IntFlag is not there. That is because it was added in 3.6. So the error you are seeing is indeed correct and not a problem with your enum34 installation. It also looks like the enum package in pypi also doesn't have IntFlag. You can monkey patch this pretty easily though by copying the source for IntFlag into a module in your project: from enum import Enum class Flag(Enum): """Support for flags""" def _generate_next_value_(name, start, count, last_values): """ Generate the next value when not given. name: the name of the member start: the initital start value or None count: the number of existing members last_value: the last value assigned or None """ if not count: return start if start is not None else 1 for last_value in reversed(last_values): try: high_bit = _high_bit(last_value) break except Exception: raise TypeError('Invalid Flag value: %r' % last_value) from None return 2 ** (high_bit+1) @classmethod def _missing_(cls, value): original_value = value if value &lt; 0: value = ~value possible_member = cls._create_pseudo_member_(value) if original_value &lt; 0: possible_member = ~possible_member return possible_member @classmethod def _create_pseudo_member_(cls, value): """ Create a composite member iff value contains only members. """ pseudo_member = cls._value2member_map_.get(value, None) if pseudo_member is None: # verify all bits are accounted for _, extra_flags = _decompose(cls, value) if extra_flags: raise ValueError("%r is not a valid %s" % (value, cls.__name__)) # construct a singleton enum pseudo-member pseudo_member = object.__new__(cls) pseudo_member._name_ = None pseudo_member._value_ = value # use setdefault in case another thread already created a composite # with this value pseudo_member = cls._value2member_map_.setdefault(value, pseudo_member) return pseudo_member def __contains__(self, other): if not isinstance(other, self.__class__): import warnings warnings.warn( "using non-Flags in containm…

http://stackoverflow.com/q/51425084
has answer: http://stackoverflow.com/a/51425236
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/89821213
upvote count: 2
possible better answer: http://stackoverflow.com/a/51425453
linked to: http://stackoverflow.com/q/3305926
has comment: http://stackoverflow.com/comment/89821296
has answer: http://stackoverflow.com/a/51425453
has body: Lets say I have a line containing arguments splitted with , '0xe1b04048, FUTEX_WAIT, 0, NULL , "Hey, World, how, are, you"' I want regex in python that splits this sequence into list containing items (for clarity split one item by line) [ '0xe1b04048', 'FUTEX_WAIT', '0', 'NULL', '"Hey, World, how, are, you"' ] I have tried to make regex with negative lookahead, what can at least process one comma in comment and my plan was to extend it but I didnt managed to do even that. Calling re.split(r",\s(?!\".*,\s.*\")",args) on '0xe1b04048, FUTEX_WAIT, 0, NULL , "Hey, World"' results in [ '0xe1b04048', 'FUTEX_WAIT', '0', 'NULL , "Hey', 'World"' ]
type: Question
has comment: http://stackoverflow.com/comment/89821444
accepted answer: http://stackoverflow.com/a/51425236
answer count: 3
downvote count: 0
has title: Python regex, split arguments, ignore commas in quotes
favorite count: 0
has comment: http://stackoverflow.com/comment/89821204
has answer: http://stackoverflow.com/a/51425682
tagged with: python
tagged with: regex

http://stackoverflow.com/comment/89892608
comment on: http://stackoverflow.com/q/51461262
type: Comment
has text: Show the complete error message you're getting, including the traceback.
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89820243
has text: Well, then, put that out into its own function and call it from your `__main__` block...
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51413877
score: 0

http://stackoverflow.com/a/51357634
has body: One possible solution (without groupby from itertools): foo = ['bar', 'bar', 'bar', 'foo', 'foo','bar'] def my_groupby(l): first, last, current_value = 0, 0, l[0] for i, value in enumerate(l): if value != current_value: yield first + 1, last + 1, current_value current_value, first, last = value, i, i else: last = i yield first + 1, last + 1, current_value for first, last, value in my_groupby(foo): if first != last: print(f'{first}-{last} = {value}') else: print(f'{first} = {value}') Prints: 1-3 = bar 4-5 = foo 6 = bar
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51357333
answers question: http://stackoverflow.com/q/51357333

http://stackoverflow.com/comment/89980737
type: Comment
has text: @Azazel Thanks to you I got to know `easygui` and `unicodedata` !
comment on: http://stackoverflow.com/a/51409773
score: 1
type: AnswerComment

http://stackoverflow.com/comment/89855672
score: 2
comment on: http://stackoverflow.com/q/51442884
has text: what did you try yourself?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89678583
score: 2
comment on: http://stackoverflow.com/q/51353000
has text: So `self.message` is `None`, which can happen when you have NULLs in your database rows for that column. Use `return self.message or ''`.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51378402
answers question: http://stackoverflow.com/q/51378032
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89850440
has body: Try below stars = driver.find_element_by_id('acrPopover').get_attribute('title')
accepted answer of: http://stackoverflow.com/q/51378032
type: Answer
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/89850439
has comment: http://stackoverflow.com/comment/89850389

http://stackoverflow.com/comment/89798950
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51397922
score: 0
has text: Exactly what happens when you attempt an upload? What does the database model look like, and what is the format of the CSV file (maybe show the header and a few rows)?

list
tags question: http://stackoverflow.com/q/51361420
type: Tag
tags question: http://stackoverflow.com/q/51464752
tags question: http://stackoverflow.com/q/51337721
tags question: http://stackoverflow.com/q/51372775
tags question: http://stackoverflow.com/q/51410808
tags question: http://stackoverflow.com/q/51337313
tags question: http://stackoverflow.com/q/51377272
tags question: http://stackoverflow.com/q/51469160
tags question: http://stackoverflow.com/q/51468774
tags question: http://stackoverflow.com/q/51349233
tags question: http://stackoverflow.com/q/51398847
tags question: http://stackoverflow.com/q/51414133
tags question: http://stackoverflow.com/q/51464020
tags question: http://stackoverflow.com/q/51369718
tags question: http://stackoverflow.com/q/51380124
tags question: http://stackoverflow.com/q/51351713
tags question: http://stackoverflow.com/q/51438158
tags question: http://stackoverflow.com/q/51446299
tags question: http://stackoverflow.com/q/51464529
tags question: http://stackoverflow.com/q/51399035
tags question: http://stackoverflow.com/q/51395078
tags question: http://stackoverflow.com/q/51324846
tags question: http://stackoverflow.com/q/51330439
tags question: http://stackoverflow.com/q/51481077
tags question: http://stackoverflow.com/q/51384927
tags question: http://stackoverflow.com/q/51406699
tags question: http://stackoverflow.com/q/51456204
tags question: http://stackoverflow.com/q/51364122
tags question: http://stackoverflow.com/q/51349013
tags question: http://stackoverflow.com/q/51459580
tags question: http://stackoverflow.com/q/51337430
tags question: http://stackoverflow.com/q/51448811
tags question: http://stackoverflow.com/q/51341361
tags question: http://stackoverflow.com/q/51349982
tags question: http://stackoverflow.com/q/51403730
tags question: http://stackoverflow.com/q/51472684
tags question: http://stackoverflow.com/q/51461983
tags question: http://stackoverflow.com/q/51331845
tags question: http://stackoverflow.com/q/51417970
tags question: http://stackoverflow.com/q/51372651
tags question: http://stackoverflow.com/q/51469622
tags question: http://stackoverflow.com/q/51414271
tags question: http://stackoverflow.com/q/51460895
tags question: http://stackoverflow.com/q/51478949
tags question: http://stackoverflow.com/q/51478208
tags question: http://stackoverflow.com/q/51351224
tags question: http://stackoverflow.com/q/51337718
tags question: http://stackoverflow.com/q/51478288
tags question: http://stackoverflow.com/q/51378961
tags question: http://stackoverflow.com/q/51371171
tags question: http://stackoverflow.com/q/51345024
tags question: http://stackoverflow.com/q/51443124
tags question: http://stackoverflow.com/q/51445252
tags question: http://stackoverflow.com/q/51340697
tags question: http://stackoverflow.com/q/51417739
tags question: http://stackoverflow.com/q/51391300
tags question: http://stackoverflow.com/q/51350937
tags question: http://stackoverflow.com/q/51376231
tags question: http://stackoverflow.com/q/51332160
tag name: list
tags question: http://stackoverflow.com/q/51409756
tags question: http://stackoverflow.com/q/51456308
tags question: http://stackoverflow.com/q/51460366
tags question: http://stackoverflow.com/q/51392020
tags question: http://stackoverflow.com/q/51368349
tags question: http://stackoverflow.com/q/51388304
tags question: http://stackoverflow.com/q/51456897
tags question: http://stackoverflow.com/q/51461472
tags question: http://stackoverflow.com/q/51332036
tags question: http://stackoverflow.com/q/51387195
tags question: http://stackoverflow.com/q/51392556
tags question: http://stackoverflow.com/q/51465109
tags question: http://stackoverflow.com/q/51468615
tags question: http://stackoverflow.com/q/51329934
tags question: http://stackoverflow.com/q/51345545
tags question: http://stackoverflow.com/q/51434149
tags question: http://stackoverflow.com/q/51327792
tags question: http://stackoverflow.com/q/51472122
tags question: http://stackoverflow.com/q/51341929

http://stackoverflow.com/a/51413447
downvote count: 0
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51413403
answers question: http://stackoverflow.com/q/51413403
has body: df.col2 = df.col2.astype(str).str.cat(df.col3, sep='/') See https://pandas.pydata.org/pandas-docs/version/0.23/api.html#string-handling for string operations.
has comment: http://stackoverflow.com/comment/89798474
type: AcceptedAnswer

http://stackoverflow.com/q/51437954
type: Question
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/89846025
has body: Say there's a dataframe: import pandas as pd df = pd.DataFrame([1,2,3,4,5, 7,8, 10]) I want to find the "missing" numbers in it (6 and 9). My code to do this is: li = [] low = int(min(df.values)) high = int(max(df.values)) for i in range(low, high+1): if i not in df.values: li.append(i) print(li) &gt;&gt;&gt; [6, 9] But if the dataframe is huge, this may take some time with a for loop. In my case, with a dataframe of length ~300k rows, its taking 162 seconds. Is there a more efficient (vectorized?) way to do this?
possible better answer: http://stackoverflow.com/a/51438108
downvote count: 0
has title: What's the best way to find "missing" values in a dataframe?
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51438067
has comment: http://stackoverflow.com/comment/89845892
has comment: http://stackoverflow.com/comment/89846077
favorite count: 0
has answer: http://stackoverflow.com/a/51438067
has answer: http://stackoverflow.com/a/51438108
has comment: http://stackoverflow.com/comment/89845952
tagged with: python
tagged with: indexing
score: 2
type: AnsweredQuestion
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89846002

http://stackoverflow.com/q/51344681
has title: Replacing NaN in Pandas Dataframe with Column Average
linked to: http://stackoverflow.com/q/18689823
tagged with: pandas
tagged with: python
duplicate of: http://stackoverflow.com/q/18689823
has body: pandas newbie here. I have a DataFrame with some values as '?' which I have successfully replaced with 'NaN'. I would like to replace 'NaN' with the average of the column, however, I am running into an issue where the 'NaN' is not removed. I've reviewed the solution below, but it does not work, per the below. pandas DataFrame: replace nan values with average of columns Code: df = pd.DataFrame(cancer) print(df) df['A7'] = df['A7'].replace(['?'],"NaN") print(df) # the code below is where my issue arises df.fillna(df.mean()) print(df) Before ? is replaced with NaN: Scn A2 A3 A4 A5 A6 A7 A8 A9 A10 CLASS [.....] 21 1054593 10 5 5 3 6 7 7 10 1 4 22 1056784 3 1 1 1 2 1 2 1 1 2 23 1057013 8 4 5 1 2 ? 7 3 1 4 Before NaN is replaced with mean: Scn A2 A3 A4 A5 A6 A7 A8 A9 A10 CLASS [.....] 21 1054593 10 5 5 3 6 7 7 10 1 4 22 1056784 3 1 1 1 2 1 2 1 1 2 23 1057013 8 4 5 1 2 NaN 7 3 1 4 After NaN is replaced with average: Scn A2 A3 A4 A5 A6 A7 A8 A9 A10 CLASS [.....] 21 1054593 10 5 5 3 6 7 7 10 1 4 22 1056784 3 1 1 1 2 1 2 1 1 2 23 1057013 8 4 5 1 2 NaN 7 3 1 4 I'm not sure what I am doing wrong.
answer count: 0
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89662641
has comment: http://stackoverflow.com/comment/89662719
has comment: http://stackoverflow.com/comment/89662691
type: Question
tagged with: dataframe

http://stackoverflow.com/comment/89917178
comment on: http://stackoverflow.com/q/51474401
has text: What is your initial i value? Did you set it to 0?
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/51405048
has answer: http://stackoverflow.com/a/51405668
score: 7
has title: ChromeOption '--safebrowsing-disable-download-protection' doesn't disables the download warning in Chrome version 67.x
favorite count: 0
type: Question
tagged with: python
has body: I am trying to use Selenium webdriver to automate some of the work. My automation includes downloading some .msg outlook email file from the web attached by somebody else. Downloading the .msg file prompted a warning from Chrome saying "This type of file can harm the computer...". Using the ChromeOptions to add argument --safebrowsing-disable-download-protection does not work, the download still prompted the warning with the argument added into the chrome options, any help will be appreciated. Code trial: from selenium import webdriver chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--safebrowsing-disable-download-protection') driver = webdriver.Chrome(chrome_options=chrome_options) printing the chrome_options.arguments shows that the '--safebrowsing-disable-download-protection' is added into the arguments, but when I started to download the .msg files using Selenium, I still receive the same warning. Something to note, when i manually run chrome.exe via cmd using the '--safebrowsing-disable-download-protection', downloading without warning works.
tagged with: selenium-webdriver
tagged with: selenium-chromedriver
has answer: http://stackoverflow.com/a/68637624
has answer: http://stackoverflow.com/a/51405692
answer count: 3
tagged with: selenium
upvote count: 7
tagged with: google-chrome
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/q/51410187
downvote count: 1
type: Question
duplicate of: http://stackoverflow.com/q/20625582
has title: get rid of warning pandas copy local
score: 0
has comment: http://stackoverflow.com/comment/89791803
tagged with: pandas
upvote count: 1
tagged with: python
favorite count: 0
linked to: http://stackoverflow.com/q/20625582
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89791871
has body: I keep running into the following warning in pandas but I am failing to see why. let's say I have a dataframe and I create a new column this way: x = pd.DataFrame({'A':[1,2,3]}) x['AA'] = x['A'] I do not get any warning. But I basically do the same for a Df I get from a SQL db and I get a warning. m = rs.selectQueryIntoPandas(sql) # filter out all rigs with NULL ID - out: m1 null_flag = rigs['id'].isnull() n_nulls = sum(null_flag) m1 = m.loc[~null_flag] id_cleaned = m1['id'].apply(lambda x: cleanId(x)) m1['id_orig'] = m1['id'] /home/ubuntu/.pycharm_helpers/pydev/pydevconsole.py:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy ''' I have no idea why.

search-engine
type: Tag
tag name: search-engine
tags question: http://stackoverflow.com/q/51423482

http://stackoverflow.com/a/51668435
upvote count: 3
type: Answer
downvote count: 0
has body: It was due to the construction of the body dict. I needed to create the body as a dict, and include all body dicts into a list. This is the solution: def index_with_streaming_bulk(self): all_body = [] with open(self.geonames_file, encoding='utf-8') as csvfile: reader = csv.reader(csvfile, delimiter='\t') body = {} next(reader) # skip column names for row_ind, row in enumerate(reader): body['_index'] = self.index_name body['_type'] = self.doc_type body['_id'] = row_ind + 1 # to map index value to geonames. remove the column headers for field_tup in self.included_cols: field_name = field_tup[0] field_ind = field_tup[1] field_type = field_tup[2] val_init = row[field_ind] mod_val = self.transform_value(field_type, val_init) body[field_name] = mod_val all_body.append(body) body={} def gendata(): for body in all_body: yield body res = elasticsearch.helpers.streaming_bulk(client=es, actions=all_body, chunk_size=1000, max_retries=5, initial_backoff=2, max_backoff=600, request_timeout=3600) for ok, response in res: print(ok, response)
score: 3
accepted answer of: http://stackoverflow.com/q/51358868
answers question: http://stackoverflow.com/q/51358868
type: AcceptedAnswer

http://stackoverflow.com/q/51446471
type: Question
has comment: http://stackoverflow.com/comment/89868418
answer count: 1
favorite count: 0
has body: I am using Python 3.6.5 with the following libraries: Appium-Python-Client==0.26 unittest2==1.1.0 selenium==3.5.0 pytest==3.6.3 Now I need to capture the screenshot in case of test failure, So intentionally I did put a false statement self.driver.find_element_by_css_selector('test') . I am using sys.exc_info(). But when I executing below code using a command: py.test untitled.py or python3 -m unittest untitled.py it does not capturing it. Code: import sys, time, unittest2 from selenium import webdriver class FB360(unittest2.TestCase): def setUp(self): self.driver = webdriver.Chrome() def test_user_can_login(self): self.driver.get('https://www.google.co.in') self.driver.find_element_by_css_selector('test') def tearDown(self): print(sys.exc_info()) if sys.exc_info()[0]: test_method_name = self._testMethodName self.driver.save_screenshot(test_method_name + str(time.time()) + '.png') self.driver.quit() if __name__ == '__main__': unittest2.main() O/P: (None, None, None) E ====================================================================== ERROR: test_user_can_login (untitled.FB360) Traceback (most recent call last): File "/Volumes/Harry/Projects/pythonScreenshots/untitled.py", line 11, in test_user_can_login self.driver.find_element_by_css_selector('test') File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 498, in find_element_by_css_selector return self.find_element(by=By.CSS_SELECTOR, value=css_selector) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 832, in find_element 'value': value})['value'] File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 297, in execute self.error_handler.check_response(response) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py"…
has comment: http://stackoverflow.com/comment/89881518
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/89875399
tagged with: selenium-webdriver
downvote count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/4414234
has comment: http://stackoverflow.com/comment/89868343
tagged with: pytest
has answer: http://stackoverflow.com/a/53274402
tagged with: python-unittest
score: 4
has title: How to capture screenshot on test case failure for Python Unittest
tagged with: python-3.6

http://stackoverflow.com/q/51326385
tagged with: python
tagged with: unit-testing
type: Question
has comment: http://stackoverflow.com/comment/89628676
has title: unittest main module python
score: 0
has comment: http://stackoverflow.com/comment/89628280
has comment: http://stackoverflow.com/comment/89628326
has body: I have the following main module: import pandas as pd from formatting import abs_value, api_call def main(): dataframe2 = abs_value(dataframe1) dataframe3 = api_call(dataframe2) The main module is just using various functions (abs_value and api_call) in another module called formatting to perform updates to a dataframe. I have unittested the formatting module to 100% but my main is at 20%. When I test the main, it actually tries to run the various functions so I assume I have to mock this? The end result of my main has no result so it would be "return None". I would like to assert that this occurs at the end, but am unsure conceptually of how to proceed.
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/89742102
has text: you can also use `\d` instead. `int(re.sub('[^\d]','', s))`
type: Comment
comment on: http://stackoverflow.com/a/51385045
score: 1
type: AnswerComment

http://stackoverflow.com/q/51438253
type: Question
accepted answer: http://stackoverflow.com/a/51499602
tagged with: python
has comment: http://stackoverflow.com/comment/89896513
tagged with: mapping
tagged with: metadata
has title: How to use vtkInformation objects in VTK?
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89965961
has answer: http://stackoverflow.com/a/51499602
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89847376
tagged with: vtk
has body: I am trying to pass some extra information (string data) in a vtkMultiBlockDataSet using its meta data vtkInformation container. I have problems retrieving the data from the information object. The following code in python shows the problem: import vtk from vtk.util import keys mb = vtk.vtkMultiBlockDataSet() mb.SetBlock(0, vtk.vtkPolyData()) metaData = mb.GetMetaData(0) key = keys.MakeKey(keys.StringKey, "Key", "x") metaData.Set(key, "Value") # Going to some other place in space and time key2 = keys.MakeKey(keys.StringKey, "Key", "x") print metaData.Get(key2) The print in the last line prints None. How is it possible for me to retrieve the value of Key from the information container without using exactly the same key? (Using key in the last line above, prints the correct value)

http://stackoverflow.com/comment/89750623
score: 1
comment on: http://stackoverflow.com/q/51389298
has text: But the code you have listed above is identical, how are the lists supposed to be different? It seems like the `count` logic is lost in your list comprehensions
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89647356
comment on: http://stackoverflow.com/a/51325861
type: Comment
has text: i corrected it by changing mydict=dict.fromkeys(z,None) to mydict=dict.fromkeys(z,[])
type: AnswerComment
score: 0

http://stackoverflow.com/q/51332141
upvote count: 0
has answer: http://stackoverflow.com/a/51342742
has answer: http://stackoverflow.com/a/51334546
has title: How to ignore error instead of returning 400 Bad Request?- Django Rest Framework
tagged with: django-rest-framework
favorite count: 0
tagged with: rest
possible better answer: http://stackoverflow.com/a/51342742
has comment: http://stackoverflow.com/comment/89651864
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51361709
tagged with: django
downvote count: 1
type: Question
has body: I have a model named Cart. Cart has an Foreign Key to Coupon. When I POST to create a new Cart, it runs some validations to find if Coupon exists. If not, it return Error 400 saying that the object does not exist. I dont want an 400 Error, I need it to continue the processes returning Coupon as Null. serializers.py class CartSerializer(serializers.ModelSerializer): id = serializers.UUIDField(format='hex', read_only=True) delivery = DeliverySerializer(required=False, write_only=True) customer = CustomerSerializer(required=False, write_only=True) coupon = CouponSerializer( required=False, ) totals = serializers.SerializerMethodField() class CouponSerializer(serializers.Serializer): code = serializers.SlugRelatedField( slug_field='code', required=False, source='coupon', queryset=Coupon.objects.only_valid(), ) def to_representation(self, coupon): return { 'code': coupon.code, 'discount_amount': coupon.discount_amount, 'discount_percentage': coupon.discount_percentage, 'only_first_order': coupon.only_first_order, } views.py class CartViewset(CreateModelMixin, GenericViewSet): queryset = Cart.objects.all() serializer_class = CartSerializer permission_classes = (AllowAny,)
linked to: http://stackoverflow.com/q/8609192
has comment: http://stackoverflow.com/comment/89640108
score: -1
accepted answer: http://stackoverflow.com/a/51361709
answer count: 3
tagged with: api

http://stackoverflow.com/q/51409964
tagged with: amazon-s3
tagged with: amazon-s3-select
answer count: 2
downvote count: 0
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/89792283
favorite count: 0
has answer: http://stackoverflow.com/a/51410390
possible better answer: http://stackoverflow.com/a/72245089
tagged with: python
has title: S3 Select Python error
has answer: http://stackoverflow.com/a/72245089
score: 1
upvote count: 1
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51410390
has body: I'm trying to catch the data form a S3 object. I'm using a S3 Select feature as below: boto3 version : 1.7.59 import boto3 s3 = boto3.client('s3') r = s3.select_object_content( Bucket="bucket", Key="file.json", ExpressionType='SQL', Expression="select * from s3object S3Object AS s", InputSerialization = { 'JSON': { 'Type': 'LINES' } }, OutputSerialization = { 'JSON': { 'RecordDelimiter': ',' } }, ) for event in r['Payload']: if 'Records' in event: records = event['Records']['Payload'].decode('utf-8') print(records) elif 'Stats' in event: statsDetails = event['Stats']['Details'] print("Stats details bytesScanned: ") print(statsDetails['BytesScanned']) print("Stats details bytesProcessed: ") print(statsDetails['BytesProcessed']) After run my code I'm getting the error: Traceback (most recent call last): File "C:/Users/a_urrego/PycharmProjects/DW_FlightHub/S3Select.py", line 48, in OutputSerialization = { 'JSON': { 'RecordDelimiter': ',' } }, File "C:\Users\a_urrego\AppData\Local\Programs\Python\Python36-32\lib\site-packages\botocore\client.py", line 314, in _api_call return self._make_api_call(operation_name, kwargs) File "C:\Users\a_urrego\AppData\Local\Programs\Python\Python36-32\lib\site-packages\botocore\client.py", line 612, in _make_api_call raise error_class(parsed_response, operation_name) botocore.exceptions.ClientError: An error occurred (ParseUnexpectedToken) when calling the SelectObjectContent operation: Unexpected token found AS:as at line 1, column 33. Process finished with exit code 1

http://stackoverflow.com/comment/89649797
type: QuestionComment
has text: Welcome to sackoverflow. It is hard to understand what is "raw_input' and how you did enter 1 or 0 without the Python code, so please edit your question to be more clear. Also try to fix the code indentation problem. Are you certain that your Arduino is on port "Com3" and uses a speed of 9600 bauds ?
score: 0
comment on: http://stackoverflow.com/q/51337563
type: Comment

http://stackoverflow.com/q/51414615
has body: I have been working on jupyter and while I am runnning the code it has the Type error Here is my code: import numpy as np import tensorflow as tf import random import os os.environ['CUDA_VISIBLE_DEVICES']='0' class GAN_trainer(object): def __init__(self, gan_model, train_script, train_script_len, train_action, init_pose, num_data, batch_size, gan_model_dir, seq2seq_model_dir, dis_model_dir, sentence_steps, action_steps, dim_sentence, dim_char_enc, dim_gen, dim_random, restore=0, restore_path='', restore_step=0, max_epoch=500, save_stride=5, gen_learning_rate=0.000002, dis_learning_rate=0.000002 #0.00001 ): self.action_steps = action_steps self.dim_action = 24 self.gan_model = gan_model self.train_script = train_script self.train_script_len = train_script_len self.train_action = train_action self.init_pose = init_pose self.num_data = num_data self.batch_size = batch_size self.batch_init = np.transpose(np.tile(self.init_pose, (1, self.batch_size)), [1, 0]) self.num_batch = self.num_data / batch_size self.gan_model_dir = gan_model_dir self.seq2seq_model_dir = seq2seq_model_dir self.dis_model_dir = dis_model_dir self.sentence_steps = sentence_steps self.dim_sentence = dim_sentence self.dim_char_enc = dim_char_enc self.dim_gen = dim_gen self.dim_gen_inp = self.dim_action self.dim_random = dim_random self.restore = restore self.restore_path = restore_path self.restore_step = restore_step self.max_epoch = max_epoch self.save_stride = save_stride self.gen_learning_rate = gen_learning_rate self.dis_learning_rate = dis_learning_rate self.ph_sen = tf.placeholder(tf.float32, [None, self.sentence_steps, self.dim_sentence]) self.ph_action = tf.placeholder(tf.float32, [None, self.action_steps, self.dim_action]) self.ph_action_fake = tf.placeholder(tf.float32, [None, self.action_steps, self.dim_action]) self.ph_enc_state = tf.placeholder(tf.float32, [None, self.sentence_steps, self.dim_char_enc]) self.ph_random = tf.placeholder(tf.float32, [None, self.sentence_steps, self.dim_rando…
has comment: http://stackoverflow.com/comment/89800796
tagged with: typeerror
has comment: http://stackoverflow.com/comment/89800831
tagged with: python
has title: I keep getting this error on my jupyter: TypeError: 'float' object cannot be interpreted as an integer
answer count: 0
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89800659
type: Question

http://stackoverflow.com/comment/89713116
has text: @Varmushu would you mind specifying the full path to the file, just in case
type: AnswerComment
comment on: http://stackoverflow.com/a/51369074
score: 0
type: Comment

http://stackoverflow.com/q/51386585
has comment: http://stackoverflow.com/comment/89745504
tagged with: python
has answer: http://stackoverflow.com/a/51387011
has body: I wrote a code to create a user and login but the created user will be in memory only till the program is running and when the program closes then the user gets destroyed. Now if I decide to store the username and password to a file, then how can I do so in the below python code.I just want to store it to a file not to read or compare it yet. And I just started learning Python so don't know anything advance or any tricky terms. Edit: I am unable to write the username and password to the file. users = {} status = "" f = open('E:\\login_try2.txt','w') def displayMenu(): status = input("Are you registered user? y/n/q ") if status == "y": oldUser() elif status == "n": newUser() elif status == "q": exitCode() def exitCode(): exit() def newUser(): username = input("Enter username: ") f.write(username) if username in users: print("\nUsername already exists!\n") else: password = input("Create Password: ") users[username] = password f.write(password) print("\nUser created\n") def oldUser(): login = input("Enter username: ") passw = input("Enter password: ") if login in users and users[login] == passw: print("\nLogin Successful!\n") else: print("\nUser doesnt exist or wrong password!\n") while status != "q": displayMenu() f.close()
tagged with: python-3.x
type: UnansweredQuestion
score: -4
has comment: http://stackoverflow.com/comment/89745331
has answer: http://stackoverflow.com/a/51387012
has comment: http://stackoverflow.com/comment/89745605
has comment: http://stackoverflow.com/comment/89745533
has comment: http://stackoverflow.com/comment/89745494
has comment: http://stackoverflow.com/comment/89745556
type: Question
answer count: 2
downvote count: 4
linked to: http://stackoverflow.com/q/1047318
upvote count: 0
has comment: http://stackoverflow.com/comment/89745578
has comment: http://stackoverflow.com/comment/89745709
has comment: http://stackoverflow.com/comment/89745370
has title: How can I write data to file in the python program?
favorite count: 0

http://stackoverflow.com/comment/89904551
has text: Possible duplicate of [Decoding a Huffman code with a dictionary](https://stackoverflow.com/questions/33089660/decoding-a-huffman-code-with-a-dictionary)
type: QuestionComment
comment on: http://stackoverflow.com/q/51456266
score: 0
type: Comment

http://stackoverflow.com/a/51328217
type: Answer
answers question: http://stackoverflow.com/q/51327984
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51327984
has body: concat have join = 'inner' pd.concat([x,y],join = 'inner', axis=1) Out[184]: a b c d e f 0 2 4 6 6 7 1 1 4 7 9 9 5 8
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89845239
comment on: http://stackoverflow.com/q/51437654
type: Comment
score: 0
has text: 3.6.5. it's the correct
type: QuestionComment

http://stackoverflow.com/q/51361540
tagged with: python
downvote count: 1
has body: With the following code, I try to plot 12 different histograms in one picture using Matplotlib. for graph in range(1,13): name = all_results[graph-1] plt.subplot(4,3,graph, title = name) plt.tight_layout() current_model = name plt.hist(all_val_accuracies[current_model], #range = (0.49, 0.58), bins = 50) plt.xlabel('Accuracy') plt.ylabel('Frequency') plt.axis([0.48, 0.58, 0, 50]) With this code, all histograms are plotted in one image as how I indicated it. However, the graphs itself are squeezed to such an extend that you cant see them anymore What can I do so that these 12 histograms are plotted in one image and that each histogram can be seen clearly?
type: AnsweredQuestion
tagged with: matplotlib
has answer: http://stackoverflow.com/a/51361770
score: -1
type: Question
upvote count: 0
tagged with: subplot
linked to: http://stackoverflow.com/q/332289
accepted answer: http://stackoverflow.com/a/51361770
duplicate of: http://stackoverflow.com/q/332289
answer count: 1
favorite count: 0
has title: How to vertically stretch graphs with matplotlib subplot

http://stackoverflow.com/comment/101694079
score: 0
type: Comment
has text: @RKO Unfortunately `tf.logging` has been removed from `tensorflow 2.0`. Please execute the below commands: `import logging logger = tf.get_logger() logger.setLevel(logging.ERROR) `
comment on: http://stackoverflow.com/a/57369096
type: AnswerComment

http://stackoverflow.com/comment/89782344
comment on: http://stackoverflow.com/a/51398278
type: AnswerComment
score: 0
has text: @user9159408: Note that symplectic integrators are not generally faster or the solution for your problem. The relevant difference is that they preserve energy for Hamiltonian systems, which other integrators do not. If your system is Hamiltonian, this may be a relevant feature. Otherwise, symplectic integrators are not relevant for you.
type: Comment

http://stackoverflow.com/comment/89698608
score: 0
type: Comment
has text: This approach is not the best idea. The Voronoi diagram computation is indeed very fast, unless the number of centers is large (it could even be of order N where N is the number of pixels). But the transformation from the Voronoi cell to an efficient point location structure is not so cool, and the total workload for filling the map would be N Log(K) for K centers. A much better option is to fill every Voronoi cell with a scanline algorithm, which can be done in time O(A) where A is the polygon area (plus small overhead depending on the number of sides), for a total of O(N + K Log K).
comment on: http://stackoverflow.com/a/51344915
type: AnswerComment

http://stackoverflow.com/q/51462420
tagged with: pandas
has body: With one-hot encoding, once you have a column with 1 value in it, lets say "color", pandas get_dummies will do as follows: df = pd.DataFrame({'f1': ['red', 'yellow']}) df Out[24]: f1 0 red 1 yellow pd.get_dummies(df) Out[25]: f1_red f1_yellow 0 1 0 1 0 1 A "many-hot encoding" problem will be where you might have a list of colors, like the following example: df = pd.DataFrame({'f1': ['red', ['yellow', 'blue']]}) df Out[27]: f1 0 red 1 [yellow, blue] Is there any graceful-smart-Pythonic way, hopefully supported in Pandas, that will yield me the following result: f1_red f1_yellow f1_blue 0 1 0 0 1 0 1 1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51462463
accepted answer: http://stackoverflow.com/a/51462463
tagged with: python
score: 2
downvote count: 0
type: AnsweredQuestion
has title: Many-Hot (N-hot) encoding - quick pandas approach?
tagged with: dataframe
type: Question
upvote count: 2

http://stackoverflow.com/a/51455370
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89881060
has comment: http://stackoverflow.com/comment/89881695
accepted answer of: http://stackoverflow.com/q/51455279
has body: You could use the os.path module from python: import os path = 'android/data/com.something' os.path.split(path)[-1] returns the last element of your path structure: 'com.something' EDIT: If you need multiple parts of your data path, split it at /. This returns a list of all path elements. If you want to find multiple elements with a shared pattern, you can use Regex to find those. In your example case: import re path = 'android/data/com.something/com.facebook/com.skype' split_path = path.split('/') elements = [element for element in split_path if re.match(\A['com.'], element)] Output: ['com.something', 'com.facebook', 'com.skype'] The re.match here takes every element that starts with com.. Of course you can modify your regex according to your needs.
has comment: http://stackoverflow.com/comment/89880552
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89880707
answers question: http://stackoverflow.com/q/51455279
has comment: http://stackoverflow.com/comment/90226988

http://stackoverflow.com/comment/89879050
comment on: http://stackoverflow.com/q/51454468
score: 0
has text: @Azat Ibarkov i get the output: Enter the number of passes: 2 [54,17,77,31,44,55,20,26,93] Which means the first pass ran correctly because of 93 at highest index, but then 55 should be with 93.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51350706
tagged with: pandas
has body: I want to search an entire column 'Warehouse' in a Pandas Data Frame using Python and if a cell value occurs more than 3 times, I want to write the same value to the GeneralDescription column. I am trying to write code that would work for thousands of rows and ignore upper or lower case values. Here is my code that tries to accomplish this which only outputs the values that appear more than 3 times but does not write anything to the GeneralDescription column. What am I doing wrong? Any help is greatly appreciated. import pandas as pd from collections import Counter import numpy as np data= [[2,'Empty','Empty'],[3,'General Liability','Empty'],[4,'WRS','Empty'],[5,'WRS','Empty'],[6,'CENTRAL','Empty'],[7,'General Liability','Empty'],[8,'CENTRAL','Empty'],[9,'wrs','Empty'],[10,'WRS','Empty'],[11,'GENERAL LIABILITY','Empty'],[12,'General Liability','Empty']] df1=pd.DataFrame(data,columns=['LineNum','Warehouse','GeneralDescription']) vc=df1.Warehouse.value_counts() #print (vc[vc&gt;3].index[0]) counts=Counter(df1.Warehouse.str.lower()) df1[df1.Warehouse.str.lower().isin([key for key in counts if counts[key]&gt;3])].fillna(df1['GeneralDescription']) df1 LineNum Warehouse GeneralDescription 0 2 Empty Empty 1 3 General Liability Empty 2 4 WRS Empty 3 5 WRS Empty 4 6 CENTRAL Empty 5 7 General Liability Empty 6 8 CENTRAL Empty 7 9 wrs Empty 8 10 WRS Empty 9 11 GENERAL LIABILITY Empty 10 12 General Liability Empty df2 Desired Result LineNum Warehouse GeneralDescription 0 2 1 3 General Liability General Liability 2 4 WRS WRS 3 5 WRS WRS 4 6 CENTRAL 5 7 General Liability General Liability 6 8 CENTRAL 7 9 wrs WRS 8 10 WRS WRS 9 11 GENERAL LIABILITY General Liability 10 12 General Liability General Liability
downvote count: 0
tagged with: string
accepted answer: http://stackoverflow.com/a/51350784
favorite count: 0
has title: Mask values that occur less than K times in a pandas column (case insensitive comparison)
tagged with: python
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/89674412
type: Question
has answer: http://stackoverflow.com/a/51350784
score: 3
possible better answer: http://stackoverflow.com/a/51350805
has comment: http://stackoverflow.com/comment/89674208
tagged with: dataframe
has answer: http://stackoverflow.com/a/51350895
has answer: http://stackoverflow.com/a/51350805
has comment: http://stackoverflow.com/comment/89674390
answer count: 3

http://stackoverflow.com/comment/89664773
comment on: http://stackoverflow.com/q/51345817
type: Comment
type: QuestionComment
has text: Why do you think this is possible? See [this](http://www.webune.com/forums/how-to-ping-by-mac-address.html) article for example.
score: 0

http://stackoverflow.com/q/51426983
has answer: http://stackoverflow.com/a/78039199
has body: So I have a database where a bunch of hashed passwords are stored in strings. Now I am trying to then pull them down, and compare them to the plain text passwords the user enters. Here is an example: import bcrypt # at creation first: password = u"seCr3t" hashed_password = bcrypt.hashpw(password.encode('utf8'), bcrypt.gensalt()) print(hashed_password) #example of it being stored in the database hashed_password = str(hashed_password) # first attempt: password = u"seCrEt" print(bcrypt.checkpw(password.encode('utf8'), hashed_password.encode('utf8'))) # -&gt; False # second attempt: password = u"seCr3t" print(bcrypt.checkpw(password.encode('utf8'), hashed_password.encode('utf8'))) # -&gt; True # However I get the error "Invalid Salt" I don't know how to get around this error and have not been able to find much about it online. Any help would be appreciated. Thanks
favorite count: 0
tagged with: python-3.x
tagged with: hash
upvote count: 2
type: UnansweredQuestion
tagged with: bcrypt
tagged with: python
has title: How to compare hashed passwords stored as strings in python using bcrypt?
tagged with: passwords
score: 2
has answer: http://stackoverflow.com/a/51427463
type: Question
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/89921771
type: Comment
type: QuestionComment
has text: A decorator can't access the decorated function's local variables. They're local after all.
score: 1
comment on: http://stackoverflow.com/q/51476458

http://stackoverflow.com/comment/89643717
comment on: http://stackoverflow.com/q/51333771
has text: I just updated my original post to show how my list is stored.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89668997
type: QuestionComment
comment on: http://stackoverflow.com/q/51347449
has text: I'm using Pelican, the static site generator, not Flask.
score: 0
type: Comment

http://stackoverflow.com/a/51459493
type: Answer
has body: You can save your project anywhere. But you should activate the virtual environment before working on that project. You can activate the virtual environment using the following command. source path-to-virtualenvironment/bin/activate After activating the virtual environment move to your project location.
score: 1
has comment: http://stackoverflow.com/comment/89888620
answers question: http://stackoverflow.com/q/51459394
upvote count: 1
has comment: http://stackoverflow.com/comment/89888552
has comment: http://stackoverflow.com/comment/89888524
downvote count: 0

http://stackoverflow.com/comment/89780540
has text: Try to call `pool.join()` after `pool.close()`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51404807

http://stackoverflow.com/q/51414262
has comment: http://stackoverflow.com/comment/89800646
has comment: http://stackoverflow.com/comment/89812928
has comment: http://stackoverflow.com/comment/89800230
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/89813882
has answer: http://stackoverflow.com/a/51433684
has comment: http://stackoverflow.com/comment/89801362
has title: What is causing this KeyError from a simple function call?
has comment: http://stackoverflow.com/comment/89800155
downvote count: 1
accepted answer: http://stackoverflow.com/a/51433684
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51422324
linked to: http://stackoverflow.com/q/31593201
upvote count: 5
has comment: http://stackoverflow.com/comment/89800307
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/51434826
type: Question
has answer: http://stackoverflow.com/a/51434826
tagged with: numpy
answer count: 3
tagged with: function
score: 4
has body: The following error is caused by the following code. I've read KeyError: 0 is due to a dictionary file lacking an entry, but I still don't really know what a dictionary file is or how my code is accessing it: I am simply trying to access data in a dataframe. Apparently the problem is that a subset of the dataframe VolValues uses indices beginning around 23000 whereas I am trying to slice it with index '0' for what I thought was python's "first element" syntax. Can you tell me what is wrong with the code and how to fix it? runfile('/Users/daniel/Documents/programming/RectumD2Metrics.py', wdir='/Users/daniel/Documents/programming') Traceback (most recent call last): File "&lt;ipython-input-2-d170dca123d7&gt;", line 1, in &lt;module&gt; runfile('/Users/daniel/Documents/programming/RectumD2Metrics.py', wdir='/Users/daniel/Documents/programming') File "/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "/Users/daniel/Documents/programming/RectumD2Metrics.py", line 37, in &lt;module&gt; D2Planned = interpD2('planned',df) File "/Users/daniel/Documents/programming/RectumD2Metrics.py", line 30, in interpD2 if (VolValues[loop] &gt; 2) and (VolValues[loop+1] &lt; 2): File "/anaconda3/lib/python3.6/site-packages/pandas/core/series.py", line 766, in __getitem__ result = self.index.get_value(self, key) File "/anaconda3/lib/python3.6/site-packages/pandas/core/indexes/base.py", line 3103, in get_value tz=getattr(series.dtype, 'tz', None)) File "pandas/_libs/index.pyx", line 106, in pandas._libs.index.IndexEngine.get_value File "pandas/_libs/index.pyx", line 114, in pandas._libs.index.IndexEngine.get_value File "pandas/_libs/index.pyx", line 162, in pandas._libs.index.IndexEngine.get_loc File "pandas/_libs/hashtable_class_helper.pxi", line 958, in p…
favorite count: 0

http://stackoverflow.com/comment/89903218
comment on: http://stackoverflow.com/a/51426519
has text: the width is not by the inflection points but by finding the point where it "drops off". the reason why I cannot find a better mathematical formulation is because it is a measured quantity and not a known functional relation
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51424240
answer count: 2
tagged with: python-exec
favorite count: 0
has answer: http://stackoverflow.com/a/51428676
score: 0
possible better answer: http://stackoverflow.com/a/51428405
has comment: http://stackoverflow.com/comment/89823880
has answer: http://stackoverflow.com/a/51428405
has title: Defining a Method from A String in Python 3 and Referencing As Method
has body: I have a need to allow the user to define a function that processes data in an object (the wisdom and security implications in this have been discussed at length in another question and would just be duplicate comments here.) I'd like the function to act just like any other method. That is def my_method(self):... Would be invoked with: obj_handle.my_method() I almost have this achieved below except that the function that results need to be explicitly passed self as an argument, rather than receiving it as the first argument as is typical for a method. You can see this in property p where I have the odd self.process(self) call. I imagine that I need to provide something to exec that is like the globals() dictionary, but I'm not certain of several things: Is this correct? What is the equivalent of globals() in a class? Does this solve the problem? If not what do I need to do? So the question is, how do I get an exec() defined function to act as an object's method? class test: def __init__(self, a, b): self.a=a self.b=b @property def p(self): return self.process(self) def set_process(self,program): func_dict={} proc_fun = exec(program,func_dict) setattr(self,'process',func_dict['process']) def process(self): return self.a+self.b t=test(1,2) prog = '''\ def process(self): return self.a * self.b ''' t.set_process(prog) t.p
tagged with: python-3.x
upvote count: 1
tagged with: python
downvote count: 1
accepted answer: http://stackoverflow.com/a/51428676
type: AnsweredQuestion
type: Question

http://stackoverflow.com/comment/89901094
has text: FYI: That code is very un-pythonic.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51466034

http://stackoverflow.com/q/51470864
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51470980
answer count: 1
downvote count: 0
favorite count: 0
has title: invalid syntax when run pylint
has body: the following is the stack trace, please suggest my python version is 2.7 ----------------- pylint Traceback (most recent call last): File "E:\Python27\Scripts\pylint-script.py", line 11, in &lt;module&gt; load_entry_point('pylint==2.0.0', 'console_scripts', 'pylint')() File "E:\Python27\lib\site-packages\pylint-2.0.0-py2.7.egg\pylint\__init__.py" , line 17, in run_pylint from pylint.lint import Run File "E:\Python27\lib\site-packages\pylint-2.0.0-py2.7.egg\pylint\lint.py", li ne 75, in &lt;module&gt; import astroid File "E:\Python27\lib\site-packages\astroid-2.0.1-py2.7.egg\astroid\__init__.p y", line 59, in &lt;module&gt; from astroid.exceptions import * File "E:\Python27\lib\site-packages\astroid-2.0.1-py2.7.egg\astroid\exceptions .py", line 13, in &lt;module&gt; from astroid import util File "E:\Python27\lib\site-packages\astroid-2.0.1-py2.7.egg\astroid\util.py", line 148 yield from islice(iterator, size) ^ SyntaxError: invalid syntax my python version is 2.7
accepted answer: http://stackoverflow.com/a/51470980
has comment: http://stackoverflow.com/comment/89910048
tagged with: python
type: AnsweredQuestion
score: 1

http://stackoverflow.com/a/51332440
has body: I would use itertools.groupby on the reversed list. from itertools import groupby n = 2 lst = [None, 1, 3, None, 5, 6, 7, 8, 10, None, None, 11, 12, None, None] groups = groupby(reversed(lst), lambda x: isinstance(x, int)) result = next((grplist[0] for p, grp in groups for grplist in [list(grp)] if p and len(grplist) &gt; n), None)
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51332036
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89640482

http://stackoverflow.com/comment/89850563
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/51436675
has text: I am still unclear on a) what you want to do, and b) what the current problem is. Please click `edit` under your question and add a proper description to your question of what you want to do overall, and what the current problem is. Are there error messages? Is it too slow? Why are you even writing JPEG images out to disk - you can load frames from the videos and compute hashes on them as you go without JPEG encoding and disk I/O.

http://stackoverflow.com/a/51369336
answers question: http://stackoverflow.com/q/51354881
has body: A solution I found is to save the text as a run instead of a paragraph. For some reason it keeps the transparency/opacity you saved in the original document.
score: 0
type: Answer

http://stackoverflow.com/a/51427753
has body: &gt;&gt;&gt; from itertools import groupby, chain &gt;&gt;&gt; temp_merged_data = sorted(chain(list_1, list_2), key=lambda x:x['route']) &gt;&gt;&gt; route_data = [dict(chain(*map(dict.items, v))) for k,v in groupby(temp_merged_data, key=lambda x:x['route'])] &gt;&gt;&gt; route_data = [d for d in route_data if 'site' in d] &gt;&gt;&gt; pprint (route_data) [{'mask': '255.255.255.0', 'next_hop': '172.18.1.5', 'route': '10.10.4.0', 'site': 'Edinburgh'}, {'mask': '255.255.255.0', 'next_hop': '172.18.1.5', 'route': '10.10.5.0', 'site': 'London'}, {'mask': '255.255.255.0', 'next_hop': '172.16.66.34', 'route': '10.10.8.0', 'site': 'Manchester'}] Now if you convert the route data into a dict it would be easier to access the parameters for each site &gt;&gt;&gt; route_dict = {d['site']:d for d in route_data} &gt;&gt;&gt; route_dict['London']['next_hop'] '172.18.1.5'
type: Answer
score: 0
answers question: http://stackoverflow.com/q/51427277

http://stackoverflow.com/a/72952407
downvote count: 0
has body: Apparently, use of back_populates with explicit relationship() constructs should be preferred as explained at: https://docs.sqlalchemy.org/en/14/orm/backref.html
type: Answer
has comment: http://stackoverflow.com/comment/134151940
answers question: http://stackoverflow.com/q/51335298
upvote count: 17
score: 17

http://stackoverflow.com/a/51417718
upvote count: 1
score: 1
has body: Try this - def myList(spam): s = '' for i in range(len(spam)): if i == len(spam) - 1: s+= "and "+spam[i] else: s+= spam[i]+", " print(s) myList(spam) Or use join - print(', '.join(spam[:-1]) + ', and ' + spam[-1])
has comment: http://stackoverflow.com/comment/89806743
downvote count: 0
has comment: http://stackoverflow.com/comment/89806919
answers question: http://stackoverflow.com/q/51417424
type: Answer

http://stackoverflow.com/a/78121651
answers question: http://stackoverflow.com/q/51325551
has body: Found this question looking for a solution to read remote xls/xlsx file via proxy with pd.read_excel(). The solution that I found, was the following: response = requests.get(url, proxies = proxy_dict) filedata = BytesIO(response.content) df = pd.read_excel(filedata)
type: Answer
score: 0

http://stackoverflow.com/a/62715422
has comment: http://stackoverflow.com/comment/122446594
upvote count: 1
answers question: http://stackoverflow.com/q/51434897
type: Answer
has body: I know it's late but I wrote a program to convert mp3 to different playback speed. First, Convert the .MP3 -> .Wav because PYRubberBand supports only .wav format. Then streach the time and pitch at the same time to avoid chipmunk effect. import wave import sys from pydub import AudioSegment #sound = AudioSegment.from_file("deviprasadgharpehai.mp3") sound = AudioSegment.from_mp3(sys.argv[1]) sound.export("file.wav", format="wav") print(sys.argv[1]) import soundfile as sf import pyrubberband as pyrb y, sr = sf.read("file.wav") # Play back at extra low speed y_stretch = pyrb.time_stretch(y, sr, 0.5) # Play back extra low tones y_shift = pyrb.pitch_shift(y, sr, 0.5) sf.write("analyzed_filepathX5.wav", y_stretch, sr, format='wav') sound = AudioSegment.from_wav("analyzed_filepathX5.wav") sound.export("analyzed_filepathX5.mp3", format="mp3") # Play back at low speed y_stretch = pyrb.time_stretch(y, sr, 0.75) # Play back at low tones y_shift = pyrb.pitch_shift(y, sr, 0.75) sf.write("analyzed_filepathX75.wav", y_stretch, sr, format='wav') sound = AudioSegment.from_wav("analyzed_filepathX75.wav") sound.export("analyzed_filepathX75.mp3", format="mp3") # Play back at 1.5X speed y_stretch = pyrb.time_stretch(y, sr, 1.5) # Play back two 1.5x tones y_shift = pyrb.pitch_shift(y, sr, 1.5) sf.write("analyzed_filepathX105.wav", y_stretch, sr, format='wav') sound = AudioSegment.from_wav("analyzed_filepathX105.wav") sound.export("analyzed_filepathX105.mp3", format="mp3") # Play back at same speed y_stretch = pyrb.time_stretch(y, sr, 1) # Play back two smae-tones y_shift = pyrb.pitch_shift(y, sr, 1) sf.write("analyzed_filepathXnormal.wav", y_stretch, sr, format='wav') sound = AudioSegment.from_wav("analyzed_filepathXnormal.wav") sound.export("analyzed_filepathXnormal.mp3", format="mp3") **Make Sure to install ** Wave, AudioSegment, FFmpeg, PYRubberBand, Soundfile To use this Run, python3 filename.py mp3filename.mp3
downvote count: 0
score: 1

http://stackoverflow.com/comment/89687149
type: AnswerComment
score: 0
type: Comment
has text: Thank you for your answer. However, there are also columns which might contain numbers, is it possible to limit the summation only occurs in column a,b,c? @phi
comment on: http://stackoverflow.com/a/51357540

http://stackoverflow.com/comment/89850404
has text: great answer - just wondering is it `100/len(A)` or `1/len(A)` because it says `100%` in the function
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51440114

http://stackoverflow.com/a/51592052
answers question: http://stackoverflow.com/q/51442670
downvote count: 0
upvote count: 2
has body: You need to insert a call to robot.step() inside your while loop otherwise, the Webots simulation won't progress and the time will remain the same.
type: Answer
score: 2

http://stackoverflow.com/a/51380192
type: Answer
answers question: http://stackoverflow.com/q/51380124
score: 2
upvote count: 2
has body: Use a Counter To create: In [166]: import collections In [169]: d = collections.Counter(['hello', 'world', 'hello']) To display: In [170]: for word, freq in d.items(): ...: if freq &gt; 1: ...: print('{0} appeared {1} times'.format(word, freq)) ...: else: ...: print(word) ...: hello appeared 2 times world
downvote count: 0

http://stackoverflow.com/comment/89698764
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51363199
has text: That `print` inherently produces two spaces: one explicitly from the string literal, one implicitly from the separator between items. In Python 2.x you could hack out that second space within `calculate()` (via `sys.stdout.softspace = False`); in 3.x I don't believe there's any way without modifying the `print`.

http://stackoverflow.com/comment/89862717
score: 0
comment on: http://stackoverflow.com/a/51446155
type: Comment
has text: Could you try to manually download django using https://pypi.org/project/Django/#files and intall it using pip?
type: AnswerComment

http://stackoverflow.com/a/57088330
has body: Add my few cents to rvinas answer - there's parameter called keepdims which prevent reducing shape of tensor after applying some operation to it. keepdims: A boolean, whether to keep the dimensions or not. If keepdims is False, the rank of the tensor is reduced by 1. If keepdims is True, the reduced dimension is retained with length 1. out = Lambda(lambda x: K.mean(x, axis=1), keepdims=True)(conv4)
has comment: http://stackoverflow.com/comment/102178649
downvote count: 0
answers question: http://stackoverflow.com/q/51479940
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/51347364
has body: I'm working with Django, I have trouble fetching objects that are chained referenced. Here we are my Models class Environment(models.Model): name = models.CharField(max_length=200, unique=True) class Element(models.Model): environment = models.ForeignKey(Environment, on_delete=models.CASCADE,related_name='GroupPre') class AlarmActive(models.Model): element = models.ForeignKey(Element, on_delete=models.CASCADE,related_name='AlarmActivePre') My task is straightforward, I have to fetch all environments that have an AlarmActive. How can I achieve it? Thank you!
tagged with: python
favorite count: 0
type: UnansweredQuestion
has title: Get referenced object multipla layers django
tagged with: django
upvote count: 1
has answer: http://stackoverflow.com/a/51347428
type: Question
tagged with: django-models
answer count: 1
downvote count: 0
score: 1

http://stackoverflow.com/comment/89883420
has text: What does "representative" mean in this context? And [a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) is of course missing.
score: 1
comment on: http://stackoverflow.com/q/51456938
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51371482
tagged with: syntax
tagged with: type-hinting
has comment: http://stackoverflow.com/comment/89715077
has comment: http://stackoverflow.com/comment/89715083
type: Question
tagged with: types
downvote count: 0
accepted answer: http://stackoverflow.com/a/51371518
has comment: http://stackoverflow.com/comment/89715053
has body: I would like to annotate an argument of a function to indicate that a list is expected as argument. However I would like to keep the base type of the list unspecified. Is there a way to do this? Ie use a placeholder like below? def my_func(li: List[any]) edit is it possible to use a template: Ie something like: def union(li: List[List[T]])-&gt; List[T]:
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89715090
has title: Python type annotation for arbitrary list?
has comment: http://stackoverflow.com/comment/89715064
has comment: http://stackoverflow.com/comment/89715107
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/51371518
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/89836403
comment on: http://stackoverflow.com/q/51432598
score: 0
type: Comment
has text: What exactly is wrong with the plot you get? What does "sticking with the axes" mean?
type: QuestionComment

http://stackoverflow.com/q/51369821
type: AnsweredQuestion
has body: I have a Python 3 script that works well on my Linux Debian machine. I compiled it with Pyinstaller, (since only Python2.7 is installed on the server) and the generated executable is working fine on my machine as well. Then I copied the generated folder to a Linux server and tried to invoke it with the following PHP command: exec(dirname(__FILE__) . "/solve --state $state 2&gt;&amp;1", $response, $r); The $r variable contains the 139 exit code. I found out that this means some fragmentation error. I ran the "chmod 0764" command on the executable, but the problem still persists. Does anyone have any idea how could I solve this?
has answer: http://stackoverflow.com/a/51415179
accepted answer: http://stackoverflow.com/a/51415179
type: Question
tagged with: executable
score: 0
answer count: 1
tagged with: exec
tagged with: pyinstaller
tagged with: python
has title: Pyinstaller compiled executable fails with 139 exit code

http://stackoverflow.com/comment/89678390
has text: okay, if its numpy, is there any solution for this?
type: Comment
comment on: http://stackoverflow.com/q/51352905
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89894417
comment on: http://stackoverflow.com/q/51462749
type: Comment
has text: What is "timer code"?
score: 1
type: QuestionComment

http://stackoverflow.com/a/51357450
answers question: http://stackoverflow.com/q/51340790
type: Answer
has body: Use a char_filter to remove the hyphens before indexing. As a simple example: Set up the custom analyzer and apply it to the phone field. PUT my_index { "settings": { "analysis": { "analyzer": { "phone_analyzer": { "tokenizer": "standard", "char_filter": [ "phone_char_filter" ] } }, "char_filter": { "phone_char_filter": { "type": "mapping", "mappings": [ "- =&gt; " ] } } } }, "mappings": { "_doc": { "properties": { "phone": { "type": "text", "analyzer": "phone_analyzer" } } } } } Add some docs POST my_index/_doc {"phone": "123-456-7890"} POST my_index/_doc {"phone": "2345678901"} Search in xxx-xxx-xxxx format GET my_index/_search { "query": { "match": { "phone": "123-456-7890" } } } Search in xxxxxxxxxx format GET my_index/_search { "query": { "match": { "phone": "1234567890" } } }
upvote count: 1
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51340790
downvote count: 0

http://stackoverflow.com/comment/89757291
type: AnswerComment
has text: I mean the code in browser which is generated by django
comment on: http://stackoverflow.com/a/51392286
type: Comment
score: 0

ebnf
type: Tag
tags question: http://stackoverflow.com/q/51445192
tags question: http://stackoverflow.com/q/51327312
tag name: ebnf

http://stackoverflow.com/comment/89711109
type: Comment
type: QuestionComment
has text: For some reason your python does not see that library. Are you using conda?
score: 0
comment on: http://stackoverflow.com/q/51369426

http://stackoverflow.com/comment/89736327
comment on: http://stackoverflow.com/a/51381663
score: 0
type: AnswerComment
type: Comment
has text: It's working perfectly, but it's not so efficient and not stable.

http://stackoverflow.com/comment/89764944
type: QuestionComment
comment on: http://stackoverflow.com/q/51396867
has text: and what is the reason you do not plan to fix the script to prevent it from crashing?
score: 0
type: Comment

http://stackoverflow.com/a/73317234
downvote count: 0
has body: As for me. I hava several python version in my OS. When i run pip2 -v, it shows Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/pkg_resources/__init__.py", line 567, in _build_master ws.require(__requires__) File "/usr/local/lib/python3.5/dist-packages/pkg_resources/__init__.py", line 884, in require needed = self.resolve(parse_requirements(requirements)) File "/usr/local/lib/python3.5/dist-packages/pkg_resources/__init__.py", line 775, in resolve raise VersionConflict(dist, req).with_context(dependent_req) pkg_resources.VersionConflict: (pip 20.3.4 (/usr/local/lib/python3.5/dist-packages), Requirement.parse('pip==8.1.1')) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/bin/pip2", line 5, in <module> from pkg_resources import load_entry_point File "/usr/local/lib/python3.5/dist-packages/pkg_resources/__init__.py", line 3238, in <module> @_call_aside File "/usr/local/lib/python3.5/dist-packages/pkg_resources/__init__.py", line 3222, in _call_aside f(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/pkg_resources/__init__.py", line 3251, in _initialize_master_working_set working_set = WorkingSet._build_master() File "/usr/local/lib/python3.5/dist-packages/pkg_resources/__init__.py", line 569, in _build_master return cls._build_from_requirements(__requires__) File "/usr/local/lib/python3.5/dist-packages/pkg_resources/__init__.py", line 582, in _build_from_requirements dists = ws.resolve(reqs, Environment()) File "/usr/local/lib/python3.5/dist-packages/pkg_resources/__init__.py", line 770, in resolve raise DistributionNotFound(req, requirers) pkg_resources.DistributionNotFound: The 'pip==8.1.1' distribution was not found and is required by the application It shows that it find pip version in python3.5 directroy, so I think it maybe the multi version problem. So i execute ls -l /usr/bin/ |grep python, it shows that lrwxrwxrwx 1 root root 26 Aug 16 2019 dh_pypy ->…
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51392098
score: 1

http://stackoverflow.com/a/51419686
type: AcceptedAnswer
downvote count: 0
has body: You are reassigning bs4 on the bs4 = bs4.BeautifulSoup(r.content, 'html.parser') line, so at bs41 = bs4.BeautifulSoup(r1.content, 'html.parser') bs4 won't be the module. I suggest renaming that first bs4 = ... to soup = ..., maybe.
accepted answer of: http://stackoverflow.com/q/51419625
has comment: http://stackoverflow.com/comment/89810591
type: Answer
answers question: http://stackoverflow.com/q/51419625
upvote count: 1
score: 1

http://stackoverflow.com/a/51388059
has comment: http://stackoverflow.com/comment/89747954
score: 6
type: Answer
accepted answer of: http://stackoverflow.com/q/51388013
upvote count: 6
answers question: http://stackoverflow.com/q/51388013
has body: you want operator.attrgetter, no need for lambdas. This should also perform better: sorted(some_list, key=operator.attrgetter('name'))
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89828084
has text: `data.date.dt.minute` instead of `map`
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51428300

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/51478940
tags question: http://stackoverflow.com/q/51455279
tags question: http://stackoverflow.com/q/51337666
tag name: kivy-language
tags question: http://stackoverflow.com/q/51394464
tags question: http://stackoverflow.com/q/51348686

http://stackoverflow.com/comment/89776313
has text: Thank you for your messages, Please find my code above, sorry for that. Thank you
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51402593
type: QuestionComment

http://stackoverflow.com/q/51346710
favorite count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51346855
has body: I have a Base dataframe with 4 columns. column_A column_B column_C id 0 1 1 anna 123 1 2 1 anna 7 2 30 2 bob 42 2 20 2 bob 12 3 10 3 charlie 1 4 100 3 david 2 I want to split it into 2 different dataframes with the following properties. Dataframe 1: column_A column_B column_C id 0 1 1 anna 123 1 2 1 anna 7 2 30 2 bob 42 2 20 2 bob 12 where both values in column_B column_C match Dataframe 2: column_A column_B column_C id 3 10 3 charlie 1 4 100 3 david 2 where only values in column_B match
type: Question
possible better answer: http://stackoverflow.com/a/51347053
answer count: 2
has answer: http://stackoverflow.com/a/51347053
has title: I want to split Pandas Dataframe into 2 dataframes based on a condition
tagged with: pandas-groupby
tagged with: pandas
has answer: http://stackoverflow.com/a/51346855
downvote count: 0
score: 1

http://stackoverflow.com/a/51342742
has comment: http://stackoverflow.com/comment/89677409
has comment: http://stackoverflow.com/comment/89677594
has comment: http://stackoverflow.com/comment/89677241
score: 1
has body: You need to add blank=True to your model since it is a ForeignKey coupon = models.ForeignKey('carts.Coupon',related_name='carts',on_delete=models.SET_NULL, null=True, blank=True ) Here is a good post about the difference of null and blank on models
has comment: http://stackoverflow.com/comment/89677368
has comment: http://stackoverflow.com/comment/89677191
upvote count: 1
has comment: http://stackoverflow.com/comment/89677258
has comment: http://stackoverflow.com/comment/89677307
type: Answer
has comment: http://stackoverflow.com/comment/89677202
has comment: http://stackoverflow.com/comment/89675308
answers question: http://stackoverflow.com/q/51332141
has comment: http://stackoverflow.com/comment/89677471
downvote count: 0
has comment: http://stackoverflow.com/comment/89677717

http://stackoverflow.com/comment/89698942
has text: So how do I solve the next error: `chunk += ' ' * (16 - (len(chunk) % 16)) TypeError: can't concat bytes to str`? If I put a `b` in front of it, the encrypted file says it has bytes, but when i open it in the text editor, the file is blank.
comment on: http://stackoverflow.com/a/51362868
type: AnswerComment
score: 0
type: Comment

load-csv
tags question: http://stackoverflow.com/q/51470830
type: Tag
tag name: load-csv

http://stackoverflow.com/q/51455760
tagged with: python
has title: How can i run a loop that adds values to a string?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89881520
type: Question
has answer: http://stackoverflow.com/a/51455797
score: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/51455809
has answer: http://stackoverflow.com/a/51455833
has answer: http://stackoverflow.com/a/51455809
tagged with: string
accepted answer: http://stackoverflow.com/a/51455797
has body: my files names look like this: data00001 data00002 data00003 .... data00010 .... i have them saved and want to download them from the website they're in using this code: import urllib.request as urllib2 response = urllib2.urlopen("https://somewebsite/data00001.mat") file = open(r"C:\Users\me\Desktop\data\data00001.mat", 'wb') file.write(response.read()) file.close() i shall give the starting and end file name for example: from data00001 to data01000 so in this example i want the files from data0001 to data01000 downloaded. how can i increment the numeric value near data to make that work?
has comment: http://stackoverflow.com/comment/89881086
favorite count: 0
tagged with: python-3.x
upvote count: 2
downvote count: 2

http://stackoverflow.com/comment/89856937
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51443449
has text: (str.splitlines)[https://docs.python.org/2/library/stdtypes.html#str.splitlines] will be more robust here.

http://stackoverflow.com/comment/89830425
has text: It is utterly pointless to return anything from a Button's `command` - Tkinter is calling that function on your behalf, and is ignoring any return value. The reason you're not getting anything from that final `print` is that it happens immediately after constructing your GUI: the user has had no chance to actually do anything yet.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51429266
score: 2

http://stackoverflow.com/q/51390737
has comment: http://stackoverflow.com/comment/89785996
tagged with: selenium
type: Question
has comment: http://stackoverflow.com/comment/89784940
tagged with: javascript
has body: Goal: Hello I am pretty new to Web and Selenium. I am currently trying to grab a value from my JIRA Board. Here: Problem: For some reason that value does not show up in the page source. I think it might be a JavaScript rendered value? or maybe it gets generated after the page loads. I tried using implicitly_wait, WebDriverWait, and switch_Frame but nothing seems to work. =/ Code: #!/usr/local/bin/python2.7 #import requests import json import base64 import sys import getopt import argparse from datetime import datetime from datetime import timedelta from bs4 import BeautifulSoup from jira import JIRA from jira.client import GreenHopper import selenium from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.firefox.firefox_binary import FirefoxBinary from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.common.exceptions import TimeoutException JIRA_INSTALLATION = "jira.turn.com" STATE_IN_PROGRESS = "In Progress" STATE_RESOLVED = "Resolved" STATE_CLOSED = "Closed" options = {'server': 'https://jira.turn.com'} CUR_TIMEZONE_SHIFT = timedelta(hours=7) def main(argv): p=argparse.ArgumentParser(description="Gets a set of completed stories and list them with their implementation time.") p.add_argument('filter_id', help="Id of the filter that contains completed stories.") p.add_argument('-u', dest='username', help="JIRA username. Needs to have read access to all tickets returned from the search filter.") p.add_argument('-p', dest='password', help="Password for the JIRA user to use for API calls.") args = p.parse_args(argv) driver = webdriver.Firefox() driver.get('https://jira.turn.com/') driver.find_element_by_id("login-form-username").send_keys(args.username) driver.find_element_by_id ("login-form-password").send_keys(args.password) driver.find_element_by_id("login").click() #driver.implicitly_wait(10) #e…
upvote count: 1
has title: Python Selenium BeautifulSoup Page Source Does Not Display Everything
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0
downvote count: 0
score: 1

http://stackoverflow.com/q/51459785
has answer: http://stackoverflow.com/a/51983954
score: 0
accepted answer: http://stackoverflow.com/a/51983954
answer count: 1
has title: How to assign filename to Image in Django based on EXIF DateTime
tagged with: python
type: AnsweredQuestion
has body: I would like to read EXIF information from a user-uploaded image in Django, then use that EXIF info to generate the filename to store the image as (under the animal_img/alfred-0012 directory), for example: Original filename: P1110438.JPG Date taken: 2012-07-22 Name: Alfred Intended filename: alfred-20120722.jpg Somehow, this had been working up until recently, but Django has been complaining about not finding the file with [Errno 2] No such file or directory: 'P1110438.JPG' The code I've been using in my model to rename the images: def img_namer(instance, filename): path = 'animal_img/%s-%04d/' % (instance.name.lower(), instance.id) name = instance.name.lower() + Image.open(filename)._getexif()[36867] + ".jpg" return os.path.join(path, name) image = models.ImageField( default=None, blank=True, upload_to=img_namer, ) I can see the limitations with trying to open the ImageFile before it's been properly saved, however this had been working, like I said, so maybe I'm doing something wrong? Any help is appreciated!
tagged with: django
type: Question

http://stackoverflow.com/q/51457418
upvote count: 5
has body: I have a string: 'BZh91AY&amp;SYA\xaf\x82\r\x00\x00\x01\x01\x80\x02\xc0\x02\x00 \x00!\x9ah3M\x07&lt;]\xc9\x14\xe1BA\x06\xbe\x084' And I want: b'BZh91AY&amp;SYA\xaf\x82\r\x00\x00\x01\x01\x80\x02\xc0\x02\x00 \x00!\x9ah3M\x07&lt;]\xc9\x14\xe1BA\x06\xbe\x084' But I keep getting: b'BZh91AY&amp;SYA\\xaf\\x82\\r\\x00\\x00\\x01\\x01\\x80\\x02\\xc0\\x02\\x00 \\x00!\\x9ah3M\\x07&lt;]\\xc9\\x14\\xe1BA\\x06\\xbe\\x084' Context I scraped a string off of a webpage and stored it in the variable un. Now I want to decompress it using BZip2: bz2.decompress(un) However, since un is a str object, I get this error: TypeError: a bytes-like object is required, not 'str' Therefore, I need to convert un to a bytes-like object without changing the single backslash to an escaped backslash. Edit 1: Thank you for all the help! @wim I understand what you mean now, but I am at a loss as to how I can retrieve a bytes-like object from my webscraping method: r = requests.get('http://www.pythonchallenge.com/pc/def/integrity.html') doc = html.fromstring(r.content) comment = doc.xpath('//comment()')[0].text.split('\n')[1:3] pattern = re.compile("[a-z]{2}: '(.+)'") un = re.search(pattern, comment[0]).group(1) The packages that I am using are requests, lxml.html, re, and bz2. Once again, my goal is to decompress un using bz2, but I am having difficulty getting a bytes-like object from my webscraping process. Any pointers?
score: 4
has answer: http://stackoverflow.com/a/51457700
has title: Python: Convert Raw String to Bytes String without adding escape chraracters
tagged with: lxml
has answer: http://stackoverflow.com/a/51457730
tagged with: lxml.html
possible better answer: http://stackoverflow.com/a/51457700
favorite count: 0
tagged with: python-3.x
tagged with: bz2
tagged with: python
has comment: http://stackoverflow.com/comment/89889156
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51457730
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/7585435
answer count: 2
has comment: http://stackoverflow.com/comment/89884843
has comment: http://stackoverflow.com/comment/89885028

python-multiprocessing
tags question: http://stackoverflow.com/q/51424332
tags question: http://stackoverflow.com/q/51409295
tags question: http://stackoverflow.com/q/51398008
tags question: http://stackoverflow.com/q/51431243
tags question: http://stackoverflow.com/q/51474424
tags question: http://stackoverflow.com/q/51447406
tags question: http://stackoverflow.com/q/51379739
tags question: http://stackoverflow.com/q/51418671
tags question: http://stackoverflow.com/q/51431517
type: Tag
tags question: http://stackoverflow.com/q/51371880
tags question: http://stackoverflow.com/q/51415191
tags question: http://stackoverflow.com/q/51332411
tags question: http://stackoverflow.com/q/51325705
tag name: python-multiprocessing
tags question: http://stackoverflow.com/q/51427726
tags question: http://stackoverflow.com/q/51354706
tags question: http://stackoverflow.com/q/51352675
tags question: http://stackoverflow.com/q/51467460
tags question: http://stackoverflow.com/q/51412678
tags question: http://stackoverflow.com/q/51370913
tags question: http://stackoverflow.com/q/51350879
tags question: http://stackoverflow.com/q/51429801

http://stackoverflow.com/q/51393216
type: Question
has title: intuition to Async functions
has answer: http://stackoverflow.com/a/51396483
tagged with: function
answer count: 1
has comment: http://stackoverflow.com/comment/89758126
has body: thanks in advance, say you have an async funtion: async def create_list(num): print("Creating a list that is length {}".format(num)) i = 0 list = [] While True: i += 1 if i &gt; 100000: await asyncio.sleep(0.0001) list.append(i) if i == num: print("Finished creating a list that is length {}".format(num)) return list say you want to start some coroutines: async def main(): list1 = loop.create_task(create_list(1000)) list2 = loop.create_task(create_list(1000)) list3 = loop.create_task(create_list(1000)) await asyncio.wait([list1, list2, list3]) if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.close() my question is : firstly, is it right to assume that : if i &gt; 100000: await asyncio.sleep(0.0001) this code block here would temporarily halt the task and automatically switch to another coroutine? if so, then does the "i" variable in each coroutine get stored separately, or does the halting of the task completely abandon the previous process and when you come back to that same process you are just going to have to start again from 0. Thanks!
tagged with: python
tagged with: asynchronous
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89762393
tagged with: coroutine

http://stackoverflow.com/comment/89648398
comment on: http://stackoverflow.com/q/51336853
has text: What is the logic behind each of the day columns? I might try to handle this in the database. By the way, which database are you using?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89635061
type: QuestionComment
comment on: http://stackoverflow.com/q/51329675
has text: @DusanGligoric This throws an error: `AttributeError: 'PhotoImage' object has no attribute 'putalpha'`
score: 0
type: Comment

http://stackoverflow.com/comment/89716155
comment on: http://stackoverflow.com/q/51369701
type: Comment
has text: Just curious can I do it without using Ajax?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89739294
has text: after running the Draw() and print(Vehicle(0).routes), I still get empty list for Vehicle 0
comment on: http://stackoverflow.com/a/51379153
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51386128
has comment: http://stackoverflow.com/comment/89748370
score: 0
has comment: http://stackoverflow.com/comment/89748439
upvote count: 1
has comment: http://stackoverflow.com/comment/89746090
downvote count: 1
has comment: http://stackoverflow.com/comment/89748298
type: Question
has body: Department = input("what dept") editfile = pd.read_csv('52.csv', encoding='Latin-1') editfilevalues= editfile.loc[editfile['Customer'].str.contains(Department, na=False), 'May-18\nQty'] editfilevalues = editfilevalues.fillna(int(0)) print(int(editfilevalues) *1.3) I have looked through stackoverflow and no answer seems to help me this problem. I simply want to be able to manipulate data in a series like this but I get different errors, with this current code I receive this: "{0}".format(str(converter))) TypeError: cannot convert the series to &lt;class 'int'&gt; My main issue is converting a series to an int type, I have tried several different ways to do this and none are giving me the results
has comment: http://stackoverflow.com/comment/89746351
tagged with: dataframe
has answer: http://stackoverflow.com/a/51387471
has comment: http://stackoverflow.com/comment/89748351
answer count: 1
accepted answer: http://stackoverflow.com/a/51387471
has comment: http://stackoverflow.com/comment/89748163
favorite count: 0
has comment: http://stackoverflow.com/comment/89748278
has title: Python, manipulating dataframes
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/51371755
tagged with: matplotlib
score: 0
accepted answer: http://stackoverflow.com/a/51380025
tagged with: pandas
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89715604
has body: I am attempting to plot 7 histograms to observe returns in the market. My code is below. It is throwing the following error ValueError: x and y must have same first dimension, but have shapes (1230,) and (1,) I do not understand this error because my check is confirming the data is set up correctly &gt;&gt;&gt; print(SPY['SPY']) date 2013-07-16 151.7347 2013-07-17 152.1197 2013-07-18 152.9529 2013-07-19 153.2247 2013-07-22 153.5236 2013-07-23 153.1975 def plot_fat_tails(): SPY = pdr.DataReader('SPY', 'iex', start, end).rename(columns={'close': 'SPY'}) DIA = pdr.DataReader('DIA', 'iex', start, end).rename(columns={'close': 'DIA'}) DAX = pdr.DataReader('DAX', 'iex', start, end).rename(columns={'close': 'DAX'}) EWU = pdr.DataReader('EWU', 'iex', start, end).rename(columns={'close': 'EWU'}) EWH = pdr.DataReader('EWH', 'iex', start, end).rename(columns={'close': 'EWH'}) EWS = pdr.DataReader('EWS', 'iex', start, end).rename(columns={'close': 'EWS'}) INDY = pdr.DataReader('INDY', 'iex', start, end).rename(columns={'close': 'INDY'}) n_bins = 50 fig, axs = plt.subplots(7, 1, sharex=True) # Remove horizontal space between axes fig.subplots_adjust(hspace=0) # Plot each graph, and manually set the y tick values axs[0].plot(SPY['SPY'], n_bins, density=True, histtype='bar') axs[1].plot(DIA['DIA'], n_bins, density=True, histtype='bar') axs[2].plot(DAX['DAX'], n_bins, density=True, histtype='bar') axs[3].plot(EWU['EWU'], n_bins, density=True, histtype='bar') axs[4].plot(EWH['EWH'], n_bins, density=True, histtype='bar') axs[5].plot(EWS['EWS'], n_bins, density=True, histtype='bar') axs[6].plot(INDY['INDY'], n_bins, density=True, histtype='bar') plot.show() Corrected Code: def plot_fat_tails(): SPY = pdr.DataReader('SPY', 'iex', start, end).rename(columns={'close': 'SPY'}) DIA = pdr.DataReader('DIA', 'iex', start, end).rename(columns={'close': 'DIA'}) DAX = pdr.DataReader('DAX', 'iex', start, end).rename(columns={'close': 'DAX'}) EWU = pdr.DataReader('EWU', 'iex', start, end).rename(c…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89715587
has title: How to build histogram subplots using pandas python
has answer: http://stackoverflow.com/a/51380025
type: Question

http://stackoverflow.com/q/51425803
upvote count: 8
tagged with: python
has answer: http://stackoverflow.com/a/51426029
type: AnsweredQuestion
downvote count: 1
tagged with: tensorflow
type: Question
has title: What is the difference between static_rnn and dynamic_rnn?
score: 7
accepted answer: http://stackoverflow.com/a/51426029
answer count: 1
has body: In tensorflow, what is the difference between tf.nn.static_rnn and tf.nn.dynamic_rnn, and when to use them? Both take a sequence_length argument that adapts the computation to the actual length of the input; it is not as if static_rnn is limited to fixed-size inputs, right? dynamic_rnn has the following extra arguments: parallel_iterations swap_memory time_major But I suppose these are only minor differences. So what is the main difference between tf.nn.static_rnn and tf.nn.dynamic_rnn and when should we use one over the other?
favorite count: 0

http://stackoverflow.com/q/51360599
upvote count: 2
tagged with: loops
type: Question
tagged with: numpy
has title: Create a list by doing operations which depend on multiple indices - python
tagged with: arrays
accepted answer: http://stackoverflow.com/a/51360710
answer count: 2
possible better answer: http://stackoverflow.com/a/51360812
downvote count: 0
has answer: http://stackoverflow.com/a/51360812
favorite count: 0
has body: I am looking for a faster and more pythonic way to create a list whose elements depend on multiple indices from another list. An example of the code: import numpy as np xrandomsorted = np.sort(np.random.randn(1000000)) #input which needs to be used Npts = int(len(xrandomsorted)/3) #Part to be optimised begins here final_list = np.zeros(Npts) for i in range(Npts): xval = 12 - 3*xrandomsorted[i] + 7*xrandomsorted[2*i] - xrandomsorted[3*i] final_list[i] = xval I have found this solution to be marginally faster (though I still think there may be better solutions!): list1 = xrandomsorted[0:Npts] list2 = xrandomsorted[::2][0:Npts] list3 = xrandomsorted[::3][0:Npts] final_list = [] for value1, value2, value3 in zip(list1, list2, list3): xval = 12 - 3*value1 + 7*value2 -value3 final_list.append(xval) Is there any other way to make the code faster without using numba/cython?
tagged with: python
has answer: http://stackoverflow.com/a/51360710
type: AnsweredQuestion
score: 2

http://stackoverflow.com/comment/89795375
score: 0
type: AnswerComment
type: Comment
has text: Actually, you don’t need `varargout` in the case of an optional output argument either. You can, in the function, only assign something to the 2nd output argument if `nargout>1`. `varargout` is useful only when you don’t know how many output arguments you’ll have (see `deal` for example).
comment on: http://stackoverflow.com/a/51410140

http://stackoverflow.com/comment/89648049
score: 0
comment on: http://stackoverflow.com/q/51334861
type: QuestionComment
type: Comment
has text: @eyllanesc the table is updated instantly and automatically ? what is your config ?

http://stackoverflow.com/a/51366395
has body: You have an error in your code because you use df.Avg_Gain in creating df.Avg_Gain. Y values = [0, (df.Advance.rolling(14).sum())/14, (df.Avg_Gain.shift(1) * 13 + df.Advance)/14] df['Avg_Gain'] = np.select(conditions, values) I changed that part of the code to the following: up = df.Advance.rolling(14).sum()/14 values = [0, up, (up.shift(1) * 13 + df.Advance)/14] Output (idx>=14): Date Open High Low Close RSI 14 2018-01-19 1828.25 1836.35 1811.00 1829.50 75.237850 15 2018-01-22 1816.50 1832.55 1805.50 1827.20 72.920021 16 2018-01-23 1825.00 1825.00 1782.25 1790.15 58.793750 17 2018-01-24 1787.80 1792.70 1732.15 1737.50 40.573938 18 2018-01-25 1739.90 1753.40 1720.00 1726.40 31.900045 19 2018-01-29 1735.15 1754.95 1729.80 1738.70 33.197678 There should be a better way of doing this though. I'll update it with a better solution if i find one. Let me know if this data is correct. UPDATE: You also need to correct your calculation for 'Avg_loss`:: down = df.Decline.rolling(14).sum()/14 down_values = [0, down, (down.shift(1) * 13 + df.Decline)/14] df['Avg_Loss'] = np.select(conditions, down_values) http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:relative_strength_index_rsi#calculation UPDATE 2: After Expected data was provided. So the only way i could do this is by looping - not sure if possible to do it otherwise - maybe some pandas functionality i'm unaware of. So first do the same as before with setting Avg_Gain and Avg_Loss: you just need to change the values slightly: conditions = [idx&lt;13, idx==13, idx&gt;13] up = df.Advance.rolling(14).sum()/14 values = [0, up, 0] df['Avg_Gain'] = np.select(conditions, values) down = df.Decline.rolling(14).sum()/14 down_values = [0, down, 0] df['Avg_Loss'] = np.select(conditions, d_values) I have changed your conditions to split on index 13 - since this is what i see based on the expected output. Once you run this code you will populate the values for Avg_Gain and Avg_Loss from index 14 using the previ…
has comment: http://stackoverflow.com/comment/89729649
has comment: http://stackoverflow.com/comment/89735984
has comment: http://stackoverflow.com/comment/89732478
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89729440
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51356176
has comment: http://stackoverflow.com/comment/89722012
answers question: http://stackoverflow.com/q/51356176
score: 2

http://stackoverflow.com/q/51358929
type: Question
has comment: http://stackoverflow.com/comment/89690300
has answer: http://stackoverflow.com/a/51359038
tagged with: python-2.7
answer count: 2
has answer: http://stackoverflow.com/a/51359312
favorite count: 0
has comment: http://stackoverflow.com/comment/89690165
has comment: http://stackoverflow.com/comment/89690019
tagged with: python
has body: I am doing Shaw's exercise 32, from his book "Learn Python the Hard Way". First of all, this is the code from the exercise: the_count = [1, 2, 3, 4, 5] fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] # this first kind of for-loop goes through a list for number in the_count: print "This is count %d" % number # same as above for fruit in fruits: print "A fruit of type: %s" % fruit # also we can go through mixed lists too # notice we have %r since we don't know what's in it. for i in change: print "I got %r" % i # we can also build lists, first start with an empty one elements = range(0, 6) # then use the range function to do 0 to 5 counts #for i in range(0, 6): print "Adding %r to the list." % elements # append is a function that lists understand #elements.append(i) # now we can print them out too for i in elements: print "Element was: %r" % i In Study Drills I stumbled upon simple task, which is: Could you have avoided that for- loop entirely on line 22 and just assigned range(0,6) directly to elements? I changed it from this: elements = [] for i in range(0, 6): print "Adding %r to the list." % elements elements.append(i) To this: elements = range(0,6) print "Adding %r to the list." % elements elements.append(i) Still, the output, before commenting out elements.append(i) was: This is count 1 This is count 2 This is count 3 This is count 4 This is count 5 A fruit of type: apples A fruit of type: oranges A fruit of type: pears A fruit of type: apricots I got 1 I got 'pennies' I got 2 I got 'dimes' I got 3 I got 'quarters' Adding [0, 1, 2, 3, 4, 5] to the list. Element was: 0 Element was: 1 Element was: 2 Element was: 3 Element was: 4 Element was: 5 Element was: 'quarters' Why is the last line printed? Or, more precisely, why append adds quarters? What is the mechanism behind it? P.S. I would like to know why it will get / is this getting downvoted, since I want to improve next time I dare to ask question here at SO…
tagged with: append
score: -1
type: UnansweredQuestion
downvote count: 2
has title: Why does command append(i) adds last element from previous call?
upvote count: 1

http://stackoverflow.com/a/51391302
score: 0
type: Answer
has body: I'm not entirely sure I follow you're problem description, but here is my attempt at interpreting it as best I can: import math def is_factor(n,m): return m % n == 0 def is_prime(n): if n % 2 == 0 and n &gt; 2: return False return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2)) def assign_points(n): for i in range(1,n+1): if is_factor(i,n) and is_prime(i): print('two points for: ', i) elif is_factor(i,n): print('one point for: ', i) print(assign_points(15))
answers question: http://stackoverflow.com/q/51391014

http://stackoverflow.com/comment/89673906
type: AnswerComment
score: 0
has text: With more context I meant more what you actually want to archieve. DeepSpace answers your question that there is no way on windows to write to on already opened file. I would suggest looking into xlwings because there you can integrate python code with excel. If you have another concrete question I would suggest asking a new one here on SO.
type: Comment
comment on: http://stackoverflow.com/a/51349851

http://stackoverflow.com/q/51366606
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89706428
downvote count: 0
type: Question
score: 5
has body: The python module datetime.datetime provides strftime and strptime. datetime.date provides only strftime. Why is that?
has answer: http://stackoverflow.com/a/51367552
accepted answer: http://stackoverflow.com/a/51367552
has comment: http://stackoverflow.com/comment/89705517
has title: Why does datetime.date not provide strptime?
answer count: 1
favorite count: 0
upvote count: 5
tagged with: python

http://stackoverflow.com/a/51368936
score: 4
has comment: http://stackoverflow.com/comment/89714462
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51368440
accepted answer of: http://stackoverflow.com/q/51368440
type: Answer
has body: Similar to the answer by @Aaron but without sorting the list. Just keep track of the running best. import itertools def choose_best_sum(t, k, ls): best_sum = 0 best_set = None combinations = itertools.combinations(ls, k) for combination in combinations: combi_sum = sum(combination) if combi_sum &lt;= t and combi_sum &gt; best_sum: best_set = combination best_sum = combi_sum return (best_set, best_sum) xs = [100, 76, 56, 44, 89, 73, 68, 56, 64, 123, 2333, 144, 50, 132, 123, 34, 89] xs = [item for item in xs if item &lt; 430] choose_best_sum(230, 4, xs)#, 230) choose_best_sum(430, 5, xs)#, 430) choose_best_sum(430, 8, xs)#, None) The first thing you can do is just ditch 2333 from xs because that can never be in a combination. I'm not sure why, in addition to creating your own sum, you have while len(distances)!=0 and max(distances)&gt;t: and so much list manipulation (appending and popping). The %timeit result: %timeit choose_best_sum(430, 8, xs) 5.43 ms ± 72.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
upvote count: 4
downvote count: 0

http://stackoverflow.com/comment/89664942
comment on: http://stackoverflow.com/a/51345522
type: AnswerComment
score: 1
type: Comment
has text: The requirement to `return` something for the caller to print isn't strictly necessary, though it's arguably an architectural improvement.

http://stackoverflow.com/comment/89844677
score: 0
type: Comment
type: QuestionComment
has text: Always the same format - they explain the ground conditions of a race (in horse racing) so the ground is slow or that ground is Standard to Slow
comment on: http://stackoverflow.com/q/51401963

http://stackoverflow.com/q/51352834
score: 1
favorite count: 0
type: Question
tagged with: python
has body: I currently have this setup: class Address (models.Model): Member = models.ForeignKey(Member, blank=True, null=True, on_delete=models.CASCADE) Unit = models.ForeignKey(Unit, blank=True, null=True, on_delete=models.CASCADE) Address1 = models.TextField(max_length=512) Address2 = models.TextField(max_length=512, null=True, blank=True) City = models.TextField(max_length=100) State = models.TextField(max_length=100) Zip = models.TextField(max_length=25) Latitude = models.FloatField(null=True, blank=True) Longitude = models.FloatField(null=True, blank=True) Primary = models.BooleanField(default=False) class Phone (models.Model): Member = models.ForeignKey(Member, blank=True, null=True, on_delete=models.CASCADE) Unit = models.ForeignKey(Unit, blank=True, null=True, on_delete=models.CASCADE) Phone = models.CharField(max_length=25) Type = models.CharField(max_length=25) Primary = models.BooleanField(default=False) class Member (models.Model): FederationID = models.FloatField(unique=True) UserId = models.ForeignKey(User, on_delete=models.CASCADE) height = models.IntegerField(blank=True, null=True) eye = models.CharField(blank=True, null=True) hair = models.CharField(blank=True, null=True) bio = models.TextField() class Unit (models.Model): Name = models.CharField(max_length=255) Hull = models.CharField(max_length=20) Type = models.CharField(max_length=20) I'm trying to use a single address table to mimic both Members and Units' Address. I'm asking if this is the right way to go about this? Is there a more DRY version of doing this correctly. Notice the Phone model as well. Same question. Thanks.
tagged with: django
has title: How do I share a child foreign table amongst to parent tables in Django models
upvote count: 1
has answer: http://stackoverflow.com/a/51353277
answer count: 1
tagged with: django-models
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/a/51418743
accepted answer of: http://stackoverflow.com/q/51418579
upvote count: 1
has comment: http://stackoverflow.com/comment/89810628
has comment: http://stackoverflow.com/comment/89808496
type: AcceptedAnswer
downvote count: 0
score: 1
has body: You need to make copy of original list and then iterate over new copy and remove the items from original list for item in list(original_list): ... original_list.remove(item) In your case, code will look like below total_read = 0 for i in range(21): random.shuffle(info) for index, value in enumerate(list(info)): b, p, s = value if len(s) &lt;= i+1: print("Overshot! Shouldn't see this sentence anymore: %s" % (s)) info.pop(index) print s[:i+1], i, s total_read += len(s[i + 1])
type: Answer
answers question: http://stackoverflow.com/q/51418579

http://stackoverflow.com/q/51433914
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89838337
has title: Python 3.5 syntax using '@' to pass argument into function and PyLint
type: UnansweredQuestion
tagged with: pylint
tagged with: python
score: 1
upvote count: 1
has body: I'm currently using the PySpice module for circuit sim. PySpice is using some syntax implemented in Python 3.5 that I've never seen before: https://pyspice.fabrice-salvaire.fr/api/PySpice/Unit.html I'd like to find the Python reference for this syntax. Primarily, I'd like to get PyLint to recognize it.
type: Question
tagged with: python-3.5
has comment: http://stackoverflow.com/comment/89838481
has answer: http://stackoverflow.com/a/51433925
has comment: http://stackoverflow.com/comment/89838343
answer count: 1

http://stackoverflow.com/q/51352883
has answer: http://stackoverflow.com/a/51359776
tagged with: list
has title: how to split a python list by a regex expression
type: Question
tagged with: split
answer count: 2
has comment: http://stackoverflow.com/comment/89681040
score: 0
has comment: http://stackoverflow.com/comment/89678469
has comment: http://stackoverflow.com/comment/89678511
tagged with: python
tagged with: regex
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89678457
has answer: http://stackoverflow.com/a/51353024
has body: I am reading a file from the web row by row and each row is a list. The list has three columns visibly separated by this pattern: +++$+++. this is my code: with closing(requests.get(url, stream=True)) as r: reader = csv.reader(codecs.iterdecode(r.iter_lines(), 'latin-1')) for i, row in enumerate(reader): if i &lt; 5: t = row[0].split('(\s\+{3}\$\+{3}\s)+') print(t) I have tried to split the list using this instruction in python3.6 and can't get it to work. Any suggestion is well appreciated: the list: ['m0 +++$+++ 10 things i hate about you +++$+++ http://www.dailyscript.com/scripts/10Things.html'] ['m1 +++$+++ 1492: conquest of paradise +++$+++ http://www.hundland.org/scripts/1492-ConquestOfParadise.txt'] ['m2 +++$+++ 15 minutes +++$+++ http://www.dailyscript.com/scripts/15minutes.html'] ['m3 +++$+++ 2001: a space odyssey +++$+++ http://www.scifiscripts.com/scripts/2001.txt'] ['m4 +++$+++ 48 hrs. +++$+++ http://www.awesomefilm.com/script/48hours.txt'] this is my regex expression: row[0].split('(\s\+{3}\$\+{3}\s)+') each row has only one component -> row[0] when I print the result is not splitting the row.

http://stackoverflow.com/comment/89854880
type: AnswerComment
score: 0
type: Comment
has text: In your question you did say 'equal'... I suppose you can apply rounding to your data but that's probably not desirable, alternatively my answer can be modified to work with greater than or less than conditions, although that would become pretty much the same as the accepted answer
comment on: http://stackoverflow.com/a/51442224

http://stackoverflow.com/comment/89835724
score: 0
type: Comment
has text: ok thanks ill try that
type: QuestionComment
comment on: http://stackoverflow.com/q/51412137

http://stackoverflow.com/q/51438472
tagged with: python
has answer: http://stackoverflow.com/a/51441016
tagged with: matplotlib
has body: I'm writing a small class containing all the parameters suitable for my needs, but I came across a problem when I define the 3 cycles to be accomplish. What I' do is : define 3 type of cycle (cycle0, cycle1, cycle2) and then in a dictionary containing several rcParams i set 'axes.prop_cycle' the 3 cycle are defined as follow: cycle0 = plt.cycler("color", colors) cycle1 = plt.cycler("color", colors) + plt.cycler("linestyle", linestyles) cycle2 = plt.cycler("color", colors) * plt.cycler("linestyle", linestyles) the problem appars when I chose to use cycle0 : 'axes.prop_cycle': cycle0, and the set of the colors (that I choose) have a different length respect the linestyle but with cycle0 I don't wan't use the linestyle ! how can I manage this problem ? so far I have to comment out cycle1 when I have to use cycle0 and comment out cycle1 when I wabt to use its EDIT the error is this one : ValueError: Can only add equal length cycles, not 6 and 8 but in myparams definition I'm use 'axes.prop_cycle': cycle0, EDIT minimum compilable example : import numpy as np import matplotlib.pyplot as plt def _plot(*args,**kwargs): linestyles = [(0, ()),(0, (1, 1)),(0, (5, 10)),(0, (5, 5)),(0, (5, 1)),(0, (3, 10, 1, 10)),(0, (3, 5, 1, 5)),(0, (3, 5, 1, 5, 1, 5)) ] colors = ['#3B4CC0','#7C9FF9','#C0D4F5','#F2CBB7','#EE8568','#B40426'] variable = [*args] if len(variable) % 3 != 0: print('Error variable must be coupled (even number)') raise AttributeError('you must give 2 array x,y followed by string label for each plot') parameters = {**kwargs} cycle0 = plt.cycler("color", colors) cycle1 = plt.cycler("color", colors) + plt.cycler("linestyle", linestyles) cycle2 = plt.cycler("color", colors) * plt.cycler("linestyle", linestyles) myparams = { 'axes.prop_cycle': cycle0 } plt.rcParams.update(myparams) fig,ax = plt.subplots(1,figsize=(7,4.2)) for i in range(0,len(variable)-1,3): plt.plot(variable[i],variable[i+1], linewidth=3, label= variable[i+2]) plt.grid(linestyle='--', dashes=(5,7)) plt.sh…
has comment: http://stackoverflow.com/comment/89851894
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89848387
type: Question
has comment: http://stackoverflow.com/comment/89848782
score: 0
answer count: 1
favorite count: 0
has title: Matplotlib problems with colors and line cycles
type: UnansweredQuestion

http://stackoverflow.com/q/51352544
tagged with: count
tagged with: python
has answer: http://stackoverflow.com/a/51352741
accepted answer: http://stackoverflow.com/a/51352741
upvote count: 1
answer count: 1
has body: I've got a dataframe with the following data idpresm teamid competicion fecha local \ 0 12345 dummy1 ECU D1 2018-07-07 Deportivo Cuenca 1 12345 dummy1 ECU D1 2018-07-03 Liga Dep. Universitaria Quito 2 12345 dummy1 ECU D1 2018-06-24 Universidad Catolica 3 12345 dummy1 ECU D1 2018-06-18 Club Sport Emelec 4 12345 dummy1 ECU D1 2018-06-12 Universidad Catolica 5 12345 dummy1 ECU D1 2018-06-05 Delfin SC 6 12345 dummy1 ECU D1 2018-05-31 Sociedad Deportiva Aucas 7 12345 dummy1 ECU D1 2018-05-26 Universidad Catolica 8 12345 dummy1 ECU D1 2018-05-12 Universidad Catolica 9 12345 dummy1 ECU D1 2018-05-05 Macara 10 12345 dummy1 ECU D1 2018-04-28 Universidad Catolica 11 12345 dummy1 ECU D1 2018-04-21 Guayaquil City 12 12345 dummy1 ECU D1 2018-04-14 Universidad Catolica 13 12345 dummy1 ECU D1 2018-04-07 CD El Nacional 14 12345 dummy1 ECU D1 2018-03-31 Universidad Catolica 15 12345 dummy1 ECU D1 2018-03-25 Independiente Jose Teran 16 12345 dummy1 ECU D1 2018-03-20 Universidad Catolica 17 12345 dummy1 ECU D1 2018-03-10 Tecnico Universitario 18 12345 dummy1 INT CF 2018-03-09 Colchagua CD 19 12345 dummy1 ECU D1 2018-03-04 Universidad Catolica aw homeha line awayha r1 r3 0 2.39 0.96 0 0.80 1 1 1 3.79 0.85 0.5 0.91 2 1 2 9.32 1.00 1.5 0.84 4 0 3 5.80 0.99 1 0.85 2 3 4 2.93 0.85 0/0.5 0.97 1 1 5 3.86 1.04 0.5 0.80 5 2 6 2.61 0.85 0 0.99 0 1 7 3.32 1.04 0/0.5 0.80 1 1 8 5.56 0.90 1 0.94 2 1 9 2.82 0.70 0 1.16 1 2 10 3.60 1.00 0.5 0.84 3 1 11 2.20 1.04 0 0.80 1 1 12 4.07 0.99 0.5 0.85 2 0 13 2.77 0.97 0/0.5 0.85 0 0 14 3.36 0.80 0.5 1.02 3 1 15 6.11 0.97 0.5 0.85 2 1 16 2.03 0.91 0/-0.5 0.85 2 0 17 2.21 0.70 0/-0.5 1.13 0 2 18 1.44 NaN NaN NaN 0 0 19 2.76 0.80 0 1.02 1 2 what I do is I gruopby by local column, and then I intend to get the average of the column r1, for that I do the following homedata.groupby('local')['r1'].agg({'media':np.average,'contador': lambda x: x.value_counts()}) I would expect a column of integers in 'contador'. what I get is this media contador local CD El Naciona…
has title: Groupby and how value_counts work
tagged with: pandas-groupby
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x
type: Question

http://stackoverflow.com/comment/89870280
comment on: http://stackoverflow.com/q/51449888
type: Comment
has text: Possible duplicate of [Pythonic way to create a long multi-line string](https://stackoverflow.com/questions/10660435/pythonic-way-to-create-a-long-multi-line-string)
score: 1
type: QuestionComment

http://stackoverflow.com/comment/89728311
comment on: http://stackoverflow.com/q/51378225
has text: share your code its difficult to understand the problem like this
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89724810
comment on: http://stackoverflow.com/a/51367148
type: AnswerComment
score: 0
type: Comment
has text: Hi! Thank you for the clear explanation! I'm still facing issues (Wrong Answer) with the corrected code.

http://stackoverflow.com/comment/89934014
score: 1
type: QuestionComment
has text: You can use a class, and make your functions methods of the class. All the methods will then automatically receive `self`, and you can replace the global variable `task_queued` with an instance member `self.task_queued`. You would initialize the variable in the constructor (`__init__`). This classic OO approach allows the methods to share the state without confining it to a singleton - e.g. it then becomes possible to run two queues at the same time.
comment on: http://stackoverflow.com/q/51482501
type: Comment

http://stackoverflow.com/comment/89899057
comment on: http://stackoverflow.com/a/51465045
type: AnswerComment
score: 0
type: Comment
has text: hi andrej I have placed my code and the error in this link https://anotepad.com/notes/hn7k2k

music21
type: Tag
tags question: http://stackoverflow.com/q/51416484
tag name: music21
tags question: http://stackoverflow.com/q/51370418

http://stackoverflow.com/comment/89850297
comment on: http://stackoverflow.com/q/51439825
score: 0
type: QuestionComment
has text: @FlyingTeller ['D:\\PycharmProjects\\Tasks\\applications', 'D:\\PycharmProjects\\Tasks', 'C:\\Program Files\\Python36\\python36.zip', 'C:\\Program Files\\Python36\\DLLs', 'C:\\Program Files\\Python36\\lib', 'C:\\Program Files\\Python36', 'C:\\Program Files\\Python36\\lib\\site-packages']
type: Comment

http://stackoverflow.com/comment/89673110
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51349523
has text: you need `for idx,item in enumerate(my_list):` to get the index **and** the element
type: AnswerComment

http://stackoverflow.com/a/51388479
upvote count: 1
has body: Thanks to all that answered - Zoe's answer helped me frame the below logic - I believe the difference was adding (.values()) to refer the value . It is not exactly a straightforward if-else - I will have to write another condition to evaluate once the entire thing runs. However, it will do for now. I do wish that I can do away with the abc = 0 though, removing it throws up an error. CompName=[{"name":"AB","freq":1}, {"name":"BC","freq":1}, {"name":"CD","freq":1}] CompNameText="XY" abc=0 for AllNames in CompName.values(): if CompNameText in AllNames["name"]: print("Found") AllNames['freq']=AllNames['freq']+1 break else: abc+=1 if abc == len(CompName): CompName.append({"name":CompNameText,"freq":1}) print(CompName)
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/51387434
score: 1

http://stackoverflow.com/a/51446512
accepted answer of: http://stackoverflow.com/q/51446327
downvote count: 0
answers question: http://stackoverflow.com/q/51446327
score: 9
has comment: http://stackoverflow.com/comment/89886806
type: AcceptedAnswer
upvote count: 9
has comment: http://stackoverflow.com/comment/89886703
has comment: http://stackoverflow.com/comment/89873479
has body: I think this is always going to be messy as long as you're trying to fit this into a one liner. I would just bite the bullet and go with a generator function here. Especially useful if you don't know the actual size (say, if gen is an infinite generator, etc). from itertools import islice def chunk(gen, k): """Efficiently split `gen` into chunks of size `k`. Args: gen: Iterator to chunk. k: Number of elements per chunk. Yields: Chunks as a list. """ while True: chunk = [*islice(gen, 0, k)] if chunk: yield chunk else: break &gt;&gt;&gt; gen = iter(list(range(11))) &gt;&gt;&gt; list(chunk(gen)) [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10]] Someone may have a better suggestion, but this is how I'd do it.
type: Answer

http://stackoverflow.com/comment/89658513
comment on: http://stackoverflow.com/q/51342544
score: 0
type: Comment
type: QuestionComment
has text: I edited my original post, it explained

http://stackoverflow.com/a/51397503
upvote count: 3
score: 3
has body: You can use numpys broadcasting rules to cast the first array to the shape (13, 1, 2) and the second to the shape (1, 5, 2): numpy.all(x[:, None, :] + y[None, :, :] == xy) # True The array is repeated across the dimension where None is added (since it has length 1). Therefore the shape of the output becomes (13, 5, 2).
answers question: http://stackoverflow.com/q/51397389
downvote count: 0
type: Answer

http://stackoverflow.com/a/51367406
type: Answer
has body: Vectorised, you can use pd.Series.value_counts after filtering your dataframe. You can use categorical data to ensure all keys are included: df1 = pd.DataFrame({'sku': ['A0', 'A0', 'A2', 'A2', 'A3', 'A3'], 'ID': ['10', 'T1', 'T1', 'T2', '10', '20']}) df1['sku'] = df1['sku'].astype('category') res = df1.loc[df1['ID'].str[0] == 'T', 'sku'].value_counts(sort=False) print(res) A0 1 A2 2 A3 0 Name: sku, dtype: int64 For unique values, you can use groupby + nunique: res = df1[df1['ID'].str[0] == 'T'].groupby('sku')['ID'].nunique()
has comment: http://stackoverflow.com/comment/89715118
upvote count: 3
answers question: http://stackoverflow.com/q/51367369
score: 3
downvote count: 0

http://stackoverflow.com/comment/89653727
type: Comment
type: QuestionComment
score: 0
has text: If I understand your question, click on the start button and locate Anaconda3 in the list. Expand this and should notice Anaconda Navigator and click to execute it. OR search for Anaconda Navigator after clicking start.You should see all the missing programs within Navigator.
comment on: http://stackoverflow.com/q/51339986

arrays
tags question: http://stackoverflow.com/q/51372651
tags question: http://stackoverflow.com/q/51393982
type: Tag
tags question: http://stackoverflow.com/q/51426669
tags question: http://stackoverflow.com/q/51348977
tags question: http://stackoverflow.com/q/51337570
tags question: http://stackoverflow.com/q/51436102
tags question: http://stackoverflow.com/q/51359623
tags question: http://stackoverflow.com/q/51468957
tags question: http://stackoverflow.com/q/51368357
tags question: http://stackoverflow.com/q/51461133
tags question: http://stackoverflow.com/q/51371018
tags question: http://stackoverflow.com/q/51369718
tags question: http://stackoverflow.com/q/51360599
tags question: http://stackoverflow.com/q/51394993
tags question: http://stackoverflow.com/q/51481373
tags question: http://stackoverflow.com/q/51431255
tags question: http://stackoverflow.com/q/51422519
tags question: http://stackoverflow.com/q/51349738
tags question: http://stackoverflow.com/q/51371902
tags question: http://stackoverflow.com/q/51478920
tags question: http://stackoverflow.com/q/51455543
tags question: http://stackoverflow.com/q/51472668
tags question: http://stackoverflow.com/q/51442086
tags question: http://stackoverflow.com/q/51332056
tags question: http://stackoverflow.com/q/51434441
tags question: http://stackoverflow.com/q/51471097
tags question: http://stackoverflow.com/q/51331102
tags question: http://stackoverflow.com/q/51361765
tags question: http://stackoverflow.com/q/51344821
tags question: http://stackoverflow.com/q/51373302
tags question: http://stackoverflow.com/q/51435571
tags question: http://stackoverflow.com/q/51372523
tags question: http://stackoverflow.com/q/51372970
tags question: http://stackoverflow.com/q/51383195
tags question: http://stackoverflow.com/q/51352527
tags question: http://stackoverflow.com/q/51411388
tags question: http://stackoverflow.com/q/51432666
tags question: http://stackoverflow.com/q/51378404
tag name: arrays
tags question: http://stackoverflow.com/q/51328718
tags question: http://stackoverflow.com/q/51453265
tags question: http://stackoverflow.com/q/51410509
tags question: http://stackoverflow.com/q/51442279
tags question: http://stackoverflow.com/q/51431380
tags question: http://stackoverflow.com/q/51356287
tags question: http://stackoverflow.com/q/51401832
tags question: http://stackoverflow.com/q/51426289
tags question: http://stackoverflow.com/q/51451400
tags question: http://stackoverflow.com/q/51466137
tags question: http://stackoverflow.com/q/51410742
tags question: http://stackoverflow.com/q/51335766
tags question: http://stackoverflow.com/q/51458509
tags question: http://stackoverflow.com/q/51433630
tags question: http://stackoverflow.com/q/51342162
tags question: http://stackoverflow.com/q/51335959
tags question: http://stackoverflow.com/q/51383298
tags question: http://stackoverflow.com/q/51373413
tags question: http://stackoverflow.com/q/51358494
tags question: http://stackoverflow.com/q/51392515
tags question: http://stackoverflow.com/q/51419025
tags question: http://stackoverflow.com/q/51457912
tags question: http://stackoverflow.com/q/51456777
tags question: http://stackoverflow.com/q/51428730
tags question: http://stackoverflow.com/q/51388548
tags question: http://stackoverflow.com/q/51438577
tags question: http://stackoverflow.com/q/51425667
tags question: http://stackoverflow.com/q/51449319
tags question: http://stackoverflow.com/q/51398004
tags question: http://stackoverflow.com/q/51338448
tags question: http://stackoverflow.com/q/51469160
tags question: http://stackoverflow.com/q/51474100
tags question: http://stackoverflow.com/q/51439215
tags question: http://stackoverflow.com/q/51468593
tags question: http://stackoverflow.com/q/51423972
tags question: http://stackoverflow.com/q/51358894
tags question: http://stackoverflow.com/q/51419553
tags question: http://stackoverflow.com/q/51402133
tags question: http://stackoverflow.com/q/51439644
tags question: http://stackoverflow.com/q/51372801

http://stackoverflow.com/comment/89935806
has text: But **why** are you running it as root? `ls -l` doesn't mean anything for Python/Jupyter
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51481948

http://stackoverflow.com/comment/128951544
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51335298
has text: @GordThompson, but the current documentation recommends both without mention of one being preferred over the other, implying that they have different purposes: https://docs.sqlalchemy.org/en/14/orm/basic_relationships.html
score: 0

http://stackoverflow.com/q/51443913
upvote count: 3
has body: Currently I have a dataframe that looks like the following: df = Open High Low Close TotalVolume 0 113.40 113.54 113.40 113.54 7237 1 113.54 113.58 113.52 113.57 10099 2 113.59 113.81 113.52 113.78 13827 3 113.76 113.94 113.75 113.92 16129 4 113.91 114.01 113.88 113.97 27052 5 113.97 114.11 113.92 114.01 24925 6 114.00 114.15 113.99 114.04 13461 7 114.06 114.14 113.94 113.94 10702 8 113.92 113.99 113.86 113.99 5538 9 113.96 113.96 113.85 113.86 14000 It does not necessarily have to be a datetime index but I felt like it would be the easiest. From this I have a variable startDate that follows this format startDate = "03-20-2018t14:00" From this, this is minute data and for it to run another program, the format has to follow this, but this is the end result I am hoping for: updated_df = Date Time Open High Low Close TotalVolume 03/20/2018 14:00 113.40 113.54 113.40 113.54 7237 03/20/2018 14:01 113.54 113.58 113.52 113.57 10099 03/20/2018 14:02 113.59 113.81 113.52 113.78 13827 03/20/2018 14:03 113.76 113.94 113.75 113.92 16129 03/20/2018 14:04 113.91 114.01 113.88 113.97 27052 03/20/2018 14:05 113.97 114.11 113.92 114.01 24925 03/20/2018 14:06 114.00 114.15 113.99 114.04 13461 03/20/2018 14:07 114.06 114.14 113.94 113.94 10702 03/20/2018 14:08 113.92 113.99 113.86 113.99 5538 03/20/2018 14:09 113.96 113.96 113.85 113.86 14000
accepted answer: http://stackoverflow.com/a/51444011
type: Question
type: AnsweredQuestion
score: 3
tagged with: dataframe
has title: python/pandas from start date + time, create datetime index
downvote count: 0
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/35398944
has answer: http://stackoverflow.com/a/51444011
tagged with: pandas
tagged with: python

http://stackoverflow.com/q/51430132
accepted answer: http://stackoverflow.com/a/51430184
tagged with: pandas
has title: How to do a calculation on each line of a pandas dataframe in python?
answer count: 1
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/89831429
downvote count: 2
upvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51430184
score: -1
has comment: http://stackoverflow.com/comment/89831299
type: Question
linked to: http://stackoverflow.com/q/51370465
has body: I am brand new to python, I am attempting to convert the function I made in R to Python, R function described here: How to optimize this process? From my reading it looks like the best way to do this in python would be to use a for loop that would take the following form for line 1 in probe test find user in U_lookup find movie in M_lookup take the value found in U_lookup and retrieve that line number from knn_text take the values found in that row of knn_text, and retrieve the line numbers from dfm for those line numbers in dfm, retrieve column=U_lookup take the average of the non zero values found save value into pandas datafame in new column for that line Is this the most efficient (in terms of speed of calculation) way to complete an operation like this? Coming from R so I wasn't sure if there was better functionality for something like this within the pandas package or not. As a followup, is there an equivalent in python to the function dput() in R? dput essentially provides code to easily share a subset of data for questions like this.
tagged with: for-loop

http://stackoverflow.com/comment/89815501
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51422193
has text: What programming language or tool are you running your regex with?
score: 0

http://stackoverflow.com/comment/89769386
type: Comment
comment on: http://stackoverflow.com/a/51398607
score: 0
type: AnswerComment
has text: I used lasso to predict the probability of outcome. So i will use all coefficients to compute that probability. thanks

http://stackoverflow.com/comment/89766297
type: Comment
has text: Thanks Zak! I am able to do it now :)
type: AnswerComment
comment on: http://stackoverflow.com/a/51397593
score: 0

http://stackoverflow.com/q/51374273
answer count: 3
tagged with: windows
favorite count: 0
type: UnansweredQuestion
has body: I tried tflite_convert to convert my saved_model.pb(object detection API) file to .tflite but when i execute this command on cmd on the directory of C:\Users\LENOVO-PC\tensorflow&gt; where tensorflow git is cloned, tflite_convert \ --output_file=/saved_model/maonani.tflite \ --saved_model_dir=/saved_model/saved_model I get an error saying ImportError: No module named 'tensorflow.contrib.lite.python.tflite_convert' the complete sourcelog is C:\Users\LENOVO-PC\tensorflow&gt;tflite_convert \ --output_file=/saved_model/maonani.tflite \ --saved_model_dir=/saved_model/saved_model Traceback (most recent call last): File "c:\users\lenovo-pc\appdata\local\programs\python\python35\lib\runpy.py", line 184, in _run_module_as_main "__main__", mod_spec) File "c:\users\lenovo-pc\appdata\local\programs\python\python35\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\LENOVO-PC\AppData\Local\Programs\Python\Python35\Scripts\tflite_convert.exe\__main__.py", line 5, in &lt;module&gt; ImportError: No module named 'tensorflow.contrib.lite.python.tflite_convert' is there anyway to convert my .pb file to .tflite on WINDOWS?
upvote count: 1
tagged with: python
tagged with: object-detection
has title: ImportError: No module named 'tensorflow.contrib.lite.python.tflite_convert'
tagged with: tensorflow-lite
score: 1
has answer: http://stackoverflow.com/a/51374412
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/54742492
downvote count: 0
has answer: http://stackoverflow.com/a/53190791

http://stackoverflow.com/q/51418309
has answer: http://stackoverflow.com/a/51419733
has comment: http://stackoverflow.com/comment/90070918
upvote count: 1
score: 1
tagged with: dataframe
type: Question
answer count: 1
downvote count: 0
has title: Returning multiple values to a dataframe from a for loop
has body: import pandas as pd def makeaddr(a,b,c,d): return ipaddress.IPv4Address(bytes([a,b,c,d])) def ipaddr(): for x in range(256): a = makeaddr(x,x,x,x) a = str(a) return a data = {'Ipaddress':[ipaddr() for x in range(256)]} df = pd.DataFrame({key:pd.Series(value) for key, value in data.items() }) print(df) How can I return the ipaddress from my code from 0.0.0.0 to x.x.x.x into the dictionary so that my dataframe can print the ipaddress. I am planning to make a dataframe which will give me the output of IPAddress Domain Name Lat&amp;Long Country I would like my program to print out all the IP address from 0.0.0.0 to 255.255.255.255 but in order to do that I would need to have the ipaddr() to return multiple values is there a way to do it? I Found a solution to my problem it is given below :- import pandas as pd import ipaddress import socket import geocoder import threading import csv list1= [] list2= [] list3= [] list4= [] def makeaddr(a,b,c,d): return ipaddress.IPv4Address(bytes([a,b,c,d])) def ip(): for x in range(256): try: a = makeaddr(0,0,0,x) b = makeaddr(0,0,0,x) b = str(b) hostb = socket.gethostbyaddr(str(b)) hostname = hostb[0] g = geocoder.ip(b) g1 = g.latlng g2 = g.city list1.append(a) list2.append(hostname) list3.append(g1) list4.append(g2) except: list1.append(a) def ip1(): for x in range(256): try: a = makeaddr(0,0,x,255) b = makeaddr(0,0,x,255) b = str(b) hostb = socket.gethostbyaddr(str(b)) hostname = hostb[0] g = geocoder.ip(b) g1 = g.latlng g2 = g.city list1.append(a) list2.append(hostname) list3.append(g1) list4.append(g2) except: list1.append(a) def ip2(): for x in range(256): try: a = makeaddr(0,x,255,255) b = makeaddr(0,x,255,255) b = str(b) hostb = socket.gethostbyaddr(str(b)) hostname = hostb[0] g = geocoder.ip(b) g1 = g.latlng g2 = g.city list1.append(a) list2.append(hostname) list3.append(g1) list4.append(g2) except: list1.append(a) def ip3(): for x in range(256): try: a = makeaddr(x,255,255,255) b = makeaddr(x,255,255,255) b = str(b) c = 'Host…
tagged with: pandas
tagged with: python
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/89907038
type: AnswerComment
comment on: http://stackoverflow.com/a/51468070
score: 0
type: Comment
has text: Thank you. Especially as a beginner I appreciate any sort of tip!

http://stackoverflow.com/comment/89690090
comment on: http://stackoverflow.com/q/51358894
score: 0
has text: I tried to use list.pop command in for loop considering a as a list. But it is not giving the required result. ans np.delete is also not appropriate
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51386418
has comment: http://stackoverflow.com/comment/89745502
has comment: http://stackoverflow.com/comment/89744959
type: Question
score: 0
has title: Execute script from share directory
has body: I want to execute python script from network share (samba). Local and distant OS are on the same Debian. At the moment i have Permission denied message... And of course sudo &amp; chmod doesn't works. If possible I don't want to do a local copy of this file. The goal is execute script directly from the share directory on the local computer. Thx to all !
has comment: http://stackoverflow.com/comment/89745238
tagged with: python
tagged with: debian
has comment: http://stackoverflow.com/comment/89744806
answer count: 0
type: UnansweredQuestion
tagged with: samba

http://stackoverflow.com/q/51413906
has title: Cumulative count in a pandas df
tagged with: cumulative-sum
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51413961
accepted answer: http://stackoverflow.com/a/51413961
answer count: 1
score: 0
has body: I am trying to export a cumulative count based off two columns in a pandas df. An example is the df below. I'm trying to export a count based off Value and Count. So when the count increase I want attribute that to the adjacent value import pandas as pd d = ({ 'Value' : ['A','A','B','C','D','A','B','A'], 'Count' : [0,1,1,2,3,3,4,5], }) df = pd.DataFrame(d) I have used this: for val in ['A','B','C','D']: cond = df.Value.eq(val) &amp; df.Count.eq(int) df.loc[cond, 'Count_' + val] = cond[cond].cumsum() If I alter int to a specific number it will return the count. But I need this to read any number as the Count column keeps increasing. My intended output is: Value Count A_Count B_Count C_Count D_Count 0 A 0 0 0 0 0 1 A 1 1 0 0 0 2 B 1 1 0 0 0 3 C 2 1 0 1 0 4 D 3 1 0 1 1 5 A 3 1 0 1 1 6 B 4 1 1 1 1 7 A 5 2 1 1 1 So the count increase on the second row so 1 to Value A. Count increases again on row 4 and it's the first time for Value C so 1. Same again for rows 5 and 7. The count increases on row 8 so A becomes 2.
tagged with: pandas
tagged with: python
tagged with: count

http://stackoverflow.com/q/51346714
has answer: http://stackoverflow.com/a/51346894
answer count: 5
has title: converting numeric,string to datetime in python2.7
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51346757
type: Question
has answer: http://stackoverflow.com/a/51346856
tagged with: python-2.7
score: 0
has body: I have a datetime coming in 4 different columns ( year,month,date,time) and values are (2001,01,01,1600Z) How do I convert to datetime in python?
has answer: http://stackoverflow.com/a/51346830
has answer: http://stackoverflow.com/a/51346807

http://stackoverflow.com/a/70505980
downvote count: 0
score: 1
upvote count: 1
has body: As per the Qualys API v10.16, you can try Session Based Authentication by passing QualysSession cookies after performing login. Post login request: login_api = api_url+"/api/2.0/fo/session/" myheaders = { 'X-Requested-With': 'python'} myparams = { "action" : "login", "username" : api_username, "password" : api_password} r_login = requests.post(login_api, headers=myheaders, params=myparams) print(r_login.status_code) print(r_login.cookies.get_dict()) After getting the login ok response you can pass the cookies as dict ins subsequent get or post: mycookies = r_login.cookies.get_dict() r_new = requests.post(another_url, headers=myheaders, params=myparams, cookies=mycookies)
type: Answer
answers question: http://stackoverflow.com/q/51383793

size
tags question: http://stackoverflow.com/q/51388178
type: Tag
tag name: size

http://stackoverflow.com/comment/89930240
comment on: http://stackoverflow.com/q/51480756
has text: `replay` calls `theGame`, and `theGame` calls `replay`. But also, `replay` calls `theGame` in a while loop. I don't think you need to do both of those. What happens if you delete that last `replay()` in `theGame`'s definition?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51389783
type: UnansweredQuestion
score: 1
has body: I have a directory with many sub-directories that some of them contain html files. Every time i find an html file i want to parse the data into a pandas dataframe. The thing is, that I am getting this error "IndexError: list index out of range" My code is this: or root, subdirs, files in os.walk(walk_dir): list_file_path = os.path.join(root, 'my-directory-list.txt') with open(list_file_path, 'wb') as list_file: for subdir in subdirs: for filename in files: file_path = os.path.join(root, filename) with open(file_path, 'rb') as f: f_content = f.read() #Check if file is html check_html = bool(BeautifulSoup(f_content, "lxml").find()) #If it is HTML if check_html == True: print ("It's html") soup = BeautifulSoup(f_content, 'lxml') table = soup.find_all('table')[0] df = pd.read_html(str(table)) print(tabulate(df[0])) #If it is not HTML else: print ("its not") I know that my error is the df[0] in this line table = soup.find_all('table')[0] but I do not know how to cope with it. Also the html files I am trying to parse usually look like this(the first line) : &lt;!DOCTYPE html&gt; &lt;html class="no-js"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"&gt; &lt;title&gt; text1 &lt;/title&gt; and in some cases they also contains tables. Any help please?
upvote count: 1
type: Question
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/51389884
has title: List index out of error when parsing html with bs4 and pandas
tagged with: http://stackoverflow.com/tag/html
tagged with: python

http://stackoverflow.com/comment/89642200
has text: Thanks Mike the code works exactly as I'd like, but there's one thing I don't understand. Shouldn't the code be stuck in the `change_text()` loop and therefore be unable to execute `root.mainloop()` to create the window.
type: Comment
comment on: http://stackoverflow.com/a/51333294
score: 0
type: AnswerComment

google-oauth
type: Tag
tags question: http://stackoverflow.com/q/51414856
tags question: http://stackoverflow.com/q/51342244
tags question: http://stackoverflow.com/q/51350506
tags question: http://stackoverflow.com/q/51349752
tag name: google-oauth

http://stackoverflow.com/a/51455892
has comment: http://stackoverflow.com/comment/89881469
downvote count: 0
answers question: http://stackoverflow.com/q/51455280
type: Answer
score: 2
has body: Can also do df.groupby(df[df.complete.cumsum().duplicated(keep=False)].complete.cumsum()).num.sum() Explanation: df.complete.cumsum() gives you a Series where you will want the rows with same numbers (e.g. 1 1 1 and 2 2) summed. 0 0 1 1 2 1 3 1 4 2 5 2 6 3 7 4 Then, duplicated(keep=False) allows you to filter your df with only rows that this happen. df[df.complete.cumsum().duplicated(keep=False)] complete num 1 True 5.20 2 False 1.30 3 False 0.33 4 True 0.74 5 False 0.50 Now just use .cumsum() again and groupby with it this filtered data frame 1 1 2 1 3 1 4 2 5 2 df.groupby(...).num.sum() 1.0 6.83 2.0 1.24 Edit: c = df.complete.cumsum() d = c[c!=0].duplicated(keep=False) e = df.loc[df.index.isin(d[d].index)].complete.cumsum() df[df.index.isin(e.index)].groupby(e).num.sum() This works for every case I believe :)
upvote count: 2

http://stackoverflow.com/q/51455765
has answer: http://stackoverflow.com/a/51455934
favorite count: 0
has body: I have made a small PyQt application containing 5-6 .py files. Now I want to build and compile them into a single main file, meaning it has to operate from one main window exe. My .py files are connected with each other successfully. I have used pyinstaller to make the executable file, but the problem is I built each .py file into its own .exe file. But I want to make a single .exe file through which all the .py files can be used. How to build all .py files into a single .exe file?
answer count: 5
type: UnansweredQuestion
tagged with: pyinstaller
has title: How to build multiple .py files into a single executable file using pyinstaller?
tagged with: python
has comment: http://stackoverflow.com/comment/89881202
score: 42
has comment: http://stackoverflow.com/comment/89881009
has answer: http://stackoverflow.com/a/60952387
tagged with: pyqt5
has answer: http://stackoverflow.com/a/68895428
type: Question
upvote count: 42
has answer: http://stackoverflow.com/a/71571440
has answer: http://stackoverflow.com/a/51456120
downvote count: 0

http://stackoverflow.com/q/51354423
answer count: 2
possible better answer: http://stackoverflow.com/a/51354815
has comment: http://stackoverflow.com/comment/89681358
has answer: http://stackoverflow.com/a/51354815
tagged with: python
has comment: http://stackoverflow.com/comment/89681832
has title: Reshape numpy array in z axis
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89681357
has comment: http://stackoverflow.com/comment/89681752
accepted answer: http://stackoverflow.com/a/51355236
has comment: http://stackoverflow.com/comment/89682532
type: Question
linked to: http://stackoverflow.com/q/45973722
has answer: http://stackoverflow.com/a/51355236
has body: I have a data set like this a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] How can I reshape this into shape (3,2,2) so that a[:,0,0] = [1,2,3]?
tagged with: numpy
score: 0

http://stackoverflow.com/comment/89885548
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51457805
has text: Javascript has this feature, and confirmed through experience that it's a terrible idea. It's highly discouraged, and banned in strict mode.
score: 2

http://stackoverflow.com/a/51417546
has comment: http://stackoverflow.com/comment/89806051
accepted answer of: http://stackoverflow.com/q/51417472
answers question: http://stackoverflow.com/q/51417472
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89807006
has comment: http://stackoverflow.com/comment/89806110
type: Answer
has body: You'll just have to keep a buffer (a list) of the N last lines, then print them when you encounter a match. context_lines = [] for line in f: context_lines.append(line) if len(context_lines) &gt; 5: # Too many lines? context_lines.pop(0) # Pop the first one off. if word in line: # context_lines already includes the `line` we're looking at for ctx_line in context_lines: print(ctx_line)
has comment: http://stackoverflow.com/comment/89809562
score: 4

http://stackoverflow.com/q/51343700
answer count: 1
type: UnansweredQuestion
tagged with: pygsheets
tagged with: python
tagged with: gspread
has comment: http://stackoverflow.com/comment/89702395
has body: In pygsheets, is it possible to turn filtering on and off? I am able to get a dataframe into a sheet, but I cannot figure out how to turn on a filter without manually going to the sheet itself. My dataframe will be changing size and the default filter is not smart enough to grow with the data, thus requiring me to turn the filter off and back on again. Thanks for your help!
type: Question
tagged with: google-sheets-api
has comment: http://stackoverflow.com/comment/89704262
tagged with: google-sheets
score: 0
has title: Creating a Basic Filter
has answer: http://stackoverflow.com/a/51393264

http://stackoverflow.com/q/51469321
tagged with: python
tagged with: adjacency-matrix
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/89907530
has title: Number of columns in bi_adjacency matrix in python
score: 0
has body: I want to create a bi_adjacency matrix from a dataframe. I have written the following code: import pandas as pd from sklearn.model_selection import train_test_split import networkx as nx from operator import itemgetter from networkx.algorithms.bipartite import biadjacency_matrix # create the biadjacency matrix, creating a graph with data's edges def to_adjacency_matrix(data): g = nx.DiGraph() g.add_edges_from(data) partition_0 = set(map(itemgetter(0), data)) partition_1 = set(map(itemgetter(1), data)) return biadjacency_matrix(g, partition_0).toarray(), partition_0, partition_1 df = pd.read_csv("final.csv", sep=" ", header=1, names=["Tags", "Users"]) #train dataset 90% &amp; test dataset 10%!!! train, test = train_test_split(df, test_size=0.1) # change columns order to have users first train = train'Users', 'Tags' test = test'Users', 'Tags' data = list(zip(*[train[c].values.tolist() for c in train])) bi_adjacency, user_node, tag_node = to_adjacency_matrix(data) print(bi_adjacency.shape) print(len(user_node)) print(len(tag_node)) While my unique users are 41576 and unique tags 10000, my result is an array of shape (41576, 6879). I can't understand why the last one is different from (41576, 10000). Could someone help me somehow? Thank you for everything! Attached some lines (The first element is a tag, the second is a user): (99203 214006) (17572 4935) (45786 31658) (870 34) (37429 11146) (11215 819) (20630 119669) (12635 9361) (4059 1500) (18527 1134) (8947 324122) (6485 91299) (134203 34) (30798 67598) (75004 14112) (138671 17180) (65591 1711) (59503 17702) (11073 38071) (9454 3567) (22172 1318) (33324 17162) (127867 778) (78174 8210) (9298 68) (147376 16097) (11537 502821) (146005 7271) (1188 4080) (8741 75363) (39363 2293) (75308 13957) (2663 431) (93042 7599) (54620 33807) (112129 38447) (21496 601) (122439 874) (4038 7576) (30091 1238) (24843 250) (3502 415) (41202 2929) (18628 28876) (58895 33987) (153769 530) (23866 34810) (61654 894) (35460 3665) (747…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89918862

http://stackoverflow.com/comment/89823345
type: QuestionComment
has text: @tripleee can i use smtplib without smtp server?
comment on: http://stackoverflow.com/q/51426065
score: 0
type: Comment

http://stackoverflow.com/q/51405785
answer count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/89782946
favorite count: 0
has answer: http://stackoverflow.com/a/51406129
has answer: http://stackoverflow.com/a/51405881
tagged with: python
has title: 'Clumping' a list in python
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/51406050
type: Question
score: 3
accepted answer: http://stackoverflow.com/a/51405881
possible better answer: http://stackoverflow.com/a/51406050
has comment: http://stackoverflow.com/comment/89783013
has comment: http://stackoverflow.com/comment/89783094
has body: I've been trying to 'clump' a list I mean putting items together depending on the item inbetween, so ['d','-','g','p','q','-','a','v','i'] becomes ['d-g','p','q-a','v','i'] when 'clumped' around any '-' Here's my attempt: def clump(List): box = [] for item in List: try: if List[List.index(item) + 1] == "-": box.append("".join(List[List.index(item):List.index(item)+3])) else: box.append(item) except: pass return box However, it outputs (for the example above) ['d-g', '-', 'g', 'p', 'q-a', '-', 'a', 'v'] As I have no idea how to skip the next two items Also, the code is a complete mess, mainly due to the try and except statement (I use it, otherwise I get an IndexError, when it reaches the last item) How can it be fixed (or completely rewritten)? Thanks

http://stackoverflow.com/a/51392335
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51392013
has body: Since all you're really looking for is to change the default behavior of print so that it doesn't output a trailing newline by default, you can use functools.partial to make end='' a default parameter instead. This way, you don't need to worry about creating a new list from array_1. from functools import partial print = partial(print, end='') array_1 = ["Hello", "World", '\n', '\n', "This", "is", '\n', "a", "textarray"] for item in array_1: print(item) This outputs: HelloWorld Thisis atextarray
accepted answer of: http://stackoverflow.com/q/51392013
type: AcceptedAnswer
downvote count: 0
type: Answer

encoder-decoder
type: Tag
tags question: http://stackoverflow.com/q/51359851
tag name: encoder-decoder

http://stackoverflow.com/q/51384841
downvote count: 0
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/89741741
favorite count: 0
has body: To make my question simple I have A Form That user can upload their cv's into databse. My forms.py class resume_upload(forms.ModelForm): cv = forms.FileField(required = True) job_title = forms.CharField(required = True) def save(self, commit=False): cvs = super(resume_upload, self).save(commit=False) cvs.cv = self.cleaned_data['cv'] cvs.job_title = self.cleaned_data['job_title'] if commit: cvs.save() class Meta: model = Cv fields = ('cv', 'job_title',) My models.py class Cv(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) cv = models.FileField(upload_to='cvs', default='', validators=[validate_file_extension]) job_title = models.CharField(max_length=100, default='') def __str__(self): return self.job_title and my views.py def upload_resume(request): if request.method == 'POST': form = resume_upload(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/') else: messages.error(request,"Oops! That didn't work. Please try again") else: form = resume_upload() return render(request, 'upload_resume.html',{'form':form,}) And the problem is it redirect to home page but i cant find object in admin panel
has answer: http://stackoverflow.com/a/51384946
accepted answer: http://stackoverflow.com/a/51384946
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 1
type: Question
has comment: http://stackoverflow.com/comment/89741658
has title: Save form with user id Django
has comment: http://stackoverflow.com/comment/89741761

http://stackoverflow.com/a/51335064
has comment: http://stackoverflow.com/comment/89645301
has comment: http://stackoverflow.com/comment/89645313
has comment: http://stackoverflow.com/comment/89645346
answers question: http://stackoverflow.com/q/51335009
accepted answer of: http://stackoverflow.com/q/51335009
has body: Normally, replace operates in regex mode. You have two simple options to get around it. The preferred one, suggested by @101, is to turn off regex: df['Purpose'] = df['Purpose'].str.replace('rs.', '', regex=False) Another alternative is to escape the dot so it matches an actual period instead of any character. This is the option to use in versions of pandas before 0.23.0, when the regex parameter was introduced: df['Purpose'] = df['Purpose'].str.replace(r'rs\.', '') Regex matching is generally slower than simple string comparisons, so the first option can be expected to be more performant.
upvote count: 5
has comment: http://stackoverflow.com/comment/89645387
score: 5
has comment: http://stackoverflow.com/comment/89645399
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/89645349

http://stackoverflow.com/comment/89882852
comment on: http://stackoverflow.com/q/51455118
score: 0
has text: Thanks for that information, I've posted the explanation / fix as an answer below. Hope that's helpful!
type: Comment
type: QuestionComment

contour
tags question: http://stackoverflow.com/q/51349254
tags question: http://stackoverflow.com/q/51397212
tag name: contour
type: Tag
tags question: http://stackoverflow.com/q/51410961

http://stackoverflow.com/comment/89783903
has text: "but computing from one dataframe (keystrokes) and then populating the other (messages) seems already quite complex to do within a vectorized command" not necessarily, merge and groupby are always handy.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51406368

http://stackoverflow.com/comment/89633166
type: QuestionComment
comment on: http://stackoverflow.com/q/51328454
score: 0
has text: Do you have some other tool that needs this? Because most spreadsheet programs, Python scripts, R scripts, etc. aren’t going to recognize the format any more than Pandas is.
type: Comment

http://stackoverflow.com/q/51361250
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89699313
tagged with: postgresql
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/89696480
tagged with: psycopg2
has answer: http://stackoverflow.com/a/51366426
upvote count: 2
has body: I've gotten this error consistently while trying to insert to an array of INET type. psycopg2.DataError: invalid input syntax for type inet: "Inet('8.8.8.8')" Also for some variants I've tried: TypeError: not all arguments converted during string formatting Test table: cursor.execute( "CREATE TABLE test( ip_list inet[] );" ) Some variants I've tried to get it to work: cursor.execute( "INSERT INTO test( ip_list ) VALUES ( %s );", ( str( { "8.8.8.8" } ) ) ) cursor.execute( "INSERT INTO test( ip_list ) VALUES ( %s );", ( str( { psycopg2.extras.Inet( "8.8.8.8" ) } ) ) ) cursor.execute( "INSERT INTO test( ip_list ) VALUES ( %s );", ( psycopg2.extras.Inet( [ "8.8.8.8", "8.8.4.4" ] ) ) ) The psycopg2.extras.Inet( [ "8.8.8.8", "8.8.4.4" ] ) command generates the correct Inet object Inet(['8.8.8.8', '8.8.4.4']). However while trying to insert using that with cursor.execute( "INSERT INTO test( ip_list ) VALUES ( %s );", ( psycopg2.extras.Inet( [ "8.8.8.8", "8.8.4.4" ] ) ) ) It gives me the error: TypeError: 'Inet' object does not support indexing When I tried casting it to string before inserting via: ursor.execute( "INSERT INTO test( ip_list ) VALUES ( %s );", ( str( psycopg2.extras.Inet( [ "8.8.8.8", "8.8.4.4" ] ) ) ) ) I got the error TypeError: not all arguments converted during string formatting.
has comment: http://stackoverflow.com/comment/89695555
has title: What is the correct way to insert an Array of INET type in Postgresql using Python ( psycopg2 library )
answer count: 1
tagged with: database
accepted answer: http://stackoverflow.com/a/51366426
has comment: http://stackoverflow.com/comment/89809441
has comment: http://stackoverflow.com/comment/89695727
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89695135
score: 2
tagged with: sql

http://stackoverflow.com/comment/89685645
type: Comment
has text: there are 10k images and all images size and resolution are not same so regarding this problem i think we have to locate the center point of the image
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51356653

psse
tags question: http://stackoverflow.com/q/51480580
tag name: psse
type: Tag

http://stackoverflow.com/a/51401035
type: Answer
has body: Check if the response object contains the cookie you're looking for, namely JSESSIONID. if x.cookies.get('JSESSIONID'): print 'Login successful.'
has comment: http://stackoverflow.com/comment/89776558
answers question: http://stackoverflow.com/q/51400941
has comment: http://stackoverflow.com/comment/89774377
score: 0
has comment: http://stackoverflow.com/comment/89774161
has comment: http://stackoverflow.com/comment/89774045
has comment: http://stackoverflow.com/comment/89773990

http://stackoverflow.com/comment/89841205
type: AnswerComment
comment on: http://stackoverflow.com/a/51410872
type: Comment
has text: Hii, I update my question , according to your request. Your solution give only partial solution to my question. Thanks
score: 0

http://stackoverflow.com/q/51371024
has comment: http://stackoverflow.com/comment/89714271
type: Question
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51377379
tagged with: priority-queue
has comment: http://stackoverflow.com/comment/89714421
tagged with: python
has comment: http://stackoverflow.com/comment/89714320
favorite count: 0
has comment: http://stackoverflow.com/comment/89714659
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51377379
upvote count: 1
has body: I need "priority stack" datastructure (like priority queue, but more like LIFE like a stack) in Python 3. I know queue.PriorityQueue but found no thing like queue.PriorityStack.
has title: "Priority stack" (a hybrid of priority queue and stack) in Python 3?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89714392
score: 1
tagged with: stack

http://stackoverflow.com/a/51326703
downvote count: 0
score: 1
type: Answer
upvote count: 1
has body: Check the asmatrix method of Numpy: import numpy as np height = np.array([3,2,4,3,3.5,2,5.5,1]) width = np.array([1.5,1,1.5,1,.5,.5,1,1]) x = np.asmatrix([height, width]) x The result is matrix([[ 3. , 2. , 4. , 3. , 3.5, 2. , 5.5, 1. ], [ 1.5, 1. , 1.5, 1. , 0.5, 0.5, 1. , 1. ]])
answers question: http://stackoverflow.com/q/51326574

http://stackoverflow.com/comment/89696180
comment on: http://stackoverflow.com/q/51361990
score: 0
type: Comment
type: QuestionComment
has text: Sounds like there simply is no `entry['messaging']` …

lxml
tags question: http://stackoverflow.com/q/51354616
tags question: http://stackoverflow.com/q/51334116
type: Tag
tags question: http://stackoverflow.com/q/51436936
tags question: http://stackoverflow.com/q/51460574
tags question: http://stackoverflow.com/q/51462535
tags question: http://stackoverflow.com/q/51452779
tags question: http://stackoverflow.com/q/51437560
tags question: http://stackoverflow.com/q/51462703
tag name: lxml
tags question: http://stackoverflow.com/q/51349893
tags question: http://stackoverflow.com/q/51457418
tags question: http://stackoverflow.com/q/51354279

http://stackoverflow.com/q/51426669
favorite count: 0
has comment: http://stackoverflow.com/comment/89825401
upvote count: 2
has comment: http://stackoverflow.com/comment/89825572
has comment: http://stackoverflow.com/comment/89824690
has title: Getting the original row of a numpy 2d slice in np.nonzero
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51427422
type: Question
tagged with: numpy
score: 2
has answer: http://stackoverflow.com/a/51430821
tagged with: arrays
downvote count: 0
has body: in my program I take a 2d slice of a N*N matrix: message = np.eye(10) depth = 4 slice = message [depth:] output: [[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 1. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 1. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 1. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 1. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]] my_ones = np.nonzero(slice) output: (array([0, 1, 2, 3, 4, 5]), array([4, 5, 6, 7, 8, 9])) So, as we can see, it considers the slice to be a new array, and so the rows for the nonzero function start at 0, instead of at 4. But I want the row numbers relative to the original array, rather than just the portion I chose to examine. I could, of course, save the number of removed rows (or columns, if that is the case), and then for each row of the nonzero function I would add that number. But, that is horribly inelegant and will make my code gross if I am making lots of varying slices. Is there a way to do this where the nonzero function would realize that it's looking at a slice of a larger array and output the row relative to that context? For example, in this case, I would want the desired output of: (array([4, 5, 6, 7, 8, 9]), array([4, 5, 6, 7, 8, 9])), because those were the actual rows in the original 2d array (message). Thank you.
has comment: http://stackoverflow.com/comment/89825661
answer count: 3
possible better answer: http://stackoverflow.com/a/51427366
has answer: http://stackoverflow.com/a/51427366
tagged with: python
has answer: http://stackoverflow.com/a/51427422

http://stackoverflow.com/a/51328269
type: Answer
answers question: http://stackoverflow.com/q/51327984
upvote count: 1
downvote count: 1
score: 0
has body: You can use join to join the dataframes df1 = pd.DataFrame({'a': [2, 4], 'b': [4, 7], 'c': [6, 9]}) df2= pd.DataFrame({'d': [6, 9, 7, 5], 'e': [ 7, 5, 9, 8], 'f': [1,8,6, 2]}) df1.join(df2) a b c d e f 0 2 4 6 6 7 1 1 4 7 9 9 5 8

http://stackoverflow.com/q/51343370
favorite count: 0
has answer: http://stackoverflow.com/a/51343424
tagged with: pandas
has body: I have a dataframe with two columns of interest ['Response_hour','Incident_date'] like so: Response_hour Incident_date 08 2011-01-01 07 2011-01-01 NaN 2011-01-02 When I run df['temp'] = ddf['Incident_date'] + pd.to_timedelta(df.Response_hour, unit='h') df['temp'][0] I get: Timestamp('2011-01-01 00:00:00.000000008') Why is to_timedelta ignoring the unit that I've specified?
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/89660134
has title: pandas to_timedelta ignoring unit parameter?
score: 2
has comment: http://stackoverflow.com/comment/89660388
type: Question
type: AnsweredQuestion
tagged with: dataframe
upvote count: 2
accepted answer: http://stackoverflow.com/a/51343424
answer count: 1
downvote count: 0
tagged with: timedelta

http://stackoverflow.com/q/51353229
downvote count: 0
has title: Invoking a function by using an object?
has answer: http://stackoverflow.com/a/51353308
type: Question
tagged with: object
has body: Write a Boolean function between that takes two MyTime objects, t1 and t2, as arguments, and returns True if the invoking object falls between the two times. Assume t1 &lt;= t2, and make the test closed at the lower bound and open at the upper bound, i.e. return True if t1 &lt;= obj &lt; t2. Now from the wording of this question, it seems like there should only be two arguments in the function, but I cannot see a way to make such a function by only using two arguments. I mean I guess you could make another function that creates a variable that is a MyTime object, but I was only going to keep it to one function and not make two. The wording of the question makes it seem like you should have Object(Function(t1,t2)) but I dont think that is possible. Is it possible to make the 'between' function with only two arguments? Here is my code class MyTime: """ Create some time """ def __init__(self,hrs = 0,mins = 0,sec = 0): """Splits up whole time into only seconds""" totalsecs = hrs*3600 + mins*60 + sec self.hours = totalsecs // 3600 leftoversecs = totalsecs % 3600 self.minutes = leftoversecs // 60 self.seconds = leftoversecs % 60 def __str__(self): return '{0}:{1}: {2}'.format(self.hours,self.minutes,self.seconds) def to_seconds(self): # converts to only seconds return (self.hours * 3600) + (self.minutes * 60) + self.seconds def between(t1,t2,x): t1seconds = t1.to_seconds() t2seconds = t2.to_seconds() xseconds = x.to_seconds() if t1seconds &lt;= xseconds &lt; t2seconds: return True return False currentTime = MyTime(0,0,0) doneTime = MyTime(10,3,4) x = MyTime(2,0,0) print(between(currentTime,doneTime,x))
has comment: http://stackoverflow.com/comment/89695922
has comment: http://stackoverflow.com/comment/89679156
has comment: http://stackoverflow.com/comment/89679116
upvote count: 2
has comment: http://stackoverflow.com/comment/89679132
answer count: 2
linked to: http://stackoverflow.com/q/17134653
has comment: http://stackoverflow.com/comment/89679123
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89679025
has comment: http://stackoverflow.com/comment/89679170
possible better answer: http://stackoverflow.com/a/51353791
has answer: http://stackoverflow.com/a/51353791
tagged with: python
accepted answer: http://stackoverflow.com/a/51353308
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/89850599
has text: How many stop words do you have? Maybe compilng or applying the regex is just slow. Btw, the `\b` around the `|` should not be needed.
comment on: http://stackoverflow.com/q/51440147
type: QuestionComment
type: Comment
score: 2

http://stackoverflow.com/q/51470240
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89942514
favorite count: 0
tagged with: protocols
tagged with: python
type: AnsweredQuestion
tagged with: can-bus
accepted answer: http://stackoverflow.com/a/51486781
has comment: http://stackoverflow.com/comment/89949976
type: Question
tagged with: filtering
has comment: http://stackoverflow.com/comment/89942633
has body: Require some help with Python-can. At the moment, my code is just receiving data with a 2 second delay so the shell doesn't flood itself. How do i filter the information, just so I can use the bytes received to interpret the information? At the moment its giving me everything. import can import time bus = can.interface.Bus(bustype='nican', channel='CAN0', bitrate=1000000) recvMsg = bus.recv(timeout=None) while(recvMsg is not None): print (recvMsg.) time.sleep(2) else: print ("None")
has answer: http://stackoverflow.com/a/51486781
has title: Python-Can Bus, grab only the bytes?
score: 0
upvote count: 1

http://stackoverflow.com/q/51420406
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51425568
type: UnansweredQuestion
tagged with: apache-beam
tagged with: python
upvote count: 3
linked to: http://stackoverflow.com/q/45670930
has title: Apache Beam explaination of ParDo behaviour
type: Question
score: 3
tagged with: google-cloud-dataflow
has body: Taking an ndjson formatted text file the following code produces what I would expect. An ndjson file with the quotes.USD dict unnested and the original quotes element deleted. def unnest_quotes(element): element['USDquotes'] = element['quotes']['USD'] del element['quotes'] return element p = beam.Pipeline(options=pipeline_options) ReadJson = p | ReadFromText(known_args.input,coder=JsonCoder()) MapFormattedJson = ReadJson | 'Map Function' &gt;&gt; beam.Map(unnest_quotes) MapFormattedJson | 'Write Map Output' &gt;&gt; WriteToText(known_args.output,coder=JsonCoder()) However when I try to achieve the same thing with a ParDo I don't understand the behaviour. class UnnestQuotes(beam.DoFn): def process(self,element): element['USDquotes'] = element['quotes']['USD'] del element['quotes'] return element p = beam.Pipeline(options=pipeline_options) ReadJson = p | ReadFromText(known_args.input,coder=JsonCoder()) ClassFormattedJson = ReadJson | 'Pardo' &gt;&gt; beam.ParDo(UnnestQuotes()) ClassFormattedJson | 'Write Class Output' &gt;&gt; WriteToText(known_args.output,coder=JsonCoder()) This produces a file with each key of the dict on a separate line with no value as shown below. "last_updated" "name" "symbol" "rank" "total_supply" "max_supply" "circulating_supply" "website_slug" "id" "USDquotes" It's as if the PCollection produced by the Map function is the full dict whereas the Pardo produces a PCollection per key. I know I can just use the map function but I need to understand this behaviour for when I do need to use a ParDo in the future.
answer count: 1

http://stackoverflow.com/comment/89713823
comment on: http://stackoverflow.com/q/51370602
type: QuestionComment
has text: That's what I'm taking a look at @abarnert
score: 0
type: Comment

http://stackoverflow.com/q/51328566
has title: Transform JSON String to Dictionary using shell without escape
tagged with: python
answer count: 4
type: AnsweredQuestion
tagged with: escaping
upvote count: 0
has body: I am calling a python script from the shell, with one input argument. python main.py """{"key1":"value1", "key2":"value2"}""" All keys and values are strings. Once in python, I would like to convert the JSON string to a dictionary, so I have acess to the values by using the keys. I tried the following import json import sys dict_in = json.loads(sys.argv[1]) But dict_in would end up a string like that {key1:value1, key2:value2} So it seems like I need to find a way to pass the string with quotation marks from the shell to python. I can not use escape characters since the string is provided by a different program. Is there an elegant way to solve this?
has comment: http://stackoverflow.com/comment/89632970
possible better answer: http://stackoverflow.com/a/51328717
has answer: http://stackoverflow.com/a/51328717
type: Question
has answer: http://stackoverflow.com/a/51375633
has answer: http://stackoverflow.com/a/51328848
score: -1
downvote count: 1
tagged with: argv
tagged with: shell
has comment: http://stackoverflow.com/comment/89632855
favorite count: 0
has answer: http://stackoverflow.com/a/51328843
accepted answer: http://stackoverflow.com/a/51328843
has comment: http://stackoverflow.com/comment/89632887

http://stackoverflow.com/q/51409961
tagged with: python
has comment: http://stackoverflow.com/comment/89791462
answer count: 0
has comment: http://stackoverflow.com/comment/89791365
type: Question
score: 0
has body: I've constructed a data frame from some signal data. I'd like to perform a DFT on one column of the data frame (using numpy.fft.fft) and then have the output be a data frame of the same structure, but with the correct column reflecting the application of the function. The original data frame is lead_pts_df: import pandas as pd import numpy as np ...(some setup code omitted) # apply a discrete fast Fourier transform to each data series in the data frame lead_pts_fft_df = lead_pts_df.magnitude.apply(np.fft.fft) The original data frame looks like this, with both of my columns intact: The output data frame post-.apply(np.fft.fft) is: How can I get a data frame with the original structure intact, but with the DFT function applied to the magnitude column?
tagged with: pandas
has title: Python, pandas: Applying Function to Dataframe in Place
type: UnansweredQuestion

http://stackoverflow.com/q/51326147
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/55168094
has body: I am trying to do a distributed task-queue Django-project with Dramatiq as the worker-library. I'm able to run the project without errors when doing it from the dev-environment, but getting cryptic FileNotFoundError when trying to run the built docker-container. I've run out ideas on why this happens. The traceback of the error is: Traceback (most recent call last): File "manage.py", line 15, in &lt;module&gt; execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.5/dist-packages/django_dramatiq/management/commands/rundramatiq.py", line 83, in handle os.execvp(executable_path, process_args) File "/usr/lib/python3.5/os.py", line 615, in execvp _execvpe(file, args) File "/usr/lib/python3.5/os.py", line 660, in _execvpe raise last_exc.with_traceback(tb) File "/usr/lib/python3.5/os.py", line 650, in _execvpe exec_func(fullname, *argrest) FileNotFoundError: [Errno 2] No such file or directory I've made a skeleton Django-project with a single Dramatiq-task to reproduce the problem. The repository can be cloned from here: https://bitbucket.org/AvareaToniN/dramatiqexample/src/master/ and here are the relevant parts from that repository: dramatiqexample │ .gitignore │ circus.ini │ Dockerfile │ entrypoint.sh │ manage.py │ requirements.txt │ ├───dramatiqexample │ settings.py │ urls.py │ wsgi.py │ __init__.py │ └───exampleapp │ admin.py │ apps.py │ models.py │ tasks.py │ tests.py │ views.py │ __init__.p…
favorite count: 0
upvote count: 2
tagged with: django
has title: Why does Dramatiq fail to start in Docker-container?
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: circusd
has answer: http://stackoverflow.com/a/55168094
type: Question
linked to: http://stackoverflow.com/q/9259844
tagged with: docker

http://stackoverflow.com/comment/89829285
comment on: http://stackoverflow.com/q/51429088
score: 0
has text: Perhaps this is useful: https://stackoverflow.com/questions/49734233/reading-in-a-binary-jpeg-header-in-python
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51341959
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89657487
score: 1
possible better answer: http://stackoverflow.com/a/51346096
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89657401
answer count: 2
has comment: http://stackoverflow.com/comment/89657390
downvote count: 0
has body: I'm trying to make a visual representation of the first million digits of pi inside a circle. Like in the coding train channel, but with Python. (https://www.youtube.com/watch?v=WEd_UIKG-uc&amp;index=137&amp;list=PLRqwX-V7Uu6ZiZxtDDRCi6uhfTH4FilpH) It should be looking like this: but it looks like this: First off all I imported math and tkinter class, I read the document and make the canvas. I think there's no problem in here: from math import * from tkinter import * openpi = open (r'PI_numbers.txt', 'r') pi = openpi.read() win= Tk() win = Canvas(win, width=500, height=500) win.configure(background=('black')) win.create_oval(0,0,500,500, fill='white') Next, as I didn't know how to make a switch case, I searched and found something. def zero(sx,sy): angle=36*0 x= 250* (1 + cos(angle)) y= 250* (1 + sin(angle)) win.create_line(sx,sy, x, y) sx=x sy=y def one(sx,sy): angle=36*1 x = 250 * (1 + cos(angle)) y = 250 * (1 + sin(angle)) win.create_line(sx, sy, x, y) sx = x sy = y def two(sx,sy): angle=36*2 x = 250 * (1 + cos(angle)) y = 250 * (1 + sin(angle)) win.create_line(sx, sy, x, y) sx = x sy = y And like this to nine. And then: y=250 x=250 options = { '0': zero(sx=x, sy= y), '1': one(sx=x, sy= y), '2': two(sx=x, sy= y), '3': three(sx=x, sy= y), '4': four(sx=x, sy= y), '5': five(sx=x, sy= y), '6': six(sx=x, sy= y), '7': seven(sx=x, sy= y), '8': eight(sx=x, sy= y), '9': nine(sx=x, sy= y), ".": point() } i=0 while len(pi)&gt; i: n = pi[i] options [n] i += 1 win.pack() win.mainloop() So, in here I'm trying to make a line from the last number to the new one. I start at 250 250, the center of the circumference. The problem I detect is not just the x and y are wrong but the fact that it's starting always from the center and i don't know why. And in line of options [n] I get this : statement seems to have no effect.
favorite count: 0
tagged with: python-3.x
has title: Making a visual representation of pi digits in Python
has answer: http://stackoverflow.com/a/51343072
has comment: http://stackoverflow.com/comment/89658120
has comment: http://stackoverflow.com/comment/89657346
has answer: http://stackoverflow.com/a/51346096
tagged with: python
linked to: http://stackoverflow.com/q/9004789
accepted answer: http://stackoverflow.com/a/51343072

http://stackoverflow.com/q/51449769
has title: How to insert a attribute into a doc just if it does not exist?
score: 0
answer count: 1
tagged with: elasticsearch
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51453606
type: Question
has answer: http://stackoverflow.com/a/51453606
has body: I'm trying to insert a attribute into a doc called 'users' using bulk on python. Like this: actions = [ { '_op_type': 'update', "_index": index, "_type": "users", "_id": s['id_user'], "doc": { "purchases": [] }, } for i, s in users.iterrows() ] success, failure = self.db.bulk(actions, stats_only=True) How can I add purchases just if it does not exist? I do not want a upsert in this case. It's forbidden to change the value if it has already been indexed.

http://stackoverflow.com/a/51426394
has comment: http://stackoverflow.com/comment/89823968
has body: Probably the best answer is storing those values as the string "nan" in your db, which float parses just fine. Afterwards you can use for example np.isnan to get those values that are not defined. As an alternative, leave them at zero: for i in range(0, len(ans)): try: x[i] = float(ans[i][1]) except ValueError: pass try: y[i] = float(ans[i][2]) except ValueError: pass Or, leave them out entirely: xy = np.array([tuple(map(float, values[1:])) for values in ans if values[2]]) x = xy[:, 0] y = xy[:, 1]
score: 0
has comment: http://stackoverflow.com/comment/89824396
has comment: http://stackoverflow.com/comment/89824443
has comment: http://stackoverflow.com/comment/89824136
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89824066
has comment: http://stackoverflow.com/comment/89824520
type: Answer
has comment: http://stackoverflow.com/comment/89824686
accepted answer of: http://stackoverflow.com/q/51426289
answers question: http://stackoverflow.com/q/51426289
has comment: http://stackoverflow.com/comment/89823981
has comment: http://stackoverflow.com/comment/89824337

http://stackoverflow.com/q/51467460
tagged with: eventlet
type: UnansweredQuestion
tagged with: python
has body: My code (Python 3.5 on Raspbian 9 - Stretch) is divided up into a number of separate processes, which are run from main.py. A simplified example of my code is below, which I believe is plain vanilla use of Flask, socketIO, eventlet with multiprocessing.Process. The problem is it hangs when I try to access the pipe that connects the different processes. My understanding (which wouldn’t surprise me if I was completely wrong) is that this is a long standing issue related to eventlet and multiprocessing.Process and as of January 2018 has not been resolved. How to combine multiprocessing and eventlet https://github.com/eventlet/eventlet/issues/147 My question is this. This seems like a common use case, but doesn’t work. So, what work around or different approach would you recommend? --- in webprocess.py --- #!/usr/bin/python3 def WebFunc(outfrompipe, intopipe): global thread app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app, async_mode=”eventlet”) thread = None thread_lock = Lock() @app.route('/') def index(): return render_template('index.html', async_mode=socketio.async_mode) @socketio.on('my_event', namespace='/test') def test_msg(msg): # Receive a message from a web app print(“Received message”, msg) # Send this message to another process # THIS IS WHERE IT HANGS!! intopipe.send(msg) socketio.run(app, debug=False, host='0.0.0.0') --- in main.py --- #!/usr/bin/python3 import webprocess as webproc import multiprocessing import time if __name__ == '__main__': multiprocessing.set_start_method('spawn') outfrompipe, intopipe = multiprocessing.Pipe() wf = multiprocessing.Process(name=”WebProc”, target=webproc.WebFunc, args=(outfrompipe, intopipe)) wf.start() while True: message = outfrompipe.recv() print(message) time.sleep(1) wf.join()
answer count: 0
linked to: http://stackoverflow.com/q/48218396
has comment: http://stackoverflow.com/comment/89988851
type: Question
tagged with: flask-socketio
has comment: http://stackoverflow.com/comment/89988865
tagged with: python-multiprocessing
has comment: http://stackoverflow.com/comment/89936789
score: 0
has comment: http://stackoverflow.com/comment/89935687
has title: Flask-SocketIO, eventlet, multiprocessing.Process not compatible

http://stackoverflow.com/comment/89845702
has text: I wouldn't say it's not elegant, it's wrong: imagine that your method takes 0.1 seconds and you want to have it run 10 times a second, then it will just run 5 times, which is wrong. In other programming languages, there are `Timer` classes, which give the opportunity to launch a method every time a certain time limit is reached. I'll advise you to follow such an approach.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51437139

http://stackoverflow.com/comment/89712151
has text: hard for me to tell without seeing your input tbh
type: AnswerComment
comment on: http://stackoverflow.com/a/51369886
type: Comment
score: 0

http://stackoverflow.com/a/51388271
type: Answer
has body: There's two issues here. By taking .values you actually access the underlying numpy array; you no longer have a pandas.Series. numpy arrays do not have an apply method. You are trying to use apply for a simple multiplication, which will be orders of magnitude slower than using a vectorized approach. See below: import pandas as pd import numpy as np df = pd.DataFrame({'a': np.arange(1000, dtype=np.float64)}) print(type(df['a'])) # Gives pandas.core.series.Series print(type(df['a'].values)) # Gives numpy.ndarray # The vectorized approach df['a'] = df['a'] * 1.3
upvote count: 2
score: 1
downvote count: 1
answers question: http://stackoverflow.com/q/51388050

http://stackoverflow.com/comment/89821460
has text: Maybe it can help you: https://stackoverflow.com/questions/43356982/docker-python-set-utf-8-locale
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51425082
type: AnswerComment

google-drive-api
tags question: http://stackoverflow.com/q/51411985
tags question: http://stackoverflow.com/q/51468295
tags question: http://stackoverflow.com/q/51439810
type: Tag
tags question: http://stackoverflow.com/q/51338159
tags question: http://stackoverflow.com/q/51414856
tag name: google-drive-api
tags question: http://stackoverflow.com/q/51423482
tags question: http://stackoverflow.com/q/51329367

http://stackoverflow.com/q/51346102
has comment: http://stackoverflow.com/comment/89665456
tagged with: python
has comment: http://stackoverflow.com/comment/89665644
type: AnsweredQuestion
tagged with: tkinter
has title: How to add scrollbars to this listbox
has comment: http://stackoverflow.com/comment/89665420
score: 1
accepted answer: http://stackoverflow.com/a/51346679
linked to: http://stackoverflow.com/q/47368559
upvote count: 1
type: Question
tagged with: python-3.6
has body: Python V3.6, Windows 7, beginner 1 month. I'm trying to work out how to add scrollbars to a listbox, using tkinter. can anyone tell me what I'm doing wrong please? I have already tried to implement a similar answer from here:How to attach my scrollbar to my listbox widget but I can't get that to work either. #listbox window edit_space = Listbox( master = top, selectmode = 'single', width = 53, height = 10, fg="blue") edit_space.place(x=10, y=130) edit_space.bind('&lt;Double-1&gt;', onselect) # add scrollbar to listbox #not working scrollbar = Scrollbar(edit_space) edit_space.config(yscrollcommand=scrollbar.set) scrollbar.config(command=edit_space.yview)
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89665426
has answer: http://stackoverflow.com/a/51346679
favorite count: 0
has comment: http://stackoverflow.com/comment/89665445

glyph
type: Tag
tag name: glyph
tags question: http://stackoverflow.com/q/51361152

http://stackoverflow.com/comment/89646094
has text: @smac89 `reverse_1` is worse: it's `O(n*n)`. Try that on a really large string, it never ends because it has to copy the string. So basically `n*(n-1)//2` copies
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51335422
score: 0

http://stackoverflow.com/a/51473577
type: Answer
has comment: http://stackoverflow.com/comment/89960755
has comment: http://stackoverflow.com/comment/89960512
score: 0
answers question: http://stackoverflow.com/q/51467350
has comment: http://stackoverflow.com/comment/89933825
has body: There are 2 solutions for you: Build only 1 tree (meaning use only 1 iteration), that means that when you train use num_boost_round=1 When you predict use ntree_limit=1 Either one will solve your problem. You either train only 1 tree or you predict using only 1 tree.

http://stackoverflow.com/comment/89909105
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51470387
has text: That was it. Thanks for the quick solution.

http://stackoverflow.com/q/51324884
score: 1
has title: Writing a function that parses a nested json file in python
possible better answer: http://stackoverflow.com/a/51325484
linked to: http://stackoverflow.com/q/2835559
has comment: http://stackoverflow.com/comment/89624962
accepted answer: http://stackoverflow.com/a/51325026
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/89624808
has comment: http://stackoverflow.com/comment/89624768
has comment: http://stackoverflow.com/comment/89626631
upvote count: 1
has comment: http://stackoverflow.com/comment/89624836
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89625064
has body: I have a json file that looks something like this: { "mAutomaticTestCompleted": true, "mAutomaticTestList": [ { "mName": "acceleratorEntity", "mTestStatus": true, "mX": 3.8043518, "mY": 8.114105, "mZ": -3.3895721 }, { "mName": "barometerEntity", "mTestStatus": false, "mValue": 0 }] } There are actually lots of fields like mAutomaticTestlist, all of them are lists of objects that look just like that. I need to write a function that takes device_name and JSON itself as its arguments and returns the value of the mTestStatus field. Here's my attempt: def hasPassed(device_name, data): if isinstance(data, dict): for key, value in data.items(): if not isinstance(value, dict) and not isinstance(value, list): if key == 'mName' and value == device_name: return data['mTestStatus'] else: return hasPassed(device_name, value) elif isinstance(data, list): for element in data: return hasPassed(device_name, element) The problem with this function is that it doesn't go over the whole JSON object. EDIT: So I would like my function to work this way: hasPassed('barometerEntity', json_obj) would return False cos that's the value of the 'mTestStatus' corresponding the device_name (which is barometerEntity in this case).
has answer: http://stackoverflow.com/a/51325026
answer count: 2
has answer: http://stackoverflow.com/a/51325484
downvote count: 0

http://stackoverflow.com/comment/92098567
type: QuestionComment
comment on: http://stackoverflow.com/q/51424575
has text: @TayyabGulsherVohra Have you solved this ? And if you did, can you answer your question for others ? It would be helpful.
score: 0
type: Comment

http://stackoverflow.com/comment/89666420
has text: Yes. When all required actions on new page are done use `driver.close()` to close new window and `driver.switch_to.default_content()` to get back to main screen
comment on: http://stackoverflow.com/a/51346550
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/q/51425190
type: Question
has answer: http://stackoverflow.com/a/51428626
answer count: 2
has answer: http://stackoverflow.com/a/55617288
downvote count: 0
has comment: http://stackoverflow.com/comment/89824929
favorite count: 0
tagged with: python
tagged with: pygame
has title: How to play music in python using pygame?
tagged with: pycharm
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/89829514
linked to: http://stackoverflow.com/q/7746263
score: 1
has body: import pygame pygame.mixer.init() pygame.mixer.music.load(file)#any mp3 file pygame.mixer.music.play() while pygame.mixer.music.get_busy(): pygame.time.Clock().tick() I know this is the code to play the music in python with pygame Can you explain why we use while pygame.mixer.music.get_busy(): pygame.time.Clock().tick()

http://stackoverflow.com/comment/89753015
has text: Great! Thank you!
comment on: http://stackoverflow.com/a/51390120
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89927526
type: Comment
comment on: http://stackoverflow.com/q/51479328
type: QuestionComment
has text: I know that but i want to extract live data for the table in that case the download csv option is useless as it gives u historical data
score: 0

http://stackoverflow.com/comment/98370630
score: 0
comment on: http://stackoverflow.com/q/51325438
type: Comment
has text: Possible duplicate of [Django admin: ManyToManyField in list\_editable?](https://stackoverflow.com/questions/15655587/django-admin-manytomanyfield-in-list-editable)
type: QuestionComment

http://stackoverflow.com/comment/89762450
has text: I think need to use pillow as PIL is no longer used in python3
score: 0
comment on: http://stackoverflow.com/q/51394993
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89910450
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51462467
has text: @pkqxdd its not redundant. Since we are concatenating lists in the return, not having the else clause will return "NoneType" instead, and according to python; "can only concatenate list (not "NoneType") to list"
score: 0

http://stackoverflow.com/a/78344600
has body: def squirrel_play(temp, is_summer): return (temp&gt;=60 and temp&lt;=90) or (temp&gt;=90 and temp&lt;=100 and is_summer)
type: Answer
score: 0
answers question: http://stackoverflow.com/q/51458881

http://stackoverflow.com/a/51479588
type: Answer
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/51423379
score: 4
accepted answer of: http://stackoverflow.com/q/51423379
has body: Ok so apparently there is a problem with the current version of docker-compose for macOS... It's just my guess, but anyhow here is how I solved it curl -L https://github.com/docker/compose/releases/download/1.14.0-rc2/docker-compose-`uname -s`-`uname -m` &gt; /usr/local/bin/docker-compose chmod +x /usr/local/bin/docker-compose Then restarted the terminal
type: AcceptedAnswer

http://stackoverflow.com/comment/89812641
has text: What you meant by * this does not work.* ? Does it rais any error?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51413401
score: 0

http://stackoverflow.com/a/51850219
has body: (1) Yes (2) Yes, just slice a tensor using the loop index (3) No need to set backprop=False in ordinary use-cases (4) The usual things you do with ML models (toy datasets, test parts separately, etc) Re update 2, try using eager execution or tf.contrib.autograph; both should let you write the while loop in plain python.
score: 0
answers question: http://stackoverflow.com/q/51466554
type: Answer

http://stackoverflow.com/q/51452668
has comment: http://stackoverflow.com/comment/89875610
score: 1
has answer: http://stackoverflow.com/a/56101352
upvote count: 1
answer count: 1
downvote count: 0
has title: Widgets not displaying with macOS vibrancy (NSVisualEffectView)
tagged with: appkit
has comment: http://stackoverflow.com/comment/89876868
favorite count: 0
tagged with: pyobjc
tagged with: python
has body: I have currently got a PyQt5 application which is quite simple (just one button). I'd like for it to have vibrancy, so I've ported ObjC vibrancy code to Python. My vibrancy code is as follows: frame = NSMakeRect(0, 0, * self.get_screen_size()) # get_screen_size returns the resolution of the monitor view = objc.objc_object(c_void_p=self.winId().__int__()) # returns NSView of current window visualEffectView = NSVisualEffectView.new() visualEffectView.setAutoresizingMask_(NSViewWidthSizable|NSViewHeightSizable) # equivalent to: visualEffectView.autoresizingMask = NSViewW... visualEffectView.setFrame_(frame) visualEffectView.setState_(NSVisualEffectStateActive) visualEffectView.setMaterial_(NSVisualEffectMaterialDark) visualEffectView.setBlendingMode_(NSVisualEffectBlendingModeBehindWindow) window = view.window() window.contentView().addSubview_positioned_relativeTo_(visualEffectView, NSWindowBelow, None) # equal to: [window.contentView addSubview:visualEffectView positioned:NSWindowBelow relativeTo:nul] window.setTitlebarAppearsTransparent_(True) window.setStyleMask_(window.styleMask() | NSFullSizeContentViewWindowMask) # so the title bar is also vibrant self.repaint() All I'm doing to draw a button is: btn = QPushButton("test", self) self is a class inherited from QMainWindow and everything else should be fairly unimportant. Behaviour with the window.contentView().addSubview... line commented out (no vibrancy) Behaviour without it commented out (with vibrancy) Thanks!
tagged with: python-3.x
type: UnansweredQuestion
tagged with: pyqt5
type: Question

http://stackoverflow.com/a/51463824
answers question: http://stackoverflow.com/q/51462317
type: Answer
score: 2
upvote count: 2
has body: The problem was solved by : class MyAdminPasswordChangeForm(AdminPasswordChangeForm): def save(self, commit=True): """ Saves the new password. """ password = self.cleaned_data["password1"] self.user.myuser.set_password(password) if commit: self.user.myuser.save() return self.user.myuser and class ProfileAdmin(UserAdmin): change_password_form = MyAdminPasswordChangeForm
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51462317

http://stackoverflow.com/a/51413267
has comment: http://stackoverflow.com/comment/89798057
has comment: http://stackoverflow.com/comment/89798071
has body: np.arange needs both a start and a stop. If you provide only one parameter it will be interpreted as stop and start will default to 0. That's what's happening here. The possible usages are: np.arange(stop) # assumes start=0, step=1 np.arange(start, stop) # assumes step=1 np.arange(start, stop, step) np.arange(start) would make no sense since there is no "meaningful default" number to stop...
has comment: http://stackoverflow.com/comment/89798100
score: 0
has comment: http://stackoverflow.com/comment/89798150
answers question: http://stackoverflow.com/q/51413245
type: Answer

http://stackoverflow.com/comment/89717182
type: QuestionComment
type: Comment
has text: Your line `if print_median(sep) = None` seems to have two problems: `sep` isn't defined, but even if it is, you can't use variable assignment in an `if` statement. Instead, use `==` for equality, or `is None` if you want to be fancy.
comment on: http://stackoverflow.com/q/51371470
score: 0

http://stackoverflow.com/comment/89711869
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51369153
has text: just tried, command not found, also I don't remember installing apache
score: 0

http://stackoverflow.com/comment/89683279
comment on: http://stackoverflow.com/a/51355504
type: Comment
has text: How can I use `select_related` in my queryset?
score: 0
type: AnswerComment

http://stackoverflow.com/q/51326546
tagged with: python
duplicate of: http://stackoverflow.com/q/18206630
answer count: 0
has title: Python Flask return redirect with parameters without displaying parameters in url
type: UnansweredQuestion
upvote count: 7
score: 7
duplicate of: http://stackoverflow.com/q/17057191
type: Question
has body: I have a simple python flask app. When one of my users comments on my home page, I want to redirect them right back to the home page. Currently, I have the same route that handles the home page and commenting. It looks like this: @app.route('/home', methods=['POST', 'GET']) @login_required def home(): form = CommentForm() user = User.query.filter_by(username=current_user.username).first() house = House.query.filter_by(owner_id = current_user.id).first() neighbors = Neighbors.query.filter_by(houseid=house.id).all() if user.id == current_user.id: if form.validate_on_submit(): time = strftime("%a, %b %d %Y %X", localtime()) comment = Commentsection(houseid = house.id, commentbody = form.body.data, times = str(time), commenter=user.username, commenterid=user.id, commenterpic = user.image_file ) db.session.add(comment) db.session.commit() link = url_for('add', invite_token=house.linkinv, _external=True) comments = Commentsection.query.filter_by(houseid=house.id).order_by(Commentsection.id.desc()).all() return redirect(url_for('home', title='Home', house=house, form=form, comments=comments, link=link, neighbors=neighbors)) else: link = url_for('add', invite_token=house.linkinv, _external=True) comments = Commentsection.query.filter_by(houseid=house.id).order_by(Commentsection.id.desc()).all() return render_template('home.html', tite='Home', house=house, form=form, comments=comments, link=link, neighbors=neighbors) When the user submits the comment, the code is ran and the form is validated. When the form is validated, it creates the comment model and commits it to the database. After, it redirects the user to that same page, to avoid the annoying "Would you like to submit this form again" popup in chrome. If I did not redirect, the form would continue to submit every time I reload the page. The problem is, when I redirect, the url_for thinks I am passing in url arguments instead of variables, and places them right into the url, resulting in something like this: http://127…
downvote count: 0
tagged with: flask
favorite count: 0
linked to: http://stackoverflow.com/q/18206630

http://stackoverflow.com/a/51347762
has body: have you added your app name inside settings.py make sure you have added the name in settings.py which resides under project folder in your case it will be here: Directory of C:\Users\ad\Documents\projects\mysite\msenv\mysite\mysite like this: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app_name',] # &lt;--- polls in your case make sure you are using your routes you have defined to access the correct page for example in your case: your website's routes are: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] and your application 'polls' routes are: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] according to your views.py file which is this: from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") you must visit http://localhost:{port number}/polls/ or http://127.0.0.1:{port number}/polls/ default port number is 8000 after running server using python manage.py runserver to get your page as an output on browser
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51347587
answers question: http://stackoverflow.com/q/51347587
has comment: http://stackoverflow.com/comment/89684941
score: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51372534
answer count: 1
tagged with: scikit-learn
favorite count: 0
type: UnansweredQuestion
has title: Sklearn Classifier
tagged with: python
has answer: http://stackoverflow.com/a/51372615
downvote count: 1
type: Question
score: -1
has body: I started on my journey on machine learning a few months back, Today I was practicing my skills and I tried I few different Algorithms, I used Linear Regression, Decision Tree Classifier and Support Vector Machine, My code is very simple and it's working just fine (" I guess " ), But since I'm new pardon me if this a silly question, But using the Linear Regression and Decision Tree Classifier give me an accuracy from 1.04 to 1.22, But if I use SVM it give me 0.72, So I'm confuse since I read that SVM is better than Linear Regression in speed and performance, So can you guys please help me clarify this. :) Thanks in Advance :) THIS IS MY CODE: import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import accuracy_score from sklearn.tree import DecisionTreeClassifier dataset = pd.read_csv("/home/jairo/Downloads/diabetes.csv") dataset.shape x = dataset.drop(['Outcome'], axis=1) y = dataset['Outcome'] x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2) classifier = DecisionTreeClassifier() classifier.fit(x_train, y_train) predic = classifier.predict(x_test) score = accuracy_score(y_test, predic.round(), normalize=False) print("Accuracy : {}".format(score/100)) THIS IS THE LAST OUTPUT THAT I GOT: Accuracy : 1.15
upvote count: 0

http://stackoverflow.com/a/51348090
downvote count: 0
has comment: http://stackoverflow.com/comment/89669469
type: Answer
has body: Try to implement below solution: def get_information(driver,url): driver.get(url) current = driver.current_window_handle wait.until(EC.element_to_be_clickable((By.ID, "btnButton"))).click() for keyword in ['HMC DESIGN GROUP','HMC DESIGN GROUP']: input_field = wait.until(EC.presence_of_element_located((By.ID,"SearchOnName"))) input_field.clear() input_field.send_keys(keyword) wait.until(EC.presence_of_element_located((By.ID, "btnSearch"))).click() wait.until_not(EC.visibility_of_element_located((By.ID, "SearchingWaitImg"))) wait.until(EC.element_to_be_clickable((By.XPATH, "//td[contains(., '%s')]" % keyword))).click() driver.switch_to.window([window for window in driver.window_handles if window != current][0]) for items in wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,".listDocDetails"))): print(items.text) driver.close() driver.switch_to.window(current)
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89668863
accepted answer of: http://stackoverflow.com/q/51347987
answers question: http://stackoverflow.com/q/51347987
type: AcceptedAnswer

http://stackoverflow.com/comment/89695851
type: AnswerComment
type: Comment
has text: with the last one you do all that is in the first?
comment on: http://stackoverflow.com/a/51361706
score: 0

http://stackoverflow.com/a/52061937
downvote count: 0
type: Answer
has body: exception_view_config was added in Pyramid 1.8
answers question: http://stackoverflow.com/q/51453768
upvote count: 1
score: 1

http://stackoverflow.com/a/51356033
has comment: http://stackoverflow.com/comment/89696084
type: Answer
has comment: http://stackoverflow.com/comment/89695434
has comment: http://stackoverflow.com/comment/114875825
has comment: http://stackoverflow.com/comment/89695928
has comment: http://stackoverflow.com/comment/89696742
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51349752
has comment: http://stackoverflow.com/comment/89696376
has body: First off you should only need https://www.googleapis.com/auth/drive as it gives full access to a users drive account including reading and writing sheets. list of Sheet scopes list of drive scopes If you have already run your code once and authenticated your user then changed the scopes in your code. Remember that you will need to run your code again and re-authenticate the user to gain the access granted by the new scopes. Side note: SCOPES = 'https://www.googleapis.com/auth/spreadsheets'+"https://www.googleapis.com/auth/drive.file"+"https://www.googleapis.com/auth/drive" Is just going to be one long string you need to separate them with a space or as the other answer states use an array. SCOPES = 'https://www.googleapis.com/auth/spreadsheets ' + "https://www.googleapis.com/auth/drive.file " + "https://www.googleapis.com/auth/drive"
downvote count: 0

http://stackoverflow.com/comment/89867595
has text: If you run `type(player)` it should return that it is an instance of some object, I'm guessing. see my edit above.
score: 1
comment on: http://stackoverflow.com/a/51446446
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51444782
has comment: http://stackoverflow.com/comment/89860935
favorite count: 0
type: UnansweredQuestion
downvote count: 2
tagged with: python
tagged with: sha256
has answer: http://stackoverflow.com/a/51444936
score: 1
upvote count: 3
has body: I would appreciate your help to understand why my SHA256 encryption function in JAVA and in PYTHON does not produce the result (difference in 1 digit, one more in python): hash to encrypt is: "thisisatest" Java results is: a7c96262c21db9a06fd49e307d694fd95f624569f9b35bb3ffacd88044f9787 Python result is: a7c96262c21db9a06fd49e307d694fd95f624569f9b35bb3ffacd880440f9787 Python code: import hashlib def encrypt_string(hash_string): sha_signature = \ hashlib.sha256(hash_string.encode()).hexdigest() return sha_signature hash_string = "thisisatest" print(encrypt_string(hash_string), end="") Java code: import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class OpenAPIPasswordEncryptor1 { private static MessageDigest sha256; // generated password is stored encrypted (using also user name for hashing) public synchronized static String encrypt(String hash) { try { StringBuilder builder = new StringBuilder(); builder.append(hash); // first time , encrypt user name , password and static key String encryptedCredentials = encryptionIterator(builder.toString()); return encryptedCredentials; } catch (Exception e) { e.printStackTrace(); } return ""; } private static String encryptionIterator(String content) { try { sha256 = MessageDigest.getInstance("SHA-256"); // append the static key to each iteration byte[] passBytes = (content).getBytes(); sha256.reset(); byte[] digested = sha256.digest(passBytes); StringBuffer sb = new StringBuffer(); for (int i = 0; i &lt; digested.length; i++) { sb.append(Integer.toHexString(0xff &amp; digested[i])); } return sb.toString(); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return ""; } // generate password for developers public static void main(String[] args) { String hash = "thisisatest"; String encrypt = encrypt(hash); System.out.println("Your Password Is '" + encrypt + "'"); } }
tagged with: java
has comment: http://stackoverflow.com/comment/89859976
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/89859760
has title: SHA256 encryption in JAVA and PYTHON produce different results
has comment: http://stackoverflow.com/comment/89860129

http://stackoverflow.com/q/51480219
tagged with: pandas
has comment: http://stackoverflow.com/comment/89929588
tagged with: python
has comment: http://stackoverflow.com/comment/89929467
type: UnansweredQuestion
upvote count: 1
type: Question
has title: Pandas str.extract/ re.search using another series or column as a pattern
has comment: http://stackoverflow.com/comment/89929341
has comment: http://stackoverflow.com/comment/89929904
score: 1
has body: df = pd.DataFrame({'a':{0:'aa',1:'dd',2:'cc'}, 'b':{0:'aa(bb)daa',1:'eedd(ed)',2:'affaa(f)'}}) a b 0 aa aa(bb)daa 1 dd eedd(ed) 2 cc affaa(f) I want to extract the characters inside the parenthesis as long as the pattern before the parenthesis is the value in df['a']. I have tried using: def searcher(x): pat_result = re.search(x[0] + '\((.*?)\)', x[1]) if pat_result: return pat_result.group(1) df'a','b'.apply(lambda x :searcher(x), axis=1) 0 bb 1 ed 2 None dtype: object %%timeit df'a','b'.apply(lambda x :searcher(x), axis=1) 1.33 ms ± 3.49 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) I'm just wondering if there is a faster way (but still in pandas) or use str.extract directly? Is there way to make this work? df['b'].str.extract(df['a'] + '\((.*?)\)', expand=False)
has answer: http://stackoverflow.com/a/51480932
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89929747
favorite count: 0
has comment: http://stackoverflow.com/comment/89929642

http://stackoverflow.com/q/51345565
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51345641
downvote count: 0
has title: How do you read that a user has stopped inputting?
score: 1
type: Question
has body: If you're asking the user to input a sequence of numbers what's the best way in Python to stop waiting for input from the user once they have finished inputting? For example, in one case a user inputs '1, 44, 100', another case they input '88 22 6 2'. What's the best way to get the input but not have your program get stuck waiting for more input, or for a specific number to trigger the loop 'break'? a = int(input()) while a !="": list.append(a) a = int(input()) I hope you can see my very novice logic behind how to do, but not sure on the best way to actually make it work?
has answer: http://stackoverflow.com/a/51345640
answer count: 3
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51345609

http://stackoverflow.com/q/51363162
downvote count: 1
type: Question
has title: How to skip file that doesn't have required keyword in it's header?
has comment: http://stackoverflow.com/comment/89698660
answer count: 2
has comment: http://stackoverflow.com/comment/89698586
has answer: http://stackoverflow.com/a/51363368
favorite count: 0
has comment: http://stackoverflow.com/comment/89698524
possible better answer: http://stackoverflow.com/a/51363358
has answer: http://stackoverflow.com/a/51363358
has comment: http://stackoverflow.com/comment/89698517
tagged with: python
has comment: http://stackoverflow.com/comment/89698690
has body: I have several hundred files and most of them have the keyword 'HIERARCH ESO DRS BLAZE FILE', in their header but there are some files that doesn't have that keyword and because of that it gives error. So i want to skip the files that doesn't have the required keyword in it's header. from astropy.io import fits import numpy as np import sys, os for filename in os.listdir("/home/gyanender/bin/all_spectra/Moon_bundleII"): if filename.endswith("e2ds_A.fits"): with fits.open(filename) as hdul: e2ds_header = hdul[0].header if 'HIERARCH ESO DRS BLAZE FILE' not in e2ds_header: continue print(filename, e2ds_header['HIERARCH ESO DRS BLAZE FILE']) That's the code i'm using.can anyone tell me how to solve this? enter image description here
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/89698444
accepted answer: http://stackoverflow.com/a/51363368
upvote count: 1

http://stackoverflow.com/comment/89918781
type: Comment
comment on: http://stackoverflow.com/a/51463889
has text: Yes. I think it will fail once a person has two addresses with "123" zip code.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89886806
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51446512
has text: You can also do `chunk = (*islice(it, 0, k),)` if you want list of tuples vs a list of lists. On Python < 3.5, `tuple(islice(it, 0, k))`
type: Comment

http://stackoverflow.com/q/51433697
tagged with: django
tagged with: python
type: AnsweredQuestion
upvote count: 2
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51433792
has body: I installed django using pip install Django My result was Requirement already satisfied: Django in /usr/local/lib/python2.7/site-packages (1.11.14) When I run django --version I get zsh: command not found: django Here is the entire script: ➜ frameworks git:(master) ✗ pip install Django Requirement already satisfied: Django in /usr/local/lib/python2.7/site-packages (1.11.14) Requirement already satisfied: pytz in /usr/local/lib/python2.7/site-packages (from Django) (2018.5) azure-cli-core 2.0.41 has requirement pyyaml~=4.2b4, but you'll have pyyaml 3.12 which is incompatible. azure-cli-core 2.0.41 has requirement tabulate&lt;=0.8.2,&gt;=0.7.7, but you'll have tabulate 0.7.5 which is incompatible. azure-cli-core 2.0.41 has requirement wheel==0.30.0, but you'll have wheel 0.31.0 which is incompatible. rainbowstream 1.3.7 has requirement requests==2.5.3, but you'll have requests 2.18.4 which is incompatible. flask 1.0.2 has requirement click&gt;=5.1, but you'll have click 4.1 which is incompatible. cli-helpers 1.0.2 has requirement tabulate[widechars]&gt;=0.8.2, but you'll have tabulate 0.7.5 which is incompatible. cookiecutter 1.6.0 has requirement click&gt;=5.0, but you'll have click 4.1 which is incompatible. cycli 0.7.6 has requirement prompt-toolkit==0.57, but you'll have prompt-toolkit 1.0.15 which is incompatible. azure-cli-acs 2.1.3 has requirement pyyaml~=4.2b4, but you'll have pyyaml 3.12 which is incompatible. azure-cli-interactive 0.3.25 has requirement pyyaml~=4.2b4, but you'll have pyyaml 3.12 which is incompatible. azure-cli-extension 0.1.0 has requirement wheel==0.30.0, but you'll have wheel 0.31.0 which is incompatible. azure-cli-container 0.2.1 has requirement pyyaml~=4.2b4, but you'll have pyyaml 3.12 which is incompatible. legit 1.0.1 has requirement click==6.7, but you'll have click 4.1 which is incompatible. ➜ frameworks git:(master) ✗ django --version zsh: command not found: django ➜ frameworks git:(master) ✗ django version zsh: command not found:…
tagged with: azure
answer count: 1
score: 1
favorite count: 0
has title: command not found: django
accepted answer: http://stackoverflow.com/a/51433792
tagged with: path

http://stackoverflow.com/comment/89873147
comment on: http://stackoverflow.com/q/51432497
type: QuestionComment
score: 0
has text: `f = convex <=> -f is concave` is usually mentioned in textbooks. A general purpose NLP solver can find local optima. For proven global solutions you need a global solver. Anyway, finding a solution with maximum risk is not so interesting anyway. I would focus on solutions with minimum risk.
type: Comment

http://stackoverflow.com/q/51391488
has answer: http://stackoverflow.com/a/51391571
linked to: http://stackoverflow.com/q/2369492
tagged with: python
has answer: http://stackoverflow.com/a/51391898
tagged with: heatmap
possible better answer: http://stackoverflow.com/a/51391571
upvote count: 2
downvote count: 1
type: AnsweredQuestion
score: 1
tagged with: matplotlib
has body: I have two heatmaps which are based on 2d histograms that I am trying to overlay on a single graph. The limits of their axes (extent_L and extent_H) do not necessarily coincide exactly. I can make the individual plots satisfactorily if needed, but when trying to show both heatmaps on a single graph nicely, only the most recent one is displayed. import numpy as np import numpy.random import matplotlib.pyplot as plt # Generate some test data x_L = np.random.randn(8873) y_L = np.random.randn(8873) x_H = np.random.randn(1000) y_H = np.random.randn(1000) heatmap_L, xedges_L, yedges_L = np.histogram2d(x_L, y_L, bins=50) extent_L = [xedges_L[0], xedges_L[-1], yedges_L[0], yedges_L[-1]] heatmap_H, xedges_H, yedges_H = np.histogram2d(x_H, y_H, bins=50) extent_H = [xedges_H[0], xedges_H[-1], yedges_H[0], yedges_H[-1]] plt.clf() im1 = plt.imshow(heatmap_L.T, extent=extent_L, origin='lower', cmap='Blues') im2 = plt.imshow(heatmap_H.T, extent=extent_H, origin='lower', cmap='Greens') plt.show() Edit: If I'm not mistaken, all points are not in exactly the proper location import numpy as np import numpy.random import matplotlib.pyplot as plt # Generate some test data x_L = np.random.randn(8873) y_L = np.random.randn(8873) x_H = np.random.randn(1000) y_H = np.random.randn(1000) heatmap_L, xedges_L, yedges_L = np.histogram2d(x_L, y_L, bins=50) extent_L = np.array([xedges_L[0], xedges_L[-1], yedges_L[0], yedges_L[-1]]) heatmap_H, xedges_H, yedges_H = np.histogram2d(x_H, y_H, bins=50) extent_H = np.array([xedges_H[0], xedges_H[-1], yedges_H[0], yedges_H[-1]]) plt.clf() im1 = plt.imshow(heatmap_L.T, extent=extent_L, origin='lower', cmap='Blues') im2 = plt.imshow(heatmap_H.T, extent=extent_H, origin='lower', cmap='Greens') plt.autoscale() plt.show() flatHMH = np.reshape(heatmap_H, 2500) # flatten the 2D arrays flatHML = np.reshape(heatmap_L, 2500) maxHMH = flatHMH.max() # Find the maximum in each maxHML = flatHML.max() # Now for each value in the flat array build an RGBA tuple using # 1 …
accepted answer: http://stackoverflow.com/a/51391898
has title: Overlaying plots on a single graph
type: Question
answer count: 2
tagged with: histogram
tagged with: imshow
has comment: http://stackoverflow.com/comment/89755054
favorite count: 0

http://stackoverflow.com/q/51461110
answer count: 2
tagged with: for-loop
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/89892456
has comment: http://stackoverflow.com/comment/89891635
favorite count: 0
possible better answer: http://stackoverflow.com/a/51461270
has title: Python: for loop iteration through objects, not strings
has comment: http://stackoverflow.com/comment/89891654
has comment: http://stackoverflow.com/comment/89891710
tagged with: python
has body: I used pd.GetDummies to one hot encode my categorical variables to be used as predictors. For some of my columns that had many unique values, I have many new columns and I am trying to find a fast way to create interaction terms for these. (I only want interactions for a subset of my columns, so PolynomialFeatures() won't work...or will it?) Here is what I am trying to do: Step 1: Create lists of column names for each of the subset I want to multiply: channel = [col for col in df if col.startswith('channel')] quote = [col for col in df if col.startswith('quote')] print(channel[:1]) Out: 'channel_A' 'channel_B' Step 2: for loop: cols = 'channel quote'.split() for col in cols: for i in col: colname = 'value_X_'+i df[colname] = df['value_days']*df[i]+0 The problem is that the inner loop does not recognize col as an object: it recognizes it as a string (error = 'c', evidenced by: for col in cols: for i in col: print i Out[1]: c h . . . o t e Goal: My desired outcome is to get a new column that is named for the two columns were originally multiplied and has values for the multiplication. For example, the first element in channel is channel_A, so I want to get a new column named value_X_channel_A and it should have values that are equivalent to the product of value_days*channel_A. value_days | channel_A | value_X_channel_A ------------------------------------------- 5 |5 |25 This works perfectly fine if I just run the inner loop and replace col with channel. How can I get this to work? Thanks in advance.
has answer: http://stackoverflow.com/a/51461316
accepted answer: http://stackoverflow.com/a/51461316
has comment: http://stackoverflow.com/comment/89891544
has comment: http://stackoverflow.com/comment/89891768
upvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51461270
score: 1
type: Question

http://stackoverflow.com/q/51365865
score: 3
has body: I am training a CGAN to reconstruct images from corrupted images. I have written all my code for variable batch sizes so I can also train on variable batch sizes (I dont get an error or anything). When I use batch size one, after 2 minutes the reconstructed images no longer have any strange artifacts. However here is my problem: for any other batch size I get very strange checkerboard artifacts, even when I try different learning rates or when I train for multiple hours. This is a reconstructed image at batch size 2 after training for a while. (These weird artifacts were not in the corrupted data.) This is the adversarial component to the generator loss at batch size 2. This is the generator loss at batch size 2. This is the discriminator loss at batch size 2. For comparison, at batch size 1: advloss gloss dloss Orange is train, Blue is validation It seems like my code does something completely different as soon as the batch size is larger than one. I'm certain that the batches are being loaded correctly. Am I going crazy? My model: self.original = tf.placeholder(tf.float32, shape=(None,conf.fig_size, conf.fig_size, conf.fig_channel), name="original") self.corrupted = tf.placeholder(tf.float32, shape=(None,conf.fig_size, conf.fig_size, conf.fig_channel), name="corrupted") self.reconstructed = self.generator(self.corrupted) pos = self.discriminator(self.original, self.corrupted, False) neg = self.discriminator(self.original, self.corrupted, True) pos_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=pos, labels=tf.ones_like(pos))) neg_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=neg, labels=tf.zeros_like(neg))) self.d_loss = pos_loss + neg_loss adv_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=neg, labels=tf.ones_like(neg))) self.g_loss = adv_loss + conf.l1_lambda * tf.reduce_mean(tf.abs(self.original - self.reconstructed)) t_vars = tf.trainable_variables() self.d_vars = [var for var in t_vars if 'disc…
downvote count: 0
has answer: http://stackoverflow.com/a/51365988
favorite count: 0
type: Question
tagged with: python
tagged with: generative-adversarial-network
upvote count: 3
tagged with: image-processing
answer count: 1
tagged with: tensorflow
type: UnansweredQuestion
has title: Tensorflow GAN only works when batch size equals one

http://stackoverflow.com/comment/89794511
has text: When you say *"the lists could be huge"*, do you mean the lengths X, Y or both? Anyway, two lists are the wrong data structure to insert into. Use two trees instead (or heap). Then both structures will be sorted by default, and can trivially easily find their (predecessor and successor) neighbors. The rest is trivial.
comment on: http://stackoverflow.com/q/51410808
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/51340107
has comment: http://stackoverflow.com/comment/89653836
has answer: http://stackoverflow.com/a/51341189
upvote count: 2
type: UnansweredQuestion
has title: Concatenate multiple Convolution Layers
tagged with: python
score: 2
tagged with: conv-neural-network
has comment: http://stackoverflow.com/comment/89653934
type: Question
has comment: http://stackoverflow.com/comment/89655056
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89655246
tagged with: lstm
has comment: http://stackoverflow.com/comment/89654276
has comment: http://stackoverflow.com/comment/89655016
tagged with: keras-2
has body: Text classification by extracting tri-grams and quad-grams features of character level inputs using multiple concatenated CNN layers and passing it to BLSTM layer submodels = [] for kw in (3, 4): # kernel sizes model = Sequential() model.add(Embedding(vocab_size, 16,input_length=maxlen,input_shape=(maxlen,vocab_size)) model.add(Convolution1D(nb_filter=64, filter_length=kw, border_mode='valid', activation='relu')) submodels.append(model) big_model = Sequential() big_model.add(keras.layers.Concatenate(submodels)) big_model.add(Bidirectional(LSTM(100, return_sequences=False))) big_model.add(Dense(n_out,activation='softmax')) Model summary of individual conv layers: Layer (type) Output Shape Param ------------ ------------ ----- embedding_49 (Embedding) (None, 1024, 16) 592 conv1d_41 (Conv1D) (None, 1024, 64) 4160 But, I am getting this error: ValueError: Input 0 is incompatible with layer conv1d_22: expected ndim=3, found ndim=4 UPDATE NOW USING FUNCTIONAL KERAS API x = Input(shape=(maxlen,vocab_size)) x=Embedding(vocab_size, 16, input_length=maxlen)(x) x=Convolution1D(nb_filter=64, filter_length=3,border_mode='same', activation='relu')(x) x1 = Input(shape=(maxlen,vocab_size)) x1=Embedding(vocab_size, 16, input_length=maxlen)(x1) x1=Convolution1D(nb_filter=64, filter_length=4,border_mode='same', activation='relu')(x1) x2 = Bidirectional(LSTM(100, return_sequences=False)) x2=Dense(n_out,activation='softmax')(x2) big_model = Model(input=keras.layers.Concatenate([x,x1]),output=x2) big_model.compile(loss='categorical_crossentropy', optimizer='adadelta', metrics=['accuracy']) Still the same error!
has comment: http://stackoverflow.com/comment/89654305
favorite count: 0

http://stackoverflow.com/q/51406206
has title: dataset.repeat() doesn't work in TensorFlow
tagged with: python
accepted answer: http://stackoverflow.com/a/51408657
type: AnsweredQuestion
has body: This is the part of the code def train(x): prediction = cnn(x) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=prediction, labels=y)) optimizer = tf.train.AdadeltaOptimizer().minimize(cost) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for epoch in xrange(num_epochs): epoch_loss = 0 for _ in xrange(batch_size): _, c = sess.run([optimizer, cost]) epoch_loss += c print('Epoch {} completed out of {} - loss {}'.format(epoch + 1, num_epochs, epoch_loss)) n_classes = 17 batch_size = 32 dropout_rate = 0.4 num_epochs = 10 train_set = read_image_dataset_tfrecordfile('train.tfrecord', resize=True) train_set = train_set.batch(batch_size) train_set.repeat(num_epochs) train_iterator = train_set.make_one_shot_iterator() x, y = train_iterator.get_next() train(x) When I run this it does only the first epoch and then throws OutOfRangeError, here the stack Epoch 1 completed out of 10 - loss 5.82853866496e+11 Traceback (most recent call last): File "/Users/user/PycharmProjects/ProveTF/main.py", line 113, in &lt;module&gt; train(x) File "/Users/user/PycharmProjects/ProveTF/main.py", line 83, in train _, c = sess.run([optimizer, cost]) File "/Users/user/venv/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 905, in run run_metadata_ptr) File "/Users/user/venv/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1137, in _run feed_dict_tensor, options, run_metadata) File "/Users/user/venv/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1355, in _do_run options, run_metadata) File "/Users/user/venv/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1374, in _do_call raise type(e)(node_def, op, message) tensorflow.python.framework.errors_impl.OutOfRangeError: End of sequence [[Node: IteratorGetNext = IteratorGetNext[output_shapes=[[?,100,100,1], [?,17]], output_types=[DT_FLOAT, DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0"](OneShotIterator)]…
tagged with: tensorflow
has answer: http://stackoverflow.com/a/51408657
type: Question
answer count: 1
score: 0

http://stackoverflow.com/q/51412615
score: 0
has comment: http://stackoverflow.com/comment/89897902
tagged with: python
type: AnsweredQuestion
tagged with: twine
tagged with: python-packaging
tagged with: pypi
type: Question
has answer: http://stackoverflow.com/a/52920711
answer count: 1
has title: Python pypi upload with twine retruns error: ItemNotFoundException: Item does not exist
has body: I could not find any relevant content here or elsewhere about this issue. I am basically trying to upload a new version of my package to PyPi, and I get this strange error: python setup.py sdist bdist_wheel # this works fine twine upload dist/* # returns: Uploading distributions to https://upload.pypi.org/legacy/ Enter your username: XXXXXXXXXX ItemNotFoundException: Item does not exist! I could not find any reference to this error, and the exception is not even in twine source code. I can confirm that both package and my user account are fine in pypi.org. Any ideas why I am having this issue? Thanks,
accepted answer: http://stackoverflow.com/a/52920711

http://stackoverflow.com/a/51348266
has comment: http://stackoverflow.com/comment/89669199
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51348192
has comment: http://stackoverflow.com/comment/89669184
type: Answer
has comment: http://stackoverflow.com/comment/89671096
answers question: http://stackoverflow.com/q/51348192
downvote count: 0
score: 1
has body: you want to use apply on column A df['B'] = df['A'].apply(function) this does the function on each value in A. essentially you are using the apply method of the series object, more info: pandas.Series.apply
has comment: http://stackoverflow.com/comment/89669364
has comment: http://stackoverflow.com/comment/89670960

http://stackoverflow.com/q/51373072
has title: tf.optimizer update all existed weights for sparse input
type: Question
has body: I'm using tf to train a LR model via FTRLOp for sparse dataset. Code snippet as follows: feature_columns = [ tf.feature_column.categorical_column_with_hash_bucket('query_id',15), tf.feature_column.categorical_column_with_hash_bucket('ad_id',15), tf.feature_column.categorical_column_with_hash_bucket('cat_id',15), ] label_column = tf.feature_column.numeric_column('label', dtype=tf.float32, default_value=0) columns = feature_columns + [label_column] cols_to_vars = {} parsed_example = tf.parse_example(serialized_example, tf.feature_column.make_parse_example_spec(columns)) logits = tf.feature_column.linear_model( features=parsed_example, feature_columns=feature_columns, cols_to_vars=cols_to_vars ) loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=label, logits=logits)) optimizer = tf.train.FtrlOptimizer(learning_rate=0.5, learning_rate_power=-0.5, initial_accumulator_value=0.5, l1_regularization_strength=2, l2_regularization_strength=0.1) trainables = tf.trainable_variables() grads_and_vars = tf.gradients(loss, trainables) The input is sparse and categorical, input is kinda one hot and memorize the nonzero indices, for example the first two records is: 6, 10, 13 3, 9, 12 The gradients shows: The result of first record only input: current gradients is: IndexedSlicesValue(values=array([[0.5]], dtype=float32), indices=array([6]), dense_shape=array([15, 1], dtype=int32)) current gradients is: IndexedSlicesValue(values=array([[0.5]], dtype=float32), indices=array([10]), dense_shape=array([15, 1], dtype=int32)) current gradients is: IndexedSlicesValue(values=array([[0.5]], dtype=float32), indices=array([13]), dense_shape=array([15, 1], dtype=int32)) current gradients is: [0.5] Result of first two input: current gradients is: IndexedSlicesValue(values=array([[0.25], [0.25]], dtype=float32), indices=array([6, 3]), dense_shape=array([15, 1], dtype=int32)) current gradients is: IndexedSlicesValue(values=array([[0.25], [0.25]], dtype=float32), indices=array([10, …
tagged with: tfrecord
answer count: 1
score: 0
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51402251
tagged with: tensorflow
tagged with: logistic-regression

http://stackoverflow.com/q/51408490
accepted answer: http://stackoverflow.com/a/51410312
tagged with: python
type: AnsweredQuestion
has title: PyQt5 - Open new image window for each button click
has answer: http://stackoverflow.com/a/51410312
downvote count: 0
score: 1
tagged with: pyqt5
tagged with: image
has body: I'v been playing around with PyQt5 and got stuck here. In a certain menu, for each button click (and a given numpy image array), I'm trying to open a new image window (while converting the numpy array to an image). So first, I did for one image (used this answer to convert numpy image array to QPixmap): NewNumpyImageWindow.py class: import cv2 import sys from PyQt5.QtWidgets import QApplication, QWidget, QLabel from PyQt5.QtGui import QPixmap, QImage class NewImage(QWidget): def __init__(self, npImage): super().__init__() label = QLabel(self) pixmap = self.ConvertNumpyToQPixmap(npImage) label.setPixmap(pixmap) self.resize(pixmap.width(), pixmap.height()) self.show() @staticmethod def ConvertNumpyToQPixmap(np_img): height, width, channel = np_img.shape bytesPerLine = 3 * width return QPixmap(QImage(np_img.data, width, height, bytesPerLine, QImage.Format_RGB888).rgbSwapped()) if __name__ == '__main__': app = QApplication(sys.argv) currentNumpyImage = cv2.imread("capture.png") window = NewImage(currentNumpyImage) sys.exit(app.exec_()) And it works fine. The image shows up as a new window. Now, I want the image to show up as a new window each time I press a button in my main menu. So I tried to create an instance of the class above for each press (on the button 'New'), and it doesn't work. It seems like the window shows up as a new window and closes immediately when the code finishes. NewNumpyImageWindowMenu.py class: import cv2 import sys from PyQt5 import QtWidgets from NewNumpyImageWindow import NewImage class Menu(QtWidgets.QMainWindow): def __init__(self, numpyPic): super().__init__() newAct = QtWidgets.QAction('New', self) self.numpyPicture = numpyPic newAct.triggered.connect(self.newPicture) toolbar = self.addToolBar('Exit') toolbar.addAction(newAct) self.setGeometry(300, 300, 350, 250) self.show() def newPicture(self): NewImage(self.numpyPicture) #From the previous class if __name__ == '__main__': currentNumpyImage = cv2.imread("capture.png") app = QtWidgets.QAp…
type: Question
linked to: http://stackoverflow.com/q/34232632
upvote count: 1
answer count: 1
tagged with: window
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/89925860
type: QuestionComment
comment on: http://stackoverflow.com/q/51473097
has text: The Telplate base.html is like following. The code I attached above is from form.py
score: 0
type: Comment

http://stackoverflow.com/q/51390164
has comment: http://stackoverflow.com/comment/89781669
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89753048
tagged with: python
has title: Python- How to select rows from a multiIndexed data frame
upvote count: 3
type: Question
score: 3
has body: I currently have a data frame in which each row is indexed by a physical 3d coordinate. Here is an example of what the data looks like: ind pos x y z 1.0 8.0 2.0 0 (52.3311, 240.997, 70.7449) 2.0 1 (54.8969, 241.985, 72.116) 2.0 2 (51.9996, 240.91, 73.2884) 2.0 3 (51.765, 240.269, 71.5289) 2.0 4 (53.5773, 243.276, 69.569) 2.0 5 (53.1426, 240.779, 71.912) I want to select all the entries where any of the coordinates (x,y,z) are equal to some value. What is the most efficient way to do this? I have quite a large datset (~ 3 million entries) and I want to select all the rows in which any of x, y, or z are equal to a value 33.
tagged with: pandas
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/51390224
has comment: http://stackoverflow.com/comment/89759162
linked to: http://stackoverflow.com/q/18835077
has comment: http://stackoverflow.com/comment/89752949
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/51420269
score: 1
tagged with: dataframe
has title: pair-wise equality of pandas dataframe rows
type: Question
answer count: 1
downvote count: 0
tagged with: pandas
tagged with: python
favorite count: 0
has body: I have a data frame with many rows, for illustration I'll use the following sample: df = pd.DataFrame([[2,1,3,3],[2,3,3,4],[4,1,3,2]],columns=['A','B','C','D']) This results: A B C D 0 2 1 3 3 1 2 3 3 4 2 4 1 3 2 I would to get a new dataframe consisted of pair-wise equality results between the original dataframe rows. I expect to get the following result: A B C D 0 1 0 1 0 1 0 1 1 0 2 0 0 1 0 as: index 0- is row 0 vs row 1, index 1- is row 0 vs row 2, index 2- is row 1 vs row 2 A naive way to implement this would be: new_df = pd.DataFrame() for i in range(0, len(df)-1): for j in range(i+1, len(df)): new_df = new_df.append(df.iloc[i,:] == df.iloc[j,:], ignore_index=True) Is there any efficient way to implement this operation?
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/51420564

http://stackoverflow.com/comment/89728303
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51357529
has text: 'mdate.date2num(df['time'].to_pydatetime())' instead of 'pd.to_datetime()' gives this`AttributeError: 'Series' object has no attribute 'to_pydatetime'` @JeffEllen

http://stackoverflow.com/comment/89633740
has text: I edited the answer to discuss computational complexity a little bit. It's still important to profile if you're looking for speed.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51328047

http://stackoverflow.com/comment/89642259
score: 2
comment on: http://stackoverflow.com/a/51333412
has text: Somebody has to be that guy that points a UUID4 could technically collide. (Though the chances are infinitesimally small.) A [`uuid1`](https://docs.python.org/3.7/library/uuid.html#uuid.uuid1) will be "more unique" because it is dependent upon the system time. Perhaps that better fits what is being asked for here.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89749126
score: 0
comment on: http://stackoverflow.com/a/51387239
has text: What's it not doing that it should be? When combined with the imports and other supporting code, it gives a scatter plot where each point in the plot corresponds to one point from the t-SNE output, it colors them according to `smooth_midprice`, and it uses a red->blue colormap to do so. Coloring a t-SNE plot based on the five features is not possible. What would you like this code to do exactly?
type: Comment
type: AnswerComment

http://stackoverflow.com/a/51412742
downvote count: 0
has body: So if I have understood you correctly, instead of having something like this: x1 y1 z1 t1 t2 t3 Do you want something like this? x1 y1 z1 t1 x1 y1 z1 t2 x1 y1 z1 t3 I think there is more than one way to do this, but here is one using the melt functionality in Pandas. Let's say you have a data frame (like the one below), and you need to move the variables in t2 to t1 or to say it differently, you want to merge t1 and t2. df = pd.DataFrame([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18,19,20]], columns=['x','y','t1','t2']) x y t1 t2 0 1 2 3 4 1 5 6 7 8 2 9 10 11 12 3 13 14 15 16 4 17 18 19 20 To do what I believe you said you wanted, you can do the following, with f_df = df.melt(id_vars=['x','y'], value_vars = ['t1','t2'], value_name='t').drop('variable', axis=1).sort_values('x') With now f_df: x y t 0 1 2 3 5 1 2 4 1 5 6 7 6 5 6 8 2 9 10 11 7 9 10 12 3 13 14 15 8 13 14 16 4 17 18 19 9 17 18 20 From here, you can simply transform this into a numpy array
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51410223
has comment: http://stackoverflow.com/comment/89797555
answers question: http://stackoverflow.com/q/51410223
type: AcceptedAnswer

http://stackoverflow.com/comment/89809283
comment on: http://stackoverflow.com/a/51418388
type: Comment
score: 0
type: AnswerComment
has text: I have changed xPath to the link, please try it

http://stackoverflow.com/a/51451053
type: Answer
has body: After the execution of the loop for i in range(0,len(word)): a=i the value of a becomes len(word)-1 (in your case, 4) and never changes again. Here's what you are looking for: import string score = 0 # Does the string have at least one uppercase char? if set(string.ascii_uppercase) &amp; set(word): score += 5 # Does the string have at least one lowercase char? if set(string.ascii_lowercase) &amp; set(word): score += 5
upvote count: 3
answers question: http://stackoverflow.com/q/51450883
score: 3
downvote count: 0

http://stackoverflow.com/comment/89744103
comment on: http://stackoverflow.com/q/51386039
has text: `cmd` as string seems already not good, or else split would have worked. materialize your arguments in a list, don't pass a string.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/89652063
score: 0
type: Comment
type: QuestionComment
has text: Is your index open?
comment on: http://stackoverflow.com/q/51338710

http://stackoverflow.com/comment/89655454
type: Comment
has text: Thank you for your reply. I am actually not a pythonist either. I just happen to work on a project that it's written in. I think `get_browser_and_wait` is called in the second for loop in `setUp`. The cloud cross browser testing provider I can see each browser being stood up, just not calling the desired url. So the browsers just sit there doing nothing. Also please understand my example code is extremely stripped down for brevity and security. The real one is 1,000's of lines long. So it's totally possible I missed critical code. I just wanted to give enough for the example.
score: 0
comment on: http://stackoverflow.com/a/51340090
type: AnswerComment

http://stackoverflow.com/comment/89940497
comment on: http://stackoverflow.com/q/51482153
type: Comment
type: QuestionComment
has text: No idea on if this order of events would happen, but what I'm thinking is along the lines of: Both threads start; sniff_data waits patiently for a packet; process_data continually checks my_list to see if it is empty. It does this as fast as the CPU allows; sniff_data is now not actually checking for a packet because my_list is eating the whole logical processor; you exit process_data, freeing up my_list long enough for sniff_data to put something in it; somehow process_data is up again but now my_list is not empty, so it doesn't eat the CPU. possibly an extra one spawned from main module.
score: 0

math
tags question: http://stackoverflow.com/q/51465661
type: Tag
tags question: http://stackoverflow.com/q/51428007
tags question: http://stackoverflow.com/q/51445711
tags question: http://stackoverflow.com/q/51365581
tags question: http://stackoverflow.com/q/51328575
tags question: http://stackoverflow.com/q/51440058
tag name: math

http://stackoverflow.com/q/51328430
has answer: http://stackoverflow.com/a/51328554
type: Question
score: 0
answer count: 2
has body: I am learning webscraping with python using selenium and chromedriver. from selenium import webdriver driver=webdriver.Chrome(executable_path=r'C:\chromedriver\chromedriver.exe') driver.get('http://python.org') html_con=driver.page_source print('html_con') just the url gets open but sublime text does not show the html in build output
has comment: http://stackoverflow.com/comment/89632436
tagged with: python
has title: sublimetext build output not showing
has answer: http://stackoverflow.com/a/51328822
type: UnansweredQuestion

http://stackoverflow.com/a/51413053
answers question: http://stackoverflow.com/q/51360970
has comment: http://stackoverflow.com/comment/89988167
downvote count: 0
has comment: http://stackoverflow.com/comment/127593554
score: 6
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89963476
type: Answer
has body: Give you a demo from .utils import get_settings from constance import config from rest_framework.viewsets import ViewSet class SettingViewSet(ViewSet): permission_classes = (IsAuthenticated,) def setting(self, request, allow_settings): if request.method == 'GET': # list all setting items return Response(data=get_settings(allow_settings)) else: # change all allow setting items in allow_settings for key in request.data: if key in allow_settings and key in getattr(settings, 'CONSTANCE_CONFIG', {}): value = request.data[key] setattr(config, key, '' if value is None else value) return Response(data=get_settings(allow_settings)) def create(self, request): """ &lt;p&gt;update with POST:&lt;code&gt;{'Key': new_value}&lt;/code&gt; """ allow_settings = [key for key, options in getattr(settings, 'CONSTANCE_CONFIG', {}).items()] return self.setting(request, allow_settings) def list(self, request): """ get all setting item """ allow_settings = [key for key, options in getattr(settings, 'CONSTANCE_CONFIG', {}).items()] return self.setting(request, allow_settings) in utils.py: def get_settings(allow_settings): setting_list = [] for key, options in getattr(settings, 'CONSTANCE_CONFIG', {}).items(): if key in allow_settings: default, help_text = options[0], options[1] data = {'key': key, 'default': default, 'help_text': help_text, 'value': getattr(config, key)} setting_list.append(data) return setting_list in urls.py: router.register(r'setting', SettingViewSet, base_name='setting') ask get http://x.x.x.x/setting/ you can get: [ { "key": "staff_prefix", "default": "", "help_text": "工号固定代码", "value": "" }, { "key": "staff_suffix", "default": 3, "help_text": "工号尾缀", "value": "3" } ] post http://x.x.x.x/setting/ with data {'staff_prefix': 'demo'} you can update value in staff_prefix.
has comment: http://stackoverflow.com/comment/89965639
upvote count: 6
has comment: http://stackoverflow.com/comment/89966199
accepted answer of: http://stackoverflow.com/q/51360970

http://stackoverflow.com/a/51376168
downvote count: 0
has body: It's in the docs The WEB_CONCURRENCY environment variable is automatically set by Heroku, based on the processes’ Dyno size.
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51374981
answers question: http://stackoverflow.com/q/51374981
type: AcceptedAnswer

http://stackoverflow.com/comment/89731587
type: Comment
has text: tanx again just its arguments not argument
type: AnswerComment
comment on: http://stackoverflow.com/a/51377623
score: 0

http://stackoverflow.com/comment/89871419
has text: Hi. But would this order from top left to bottom right?
comment on: http://stackoverflow.com/a/51449887
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51338222
has comment: http://stackoverflow.com/comment/89651799
type: Answer
has comment: http://stackoverflow.com/comment/89651779
has comment: http://stackoverflow.com/comment/89651557
has comment: http://stackoverflow.com/comment/89651076
has comment: http://stackoverflow.com/comment/89651942
upvote count: 1
has comment: http://stackoverflow.com/comment/89651301
downvote count: 1
has comment: http://stackoverflow.com/comment/89651240
has body: What you need to do is probably this - log(str(element + 1)) What you are doing is - log(str(element) + 1) You have converted element to string but 1 is still an integer and you can't add string and integer
has comment: http://stackoverflow.com/comment/89651838
answers question: http://stackoverflow.com/q/51338095
score: 0
has comment: http://stackoverflow.com/comment/89651854
has comment: http://stackoverflow.com/comment/89651035
has comment: http://stackoverflow.com/comment/89651755
has comment: http://stackoverflow.com/comment/89651580
has comment: http://stackoverflow.com/comment/89651544
has comment: http://stackoverflow.com/comment/89651700

http://stackoverflow.com/q/51425129
type: AnsweredQuestion
score: 1
has title: Passing rows to function giving error Pandas Python
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51425197
has body: I am trying to create a new column where the values filled will be after comparing the two columns of the dataframe. Here is what I tried: def determinecolor(row,column1,column2): if row[column1] == row[column2]: val = 'k' elif row[column1] &gt; row[column2]: val = 'r' else: val = 'g' return val datasetTest['color_original'] = datasetTest.apply(determinecolor(datasetTest,'openshifted','close'), axis=1) The error I received: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-182-31188e414958&gt; in &lt;module&gt;() 2 # if(test_shifted['openshifted'][0] &gt; test_pred_list[0]): print("red") 3 datasetTest.loc[:,'predict_close'] = pd.Series(test_pred_list) ----&gt; 4 datasetTest['color_original'] = datasetTest.apply(determinecolor(datasetTest,'openshifted','close'), axis=1) 5 6 # datasetTest['color_predicted'] = datasetTest.apply(determinePredictedcolor, axis=1) &lt;ipython-input-178-d1f3e204fd17&gt; in determinecolor(row, column1, column2) 1 def determinecolor(row,column1,column2): ----&gt; 2 if row[column1] == row[column2]: 3 val = 'k' 4 elif row[column1] &gt; row[column2]: 5 val = 'r' c:\python35\lib\site-packages\pandas\core\generic.py in __nonzero__(self) 1119 raise ValueError("The truth value of a {0} is ambiguous. " 1120 "Use a.empty, a.bool(), a.item(), a.any() or a.all()." -&gt; 1121 .format(self.__class__.__name__)) 1122 1123 __bool__ = __nonzero__ ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). Kindly, help me solve this issue. EDITED Here is a sample dataset: open high low close closeTarget openshifted predict_close 0.104167 0.119048 0.117647 0.145833 0.104167 0.416667 0.881613 0.416667 0.285714 0 0.104167 0.4375 0.833333 0.684905 0.833333 0.761905 0.45098 0.4375 0.791667 0.8125 0.821244 0.8125 0.761905 0.784314 0.791667 0.770833 0.8125 0.920608 0.8125 0.761905 0.823529 0.770833 0.8125 0.916667 0.853668
answer count: 2
tagged with: pandas
downvote count: 0
possible better answer: http://stackoverflow.com/a/51425253
accepted answer: http://stackoverflow.com/a/51425197
favorite count: 0
has answer: http://stackoverflow.com/a/51425253
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89821302
tagged with: python

http://stackoverflow.com/comment/89916429
comment on: http://stackoverflow.com/q/51473216
score: 0
has text: @Kristada673 Can you give more addresses that returns you nothing? I've reproduced your code and for some reasons it works well for the address you gave in the example. I've used `https://maps.googleapis.com/maps/api/geocode/json` for the `GOOGLE_MAPS_API_URL`.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89957388
comment on: http://stackoverflow.com/a/51471874
score: 0
type: AnswerComment
type: Comment
has text: "Convert the matrix to a data frame using pd.DataFrame(matrix_name)" - Which matrix? I have two matrices X1 and X2. Do you mean I should stack them together and convert it into a dataframe?

http://stackoverflow.com/a/51470170
score: 0
has comment: http://stackoverflow.com/comment/89908923
type: Answer
answers question: http://stackoverflow.com/q/51470049
has body: Try this df['r2_x-r1_x'] = df.r2_x - df.r1_x

http://stackoverflow.com/comment/89817619
type: Comment
type: QuestionComment
has text: Possible duplicate of [Python: Assign each element of a List to a separate Variable](https://stackoverflow.com/questions/19300174/python-assign-each-element-of-a-list-to-a-separate-variable)
score: 0
comment on: http://stackoverflow.com/q/51423255

http://stackoverflow.com/comment/127320357
has text: @abdelgha4: how it "doesn't handle the case when JSON object has an empty array as value"? can you please provide an example with expected & actual behavior?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/57793454
type: Comment

http://stackoverflow.com/comment/89685721
has text: Please check if the table in this PDF can be used to enumarate your DEVICE_ID row. https://www.easa.europa.eu/sites/default/files/dfu/List%20of%20EASA%20acronyms%20and%20abbreviations%20%2813022018%29%28v10%29.pdf
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51356024

http://stackoverflow.com/comment/89747473
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51361356
has text: no, I am reading from a s3 parquet dataset processing it and writing it to another parquet dataset. i don't have a data variety problem (which lakes try to solve).

http://stackoverflow.com/comment/89836481
score: 1
has text: What happens when you try writing to the file? Do you see any kind of error output? If so, including the error would be a good start to making this question more answerable.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51431082

http://stackoverflow.com/comment/89635984
type: Comment
comment on: http://stackoverflow.com/a/51329781
has text: i didn't really got your point please explain a bit more. you mean open application through some path like /home/etc ???
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89901729
comment on: http://stackoverflow.com/q/51466576
has text: @user202729 Yes `a < b` is assumed though they can take on arbitrary values.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89721589
type: AnswerComment
has text: Yes. The same thing with the mapping between (5,6). I would like something like 4,17,29,33... to be mapped to (5,6).
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51374977

http://stackoverflow.com/q/51455875
has answer: http://stackoverflow.com/a/51455937
upvote count: 1
has title: how this for loop works in python
linked to: http://stackoverflow.com/q/14507591
tagged with: for-loop
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51455937
downvote count: 0
score: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/51456350
type: Question
has body: I'm new to python. Please anyone help me to understand this statement of python. How it will work ? {x: {y: 0. for y in myClass.features} for x in myClass.items}
has answer: http://stackoverflow.com/a/51456350
tagged with: python
has comment: http://stackoverflow.com/comment/89881213
has comment: http://stackoverflow.com/comment/89881156
answer count: 2

classification
tags question: http://stackoverflow.com/q/51408417
tags question: http://stackoverflow.com/q/51349484
tag name: classification
tags question: http://stackoverflow.com/q/51445034
tags question: http://stackoverflow.com/q/51346918
tags question: http://stackoverflow.com/q/51470179
tags question: http://stackoverflow.com/q/51367755
tags question: http://stackoverflow.com/q/51380101
tags question: http://stackoverflow.com/q/51366521
tags question: http://stackoverflow.com/q/51479054
tags question: http://stackoverflow.com/q/51394792
tags question: http://stackoverflow.com/q/51342763
type: Tag
tags question: http://stackoverflow.com/q/51329107
tags question: http://stackoverflow.com/q/51423494

http://stackoverflow.com/comment/89822634
score: 2
comment on: http://stackoverflow.com/q/51425667
has text: `list2 = [x+y for x,y in zip(list1[::2], list1[1::2])]` For explanation have a look by yourself at the docs and search for list slices, zip and list comprehension.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51373979
tagged with: tensorflow-datasets
has title: Features&labels from CSV using CsvDataset for model.fit in tf.keras
type: UnansweredQuestion
tagged with: python
answer count: 0
has body: I try to use CsvDataset(tf.contrib.data.CsvDataset) to represent features and labels of a dataset. #download Iris data TRAIN_URL = "http://download.tensorflow.org/data/iris_training.csv" train_path_x = tf.keras.utils.get_file(TRAIN_URL.split('/')[-1], TRAIN_URL) In concrete using this line[Iris dataset use, 4-float and 1-int, representing features and labels]: csv_dataset = tf.contrib.data.CsvDataset(train_path_x, [tf.float32, tf.float32, tf.float32, tf.float32, tf.int64], header=True, select_cols=[0,1,2,3,4]) To validate the information I used this: interator = csv_dataset.make_one_shot_iterator().get_next() with tf.Session() as sess: while True: try: print(sess.run(interator)) except tf.errors.OutOfRangeError: break But if I try to use the tf.keras sequential model for this dataset, I need x and y elements or features and labels model.fit() I think I need to implement a parse_function and map method for the dataset before make_one_shot_iterator like the method used tf.data.TextLineDataset or tf.data.TFRecordDataset something like that: features, label = csv_dataset.make_one_shot_iterator().get_next() model.fit(x=features, y=label, steps_per_epoch=8, epochs=200, verbose=1) but I'm not sure, any ideas?
tagged with: tensorflow
type: Question
score: 4
upvote count: 4
downvote count: 0
tagged with: keras
favorite count: 0

http://stackoverflow.com/comment/89633701
type: AnswerComment
type: Comment
has text: if "--headless" in options.arguments: print("headless as fuh") print("doing condintionally headless test things now")
comment on: http://stackoverflow.com/a/51327704
score: 0

http://stackoverflow.com/q/51433403
has comment: http://stackoverflow.com/comment/89837460
has body: I am referring to the answer from @armatita in PySide/PyQt Overlay widget The answer from @armatita has the following effect... I want to ask, how to make the overlay transparent? To be exactly: With the transparent overlay, the buttons below it can still be clicked. For your convenience I paste the code from @armatita here as follows: import sys from PyQt5 import QtWidgets, QtCore, QtGui class TranslucentWidgetSignals(QtCore.QObject): # SIGNALS CLOSE = QtCore.pyqtSignal() class TranslucentWidget(QtWidgets.QWidget): def __init__(self, parent=None): super(TranslucentWidget, self).__init__(parent) # make the window frameless self.setWindowFlags(QtCore.Qt.FramelessWindowHint) self.setAttribute(QtCore.Qt.WA_TranslucentBackground) self.fillColor = QtGui.QColor(30, 30, 30, 120) self.penColor = QtGui.QColor("#333333") self.popup_fillColor = QtGui.QColor(240, 240, 240, 255) self.popup_penColor = QtGui.QColor(200, 200, 200, 255) self.close_btn = QtWidgets.QPushButton(self) self.close_btn.setText("x") font = QtGui.QFont() font.setPixelSize(18) font.setBold(True) self.close_btn.setFont(font) self.close_btn.setStyleSheet("background-color: rgb(0, 0, 0, 0)") self.close_btn.setFixedSize(30, 30) self.close_btn.clicked.connect(self._onclose) self.SIGNALS = TranslucentWidgetSignals() def resizeEvent(self, event): s = self.size() popup_width = 300 popup_height = 120 ow = int(s.width() / 2 - popup_width / 2) oh = int(s.height() / 2 - popup_height / 2) self.close_btn.move(ow + 265, oh + 5) def paintEvent(self, event): # This method is, in practice, drawing the contents of # your window. # get current window size s = self.size() qp = QtGui.QPainter() qp.begin(self) qp.setRenderHint(QtGui.QPainter.Antialiasing, True) qp.setPen(self.penColor) qp.setBrush(self.fillColor) qp.drawRect(0, 0, s.width(), s.height()) # drawpopup qp.setPen(self.popup_penColor) qp.setBrush(self.popup_fillColor) popup_width = 300 popup_height = 120 ow = int(s.width()/2-popup_width/2) oh = int(s.height()/2-popup_hei…
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/89848702
has comment: http://stackoverflow.com/comment/89837484
has comment: http://stackoverflow.com/comment/89837558
type: Question
has comment: http://stackoverflow.com/comment/89837730
tagged with: pyqt
downvote count: 0
has title: PyQt5: How to make a transparent overlay?
has comment: http://stackoverflow.com/comment/89837630
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90528447
has comment: http://stackoverflow.com/comment/89837501
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/44264852
score: 2
answer count: 0
upvote count: 2

http://stackoverflow.com/a/51343917
upvote count: 1
answers question: http://stackoverflow.com/q/51342055
has body: You actually want to do: Window.bind(mouse_pos=on_motion)
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/q/51442688
tagged with: dataframe
has answer: http://stackoverflow.com/a/51442923
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/89855538
favorite count: 0
has answer: http://stackoverflow.com/a/51442771
upvote count: 2
type: UnansweredQuestion
has body: I have a text file which contains some strings that I want to remove from my data frame. The data frame observations contains those texts which are present in the ext file. here is the text file - https://drive.google.com/open?id=1GApPKvA82tx4CDtlOTqe99zKXS3AHiuD here is the link; Data = https://drive.google.com/open?id=1HJbWTUMfiBV54EEtgSXTcsQLzQT1rFgz I am using the following code - import nltk from nltk.tokenize import word_tokenize file = open("D://Users/Shivam/Desktop/rahulB/fliter.txt") result = file.read() words = word_tokenize(result) I loaded the text files and converted them into words/tokens. Its is my dataframe. text 0 What Fresh Hell Is This? January 31, 2018 ...A... 1 What Fresh Hell Is This? February 27, 2018 My ... 2 What Fresh Hell Is This? March 31, 2018 Trump ... 3 What Fresh Hell Is This? April 29, 2018 Michel... 4 Join Email List Contribute Join AMERICAblog Ac... If you see this, these texts are present in the all rows such as "What Fresh Hell Is This?" or "Join Email List Contribute Join AMERICAblog Ac, "Sign in Daily Roundup MS Legislature Elected O" etc. I used this for loop for word in words: df['text'].replace(word, ' ') my error. error Traceback (most recent call last) &lt;ipython-input-168-6e0b8109b76a&gt; in &lt;module&gt;() ----&gt; 1 df['text'] = df['text'].str.replace("|".join(words), " ") D:\Users\Shivam\Anaconda2\lib\site-packages\pandas\core\strings.pyc in replace(self, pat, repl, n, case, flags) 1577 def replace(self, pat, repl, n=-1, case=None, flags=0): 1578 result = str_replace(self._data, pat, repl, n=n, case=case, -&gt; 1579 flags=flags) 1580 return self._wrap_result(result) 1581 D:\Users\Shivam\Anaconda2\lib\site-packages\pandas\core\strings.pyc in str_replace(arr, pat, repl, n, case, flags) 422 if use_re: 423 n = n if n &gt;= 0 else 0 --&gt; 424 regex = re.compile(pat, flags=flags) 425 f = lambda x: regex.sub(repl=repl, string=x, count=n) 426 else: D:\Users\Shivam\Anaconda2\lib\re.pyc in compile(pattern, flags) 192 def comp…
has comment: http://stackoverflow.com/comment/89855282
tagged with: python
tagged with: regex
tagged with: nlp
has comment: http://stackoverflow.com/comment/89856050
score: 1
has comment: http://stackoverflow.com/comment/89855277
downvote count: 1
has comment: http://stackoverflow.com/comment/89856011
type: Question
has comment: http://stackoverflow.com/comment/89855549
has answer: http://stackoverflow.com/a/51443440
has comment: http://stackoverflow.com/comment/89856033
has title: removing words from a list from pandas column - python 2.7

seaborn
tags question: http://stackoverflow.com/q/51394963
tags question: http://stackoverflow.com/q/51444009
tags question: http://stackoverflow.com/q/51433415
tag name: seaborn
tags question: http://stackoverflow.com/q/51422146
tags question: http://stackoverflow.com/q/51417483
tags question: http://stackoverflow.com/q/51477339
tags question: http://stackoverflow.com/q/51408675
tags question: http://stackoverflow.com/q/51448094
tags question: http://stackoverflow.com/q/51360524
tags question: http://stackoverflow.com/q/51465555
tags question: http://stackoverflow.com/q/51468670
tags question: http://stackoverflow.com/q/51413822
tags question: http://stackoverflow.com/q/51480276
tags question: http://stackoverflow.com/q/51412287
tags question: http://stackoverflow.com/q/51442910
tags question: http://stackoverflow.com/q/51473032
tags question: http://stackoverflow.com/q/51431719
tags question: http://stackoverflow.com/q/51388707
type: Tag
tags question: http://stackoverflow.com/q/51402579

http://stackoverflow.com/a/51358827
answers question: http://stackoverflow.com/q/51358717
has comment: http://stackoverflow.com/comment/89708594
score: 0
has body: Looking at the inspector for the page, the actual routing is done via a JavaScript invocation to <a href="https://vmrest.viamichelin.com/apir/10/iti.json/fra/geom;header;roadsheet?distUnit=m&amp;itit=0&amp;veht=0&amp;stepList=1%3Ae%3A5.57072%3A50.63341%3B1%3Ae%3A5.72926%3A50.55954%3B&amp;avoidExpressWays=false&amp;avoidBorders=false&amp;avoidTolls=false&amp;avoidCCZ=false&amp;avoidORC=false&amp;avoidPass=false&amp;avoidClosedRoad=true&amp;currency=EUR&amp;data=geom;header;roadsheet&amp;favMotorways=false&amp;fuelCost=1.393&amp;fuelConsump=6.8:5.6:5.6&amp;itineraryFuelType=petrol&amp;fullMapOpt=300:300:true:true:true&amp;indemnite=0&amp;multipleIti=true&amp;stepMapOpt=300:300:true:true:true&amp;traffic=AUT;BEL;CHE;DEU;DNK;ESP;FIN;FRA;GBR;ITA;LUX;NLD;NOR;POL;SWE&amp;isCostFctUsingTraffic=false&amp;sortFDRsByTraffic=false&amp;timeLimitTDP=0&amp;distanceLimitTDP=undefined&amp;itineraryVehiculeType=hatchback&amp;wCaravan=false&amp;withSecurityAdv=true&amp;shouldUseTraffic=false&amp;costCategory=car&amp;isMotorVehicle=true&amp;lg=fra&amp;obfuscation=false&amp;charset=UTF-8&amp;ie=UTF-8&amp;authKey=JSBS20110216111214120400892678&amp;nocache=1531733870014&amp;callback=JSE.HTTP.asyncRequests[1]._scriptLoaded" rel="nofollow noreferrer">this rather long URL. The data you need seems to be in that response, starting from _scriptLoaded(. (Since it's a JavaScript object literal, you can use Python's built-in JSON library to load the data into a dict.)
type: Answer

http://stackoverflow.com/a/51422841
has body: From network inspector it seems that the page is loaded dynamically from http://lscluster.hockeytech.com/feed/ in JSON format. For obtaining any data, it needs the key from the main site. Example is here (the data is stored in variables seasons_data, teamsbyseason_data, statviewtype_data): import requests from bs4 import BeautifulSoup import json url = "http://ontariohockeyleague.com/stats/players/60" r = requests.get(url) soup = BeautifulSoup(r.text, 'lxml') seasons_url = "http://lscluster.hockeytech.com/feed/?feed=modulekit&amp;view=seasons&amp;key=%s&amp;fmt=json&amp;client_code=ohl&amp;lang=en&amp;league_code=&amp;fmt=json" teamsbyseason_url = "http://lscluster.hockeytech.com/feed/?feed=modulekit&amp;view=teamsbyseason&amp;key=%s&amp;fmt=json&amp;client_code=ohl&amp;lang=en&amp;season_id=60&amp;league_code=&amp;fmt=json" statviewtype_url = "http://lscluster.hockeytech.com/feed/?feed=modulekit&amp;view=statviewtype&amp;type=topscorers&amp;key=%s&amp;fmt=json&amp;client_code=ohl&amp;lang=en&amp;league_code=&amp;season_id=60&amp;first=0&amp;limit=100&amp;sort=active&amp;stat=all&amp;order_direction=" key = soup.find('div', id='stats')['data-feed_key'] r = requests.get(seasons_url % key) seasons_data = json.loads(r.text) r = requests.get(teamsbyseason_url % key) teamsbyseason_data = json.loads(r.text) r = requests.get(statviewtype_url % key) statviewtype_data = json.loads(r.text) # print(json.dumps(seasons_data, indent=4, sort_keys=True)) # print(json.dumps(teamsbyseason_data, indent=4, sort_keys=True)) print(json.dumps(statviewtype_data, indent=4, sort_keys=True)) Prints: { "SiteKit": { "Copyright": { "powered_by": "Powered by HockeyTech.com", "powered_by_url": "http://hockeytech.com", "required_copyright": "Official statistics provided by Ontario Hockey League", "required_link": "http://leaguestat.com" }, "Parameters": { "client_code": "ohl", "feed": "modulekit", "first": "0", "fmt": "json", "key": "2976319eb44abe94", "lang": "en", "lang_id": 1, "league_code": "",…
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/89833733
answers question: http://stackoverflow.com/q/51419743
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51419743
upvote count: 2

http://stackoverflow.com/comment/89735302
comment on: http://stackoverflow.com/q/51376060
has text: Yes, in the end I had to reinstall python 64 bit and that did the trick in this case.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89682605
comment on: http://stackoverflow.com/q/51351089
type: Comment
has text: Ah, yeah, just include them, `re.findall(r'[^.();~]+|[.();~]', line)`
type: QuestionComment
score: 0

http://stackoverflow.com/q/51482134
has body: I am just starting learn python. Please advise how I can concatenate this. a='abc' b='123' As output I want: [(a1, b2, c3)] I tried to use built in zip() function but result is (a, 1), (a, 2), (a, 3)
answer count: 3
has comment: http://stackoverflow.com/comment/89933067
has title: Concatenate zipped values in Python
possible better answer: http://stackoverflow.com/a/51482199
favorite count: 0
has answer: http://stackoverflow.com/a/51482199
tagged with: python
has answer: http://stackoverflow.com/a/51482193
has answer: http://stackoverflow.com/a/51482435
has comment: http://stackoverflow.com/comment/89933076
score: 2
type: AnsweredQuestion
downvote count: 3
has comment: http://stackoverflow.com/comment/89934362
type: Question
upvote count: 5
accepted answer: http://stackoverflow.com/a/51482193

http://stackoverflow.com/q/51405032
has answer: http://stackoverflow.com/a/51405250
tagged with: pandas
has title: How to calculate mean values for a particular column in dataframe?
favorite count: 0
has comment: http://stackoverflow.com/comment/89781707
has answer: http://stackoverflow.com/a/51405529
accepted answer: http://stackoverflow.com/a/51405521
has comment: http://stackoverflow.com/comment/89781252
has comment: http://stackoverflow.com/comment/89781582
has body: I have a dataframe which has values of type: object. Dataframe also contains NaN values. I want to ignore NaN values and for all the remaining values in the column, I want to calculate the mean. Mean is calculated as follows: Upperbound value = 30 Lowerbound value = 0 (Upperbound and lowerbound are fixed and all values need to be calculated wrt to them.) So, for '>20', mean = (20+30)/2 = 25 for '>1', mean = (30+1)/2=15.5 for '&lt;5', mean = (5+0)/2 = 2.5 for '&lt;10', mean = (10+0)/2 = 5 Dataframe: column1 &gt;20 NaN &lt;5 12 &gt;1 &lt;10 NaN 8 Note: Above values in the column are strings and I want to convert it to numerical value. Final converted dataframe should be: column1 25 NaN 2.5 12 15.5 5 NaN 8 Note: Above values like 8 and 12 are not converted I only want to convert those values which are prefixed with either > or &lt; remaining values just need to be converted to numerical from the string value.
tagged with: python
answer count: 4
type: AnsweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/89781352
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89781473
has comment: http://stackoverflow.com/comment/89781483
has comment: http://stackoverflow.com/comment/89781242
has answer: http://stackoverflow.com/a/51405521
has comment: http://stackoverflow.com/comment/89781803
score: -1
has comment: http://stackoverflow.com/comment/89781315
has answer: http://stackoverflow.com/a/51405511
possible better answer: http://stackoverflow.com/a/51405250
has comment: http://stackoverflow.com/comment/89781359

http://stackoverflow.com/a/51373703
has comment: http://stackoverflow.com/comment/89719719
has comment: http://stackoverflow.com/comment/89719611
downvote count: 0
has comment: http://stackoverflow.com/comment/89719660
has comment: http://stackoverflow.com/comment/89719921
has comment: http://stackoverflow.com/comment/89719633
type: Answer
answers question: http://stackoverflow.com/q/51371495
has body: I think your elememnt is inside frame/iframe. To be able to interact with elements inside frame/iframe you have to switch to it's content like this: WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, "//path_to_frame"))) then you can locate your element and interact with it: WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "experiment-method-next"))).click() and when you are done with content inside frame, you have to switch back to default content: driver.switch_to.default_content() Note: you have to do some imports: from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC PS: if your elements is not inside frame, then just use WebDriverWait: WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "experiment-method-next"))).click() this will wait at least 10 seconds until element will be clickable and the clicks on it. Hope this helps.
upvote count: 1
has comment: http://stackoverflow.com/comment/89719445
score: 1
has comment: http://stackoverflow.com/comment/89719883
has comment: http://stackoverflow.com/comment/89719552

http://stackoverflow.com/q/51385622
has title: python toplevel runs even after root is killed
has answer: http://stackoverflow.com/a/51385786
tagged with: python
tagged with: tkinter
score: 0
has comment: http://stackoverflow.com/comment/89743536
type: Question
has comment: http://stackoverflow.com/comment/89743396
has comment: http://stackoverflow.com/comment/89743708
tagged with: toplevel
answer count: 1
has body: I've included some basic code below, which generates a frame, and then a toplevel made to destroy itself. A second is created after the first is destroyed. When this application is run, while the first toplevel is waiting, if the 'X' on the main window is clicked, it kills itself and the toplevel, but then the second toplevel is created along with a generic Tk(). When that is closed I get an error: _tkinter.TclError: can't invoke "wm" command: application has been destroyed I've tried using root.destroy(), quit() and os._exit(), but none of these completely stops the application. What can be done to completely stop any script from running after the root window is destroyed? from tkinter import * class Application(Frame): def __init__(self,master): Frame.__init__(self,master) self.L1 = Label(root,text='Hi!') self.L1.pack() def Window1(): Wind1 = Toplevel() Wind1.geometry('100x100+100+100') Wind1.B1 = Button(Wind1,text='Close',command=Wind1.destroy) Wind1.B1.pack() Wind1.lift(aboveThis=root) Wind1.wait_window() def Window2(): Wind2 = Toplevel() Wind2.geometry('100x100+100+100') Wind2.B2 = Button(Wind2,text='Close',command=Wind2.destroy) Wind2.B2.pack() Wind2.lift(aboveThis=root) Wind2.wait_window() def Close_Window(): root.destroy() root = Tk() root.geometry('100x100+50+50') root.protocol('WM_DELETE_WINDOW',Close_Window) app = Application(root) Window1() Window2() root.mainloop()
type: UnansweredQuestion

http://stackoverflow.com/comment/114908095
type: Comment
comment on: http://stackoverflow.com/a/51460044
type: AnswerComment
has text: A bit late, but is there a way to pass arguments here, such as which printer, number of copies, or orientation?
score: 3

http://stackoverflow.com/q/51479635
answer count: 2
has comment: http://stackoverflow.com/comment/89927910
has comment: http://stackoverflow.com/comment/89927823
has answer: http://stackoverflow.com/a/51479823
has answer: http://stackoverflow.com/a/51479960
downvote count: 0
favorite count: 0
tagged with: postgresql
has title: Protect deletion of ForeignKey
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: django-database
has comment: http://stackoverflow.com/comment/89930179
has comment: http://stackoverflow.com/comment/89929746
score: 1
has comment: http://stackoverflow.com/comment/89927857
upvote count: 1
has comment: http://stackoverflow.com/comment/89929779
type: Question
has body: Is it possible to ensure that ForeignKey can't be deleted? The best example is on UserProfile: class UserProfile(Model): user = models.OneToOneField('User',on_delete=models.CASCADE ...) And there is a signal which creates a UserProfile for given User right after User object is created. I want to be sure that nobody can delete UserProfile because every User has to have one UserProfile. I tried on_delete=models.PROTECT but it doesn't allow User to be deleted instead of UserProfile.
tagged with: django-models
linked to: http://stackoverflow.com/q/14492666

keras
tags question: http://stackoverflow.com/q/51377371
tags question: http://stackoverflow.com/q/51325371
tags question: http://stackoverflow.com/q/51461272
tags question: http://stackoverflow.com/q/51376802
tags question: http://stackoverflow.com/q/51332144
tags question: http://stackoverflow.com/q/51346918
tags question: http://stackoverflow.com/q/51381331
tags question: http://stackoverflow.com/q/51344610
tags question: http://stackoverflow.com/q/51474236
tags question: http://stackoverflow.com/q/51326233
tags question: http://stackoverflow.com/q/51479940
tags question: http://stackoverflow.com/q/51408162
tags question: http://stackoverflow.com/q/51385223
tags question: http://stackoverflow.com/q/51422301
tags question: http://stackoverflow.com/q/51357266
tags question: http://stackoverflow.com/q/51381329
tags question: http://stackoverflow.com/q/51479832
tags question: http://stackoverflow.com/q/51424189
tags question: http://stackoverflow.com/q/51387317
tags question: http://stackoverflow.com/q/51432652
tags question: http://stackoverflow.com/q/51329107
tags question: http://stackoverflow.com/q/51378645
tags question: http://stackoverflow.com/q/51405517
tags question: http://stackoverflow.com/q/51474015
tags question: http://stackoverflow.com/q/51436452
tags question: http://stackoverflow.com/q/51342304
tags question: http://stackoverflow.com/q/51464401
tags question: http://stackoverflow.com/q/51338831
tags question: http://stackoverflow.com/q/51482406
tags question: http://stackoverflow.com/q/51463847
tags question: http://stackoverflow.com/q/51438511
tags question: http://stackoverflow.com/q/51359851
tags question: http://stackoverflow.com/q/51461456
tags question: http://stackoverflow.com/q/51357981
tags question: http://stackoverflow.com/q/51337558
tags question: http://stackoverflow.com/q/51457286
tags question: http://stackoverflow.com/q/51462603
tags question: http://stackoverflow.com/q/51342528
tags question: http://stackoverflow.com/q/51373979
tags question: http://stackoverflow.com/q/51464626
tags question: http://stackoverflow.com/q/51369763
tags question: http://stackoverflow.com/q/51390566
tags question: http://stackoverflow.com/q/51363709
tags question: http://stackoverflow.com/q/51364077
tags question: http://stackoverflow.com/q/51343169
tags question: http://stackoverflow.com/q/51403577
tags question: http://stackoverflow.com/q/51477729
tags question: http://stackoverflow.com/q/51435117
tags question: http://stackoverflow.com/q/51481676
tags question: http://stackoverflow.com/q/51422272
tags question: http://stackoverflow.com/q/51445034
tags question: http://stackoverflow.com/q/51391083
tags question: http://stackoverflow.com/q/51475082
tags question: http://stackoverflow.com/q/51341092
tags question: http://stackoverflow.com/q/51412473
tags question: http://stackoverflow.com/q/51447010
tags question: http://stackoverflow.com/q/51466437
tags question: http://stackoverflow.com/q/51436746
tags question: http://stackoverflow.com/q/51465526
tags question: http://stackoverflow.com/q/51436007
tags question: http://stackoverflow.com/q/51457084
tags question: http://stackoverflow.com/q/51375587
tags question: http://stackoverflow.com/q/51469638
tags question: http://stackoverflow.com/q/51453506
tags question: http://stackoverflow.com/q/51480396
tags question: http://stackoverflow.com/q/51400185
tags question: http://stackoverflow.com/q/51361402
tags question: http://stackoverflow.com/q/51395070
tags question: http://stackoverflow.com/q/51478595
tags question: http://stackoverflow.com/q/51341613
tags question: http://stackoverflow.com/q/51462264
tags question: http://stackoverflow.com/q/51396366
tags question: http://stackoverflow.com/q/51380832
tags question: http://stackoverflow.com/q/51410692
tags question: http://stackoverflow.com/q/51334491
tags question: http://stackoverflow.com/q/51382664
tags question: http://stackoverflow.com/q/51337944
tags question: http://stackoverflow.com/q/51463383
tags question: http://stackoverflow.com/q/51479054
tags question: http://stackoverflow.com/q/51447071

http://stackoverflow.com/comment/89743087
comment on: http://stackoverflow.com/q/51385215
score: 0
type: Comment
type: QuestionComment
has text: @revo you are right

http://stackoverflow.com/q/51360098
has comment: http://stackoverflow.com/comment/89692423
downvote count: 0
has title: Can I reference a dict value on dict creation?
linked to: http://stackoverflow.com/q/22468401
possible better answer: http://stackoverflow.com/a/73733481
favorite count: 0
has answer: http://stackoverflow.com/a/73733481
accepted answer: http://stackoverflow.com/a/51360134
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
tagged with: python-3.x
has body: I have this dictionary and I want to set the value of netdev["ipv6"]["addr"] with the former declared netdev["ipv6"]["prefix"]. Is there any elegant way to do this "on-the-fly" or do I have to do this outside of the dict declaration with the known mechanisms like dict.update(), ... ? net_dev = { "link_name": "eth0", "ipv4": { "address": "10.80.0.1", "mask": "255.255.255.0", }, "ipv6": { "prefix": "2001:db8:0:1::", "addr": &lt;HERE_THE_PREFIX_IS_USED&gt; + "1234:1", "mask": "64", "prefix_range": "2001:db8:0:100::", } }
upvote count: 3
type: Question
score: 3
has answer: http://stackoverflow.com/a/51360134
has comment: http://stackoverflow.com/comment/89692398
has comment: http://stackoverflow.com/comment/89692458
has comment: http://stackoverflow.com/comment/89692498
answer count: 2

http://stackoverflow.com/comment/89673364
type: QuestionComment
comment on: http://stackoverflow.com/q/51350267
has text: What do you mean to "approximate the probability distribution **between** these two groups"? Also, which event are you measuring? Time required to churn? If they churn or remain?
type: Comment
score: 1

modelica
tag name: modelica
type: Tag
tags question: http://stackoverflow.com/q/51444291

http://stackoverflow.com/a/51521476
type: Answer
accepted answer of: http://stackoverflow.com/q/51419371
downvote count: 0
score: 1
has body: Just to close this question: I figured out the problem. It was because of not calling PyObject_Del() as the last action of the destructor.
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51419371

http://stackoverflow.com/a/72197989
answers question: http://stackoverflow.com/q/51340386
score: 0
type: Answer
has body: this is what i did, if you have library problem please handle it in the following way cmd: pip3 uninstall googletrans cmd: pip3 install googletrans==3.1.0a0 from googletrans import Translator translator = Translator() text = "How to convert some text to multiple languages" destination_language = { "spanish": "es", "chinese": "zh-CN", "vietnamese": "vi", "korean": "ko", "japanese": "ja", "french": "fr", } for key, value in destination_language.items(): trans = translator.translate(text, dest=value).text print(trans)

http://stackoverflow.com/comment/89831816
comment on: http://stackoverflow.com/q/51429807
score: 0
has text: That doesn't seem to match what your code does. Also `600-650` is just the literal `(-50)`. It's important to know how you're calling the function.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51465748
answers question: http://stackoverflow.com/q/51465031
has body: np.select() and np.where() are the way to go. One more option, can also do df.loc[df.A == 1, 'D'] = 1 - df.B df.loc[df.A == 0, 'D'] = 1 - df.C
score: 0
type: Answer

http://stackoverflow.com/comment/89769007
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51398758
has text: No problem :) You should be able to select the preferred answer as the author.
type: AnswerComment

http://stackoverflow.com/comment/89701854
type: QuestionComment
has text: A good practice is to avoid posting sensitive personal information, like in your case - the client_id. Try to sanitize the code and logs before posting them on SO. Regarding your question, I am slightly confused as to what the issue is. Are you following some documentation for this project? What do the logs in Stackdriver show when you attempt to authenticate and see the error in the browser? Please keep in mind to sanitise the log information.
comment on: http://stackoverflow.com/q/51342244
score: 0
type: Comment

http://stackoverflow.com/comment/89665085
type: Comment
comment on: http://stackoverflow.com/a/51346007
score: 0
type: AnswerComment
has text: @user2357112 But PM said something about number being too big to fit in a float.

http://stackoverflow.com/comment/89857919
score: 0
type: AnswerComment
type: Comment
has text: this just throws an error: Traceback (most recent call last): File "test.py", line 16, in <module> data = [x for x in json_data if not x['ACTION'] == 'REMOVE'] TypeError: string indices must be integers, not str
comment on: http://stackoverflow.com/a/51432092

http://stackoverflow.com/q/51404310
has answer: http://stackoverflow.com/a/51404456
has answer: http://stackoverflow.com/a/51404515
downvote count: 0
possible better answer: http://stackoverflow.com/a/51404456
favorite count: 0
has answer: http://stackoverflow.com/a/51404548
tagged with: python
tagged with: regex
answer count: 4
type: AnsweredQuestion
score: 3
upvote count: 3
type: Question
accepted answer: http://stackoverflow.com/a/51404548
has answer: http://stackoverflow.com/a/51404734
has body: I'm trying to write a regexp which matches on two groups of digits or 100% separated with 'x' char. Like (first group)x(second group). And "100%" should be captured as is, with percent symbol. And percent sign is allowed only after 100. For example: 100x100 - OK 100%x100 - OK 99x99 - OK 99%x100 - not OK 99x99% - not OK Here is my approach: s = '100%x99%' # this should be failed match = re.match(r'(100%|\d+(?!%))x(100%|\d+(?!%))', s) if match: x = match.group(1) y = match.group(2) I expect that y will be none and match would be failed, because '99%' is prohibited. But with my regexp I get x = 100% and y = 9. How can I fix my regex?
has title: Regular expression that matches number or 100%, but not 99%

http://stackoverflow.com/q/51479809
has title: python: What does nan_policy=omit do for scipy.stat.spearmanr
answer count: 2
downvote count: 0
has body: scipy.stats.spearmanr([1,2,3,4,1],[1,2,2,1,np.nan],nan_policy='omit') it will give a spearman correlation of 0.349999 My understanding is that nan_policy ='omit' will discard all the pairs which have nan. If that's the case, the results should be the same as scipy.stats.spearmanr([1,2,3,4],[1,2,2,1]) However, it gives a correlation of 0.235702. Why are they different? Is my understand of nan_policy ='omit' corrent?
favorite count: 0
has answer: http://stackoverflow.com/a/74427746
has answer: http://stackoverflow.com/a/53382910
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
tagged with: scipy
type: Question

http://stackoverflow.com/comment/89684864
type: Comment
type: QuestionComment
has text: As a workaround you could try with skvideo first for each video, and if it fails cath the error and user the slower opencv ?
score: 0
comment on: http://stackoverflow.com/q/51355363

http://stackoverflow.com/q/51353314
tagged with: pandas
downvote count: 0
has title: Python: Plot all categorical subset combinations in one figure
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
has body: I want to generate plots showing how a rate changes, on average, across time for various groups and subgroups. I'm able to do it by hand, creating each grouping, defining each y-value set, and calling each plot manually. The trouble is, doing this for all combinations of groups/subgroups is impractical. Yet I'm not sure how to generalize the procedure. My data has a year, several categorical variables, and a numeric rate. It looks something like this, although in reality there are many more categorical variables: df.head() Out [33]: year gender race state rate 0 2015 F White AL 0.01 1 2013 F White NC 0.48 2 2013 F White IN 0.07 3 2013 M White NJ 0.95 4 2013 F White NY 0.09 I want to overlay the various groups and subgroups: Is there a more elegant way of subsetting/automating the generation of this/these plots? import pandas as pd import matplotlib.pyplot as plt raw_data = {'year' : [2015 , 2013 , 2013 , 2013 , 2013 , 2013 , 2014 , 2013 , 2013 , 2013 , 2017 , 2013 , 2016 , 2017 , 2016 , 2015 , 2014 , 2014 , 2013 , 2013 , 2017 , 2014 , 2013 , 2016 , 2014 , 2016 , 2015 , 2013 , 2013 , 2013 , 2013 , 2013 , 2013 , 2013 , 2013 , 2013 , 2013 , 2013 , 2013 , 2013 , 2013 , 2013 , 2013 , 2017 , 2015 , 2015 , 2013 , 2013 , 2014] , 'gender' : ['F' , 'F' , 'F' , 'M' , 'F' , 'F' , 'F' , 'M' , 'F' , 'M' , 'F' , 'M' , 'F' , 'M' , 'M' , 'M' , 'M' , 'M' , 'M' , 'M' , 'F' , 'M' , 'F' , 'M' , 'M' , 'M' , 'F' , 'M' , 'F' , 'F' , 'F' , 'M' , 'F' , 'M' , 'F' , 'F' , 'F' , 'F' , 'M' , 'M' , 'M' , 'F' , 'M' , 'M' , 'F' , 'M' , 'F' , 'M' , 'F'] , 'race' : ['White' , 'White' , 'White' , 'White' , 'White' , 'White' , 'White' , 'Black' , 'White' , 'White' , 'White' , 'White' , 'White' , 'White' , 'White' , 'White' , 'Black' , 'White' , 'White' , 'White' , 'White' , 'White' , 'White' , 'White' , 'Hispanic' , 'White' , 'Multiple' , 'White' , 'White' , 'Black' , 'Asian/Hawaii/PI' , 'Asian/Hawaii/PI' , 'Black' , 'Black' , 'Black' , 'Hispanic' , 'Black' , 'Black' , 'Black' , 'Black' , 'White' , 'Wh…
type: Question
has answer: http://stackoverflow.com/a/51353431
has answer: http://stackoverflow.com/a/51353572
tagged with: automation
tagged with: matplotlib
answer count: 2

http://stackoverflow.com/q/51362099
has answer: http://stackoverflow.com/a/51362289
downvote count: 1
possible better answer: http://stackoverflow.com/a/51363522
type: AnsweredQuestion
has title: Get a group of column values from pandas dataframe on condition
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/51362289
favorite count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/89696548
has answer: http://stackoverflow.com/a/51363522
score: 0
has body: i have a dataframe: item B val 1 qw 0 2 ss 0.9 3 ds -0.8 4 sd 0.4 5 dd 0.9 6 ll 0.4 7 wr 0.3 8 rt -0.4 9 qq 0.2 10 ee 0.6 In the values column the first row is 0, and then followed by a positive number 0.9 I want to find the group of items where the consecutive values are positive. For eg: items in groups = [1,2] ## consecutive positive val [4,5,6,7] and [9,10] Final output I am looking forward is [ [1,2] , [4,5,6,7] , [9,10] ] Is this possible without iterating the dataframe in for loop?
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/89782946
has text: The answer below is good, but I want to say that in general, if you will be accessing elements in an array that are not the specific index you're currently on, it is not good practice to use that kind of for-loop, and you will probably want to use a ranged for-loop. In general.
comment on: http://stackoverflow.com/q/51405785
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51400638
tagged with: error-handling
has answer: http://stackoverflow.com/a/51400852
has title: Python: WSGI crashing with no error
answer count: 1
tagged with: wsgi
type: UnansweredQuestion
type: Question
has body: I'm currently developing a web service in WSGI, but the script crashes on the line where I am executing my query. I'm using the exact same code as other working web services, and even simplified my query for testing purposes, but to no avail. The real problem is that while I can manually print stuff to the error_log specified in my VirtualHost, there is no log for the error that occurs when the script crashes. All I know now is that the print before the line is written to the log, but the print after isn't. How can I print the error to the log and get to the root of my problem? The code (simplified a bit): webservice.wsgi: def application(environ, start_response): ENV = environ.get('APPLICATION_ENV', 'DEV') connector = ConnectorObj(confParams['dbname'], confParams['host'], confParams['port'], confParams['user'], confParams['password']) method = environ.get('REQUEST_METHOD', '') if (method == 'POST'): content_body = json.loads(request_body) han = HandlerObj(connector) res = han.getBld() start_response('200 OK', [('content-type', 'application/json; charset=utf-8'), ('Access-Control-Allow-Origin', '*')]) return(res) getBld: def getBld(self): print "execute query" self.cur.execute(""" SELECT * FROM adr.bld """) print "after executing query" After doing the post call, I can see that "execute query" is being printed to the error_log, but then it just crashes and doesn't get to "after executing query". Again, I'm not asking what is wrong with my actual code (I would have to provide much more in order to make sense of it), but simply how I can get an error trace somehow so I can start to debug it myself..
tagged with: python
score: 0

odoo
tags question: http://stackoverflow.com/q/51445374
tags question: http://stackoverflow.com/q/51364741
tags question: http://stackoverflow.com/q/51420925
tags question: http://stackoverflow.com/q/51369835
tags question: http://stackoverflow.com/q/51469680
tags question: http://stackoverflow.com/q/51355052
tags question: http://stackoverflow.com/q/51446084
tags question: http://stackoverflow.com/q/51406268
tags question: http://stackoverflow.com/q/51329505
type: Tag
tags question: http://stackoverflow.com/q/51344282
tags question: http://stackoverflow.com/q/51347120
tags question: http://stackoverflow.com/q/51384272
tags question: http://stackoverflow.com/q/51482151
tags question: http://stackoverflow.com/q/51376820
tag name: odoo

http://stackoverflow.com/comment/89838070
comment on: http://stackoverflow.com/q/51418002
score: 0
has text: For any image processing operation to take place between matrices, they must be of same size, It is just like you are trying to do `"5" + 2`, which would give you error, as the data type(s) for the `+` operands are not same. Similarly OpenCV raises error in case the dimensions of matrices are not same, To prevent this you can either resize the matrices or do adaptive padding for aligning width first or height first.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89685368
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51356493
has text: Can you show us what you have tried ?

http://stackoverflow.com/a/51458516
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51458478
type: Answer
accepted answer of: http://stackoverflow.com/q/51458478
has body: Your new_file is a list of found matches in the file (that you fill with match.group() + newline). You may check if there is a \[\d+] match in a line and output the line into the new file: import re reg = re.compile(r'\[\d+]') # Matches a [ char, followed with 1+ digits and then ] with open('prova.txt', 'w') as f: # open file for writing with open('testoestratto.txt','r',encoding='UTF-8') as myFile: # open file for reading for line in myFile: # read myFile line by line if reg.search(line): # if there is a match anywhere in a line f.write(line) # write the line into the new file
upvote count: 1

scope
tags question: http://stackoverflow.com/q/51423517
tag name: scope
tags question: http://stackoverflow.com/q/51337842
tags question: http://stackoverflow.com/q/51359018
type: Tag
tags question: http://stackoverflow.com/q/51461000
tags question: http://stackoverflow.com/q/51432553

http://stackoverflow.com/q/51388690
type: Question
has title: How to track down NaN in tensorflow
tagged with: debugging
has comment: http://stackoverflow.com/comment/89752058
score: 6
linked to: http://stackoverflow.com/q/39051451
downvote count: 0
tagged with: nan
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 6
answer count: 0
has body: I have a VAE operating on images. If I use cross entropy, L1 or L2 loss, everything works fine, always. If I use MS-SSIM loss, it works fine on images &lt;=128px, but I get NaNs (after few iterations, usually before 5K iterations) on images >128px. No problems with images of any size using L1, L2 or CE loss, and no problems with MS-SSIM when using images &lt;=128px. My question is two fold: where is this NaN coming from in this particular case. The code itself looks safe to me. (unless it's a vanishing gradient problem). how does one debug a NaN in tensorflow to track it down. I had a look at the debugger but couldn't see what to do with it Details: Loss function is constructed like this: if loss_fn == 0: self.gen_loss = tf.reduce_mean ( msa.tf.mmath.ce_loss(msa.tf.mmath.lmap(self.x, input_range, (0,1)), msa.tf.mmath.lmap(self.y, output_range, (0,1))) )# / data_size elif loss_fn == 1: self.gen_loss = self.l1_loss elif loss_fn == 2: self.gen_loss = self.l2_loss elif loss_fn == 3: self.gen_loss = 1.0 - tf.reduce_mean( msa.tf.ssim.ms_ssim(self.x, self.y) ) # see end of post for ms_ssim self.kl_loss = tf.reduce_mean ( msa.tf.mmath.kl_loss(self.z_mu, self.z_log_sigma_sq) ) self.loss = kl_weight * self.kl_loss + self.gen_loss And like I said, problem only happens when loss_fn==3. The full error is below, but I know it's the gen_loss, because I can see that it becomes nan without warning, sometimes quite early on (here, on the 9th iteration): i:1 e:0.006 | gen_loss:0.9598 kl_loss:0.0000 l1_loss:0.5096 l2_loss:0.3638 loss:0.9598 i:2 e:0.011 | gen_loss:0.9582 kl_loss:0.0000 l1_loss:0.5017 l2_loss:0.3555 loss:0.9582 i:3 e:0.017 | gen_loss:0.9633 kl_loss:0.0000 l1_loss:0.5131 l2_loss:0.3693 loss:0.9633 i:4 e:0.022 | gen_loss:0.9583 kl_loss:0.0000 l1_loss:0.4945 l2_loss:0.3424 loss:0.9583 i:5 e:0.028 | gen_loss:0.9490 kl_loss:0.0000 l1_loss:0.4848 l2_loss:0.3359 loss:0.9490 i:6 e:0.033 | gen_loss:0.9493 kl_loss:0.0000 l1_loss:0.5229 l2_loss:0.3786 loss:0.9493 i:7 e:0.039 | gen_…
tagged with: tensorflow

http://stackoverflow.com/comment/89894150
has text: Can you please post the error message
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51462538

macos
tags question: http://stackoverflow.com/q/51403736
tags question: http://stackoverflow.com/q/51412000
tags question: http://stackoverflow.com/q/51388985
tags question: http://stackoverflow.com/q/51337939
tags question: http://stackoverflow.com/q/51377403
tags question: http://stackoverflow.com/q/51468511
tags question: http://stackoverflow.com/q/51345817
tags question: http://stackoverflow.com/q/51334492
tags question: http://stackoverflow.com/q/51469775
tags question: http://stackoverflow.com/q/51452106
tags question: http://stackoverflow.com/q/51343325
tags question: http://stackoverflow.com/q/51452157
tags question: http://stackoverflow.com/q/51439810
tags question: http://stackoverflow.com/q/51395744
type: Tag
tags question: http://stackoverflow.com/q/51447619
tags question: http://stackoverflow.com/q/51373063
tag name: macos

http://stackoverflow.com/q/51370281
duplicate of: http://stackoverflow.com/q/3033329
type: Question
score: 0
has comment: http://stackoverflow.com/comment/89713077
type: UnansweredQuestion
tagged with: python
has title: LinkedList on python and c++
has body: I am trying to implement linkedlist on python, which i have finished on c++. just for the function insertHead. i basically used the same algorithm. c++ template &lt;class T&gt; int L1List&lt;T&gt;::insertHead(T&amp;&amp; a){ L1Item&lt;T&gt; *p = new L1Item&lt;T&gt;(std::move(a)); p-&gt;pNext = _pHead; _pHead = p; _size++; return 0; } python def insertHead(self, _data): pNew = LLnode(_data) pNew.pNext = self.pHead self.pHead = pNew self.length += 1 return True i try to insert 10 million value of int. for c++ i get like 0.7s, while python run it for like 28s. why there is a huge difference??
has comment: http://stackoverflow.com/comment/89712872
linked to: http://stackoverflow.com/q/3033329
tagged with: c++
tagged with: linked-list
answer count: 0

pypi
tags question: http://stackoverflow.com/q/51451966
tags question: http://stackoverflow.com/q/51478481
tags question: http://stackoverflow.com/q/51412615
type: Tag
tags question: http://stackoverflow.com/q/51469451
tags question: http://stackoverflow.com/q/51429740
tags question: http://stackoverflow.com/q/51354856
tags question: http://stackoverflow.com/q/51398638
tags question: http://stackoverflow.com/q/51446698
tag name: pypi

http://stackoverflow.com/q/51389995
linked to: http://stackoverflow.com/q/12201577
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51390270
downvote count: 0
has comment: http://stackoverflow.com/comment/89752199
has title: Emphasize the blue in an image
score: 1
tagged with: matplotlib
has body: I'm using matplotlib to do it but for some reason, my code creates an unexpected image. import numpy as np import matplotlib.pyplot as plt from scipy.misc import imread,imsave # original image image1=imread('img.jpg') plt.imshow(image1) plt.show() # empesize the blue in that image plt.imshow(image1*[0.95,0.95,1]) plt.show() result: The top image is the original one and the second (which is shown) is the unexpected result. It seems that no matter what values I enter to the vector, I get the same strange result. Why?
tagged with: image-processing
type: Question
tagged with: image
linked to: http://stackoverflow.com/q/42044259
upvote count: 1
has comment: http://stackoverflow.com/comment/89752339
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51390270

http://stackoverflow.com/comment/89758135
type: QuestionComment
has text: Could you please reduce your question to the points which are essential to the problem?
score: 0
comment on: http://stackoverflow.com/q/51392915
type: Comment

http://stackoverflow.com/q/51482381
answer count: 3
tagged with: pandas
tagged with: datetime
favorite count: 0
has comment: http://stackoverflow.com/comment/89933918
has answer: http://stackoverflow.com/a/51482608
has title: pandas/python date_range constrictions of 9:30-16:00
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89933841
type: AnsweredQuestion
has body: Currently I have a data frame with this line of code that gives me Date and Time as follows: ts = pd.date_range(start=pd.to_datetime(startDate,format='%m-%d-%Yt%H:%M:%S'),periods=len(df),freq='1min') This gives the date range for the dataframe in minute intervals and it runs on a 24hr time frame. I was wondering how to constrict the time frame from 9:30-16:00 (9:30AM-4:00PM) and then move to the next day once it hits 4:00PM. My dataframe right now: df = Time Open High Low Close Volume Date 2018-03-20 09:30:00 93.05 93.32 93.01 93.12 524939 2018-03-20 09:31:00 93.68 93.69 93.53 93.54 77138 2018-03-20 09:32:00 92.82 92.90 92.82 92.88 43388 ... ... ... ... ... ... ... 2018-03-20 15:56:00 93.65 93.71 93.64 93.69 44175 2018-03-20 15:57:00 93.12 93.29 93.00 93.27 166822 2018-03-20 15:58:00 93.28 93.36 93.27 93.33 70954 2018-03-20 15:59:00 93.33 93.43 93.30 93.34 94118 2018-03-20 16:00:00 93.34 93.53 93.34 93.44 75326 2018-03-20 16:01:00 93.43 93.45 93.30 93.30 53790 and I would like the following dataframe to be my result updated_df = Time Open High Low Close Volume Date 2018-03-20 09:30:00 93.05 93.32 93.01 93.12 524939 2018-03-20 09:31:00 93.68 93.69 93.53 93.54 77138 2018-03-20 09:32:00 92.82 92.90 92.82 92.88 43388 ... ... ... ... ... ... ... 2018-03-20 15:56:00 93.65 93.71 93.64 93.69 44175 2018-03-20 15:57:00 93.12 93.29 93.00 93.27 166822 2018-03-20 15:58:00 93.28 93.36 93.27 93.33 70954 2018-03-20 15:59:00 93.33 93.43 93.30 93.34 94118 2018-03-20 16:00:00 93.34 93.53 93.34 93.44 75326 2018-03-21 09:30:00 93.43 93.45 93.30 93.30 53790 I used df['Date'] = ts.date df['Time'] = ts.time to create the Date and Time columns, set Date as the index and Time as the first column.
has answer: http://stackoverflow.com/a/51483112
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51482608
possible better answer: http://stackoverflow.com/a/51482581
has answer: http://stackoverflow.com/a/51482581
score: 0

http://stackoverflow.com/a/51354844
score: 3
downvote count: 0
has body: Pandas solution is also specify categories is expected order: cats= ['&lt;10', '10-90' , '100-200','500-800', '1000-4999', '10000+'] y = pd.Categorical(train['size'],ordered=True, categories=cats) print (y) [10-90, &lt;10, 100-200, 10-90, 500-800, 10000+, &lt;10, 1000-4999] Categories (6, object): [&lt;10 &lt; 10-90 &lt; 100-200 &lt; 500-800 &lt; 1000-4999 &lt; 10000+]
type: Answer
has comment: http://stackoverflow.com/comment/89693866
has comment: http://stackoverflow.com/comment/89682245
upvote count: 3
has comment: http://stackoverflow.com/comment/89682209
has comment: http://stackoverflow.com/comment/89694904
has comment: http://stackoverflow.com/comment/89682264
has comment: http://stackoverflow.com/comment/89694184
answers question: http://stackoverflow.com/q/51354805

http://stackoverflow.com/comment/89907998
has text: Sets store the whole shebang. Just make your hash be an object whose`__hash__` method just returns `self`
comment on: http://stackoverflow.com/q/51469825
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/89793485
has text: Thank you so much! Your previous answer was also very clear and detailed; I was only confused because I was not sure what the Matlab code was really trying to do. This was very helpful to my work!
comment on: http://stackoverflow.com/a/51410140
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89873198
comment on: http://stackoverflow.com/q/51451482
has text: The tag was removed, but in C `float` is like `double` but with less range and precision.
type: Comment
type: QuestionComment
score: 0

operand
tags question: http://stackoverflow.com/q/51409824
type: Tag
tag name: operand

http://stackoverflow.com/comment/89717415
has text: You can easily jump to [the commit that added `ByteString`](https://github.com/python/cpython/commit/d05eb0043e597cf2d5c429d0e554fd39364e36b0) to see the checkin comment, though.
type: Comment
comment on: http://stackoverflow.com/q/51372801
type: QuestionComment
score: 1

http://stackoverflow.com/a/68657068
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/125314468
has body: This method can be used to commit tags or files. You may also wish to consider using the CI CD variable API to store cross-build persistent data if it does not have to be committed to the repo https://docs.gitlab.com/ee/api/project_level_variables.html https://docs.gitlab.com/ee/api/group_level_variables.html ACCESS_TOKEN below is a variable at the repo or an upbound group level that contains a token that can write to the target repos. Since maintainer can see these, it is best practice to create tokens on special API users who are least privileged for just what they need to do. write_to_another_repo: before_script: - git config --global user.name "${GITLAB_USER_NAME}" - git config --global user.email "${GITLAB_USER_EMAIL}" script: - | echo "This CI job demonstrates writing files and tags back to a different repository than this .gitlab-ci.yml is stored in." OTHERREPOPATH="guided-explorations/gitlab-ci-yml-tips-tricks-and-hacks/commit-to-repos-during-ci/pushed-to-from-another-repo-ci.git" git clone https://gitlab-ci-token:${CI_JOB_TOKEN}@$CI_SERVER_HOST/$OTHERREPOPATH cd pushed-to-from-another-repo-ci CURRENTDATE="$(date)" echo "$CURRENTDATE added a line" | tee -a timelog.log git status git add timelog.log # "[ci skip]" and "-o ci-skip" prevent a CI trigger loop git commit -m "[ci skip] updated timelog.log at $CURRENTDATE" git push -o ci-skip http://root:$ACCESS_TOKEN@$CI_SERVER_HOST/$OTHERREPOPATH HEAD:master #Tag commit (can be used without commiting files) git tag "v$(date +%s)" git tag git push --tags http://root:$ACCESS_TOKEN@$CI_SERVER_HOST/$OTHERREPOPATH HEAD:master
downvote count: 0
answers question: http://stackoverflow.com/q/51420002
type: Answer
has comment: http://stackoverflow.com/comment/127616481

http://stackoverflow.com/q/51448305
has comment: http://stackoverflow.com/comment/89867187
score: 1
has comment: http://stackoverflow.com/comment/89868730
has comment: http://stackoverflow.com/comment/89867576
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/51448556
has title: Should samples from np.random.normal sum to zero?
has body: I am working on the motion model of a robot. In every time step, the robot's motion is measured, then I sample the normal distribution with the measurement as the mean and a small sigma value for covariance in order to simulate noise. This noisy motion is then added to the robot's previous state estimate. But when I keep the robot still, these noisy measurements seem to accumulate and the robot "thinks it's moving." Shouldn't these random samples not accumulate, but sum to zero? In other words, would you expect the following to be true: 0 ~ np.sum([np.random.normal(0, 0.1) for _ in range(1000)]) I have tried writing out the above in an explicit loop and seeding the random number generator with a different number before taking every sample, but the sums still deviate far from zero. Is this simply a limitation of random number generators, or am I misunderstanding the fact(?) that many samples from the normal distribution should sum to zero?
tagged with: statistics
has answer: http://stackoverflow.com/a/51448556
tagged with: robotics
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/89867240
favorite count: 0
tagged with: python
tagged with: normal-distribution
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/a/51437224
downvote count: 0
score: 3
accepted answer of: http://stackoverflow.com/q/51437111
type: AcceptedAnswer
has body: To (shallow) copy a DataFrame you can just assign it to a new variable: import pyspark.sql.functions as F import pandas as pd # Sample data df = pd.DataFrame({'x1': [1,2,3] }) df = spark.createDataFrame(df) df2 = df df2 = df2.withColumn('x1', F.col('x1') + 1) print('df:') df.show() print('df2:') df2.show() Output: df: +---+ | x1| +---+ | 1| | 2| | 3| +---+ df2: +---+ | x1| +---+ | 2| | 3| | 4| +---+ As you can see, after copying df to df2 and mutating the copy, our original DataFrame df remains unchanged.
answers question: http://stackoverflow.com/q/51437111
has comment: http://stackoverflow.com/comment/89845001
has comment: http://stackoverflow.com/comment/89845173
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/89844693

http://stackoverflow.com/a/51444743
type: Answer
upvote count: 1
score: 1
has body: For small enough files you can prepare the file contents as a list or a string and then write it to the file, e.g.: from pathlib import Path with Path('in-file').open() as in_file, Path('out-file').open('r+') as out_file: lines = [] for line1, line2 in zip(in_file.readlines()[1:], out_file.readlines()): line = '{} {}\n'.format(line2.rstrip(), line1.split()[-1]) lines.append(line) out_file.seek(0) # rewind the output file to the beginning out_file.writelines(lines) For bigger files consider using a backup file as stdlib's fileinput module does.
answers question: http://stackoverflow.com/q/51444407
downvote count: 0
has comment: http://stackoverflow.com/comment/89860318

http://stackoverflow.com/a/51333896
has body: There are two things you have to understand here. First: x or y If x is truthy, it has the value of x (without even evaluating y, so 23 or launch_nukes() doesn't launch the nukes). Otherwise, it has the value of y. Or, as the docs put it: The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned. Notice that it uses the word "true" here, not the value True. This is a bit confusing (even more so if you're talking out loud, or typing in ASCII without formatting…), which is why everyone says "truthy". So, what do "truthy" and "falsey" mean?1 "x is truthy" does not mean x == True, it means bool(x) == True. "x is falsey" does not mean x == False, it means bool(x) == False. For all builtin and stdlib types: False is falsey. None is falsey. Numeric zero values are falsey. Empty containers are falsey. Everything else is truthy. Notice that None and empty containers are falsey, but they're not equal to False. By convention, third-party types (including types that you define2) should follow the same rules. But sometimes there are good reasons not to. (For example, a NumPy array is neither truthy nor falsey.3) This is covered loosely in the same docs section: In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. User-defined objects can customize their truth value by providing a __bool__() method. The exact details for all builtin types are buried in the standard type hierarchy, which is where you learn things like whether bytes is covered by "strings and containers" (yes) or whether there's anything special about NotImplemented (nope, it's truthy). So, let's go through your examples: [1, 2] or ["hello"] Since [1, 2] is a…
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/51333688
upvote count: 3
type: Answer

http://stackoverflow.com/a/51434144
type: AcceptedAnswer
downvote count: 0
score: 1
has body: Say you have some text text= '''Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec rhoncus est augue, eget vulputate elit vulputate ut. Maecenas et tellus eget enim consectetur facilisis ut vitae ante. Donec ut feugiat elit.'''' You can use print and time.sleep for a brief period so it'll seem like it is being typed at the time. You can use some random sampling from an interval for the sleep to make it seem not so 'scripted' import random for char in text: print(char,end='') time.sleep(random.uniform(0.01, 0.05))
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/89873210
answers question: http://stackoverflow.com/q/51434105
accepted answer of: http://stackoverflow.com/q/51434105

http://stackoverflow.com/comment/89811989
type: Comment
has text: Yes updating id with integer this will give you an error. Please see my updated reply and let me know if this works.
comment on: http://stackoverflow.com/a/51419172
type: AnswerComment
score: 0

xml-parsing
tags question: http://stackoverflow.com/q/51414920
tag name: xml-parsing
tags question: http://stackoverflow.com/q/51337274
tags question: http://stackoverflow.com/q/51363720
type: Tag
tags question: http://stackoverflow.com/q/51389981
tags question: http://stackoverflow.com/q/51479952
tags question: http://stackoverflow.com/q/51395399
tags question: http://stackoverflow.com/q/51369041

http://stackoverflow.com/q/51401442
upvote count: 9
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/90204381
downvote count: 0
answer count: 1
has title: Covering 2D plots with 3D surface
has comment: http://stackoverflow.com/comment/90204543
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51405554
tagged with: python
has body: I am attempting to take many xz plots, each at various y values, and overlay a surface. I have seen many examples of how to plot 3D surfaces in python, but aside from this post, nothing seems to match my inquiry very closely. The image of what I need to do is shown below (Note: ignore the "constant x" - this is due to a more complicated variable layout than I explained here): My code is as follows, and simply takes data and plots each of the individual Magnitude vs. Frequency plots (xz plots): import numpy as np import glob, os import codecs import re import matplotlib.pyplot as plt #------------------------------------------------------------------------- os.chdir('C:/Users/elarrick/Desktop/201807161056') dataFolders = glob.glob('./*.ltda') dataLines = [] freq = [] OpenLoopMag = [] OpenLoopPhase = [] for item in dataFolders: name, ext = os.path.splitext(item) if ext == '.ltda': print item dataLines = [] f = codecs.open(item, encoding='utf-8') for line in f: if ' ' in line: dataLines.append(line) #All lines with are an entry in dataLines #print "\n\n", dataLines #break for item in dataLines: item = re.sub(" ", "", item) item = re.sub("True ", "", item) item = item.replace(",", "") splitItem = item.split() #print splitItem freq.append(float(splitItem[0])) OpenLoopMag.append(float(splitItem[1])) OpenLoopPhase.append(float(splitItem[2])) print "Frequencies: ", freq print "\n\n\n\n\n\nOpenLoopMag: ", OpenLoopMag # This is where I will make the plots for each x,y position name = name.strip(".\\") name = name.replace("-","NEG") plt.semilogx(freq, OpenLoopMag) #plt.plot(freq, OpenLoopMag) plt.xlabel("Frequency, (Hz)") plt.ylabel("Magnitude") plt.title("{0}".format(name)) plt.xlim([20,2000]) #plt.ylim([-43.2,10.9]) ticks = [20,40,70,100,200,400,700,1000,2000] plt.xticks(ticks,ticks) plt.savefig("plot_{0}.png".format(name)) #________ Clear the values for the next data folder_______# freq = [] OpenLoopMag = [] OpenLoopPhase = [] break else: print "Something went wrong - check…
tagged with: plot
tagged with: mplot3d
tagged with: matplotlib-3d
linked to: http://stackoverflow.com/q/46949455
score: 9
type: Question

http://stackoverflow.com/q/51410733
duplicate of: http://stackoverflow.com/q/2501208
type: Question
has answer: http://stackoverflow.com/a/51415795
has comment: http://stackoverflow.com/comment/137001919
score: 2
answer count: 1
downvote count: 0
has body: I try to understand why my pasting in my terminal (linux) in my python interpreter put double indent every line for example : if I paste these lines : def function(string): final = '' for i in string: try: final += str(int(i)) except ValueError: return int(final) I'll get this in my terminal : ent&gt;&gt;&gt; def function(string): ... File "&lt;stdin&gt;", line 2 ^ IndentationError: expected an indented block &gt;&gt;&gt; final = '' File "&lt;stdin&gt;", line 1 final = '' ^ IndentationError: unexpected indent &gt;&gt;&gt; &gt;&gt;&gt; for i in string: File "&lt;stdin&gt;", line 1 for i in string: ^ IndentationError: unexpected indent &gt;&gt;&gt; And more and more... because when there is a for or any instruction that needs a tab, it return it directly instead to wait for the next instruction,so it rise an IndentationError: And I realize that if I paste this for exemple : import mathimport threading it will paste like this in my terminal : &gt;&gt;&gt; import math &gt;&gt;&gt; import threading &gt;&gt;&gt; I didn't have from the beginin, so any idea ? because it was impossible to find my answer in internet..
favorite count: 0
linked to: http://stackoverflow.com/q/2501208
has comment: http://stackoverflow.com/comment/89793047
upvote count: 2
type: UnansweredQuestion
tagged with: python
has title: how to desactivate double indent when I paste the code in a python terminal
tagged with: paste

http://stackoverflow.com/q/51341882
tagged with: doc2vec
has comment: http://stackoverflow.com/comment/89657559
has comment: http://stackoverflow.com/comment/89657999
has comment: http://stackoverflow.com/comment/89657255
score: 0
has body: I am trying to make predictions on a dataset based on some pre-defined data (tweets and categories that the tweets belong to, labeled 1-16) that I have built a model in with doc2vec and trained on random forest classifier. I am confused about what format I need to put my data into before I call clf.predict(tweet) on it. import csv from sklearn.ensemble import RandomForestClassifier import pandas as pd import itertools from gensim import utils from gensim.models import Doc2Vec import gensim import numpy as np #just making the object to put into gensim's doc2vec class LabeledLineSentence(object): def __init__(self, doc_list, labels_list): self.labels_list = labels_list self.doc_list = doc_list def __iter__(self): for t, l in itertools.izip(self.doc_list, self.labels_list): #change here t = nltk.word_tokenize(t) #end of change yield gensim.models.doc2vec.LabeledSentence(t, [l]) #predefined tweets = ["a tweet", "another tweet", ... , "a thousandth tweet"] labels = [1, 1, ... , 16] #what category the tweet belongs to training_data = LabeledLineSentence(tweets, labels_list) #build the doc2vec model model = Doc2Vec(vector_size=100, min_count=1, dm=1) model.build_vocab(training_data) model.train(training_data, total_examples=model.corpus_count, epochs=20) #put tweets into classifier train_tweets = [] for i in range(len(tweets)): label = labels_list[i] train_tweets.append(model[label]) #have to convert to numpy array because that is what clf takes train_tweets = np.array(train_tweets) train_labels = np.array(labels_list) #fit classifier clf = RandomForestClassifier().fit(train_tweets, train_labels) #this is the data i am trying to classify into labels test_data = ["an unseen tweet", "another unseen tweet", ... , "a thousandth unseen tweet"] #*******change here*************** for t in test_data: split = nltk.word_tokenize(t) vect = model.infer_vector(split) vect = vect.reshape(1, -1) print clf.predict(vect) Towards the end of this code block is where I am getting confused. I …
has comment: http://stackoverflow.com/comment/89658636
has title: Cannot figure out format needed to make predictions on dataset trained with doc2vec and random forest classifier
has comment: http://stackoverflow.com/comment/89658489
has comment: http://stackoverflow.com/comment/89658529
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89657304
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/89657967
answer count: 0
has comment: http://stackoverflow.com/comment/89658356
type: Question
tagged with: random-forest

http://stackoverflow.com/q/51450442
linked to: http://stackoverflow.com/q/17985159
tagged with: dataframe
has answer: http://stackoverflow.com/a/51450888
has title: Pandas DataFrame Table with Internal Stacked sub-table
tagged with: pandas
answer count: 1
downvote count: 0
has body: Lets say I have the following input data coming from a database. data = [{'abc': 'None', 'cde': 4, 'efg': 1, 'blah': {'k': 23, 'y': 26, 'u':48} },{'abc': 'hdf', 'cde':10, 'efg': 2, 'blah': {'k': 244, 'y': 747, 'u':75, 'g':88}, }, ] The following is the look of the pandas data frame which I would like to produce: blah cde abc g k u y efg 1 4 'None' N/A 23 48 26 2 10 'hdf' 88 244 75 747 key features: 'efg' is merged vertically and acts as the index (i think, please correct me if i am wrong) Flat features such as 'cde', 'abc' are treated like normal columns The nested dict has the parent stacked on top of its respective child elements, any nested field that does not have a value associated with the index, 'efg' gets N/A. Attempts: When I take the data into a pandas data frame I get the following: abc cde efg blah k None 4 1 23 u None 4 1 48 y None 4 1 26 g hdf 10 2 88 k hdf 10 2 244 u hdf 10 2 75 y hdf 10 2 747 I suspect pandas is taking the nested dict keys as an index, so i reset it which gives the following: index abc cde efg blah 0 k None 4 1 23 1 u None 4 1 48 2 y None 4 1 26 3 g hdf 10 2 88 4 k hdf 10 2 244 5 u hdf 10 2 75 6 y hdf 10 2 747 So I pivot this table by the pandas supplied 'index' column, i would expect it to have a stacked cross tab with the 'blah' parent as the top most item, with sub columns being its nested dict ('k','u', 'y', 'g'). In addition I expect the other columns to stay intact, with only the 'blah' section having merged cells. But, we get this instead: &gt;&gt;&gt; t_pivot = t_concat.pivot_table(columns='index') &gt;&gt;&gt; t_pivot index g k u y blah 88.0 133.5 61.5 386.5 cde 10.0 7.0 7.0 7.0 efg 2.0 1.5 1.5 1.5 Ok not great, So maybe i need to be explicit about what data we should index by: t_pivot = t_concat.pivot_table(index = 'efg',columns=['index', 'cde']) &gt;&gt;&gt; t_pivot blah index g k u y cde 10 4 10 4 10 4 10 efg 1 NaN 23.0 NaN 48.0 NaN 26.0 NaN 2 88.0 NaN 244.0 NaN 75.0 NaN 747.0 Still not right. So any ideas on how to form …
favorite count: 0
tagged with: python-3.x
tagged with: data-analysis
accepted answer: http://stackoverflow.com/a/51450888
tagged with: python
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/89871459
has comment: http://stackoverflow.com/comment/89871611
type: Question
score: 3

http://stackoverflow.com/comment/89705808
type: QuestionComment
comment on: http://stackoverflow.com/q/51366674
score: 0
has text: Your `rownum` will always be zero as it's not in your `for row in reader:` block, hence `if rownum == 0` will always evaluate to `True`. Unless you screwed up the indentation while pasting to SO, that's probably your main issue.
type: Comment

gurobi
tags question: http://stackoverflow.com/q/51417739
tags question: http://stackoverflow.com/q/51340276
tag name: gurobi
type: Tag
tags question: http://stackoverflow.com/q/51348079

http://stackoverflow.com/q/51347844
type: Question
has body: I've made a parser to extract questions from past exam papers and tabulate how often particular questions/topics arise through the years. It stores the question/topic as a dictionary and the date as a list and is supposed to combine both as follows: questions = {'Question1':['April 2011', 'May 2016'], 'Question2': ['June 2013']} Problem is, I'm unable to update the list of dates within the dictionary. A snippet of my code is as follows: def extract_topics_dates(file): corpus = '' topics = [] questions = {} year = [] pdf_reader = PyPDF2.PdfFileReader(open(file, 'rb')) for page in pdf_reader.pages: #For each page, get corpus of text. for line in page.extractText().splitlines(): corpus = corpus + line #For each page, extract topics. for i in [phrase for phrase in map(str.strip, re.split('\d+\s\s', corpus)) if phrase]: topics.append(extract_topic(i)) topics = [x for x in topics if x is not None] #For each page, extract date. year = set([x for x in year if x is not None]) year.add(get_date(page)) #For each page, now combine the topic + date. for i in topics: questions[i].add(year) return questions Everything in this function works as intended, except the last questions[i].add(year) which returns a KeyError. Where am I going wrong?
downvote count: 0
has comment: http://stackoverflow.com/comment/89668738
has answer: http://stackoverflow.com/a/51347948
answer count: 1
score: 1
favorite count: 0
upvote count: 1
tagged with: python
tagged with: dictionary
has title: How to change a list within a dictionary?
accepted answer: http://stackoverflow.com/a/51347948
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/comment/89682871
type: QuestionComment
has text: @coldspeed The mean would be, for each row, `mean = sum(all_numerical_values_in_the_row)/ len (row) `
comment on: http://stackoverflow.com/q/51355151
score: 0
type: Comment

django
tags question: http://stackoverflow.com/q/51341625
tags question: http://stackoverflow.com/q/51347871
tags question: http://stackoverflow.com/q/51439689
tags question: http://stackoverflow.com/q/51452186
tags question: http://stackoverflow.com/q/51458762
tags question: http://stackoverflow.com/q/51336401
tags question: http://stackoverflow.com/q/51360932
tags question: http://stackoverflow.com/q/51343674
tags question: http://stackoverflow.com/q/51473652
tags question: http://stackoverflow.com/q/51366191
tags question: http://stackoverflow.com/q/51431241
tags question: http://stackoverflow.com/q/51462947
tags question: http://stackoverflow.com/q/51333549
tags question: http://stackoverflow.com/q/51471329
tags question: http://stackoverflow.com/q/51480504
tags question: http://stackoverflow.com/q/51399204
tags question: http://stackoverflow.com/q/51341349
tags question: http://stackoverflow.com/q/51473617
tags question: http://stackoverflow.com/q/51452560
tags question: http://stackoverflow.com/q/51444242
tags question: http://stackoverflow.com/q/51343093
tags question: http://stackoverflow.com/q/51412219
tags question: http://stackoverflow.com/q/51349646
tags question: http://stackoverflow.com/q/51462191
tags question: http://stackoverflow.com/q/51380780
tags question: http://stackoverflow.com/q/51390229
tags question: http://stackoverflow.com/q/51364892
tags question: http://stackoverflow.com/q/51428697
tags question: http://stackoverflow.com/q/51459579
tags question: http://stackoverflow.com/q/51430094
tags question: http://stackoverflow.com/q/51399804
tags question: http://stackoverflow.com/q/51477133
tags question: http://stackoverflow.com/q/51466656
tags question: http://stackoverflow.com/q/51459940
tags question: http://stackoverflow.com/q/51363423
tags question: http://stackoverflow.com/q/51403157
tags question: http://stackoverflow.com/q/51398769
tags question: http://stackoverflow.com/q/51359280
tags question: http://stackoverflow.com/q/51422857
tags question: http://stackoverflow.com/q/51418915
tags question: http://stackoverflow.com/q/51336453
tags question: http://stackoverflow.com/q/51326930
tags question: http://stackoverflow.com/q/51436451
tags question: http://stackoverflow.com/q/51414783
tags question: http://stackoverflow.com/q/51340223
tags question: http://stackoverflow.com/q/51335131
tags question: http://stackoverflow.com/q/51432860
tags question: http://stackoverflow.com/q/51365273
tags question: http://stackoverflow.com/q/51369701
tags question: http://stackoverflow.com/q/51469416
tags question: http://stackoverflow.com/q/51418261
tags question: http://stackoverflow.com/q/51409728
tags question: http://stackoverflow.com/q/51478288
tags question: http://stackoverflow.com/q/51460873
tags question: http://stackoverflow.com/q/51394864
tags question: http://stackoverflow.com/q/51462068
tags question: http://stackoverflow.com/q/51362314
tags question: http://stackoverflow.com/q/51462779
tags question: http://stackoverflow.com/q/51373370
type: Tag
tags question: http://stackoverflow.com/q/51346126
tags question: http://stackoverflow.com/q/51424925
tags question: http://stackoverflow.com/q/51428143
tags question: http://stackoverflow.com/q/51352415
tags question: http://stackoverflow.com/q/51402140
tags question: http://stackoverflow.com/q/51440046
tags question: http://stackoverflow.com/q/51353000
tags question: http://stackoverflow.com/q/51454878
tags question: http://stackoverflow.com/q/51379755
tags question: http://stackoverflow.com/q/51437447
tags question: http://stackoverflow.com/q/51360493
tags question: http://stackoverflow.com/q/51385047
tags question: http://stackoverflow.com/q/51333107
tags question: http://stackoverflow.com/q/51451345
tags question: http://stackoverflow.com/q/51412175
tags question: http://stackoverflow.com/q/51362389
tags question: http://stackoverflow.com/q/51368338
tags question: http://stackoverflow.com/q/51395373
tags question: http://stackoverflow.com/q/51471699
tags question: http://stackoverflow.com/q/51471061

http://stackoverflow.com/comment/89663651
comment on: http://stackoverflow.com/a/51341789
has text: This depends on at which level in your model architecture you want to concatenate those two inputs! I am assuming that you got Convo, Maxpool, etc layers after your image input and similarly your float number input also got other layers added in!? Can you add in your model architecture?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89838920
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51434250
has text: thank you, got my code cleaner

http://stackoverflow.com/q/51340848
has title: Why is my pandas df all object data types as opposed to e.g. int, string etc?
has answer: http://stackoverflow.com/a/51340942
has answer: http://stackoverflow.com/a/78415380
type: Question
score: 5
upvote count: 5
tagged with: dataframe
has comment: http://stackoverflow.com/comment/98140791
accepted answer: http://stackoverflow.com/a/51340942
answer count: 3
tagged with: pandas
possible better answer: http://stackoverflow.com/a/51341218
downvote count: 0
has answer: http://stackoverflow.com/a/51341218
favorite count: 0
has body: Over on this SO post someone suggests using df.info() to get information about a a pandas df, including the data types of each field. Pasting part of this persons answer here: train.info() &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 891 entries, 0 to 890 Data columns (total 12 columns): PassengerId 891 non-null int64 Survived 891 non-null int64 Pclass 891 non-null int64 Name 891 non-null object Sex 891 non-null object Age 714 non-null float64 SibSp 891 non-null int64 Parch 891 non-null int64 Ticket 891 non-null object Fare 891 non-null float64 Cabin 204 non-null object Embarked 889 non-null object dtypes: float64(2), int64(5), object(5) memory usage: 83.6+ KB I tried this on my own pandas data frame: sessions1DF.info() &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 69085 entries, 0 to 69084 Data columns (total 10 columns): ga:date 69085 non-null object ga:hour 69085 non-null object ga:dimension1 69085 non-null object ga:dimension2 69085 non-null object ga:userType 69085 non-null object ga:landingpagePath 69085 non-null object ga:deviceCategory 69085 non-null object ga:sessions 69085 non-null object ga:goal1Completions 69085 non-null object ga:bounces 69085 non-null object dtypes: object(10) memory usage: 5.3+ MB Everything is an object where I expected some combination of strings and numbers. Here is the head: sessions1DF.head() Out[13]: ga:date ga:hour ... ga:goal1Completions ga:bounces 0 20180605 18 ... 0 0 1 20180605 18 ... 0 1 2 20180605 18 ... 0 0 3 20180605 18 ... 0 1 4 20180605 18 ... 0 0 [5 rows x 10 columns] (I wish I knew how to force pandas head() to show me all the features, not just the 4 it showed me above). sessions1DF actually has a field called "dimension1" which is supposed to be a string and I would like to join it with another data frame sessions2DF, where they both share the same field "dimension1". So I'd like to join them on dimension1. Is there something "wrong" with my pandas data frame? Is there a way to "extract" all t…
tagged with: python
linked to: http://stackoverflow.com/q/27637281
type: AnsweredQuestion

http://stackoverflow.com/a/51460165
upvote count: 5
type: Answer
downvote count: 0
has body: The problem is that your points when fed to Voronoi get inflated during the construction of the tessellation, and when you later filter them out the points are in the wrong order. Consequently when you set vor.filtered_points = points_center in voronoi(), the points are shuffled compared to the order of regions. So while you're computing the midpoints correctly, you're using the wrong pairs of points. I circled two correct pairings in green and an incorrect one in red here: As you can see from the red circle, the basis point in an edge cell is paired with the centroid of an adjacent cell. The solution is simple: when you're filtering the regions and find a region to keep, you need to gather the point which falls inside the corresponding region. You can do this by matching vor.points to vor.point_region and finding the corresponding region, for which you'll need to enumerate your regions: # Compute Voronoi vor = sp.spatial.Voronoi(points) # Filter regions and select corresponding points regions = [] points_to_filter = [] # we'll need to gather points too ind = np.arange(points.shape[0]) ind = np.expand_dims(ind,axis= 1) for i,region in enumerate(vor.regions): # enumerate the regions if not region: # nicer to skip the empty region altogether continue flag = True for index in region: if index == -1: flag = False break else: x = vor.vertices[index, 0] y = vor.vertices[index, 1] if not(bounding_box[0] - eps &lt;= x and x &lt;= bounding_box[1] + eps and bounding_box[2] - eps &lt;= y and y &lt;= bounding_box[3] + eps): flag = False break if flag: regions.append(region) # find the point which lies inside points_to_filter.append(vor.points[vor.point_region == i][0,:]) vor.filtered_points = np.array(points_to_filter) vor.filtered_regions = regions With these modifications the averaging works fine:
score: 5
answers question: http://stackoverflow.com/q/51429596
accepted answer of: http://stackoverflow.com/q/51429596
type: AcceptedAnswer

http://stackoverflow.com/a/51404285
has body: You're accessing a globally declared variable inside a function where it is not initialized yet, because pynput's keyboard listener is handled as a Thread and has different scope. So, you'll have to specify the variable as a global variable before accessing it. def on_press(key): # global is_typing print globals() global is_typing if not is_typing: is_typing = True controller.type('test') is_typing = False
downvote count: 1
has comment: http://stackoverflow.com/comment/89781203
answers question: http://stackoverflow.com/q/51403491
score: 0
type: Answer
upvote count: 1

http://stackoverflow.com/q/51379449
upvote count: 1
answer count: 1
favorite count: 0
tagged with: tkinter
tagged with: python
accepted answer: http://stackoverflow.com/a/51379877
has body: here is the code from tkinter import* def final_calculation(): entryField.delete(0,'end') Wood = entryWood.get() Steal = entrySteal.get() output_wood = (Wood *wood_c02) output_steal = (Steal * steal_c02 ) final = (output_steal + output_wood *c02_coal) entry.set(final) steal_c02 = int (5.5) wood_c02 = int (1.2) c02_coal = int (0.94) root = Tk() root.configure(background="black") root.title("C02 caculator") root.resizable(1,0) root.columnconfigure(0,weight=1) root.columnconfigure(1,weight=1) entry = StringVar() entryField = Entry(root, textvariable=entry,background="white",foreground="black",justify=CENTER) entryField.grid(row=0,column=0,columnspan=2,sticky=W+E) entryField.columnconfigure(0,weight=1) labelWood = Label(root, text="Amount of wood",background="black",foreground="grey90") labelWood.grid(row=1,column=0, sticky=E) labelSteal = Label(root, text="Amount of steal",background="black",foreground="grey90") labelSteal.grid(row=2,column=0, sticky=E) entryWood = Entry(root,background="grey80",foreground="black") entryWood.grid(row=1,column=1,sticky=W) entrySteal = Entry(root,background="grey80",foreground="black") entrySteal.grid(row=2,column=1,sticky=W) button = Button(root, text="caculate C02", command= final_calculation) button.grid(row=3, columnspan=2) root.mainloop() Press run and all is fine. Until you calculate the sum what redissolves in a issue, that is the second input is duplicated 5 times and that is displayed as the output, any help would be well helpful. kind regards:49.95
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89730584
tagged with: error-handling
has answer: http://stackoverflow.com/a/51379877
type: Question
has comment: http://stackoverflow.com/comment/89730959
has comment: http://stackoverflow.com/comment/89730895
has title: Unexpected output from python tkinter "calculator"

http://stackoverflow.com/comment/89646245
type: AnswerComment
comment on: http://stackoverflow.com/a/51335322
type: Comment
has text: @user10025959 i would guess it might be some extra bracket somewhere. hope it helps.
score: 0

http://stackoverflow.com/comment/139802630
type: Comment
comment on: http://stackoverflow.com/a/67233421
type: AnswerComment
has text: This is wrong - offset IS the correction. Your correction would correct the local time to the time the server tx_time, which is the time it transmitted the response.
score: 0

http://stackoverflow.com/comment/89691471
score: 0
type: AnswerComment
has text: And one more thing I wanted to get the router value from file content and store it in a variable.How do i do that..?
type: Comment
comment on: http://stackoverflow.com/a/51358893

http://stackoverflow.com/comment/89740407
score: 0
has text: @Wen That worked!!! Such a simple fix, not sure how I missed that!
comment on: http://stackoverflow.com/q/51383400
type: Comment
type: QuestionComment

django-celery
tags question: http://stackoverflow.com/q/51408605
tag name: django-celery
tags question: http://stackoverflow.com/q/51378081
tags question: http://stackoverflow.com/q/51366191
type: Tag
tags question: http://stackoverflow.com/q/51376872

http://stackoverflow.com/a/58115954
score: 2
type: Answer
downvote count: 2
has body: Not exactly what you want, but more lazy: It may be usefull when you want to create some fast debug: num_list = [1, 2, 3, 4, 5] logger.info(str(("Numbers in num_list are: ",num_list)) output: ('Numbers in num_list are: ', [1, 2, 3, 4, 5])
answers question: http://stackoverflow.com/q/51477200
upvote count: 4

http://stackoverflow.com/comment/89636934
type: Comment
comment on: http://stackoverflow.com/q/51330475
type: QuestionComment
score: 0
has text: @abarnert So, I ran my code through leetcode and that was their example. I also edited my post to include the Leetcode solution. Here's the link if you're interested. https://leetcode.com/problems/image-smoother/description/

http://stackoverflow.com/comment/89914613
type: QuestionComment
type: Comment
has text: I am trying to find a better way to write my function to "fish" out random encounters, as it currently involves a lot of hard coding.
score: 0
comment on: http://stackoverflow.com/q/51473138

http://stackoverflow.com/a/51449291
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51449044
has comment: http://stackoverflow.com/comment/89869017
answers question: http://stackoverflow.com/q/51449044
score: 2
has comment: http://stackoverflow.com/comment/89869178
has body: Initially, self.new_button refers to a method. Then, you do this: self.new_button = Button(self) That effecting removes the method and replaces it with the button widget itself. Also, you never assign a command to the new button, so clicking it doesn't cause anything to be called.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89917493
comment on: http://stackoverflow.com/a/51469764
has text: If you export the html, there is no option for a live view; you can in that case fall back to your previous solution of exporting html5 video.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51357981
answer count: 2
has comment: http://stackoverflow.com/comment/89688191
has title: What is the format of "input_shape" is keras.Sequential()?
tagged with: keras
has body: Following this tensorflow tutorial, under the Build the model section, the first layer of keras.Sequential() is given parameter vocab_size=10000. What does it mean? After looking at the documentation I figured out that, the Sequential model needs to know the shape of the input tensor(tensor to the input layer), and input_shape attribute defines it. But input_shape should be like (30, 50, 50, 3) (for 30, 50x50 RGB images). The value in the tutorial is 10000.
score: 0
possible better answer: http://stackoverflow.com/a/51358186
favorite count: 0
accepted answer: http://stackoverflow.com/a/51358300
upvote count: 1
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/51358300
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89688214
has answer: http://stackoverflow.com/a/51358186
has comment: http://stackoverflow.com/comment/89688168
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/89926019
comment on: http://stackoverflow.com/q/51477290
has text: @KlausD. I thought I did handle it? Isn't that what it being inside the try/except block does?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51468957
duplicate of: http://stackoverflow.com/q/20002503
downvote count: 1
linked to: http://stackoverflow.com/q/15112125
tagged with: numpy
tagged with: arrays
has answer: http://stackoverflow.com/a/51468971
has title: Python OR Operator Trouble
type: AnsweredQuestion
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/51468971
has body: I have a list of probabilities dictating whether an output is a 1 or a 0 in a numpy array. I'm trying to split these probabilities into two separate arrays based on a certainty level of 75%. If either probability is above 75% it goes into the 'certain' array, and if neither cross that threshold, it goes into the 'uncertain' array. For some reason, when I run this code it does not correctly differentiate between the two and proceeds to add all the instances to the 'certain' array. Code: probs = rfc.predict_proba(X_validate) certain = [] uncertain = [] for i in probs[0:10]: zero_val = i[0] one_val = i[1] if zero_val or one_val &gt; 0.75: certain.append(i) else: uncertain.append(i) print(len(certain)) print(certain) print(len(uncertain)) print(uncertain) Here is the output: 10 [array([0., 1.]), array([1., 0.]), array([0.95, 0.05]), array( [0.77, 0.23]), array([0.74, 0.26]), array([0.38, 0.62]), array ([0.11, 0.89]), array([1., 0.]), array([0.94, 0.06]), array([0 .19, 0.81])] 0 [] What is causing every instance to be added to the 'certain' array regardless? Thanks!
tagged with: python
answer count: 1
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/89982193

http://stackoverflow.com/a/51326621
downvote count: 0
type: AcceptedAnswer
has body: The problem could be that you are cropping a small area of your document that may or may not be blank. There has been a similar question and it should have your answer #!/usr/bin/python # from pyPdf import PdfFileWriter, PdfFileReader with open("in.pdf", "rb") as in_f: input1 = PdfFileReader(in_f) output = PdfFileWriter() numPages = input1.getNumPages() print "document has %s pages." % numPages for i in range(numPages): page = input1.getPage(i) print page.mediaBox.getUpperRight_x(), page.mediaBox.getUpperRight_y() page.trimBox.lowerLeft = (25, 25) page.trimBox.upperRight = (225, 225) page.cropBox.lowerLeft = (50, 50) page.cropBox.upperRight = (200, 200) output.addPage(page) with open("out.pdf", "wb") as out_f: output.write(out_f) Question answered by: danio
accepted answer of: http://stackoverflow.com/q/51326378
answers question: http://stackoverflow.com/q/51326378
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/q/51465501
type: Question
upvote count: 5
score: 4
answer count: 2
has answer: http://stackoverflow.com/a/79085434
has title: Django: When do I need __eq__ method?
favorite count: 0
type: UnansweredQuestion
has body: In Django I've written a custom class-based validator and implemented the __eq__ method because it's also done for the validators that are already implemented by Django itself. Here you can see it: @deconstructible class FileSizeValidator: def __init__(self, mb): self.mb = mb def __call__(self, value): limit = self.mb * 1024 * 1024 if value.size &gt; limit: raise ValidationError('File too big (max. ' + str(self.mb) + ' MiB).') def __eq__(self, other): return ( isinstance(other, FileSizeValidator) and self.mb == other.mb ) Now, I've also written a custom class for the ImageField. I want to use it for the upload_to= parameter in a model for the ImageField. Here you can see my example: @deconstructible class RandomFileName: def __init__(self, directory=''): self.directory = directory def __call__(self, instance, filename): return self.directory + ("/" if self.directory else '') + get_random_string(7) + "." + filename.split('.')[-1] def __eq__(self, other): return ( isinstance(other, RandomFileName) and self.directory == other.directory ) In general, I am happy with it and it seems to work fine. I just do not know when I need the __eq__ method and would like to ask you for an explanation.
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/51465694
downvote count: 1

http://stackoverflow.com/comment/89808200
has text: @ImportanceOfBeingErnest - apologies, I had replaced "b" with "i" in the function incorrectly. I've edited the code and it should now be runnable.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51409257

http://stackoverflow.com/comment/89750781
type: Comment
has text: yes thats what i want. also the repeated words in a category will be counted as 1
score: 0
comment on: http://stackoverflow.com/q/51389377
type: QuestionComment

http://stackoverflow.com/q/51412095
possible better answer: http://stackoverflow.com/a/54816207
accepted answer: http://stackoverflow.com/a/51418267
tagged with: nlp
favorite count: 0
has answer: http://stackoverflow.com/a/54816207
tagged with: spacy
has title: Spacy - Save custom pipeline
tagged with: python
type: AnsweredQuestion
upvote count: 10
type: Question
has answer: http://stackoverflow.com/a/51418267
score: 10
answer count: 2
has body: I'm trying to integrate a custom PhraseMatcher() component into my nlp pipeline in a way that will allow me to load the custom Spacy model without having to re-add my custom components to a generic model on each load. How can I load a Spacy model containing custom pipeline components? I create the component, add it to my pipeline and save it with the following: import requests from spacy.lang.en import English from spacy.matcher import PhraseMatcher from spacy.tokens import Doc, Span, Token class RESTCountriesComponent(object): name = 'countries' def __init__(self, nlp, label='GPE'): self.countries = [u'MyCountry', u'MyOtherCountry'] self.label = nlp.vocab.strings[label] patterns = [nlp(c) for c in self.countries] self.matcher = PhraseMatcher(nlp.vocab) self.matcher.add('COUNTRIES', None, *patterns) def __call__(self, doc): matches = self.matcher(doc) spans = [] for _, start, end in matches: entity = Span(doc, start, end, label=self.label) spans.append(entity) doc.ents = list(doc.ents) + spans for span in spans: span.merge() return doc nlp = English() rest_countries = RESTCountriesComponent(nlp) nlp.add_pipe(rest_countries) nlp.to_disk('myNlp') I then attempt to load my model with, nlp = spacy.load('myNlp') But get this error message: KeyError: u"[E002] Can't find factory for 'countries'. This usually happens when spaCy calls nlp.create_pipe with a component name that's not built in - for example, when constructing the pipeline from a model's meta.json. If you're using a custom component, you can write to Language.factories['countries'] or remove it from the model meta and add it via nlp.add_pipe instead." I can't just add my custom components to a generic pipeline in my programming environment. How can I do what I'm trying to do?
downvote count: 0

http://stackoverflow.com/q/51474159
type: UnansweredQuestion
tagged with: python
has title: Make flask run honor app.debug
score: 0
type: Question
linked to: http://stackoverflow.com/q/17309889
tagged with: flask
has comment: http://stackoverflow.com/comment/89917857
duplicate of: http://stackoverflow.com/q/17309889
has comment: http://stackoverflow.com/comment/89916818
has comment: http://stackoverflow.com/comment/89916771
has comment: http://stackoverflow.com/comment/89916953
answer count: 0
has body: I have a minimal application in test_app/__init__.py: from flask import Flask app = Flask(__name__) app.debug = True Now if I try to run it with env FLASK_APP=test_app:app flask run, I get this output: * Serving Flask app "test_app:app" * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: off * Running on http://127.0.0.1:5001/ (Press CTRL+C to quit) (Note the line Debug mode: off) However, if I create a test_app/__main__.py file with from test_app import app app.run() I get the expected result: * Serving Flask app "test_app" (lazy loading) * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: on * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: xxx-xxx-xxx I also tried adding this to __init__.py: class Config: DEBUG = True app.config.from_object(Config) The result is the same. Adding the command line option --debugger for flask run also doesn’t seem to help. Am I missing something? Is there a way to make the CLI honor the debug value? Using Flask 1.0.2, but the problem seems to be present in 0.12, too.

http://stackoverflow.com/q/51351508
has answer: http://stackoverflow.com/a/51352314
has body: I came across some weird behavior where pickle was producing different serialized output for the same input. It is somehow triggered when serializing a deserialized pickled object (as could happen if the object was retrieved from mp.Queue). It also only happens when the list has more than one element (not sure why). Can someone explain what is going on here? I have read this question but it doesn't seem to be the same situation, as a,b,c all have different ids. Code to reproduce below. I'm using Python 3.6.3 from Anaconda. import pickle import numpy as np def f(): return np.array([1,2,3]) a = f() b = f() c = pickle.loads(pickle.dumps(f())) print(id(a), id(b), id(c)) # 4464565184 4464565504 4466959424 print('[a]==[b]', pickle.dumps([a]) == pickle.dumps([b])) # True print('[a]==[c]', pickle.dumps([a]) == pickle.dumps([c])) # True print('[b]==[c]', pickle.dumps([b]) == pickle.dumps([c])) # True print('[a,b]==[a,c]', pickle.dumps([a,b]) == pickle.dumps([a,c])) # False print('a.tolist()==c.tolist()', a.tolist()==c.tolist()) # True
type: Question
tagged with: numpy
answer count: 1
linked to: http://stackoverflow.com/q/37748001
score: 0
has title: pickling a deserialized object produces different binary (vs original)
type: UnansweredQuestion
tagged with: pickle
tagged with: python

http://stackoverflow.com/q/51380949
favorite count: 0
upvote count: 3
has comment: http://stackoverflow.com/comment/89733619
accepted answer: http://stackoverflow.com/a/51381252
tagged with: python
tagged with: module
answer count: 4
has answer: http://stackoverflow.com/a/51381017
has title: Get a parameter of a file .txt using python
downvote count: 0
possible better answer: http://stackoverflow.com/a/51381026
tagged with: file
has answer: http://stackoverflow.com/a/51381252
has answer: http://stackoverflow.com/a/51381026
tagged with: parameters
type: AnsweredQuestion
score: 3
type: Question
has answer: http://stackoverflow.com/a/51381070
has body: I'm trying to get parameters of a .txt like that: a=10 b=15 c=20 How can i do a function called get() that takes from this file called parameters.txt the parameter b and return 15?? It's to build a module that works like a getter of parameters. To simplify and explain information: the .txt conatains parameters with and int value. The get() function will obtain the integer value associated to the parameter.
tagged with: function
has comment: http://stackoverflow.com/comment/89733618
has comment: http://stackoverflow.com/comment/89733586

http://stackoverflow.com/a/51361858
has body: I have 2 methods for this: This method we multiply by the max value of each user-id - it works on the sample dataset you porivded but it might not work overal. df.set_index('user-id', inplace=True) df['value'] += df.groupby('user-id')['value'].apply( lambda x:(x.shift() &gt; x).astype(int).cumsum() ) * 10**df.groupby('user-id')['value'].max().apply(lambda x: len(str(x))) The other on is looping through each item: def foo(x): for i in range(1,len(x)): if x.iloc[i] &lt; x.iloc[i-1]: x.iloc[i:] = x.iloc[i:] + 10**(len(str(x.iloc[i-1]))) return x df['value'] = df.groupby('user-id')['value'].apply(foo)
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51358307

http://stackoverflow.com/q/51421712
has answer: http://stackoverflow.com/a/51423879
has title: python package import from the root
type: Question
has comment: http://stackoverflow.com/comment/89814324
tagged with: python
has answer: http://stackoverflow.com/a/51421890
score: 0
answer count: 2
has body: I have a following directory structure: main_work/ data_processing/ data_extraction.py data_selector.py data_selector.py: from data_extraction import connect_to_db If I start working in main_work and want to do from data_processing import data_selector as ds it throws me an error: ModuleNotFoundError: No module named 'data_extraction' So, the import in data_selector.py takes into account only current folder (main_work) and doesnt go one level deeper into data_processing. I need to be able to do from main_work following: from data_processing import data_selector as ds and from data_processing following: import data_selector How do I achieve those two functionalities?
has comment: http://stackoverflow.com/comment/89814425
has comment: http://stackoverflow.com/comment/89818680
type: UnansweredQuestion

http://stackoverflow.com/q/51426623
type: Question
tagged with: performance
tagged with: algorithm
has comment: http://stackoverflow.com/comment/89825861
has comment: http://stackoverflow.com/comment/89825055
has comment: http://stackoverflow.com/comment/89824749
has comment: http://stackoverflow.com/comment/89825763
answer count: 1
has comment: http://stackoverflow.com/comment/89825295
has comment: http://stackoverflow.com/comment/89826752
tagged with: combinatorics
score: 0
has answer: http://stackoverflow.com/a/51427897
has body: Problem For a computation engineering model, I want to do a grid search for all feasible parameter combinations. Each parameter has a certain possibility range, e.g. (0 … 100) and the parameter combination must fulfil the condition a+b+c=100. An example: ranges = { 'a': (95, 99), 'b': (1, 4), 'c': (1, 2)} increment = 1.0 target = 100.0 So the combinations that fulfil the condition a+b+c=100 are: [(95, 4, 1), (95, 3, 2), (96, 2, 2), (96, 3, 1), (97, 1, 2), (97, 2, 1), (98, 1, 1)] This algorithm should run with any number of parameters, range lengths, and increments. My solutions (so far) The solutions I have come up with are all brute-forcing the problem. That means calculating all combinations and then discarding the ones that do not fulfil the given condition: def solution1(ranges, increment, target): combinations = [] for parameter in ranges: combinations.append(list(np.arange(ranges[parameter][0], ranges[parameter][1], increment))) # np.arange() is exclusive of the upper bound, let's fix that if combinations[-1][-1] != ranges[parameter][1]: combinations[-1].append(ranges[parameter][1]) combinations = list(itertools.product(*combinations)) df = pd.DataFrame(combinations, columns=ranges.keys()) # using np.isclose() so that the algorithm works for floats return df[np.isclose(df.sum(axis=1), target)] Since I ran into RAM problems with solution1(), I used itertools.product as an iterator. def solution2(ranges, increment, target): combinations = [] for parameter in ranges: combinations.append(list(np.arange(ranges[parameter][0], ranges[parameter][1], increment))) # np.arange() is exclusive of the upper bound, let's fix that if combinations[-1][-1] != ranges[parameter][1]: combinations[-1].append(ranges[parameter][1]) result = [] for combination in itertools.product(*combinations): # using np.isclose() so that the algorithm works for floats if np.isclose(sum(combination), target): result.append(combination) df = pd.DataFrame(result, columns=ranges.keys()) return df Howe…
tagged with: python
has title: How to efficiently do a grid search for parameter combinations in Python?
has comment: http://stackoverflow.com/comment/89825245
type: UnansweredQuestion

http://stackoverflow.com/q/51408458
favorite count: 0
tagged with: python-3.x
tagged with: sample-rate
has body: Suppose I have two audio segments of the same sample rate that I have imported from .wav files in Pydub, and assume I know which is shorter. Now suppose I want to split the longer audio file into two segments so that the first segment is the exact same length (down to the exact same number of samples!) as the shorter audio file and assign each of these two segments to new audio segments. How can I do this in Pydub? If I cannot get this level of precision using Pydub, can you give me an alternative that will work just as well? Basically I just want to split the longer audio segment into two at the sample-perfect level. Here's an illustration of what I want:
type: UnansweredQuestion
score: 5
tagged with: python
tagged with: audio
has title: Pydub Slice Audio Segment By Sample
type: Question
upvote count: 5
has answer: http://stackoverflow.com/a/51625503
tagged with: pydub
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/89800905
type: Comment
comment on: http://stackoverflow.com/a/51414387
score: 0
type: AnswerComment
has text: Wow, I am ignorant. Thank you

http://stackoverflow.com/q/51367555
has answer: http://stackoverflow.com/a/51367724
tagged with: sorting
upvote count: 2
tagged with: pandas
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89707775
score: 2
has body: Below is my data. TX Subj W1 W2 W3 W4 0B C2 33.1 32.9 35.6 35.9 1A B12 22.5 22.2 21.9 22.6 1A B10 22.4 22.1 21.6 22.9 1B A6 28.7 29.1 28.6 29.8 0B C1 30.7 32.1 35.4 36.1 0A C4 39.6 39.8 42.9 43.4 0A B4 42.7 41.4 44.1 43.9 1A C6 31.5 31.8 34.4 33.4 0A D7 23.4 26.3 29.7 29.4 1A D2 31.6 27.8 30.2 30.5 1B A20 21.7 21.8 22.3 23.7 1C A1 34.7 34.8 34.6 38.3 1A C5 27.5 28.1 29.1 28.4 I would like to sort this data in this specific order '0A', '1A', '0B', '1B', '1C'. I could use the sort_index. But it gave me sorting data in the ascending order (0A, 0B, 1A, 1B, 1C). Which function should I use to sort this data by the specific order?
downvote count: 0
has comment: http://stackoverflow.com/comment/89707696
has title: custom data sorting in pandas dataframe
has comment: http://stackoverflow.com/comment/89707674
type: Question
linked to: http://stackoverflow.com/q/23279238

python-3.5
tags question: http://stackoverflow.com/q/51451747
type: Tag
tags question: http://stackoverflow.com/q/51447041
tag name: python-3.5
tags question: http://stackoverflow.com/q/51344120
tags question: http://stackoverflow.com/q/51440682
tags question: http://stackoverflow.com/q/51448429
tags question: http://stackoverflow.com/q/51433914
tags question: http://stackoverflow.com/q/51411981

http://stackoverflow.com/comment/89911554
type: QuestionComment
comment on: http://stackoverflow.com/q/51471500
score: 0
has text: have you tried threading.Timer ????
type: Comment

http://stackoverflow.com/comment/89722933
has text: I have to create sql query using old and new values for each of the groups, Is there any alternative instead of iterating through each row?
comment on: http://stackoverflow.com/a/51375663
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51457905
has comment: http://stackoverflow.com/comment/89941608
score: 0
has body: Fetch the row. Use a python function to turn the JSON into a python structure. Walk through the structure using python code. Create INSERT statements as needed, and execute them. That is, steps 2 and 3 are better done via the application language than via SQL.
answers question: http://stackoverflow.com/q/51455872
type: Answer
has comment: http://stackoverflow.com/comment/89889880

http://stackoverflow.com/comment/89709323
comment on: http://stackoverflow.com/a/51367060
has text: CaitLAN: My reason for using BeautifulSoup is to ultimately convert nasty HTML .eml files to plain text .txt files. Is there a better way without BeautifulSoup?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51482526
downvote count: 0
favorite count: 0
has title: Loss of Bokeh charts interactivity on Mobile
has body: I've set some charts up in Bokeh, which I'm generally very happy with on desktop screens. However, when I open them on a mobile screen I have several functionality issues that makes them really horrible to use: The hover functionality won't work (or at least is very buggy). When I click certain lines nothing happens and other times it recognizes that I'm clicking a completely difference part of the screen There is a huge white space after each chart, when I embed the HTML in a site. Code for my charts below (I embed the resulting HTML on a website). Any advice? Thanks! ### V3: Top Positive words from bokeh.io import output_notebook, show, output_file, save, output from bokeh.plotting import figure from bokeh.models import ColumnDataSource, HoverTool, Legend from bokeh.embed import file_html from google.colab import files from bokeh.io import curdoc # removes old html runs # https://github.com/bokeh/bokeh/issues/5681 curdoc().clear() output_notebook() use = pos_tailor # set out axes x = 'time_rnd' y = 'count' # Add annotations # set colour palette col_brew = ['#8dd3c7','#ffffb3','#bebada','#fb8072','#80b1d3','#fdb462','#b3de69','#fccde5','#d9d9d9','#bc80bd','#ccebc5','#ffed6f'] # map out figure plot = figure(tools='', x_axis_type='datetime', sizing_mode='scale_both', toolbar_location='above') # add HoverTool hover_info = [('time', '@hover_time'), ('word', '@word'), ('count', '@count')] hover = HoverTool(names=['use'],tooltips=hover_info, mode='mouse', show_arrow=True ) plot.add_tools(hover) # FORMAT plot.title.text = 'Positive Deep Dive: Key Callouts' plot.title.align = "center" plot.axis.minor_tick_in = -3 plot.axis.minor_tick_out = 6 plot.xaxis.axis_label = 'Time' plot.xaxis.axis_label_standoff = 15 plot.yaxis.axis_label = 'Count' plot.yaxis.major_label_text_color = "orange" plot.yaxis.axis_label_standoff = 15 ### FOR LOOP Data # https://stackoverflow.com/questions/46730609/position-the-legend-outside-the-plot-area-with-bokeh legend_it = [] for i in use: df_eng_wor…
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
tagged with: bokeh
type: Question
linked to: http://stackoverflow.com/q/46730609

http://stackoverflow.com/q/51427261
has comment: http://stackoverflow.com/comment/89825674
score: -1
has title: TypeError in Python occurs in Python Shell but not script?
upvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89825838
tagged with: python
has comment: http://stackoverflow.com/comment/89832147
has body: I don't know why the following simple lines work when I write a script.py and run that script but does not work in the Python shell: random = [1,2,3] iter = iter(random) print (next(iter)) The output for this is of course: 1 when running script But if I enter each line in the Python shell, I get: 'str_iterator' object not callable after iter = iter(random) Why is that so? Thanks in advance! :)
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51427348

http://stackoverflow.com/q/51346977
has comment: http://stackoverflow.com/comment/89667646
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/50284972
has comment: http://stackoverflow.com/comment/89666688
type: Question
has comment: http://stackoverflow.com/comment/89666978
has comment: http://stackoverflow.com/comment/89667591
answer count: 1
has answer: http://stackoverflow.com/a/51347183
has comment: http://stackoverflow.com/comment/89666929
has comment: http://stackoverflow.com/comment/89666885
score: 0
has title: python search different strings on same line
accepted answer: http://stackoverflow.com/a/51347183
has body: i have the following code that I'd like to optimize: if re.search(str(stringA), line) and re.search(str(stringB), line): ..... ..... I tried: stringAB = stringA + '.*' + stringB if re.search(str(stringAB), line): ..... ..... But the results I get is not reliable. I'm using "re.search" here because it seems to be the only way i can search for the exact regex of the pattern specified in stringA and stringB. The logic behind this code is modeled after this egrep command example: stringA=Success stringB=mysqlDB01 egrep "${stringA}" /var/app/mydata | egrep "${stringB}" If there's a better way to do this without re.search, please let me know.
tagged with: python

http://stackoverflow.com/q/51426743
answer count: 2
score: 3
downvote count: 0
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51438668
has title: How to create complicated constants in Tensorflow from constants
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89826014
upvote count: 3
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/51436495
has comment: http://stackoverflow.com/comment/89829618
has body: I want to create a tensorflow constant based on the value of some other tensorflow consant / placeholder. Let's say the input must be a tf.constant / tf.placeholder. How do I apply tensorflow logic to create a constant based on that constant? For example something like: i = tf.constant(...) ei = tf.zeros(shape=[N]) ei[i] = 1 This would not work, because TypeError: 'Tensor' object does not support item assignment And that makes sense, because you should not be able to mutate a constant. I also don't want my ei in this examples to be variables, because they logically are constants, and should not be optimized when I run my network.

http://stackoverflow.com/a/51382287
downvote count: 0
score: 1
has body: I'm not really sure what the text= option of an Entry does, since it isn't mentioned in any reference. To put text in an entry use the .insert() method: entry_dir.insert(END, last_dir) Then, to always open the askdirectory window with the folder currently in the Entry, use dir_name = askdirectory(title = "SiteConverter output directory", initialdir=directory_entry.get()) As per Bryan Oakley's comments, Tkinter accepts abbreviations of option names as long as they are unique. The Entry widget doesn't have a text option, but it does have a textvariable option so that's the one you set when you set text=.... That makes that if you were to use it, you shouldn't give it a string object but a StingVar object. For this specific example you're good without it though.
has comment: http://stackoverflow.com/comment/89738698
has comment: http://stackoverflow.com/comment/89736946
has comment: http://stackoverflow.com/comment/89739844
type: Answer
accepted answer of: http://stackoverflow.com/q/51381932
upvote count: 1
answers question: http://stackoverflow.com/q/51381932
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89737386

http://stackoverflow.com/a/51368396
has comment: http://stackoverflow.com/comment/89709995
answers question: http://stackoverflow.com/q/51368357
upvote count: 4
has comment: http://stackoverflow.com/comment/89709255
type: AcceptedAnswer
downvote count: 0
score: 4
accepted answer of: http://stackoverflow.com/q/51368357
type: Answer
has comment: http://stackoverflow.com/comment/89709362
has body: You should be able to do out = df[df.index.isin(n)]

http://stackoverflow.com/a/51359842
answers question: http://stackoverflow.com/q/51351224
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89698017
accepted answer of: http://stackoverflow.com/q/51351224
type: Answer
score: 1
has body: You need to keep book of your random_list outside the function random_function that removes items from it.
upvote count: 1

http://stackoverflow.com/q/51360696
tagged with: python
has title: unable to send flask data to database
upvote count: 0
has answer: http://stackoverflow.com/a/51361070
downvote count: 1
type: Question
type: AnsweredQuestion
score: -1
answer count: 1
tagged with: flask
tagged with: flask-sqlalchemy
favorite count: 0
accepted answer: http://stackoverflow.com/a/51361070
has body: How to send flask data to the database. I created the .html form but unable to perform the connectivity. All functions are written in the app.py. .html code: Registration Form Your Name* Your Email* How to give connectivity using mysql, SQLAlchemy etc.

http://stackoverflow.com/q/51343908
has comment: http://stackoverflow.com/comment/89811487
type: UnansweredQuestion
has title: modify python script with astropy package
has comment: http://stackoverflow.com/comment/89810944
has comment: http://stackoverflow.com/comment/89689642
tagged with: python
has comment: http://stackoverflow.com/comment/89855477
answer count: 0
type: Question
has body: I have python script that takes a fit image and plots flux versus pixel. It draws 6 lines from a chosen central point corresponding to 0, 30, 60,90, 120 and 150 degree. Then it calculates the flux along each line. I want to use 2 images and overlay them and plot each line for both images individually to compare them. i.e 0 degree of the first image plotted over the 0 degree of the second image. The script has an astropy package for astronomy which can be downloaded online, try anaconda. The script is as follow: #CODE CREATED BY A.AVISON 20-APR-2018# import numpy as np import scipy.ndimage import matplotlib.pyplot as plt from astropy.io import fits #--- FITSNAME ---# fitsName="fix_N7027.JVLA+eMer.eq.image.fits" #---get fits image data---# hdulist = fits.open(fitsName) imData=hdulist[0].data imData[np.isnan(imData)] = -0.0005 #== set NaNs to something which is a real number roughSigma=np.median(imData[np.where(imData&gt;0.0)])#=== takes the median non-zero values as a pseudoRMS levs=np.arange(5.0,55.0,10.0)*roughSigma #=== DEFINE CeNTRAL POSTION y_peak=1043 #in pixels x_peak=990 #in pixels cutLen=500.0 #in pixels #-- Plot... fig, axes = plt.subplots(ncols=2, figsize=[12,6]) axes[0].imshow(imData,cmap='bone',origin='lower')#'gist_ncar' axes[0].contour(imData,colors='w',linewidths=0.5,levels=levs) #-- Extract data values along the line... # Make a line with "num" points... numCuts=6 angPerCuts=180.0/float(numCuts) for ang in range(numCuts): x1=x_peak-float(np.floor(cutLen*np.cos(np.radians(float(ang)*angPerCuts)))) y1=y_peak-float(np.floor(cutLen*np.sin(np.radians(float(ang)*angPerCuts)))) x0=x_peak+float(np.floor(cutLen*np.cos(np.radians(float(ang)*angPerCuts)))) y0=y_peak+float(np.floor(cutLen*np.sin(np.radians(float(ang)*angPerCuts)))) num = int(cutLen) x, y = np.linspace(x0, x1, num), np.linspace(y0, y1, num) # Extract the values along the line, using cubic interpolation zi = 0 zi = scipy.ndimage.map_coordinates(imData, np.vstack((x,y))) axes[0].plot(y,x, '-',linewi…
has comment: http://stackoverflow.com/comment/89811455
has comment: http://stackoverflow.com/comment/89754097
tagged with: astropy
has comment: http://stackoverflow.com/comment/89741782
score: 0

http://stackoverflow.com/comment/89678953
type: Comment
type: QuestionComment
has text: Depending on what you want to do, there may be solutions that don't require seeking every pair, perhaps using a clever data-structure like a kd-tree or a ball-tree, or if you actually need every comparison, there is a parallelized pair-wise distance implementation in scikit-learn. Or you could program your own, maybe in another language. But it *sounds* like you are abusing `pandas.DataFrames` to begin with. At the very least, you are being very memory-wasteful.
comment on: http://stackoverflow.com/q/51353038
score: 0

http://stackoverflow.com/a/51374978
type: Answer
upvote count: 1
score: 1
has body: As per the HTML you have shared @AndreiSuvorkov's answer would possibly cater to your current requirement. Perhaps you can get much more granular and construct an optimized xpath by: Instead of using contains using starts-with Include the ?code= part of the @href attribute Your effective code block will be: all_elements = driver.find_elements_by_xpath("//a[starts-with(@href,'/mathscinet/search/mscdoc.html?code=')]") for elem in all_elements: print(elem.get_attribute("innerHTML"))
downvote count: 0
answers question: http://stackoverflow.com/q/51370650

http://stackoverflow.com/q/51469536
upvote count: 2
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/89907590
has comment: http://stackoverflow.com/comment/89942337
has comment: http://stackoverflow.com/comment/89907611
favorite count: 0
has title: python 3 urllib.request.urlopen not working in place of python 2 urllib2.urlopen
tagged with: python-3.x
tagged with: rest
has comment: http://stackoverflow.com/comment/89907445
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89907661
score: 2
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/89907546
has body: I inherited some python 2 code that uses urllib2.urlopen to post some data to a local server, and I'd like to convert it to python 3. I initially tried the requests module, and when that didn't work I fell back to urllib.request.urlopen, since the documentation says urllib.request.urlopen() corresponds to the old urllib2.urlopen. Both python 3 approaches are throwing the same exception, while the python 2 code works fine. working python 2 code: &gt;&gt;&gt; request = urllib2.Request(url) &gt;&gt;&gt; request.add_data(data) &gt;&gt;&gt; response = urllib2.urlopen(request) &gt;&gt;&gt; response.read() '' &gt;&gt;&gt; response.close() python 3 equivalent &gt;&gt;&gt; request = urllib.request.Request(url, data) &gt;&gt;&gt; response = urllib.request.urlopen(request) generates the following traceback: --------------------------------------------------------------------------- RemoteDisconnected Traceback (most recent call last) &lt;ipython-input-56-d5c6f6ac8b5c&gt; in &lt;module&gt;() ----&gt; 1 response = urllib.request.urlopen(request) /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context) 221 else: 222 opener = _opener --&gt; 223 return opener.open(url, data, timeout) 224 225 def install_opener(opener): /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py in open(self, fullurl, data, timeout) 524 req = meth(req) 525 --&gt; 526 response = self._open(req, data) 527 528 # post-process response /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py in _open(self, req, data) 542 protocol = req.type 543 result = self._call_chain(self.handle_open, protocol, protocol + --&gt; 544 '_open', req) 545 if result: 546 return result /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py in _call_chain(self, chain, kind, meth_name, *args) 502 for handler in handlers: 503 func = getattr(handler, meth_name) --&g…
has comment: http://stackoverflow.com/comment/89907526
type: Question
has comment: http://stackoverflow.com/comment/89907516
has comment: http://stackoverflow.com/comment/89907488
has comment: http://stackoverflow.com/comment/89907562

http://stackoverflow.com/comment/89930894
type: QuestionComment
comment on: http://stackoverflow.com/q/51481069
has text: Presumably the Python script fails to run. Check exec() manual page. Use the 2nd and 3rd optional parameters to debug.
score: 0
type: Comment

http://stackoverflow.com/comment/89755860
has text: Trying to reduce to minimal example and found that you have both a function and a variable called `index`. They don't seem to interfere but its a bad thing...
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51389968
type: QuestionComment

http://stackoverflow.com/a/51451964
has body: Since I was also moving to python 3.7, I came across this question and decided to answer it, as well as finish my installation. This are the two sources, which I used for installing python 3.7 on ubuntu 16.04: https://askubuntu.com/questions/865554/how-do-i-install-python-3-6-using-apt-get https://superuser.com/questions/241865/updating-python-on-ubuntu-system Apparently from the first source the deadsnakes PPA contain Python 3.7 - Link: https://github.com/deadsnakes/python3.7/tree/ubuntu/xenial/Python So following from my first source, I used the following commands to install Python 3.7: sudo add-apt-repository ppa:deadsnakes/ppa sudo apt-get update sudo apt-get install python3.7 It installed Python 3.7 successfully but my Python 3.5.2 remains default. You can invoke/use Python 3.7 by running the commands: python3.7 script.py It works, so I decided to set Python 3.7 as default by removing python 3.5, but I came across my second source, and just decided to stick with using python3.7, when running my script in the terminal. Apparently it says: Ubuntu policies extensively for writing end-user software. So basically, a large part of the system is written in Python. To switch to Python 3.7, there needs to be done a piece of work consisting of updating and re-testing all the scripts. So to say you can't just switch to Python 3.7 and delete the older version. Also from a comment from my first source it states deleting the older version might break the system. I haven't been around to deleting my older version in case it might break the system, but since you are asking for how to download Python 3.7, I think my first source and the first part of my answer should to the work. I hope it helps :)
downvote count: 0
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/51343421
score: 3

http://stackoverflow.com/q/51366456
tagged with: django-rest-framework
has body: What's the most elegant way to fetch data from an external API if I want to be faithful to the Single Responsibility Principle? Where/when exactly should it be made? Assuming I've got a POST /foo endpoint which after being called should somehow trigger a call to the external API and fetch/save some data from it in my local DB. Should I add the call in the view? Or the Model?
score: 0
answer count: 1
has title: fetch data from 3rd party API - Single Responsibility Principle in Django
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51407850
tagged with: django
tagged with: python
type: Question

http://stackoverflow.com/q/51444861
score: 0
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/89859821
has answer: http://stackoverflow.com/a/51445296
has comment: http://stackoverflow.com/comment/89860867
type: UnansweredQuestion
tagged with: special-characters
linked to: http://stackoverflow.com/q/2171095
has comment: http://stackoverflow.com/comment/89860326
type: Question
has title: Import data from Json to Excel after cleaning text and stopword removal with Python
tagged with: python
answer count: 1
tagged with: excel
has body: I have Json file that contains data I've scraped from a website using Scrapy, my next step is to clean the data text from special characters and stopwords, and save them in Excel file for another step. The data is like: {"title": ["\u2605\u2605 The New J7 - Social Offer \u2605\u2605"], "seller": ["Galaxy"]} What I need to do: Read each item Remove special characters, which I don't know how to read because they are decoded like this: \u2605\u2605 Remove stop words Save the new data in Excel file I've read a lot of threads about importing Json to Excel but all declare a way of importing it all at once in whole block without modifying the data. EDIT: Here is my final code that reads the json file, edit the values and save them to excel, I hope it will help others too. import json import pandas as pd from nltk.corpus import stopwords import re import codecs data = "" stopwords_list = stopwords.words('english') with codecs.open("data.json", 'r', 'utf8') as data_file: data = json.load(data_file) for item in data: for key in item: if key == "title": temp = str(item[key]).lower() temp = re.sub('[`~!@#$^&amp;*()\-_=+{};:\'",&lt;.&gt;/?\\|\[\]★]', '', temp) temp = ' '.join([word for word in temp.split() if word not in stopwords_list]) item[key] = temp with codecs.open('new_data.json', 'w', 'utf8') as new_data_file: json.dump(data, new_data_file) df = pd.read_json(codecs.open('new_data.json','r','utf-8')) df.to_excel('out.xlsx')

http://stackoverflow.com/q/51481038
score: 2
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89930752
has comment: http://stackoverflow.com/comment/90038720
has comment: http://stackoverflow.com/comment/89935217
tagged with: python
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: swig
has answer: http://stackoverflow.com/a/51542016
has title: Calling function in C that receives pointer to function from Python
tagged with: http://stackoverflow.com/tag/c
type: Question
has body: I am using Swig to make a python library from C source code. There is a function that receives a pointer to function in C. I need to call it from Python but the callback function must be in Python. All documentation I have seen uses callback functions in C. Example: typedef double (*FeeCalculator)(Transaction* p); void dealTransaction(Transaction* t, FeeCalculator feeCalculator); I want that function to be usable in Python. Something like: def myFeeCalculator(tran): return trans.Sum * 0.1 def main(): t = Transaction() dealTransaction(t, myFeeCalculator)

http://stackoverflow.com/q/51341690
has comment: http://stackoverflow.com/comment/89658573
accepted answer: http://stackoverflow.com/a/51342531
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89656882
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89656878
tagged with: python
type: AnsweredQuestion
score: 2
has body: I'm working on a program where I would like to report the status of specific variables from time to time, however, I don't necessarily know which variables I'll need apriori. Other programs I have worked on (in C++) use a registration system where the variables of interest are registered with a central output processor once, then when program status needs to be reported, a central module gathers the data from the output variables and writes to an output file. So, the program flow would be something like this. Example MyModule.py from OutputProcessor import OutputProcessor class MyClass(): def __init__(self): op = OutputProcessor() # variable I want to report self.foo = None # register with output processor op.register_output_variable(self.foo, "Foo") def calc_foo(self, bar, rand): self.foo = bar ** rand Example OutputProcessor.py class OutputProcessor(object): # list or dict object containing the name and link information to variables of interest output_vars_data = [] def __init__(self): pass def register_output_variable(self, var, name): OutputProcessor.output_vars_data.append({"link address": id(var), "name": name}) def report_output(self): for data in OutputProcessor.output_vars_data: self.write_to_output_file(data) def write_to_output_file(self, data): # write all of the data to the output file here pass Example Main.py import random from MyClass import MyClass from OutputProcessor import OutputProcessor as OP if __name__ == "__main__": cls_instance = MyClass() for i in range(100): cls_instance.calc_foo(i, random.randint(1, 10)) OP().report_output() My first question: is this even possible, or practicable? Second, if so, how would I go about doing this? There are going to be some nuances to deal with, like how to handle multiple instances of the same class reporting the same variable, but that seems like a small issue. Is there a way to implement this so that I'm always getting the current value of the variable, and not just an old copy of it? Any thoughts, or s…
upvote count: 2
has comment: http://stackoverflow.com/comment/89656886
has title: Symbolic Links to Variables
type: Question
has comment: http://stackoverflow.com/comment/89658680
has answer: http://stackoverflow.com/a/51342531
has comment: http://stackoverflow.com/comment/89657639

http://stackoverflow.com/comment/89927348
score: 0
type: Comment
has text: Great. Thank you!! Just building now. Will report back ASAP!
type: AnswerComment
comment on: http://stackoverflow.com/a/51479495

http://stackoverflow.com/q/51429167
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
tagged with: mqtt
tagged with: python
has body: I run Mosquito MQTT on docker as follows: broker: image: "toke/mosquitto" ports: - "1883:1883" - "9001:9001" Then I want to subscribe to a topic queue1, publish a message ON and confirm that it was published (i.e. consume it). This is my current code: def on_connect(client, userdata, flags, rc): print('connected (%s)' % client._client_id) def on_message(client, userdata, message): print('------------------------------') print('topic: %s' % message.topic) print('payload: %s' % message.payload) print('qos: %d' % message.qos) broker = "localhost" port = 1883 mqttc = mqtt.Client("client") mqttc.on_connect = on_connect mqttc.on_message = on_message print("connecting to broker ", broker) mqttc.connect(broker, port, 60) mqttc.loop_start() print("subscribing ") mqttc.subscribe("queue1") time.sleep(2) print("publishing ") res = mqttc.publish("queue1","ON") time.sleep(10) mqttc.disconnect() mqttc.loop_stop() But it gives me the following feedback. It looks like the message is not published: connecting to broker 127.0.0.1 subscribing connected (b'client') publishing ------------------------------ topic: queue1 payload: b'ON' qos: 0
type: Question
tagged with: paho
has comment: http://stackoverflow.com/comment/89835103
score: 0
tagged with: mosquitto
has comment: http://stackoverflow.com/comment/89844960
has title: Cannot publish a message to MQTT topic in Python

http://stackoverflow.com/a/51482245
answers question: http://stackoverflow.com/q/51476745
score: 0
has body: Edited Sorry for the misunderstanding of the question. I think the conversion of the zip file can be done as follows. I assume that the 1st and last positions of the file are { and } respectively without any newlines symbols. data = eval(f"[{file.replace('\n', ',')}") Also being inspired by this post I can offer a solution using pure pandas. If we import the data into a pandas DataFrame, by passing to the constructor a list of the dictionaries above, the problem becomes in how to explode a list within a DataFrame's cell. This is done by the combination of .apply(pd.Series) that creates multiple columns for the different elements within the list and pd.melt that transforms those columns back into a single column. By previously setting as index the other columns we can save them for the resulting DataFrame. Here the code: # Formatting the data to be introduced in the pd.DataFrame data = [{"id":"1","f":"A","data":[["2040",0],["2039",0],["2038",0],["2037",0],["2036",0]]}, {"id":"2","f":"A","data":[["2040",0],["2039",0],["2038",0],["2037",0],["2036",0]]}, {"id":"3","f":"A","data":[["2040",0],["2039",0],["2038",0],["2037",0],["2036",0]]}, {"id":"4","f":"A","data":[["2040",0],["2039",0],["2038",0],["2037",0],["2036",0]]}, {"id":"5","f":"A","data":[["2040",0],["2039",0],["2038",0],["2037",0],["2036", 0]]} ] # And the piece of code (pd.melt((pd.DataFrame(data) .assign(data=lambda x: [[l[0] for l in ls] for ls in x.data]) .set_index(['id', 'f']) .data.apply(pd.Series) .reset_index() ), id_vars=['id', 'f'], value_name='data' ) .set_index(['id', 'f']) .drop('variable', axis=1) .dropna() .sort_index() .reset_index() ) id f data 0 1 A 2040 1 1 A 2039 2 1 A 2038 3 1 A 2037 4 1 A 2036 5 2 A 2040 6 2 A 2039 7 2 A 2038 8 2 A 2037 9 2 A 2036 10 3 A 2040 11 3 A 2039 12 3 A 2038 13 3 A 2037 14 3 A 2036 15 4 A 2040 16 4 A 2039 17 4 A 2038 18 4 A 2037 19 4 A 2036 20 5 A 2040 21 5 A 2039 22 5 A 2038 23 5 A 2037 24 5 A 2036
type: Answer
has comment: http://stackoverflow.com/comment/89948849

http://stackoverflow.com/comment/89767748
comment on: http://stackoverflow.com/a/51397556
score: 0
type: Comment
has text: Give me application name (python package name) of urls.py file specified above. I see you have `main` and `upload` packages. You should rewrite urls pattern to **pass reference to view function**. I don't know your project structure and urls patterns
type: AnswerComment

http://stackoverflow.com/comment/89903555
comment on: http://stackoverflow.com/q/51461881
type: Comment
type: QuestionComment
has text: Oh yes forgot to mention, there is `import Cookies, os` at the top of my code
score: 0

http://stackoverflow.com/q/51482153
has title: Threaded Python script only seems to work as expected after signaling keyboard interrupt?
has comment: http://stackoverflow.com/comment/89933968
has comment: http://stackoverflow.com/comment/89940299
has comment: http://stackoverflow.com/comment/89939975
score: 0
has body: Basically, I have a script that sniffs packets in one thread, and appends them to a list. A second thread also runs, and if the list is not empty, then it will perform calculations with the data. However, the sniffing thread only seems to work properly after hitting Ctrl + C. Before sending the keyboard interrupt, console output that I've produced for debugging is very slow and it seems to be missing packets. Afterwards hitting Ctrl + C it runs much faster and works as expected. Any ideas why this might be occurring? My code would look something similar to what is below. Packet sniffer: import socket, sys from struct import * def eth_addr(a): #create a AF_PACKET type raw socket (thats basically packet level) #define ETH_P_ALL 0x0003 /* Every packet (be careful!!!) */ try: s = socket.socket( socket.AF_PACKET , socket.SOCK_RAW , socket.ntohs(0x0003)) except socket.error , msg: print 'Socket could not be created. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] sys.exit() def packet_sniff(): # receive a packet while True: packet = s.recvfrom(65565) #packet string from tuple packet = packet[0] #parse ethernet header eth_length = 14 eth_header = packet[:eth_length] eth = unpack('!6s6sH' , eth_header) eth_protocol = socket.ntohs(eth[2]) print 'Destination MAC : ' + eth_addr(packet[0:6]) + ' Source MAC : ' + eth_addr(packet[6:12]) + ' Protocol : ' + str(eth_protocol) #TCP protocol if protocol == 6 : t = iph_length + eth_length tcp_header = packet[t:t+20] #now unpack them tcph = unpack('!HHLLBBHHH' , tcp_header) source_port = tcph[0] dest_port = tcph[1] sequence = tcph[2] acknowledgement = tcph[3] doff_reserved = tcph[4] tcph_length = doff_reserved &gt;&gt; 4 print 'Source Port : ' + str(source_port) + ' Dest Port : ' + str(dest_port) + ' Sequence Number : ' + str(sequence) + ' Acknowledgement : ' + str(acknowledgement) + ' TCP header length : ' + str(tcph_length) h_size = eth_length + iph_length + tcph_length * 4 data_size = len(packet) - h_size #get data from the packe…
has comment: http://stackoverflow.com/comment/89940135
has comment: http://stackoverflow.com/comment/89940497
linked to: http://stackoverflow.com/q/419163
accepted answer: http://stackoverflow.com/a/51485940
tagged with: python-multithreading
tagged with: multithreading
tagged with: python
has comment: http://stackoverflow.com/comment/89940760
has comment: http://stackoverflow.com/comment/89940548
type: AnsweredQuestion
type: Question
tagged with: debugging
tagged with: network-programming
has comment: http://stackoverflow.com/comment/89934534
has answer: http://stackoverflow.com/a/51485940
answer count: 1

http://stackoverflow.com/q/51329685
type: UnansweredQuestion
downvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/51329855
has body: i am trying to remove lines from a .txt file that contains duplicated substrings. lets say i have lines like this: aaaaaa, something.... bbbbbb, something differet.. cccccc, some other text.. cccccc, again different text.. dddddd, again some other text.. eeeeee, some other text... etc.. i want to filter out all the lines that start with the same substring (first N chars), so that there will be only one (the first one) line starting with it. these i want to copy to a new txt file. so in the example above the first three lines would be copied, the fourth would be skipped and the rest would be copied. i want to copy all the lines, not only the substring that i am checking this is what i have written based on what i have found lines_seen = set() outfile = open(outfile, "w") for line in open(infile, "r"): string_to_compare = line[0:N] #save the substring into a variable if line.startswith(string_to_compare) not in lines_seen: outfile.write(line) lines_seen.add(line) outfile.close() this code above actually copies all the lines from the outfile into infile, so no filtering is done. can anyone tell me where is the mistake or how to make it work, please?
upvote count: 1
has comment: http://stackoverflow.com/comment/89635012
type: Question
has comment: http://stackoverflow.com/comment/89635249
has comment: http://stackoverflow.com/comment/89669401
has comment: http://stackoverflow.com/comment/89669293
answer count: 1
tagged with: string
has title: how to remove lines with duplicated substrings from txt file in python?
favorite count: 0
score: -1

http://stackoverflow.com/comment/89913855
comment on: http://stackoverflow.com/q/51444291
has text: @ChristianBertsch Exactly what I was looking for. Thank you
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89750161
comment on: http://stackoverflow.com/a/51388829
score: 0
has text: @dataviews added some clarification, hope that helps
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51420822
type: Question
score: 0
has title: Pandas calculation - index 0 is out of bounds for axis 0 with size 0
upvote count: 1
downvote count: 1
favorite count: 0
tagged with: python
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89813345
has body: I am loading 2 comma seperated values and one identifier from a csv into a dataframe. After that, I replace the commas with dots and cast them to a float: tzeitverbrauch = [] df = df.apply(lambda x: x.str.replace(',', '.')) df.Aufwand_geplant = df.Aufwand_geplant.astype(float).fillna(0.0) df.Aufwand_laufend_ist = df.Aufwand_laufend_ist.astype(float).fillna(0.0) After that I am calling a function which calculates the difference for these 2 values for one identifier: def calculate(identifier): aufwand_geplant = df.loc[(df.Identifier == identifier), 'Aufwand_geplant'].values[0] aufwand_ist = df.loc[(df.Identifier == identifier), 'Aufwand_laufend_ist'].values[0] x = aufwand_ist - aufwand_geplant tzeitverbrauch.append(x) for x in df_identifier: calculate(x) However, for some strange reason I have results and everything is okay when i debug the code but on some point the exception is popping up: Traceback (most recent call last): File "H:/PycharmProjects/PycharmProjects/PP-KPI/Levenshtein.py", line 53, in &lt;module&gt; calculate(x) File "H:/PycharmProjects/PycharmProjects/PP-KPI/Levenshtein.py", line 43, in calculate aufwand_geplant = df.loc[(df.identifier == identifier), 'Aufwand_geplant'].values[0] IndexError: index 0 is out of bounds for axis 0 with size 0 The values here: print(len(df.Aufwand_geplant)) = 125 print(len(df.Aufwand_laufend_ist)) = 125 print(len(df_identifier)) = 125 I appreciate some input and help how to identify the problem!
has comment: http://stackoverflow.com/comment/89813172
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89814166

http://stackoverflow.com/comment/89825542
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51414622
has text: The answer is yes, your assumptions are correct. Note also that there is an `OrderedDictionary` class in Pharo 6.1.
type: Comment

http://stackoverflow.com/q/51471728
type: Question
score: -2
has comment: http://stackoverflow.com/comment/89911762
has comment: http://stackoverflow.com/comment/89914264
has answer: http://stackoverflow.com/a/51471785
has comment: http://stackoverflow.com/comment/89911767
linked to: http://stackoverflow.com/q/19904120
answer count: 2
has answer: http://stackoverflow.com/a/51474475
favorite count: 0
has body: with open('90_out.csv', 'w') as f: data = open('A:/pycharm/study0722/data/90.txt', 'r') f.write('year, month, day, tmax, tavg, tmin, rainfall') f.write('\n') for line in data: tokens = line.split() year = int(tokens[0]) month = int(tokens[1]) day = int(tokens[2]) tmax = float(tokens[3]) tavg = float(tokens[4]) tmin = float(tokens[5]) rainfall = float(tokens[10]) f.write("{:d}, {:d}, {:d}, {:.1f}, {:.1f}, {:.1f}, {:.1f}".format(year, month, day, tmax, tavg, tmin, rainfall)) f.write('\n') I modified and saved one txt file with the above code. Approximately 50 files should be worked in the same way. but i don't know how to open multiple files and save each other. *i used pycharm
has comment: http://stackoverflow.com/comment/89912631
has title: how to open, modify, and save multiple .txt files?
type: UnansweredQuestion
tagged with: python
upvote count: 0
has comment: http://stackoverflow.com/comment/89914346
tagged with: pycharm
has comment: http://stackoverflow.com/comment/89912113
downvote count: 2
tagged with: file

http://stackoverflow.com/comment/89675037
score: 0
comment on: http://stackoverflow.com/q/51332144
type: Comment
type: QuestionComment
has text: I don´t understand your question in detail., maybe you can rephrase it? I am working with something similar. I also have text data and numerical data. In my case I have n sentences, where every sentence (seq of words in embedding space) is going through its "own" LSTM but the weights are shared. Finally I put all LSTM output into a 1D convolution and after that concat with the numerical data.

http://stackoverflow.com/comment/89860510
comment on: http://stackoverflow.com/a/51410081
score: 1
type: AnswerComment
type: Comment
has text: Hi Vikas NS, I still struggle with that error although I try to use your solution, do you have any idea to solve it?? this is my error: ValueError: Error when checking input: expected conv1d_1_input to have 3 dimensions, but got array with shape (1, 15)

http://stackoverflow.com/comment/89885805
type: AnswerComment
has text: OP example contains multiple consecutive or near-consecutive newlines per string. `strip()` won't get them all.
comment on: http://stackoverflow.com/a/51458231
score: 0
type: Comment

http://stackoverflow.com/q/51432598
score: 1
has title: Duplicating y axes
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89836544
tagged with: matplotlib
tagged with: duplicates
has comment: http://stackoverflow.com/comment/89836576
answer count: 1
downvote count: 0
favorite count: 0
tagged with: axes
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51433019
linked to: http://stackoverflow.com/q/23965223
has comment: http://stackoverflow.com/comment/89836403
tagged with: multiple-axes
has body: I have the below code. In a nutshell, I need to duplicate the bottom x axes so I keep already plotted data (in place) but change the xlim. I have tried set_xlim after plotting the data (just readjusts the data to the new scale (as expected); also tried to duplicate the axis (with twiny) and then customise with a new scale (and then add lines with axvline). The below way works, however, the label is now not sticking with the axes! I thought I must be missing something. Any suggestions? import matplotlib.pyplot as plt plt.plot([1,2,1,4,5],[1,2,3,4,5], marker='o', label='value 1') plt.plot([3,1,3,1,2],[1,2,3,4,5], label='value 2') plt.gca().get_xaxis().set_visible(False) ax1 = plt.twiny() ax2 = ax1.twiny() ax1.set_xlabel('TOP') ax2.set_xlabel('BOTTOM') plt.savefig(fname='test.png') plt.show() It's very much like this question (Changing axis without changing data (Python)), but I use a constant (say 0 to 750) as the original plot and the range I want to set the xlim to is somewhat unrelated to the original data (say 0 to 30000).

http://stackoverflow.com/comment/89730069
type: Comment
score: 1
has text: What are the possible dimensions of the lawn? Is it always rectangular, or can it have more than 4 sides? How many pieces would you like the lawn to be divided into? Does this change with the size of the lawn? Or is it based on a fixed size of 'piece'? What if the lawn is smaller than this size? **What have you tried so far?**
type: QuestionComment
comment on: http://stackoverflow.com/q/51379058

http://stackoverflow.com/q/51409861
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89791261
upvote count: 1
tagged with: python
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89791172
has answer: http://stackoverflow.com/a/51410258
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/89791769
has body: I have two numpy array's that look like the following: a = np.array([[1, 10], [2, 12], [3, 5]]) b = np.array([[1, 0.78], [3, 0.23]]) The first number in the list is the id parameter, and the second one is a value. I'm looking to combine them. The expected output to be equal to this: np.array([1, 10, 0.78], [2, 12, 0], [3, 5, 0.23]) Is there a function (or combination of functions that can do this for me? Any help is greatly appreciated. If an object is not found, a 0 is put in it's place.
tagged with: data-manipulation
answer count: 1
score: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51410258
has title: Perform a 'join' on two numpy arrays
favorite count: 0

http://stackoverflow.com/a/51347836
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/89671211
has comment: http://stackoverflow.com/comment/89671270
accepted answer of: http://stackoverflow.com/q/51347770
upvote count: 10
has comment: http://stackoverflow.com/comment/89672189
answers question: http://stackoverflow.com/q/51347770
has body: cPython has two main ways to call C code: either by loading a shared library and calling its symbols, or by packing C code as Python binary modules and then calling them from Python code as though they were ordinary Python modules, which is how high performance stuff in the standard library is implemented - e.g. json. Loading a shared library and calling functions from it using the ctypes module is rather trivial, and you can find a lot of examples here: https://docs.python.org/3/library/ctypes.html Packing your C code as binary Python module requires a lot of boilerplate and careful attention to details such as ref counting, null pointers, etc, and is documented here: https://docs.python.org/2/extending/extending.html There are several libraries that automate the process and generate binding code for you. One example is boost.python: https://www.boost.org/doc/libs/1_65_0/libs/python/doc/html/tutorial/index.html
score: 10
type: AcceptedAnswer

http://stackoverflow.com/q/51349907
tagged with: python
has body: Now there are 3 solutions to resize a image: 1st: img = Image.open('C:\\Users\\Vishal\\Desktop\\Test\\xyx.jpg') img = img.resize((90, 90), Image.ANTIALIAS) img.save('C:\\Users\\Vishal\\Desktop\\Test\\xyz.jpg') 2nd : img = Image.open('C:\\Users\\Vishal\\Desktop\\Test\\xyx.jpg') bg = Image.new("RGB", img.size, (255, 255, 255)) bg.paste(img, img) bg = bg.resize((90, 90), Image.ANTIALIAS) bg.save('C:\\Users\\Vishal\\Desktop\\Test\\xyz.jpg') and the 3rd: img = Image.open('C:\\Users\\Vishal\\Desktop\\Test\\xyx.jpg') img = img.convert('RGB') img = img.resize((90, 90), Image.ANTIALIAS) img.save('C:\\Users\\Vishal\\Desktop\\Test\\xyz.jpg') For cases, The problems with 1st comes as error "cannot write mode RGBA as JPEG", for 2nd it comes as "bad transparency mask" and the problem with third is that it works in all cases but the images with transparency after resizing get their background as black which is not acceptable,also distorted colors pixels can be seen near the edges. So what can be the universal solution to these problems? Note:(The output format required is .jpg and the images to be resized varies in the format as they are getting scraped, mostly .png with transparent background) Update: As per comments I have placed an if else based on alpha condition as: img = Image.open('C:\\Users\\Vishal\\Desktop\\Test\\xyx.jpg") has_alpha = img.mode == 'RGBA' print(has_alpha) if has_alpha == True: bg = Image.new("RGB", img.size, (255, 255, 255)) bg.paste(img, img) bg = bg.resize((80, 80), Image.ANTIALIAS) bg.save('C:\\Users\\Vishal\\Desktop\\Test\\xyz.jpg", quality=92) else: img.resize((80, 80), Image.ANTIALIAS) img.save('C:\\Users\\Vishal\\Desktop\\Test\\xyz.jpg", quality=92) It is working fine, But In some rare cases, has_alpha being false, I'm getting following error. False Traceback (most recent call last): File "C:\Intel\lib\site-packages\PIL\JpegImagePlugin.py", line 620, in _save rawmode = RAWMODE[im.mode] KeyError: 'P' During handling of the above exception, another exc…
has comment: http://stackoverflow.com/comment/89672845
downvote count: 0
has comment: http://stackoverflow.com/comment/89678094
type: AnsweredQuestion
tagged with: python-imaging-library
score: 1
tagged with: image
type: Question
upvote count: 1
answer count: 1
favorite count: 0
has title: Expert Advice needed to resize image in Python as Existing solutions have exceptions
has comment: http://stackoverflow.com/comment/89677299
has answer: http://stackoverflow.com/a/51352124
accepted answer: http://stackoverflow.com/a/51352124
has comment: http://stackoverflow.com/comment/89672447

http://stackoverflow.com/comment/89770255
comment on: http://stackoverflow.com/a/51389319
has text: @Py_Mel just made a tiny change in the answer to solve your problem
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89831833
type: QuestionComment
score: 0
type: Comment
has text: side question ... does that link you refer to http://mriquestions.com supply sample dataset files similar to the one you plot above ?
comment on: http://stackoverflow.com/q/51429792

http://stackoverflow.com/q/51401774
type: AnsweredQuestion
score: 2
tagged with: pythonpath
downvote count: 0
favorite count: 0
has title: Prevent PyCharm from extending sys.path
has answer: http://stackoverflow.com/a/51401872
type: Question
tagged with: path
tagged with: python
has body: It really bugs (ha.) me that PyCharm executes scripts ever so slightly differently than plain command line execution. It makes project and package configuration hard for a relative newbie like me. Problem: Every time a script is run, either normally or in the Python console (Run > Edit conf.) the script folder and the project root are automagically appended to sys.path. I'd expect either one, but not both. So, is there a way to disable or otherwise configure this appending? I'd like to do it without manipulating the path in the beginning of every executable script, but if there's a way to use a startup script or a run script of some sort, that'd be fine.
tagged with: pycharm
upvote count: 2
answer count: 1
accepted answer: http://stackoverflow.com/a/51401872

http://stackoverflow.com/comment/89866310
has text: @Edmond301 Please make sure to select the check mark next to the answer that solved your issue.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51446674

http://stackoverflow.com/comment/89871596
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51450298
type: QuestionComment
has text: PowerControl does not do anything except wrap either PowerControlA or PowerControl B. Can you explain what a factory function is?

http://stackoverflow.com/q/51448795
favorite count: 0
tagged with: python
score: 2
upvote count: 2
type: UnansweredQuestion
has title: Bokeh hover tool showing '???' instead of ColumnDataSource value
has body: I am trying to add a hover tooltip to my bokeh plot. The tooltip shows up, but the area value I am trying to display shows up as '???'. I am using ColumnDataSource to set the plot source data, and area is a valid column in that data source. I can't figure out why the plot can't fine the area values. source = ColumnDataSource(data=df.groupby('state').sum()) TOOLTIPS = [("area", "@%area")] p = figure(x_range=source.data['state'], width=1300, height=1000) p.vbar(x=source.data['state'], top=source.data['area'], width=.5) from bokeh.models import HoverTool p.add_tools(HoverTool(tooltips=TOOLTIPS))
tagged with: bokeh
has answer: http://stackoverflow.com/a/51449651
type: Question
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/89672133
type: QuestionComment
comment on: http://stackoverflow.com/q/51342717
score: 1
has text: @g_kub: SDL2 is not installed in your venv. Please refer to [sdl2 - ImportError: DLL load failed: The specified module could not be found.](https://stackoverflow.com/questions/49466785/kivy-error-python-2-7-sdl2-import-error/49477111#49477111)
type: Comment

http://stackoverflow.com/comment/89809573
score: 0
type: AnswerComment
has text: I tried with the following; `l = []` `for s_row in self.final_df.itertuples():` `for o_row in` `self.obsolete_dataframe.loc[self.obsolete_dataframe['SUBSYSTEM_TYPE'] ==` `s_row[26]].itertuples():` `if s_row[28] == o_row[2]: # compare EDITION` `l.append((s_row[28], s_row[2]))` `elif o_row[2] == '*':` `l.append((s_row[28], s_row[2]))` However it took a very, very long time, the df has around 300k entries so will have to search for something more optimised. Thanks for the suggestion!
type: Comment
comment on: http://stackoverflow.com/a/51417735

http://stackoverflow.com/comment/89933309
type: AnswerComment
comment on: http://stackoverflow.com/a/51482242
has text: Can't prove it right now, but not sure if this is still faster for big df's. Would guess `df.gt(0)` gets faster
score: 0
type: Comment

http://stackoverflow.com/comment/89688825
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51358247
has text: Have you tried anything ? Please provide the code that you have tried before posting here.
score: 0

http://stackoverflow.com/comment/89752250
has text: Why do you have `'id'` in quotes?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51389981

http://stackoverflow.com/comment/89632416
has text: That sounds like a very reasonable change. There is a council of elders that reviews database changes, and making reasonable requests of them is fraught with peril :-/ Nobody cares what my test code does though.... Also, "just don't do a group by" is the answer to my question. I'll accept it if you post it.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51327600
score: 0

http://stackoverflow.com/a/51459629
upvote count: 10
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51456403
has body: If you've already imported from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * there is no need to from PyQt5 import * Once you've imported QtCore, you no longer need to call its functions/classes with 'QtCore.QEvent', Just using QEvent is fine I believe the question you linked to used PyQt4. In PyQt5, the initialization procedure for the class changed The code below should work. from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys class mouseoverEvent(QWidget): def __init__(self): super().__init__() self.stop = False # your 'stop' variable self.initUI() def initUI(self): self.lbl=QLabel(self) self.lbl.setText("Hover over me to stop the program") self.lbl.installEventFilter(self) self.setGeometry(1000, 30, 300, 100) self.setWindowTitle('QLineEdit') self.show() def eventFilter(self, object, event): if event.type() == QEvent.Enter: print("Mouse is over the label") self.stop = True print('program stop is', self.stop) return True elif event.type() == QEvent.Leave: print("Mouse is not over the label") self.stop = False print('program stop is', self.stop) return False if __name__ == '__main__': app = QApplication(sys.argv) ex = mouseoverEvent() sys.exit(app.exec_()) if you only want the stop to activate over a label with certain text change your eventFilter function to: def eventFilter(self, object, event): if hasattr(object, 'text'): #check to see if the object has text, otherwise if you hover over something without text, PyQt will return an error if object.text() == "Hover over me to stop the program": if event.type() == QEvent.Enter: print("Mouse is over the label") self.stop = True print('program stop is', self.stop) return True elif event.type() == QEvent.Leave: print("Mouse is not over the label") self.stop = False print('program stop is', self.stop) return False
score: 9

http://stackoverflow.com/comment/89756107
has text: yeah this works: reader = PyPDF2.PdfFileReader(open(os.path.join(path1, pdfname), 'rb')) print(reader.getNumPages())
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51372164
type: Comment

http://stackoverflow.com/q/51391328
tagged with: import
type: Question
has title: Python: How to best handle developing a library and an application that uses it simultaneously?
score: 4
has comment: http://stackoverflow.com/comment/89758839
upvote count: 4
has comment: http://stackoverflow.com/comment/89758804
has body: Example directory structure of current project: myproject/ | +-- mylibrary/ | | | +-- __init__.py | | | +-- (code files) | +-- webapi/ | | | +-- __init__.py &lt;-- contains Flask API code and blueprints, using the mylibrary code | | | +-- object/ | | | +-- __init__.py &lt;-- Flask API code for "object"s, imported via blueprints | +-- cli/ | | | +-- __init__.py &lt;-- argparse, code to use the mylibrary code from the CLI, etc. | +-- gui_app/ | +-- __init__.py &lt;-- the start of a GUI application, using the mylibrary code I am the sole developer, and am developing all of the above pieces of the application in parallel. My questions: How can I best handle writing import statements in the three projects (webapi, cli and gui_app) to import code from the mylibrary module? I see three options: Use PYTHONPATH or sys.path to add .. to the path of each app using the library. This works for the __init__.py files, but I'm not sure how to do it from, say, webapi/object/__init__.py without basically adding ../.. to sys.path. Additionally, this makes the application much harder to later distribute. Restructure the application so that each "user" of the library is a submodule of the library; then I can do from .. import mylibrary. This is a bad idea because it basically makes the entire mylibrary module "monolithic". Each time I make a chance to mylibrary, install it into my site-packages. Then just develop the other three applications using import mylibrary. This is quite a pain however, since I'm developing all four pieces of the application in parallel. I would be planning to distribute mylibrary on its own, so it could be installed by e.g. pip. Then, separately, one can install webapi or gui_app. (Perhaps cli could be merged into mylibrary so that if it's run as a module it will present the CLI, but still doesn't solve the problem for the other two apps) This is my first experience writing a code library at the same time as more than one application that will make use of that …
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: module
has comment: http://stackoverflow.com/comment/89754967
has answer: http://stackoverflow.com/a/51406030

http://stackoverflow.com/q/51437165
tagged with: python
type: AnsweredQuestion
tagged with: screen-scraping
type: Question
has body: So, i am kinda of a new python programmer, if i can call myself like that, and i am trying to learn through the "picking new projects" procedure. What i want to do now is : enter a website that gives live score results as http://www.livescore.com for example. somehow scrape all the teams that playing against each other and manipulate those data. Then i want to build an app that takes those data, arrange them nicely in a table format (let's say) and then update it every time a team scores a goal (possibly through scrapping again ? i don't know..). So i want to project them as my own data. As i am new to python, i don't even know if that's possible to be done. If so, can you help me ? Point me to some directions maybe, point me specific chapters of python to read, specific modules etc etc ? I really need any help i can get because i am really lost on the matter. I don't know where to begin with. Thanks in advance
accepted answer: http://stackoverflow.com/a/51437430
upvote count: 0
score: -2
answer count: 1
tagged with: javascript
has comment: http://stackoverflow.com/comment/89844208
favorite count: 0
has title: Python, Scraping Data from javascript website
tagged with: web
downvote count: 2
has answer: http://stackoverflow.com/a/51437430

http://stackoverflow.com/comment/89893213
type: QuestionComment
comment on: http://stackoverflow.com/q/51461696
has text: @NeerajNair what do you mean by "place the code in same window but different window" ? Also you told to destroy login window but did't tell how to invoke my main application.
score: 0
type: Comment

http://stackoverflow.com/comment/89791362
type: Comment
type: QuestionComment
has text: Which python are you using ?
comment on: http://stackoverflow.com/q/51409987
score: 0

http://stackoverflow.com/q/51382162
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/89833408
tagged with: python
has comment: http://stackoverflow.com/comment/89833453
accepted answer: http://stackoverflow.com/a/51431682
has comment: http://stackoverflow.com/comment/89833526
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51537351
upvote count: 10
has comment: http://stackoverflow.com/comment/89736075
type: Question
has title: Getting data from hidden html (popup) using BS4
has comment: http://stackoverflow.com/comment/89833289
score: 10
possible better answer: http://stackoverflow.com/a/51382249
has answer: http://stackoverflow.com/a/51382249
has answer: http://stackoverflow.com/a/51431682
answer count: 3
downvote count: 0
favorite count: 0
has body: I am trying to scrape the name of a link in a popup in wikipedia. So when you hover a link in wikipedia, it brings up a little snippet from the intro to that link. I need to scrape that information but I am unsure where it would be in the source. When I inspect the element(as it is popped up) this is the html (for this example I am hovering over the link "Greek") The Ancient Greek language includes the forms of Greek...(a bunch more text)... What I need to extract is the href which = "/wiki/Ancient_Greek" but this piece of html disappears when I am not hovering the link. Is there a way (with BS4 and python) to extract this information with the source html I am scraping? EDIT: I can't afford to make additional calls to webpages because the project takes long to run as it is. If there is anyway to change how I am retrieving the source such that I can get the popup information that would be helpful. This project is giant and getting this popup information is crucial. any suggestions at all that don't require a complete rebuild of the project is extremely appreciated-- I am using urllib to pull source(with requests) and bs4 to scrape through.

http://stackoverflow.com/a/51336388
has body: Another good solution is to use a dictionary: d={'y':t[0]} return d.get(val,t[1]) Output: y
type: Answer
answers question: http://stackoverflow.com/q/51336271
score: 0

http://stackoverflow.com/q/51397311
upvote count: 1
type: Question
has title: AttributeError: Assignment not allowed to composite field “id” in protocol message object
answer count: 1
downvote count: 0
has body: I'm using protocol-buffers python to assign values. but the error is generated as stated. proto file: message MovingObject{ // The ID of the object. // optional Identifier id = 1; // The base parameters of the vehicle. // // \note The bounding box does NOT includes mirrors for vehicles. // optional BaseMoving base = 2; // The type of the object. // optional Type type = 3;} python file: mo = osi_object_pb2.MovingObject() mo.id = 12 print(mo.id)
has answer: http://stackoverflow.com/a/51424689
favorite count: 0
tagged with: protocol-buffers
tagged with: python
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/51424689

http://stackoverflow.com/q/51374500
type: Question
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89720514
favorite count: 0
has answer: http://stackoverflow.com/a/51374594
has body: Using Ubuntu 16.04. In the main environment the following problem is not there. But I am using Docker and there I am facing the following issues. Have both python version 2.7(2.7.12) and 3.5(3.5.2). While using python3.5 it sometimes give error such as : .... .... File "/usr/lib/python2.7/urllib2.py", line 254 raise AttributeError, attr ^ SyntaxError: invalid syntax And python2.7 can not be used. $python2.7 File "/usr/lib/python3.5/site.py", line 182 file=sys.stderr) ^ SyntaxError: invalid syntax Seems, it is mixing-up with 3.5 and 2.7 and creating problems for both. Had searched for long, but could not found a solution yet. As it is suggested not to uninstall 2.7, so tried to 'remove' 3.5, but it ends up with error. I had installed 3.6 also. But it also can't used. Some other info, in case needed. $ python --version Python 2.7.12 $ python2 --version Python 2.7.12 $ python3 --version Python 3.5.2 $python2.7 -m site --user-site File "/usr/lib/python3.5/site.py", line 182 file=sys.stderr) ^ SyntaxError: invalid syntax $python3.5 -m site --user-site /root/.local/lib/python3.5/site-packages Under /usr/local/lib/python3.5/site-packages, there are a whole lots of packages, preinstalled and those I had installed later on. Whereas, under /usr/local/lib/python2.7/ there are two folders, /dist-packages and /site-packages and both are empty. I have mainly installed the packages using pip and pip3.5. $pip --version pip 10.0.1 from /usr/local/lib/python3.5/dist-packages/pip (python 3.5) $pip3 --version pip 10.0.1 from /usr/local/lib/python3.5/dist-packages/pip (python 3.5) $pip2 --version File "/usr/lib/python3.5/site.py", line 182 file=sys.stderr) ^ SyntaxError: invalid syntax Adding as a response to those had kindly suggested solutions. (1) Tried to remove 3.5 and 3.6, but both end up with error. Tried to remove 3.5 and 3.6, but ends up giving error. Even when trying to say, 3.6 with various other it gives the same error msg as, File "/usr/lib/python3.5/site.py", line 182 file…
tagged with: python
has title: Python 2.7 and 3.5 library mix-up?
score: 2
upvote count: 2
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/19256127
has answer: http://stackoverflow.com/a/51374575

http://stackoverflow.com/a/51330889
has comment: http://stackoverflow.com/comment/89637724
accepted answer of: http://stackoverflow.com/q/51330863
has comment: http://stackoverflow.com/comment/89637624
score: 3
has comment: http://stackoverflow.com/comment/89637579
has comment: http://stackoverflow.com/comment/89637505
has comment: http://stackoverflow.com/comment/89637557
has body: To reference the same model use the normal Python syntax self but as a string, Class Component(models.Model): name = models.CharField() description = models.CharField() status_ok = models.BooleanField() subcomponents = models.ForeignKey('self')
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51330863
downvote count: 0
has comment: http://stackoverflow.com/comment/89637662
type: Answer
upvote count: 3

http://stackoverflow.com/comment/89786917
score: 0
type: Comment
has text: I received this error... File "<ipython-input-13-9e979913de31>", line 1 for comment in soup.find_all(string=lambda text:isinstance(text,Comment)): ^ SyntaxError: unexpected EOF while parsing
type: AnswerComment
comment on: http://stackoverflow.com/a/51394509

http://stackoverflow.com/q/51346021
has title: Syntax Error running on Python
has answer: http://stackoverflow.com/a/51346402
answer count: 2
has comment: http://stackoverflow.com/comment/89665441
has body: I'm trying to follow the blockchain tutorial which is in JS but I'm trying it on Python. I've got this far and when I'm trying to test run it, I get this syntax error which is confusing me since it seems legit. Any thoughts? import hashlib class block: def __init__(self, index, timestamp, data, previous= ''): self.index = index self.timestamp = timestamp self.data= data self.previous = previous self.hash = '' def calculateHash(self): return hashlib.sha256(self.index + self.previous + self.timestamp+ (self.data).__str__() class blockchain: #btw this it where it says the error is: "class" def __init__(self): self.chain= [self.createGenesisBlock()] def createGenesisBlock(self): return block(0, "01/01/2017", "Genesis Block", "0") def getLatestBlock(self): return self.chain[len(self.chain)-1] def addBlock(self, newBlock): newBlock.previous = self.getLatestBlock().hash newBlock.hash= newBlock.calculateHash() self.chain.push(newBlock) korCoin = blockchain() korCoin.addBlock(block(1, "10/07/2017", 4)) korCoin.addBlock(block(2, "12/07/2017", 40)) if __name__ = "__main__": print(korCoin)
possible better answer: http://stackoverflow.com/a/51346100
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/51346402
score: -1
tagged with: blockchain
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89665060
downvote count: 1
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/51346100

http://stackoverflow.com/comment/89636733
score: 0
has text: This is very elegant and exactly what I was looking for. The way that `data` is defined makes it easiest to get the information from the read lines that I need. Thank you so much!
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51330247

http://stackoverflow.com/a/51402765
score: 0
has comment: http://stackoverflow.com/comment/89777575
type: Answer
has body: This is just an attempt to make sure the server doesnt blacklist me thinking the requests are all coming from the same place if that is one of your intentions as well. It still floods the server but by trying to deceive making it think the requests are not coming from the same place. There are times when I also switch between VPNs to have different IPs. This is a snippet of using a fake user agent: from fake_useragent import UserAgent ua1 = UserAgent() randomHeader = {'User-Agent':str(ua1.random)} page = requests.get(restListLink, randomHeader) If putting a delay between requests is not a concern for you, then you can also try to add a random delay mechanism between requests. For the delay, you can check the sleep function! import time time.sleep(0.100)
answers question: http://stackoverflow.com/q/51398543
has comment: http://stackoverflow.com/comment/89777305
has comment: http://stackoverflow.com/comment/89776545
has comment: http://stackoverflow.com/comment/89776652
has comment: http://stackoverflow.com/comment/89776628

http://stackoverflow.com/q/51344978
possible better answer: http://stackoverflow.com/a/66680887
has body: I am starting on a code that loads and edits excel (the version I am using is office 2017) sheet using openpyxl. Right now I am still trying to wrap my head around how this module works, here's the code import openpyxl from openpyxl import load_workbook from openpyxl import workbook from openpyxl.compat import range from openpyxl.utils import get_column_letter import os os.chdir("D:\Scripts\Python\Testing Scripts\My Excel Folder") wb = load_workbook("MyExcel.xlsx") names = wb.sheetnames() print(names) print(type(wb)) and the error I receive is, TypeError: 'list' object is not callable For the string of code names = wb.sheetnames()
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51344991
favorite count: 0
upvote count: 3
tagged with: typeerror
tagged with: python
has answer: http://stackoverflow.com/a/66680887
tagged with: python-3.x
downvote count: 0
tagged with: openpyxl
has title: python openpyxl get sheet names
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/51344991

http://stackoverflow.com/comment/89945682
score: 1
comment on: http://stackoverflow.com/q/51447406
has text: Hi there yes you can do this will provide a working example shortly.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51396342
has answer: http://stackoverflow.com/a/51396508
answer count: 3
has body: import time def taym(): time.sleep(5) def getprice(): myfile = open('C:\\Users\\DELL\\Desktop\\Python\\html1.html') txt = myfile.read() t = txt.find("$") it = float(txt[t-4:t]) it=8 while it != 1000: getprice() if it &lt;= 4.74: print("Price is Ok!") taym() else: print("The price of the coffee beans is "+txt[t-4:t+1]) taym() When I run this code in python3, I get an error message like this: "print("The price of the coffee beans is "+txt[t-4:t+1]) NameError: name 'txt' is not defined." I know I could use the original code from getprice() inside the loop, but I need to know why doesn't it work when I have a function that I call.
tagged with: function
has answer: http://stackoverflow.com/a/61488592
tagged with: variables
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/51396508
tagged with: text-files
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51396373
upvote count: 2
downvote count: 3
tagged with: file
has comment: http://stackoverflow.com/comment/89763824
possible better answer: http://stackoverflow.com/a/51396373
type: Question
has title: Why is function not working sometimes in python?
score: -1

http://stackoverflow.com/comment/89856911
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51432716
has text: Thanks and thank you for your help! Much appreciated and will literally save me hours of plotting time.

http://stackoverflow.com/comment/89849835
type: QuestionComment
comment on: http://stackoverflow.com/q/51439084
has text: The quantifier affects the whole sequence of patterns inside a group. Else, it would match `ABC DEF` only strings. With `*`, it matches `ABC`, `ABC DEF`, `A-C B.F H#D` strings.
score: 0
type: Comment

http://stackoverflow.com/comment/89851721
score: 0
has text: I would recommend using binarization rather then edge detection.
comment on: http://stackoverflow.com/q/51440895
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51457460
has comment: http://stackoverflow.com/comment/89884415
tagged with: python
has comment: http://stackoverflow.com/comment/89884638
has comment: http://stackoverflow.com/comment/89884991
has comment: http://stackoverflow.com/comment/89884689
has comment: http://stackoverflow.com/comment/89884717
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89884500
has title: Python 3: How to import from different folder/directories
type: Question
has answer: http://stackoverflow.com/a/51457513
answer count: 2
has answer: http://stackoverflow.com/a/51457536
has body: I’ve been working a lot lately with python 3 and I found that I am unable to import a module from a separate folder. Is there a way to import it while it’s in a folder subdivision? To give more context of this issue here is the “launcher” location and folder that I want to access: Launcher.py Folder - program-to-import.py That’s the layout. How do I import into launcher from my other module?
linked to: http://stackoverflow.com/q/391879
linked to: http://stackoverflow.com/q/1801878
possible better answer: http://stackoverflow.com/a/51457513
linked to: http://stackoverflow.com/q/72852
score: 0
linked to: http://stackoverflow.com/q/5155135
accepted answer: http://stackoverflow.com/a/51457536

http://stackoverflow.com/q/51354298
score: 0
has title: How to do bounds to solve double integral for data arrays? Python
tagged with: numpy
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51356400
tagged with: integral
linked to: http://stackoverflow.com/q/24875722
tagged with: python
has body: Double integral with function and sampled data Python Refer to this question, similarly, I need to solve a double integral for a sampled data which I don't know the function that generates it. I have understood how this answer does to solve such problem. However, in my case the data is above a certain region which varies depending on an extra parameter that I also have as an array. To make a case, I now assume it is bounded by a circular region. a,b and r are constant, d is the parameter list. I want a result of list to have same length of d. And for some reason, I want to keep it in Cartesian coordinate system. The data always cover the moving region. I was thinking to cut the data in order to just keep the part in the region and then use the solution from the question. I imagine it may lead to big error if I restrict the data region always (smaller than)/in the bound. Is there a better function in numpy package to solve definite double integral for data array in stead of using np.trapz?
answer count: 1

http://stackoverflow.com/q/51445064
tagged with: x86-64
has body: I am trying to cross compile an application for arm that depends on Python2.7 headers, but as you may understand, I don't have these headers and I don't know where nor how obtain them. I tried doing something like: sudo apt install libpython2.7-dev:armhf But it didn't work, it can't find the package. I saw another question like this but the answer were that this isn't possible as it is a conflict (both binaries are named Python and so on...), but it is? I just want the headers which are going to be in /usr/arm-linux-gnueabihf/include , what's the problem with that? Also, is possible that I am wrong thinking that the solution for my problem is to install the headers, the error is the following: /usr/include/python2.7/pyconfig.h:24:54: fatal error: arm-linux-gnueabihf/python2.7/pyconfig.h: No such file or directory compilation terminated. error: command 'arm-linux-gnueabihf-gcc' failed with exit status 1 Any other ideas than mine? Thank you very much, Marc
favorite count: 0
tagged with: linux
type: Question
tagged with: cross-compiling
tagged with: python
upvote count: 3
has answer: http://stackoverflow.com/a/51445230
answer count: 1
downvote count: 1
type: UnansweredQuestion
has title: Is there a way to install Python for ARM in a amd64 architecture?
tagged with: arm
score: 2

http://stackoverflow.com/comment/89866710
type: AnswerComment
type: Comment
has text: That's correct. So I tried manipulating the data. As in stored frequency in another variable and response in other. Converted it to list and then tried it. But still was not able to do it. What can be done in such a case?
comment on: http://stackoverflow.com/a/51446367
score: 0

http://stackoverflow.com/comment/89763306
type: Comment
comment on: http://stackoverflow.com/a/51392465
has text: `await os.system(...)` can't work, since `os.system` is not a coroutine.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89753299
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51390521
type: Comment
has text: @SunnyPatel that sounds like a messy solution, I'm using this in a GUI and instantiating Test1 twice would open a bunch of random frames.

http://stackoverflow.com/comment/89848153
comment on: http://stackoverflow.com/a/51426380
type: AnswerComment
score: 0
type: Comment
has text: Thanks! I did RTFM, but didn't find this, I'm new to numba, there's a ton of info to process.

http://stackoverflow.com/q/51471199
tagged with: postgresql
has title: Declare "MUL key" field in python. (django framework)
score: 0
has body: I have a column which should be MUL key, but I couldn't find out how I can do that. Here's the code: class table(models.Model): field2 = Models.int(max_length=9, null= False, default = 0)
tagged with: python
has answer: http://stackoverflow.com/a/51530125
type: UnansweredQuestion
tagged with: django
has answer: http://stackoverflow.com/a/51471224
type: Question
answer count: 2

http://stackoverflow.com/comment/89743013
has text: Lovely question mate I thought that this was impossible but apparently is :)
score: 0
comment on: http://stackoverflow.com/q/51385180
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51360609
has body: I need to split or crop my image into several images. My code is given below which can split an Image into 4 pieces but I am not be able to create 6 or 9 pieces using my code. I am a beginner so unable to find out a solution. My code is given below: from scipy import misc # Read the image img = misc.imread("Imaagi.jpg") height, width, _ = img.shape # Cut the image in half width_cutoff = width // 2 s1 = img[:, :width_cutoff, :] s2 = img[:, width_cutoff:, :] # Save each half misc.imsave("1.jpg", s1) misc.imsave("2.jpg", s2) img = misc.imread("1.jpg") height, width, _ = img.shape height_cutoff = height // 2 s3 = img[:height_cutoff, :, :] s4 = img[height_cutoff:, :, :] misc.imsave("111.jpg", s3) misc.imsave("222.jpg", s4) The code above first split an image into two parts and then from that two parts it divide that image into 4 parts.But if I need to split it as much as I need like 6,9,15 then how to do this? This is my image which I need to split into 6 separate boxes:
has answer: http://stackoverflow.com/a/51362159
type: AnsweredQuestion
score: 2
tagged with: python-imaging-library
downvote count: 0
tagged with: image-processing
has comment: http://stackoverflow.com/comment/89693472
type: Question
tagged with: image
has comment: http://stackoverflow.com/comment/89694824
upvote count: 2
has comment: http://stackoverflow.com/comment/89694433
has comment: http://stackoverflow.com/comment/89695066
has comment: http://stackoverflow.com/comment/89731524
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51362159
tagged with: python-3.x
has title: Single splitting from multiple
tagged with: python

http://stackoverflow.com/comment/89636100
type: QuestionComment
has text: Are opening and closing tags to be expected on the same line or not? Can there be more then one of these elements on a single line? This information impacts how complex/robust the solution needs to be.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51326585

http://stackoverflow.com/comment/89754113
has text: Can you link to a tutorial that does this?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51390979

http://stackoverflow.com/q/51333211
downvote count: 3
upvote count: 1
has title: Cutting string in python
possible better answer: http://stackoverflow.com/a/51333241
favorite count: 0
accepted answer: http://stackoverflow.com/a/51333471
tagged with: python
has answer: http://stackoverflow.com/a/51333471
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51333241
type: Question
score: -2
has comment: http://stackoverflow.com/comment/89642159
tagged with: slice
has body: I did some search but couldn't find any useful information. s = ['33PM'] My aim is to cut 'PM' from s[0] and append it as s[1].
answer count: 2

http://stackoverflow.com/q/51396560
linked to: http://stackoverflow.com/q/19780178
has comment: http://stackoverflow.com/comment/89764780
has body: I'm trying to get the following contrived example to work: class Person(Base): __tablename__ = "persons" __table_args__ = {"mysql_charset": "utf8mb4"} id = Column(Integer, primary_key=True) name = Column(String(50), index=True, unique=True) birthday = Column(Boolean, default=False) @hybrid_property def is_birthday_person(self): return self.birthday == True class Party(Base): __tablename__ = "parties" __table_args__ = {"mysql_charset": "utf8mb4"} id = Column(BigInteger, primary_key=True) one_id = Column(Integer, ForeignKey("persons.id")) two_id = Column(Integer, ForeignKey("persons.id")) one_person = relationship("Person", foreign_keys=[one_id]) two_person = relationship("Person", foreign_keys=[two_id]) sunshine = Column(Boolean, default=False) @hybrid_property def everyones_birthday_in_sunshine(self): return self.one_person.is_birthday_person and self.two_person.is_birthday_person and self.sunshine What I am trying to achieve is to filter all parties and only return parties where both persons celebrate their birthday and the sun is shining when I run the following query: session.Query(Party).filter(Party.everyones_birthday_in_sunshine).all() The error I am getting is: AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Party.one_person has an attribute 'is_birthday_person' When I change everyones_birthday_in_sunshine to: return self.sunshine == True It works and return all parties where the sun in shining when I run: session.Query(Party).filter(Party.everyones_birthday_in_sunshine).all() So the problem lies in the relationship between Party and Person, but I can't figure out how to get it to work. Edit: When I try to print properties from the person instance in Party: everyones_birthday_in_sunshine eg: one_person.name it just prints out Party.one_person. Definitly a relationship issue I guess.
tagged with: sqlalchemy
type: UnansweredQuestion
has title: Use hybridattribute on relationship in sqlalchemy
score: 2
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/89764660
favorite count: 0
type: Question
upvote count: 2
tagged with: python

http://stackoverflow.com/q/51326799
has title: Tic tac toe RNG
has answer: http://stackoverflow.com/a/51326960
has comment: http://stackoverflow.com/comment/89629232
has answer: http://stackoverflow.com/a/51326969
downvote count: 3
has body: import random a = 1 b = 2 c = 3 d = 4 # I would like the random_number to be 5 random_number = random.randint(1,5) def function(): global random_number while True: random_number = random.randint(1,5) if random_number != a or b or c or d: break print (random_number) function() down below is the link for the code https://pastebin.com/bhmMkF81 So I am trying to make a program that will be able to play tic tac toe. But I have problem with generation of numbers that arent assigned to the variable.This code that I posted keeps giving me random numbers.
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/89629475
upvote count: 0
has comment: http://stackoverflow.com/comment/89628833
has comment: http://stackoverflow.com/comment/89628963
has comment: http://stackoverflow.com/comment/89628974
linked to: http://stackoverflow.com/q/24159301
favorite count: 0
has comment: http://stackoverflow.com/comment/89628781
type: UnansweredQuestion
score: -3
tagged with: python
tagged with: tic-tac-toe

http://stackoverflow.com/a/51346292
has comment: http://stackoverflow.com/comment/89673867
score: 0
has comment: http://stackoverflow.com/comment/89670433
has body: Using Mongo aggregation pipeline, the fields you care about can be projected and made to replace the returned fields in the returned root document. e.g. pipeline = [ {'$project': {'a.x':1, 'b.w': 1}}, {'$replaceRoot': {'newRoot': {'a_x': '$a.x', 'b_w': '$b.w'}}} ] cur = db.keyes.aggregate(pipeline) result = next(cur) This way, you can go ahead to extend the respective lists using the result. tolist = lambda x: x if isinstance(x, list) else [x] data1.extend(tolist(result['a_x'])) data2.extend(tolist(result['b_w']))
has comment: http://stackoverflow.com/comment/89669327
answers question: http://stackoverflow.com/q/51344950
type: Answer
has comment: http://stackoverflow.com/comment/89690027
has comment: http://stackoverflow.com/comment/89671219
has comment: http://stackoverflow.com/comment/89688707

http://stackoverflow.com/a/62488893
score: 4
answers question: http://stackoverflow.com/q/51350493
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51350493
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/139214821
downvote count: 0
has body: I was struggling with a similar problem and found a quite convenient method for me by using the Open3D library. Simply install the library using pip pip install open3d or conda conda install -c open3d-admin open3d and run these three lines: import open3d as o3d pcd = o3d.io.read_point_cloud("source_pointcloud.ply") o3d.io.write_point_cloud("sink_pointcloud.pcd", pcd) It worked fine and kept the colors (checked by using CloudCompare).

http://stackoverflow.com/comment/89927747
has text: i placed one second edit to makeyour CHOICES work, check this out if you want to keep your code as it is
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51477738

http://stackoverflow.com/a/61586123
has comment: http://stackoverflow.com/comment/133768253
answers question: http://stackoverflow.com/q/51347012
downvote count: 0
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/108939782
has body: Follow the given steps explained in my blog will resolve your problem- How to Setup PySpark on Windows https://beasparky.blogspot.com/2020/05/how-to-setup-pyspark-in-windows.html To set up the environment paths for Spark. Go to "Advanced System Settings" and set below paths JAVA_HOME="C:\Program Files\Java\jdk1.8.0_181" HADOOP_HOME="C:\spark-2.4.0-bin-hadoop2.7" SPARK_HOME="C:\spark-2.4.0-bin-hadoop2.7" Also, add their bin path into the PATH system variable

http://stackoverflow.com/q/51341361
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/89656364
score: 1
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/89656247
has title: Cannot append a list of dictionaries in a python list
has answer: http://stackoverflow.com/a/51341370
accepted answer: http://stackoverflow.com/a/51341370
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89656170
duplicate of: http://stackoverflow.com/q/11492656
tagged with: python
tagged with: dictionary
has body: I am trying to ouptut a list of dicts with unique user IDs. I am using the following code to achieve this: import json import random import string def random_string_generator(size=15, chars=string.ascii_uppercase + string.digits): return '#' + ''.join(random.choice(chars) for _ in range(size)) list_users = ['user_id'] * 5 data = {} list_json = [] for user in list_users: data['user_id'] = random_string_generator() # function to generate a unique key list_json.append(data) print(list_json) However, my code output is giving the following: [{'user_id': '#J1FTZ3TLOITMVW6'}, {'user_id': '#J1FTZ3TLOITMVW6'}, {'user_id': '#J1FTZ3TLOITMVW6'}, {'user_id': '#J1FTZ3TLOITMVW6'}, {'user_id': '#J1FTZ3TLOITMVW6'}] I would like to know why the list is filled with the same item over and over again?

postgresql
tags question: http://stackoverflow.com/q/51351063
tags question: http://stackoverflow.com/q/51352145
tags question: http://stackoverflow.com/q/51474825
tags question: http://stackoverflow.com/q/51471599
tags question: http://stackoverflow.com/q/51383508
tags question: http://stackoverflow.com/q/51370752
tags question: http://stackoverflow.com/q/51447041
tags question: http://stackoverflow.com/q/51468973
tags question: http://stackoverflow.com/q/51471199
tags question: http://stackoverflow.com/q/51373524
tags question: http://stackoverflow.com/q/51360469
tags question: http://stackoverflow.com/q/51346000
tags question: http://stackoverflow.com/q/51463912
tags question: http://stackoverflow.com/q/51393957
tags question: http://stackoverflow.com/q/51421283
tag name: postgresql
tags question: http://stackoverflow.com/q/51448734
tags question: http://stackoverflow.com/q/51399204
type: Tag
tags question: http://stackoverflow.com/q/51460590
tags question: http://stackoverflow.com/q/51361250
tags question: http://stackoverflow.com/q/51381312
tags question: http://stackoverflow.com/q/51470200
tags question: http://stackoverflow.com/q/51373771
tags question: http://stackoverflow.com/q/51445521
tags question: http://stackoverflow.com/q/51479635
tags question: http://stackoverflow.com/q/51405055
tags question: http://stackoverflow.com/q/51473487
tags question: http://stackoverflow.com/q/51333360

http://stackoverflow.com/q/51426446
has comment: http://stackoverflow.com/comment/89824114
has title: generators : object is not subscriptable
has comment: http://stackoverflow.com/comment/89824564
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
downvote count: 1
tagged with: generator
tagged with: differential-equations
has body: I have this method : it's a solver stepper, I decide to develop it using generator for a question of elegance of the code. the problem here is that u is type: np.array def step(f, t, u, dt): def f(ti,ui): return np.array([function(ti,ui) for function in func]) um3 = u yield u + dt * f(t, u) um2 = u yield u + dt * f(t, u) um1 = u yield u + dt * f(t, u) while True: k1 = 55.0 * f(t, u) k2 = 59.0 * f(t - dt, um1) k3 = 37.0 * f(t - 2 * dt, um2) k4 = 9.0 * f(t - 2 * dt, um3) yield u + dt * (k1 - k2 + k3 - k4) / 24.0 um3 = um2 um2 = um1 um1 = u when I compile I got the error reported in the title. How can I fix it ? is it possible have a generator that return an array ? EDIT thanks for your interests ! here the full traceback: Traceback (most recent call last): File "drive.py", line 377, in &lt;module&gt; main() File "drive.py", line 224, in main f.write('%f %f \n' %(t, u[0] )) # u[0]) ) TypeError: 'generator' object is not subscriptable ------------------------------------------------------------ @friederikk99 the code in which I call the generator is : with open('AdamsBashforth4_p1.dat', 'w') as f: while True: f.write('%f %f \n' %(t, u[0] )) # u[0]) ) u = adamsmethods.AdamsBashforth._4th.step(func0,t,u,dt) t += dt if t &gt; tf: break ok I have change the line in : f.write('%f %f \n' %(t, np.array(u)[0])) but I got this strange message: Traceback (most recent call last): File "drive.py", line 378, in &lt;module&gt; main() File "drive.py", line 225, in main f.write('%f %f \n' %(t, np.array(u)[0])) # u[0]) ) IndexError: too many indices for array I've tried also like this : f.write('%f %f \n' %(t, list(u)[0])) ... same error
type: Question
has comment: http://stackoverflow.com/comment/89824064
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/89825371

serverless-framework
tag name: serverless-framework
type: Tag
tags question: http://stackoverflow.com/q/51471298

http://stackoverflow.com/q/51336510
tagged with: discord.py
accepted answer: http://stackoverflow.com/a/51338526
score: -1
answer count: 2
upvote count: 0
has title: Send message to multiple tagged user
possible better answer: http://stackoverflow.com/a/51336742
has answer: http://stackoverflow.com/a/51336742
favorite count: 0
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/51338526
tagged with: discord
type: AnsweredQuestion
has body: How to send a message to multiple user by tagging. @bot.command(pass_context=True) async def ping(ctx, member: discord.Member): await bot.send_message(member, "Pong...".format(ctx.message)) So above code works perfectly when tagged a single user ?ping @user1 but how to make it work when we tag multiple users ?ping @user1 @user2. So is it possible to make it custom message given in channel not in script. example: when we type ?ping @user1 @user2 bot should ask a message to send, when we add a message it will forward thet message to tagged user.
downvote count: 1
type: Question

http://stackoverflow.com/a/51355194
score: 0
answers question: http://stackoverflow.com/q/51354280
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89683061
accepted answer of: http://stackoverflow.com/q/51354280
type: Answer
has comment: http://stackoverflow.com/comment/89682819
has body: it is rather unclear whet GatherWood does, however, one way to do this is to link your button to a command that increments WoodInt by 20: def increment_woodint_by_20(): global WoodInt Woodint += 20 WoodInt = GatherWood(WoodInt) BWood = tk.Button(Top, text ="Gather Wood", command=increment_woodint_by_20) ...
has comment: http://stackoverflow.com/comment/89704683

http://stackoverflow.com/q/51428390
has answer: http://stackoverflow.com/a/51428667
upvote count: 0
has answer: http://stackoverflow.com/a/51428774
favorite count: 0
tagged with: http://stackoverflow.com/tag/xml
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/6523886
has answer: http://stackoverflow.com/a/51428706
has comment: http://stackoverflow.com/comment/89828416
has comment: http://stackoverflow.com/comment/89828540
downvote count: 1
type: Question
score: -1
has title: Changing value in XML using Python
has body: a One b Two c Three I have to replace the values One, Two and Three with some other number using the python script. Please suggest what needs to done
answer count: 3

http://stackoverflow.com/q/51416700
upvote count: 3
has comment: http://stackoverflow.com/comment/96498753
downvote count: 1
answer count: 1
has body: I have 40 csv files in a folder and I need to convert into a single csv file? The problem I face is though the body of csv's are the same the headings are different across sheets how do I correct them and merge?
has answer: http://stackoverflow.com/a/51416872
score: 2
type: AnsweredQuestion
has title: How to merge different csv files in a folder into a single csv file?
favorite count: 0
type: Question
tagged with: pandas
tagged with: python
accepted answer: http://stackoverflow.com/a/51416872
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89811067

matrix-multiplication
tags question: http://stackoverflow.com/q/51468287
tags question: http://stackoverflow.com/q/51338448
type: Tag
tags question: http://stackoverflow.com/q/51413016
tags question: http://stackoverflow.com/q/51463061
tags question: http://stackoverflow.com/q/51431327
tags question: http://stackoverflow.com/q/51416825
tag name: matrix-multiplication

http://stackoverflow.com/q/51469449
upvote count: 1
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/89907378
has title: ModuleNotFoundError: No module named 'Shiba'
tagged with: python
has comment: http://stackoverflow.com/comment/89907337
tagged with: python-3.x
answer count: 0
has comment: http://stackoverflow.com/comment/89907407
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89907483
has comment: http://stackoverflow.com/comment/89907324
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89907347
has comment: http://stackoverflow.com/comment/89907356
has comment: http://stackoverflow.com/comment/89907313
has comment: http://stackoverflow.com/comment/89907361
has body: I'm trying to run the following example from Shiba but keep running into the following error: Traceback (most recent call last): File "C:\test.py", line 1, in &lt;module&gt; from Shiba.shibaconnection import ShibaConnection ModuleNotFoundError: No module named 'Shiba' I found this excellent guide on the infamous ModuleNotFoundError but still can't seem to get it to work. Any ideas? Shiba is installed: And here is the shibaconnection.py module : `from __future__ import unicode_literals login = 'xxxx' pwd = 'xxxx' from shiba.salesManagement import salesManagement class ShibaConnection(object): """The main Shiba class, standing as an initialization and mandatory for each submodules instancing. :param login: PriceMinister Seller login :param pwd: PriceMinister Seller Token \ (see more at https://developer.priceminister.com/blog/fr/documentation/identification-by-token) :param sandbox: give it True if you want to test the API on a sandboxed version of PriceMinister. """ def __init__(self, login, pwd, sandbox=False): self.login = str(login) self.pwd = str(pwd) self.domain = "https://ws.priceminister.com" if sandbox is False else "https://ws.sandbox.priceminister.com" self.actionsinfo = { "producttypes": {"cat": "stock_ws", "version": "2011-11-29", "login": self.login, "pwd": self.pwd}, "producttypetemplate": {"cat": "stock_ws", "version": "2013-05-14", "login": self.login, "pwd": self.pwd}, "genericimportfile": {"cat": "stock_ws", "version": "2012-09-11", "login": self.login, "pwd": self.pwd}, "genericimportreport": {"cat": "stock_ws", "version": "2011-11-29", "login": self.login, "pwd": self.pwd}, "getavailableshippingtypes": {"cat": "sales_ws", "version": "2013-06-25", "login": self.login, "pwd": self.pwd}, "export": {"cat": "stock_ws", "version": "2014-11-04", "login": self.login, "pwd": self.pwd}, "listing": {"cat": "listing_ssl_ws", "version": "2015-07-05", "login": self.login, "pwd": self.pwd}, "categorymap": {"cat": "categorymap_ws", "version": "2011-10-11", "login…

http://stackoverflow.com/comment/89698130
has text: Do not use `os.random()` when doing crypto, use [`Crypto.Random()`](https://www.dlitz.net/software/pycrypto/api/current/Crypto.Random-module.html) instead. Check [`this answer`](https://stackoverflow.com/a/44212550/7553525) to see how to do it properly, it also shows differences between Python 2.x and 3.x.
type: QuestionComment
comment on: http://stackoverflow.com/q/51362459
type: Comment
score: 0

http://stackoverflow.com/comment/89715869
has text: Please provide a [**Minimal, Complete, and Verifiable example**](https://stackoverflow.com/help/mcve)
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51371734

http://stackoverflow.com/q/51392528
tagged with: pandas
answer count: 1
tagged with: timedelta
accepted answer: http://stackoverflow.com/a/51394400
has title: Convert and order time in a pandas df
has body: I am trying to order timestamps in a pandas df. The times begin around 08:00:00 am and finish around 3:00:00 am. I'd like to add 24hrs to times after midnight. So times read 08:00:00 to 27:00:00 am. The problem is the times aren't ordered. Example: import pandas as pd d = ({ 'time' : ['08:00:00 am','12:00:00 pm','16:00:00 pm','20:00:00 pm','2:00:00 am','13:00:00 pm','3:00:00 am'], }) df = pd.DataFrame(data=d) If I try order the times via df = pd.DataFrame(data=d) df['time'] = pd.to_timedelta(df['time']) df = df.sort_values(by='time',ascending=True) Out: time 4 02:00:00 6 03:00:00 0 08:00:00 1 12:00:00 5 13:00:00 2 16:00:00 3 20:00:00 Whereas I'm hoping the output is: time 0 08:00:00 1 12:00:00 2 13:00:00 3 16:00:00 4 20:00:00 5 26:00:00 6 27:00:00 I'm not sure if this can be done though. Specifically, if I can differentiate between 8:00:00 am and the times after midnight (1am-3am).
tagged with: time
tagged with: python
has comment: http://stackoverflow.com/comment/89757467
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89757491
has comment: http://stackoverflow.com/comment/89759337
type: Question
has answer: http://stackoverflow.com/a/51394400
has comment: http://stackoverflow.com/comment/89757664
has comment: http://stackoverflow.com/comment/89757155
score: 0

http://stackoverflow.com/comment/89949625
type: Comment
comment on: http://stackoverflow.com/a/51475163
has text: Yes, I tried different versions including the one you mentioned, all give the same error.
score: 0
type: AnswerComment

http://stackoverflow.com/a/75135236
has body: You can use eco2AI library to estimate power consumption. https://github.com/sb-ai-lab/Eco2AI It was designed to track CO2 emissions during ML models training, but it also measures power consumption of the GPU, CPU and RAM separately.
answers question: http://stackoverflow.com/q/51426379
score: 0
has comment: http://stackoverflow.com/comment/132608303
type: Answer

http://stackoverflow.com/a/51455124
type: AcceptedAnswer
upvote count: 3
type: Answer
downvote count: 0
has body: In your first code, a and b are each a name for a one-dimensional, one-entry numpy array. When you build the list [a, b] in your for statement, the list contains those arrays, so i in your loop becomes an array. The key point is the next: when the line i+=1 is executed, Python adds 1 to the array. Numpy intercepts this command and uses a universal function (also called a ufunc) to add 1 to each member of the array. So each array is changed. However, a and b are still names for those arrays, so a and b are each changed, and you get your results. In your second code, a and b are each a name for a numeric constant. When the list is built, it contains those constants. When the line i+=1 is executed, 1 is added to the constant, but since the constant is immutable the result is just thrown away. Thus a and b are not changed. So the short answer is: your first code uses mutable values in a list, while the second used immutable values in list. These behave differently in Python.
score: 3
accepted answer of: http://stackoverflow.com/q/51455074
answers question: http://stackoverflow.com/q/51455074

http://stackoverflow.com/comment/89646066
has text: @VenkataGogu if using best features of python is cheating then I don't know... you can boast with alternatives like I provided in my answer, & the argumentation. I doubt an interviewer would object that.
comment on: http://stackoverflow.com/q/51335422
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89851703
comment on: http://stackoverflow.com/a/51422276
type: AnswerComment
type: Comment
has text: I'll edit my answer to acknowledge what you and the other answer have said. Thank you
score: 2

http://stackoverflow.com/q/51443641
tagged with: random
answer count: 1
has comment: http://stackoverflow.com/comment/89858886
linked to: http://stackoverflow.com/q/30564015
has title: Generating "amoeba-like" clusters around lat/lng points
has comment: http://stackoverflow.com/comment/89858030
tagged with: python
accepted answer: http://stackoverflow.com/a/51445445
type: AnsweredQuestion
type: Question
tagged with: cluster-analysis
has comment: http://stackoverflow.com/comment/89858986
has body: I have a fairly unique problem I'm trying to solve, and the math is confusing me. I'm working on a map project, and one of the needs is to generate random, "amoeba-like" clusters of points around a given latitude/longitude center. By "amoeba-like", I mean the cluster shouldn't be overly round or uniform, but should, ideally, have "arms" that extend out from the center. At the same time, the arms should be somewhat random and not particularly spiral-like. I've tried a number of approaches, but so far, none of the clusters I've generated are quite the shape I want. I've tried approaches similar to what's described here, and I've tried the make_blobs from sklearn. But I couldn't figure out how to extend either of those get the "arms" I'm looking for, and I'm not confident that either of those approaches really makes sense. Any advice anyone could provide would be much appreciated!
has comment: http://stackoverflow.com/comment/89859227
has answer: http://stackoverflow.com/a/51445445
score: 0

http://stackoverflow.com/comment/89939375
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51471672
has text: sklearn minmaxscaler has an option like this: inverse_transform(X). Would there be a similar function for z score?

http://stackoverflow.com/q/51377987
tagged with: selenium-webdriver
score: 2
upvote count: 2
tagged with: screenshot
tagged with: selenium
tagged with: webdriver
type: Question
has answer: http://stackoverflow.com/a/67290865
has title: Unable to take proper screenshot through Selenium
has body: I had wrote some code by python. It is to capture web page. But image has broken font. This is my code: # -*- coding: utf-8 -*-iore from selenium import webdriver import json import os, sys import re options = webdriver.ChromeOptions() options.add_argument('--headless') options.add_argument('--no-sandbox') options.add_argument("disable-gpu") driver = webdriver.Chrome('[DRIVERPATH]', chrome_options=options) driver.get("http://google.co.kr") driver.set_window_size(500, 900) screenshot = driver.get_screenshot_as_base64() print screenshot driver.quit() This is resulten image: How can I fix it? updated your advice is maximize screen. but font is still broken. This is my fix code. #driver.set_window_size(500, 900) driver.maximize_window() and capture image.
has answer: http://stackoverflow.com/a/54882177
has comment: http://stackoverflow.com/comment/89727860
answer count: 3
has answer: http://stackoverflow.com/a/51378928
has comment: http://stackoverflow.com/comment/89727618
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51337021
score: 2
type: AnsweredQuestion
downvote count: 0
type: Question
upvote count: 2
tagged with: pandas
has title: Rows don't get deleted correctly
answer count: 1
has answer: http://stackoverflow.com/a/51337053
accepted answer: http://stackoverflow.com/a/51337053
favorite count: 0
tagged with: python
has body: I am trying to delete rows that have the value of Rating equal to NaN and the sum of single columns is &lt;50. Rating contains integer values in the range of [1,5]. This is my code for deleting them. bow = bow.loc[~(bow['Rating'] &lt; 1), ~(bow.sum(0) &lt; 50)] But when I print the dataframe I can still see NaN ratings. The sum part does its job correctly. Any help is greatly appreciated! EDIT: This is how bow was created: bow = df.Review2.str.split().apply(pd.Series.value_counts) rating = df['Rating'] df_rating = pd.DataFrame([rating]) df_rating = df_rating.transpose() bow = bow.join(df_rating) bow.head()

http://stackoverflow.com/a/51472737
upvote count: 3
has body: This is quite straightforward. Because your if statement is &lt;4, and then it +=1, so it means it will grow from 3 to 4 in loop. Just simply change if lineIDSpace6Num &lt; 4: to if lineIDSpace6Num &lt; 3: Your problem will be resolved.
answers question: http://stackoverflow.com/q/51472668
type: Answer
downvote count: 1
score: 2

http://stackoverflow.com/comment/89835716
has text: Can you edit your code into a [mcve] that shows us how you want to use that class? Those methods are instance methods, so they ought to be called on an instance of the `Menu` class.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51432300
type: Comment

http://stackoverflow.com/a/51469908
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/89908698
score: 1
answers question: http://stackoverflow.com/q/51469825
has body: That's not quite how sets work. Both the hash value and the value are required, because the values must be checked for equality in case of a hash collision. If you don't care about collisions, you can use a Bloom filter instead of a set. These are very memory efficient, but give probabilistic answers (either definitely not in the set, or maybe in the set). There's no Bloom filter in the standard library, but there are several implementations on PyPI. If you care more about optimizing space than time, you could just keep the hashes in a list and then when you need to check for an element, sort it in place and do a binary search. Python's Timsort is very efficient when the list is mostly sorted already, so subsequent sorts will be relatively fast. Python lists have a sort() method and you can implement a binary search fairly easily using the standard library bisect module. You can combine both techniques, i.e. don't bother sorting if the Bloom filter indicates the element is not in the set. And of course, don't bother sorting again if you haven't added any elements since last time.

http://stackoverflow.com/a/51374546
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/89721920
accepted answer of: http://stackoverflow.com/q/51374107
score: 1
answers question: http://stackoverflow.com/q/51374107
has body: First, let's create some constants for KiB, MiB, GiB, etc. Don't worry about hex here, we just want the numbers in whatever form makes most sense to you—whether that's 1024 or 0x400 or 2**10 doesn't matter, since those are all the same number. So: KiB = 1024 MiB = 1024 * KiB GiB = 1024 * MiB TiB = 1024 * GiB Now, how much is 12MiB? Easy: 12 * MiB Now, how much is 12MiB in hex? hex(12 * MiB) This gives you '0xc00000'. As far as "adding in hex", that's not a thing you should do. Just add the numbers as numbers, then format the result in hex. For example, if you want to add 32KiB + 16KiB + 1MiB: hex(32*KiB + 16*KiB + 1*MiB) You wanted a bit more control over the output. If that's important, you'll need to use format strings (whether via the format function, the str.format method, or f-string literals) instead of hex. You can specify a width to pad to, and a fill character to pad with. And you can use # to add the 0x automatically (in which case we have to pad to 8+2=10 characters instead of 8), or add the 0x manually (in which case we only have to pad to 8 characters, which makes a bit more sense): format(12 * MiB, '#010x') f"{12*MiB:#010x}" f"0x{12*MiB:08x}" You also wanted to separate the digits into blocks of 4. We can use a grouping character to get pretty close, but then we have to add an extra 1 to the width: f"0x{12*MiB:09_x}" … at which point we might as well use # again: f"{12*MiB:#011_x}" Now you've got '0x00c0_0000'. If you really need spaces between groups instead of underscores, then you'll need to get a bit ugly: f"{12*MiB:#11_x}".replace('_', ' ') (I believe there was a proposal to allow arbitrary grouping characters, but it was rejected, so the only options are _, ,, or n for "do whatever my locale says".) So, if you want to print out your table: print( "size hex '0x' notation") print(f"1 MiB {12*MiB:#011_x}") print(f"12 KiB {12*KiB:#011_x}") print(f"128 KiB {128*KiB:#011_x}") Or you can write a function. While we're at it, let's use an Enum instead of …
has comment: http://stackoverflow.com/comment/89721603
type: AcceptedAnswer
upvote count: 1

http://stackoverflow.com/a/51366246
has comment: http://stackoverflow.com/comment/89706008
has comment: http://stackoverflow.com/comment/89706136
type: Answer
has comment: http://stackoverflow.com/comment/89705022
has body: The issue seems to come from the fact that your 2 extra columns Cust_ID and Email in df_binary cause your dimensions to be incompatible for matrix multiplication. Try the following: df_binary = df_binary.set_index(['Cust_id', 'Email']) df_technique = df_binary.dot(df_pim.values) df_techique.columns = df_pim.columns # If you want to remove layered indicies after dot product multiplication: df_technique.reset_index() #or set to whatever index you need. You can always reset the index later if you don't want to be dealing with multi-layered indices.
answers question: http://stackoverflow.com/q/51365019
upvote count: 1
has comment: http://stackoverflow.com/comment/89704858
has comment: http://stackoverflow.com/comment/89706453
has comment: http://stackoverflow.com/comment/89706258
downvote count: 0
score: 1

http://stackoverflow.com/q/51445820
tagged with: python-3.x
tagged with: python
tagged with: combobox
tagged with: tkinter
has title: Python: How can I fetch data from SQL for a ttk combobox based on the selection of another combobox
type: UnansweredQuestion
upvote count: 1
score: 1
type: Question
has answer: http://stackoverflow.com/a/51446138
tagged with: sqlite
answer count: 1
downvote count: 0
has body: I am trying to have two ttk comboboxes that fetch data from a sqlite database. I managed to be able and list items in one combobox named divisiondropmenu using the combo_division() function. Now I am trying to do a similar thing for the second combobox named productdropmenu, but the list would need to be narrowed down based on the first selected item in combobox named divisiondropmenu. For the SQL query to pass the needed information for the second combobox I was thinking of something of this sort: 'SELECT * FROM productname WHERE divisionname=?', (function_name()) Code for the two comboboxes so far: from tkinter import * from tkinter import ttk from tkinter.ttk import * import sqlite3 def combo_division(): conn = sqlite3.connect('anglingdatabase.db') cursor = conn.cursor() cursor.execute('SELECT divisionname FROM productdivision') data = [] for row in cursor.fetchall(): data.append(row[0]) return data root = Tk() root.title("Random Window Title") root.geometry('1280x720') rows = 0 while rows &lt; 50: root.rowconfigure(rows, weight=1) root.columnconfigure(rows, weight=1) rows += 1 divisiondropmenu = ttk.Combobox(root) divisiondropmenu['values'] = combo_division() divisiondropmenu.bind('&lt;&lt;ComboboxSelected&gt;&gt;', selecteddivision) divisiondropmenu.grid(row=1, column=2, sticky='NESW') productdropmenu = ttk.Combobox(root) productdropmenu['values'] = combo_product() productdropmenu.grid(row=2, column=2, sticky='NESW') root.mainloop()
favorite count: 0

http://stackoverflow.com/a/51412997
answers question: http://stackoverflow.com/q/51411713
score: 3
downvote count: 0
has body: Don't use pygame.time.wait or delay because these functions make your program sleep for the given time and the window becomes unresponsive. You also need to handle the events (with one of the pygame.event functions) each frame to avoid this. Here are some timer examples which don't block: Countdown timer in Pygame To switch the colors, you can just assign the next color to a variable and use it to render the text. import pygame pygame.init() screen = pygame.display.set_mode((640, 480)) clock = pygame.time.Clock() title_font = pygame.font.SysFont('monospace', 50) BACKGROUND_COLOR = pygame.Color('gray12') BLUE = pygame.Color('blue') RED = pygame.Color('red') # Assign the current color to the color variable. color = RED timer = 2 dt = 0 done = False while not done: # Handle the events. for event in pygame.event.get(): # This allows the user to quit by pressing the X button. if event.type == pygame.QUIT: done = True timer -= dt # Decrement the timer by the delta time. if timer &lt;= 0: # When the time is up ... # Swap the colors. if color == RED: color = BLUE timer = 3 else: color = RED timer = 2 screen.fill(BACKGROUND_COLOR) title = title_font.render('game', 5, color) screen.blit(title, (200, 50)) pygame.display.flip() # dt is the passed time since the last clock.tick call. dt = clock.tick(60) / 1000 # / 1000 to convert milliseconds to seconds. pygame.quit()
type: AcceptedAnswer
upvote count: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/51411713

http://stackoverflow.com/a/51403062
has comment: http://stackoverflow.com/comment/89792149
answers question: http://stackoverflow.com/q/51402770
has body: df1 = pd.read_excel('file_name1') # get input from excel files df2 = pd.read_excel('file_name2') p1 = df1['p1'].values p11 = df2['p11'].values new_col = [] # we will store desired values here for i in range(len(p1)): if p1[i] - p11[i] == 0: new_col.append(1) elif abs(p1[i] - p11[i]) &gt; 0.2: new_col.append(0) else: new_col.append(p1[i]) df1['new_column'] = new_col # we add new column with our values You can also remove old column df.drop('column', axis = 1)
has comment: http://stackoverflow.com/comment/89806157
has comment: http://stackoverflow.com/comment/89777092
score: 0
has comment: http://stackoverflow.com/comment/89788034
has comment: http://stackoverflow.com/comment/89795598
has comment: http://stackoverflow.com/comment/89777014
type: Answer

http://stackoverflow.com/comment/89972029
comment on: http://stackoverflow.com/a/51439143
has text: Hi! Wonder why i didn't think of this. So, essentially you just removed the two lines of code on the top that checked if the subject and object class were part of the NE tag list right?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51458928
type: Answer
answers question: http://stackoverflow.com/q/51457912
score: 1
accepted answer of: http://stackoverflow.com/q/51457912
has body: Pick a focal point at the creature. Draw a circle around it. Subdivide the circle for each pixel in your image resolution, and cast a ray from the focal point to the circle point and out into the world. Find the points of intersection between that ray and the world objects. Get the color of the closest one to set the color in the image at that pixel. Repeat for each pixel. This gives a 360-degree perspective view, which might simplify things for a simulated creature. If you want a more directional view, just use an arc instead of a circle. 45 degrees seems reasonable.
type: AcceptedAnswer
upvote count: 1
has comment: http://stackoverflow.com/comment/89887547
has comment: http://stackoverflow.com/comment/89905920
downvote count: 0

http://stackoverflow.com/comment/89662029
type: AnswerComment
score: 0
type: Comment
has text: Thanks @gilch for detailed answer. I will look into it. :D
comment on: http://stackoverflow.com/a/51344385

http://stackoverflow.com/a/52455004
has comment: http://stackoverflow.com/comment/91867048
has comment: http://stackoverflow.com/comment/95264848
score: 5
has comment: http://stackoverflow.com/comment/104727482
has comment: http://stackoverflow.com/comment/91866428
upvote count: 6
answers question: http://stackoverflow.com/q/51351000
downvote count: 1
has body: Here's an approach which does not need to fetch the entire file (full version available here). It does require boto (or boto3), though (unless you can mimic the ranged GETs via AWS CLI; which I guess is quite possible as well). import sys import zlib import zipfile import io import boto from boto.s3.connection import OrdinaryCallingFormat # range-fetches a S3 key def fetch(key, start, len): end = start + len - 1 return key.get_contents_as_string(headers={"Range": "bytes=%d-%d" % (start, end)}) # parses 2 or 4 little-endian bits into their corresponding integer value def parse_int(bytes): val = ord(bytes[0]) + (ord(bytes[1]) &lt;&lt; 8) if len(bytes) &gt; 3: val += (ord(bytes[2]) &lt;&lt; 16) + (ord(bytes[3]) &lt;&lt; 24) return val """ bucket: name of the bucket key: path to zipfile inside bucket entry: pathname of zip entry to be retrieved (path/to/subdir/file.name) """ # OrdinaryCallingFormat prevents certificate errors on bucket names with dots # https://stackoverflow.com/questions/51604689/read-zip-files-from-amazon-s3-using-boto3-and-python#51605244 _bucket = boto.connect_s3(calling_format=OrdinaryCallingFormat()).get_bucket(bucket) _key = _bucket.get_key(key) # fetch the last 22 bytes (end-of-central-directory record; assuming the comment field is empty) size = _key.size eocd = fetch(_key, size - 22, 22) # start offset and size of the central directory cd_start = parse_int(eocd[16:20]) cd_size = parse_int(eocd[12:16]) # fetch central directory, append EOCD, and open as zipfile! cd = fetch(_key, cd_start, cd_size) zip = zipfile.ZipFile(io.BytesIO(cd + eocd)) for zi in zip.filelist: if zi.filename == entry: # local file header starting at file name length + file content # (so we can reliably skip file name and extra fields) # in our "mock" zipfile, `header_offset`s are negative (probably because the leading content is missing) # so we have to add to it the CD start offset (`cd_start`) to get the actual offset file_head = fetch(_key, cd_start + zi.header_offset +…
has comment: http://stackoverflow.com/comment/91867289
type: Answer
has comment: http://stackoverflow.com/comment/91867628
has comment: http://stackoverflow.com/comment/91857911
has comment: http://stackoverflow.com/comment/91866135

http://stackoverflow.com/comment/89706343
comment on: http://stackoverflow.com/q/51366739
has text: Your update is confusing. Your example has the values in `c`, but then your code works on `lst`. Also, the fact that you have to type `list(c[0])` instead of just `c[0]` implies that `c` may be a list of iterators or something?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/51338443
tagged with: dictionary
has comment: http://stackoverflow.com/comment/89653849
has comment: http://stackoverflow.com/comment/89651635
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/51343850
has answer: http://stackoverflow.com/a/51343850
has title: Python - Compare two dictionaries [Match case sensitive values]
has answer: http://stackoverflow.com/a/51340427
has body: I'm trying to compare two dictionaries (list containing arrays) in Python. Here are two dictionaries: tag=[{'Key': 'Base', 'Value': 'ny'}, {'Key': 'Name', 'Value': 'newyork'}] filters=[{'Key': 'Name','Value': ['Newyork', 'newyork','NewYork']}] The task here is to compare filters dict with tag dict. Following ways I tried which didn't work : &gt;&gt;&gt; tag == filters False &gt;&gt;&gt; tag[1] == filters False &gt;&gt;&gt; tag[1] == filters[0] False I want to check if tag has an array matching to filters it should return true. Probably, it is able to compare the value of Keyin the array as it has an exact matching string but for Value which has same string written in different cases, it doesn't match. The things I want to cover while comparing: comparing it with every array in the dictionary if any array matches should return true consider all types of possible cases for keyand values: 'Name','name','NAME' and 'Newyork', 'newyork','NewYork' Any help appreciated. Thanks in advance!
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89651878
type: Question
accepted answer: http://stackoverflow.com/a/51340427
has comment: http://stackoverflow.com/comment/89651840
has comment: http://stackoverflow.com/comment/89651464
tagged with: python

http://stackoverflow.com/q/51362213
favorite count: 0
tagged with: python
has title: docker-compose not printing stdout in Python app
type: UnansweredQuestion
has body: When using a print() statement in a Python app running inside a Docker container that's managed by Docker Compose, only sys.stderr output is logged. Vanilla print() statements aren't seen, so this: print("Hello? Anyone there?") ... never shows up in the regular logs: (You can see other logs explicitly printed by other libs in my app, but none of my own calls.) How can I avoid my print() calls being ignored?
type: Question
tagged with: docker-compose
score: 88
tagged with: docker
has answer: http://stackoverflow.com/a/51362306
answer count: 3
has answer: http://stackoverflow.com/a/51362214
downvote count: 1
upvote count: 89
has answer: http://stackoverflow.com/a/67818131

http://stackoverflow.com/a/51405011
has body: According to the documentation "the result of input line 4 is available either as Out[4] or as _4". More details here.
downvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/89781159
score: 1
upvote count: 3
has comment: http://stackoverflow.com/comment/89781004
has comment: http://stackoverflow.com/comment/89780902
has comment: http://stackoverflow.com/comment/89781443
answers question: http://stackoverflow.com/q/51404930

http://stackoverflow.com/q/51403374
has body: I have a txt file created named "commands.txt" and it contains two commands ( 2 lines) sh run vlan 158 sh run vlan 159 i want to run this two command in a switch but only one commands get executed.here is how my script looks like: def shvlan(device,child): commandFile = open('commands.txt', 'r') commands = [i for i in commandFile] for command in commands: child.sendline(command) child.expect('.*#') vlans = child.after child.close() print device + ' conn closed' print 'sh run vlan executed' print vlans return vlans Any suggestion why it is taking only 1st line of the .txt file ?
type: Question
has answer: http://stackoverflow.com/a/51403566
tagged with: pexpect
upvote count: 1
answer count: 1
favorite count: 0
has title: Looping lines in Python PEXPECT
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51403566
downvote count: 0
score: 1

http://stackoverflow.com/comment/89894021
type: Comment
comment on: http://stackoverflow.com/a/51453020
score: 0
type: AnswerComment
has text: For example, I need to scan the barcode, once scanned I need to redirect to view page of resource which I scanned.

http://stackoverflow.com/comment/89880708
type: Comment
has text: i tried it so many times i have deleted it and created gain but still the same issue.
comment on: http://stackoverflow.com/a/51455628
type: AnswerComment
score: 0

http://stackoverflow.com/a/51461561
type: AcceptedAnswer
downvote count: 0
has body: The reason you're getting non-ASCII characters encoded with \u is that you're using json.dumps. As you can see from the docs, the ensure_ascii parameter defaults to True, and, if true, "the output is guaranteed to have all incoming non-ASCII characters escaped". So, you could just add ensure_ascii=False to all of your dumps calls. But really, why are you using json.dumps in the first place? The format you're outputting isn't a JSON file. In fact, it seems to be something designed for human rather than computer consumption. So why do you want extra quotes, escape characters, etc. to make the parts of it JSON-parseable even though the whole isn't? It would be much simpler, and probably produce nicer output, if you just didn't do that: content = dict.get("content") loc_no = str(dict.get("location_number")) page_no = str(dict.get("page_number")) f.write("\n") f.write(content + " " + "(" + page_no + ", " + loc_no + ")" +"\n") … or, even better: content = dict.get("content") loc_no = dict.get("location_number") page_no = dict.get("page_number") f.write("\n") f.write("{} ({}, {})\n".format(content, page_no, loc_no) While we're at it, calling your dict dict is confusing (and means you can't access the dict constructor in the rest of your function without getting one of those errors that will keep you up all night debugging and then feeling like an idiot). Also, why are you using get("content") here? If you don't have to worry about cases where there is no content, just use ["content"]—or, even more simply, just pass the dict to format_map: for ref in refs: f.write("\n{content} ({page_number}, {location_number})\n".format_map(ref)) If you do need to worry about such cases, surely you want some appropriate human-meaningful string, not None. For example: for ref in refs: content = ref.get("content", "-- content missing --") page_no = ref.get("page_number", "N/A") loc_no = ref.get("location_number", "N/A") f.write("\n{} ({}, {})\n".format(content, page_no, loc_no)
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/51461463
answers question: http://stackoverflow.com/q/51461463
upvote count: 2
has comment: http://stackoverflow.com/comment/89931691
has comment: http://stackoverflow.com/comment/89931572

http://stackoverflow.com/q/51404807
score: 1
upvote count: 1
tagged with: multiprocessing
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/89781510
tagged with: for-loop
has comment: http://stackoverflow.com/comment/89780540
downvote count: 0
has comment: http://stackoverflow.com/comment/89780978
has comment: http://stackoverflow.com/comment/89781802
has title: python multiprocessing how to kill listener worker at the end of processing
favorite count: 0
has comment: http://stackoverflow.com/comment/89781326
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89780680
answer count: 0
has body: I am using python multiprocessing where a number of workers are doing a job and queueing their output to a listener. The listener will then append their outputs into a numpy array as below: def listener(q): global data while 1: m = q.get() if m == 'kill': print('FINISHED') # Save data to file break data = np.column_stack((data, m)) This is the main code data = np.empty([0,6]) manager = mp.Manager() q = manager.Queue() pool = mp.Pool(mp.cpu_count()) watcher = pool.apply_async(listener, (q,)) jobs = [] for i in range(100): job = pool.apply_async(process_data, (x1, x2, x3,)) jobs.append(job) for job in jobs: job.get() q.put('kill') pool.close() process data is a function that puts an array into the queue that the listener is then pulling from. The problem is that when running the code print('FINISHED') is never executed while data is being populated so I know that listener is working. I am also getting an output warning: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison if m == 'kill': Trying to debug this I commented out the creation of worker jobs like the code below, and FINISHED actually prints and warning message disappears. Why is this happening? data = np.empty([0,6]) manager = mp.Manager() q = manager.Queue() pool = mp.Pool(mp.cpu_count()) watcher = pool.apply_async(listener, (q,)) jobs = [] #for i in range(100): # job = pool.apply_async(process_data, (x1, x2, x3,)) # jobs.append(job) #for job in jobs: # job.get() q.put('kill') pool.close()

http://stackoverflow.com/q/51413797
upvote count: 4
accepted answer: http://stackoverflow.com/a/51413828
answer count: 3
downvote count: 0
has body: I'm using Selenium and Python to extract information from a page. Here is the div I want to extract from: 5 I want to extract the value "5". Here is the Python I have written: element = browser.find_elements_by_class_name('_2v66').getText print('Views:') print(element) When I run this script, I get the following message: Traceback (most recent call last): File "<string>", line 95, in <module> AttributeError: 'list' object has no attribute 'getText' [Finished in 15.478s] Solution: Although I originally thought the div class was unique, after a closer inspection of the page I realized that it is not a unique div and therefore the solution was as follows: browser.get(('https://www.facebook.com/example_page_1/insights/?section=navVideos')) browser.implicitly_wait(60) # find_elements_by_class_name - Returns the div in which the metrics are found elements = browser.find_elements_by_class_name('_2v66') for e in elements: print(e.text) The browser.implicitly_wait was crucial to allow the page to load. The errors I was receiving with regards to the object no existing were because of that.
favorite count: 0
has title: Get text from div using Selenium
tagged with: python
possible better answer: http://stackoverflow.com/a/51414313
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51414313
has answer: http://stackoverflow.com/a/51413828
tagged with: selenium
type: Question
score: 4
has answer: http://stackoverflow.com/a/76550867

http://stackoverflow.com/q/51446912
has title: Get dictionary mapping values to reference ID
has comment: http://stackoverflow.com/comment/89864254
upvote count: 1
has comment: http://stackoverflow.com/comment/89864297
tagged with: dictionary
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89864203
has comment: http://stackoverflow.com/comment/89864289
accepted answer: http://stackoverflow.com/a/51447159
possible better answer: http://stackoverflow.com/a/51447173
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/51447173
answer count: 2
has comment: http://stackoverflow.com/comment/89864341
downvote count: 0
has answer: http://stackoverflow.com/a/51447159
has comment: http://stackoverflow.com/comment/89864364
tagged with: python
has body: I have a list of numpy arrays like the following: list_list = [np.array([53, 5, 2, 5, 5, 2, 1, 5, 9]), np.array([6, 4, 1,2, 53, 23, 1, 4])] and a list of IDs for each array above: ID = [6, 2] How can I get a dictionary that for each unique value in list_list, I get a list of the IDs which contain it? For example, for this very simple example, I want something like: {53: [6, 2], 5: [6], 2: [6, 2], 1: [6, 2], etc} My actual list_list is over 1000 lists long, with each numpy array containing around 10 million value, so efficiency in the solution is key. I know that dict(zip(ID, list_list)) will give me a dictionary corresponding an ID with all of its values, but it won't give me a value corresponding to IDs, which is what I want. Thanks!
score: 1
favorite count: 0

http://stackoverflow.com/comment/89696865
score: 2
has text: `-y` is an invalid flag. `-u` is the correct one (I'l add that to my answer above.)
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51362306

http://stackoverflow.com/a/51352276
has comment: http://stackoverflow.com/comment/89683962
type: Answer
has comment: http://stackoverflow.com/comment/89680394
has comment: http://stackoverflow.com/comment/89695093
upvote count: 1
has comment: http://stackoverflow.com/comment/89693963
score: 1
answers question: http://stackoverflow.com/q/51351970
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51351970
has body: You get this error because your program didn't found the nltk library. First install nltk from cmd using pip install nltk If it installed successfully then execute your code. If you again get the same error then their may be chance that you installed two or more different version of python or python environment on your system . Their may be two Solution for this Uninstall other version of python or python environment(like Anaconda) Then again install nltk from cmd pip install nltk then execute your program Set the path of python 3.5 in the priority(keep in the top) from the environment variable. Example:- C:\Users\Tech-Ninja\AppData\Local\Programs\Python\Python36-32\ C:\Users\Tech-Ninja\AppData\Local\Programs\Python\Python36-32\Scripts\ You have to set two path one for python Interpreter and another for Script both in top. You can see in the image Then again install nltk from cmd pip install nltk then execute your program Excepting it will work for you

http://stackoverflow.com/comment/89857898
comment on: http://stackoverflow.com/a/51443940
type: Comment
score: 0
type: AnswerComment
has text: @BenJones Indeed numpy offers some syntax shortcuts =)

http://stackoverflow.com/comment/89859293
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51443725
has text: Do you have a link? I'm not really sure what to search for.

http://stackoverflow.com/q/51347059
has title: How can I create custom column in group-by then aggregation in pandas
tagged with: pandas
has comment: http://stackoverflow.com/comment/89668665
accepted answer: http://stackoverflow.com/a/51347074
tagged with: python
has body: I have DataFrame in the following format. | User | CodeID | Language | | ------------- |---------------| -------- | | foo | 1 | C | | foo | 2 | C | | foo | 3 | CPP | | bar | 4 | C | | bar | 5 | CPP | | bar | 6 | Java | | bar | 7 | CPP | Now what I want is to calculate the number of codes in each language for each user. That is I want a DataFrame in the following format. | User | C | CPP | Java | Total | | ---- | -- | --- | ---- | ----- | | foo | 2 | 1 | 0 | 3 | | bar | 1 | 2 | 1 | 4 | Point to be noted that the number of languages is dynamic. However, it is okay if someone can provide a solution with a fixed set of languages. Thanks in advance.
upvote count: 1
has comment: http://stackoverflow.com/comment/89713551
has comment: http://stackoverflow.com/comment/89667354
type: AnsweredQuestion
score: 1
tagged with: dataframe
has answer: http://stackoverflow.com/a/51347074
type: Question
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/89728587
score: 0
type: Comment
has text: I updated the solution. This should now work in jupyter, IPython and as script.
comment on: http://stackoverflow.com/a/51365787
type: AnswerComment

http://stackoverflow.com/q/51394671
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: pycharm
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51395006
has title: Unresolved attribute reference in Python 3
linked to: http://stackoverflow.com/q/2709821
downvote count: 0
answer count: 1
has body: class StringHandling: def __init__(self,yo): self.yo = yo def my_first_test(): yo = input("Enter your string here") ya = (yo.split()) even = 0 odd = 0 for i in ya: if len(i) % 2 == 0: even = even + 1 else: odd = odd + 1 print("The number of odd words are ", odd) print("The number of even words are", even) if __name__ == '__main__': c = StringHandling(yo="My name is here ") c.my_first_test() What is the problem here? Have tried everything! I have tried indenting and the object is created but the method my_first_test is not called/used by object c.
favorite count: 0

http://stackoverflow.com/q/51478595
has title: What are ways I can debug this keras layer?
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51479183
accepted answer: http://stackoverflow.com/a/51479183
type: Question
downvote count: 0
tagged with: keras
tagged with: keras-layer
tagged with: batch-normalization
has body: I am new to Keras and am attempting to implement the decorrelated batch Norm paper (https://arxiv.org/abs/1804.08450) in Keras as a learning experience. The layer is very similar to standard batch norm with a few additional components. Instead of centering the input data to each layer and normalizing by the variance, we now center the data and apply a whitening transform which is computed by doing an eigenvalue decomposition on the covariance matrix. The entire procedure is clearly laid out in the paper (Algorithm 1, page 5) and composed of only like 5 equations, whose implementation I marked in the code below. I successfully re-implemented standard batch norm layer, but am getting NaN loss and low accuracy when I incorporate the whitening procedure. I am wondering if there any advice I should follow to debug this code. I am not sure if I made a dimensionality mistake or incorrectly implemented the equations, but any help would be appreciated. Here is the code if you are interested (Edited to include Daniel Möller's corrections). The input to the layer is a tensor of dimension (batch_size height width channels). input_shape = K.int_shape(inputs) # (batch_size height width channels) # unroll all dimensions except feature maps dim (c X hwb) pool_shape = (-1, input_shape[-1]) x = K.reshape(x,pool_shape) x = K.permute_dimensions(x, (1,0)) #if you do want to invert the dimensions mean = K.mean(x,1,keepdims=True) # standard batch norm #stddev = K.std(x,1,keepdims=True) + self.epsilon #normed = (x - mean) / stddev #normed = K.reshape(normed,((-1,)+ input_shape[1:])) # center inputs centered_inputs = x - mean #vvvvvERROR SOMEWHERE IN HEREvvvvv# # compute covariance matrix for reshaped inputs xxt covar = K.batch_dot(K.expand_dims(x, axis=-1), K.expand_dims(x, axis=-1),axes=(2,2)) # fuzz covariance matrix to prevent singularity covar = covar + self.epsilon # execute eigenvalue decomposition #Lambda, D,_ = tf.svd(covar,compute_uv=True) Lambda, D = tf.self_adjoint_eig(covar) La…
answer count: 1
favorite count: 0

http://stackoverflow.com/q/51372151
answer count: 1
tagged with: python
type: AnsweredQuestion
tagged with: subprocess
has answer: http://stackoverflow.com/a/51372164
has title: Printing info from executable pdfinfo in python
accepted answer: http://stackoverflow.com/a/51372164
type: Question
score: 0
has body: path1 = "C:/Users/Gebruiker/PycharmProjects/pdf_processor/Files/pdf_files/" pdffname = "testfile2.pdf" file_info = subprocess.Popen(['pdfinfo', '-meta', os.path.join(path1, pdffname)]) So I need to find out how many pages this pdf has. If I call the function in cmd it works fine. But how do I extract the data from the -meta command? The function returns no errors. The file_info variable is of type . And supposedly the data from the -meta command is in xml format. But there is no option to extract an xml file anywhere. And it does not even print anything :/ . Completely lost here. edit: I actually made it work like this: pdf_info = subprocess.Popen(['pdfinfo', '-meta', os.path.join(path1, pdfname)], stdout=subprocess.PIPE) output = pdf_info.stdout.read() with open(os.path.join(path3, 'pdf_info.xml'), 'wb') as file: file.write(output)
tagged with: pdftotext

http://stackoverflow.com/comment/89694778
type: Comment
comment on: http://stackoverflow.com/q/51360932
score: 0
has text: No you don't. As I say, there is no such thing as generics.NameView, so the only thing this code would do is raise AttributeError. You are not actually running this code.
type: QuestionComment

http://stackoverflow.com/comment/89669739
type: Comment
comment on: http://stackoverflow.com/a/51340887
has text: how can .dat file stop me from editing it or see it . i open it with notepad and i can delete it . another thing when i open the write_it.dat file i don't understand what is written it gave something like that """€]q (X sweetqX hotqX""" can you clarify this to me i'm still a noobie.
score: 0
type: AnswerComment

http://stackoverflow.com/q/51457794
upvote count: 2
score: 1
linked to: http://stackoverflow.com/q/15053790
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89885110
has body: The problem I am trying to run my first Flask applications while following the CS50 Javascript course. I have made succesfully implemented a few of the examples of the class. However I got a 500 Internal Server Error as I tried to run the following piece of code: Code 1 from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): return render_template("index.html") if __name__ == "__main__": app.run() I run the code in the terminal by calling the name of my python app as such: python app.py What I tried 1. I tried running a more simple example: Code 2 from flask import Flask app = Flask(__name__) @app.route("/") def index(): return "hello world!" if __name__ == "__main__": app.run() Since I was able to run this without a problem I decided to get back to the previous example. However I haven't been able to figure out the solution. The syntax seems to be correct. To be sure I compared the code letter for letter with that of the video. I noticed that the teacher of the video ran the application differently using: set FLASK_APP = app.py flask run I tried that. This seemed to work too for a while. Becoming frustrated I tried many of the things that worked before and even the simplest pieces of code such as code 2 seem to yield that 500 internal Server Error. 2. At some point I thought there might be a problem with flask which led me to reinstalling it. What could be causing this? This is not the first time I have encountered this problem. Evertime it seems to "resolve" itself when I quit using the computer for a while which makes me none the wiser. How do I find a solution online to a problem that I can merely define this broadly? The 500 Internal Server Error isn't really giving me hints. [Edit:] I'm currently on a vacation at the hotel working on the local wifi. Could that have an impact on my server?
linked to: http://stackoverflow.com/q/17309889
duplicate of: http://stackoverflow.com/q/32722143
duplicate of: http://stackoverflow.com/q/17309889
has comment: http://stackoverflow.com/comment/89885383
tagged with: flask
duplicate of: http://stackoverflow.com/q/23327293
favorite count: 0
has title: 500 Internal Server Error Flask
has comment: http://stackoverflow.com/comment/89885066
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89885140
tagged with: python
has comment: http://stackoverflow.com/comment/89886089
answer count: 0

http://stackoverflow.com/comment/89777863
has text: @chepner if that directory is added, shouldn't the sys.path from withing the python code return the current sys.path, ie: I should see the script's directory added there?
comment on: http://stackoverflow.com/q/51403126
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89877061
comment on: http://stackoverflow.com/a/51453672
score: 0
type: Comment
has text: forgot to pack the frame. Try now
type: AnswerComment

http://stackoverflow.com/a/51431251
upvote count: 1
has comment: http://stackoverflow.com/comment/89835086
has comment: http://stackoverflow.com/comment/89837178
downvote count: 0
type: AcceptedAnswer
has body: You want to use ? to mark the 'end' of the substring you wish to replace. import re text = 'To: abcd@gef.org; Report from xxxxx \n Category\t Score\t \n xxxxxxxxxxx xxxxxxxxt \n xxxxxxx\t xxxxxxx\t \n\n original message\n' a=re.sub(r'Report from.+?\n\n', r'\n', text, flags=re.DOTALL) print(a) To: abcd@gef.org; original message
type: Answer
has comment: http://stackoverflow.com/comment/89834044
accepted answer of: http://stackoverflow.com/q/51430883
score: 1
answers question: http://stackoverflow.com/q/51430883

http://stackoverflow.com/comment/89895700
type: QuestionComment
comment on: http://stackoverflow.com/q/51463389
has text: @PatrickArtner Its two bus departures on the same line so timeLeft is time until the bus arrives and timeNext is time until the bus after that arrives.
score: 0
type: Comment

http://stackoverflow.com/comment/90006258
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51466554
has text: Your decoder condition uses a variable (max_loop_len) that it's not given as an input? Are you using an optimizer?
score: 0

http://stackoverflow.com/comment/133865595
has text: in Django3 2023 it requires yet another argument. Does anyone have any idea what that is?
comment on: http://stackoverflow.com/a/51326287
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89841278
score: 0
type: AnswerComment
type: Comment
has text: wow, that's amazing!! i'm amazed at all the cool stuff python is capable of doing!!
comment on: http://stackoverflow.com/a/51435444

http://stackoverflow.com/q/51325193
linked to: http://stackoverflow.com/q/47155569
has comment: http://stackoverflow.com/comment/89630840
has comment: http://stackoverflow.com/comment/89636559
downvote count: 0
has comment: http://stackoverflow.com/comment/89634847
linked to: http://stackoverflow.com/q/47373762
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89625674
has comment: http://stackoverflow.com/comment/89633947
type: UnansweredQuestion
has body: I am trying to create a simple graph using below code. Y = [DUPLICATE_INCIDENT_5, DUPLICATE_INCIDENT_4, DUPLICATE_INCIDENT_3, DUPLICATE_INCIDENT_2, DUPLICATE_INCIDENT] X = ['9th', '10th', '11th', '12th', '13th'] plt.plot(X, Y, marker='o', linestyle='--', color='g') plt.ylabel('DUPLICATE INCIDENTS') plt.xlabel('July') plt.show() plt.savefig('duplicates.svg') This just created an x-axis with the date values and y-axis with count of incidents. I want to display the graph in an order i.e. Starting from 0 - N as reference values on Y axis and plot the COUNT 8..7..13..3..0 against that. I know this is a stupid question but I am new to matplotlib and am going to start a course on it. Just going though the official documentation to have some basic knowledge before the course starts. EDIT 1: DUPLICATE_INCIDENT* - these are all numbers whose values are as printed in the Y axis. [8, 7, 13, 3, 0]. EDIT 2: My bad - I should have checked ALL the variables defined above before posting a question. One of the above variables was a string. That was causing the issue. It is working as expected now.
tagged with: python
has comment: http://stackoverflow.com/comment/89625660
answer count: 0
duplicate of: http://stackoverflow.com/q/47155569
score: 1
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/89629058
has title: Python matplotlib 2.2.2- sort y axis values?
upvote count: 1
has comment: http://stackoverflow.com/comment/89627117
type: Question
tagged with: graph
has comment: http://stackoverflow.com/comment/89625760
has comment: http://stackoverflow.com/comment/89647158

string
tags question: http://stackoverflow.com/q/51468317
tags question: http://stackoverflow.com/q/51403945
tags question: http://stackoverflow.com/q/51423858
tags question: http://stackoverflow.com/q/51388911
tags question: http://stackoverflow.com/q/51464744
tags question: http://stackoverflow.com/q/51455760
tags question: http://stackoverflow.com/q/51387762
tags question: http://stackoverflow.com/q/51473273
tags question: http://stackoverflow.com/q/51452034
tags question: http://stackoverflow.com/q/51359325
tags question: http://stackoverflow.com/q/51364933
tags question: http://stackoverflow.com/q/51327863
tags question: http://stackoverflow.com/q/51352658
tags question: http://stackoverflow.com/q/51351309
tags question: http://stackoverflow.com/q/51410127
tags question: http://stackoverflow.com/q/51462191
tags question: http://stackoverflow.com/q/51390759
tags question: http://stackoverflow.com/q/51334085
tags question: http://stackoverflow.com/q/51398116
tags question: http://stackoverflow.com/q/51450815
tags question: http://stackoverflow.com/q/51470805
tags question: http://stackoverflow.com/q/51418552
tags question: http://stackoverflow.com/q/51343919
tags question: http://stackoverflow.com/q/51337721
tags question: http://stackoverflow.com/q/51326616
tags question: http://stackoverflow.com/q/51417020
tags question: http://stackoverflow.com/q/51349233
tags question: http://stackoverflow.com/q/51375356
tags question: http://stackoverflow.com/q/51329685
tags question: http://stackoverflow.com/q/51457030
tag name: string
tags question: http://stackoverflow.com/q/51347732
tags question: http://stackoverflow.com/q/51399035
tags question: http://stackoverflow.com/q/51420726
tags question: http://stackoverflow.com/q/51364122
tags question: http://stackoverflow.com/q/51463058
tags question: http://stackoverflow.com/q/51370602
tags question: http://stackoverflow.com/q/51358395
tags question: http://stackoverflow.com/q/51432960
tags question: http://stackoverflow.com/q/51476964
tags question: http://stackoverflow.com/q/51414271
tags question: http://stackoverflow.com/q/51449901
type: Tag
tags question: http://stackoverflow.com/q/51461115
tags question: http://stackoverflow.com/q/51455199
tags question: http://stackoverflow.com/q/51349381
tags question: http://stackoverflow.com/q/51431774
tags question: http://stackoverflow.com/q/51461844
tags question: http://stackoverflow.com/q/51387458
tags question: http://stackoverflow.com/q/51414331
tags question: http://stackoverflow.com/q/51353117
tags question: http://stackoverflow.com/q/51324846
tags question: http://stackoverflow.com/q/51450004
tags question: http://stackoverflow.com/q/51443326
tags question: http://stackoverflow.com/q/51456317
tags question: http://stackoverflow.com/q/51393081
tags question: http://stackoverflow.com/q/51405913
tags question: http://stackoverflow.com/q/51338005
tags question: http://stackoverflow.com/q/51341285
tags question: http://stackoverflow.com/q/51387189
tags question: http://stackoverflow.com/q/51334327
tags question: http://stackoverflow.com/q/51468536
tags question: http://stackoverflow.com/q/51331018
tags question: http://stackoverflow.com/q/51452089
tags question: http://stackoverflow.com/q/51406294
tags question: http://stackoverflow.com/q/51434105
tags question: http://stackoverflow.com/q/51385015
tags question: http://stackoverflow.com/q/51363199
tags question: http://stackoverflow.com/q/51460441
tags question: http://stackoverflow.com/q/51350706
tags question: http://stackoverflow.com/q/51465085
tags question: http://stackoverflow.com/q/51434149
tags question: http://stackoverflow.com/q/51350812
tags question: http://stackoverflow.com/q/51378404
tags question: http://stackoverflow.com/q/51406066

http://stackoverflow.com/q/51475957
accepted answer: http://stackoverflow.com/a/51485355
has comment: http://stackoverflow.com/comment/89920200
tagged with: flask
answer count: 2
downvote count: 0
favorite count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/67499859
has answer: http://stackoverflow.com/a/51485355
has answer: http://stackoverflow.com/a/67499859
score: 4
type: AnsweredQuestion
tagged with: flask-restful
has title: flask_restful import Resource error
has body: I did the following tutorial on youtube: https://www.youtube.com/watch?v=s_ht4AKnWZg This is my code: from flask import Flask, request from flask_restful import Resource, Api app = Flask(__name__) api = Api(app) class HelloWorld(Resource): def get(self): return {'about':'Hello World!'} def post(self): some_json = request.get_json() return {'you sent': some_json}, 201 class Multi(Resource): def get(self, num): return {'result': num*10} api.add_resource(HelloWorld, '/') api.add_resource(Multi, '/multi/&lt;int:num&gt;') if __name__ == '__main__': app.run(debug=True) Now when I run the script, I get following error: /home/one/systemx/test_api$ python flask_restful.py Traceback (most recent call last): File "flask_restful.py", line 2, in &lt;module&gt; from flask_restful import Resource, Api File "/home/one/systemx/test_api/flask_restful.py", line 2, in &lt;module&gt; from flask_restful import Resource, Api ImportError: cannot import name Resource The code is 1:1 like in the video. Does someone have a idea where the problem is?
type: Question
upvote count: 4

http://stackoverflow.com/comment/89700830
comment on: http://stackoverflow.com/a/51358969
type: AnswerComment
score: 0
type: Comment
has text: Is the ValueError related to your new logging setup? Could you please add the Traceback to your question?

http://stackoverflow.com/comment/89802464
score: 0
comment on: http://stackoverflow.com/q/51415626
type: QuestionComment
type: Comment
has text: os.system(command) is used to execute the commands

http://stackoverflow.com/a/51456709
score: 0
answers question: http://stackoverflow.com/q/51456679
type: AcceptedAnswer
has body: lets assume that your dataframe is df. do the following df["Product"] = df["Product"].apply(lambda x:x.strip(","))
type: Answer
accepted answer of: http://stackoverflow.com/q/51456679

http://stackoverflow.com/q/51378194
has body: import os os.chdir('../../') print os.getcwd() import sys import unittest from chatbot_run.chatbot_conf import chatbot_conf_dict /home/mengyuguang/yige Traceback (most recent call last): File "test_time_entity.py", line 21, in &lt;module&gt; from chatbot_run.chatbot_conf import chatbot_conf_dict ImportError: No module named chatbot_run.chatbot_conf chatbot_run is a project that I wrote. I am doing this import of the fifth line which works fine on Windows. The python file is in yige/test/ner folder and I run the file in this folder, too. It printed yige and chatbot_run is in yige, too. This is really strange. What's the difference in linux that causes this.
has comment: http://stackoverflow.com/comment/89727956
has comment: http://stackoverflow.com/comment/89728293
has title: Import error in linux but success on windows
type: AnsweredQuestion
downvote count: 0
favorite count: 0
tagged with: linux
has comment: http://stackoverflow.com/comment/89728118
type: Question
has comment: http://stackoverflow.com/comment/89728316
tagged with: windows
has answer: http://stackoverflow.com/a/51378403
tagged with: python
accepted answer: http://stackoverflow.com/a/51378403
score: 1
has comment: http://stackoverflow.com/comment/89728294
has comment: http://stackoverflow.com/comment/89728390
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/89728096

http://stackoverflow.com/comment/89765205
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51395847
score: 1
has text: That looks interesting, I'll try to have a look and get back if it turns out that I misunderstood your question.

http://stackoverflow.com/comment/89833765
type: QuestionComment
has text: Yeah I have went through many examples but I am struggling to get it to work I get many syntax errors, I am new to python
comment on: http://stackoverflow.com/q/51431082
score: 0
type: Comment

http://stackoverflow.com/a/62694015
type: Answer
score: 2
upvote count: 2
has body: After so many days I hope you have found the solution to the problem, but I will share another idea here so that new people like me who will face the same problem in the future, get help. A few days ago I had this kind of problem. follow_links will be a solution to your question, as user3731622 said. Also, I think the idea of ​​merging two data generators will work. However, in that case, the batch sizes of the corresponding data generators have to be determined proportion to the extent of data in each relevant directory. Batch size of sub-generators: Where, b = Batch Size Of Any Sub-generator B = Desired Batch Size Of The Merged Generator n = Number Of Images In That Directory Of Sub-generator the sum of n = Total Number Of Images In All Directories See the code below, this may help: from keras.preprocessing.image import ImageDataGenerator from keras.utils import Sequence import matplotlib.pyplot as plt import numpy as np import os class MergedGenerators(Sequence): def __init__(self, batch_size, generators=[], sub_batch_size=[]): self.generators = generators self.sub_batch_size = sub_batch_size self.batch_size = batch_size def __len__(self): return int( sum([(len(self.generators[idx]) * self.sub_batch_size[idx]) for idx in range(len(self.sub_batch_size))]) / self.batch_size) def __getitem__(self, index): """Getting items from the generators and packing them""" X_batch = [] Y_batch = [] for generator in self.generators: if generator.class_mode is None: x1 = generator[index % len(generator)] X_batch = [*X_batch, *x1] else: x1, y1 = generator[index % len(generator)] X_batch = [*X_batch, *x1] Y_batch = [*Y_batch, *y1] if self.generators[0].class_mode is None: return np.array(X_batch) return np.array(X_batch), np.array(Y_batch) def build_datagenerator(dir1=None, dir2=None, batch_size=32): n_images_in_dir1 = sum([len(files) for r, d, files in os.walk(dir1)]) n_images_in_dir2 = sum([len(files) for r, d, files in os.walk(dir2)]) # Have to set different batch size for two g…
answers question: http://stackoverflow.com/q/51355524
downvote count: 0

http://stackoverflow.com/q/51454362
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion
downvote count: 2
has body: I was trying to do that task with Matlab using : url = 'the url of the file'; file_name = 'data.mat'; outfilename = websave(filename,url); load(outfilename); but it didn't work, how can i do that using python? kindly note i want the .mat as it is not an html , csv or any other format i just that file just downloaded(i can do it manually but i have hundreds that's why i need that) .(python 3)
has comment: http://stackoverflow.com/comment/89878252
tagged with: urllib
type: Question
upvote count: 0
score: -2
answer count: 1
has title: How can i download a .mat file from a website?
has answer: http://stackoverflow.com/a/51454411
favorite count: 0

http://stackoverflow.com/comment/138427053
comment on: http://stackoverflow.com/a/77766429
type: Comment
score: 1
has text: The question is about the Python library
type: AnswerComment

http://stackoverflow.com/a/51408918
score: 0
answers question: http://stackoverflow.com/q/51408860
has body: word_list.readlines() will give the list itself as per row ending
type: Answer

http://stackoverflow.com/q/51370135
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/89712963
has comment: http://stackoverflow.com/comment/89712981
upvote count: 1
has comment: http://stackoverflow.com/comment/89712869
downvote count: 1
has comment: http://stackoverflow.com/comment/89712700
tagged with: shared-memory
favorite count: 0
type: UnansweredQuestion
has body: I was trying to read and output the shared dictionary element to a file. But I tested that I cannot access the shared dictionary and it will return error. I wrote the following code but it only works if the dictionary object is not been shared (as I commented). Could anyone suggest how to access the shared memory dictionary? import multiprocessing as mp sharedi = mp.Manager().dict() #sharedi = {} l1 = ['a','b','c','d'] l2 = ['b','b','c','e'] for i in range(0,2): name = "abc"+str(i) sharedi.update({name:[l1,l2]}) def writ(dirname): outfile = open(dirname,'w') for i in sharedi: for object in sharedi[i][0]: outfile.write(object) print sharedi p1 = mp.Process(target = writ,args=('d1',)) p2 = mp.Process(target = writ,args=('d2',)) p1.start() p2.start() # adding join() as suggeseted in the comment p1.join() p2.join() I'm expecting to write the shared dictionary to files and this is the error message I get: Process Process-3: Process Process-2: Traceback (most recent call last): Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap self.run() File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/process.py", line 114, in run self.run() File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/process.py", line 114, in run self._target(*self._args, **self._kwargs) File "dict.py", line 14, in writ self._target(*self._args, **self._kwargs) File "dict.py", line 14, in writ for i in sharedi: for i in sharedi: File "&lt;string&gt;", line 2, in __getitem__ File "&lt;string&gt;", line 2, in __getitem__ File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/managers.py", line 755, in _callmethod File "/System/Library/Frameworks/Python.…
has title: Loading from a shared memory dictionary in python
tagged with: python
tagged with: dictionary
answer count: 0
has comment: http://stackoverflow.com/comment/89713108
linked to: http://stackoverflow.com/q/29702157
tagged with: multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/89712935
has comment: http://stackoverflow.com/comment/89712987
has comment: http://stackoverflow.com/comment/89713154
has comment: http://stackoverflow.com/comment/89712850

http://stackoverflow.com/comment/89840190
has text: @Kristada673 then I think `pd.concat([df, df1]).sort_values('Row ID')` will work
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51434865
type: AnswerComment

http://stackoverflow.com/q/51461695
accepted answer: http://stackoverflow.com/a/51463685
tagged with: python-3.x
has title: Python sqlite3 - retrieve every n-1 row in database
tagged with: python
has answer: http://stackoverflow.com/a/51463685
type: AnsweredQuestion
type: Question
has body: I have a database of values with the first column being an identifying number for each row in my database. What I want to do is create a function to retrieve every n-1 (or n-offset) row so if I give a number like '50' to the function, it will print the database that have the row numbers that are a multiple of 50-1. So inputting '50' will give the rows of '49', '99', '149', '199', etc instead of '50', '100', '150', '200' and print the database with those specific rows. This is what I have so far: import sqlite3 from tabulate import tabulate def retrieve_nth_row(rownum): with conn: data = c.execute(f"SELECT * FROM Table_name WHERE IdNum &gt; 0 and IdNum &lt;= (SELECT max(IdNum) FROM Anime) AND IdNum % {rownum} = 0") print(tabulate(data, headers="keys", tablefmt="grid", stralign='center', numalign='center')) #Prints the database as a neat table The code I have prints out the database for every multiple of 'rownum' specified (so 'rownum' = 50 prints out rows 50,100,150,200, etc). I can't seem to figure out how to add a offset it to print out 'rownum'-(offset) rows.
has comment: http://stackoverflow.com/comment/89892524
answer count: 1
score: 0
tagged with: sqlite
has comment: http://stackoverflow.com/comment/89892538

http://stackoverflow.com/comment/89805564
type: QuestionComment
has text: @tombstone Thank you, I will try that and keep you posted. The messages also appear during the training and not only during the eval though.
score: 0
comment on: http://stackoverflow.com/q/51407435
type: Comment

http://stackoverflow.com/q/51390895
tagged with: unix-timestamp
tagged with: python-3.x
tagged with: time
tagged with: python
type: AnsweredQuestion
has title: Convert UNIX timestamp to how long it was in seconds
type: Question
score: 0
has answer: http://stackoverflow.com/a/51391012
accepted answer: http://stackoverflow.com/a/51391012
answer count: 1
has body: I'm working on a project and I need help. I'd like to calculate how long ago was posted an instagram image. Using their json api I can get by example: "edge_owner_to_timeline_media": { "count": 19938, "page_info": { "has_next_page": true, "end_cursor": "AQCJsPghTApTJTITHUm_iXp9fqZGXrfJXIYCc60OqvLM98v9a8xgDQ8hiIUUaViSd913BxRHSILvz8_G2Vfw0FALXEFEf2p2fpuNnupbvjqQ8A" }, "edges": [ { "node": { "__typename": "GraphImage", "id": "1825727462006678242", "edge_media_to_caption": { "edges": [ { "node": { "text": "Yep" } } ] }, "shortcode": "BlWSXQdlWLi", "edge_media_to_comment": { "count": 9 }, "comments_disabled": false, "taken_at_timestamp": 1531863695, "dimensions": { "height": 1080, "width": 1080 }, The highlight being the "taken_at_timestamp" which gives me when the image was uploaded in UNIX time, however what I'd like to do is get the current UNIX time with by example: import time int(time.time()) And then calculate in seconds how long ago (timezone independent) the image was uploaded from now? Is that possible? It's hard for me to get my head around UNIX and Epoch times and all of that :)
tagged with: unix

http://stackoverflow.com/q/51418552
downvote count: 0
has comment: http://stackoverflow.com/comment/89808896
type: Question
has answer: http://stackoverflow.com/a/51419171
tagged with: sorting
score: 4
has comment: http://stackoverflow.com/comment/89808069
has body: I have two lists of strings. list_one = ["c11", "a78", "67b"] list_two = ["a", "b", "c"] What is the shortest way of sorting list_one using strings from list_two to get the following output? ["a78", "67b", "c11"] Edit 1: There is a similar question Sorting list based on values from another list?, but in that question he already has the list of required indexes for resulting string, while here I have just the list of substrings. Edit 2: Since the example of list above might be not fully representative, I add another case. list_one is ["1.cde.png", "1.abc.png", "1.bcd.png"] list_two is ["abc", "bcd", "cde"]. The output is supposed to be [ "1.abc.png", "1.bcd.png", "1.cde.png"] If, for example, list_one is shorter than list_two, it should still work: list_one is ["1.cde.png", "1.abc.png"] list_two is ["abc", "bcd", "cde"] The output is supposed to be [ "1.abc.png", "1.cde.png"]
has comment: http://stackoverflow.com/comment/89809489
has comment: http://stackoverflow.com/comment/89808251
linked to: http://stackoverflow.com/q/6618515
tagged with: string
has comment: http://stackoverflow.com/comment/89808213
has title: Sorting list based on order of substrings in another list
has answer: http://stackoverflow.com/a/51418835
accepted answer: http://stackoverflow.com/a/51418835
favorite count: 0
has answer: http://stackoverflow.com/a/51419500
has comment: http://stackoverflow.com/comment/89809920
has comment: http://stackoverflow.com/comment/89808498
possible better answer: http://stackoverflow.com/a/51418764
has comment: http://stackoverflow.com/comment/89809246
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/89808187
answer count: 4
has answer: http://stackoverflow.com/a/51418764
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89808020
tagged with: list

http://stackoverflow.com/a/51498593
score: -1
has body: Before CNNs segmentation by Level-Sets was all the rage. Check out this informative link (don't worry its not mine): https://wiseodd.github.io/techblog/2016/11/20/levelset-segmentation/
answers question: http://stackoverflow.com/q/51475343
downvote count: 1
type: Answer
upvote count: 0

http://stackoverflow.com/a/51438598
score: 0
has comment: http://stackoverflow.com/comment/89885914
answers question: http://stackoverflow.com/q/51437917
type: Answer
has body: l=[['Jullu', '18', 'Art'], ['sean', '25', 'Art'], ['Rubeena', '18', 'Science'], ['Kareen', '18', 'Science'], ['Rene', '18', 'Geology'], ['Babu', '18', 'Geology'], ['Riggu', '18', 'Robotics']] l=[[x for x in l if x[-1]==i] for i in list(set(list(zip(*l))[-1]))] for i in l: print(i[0][-1]) print('\n'.join(['\t'+str(x) for x in i])) Output: Robotics ['Riggu', '18', 'Robotics'] Science ['Rubeena', '18', 'Science'] ['Kareen', '18', 'Science'] Art ['Jullu', '18', 'Art'] ['sean', '25', 'Art'] Geology ['Rene', '18', 'Geology'] ['Babu', '18', 'Geology']

http://stackoverflow.com/q/51327792
has answer: http://stackoverflow.com/a/51328093
upvote count: 6
tagged with: list
has comment: http://stackoverflow.com/comment/89630922
type: Question
has title: Python: Extracting lists from list with module or regular expression
has answer: http://stackoverflow.com/a/51328145
has answer: http://stackoverflow.com/a/51328258
has answer: http://stackoverflow.com/a/51328108
has answer: http://stackoverflow.com/a/51328144
answer count: 6
tagged with: search
has body: I'm trying to extract lists/sublists from one bigger integer-list with Python2.7 by using start- and end-patterns. I would like to do it with a function, but I cant find a library, algorithm or a regular expression for solving this problem. def myFunctionForSublists(data, startSequence, endSequence): # ... todo data = [99, 99, 1, 2, 3, 99, 99, 99, 4, 5, 6, 99, 99, 1, 2, 3, 99, 4, 5, 6, 99] startSequence = [1,2,3] endSequence = [4,5,6] sublists = myFunctionForSublists(data, startSequence, endSequence) print sublists[0] # [1, 2, 3, 99, 99, 99, 4, 5, 6] print sublists[1] # [1, 2, 3, 99, 4, 5, 6] Any ideas how I can realize it?
linked to: http://stackoverflow.com/q/17870544
has comment: http://stackoverflow.com/comment/89631352
downvote count: 0
has comment: http://stackoverflow.com/comment/89630959
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89631268
has comment: http://stackoverflow.com/comment/89630979
has answer: http://stackoverflow.com/a/51328082
score: 6
tagged with: python
tagged with: regex

http://stackoverflow.com/comment/89718173
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51345055
has text: Pete, I gotta be missing something fundamental. When I punch in the edit#2 I still get Error: iterable expected, not int

http://stackoverflow.com/a/51390056
answers question: http://stackoverflow.com/q/51389834
has comment: http://stackoverflow.com/comment/89752399
has comment: http://stackoverflow.com/comment/89752240
downvote count: 0
has comment: http://stackoverflow.com/comment/89752361
type: Answer
score: 2
upvote count: 2
has body: The real issue here is that you shouldn't be writing either of these.1 self.vec.append(v1) if v1 else pass is illegal because pass is a statement, not an expression, and you can't put statements inside expressions. self.vec.append(v1) if v1 else 0 is legal, because 0 is an expression. But just because it's legal doesn't mean it's code you should ever write. The point of the if expression is that it's an expression, so it (a) has a value that you can use, and (b) can be used in larger expressions. You aren't using the value of self.vec.append(v1) (which is None), or the value of 0 (which is of course 0). You're just evaluating the first one for its side-effects and the second one as a workaround to fight against the language's syntax. You're also not putting the expression inside another expression; you're just using it as an expression statement. The way to write this is simple: if v1: self.vec.append(v1) else: pass But of course you don't need an else clause here, so you can just write this as: if v1: self.vec.append(v1) Or, if you're desperate to save space: if v1: self.vec.append(v1) Sometimes it's worth sacrificing readability for performance, or occasionally even for brevity. But your attempt to abuse an if expression for its side effects is slower (especially in the false case—a jump and evaluating a literal just to discard it may be fast, but it's not nearly as fast as doing nothing at all). And it's much longer. 1. In fact, the worry that people would try to write code like this, even though there's absolutely no reason to, was the main argument against PEP 308, the proposal to add this feature. The PEP passed only because anyone who'd be silly enough to try to write code like this is going to write Perl instead of Python anyway.

http://stackoverflow.com/a/51442482
has body: For 2 arrays x1, x2 = map(list, zip(*zip(*[iter(a)] * 2))) print(x1, x2, sep='\n') [5, 3, 1] [4, 2, 0] For 3 arrays x1, x2, x3 = map(list, zip(*zip(*[iter(a)] * 3))) print(x1, x2, x3, sep='\n') [5, 2] [4, 1] [3, 0] Why this works iter(a) creates an iterator on the list a. When you iterate through it, the elements get used up and eventually the iterator becomes exhausted. [iter(a)] * 2 creates a list that looks like this i = iter(a); [i, i]. Notice that the same iterator shows up twice. That means that when I take an element from the first i, I also take it from the second i because they point to the same iterator. So! when I use zip on the unpacked list of the same iterator zip(*[iter(a)] * 2), As I pair things up, I'm pulling from the same iterator and therefore naturally exhausting them in the order we want. I then use another zip to transpose the results and then map with list to make them lists instead of tuples.
has comment: http://stackoverflow.com/comment/89854835
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/51442086
downvote count: 0
score: 3

http://stackoverflow.com/comment/89932403
comment on: http://stackoverflow.com/q/51406199
type: QuestionComment
has text: No, nothing that wouldn't require re-writing the convolution :-/
score: 0
type: Comment

http://stackoverflow.com/comment/89636009
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51330160
has text: couldn't you just use `\\?`

http://stackoverflow.com/a/51430367
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: PyScreeze maintainer here. This is caused by a packaging error, which has been fixed in 0.1.18. It should work now if you install pyautogui, though you may have to delete the pip cache on your machine first.
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51426884
answers question: http://stackoverflow.com/q/51426884

http://stackoverflow.com/comment/89867185
type: Comment
has text: If fruit_name is a string "apple II" and the key he wants to delete is a string "apple II" then believe me, in Python 3, the code is three lines and completely viable as an answer and makes good use of the hashing involved with the search used on dictionaries
comment on: http://stackoverflow.com/a/51429172
score: 0
type: AnswerComment

http://stackoverflow.com/q/51389476
type: Question
has comment: http://stackoverflow.com/comment/89762469
score: 0
has comment: http://stackoverflow.com/comment/89751256
tagged with: flask
type: UnansweredQuestion
tagged with: python
has title: Python code isn't being executed after webbrowser.get(chrome_path).open(url)
answer count: 0
tagged with: selenium
has body: I have a little flask application, which runs specific website on the server using chrome browser and make some tests once it gets request. Here is the part of code where specific url is being opened using chrome web browser. def testrun(file, url, apiUrl): openFile(file) webbrowser.get(chrome_path).open(url) time.sleep(5) checkAppIsRunning("AmcEngine.exe") responseContent = requests.get(apiUrl) respjson = responseContent.json() slackResponse(checkAnswers (respjson, ID)) os.system("taskkill /im chrome.exe") The problem is that after webbrowser.get(chrome_path).open(url) line the rest part of the code isn't being executed untill I close chrome manually. What's interesting that when chrome is already opened when I am running this function, all code is being executed (opens new tab on this line webbrowser.get(chrome_path).open(url) ), but when chrome is closed (and new chrome instance is being opened by the function instead of opening the url in new tab) code is not working after the mentioned above line. which way to dig?

http://stackoverflow.com/a/67703340
type: Answer
answers question: http://stackoverflow.com/q/51351000
upvote count: 3
has comment: http://stackoverflow.com/comment/119672218
has comment: http://stackoverflow.com/comment/119686526
downvote count: 1
score: 2
has comment: http://stackoverflow.com/comment/119670324
has comment: http://stackoverflow.com/comment/119670533
has body: Here's an improved version of the already given solution - now it uses boto3 and handles files which are larger than 4GiB: import boto3 import io import struct import zipfile s3 = boto3.client('s3') EOCD_RECORD_SIZE = 22 ZIP64_EOCD_RECORD_SIZE = 56 ZIP64_EOCD_LOCATOR_SIZE = 20 MAX_STANDARD_ZIP_SIZE = 4_294_967_295 def lambda_handler(event): bucket = event['bucket'] key = event['key'] zip_file = get_zip_file(bucket, key) print_zip_content(zip_file) def get_zip_file(bucket, key): file_size = get_file_size(bucket, key) eocd_record = fetch(bucket, key, file_size - EOCD_RECORD_SIZE, EOCD_RECORD_SIZE) if file_size <= MAX_STANDARD_ZIP_SIZE: cd_start, cd_size = get_central_directory_metadata_from_eocd(eocd_record) central_directory = fetch(bucket, key, cd_start, cd_size) return zipfile.ZipFile(io.BytesIO(central_directory + eocd_record)) else: zip64_eocd_record = fetch(bucket, key, file_size - (EOCD_RECORD_SIZE + ZIP64_EOCD_LOCATOR_SIZE + ZIP64_EOCD_RECORD_SIZE), ZIP64_EOCD_RECORD_SIZE) zip64_eocd_locator = fetch(bucket, key, file_size - (EOCD_RECORD_SIZE + ZIP64_EOCD_LOCATOR_SIZE), ZIP64_EOCD_LOCATOR_SIZE) cd_start, cd_size = get_central_directory_metadata_from_eocd64(zip64_eocd_record) central_directory = fetch(bucket, key, cd_start, cd_size) return zipfile.ZipFile(io.BytesIO(central_directory + zip64_eocd_record + zip64_eocd_locator + eocd_record)) def get_file_size(bucket, key): head_response = s3.head_object(Bucket=bucket, Key=key) return head_response['ContentLength'] def fetch(bucket, key, start, length): end = start + length - 1 response = s3.get_object(Bucket=bucket, Key=key, Range="bytes=%d-%d" % (start, end)) return response['Body'].read() def get_central_directory_metadata_from_eocd(eocd): cd_size = parse_little_endian_to_int(eocd[12:16]) cd_start = parse_little_endian_to_int(eocd[16:20]) return cd_start, cd_size def get_central_directory_metadata_from_eocd64(eocd64): cd_size = parse_little_endian_to_int(eocd64[40:48]) cd_start = parse_little_endian_to_int(eocd6…
has comment: http://stackoverflow.com/comment/130899849

http://stackoverflow.com/a/51416335
has body: Using apply import pandas as pd df = pd.DataFrame({"names": ["Adam Smith", "Greg Rogers"]}) df["names"] = df["names"].apply(lambda x: " ".join(reversed(x.split()))) print(df) Output: names 0 Smith Adam 1 Rogers Greg
accepted answer of: http://stackoverflow.com/q/51416190
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51416190
type: Answer
has comment: http://stackoverflow.com/comment/89803881
has comment: http://stackoverflow.com/comment/89829924
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89803863

http://stackoverflow.com/comment/89802229
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51415425
type: Comment
has text: I don't think you can do relative imports unless you are in a module. Your script is not a module. You may be able to do something like call it as a module `python -m script` but when you get to tha tstage you are probably not doing things correctly.

http://stackoverflow.com/q/51442437
has comment: http://stackoverflow.com/comment/89855162
has answer: http://stackoverflow.com/a/51443304
has comment: http://stackoverflow.com/comment/89854997
has comment: http://stackoverflow.com/comment/89855844
has comment: http://stackoverflow.com/comment/89855120
answer count: 2
possible better answer: http://stackoverflow.com/a/51443304
has body: When I try to JPEG-Decompress (old-style JPEG compression, not JPEG-LS and not JPEG2000) the RAW data, I get following error: Traceback (most recent call last): File "raw-reader.py", line 766, in &lt;module&gt; raw_image_data = imageio.imread(io.BytesIO(raw_packed_image_data)) File "/home/ian/.local/lib/python3.6/site-packages/imageio/core/functions.py", line 206, in imread reader = read(uri, format, 'i', **kwargs) File "/home/ian/.local/lib/python3.6/site-packages/imageio/core/functions.py", line 129, in get_reader return format.get_reader(request) File "/home/ian/.local/lib/python3.6/site-packages/imageio/core/format.py", line 168, in get_reader return self.Reader(self, request) File "/home/ian/.local/lib/python3.6/site-packages/imageio/core/format.py", line 217, in __init__ self._open(**self.request.kwargs.copy()) File "/home/ian/.local/lib/python3.6/site-packages/imageio/plugins/pillow.py", line 398, in _open pilmode=pilmode, as_gray=as_gray) File "/home/ian/.local/lib/python3.6/site-packages/imageio/plugins/pillow.py", line 122, in _open self._im = factory(self._fp, '') File "/home/ian/.local/lib/python3.6/site-packages/PIL/JpegImagePlugin.py", line 780, in jpeg_factory im = JpegImageFile(fp, filename) File "/home/ian/.local/lib/python3.6/site-packages/PIL/ImageFile.py", line 102, in __init__ self._open() File "/home/ian/.local/lib/python3.6/site-packages/PIL/JpegImagePlugin.py", line 339, in _open handler(self, i) File "/home/ian/.local/lib/python3.6/site-packages/PIL/JpegImagePlugin.py", line 166, in SOF raise SyntaxError("cannot handle %d-bit layers" % self.bits) SyntaxError: cannot handle 14-bit layers The RAW data in the image is 14-bit JPEG data, and imageio isn't able to read it. When I tried using pillow, it didn't even recognize the data as JPEG. My question now is: How can I decompress the data without writing my own JPEG decompressor, while keeping in mind that the data is 14 bits? My code: import io import imageio allbytes = open("raw_data.dat", "rb…
downvote count: 0
has comment: http://stackoverflow.com/comment/89856224
favorite count: 0
has title: JPEG-Decompression on RAW image in python
has answer: http://stackoverflow.com/a/53073131
tagged with: python-imageio
has comment: http://stackoverflow.com/comment/89856340
tagged with: rawimage
tagged with: python
tagged with: http://stackoverflow.com/tag/jpeg
linked to: http://stackoverflow.com/q/44157201
type: AnsweredQuestion
score: 1
tagged with: compression
upvote count: 1
has comment: http://stackoverflow.com/comment/89854818
accepted answer: http://stackoverflow.com/a/53073131
type: Question

http://stackoverflow.com/q/51351521
type: Question
tagged with: python
tagged with: turtle-graphics
score: 0
has answer: http://stackoverflow.com/a/51351536
accepted answer: http://stackoverflow.com/a/51351536
answer count: 1
has body: I'm trying to use the turtle module in python, as the title says, the graphics window crashes as soon as the graphic has finished drawing. My code is: import turtle for x in range (0, 4): turtle.forward(100) turtle.right(90) I know, complex I have looked around online and found solutions saying use done() or turtle.done() or exitonclick() at the end, but none of those have worked. I am new to Python so the answer is probably something blatantly obvious.
type: AnsweredQuestion
has title: Turtle Graphics stops responding once done

http://stackoverflow.com/comment/89782438
score: 0
type: Comment
type: QuestionComment
has text: Again, I suggest you post code that anyone reading your question can run. I would try out your code, find something that works, and then answer your question. I'm not going to write new code to recreate your dataframe. There are articles on stackoverflow.com about how to write good questions. See "How to Create a Complete, Minimal, and Verifiable Example" at https://stackoverflow.com/help/How-to-ask
comment on: http://stackoverflow.com/q/51404585

http://stackoverflow.com/q/51418976
answer count: 1
has comment: http://stackoverflow.com/comment/89897575
has comment: http://stackoverflow.com/comment/89809079
tagged with: unicode
has title: Could not install Harf Buzz - text shaping engine
favorite count: 0
tagged with: python
upvote count: 0
tagged with: fonts
type: UnansweredQuestion
has body: I am using harfbuzz for shaping fonts. I am a newbie to python. I followed the instructions that was given in Harf Buzz but i couldnt understand these line Make sure you have the installation lib dir in LD_LIBRARY_PATH, as needed for the linker to find the library. Then make sure you also have GI_TYPELIB_PATH pointing to the resulting $prefix/lib/girepository-* directory. in the Readme file. Due to this i could not execute src/sample.py. Because of this i get Traceback (most recent call last): File "sample.py", line 8, in &lt;module&gt; from gi.repository import HarfBuzz as hb ImportError: cannot import name HarfBuzz Thanks in Advance.
tagged with: opentype
tagged with: harfbuzz
type: Question
has comment: http://stackoverflow.com/comment/89987995
score: -2
has answer: http://stackoverflow.com/a/51421167
downvote count: 2
has comment: http://stackoverflow.com/comment/89808924

http://stackoverflow.com/comment/89626677
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/51325767
has text: `elements[:] = [-3, -1, -2, -3, -4]` would produce your expected output...
type: Comment

http://stackoverflow.com/q/51409422
answer count: 2
has answer: http://stackoverflow.com/a/51409738
downvote count: 1
favorite count: 0
has title: Is there a way to get combinations for a set of tuples?
has answer: http://stackoverflow.com/a/51409759
has body: I have a set of tuples: (1, 3, 6) (5, 2, 4) ... (8, 1, 9) I can get combinations of middle (or first or last) values whose sum is below a certain value: def func(tuples, maxVal): values = [i[1] for i in tuples] result = [seq for s in range(len(values), 0, -1) for seq in itertools.combinations(values, s) if sum(seq) &lt;= maxVal] print(result) but i'd like to be able to keep track of which tuples the values came from, so instead of just returning sets of values with appropriate sum, i want to return whole tuples which those values came from. Not sure how to do that.
tagged with: python
type: AnsweredQuestion
score: 2
possible better answer: http://stackoverflow.com/a/51409759
type: Question
tagged with: combinations
accepted answer: http://stackoverflow.com/a/51409738
upvote count: 3

http://stackoverflow.com/q/51465085
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/89900397
accepted answer: http://stackoverflow.com/a/51466204
tagged with: string
tagged with: hash
tagged with: encryption
has comment: http://stackoverflow.com/comment/89898742
tagged with: python
type: AnsweredQuestion
has title: How to have the decryption function of this encryption function in python
has answer: http://stackoverflow.com/a/51466204
possible better answer: http://stackoverflow.com/a/51466123
type: Question
has answer: http://stackoverflow.com/a/51466123
tagged with: hashmap
has body: If this is an encryption function: (ascii_value % a_ big_ prime_number + a_number_of_ user’s_choice) what would be the opposite decrypt function to convert the encrypted string into the original one and how to implement it in python. Encrypt function will be like : def encrypt_function(string): encrypted_string = '' user_input = int(input('Enter an integer')) for c in string: encrypted_string += chr((ord(c) % 173 + user_input)) return encrypted_string encrypt_function('hello') the output will be something like 'þûĂĂą' with user_input = 150, how to create a method that returns the original string 'hello' and works with different prime numbers other than 173.

http://stackoverflow.com/q/51342116
answer count: 1
upvote count: 3
downvote count: 1
tagged with: python
has body: New here, First post aswell. I'm currently trying to use Tweepy. I've successfully set it up so far and I'm able to tweet single images. So the code runs fine. The purpose of this is because I run an account that tweets images only, no actual text tweets. I've a folder of 100's of images I go through everyday to tweet and found out about tweepy, Is it possible to be able to tell Tweepy to go into the folder of the images and select 1 or any 1 at random? I've did extensive searching and couldn't find anything at all. All help is greatly, greatly appreciated! Here's the code I've got at the moment (python-2). import tweepy from time import sleep consumer_key = 'Removed' consumer_secret = 'Removed' access_token = 'Removed' access_token_secret = 'Removed' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) api.update_with_media('Image') sleep(900) print 'Tweeted!'
has comment: http://stackoverflow.com/comment/131034251
tagged with: tweepy
favorite count: 0
has answer: http://stackoverflow.com/a/52341524
score: 2
has title: Tweepy: Auto Tweet Images From Folder?
type: UnansweredQuestion
type: Question

http://stackoverflow.com/comment/89650094
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51337563
has text: my fault first time, i edited

http://stackoverflow.com/comment/89660560
comment on: http://stackoverflow.com/q/51343573
score: 0
type: Comment
type: QuestionComment
has text: Please show the original image - you may have already discarded useful information.

http://stackoverflow.com/comment/89808204
type: QuestionComment
type: Comment
has text: choices are constant, if you want to show values other than already present in the choices then you need to dynamically load the value.
comment on: http://stackoverflow.com/q/51418261
score: 0

http://stackoverflow.com/comment/89782978
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51387056
has text: That was the issue. I spoke with my sysadmin/network admin and he resolved it in 5 minutes.
score: 0

http://stackoverflow.com/a/51422379
score: 0
type: Answer
has body: Do your dates always look the same? If not: Installation pip3 install python-dateutil pip3 install pytz Code import datetime import dateutil import dateutil.parser import pytz date_in = dateOfBith = '9-9-1992' try: if date_in.count('.') &gt;= 2: date_out = dateutil.parser.parse(date_in, dayfirst=True) else: date_out = dateutil.parser.parse(date_in, dayfirst=False) # Additional parameters for parse: # dayfirst=True # In ambiguous dates it is assumed that the day is further forward. # default=datetime.datetime(1,1,1,0,0,0) # Used only piecewise, i.e. if the year is missing, year will be 1, the rest remains! # fuzzy=True # Ignores words before and after the date. except ValueError as e: print(repr(e)) print(date_out.isoformat()) # returns 1992-09-09T00:00:00 timezone_utc = pytz.utc timezone_berlin = pytz.timezone('Europe/Berlin') # Put your capital here! try: date_out = timezone_berlin.localize(date_out) except ValueError as e: print(repr(e)) print(date_out.isoformat()) # returns 1992-09-09T00:00:00+02:00 if date_out &gt; timezone_utc.localize(datetime.datetime.utcnow()): print('The date is in the future.') Tested with Python 3.4.3 on Ubuntu 14.04.
answers question: http://stackoverflow.com/q/51421916

http://stackoverflow.com/q/51446033
downvote count: 1
accepted answer: http://stackoverflow.com/a/51446275
has comment: http://stackoverflow.com/comment/89862355
type: Question
tagged with: graphics
score: 3
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/89862599
has title: Matplotlib display axis as binary
linked to: http://stackoverflow.com/q/10411085
upvote count: 4
tagged with: python-2.7
answer count: 2
possible better answer: http://stackoverflow.com/a/51446234
has body: I'm attempting to label the x-axis of my graph in binary instead of float values in Python 2.7. I'm attempting to use FormatStrFormatter('%b') which according to the documentation provided by the Python Software Foundation should work. I'd also like all the binary strings to be the same length of characters. I've also consulted this link. The error I'm getting is: ValueError: unsupported format character 'b' (0x62) at index 1 I've tried to do it like: import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import FormatStrFormatter fig, ax = plt.subplots() ax.yaxis.set_major_formatter(FormatStrFormatter('%b')) ax.yaxis.set_ticks(np.arange(0, 110, 10)) x = np.arange(1, 10, 0.1) plt.plot(x, x**2) plt.show()
has answer: http://stackoverflow.com/a/51446234
has comment: http://stackoverflow.com/comment/89862627
has comment: http://stackoverflow.com/comment/89862584
favorite count: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51446275

http://stackoverflow.com/a/51442501
score: 2
downvote count: 0
has body: I don't know why __file__ isn't defined, probably a bug of the launcher. It normally happens when the package is built-in or when the program has been run throught cx_freeze or py2exe, which isn't the case here. In your case, a workaround would be to use sys.argv[0] as this value. It works here because it's the main program you're running. With an auxiliary package it wouldn't work (but __file__ maybe would :)) So I propose to add this to your tss.py file import sys # must be done before try: __file__ except NameError: __file__ = sys.argv[0] so if __file__ exists, well, let it be, else define it as the filepath of the script that is running.
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51442205
type: Answer
answers question: http://stackoverflow.com/q/51442205

http://stackoverflow.com/a/58564552
type: Answer
answers question: http://stackoverflow.com/q/51391458
score: 0
has body: Part of the problem here is that grpcio compiles a platform specific dynamic module: cygrpc.cpython-37m-darwin.so (in my case). According to this response you cannot import dynamic modules in a zip file: https://stackoverflow.com/a/58140801

http://stackoverflow.com/comment/105209674
has text: Thanks, this actually worked, and I couldn't find a solution until I reached this page. Exact command: `pip install --upgrade scipy`
comment on: http://stackoverflow.com/a/51352618
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/comment/89838805
score: 0
comment on: http://stackoverflow.com/a/51432784
type: Comment
has text: I received the error `AttributeError: 'Variable' object has no attribute 'make_initializableiterator'`.
type: AnswerComment

http://stackoverflow.com/q/51398626
tagged with: regex
favorite count: 0
possible better answer: http://stackoverflow.com/a/51398703
has answer: http://stackoverflow.com/a/51398725
has answer: http://stackoverflow.com/a/51398703
has title: Python , regular expressions, replace text containing a word
has answer: http://stackoverflow.com/a/51398778
has answer: http://stackoverflow.com/a/51398766
type: AnsweredQuestion
has body: I wanna replace all text if it contains a given word ( example : 'mama') . i used the following code: import re text1 = 'I love mama so much' result = re.sub(r"\bmama\b",'Nice', text1) print (result) The result of this is : 'I love Nice so much', however i want it to be only 'Nice'. How can i do that ? Thanks.
has answer: http://stackoverflow.com/a/51398758
type: Question
accepted answer: http://stackoverflow.com/a/51398758
upvote count: 1
has answer: http://stackoverflow.com/a/51399133
answer count: 6
score: 0
downvote count: 1
tagged with: python

http://stackoverflow.com/a/51357293
has body: Tensorflow has the Dataset API for this sort of thing. See the tutorial and API documentation: Importing Data tf.data.Dataset
downvote count: 0
score: 1
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51357223

http://stackoverflow.com/a/51421092
accepted answer of: http://stackoverflow.com/q/51420715
answers question: http://stackoverflow.com/q/51420715
score: 0
has body: You can use a while loop, adding 7 days with each pass. xp = [d1] while (d2 - d1).days &gt; 7: d1 += datetime.timedelta(7) xp.append(d1) In-place addition works in this case because datetime objects are immutable.
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/89713002
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51353401
type: AnswerComment
has text: @ZaidZaim I'll update the answer. It looks like what you want now is `brew cask install vlc`.

http://stackoverflow.com/comment/89876524
has text: @nonegiven72 just put my first block of code above your current `find_school` function. Don't indent the function to be within the `with` block.
type: AnswerComment
comment on: http://stackoverflow.com/a/51453349
score: 0
type: Comment

http://stackoverflow.com/q/51406294
downvote count: 0
tagged with: string
favorite count: 0
tagged with: byte
has body: I made a program to open web pages using python 3.5 by using socket library. first, i prompt user to enter URL and then I split() that URL to extract host name for connect() method. But I am getting the following error which points towards my get request command: cmd ='GET ' + user_url + ' HTTP/1.0\n\n'.encode() TypeError: Can't convert 'bytes' object to str implicitly Following is my code: import socket user_url = input("Enter url: ") host_name = user_url.split("/")[2] mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) mysock.connect((host_name, 80)) cmd ='GET ' + user_url + ' HTTP/1.0\n\n'.encode() mysock.send(cmd) while True: data = mysock.recv(512) if (len(data) &lt; 1): break print (data.decode(),end='') mysock.close()
tagged with: sockets
tagged with: python
has answer: http://stackoverflow.com/a/51406350
type: UnansweredQuestion
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89783659
has title: Can't convert 'bytes' object to str implicitly python
type: Question
has comment: http://stackoverflow.com/comment/89783649
answer count: 1

http://stackoverflow.com/comment/89833950
has text: Gym is not officially supported on windows and a lot of workarounds are needed to get it to work even minimally. You will have to supply more information on what all you installed to get it working to what it is now for anyone to help you.
comment on: http://stackoverflow.com/q/51431428
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89727328
type: QuestionComment
has text: 90% of what? You should define your idea of similarity, and then you can program it. What have you tried so far?
score: 1
comment on: http://stackoverflow.com/q/51377806
type: Comment

http://stackoverflow.com/q/51350937
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89675110
tagged with: python
has comment: http://stackoverflow.com/comment/89674505
has comment: http://stackoverflow.com/comment/89675132
has comment: http://stackoverflow.com/comment/89675251
has comment: http://stackoverflow.com/comment/89675301
tagged with: list
has comment: http://stackoverflow.com/comment/89675458
has comment: http://stackoverflow.com/comment/89674470
has body: import csv list = [] list.append(['A', 'B', 'C', 'D']) list.append(['a', 'b', 'c', 'd']) def deletepublication(d): dp = input("Please input name of publication to be deleted") for i in d: if i[3] == dp: d.remove(i) break deletepublication(list) for i in list: print(i) This function is supposed to loop through each entry in a specific column in a 2D list, then delete the row in the list containing the input entered. But when I try it with a value I know is in there, nothing happens, it isn't deleted
has comment: http://stackoverflow.com/comment/89674696
has comment: http://stackoverflow.com/comment/89674385
type: Question
has comment: http://stackoverflow.com/comment/89674950
has title: Searching a list for a method to delete
has comment: http://stackoverflow.com/comment/89674516
has comment: http://stackoverflow.com/comment/89675260
has comment: http://stackoverflow.com/comment/89674633
score: 0
has comment: http://stackoverflow.com/comment/89675254

http://stackoverflow.com/a/51404709
has comment: http://stackoverflow.com/comment/89850359
has comment: http://stackoverflow.com/comment/89850282
has comment: http://stackoverflow.com/comment/89850562
score: 2
type: Answer
has comment: http://stackoverflow.com/comment/89849989
upvote count: 2
has body: dict's constructor accepts a sequence of (key, value) pairs, so you can achieve it with dict(zip(res_list, fina_list))
has comment: http://stackoverflow.com/comment/89850146
answers question: http://stackoverflow.com/q/51404621
downvote count: 0

http://stackoverflow.com/a/52586086
score: 0
answers question: http://stackoverflow.com/q/51424690
has body: Not sure if relevant to your case, but I was running into this same error message attempting to run the sample from the Azure custom vision service here. Issue was because I'd given the graph a name when importing it - but should have left it as an empty string here: tf.import_graph_def(graph_def, name='')
type: Answer

http://stackoverflow.com/a/51451855
accepted answer of: http://stackoverflow.com/q/51343421
score: 12
answers question: http://stackoverflow.com/q/51343421
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Since you opened a bounty, I can't vote to close as a duplicate, but this question would seem to provide a possible solution. Quoting from the accepted answer: You can use checkinstall to remove Python. The idea is: Install checkinstall Use checkinstall to make a deb of your Python installation Use dpkg -r to remove the deb. checkinstall basically wraps a make install command and creates a Debian .deb package based on what was installed. Then, you can just uninstall that package to reverse make install completely. To be perfectly safe you may want to uninstall the packaged Python 3.7 first and reinstall it afterwards to avoid any conflicts (I wouldn't expect any, though, since the packaged version lives in /usr while your source version lives in /usr/local). If you don't have your source files around anymore, you can always download them again (https://www.python.org/downloads/release/python-370b3/) and rebuild Python. Specifically, the checkinstall commands would look something like this: sudo apt install checkinstall wget https://www.python.org/ftp/python/3.7.0/Python-3.7.0b3.tgz tar xf Python-3.7.0b3.tgz cd Python-3.7.0b3 ./configure &amp;&amp; make sudo checkinstall -D --fstrans=no make install sudo dpkg -r Python-3.7.0b3.deb (-D creates a Debian package, --fstrans=no disables use of a temporary directory for installation).
has comment: http://stackoverflow.com/comment/89988549
has comment: http://stackoverflow.com/comment/89986869
has comment: http://stackoverflow.com/comment/101522722
upvote count: 12

http://stackoverflow.com/a/51403226
upvote count: 1
has comment: http://stackoverflow.com/comment/89785214
score: 1
accepted answer of: http://stackoverflow.com/q/51401886
has body: Its pretty simple, and as my edit dont have nothing to do with python or django. What you have to do it create one input checkbox at your template &lt;input type="checkbox" id="my_awesome_checkbox"&gt; Create one javascript function or just bind the code to event in that input &lt;input type="checkbox" id="my_awesome_checkbox" onchange="myCuteFunction"&gt; function myCuteFunction() { var checkBox = document.getElementById("my_awesome_checkbox") if (checkBox.checked == true){ let result = confirm("Hey! You really want to leave me here?"); if (result){ location.replace("the url you wan to go"); } } } EDIT: You want to changed the Checkbox value based on information from your backend? If is that you can use ajax to get the response you want from your endpoint and change your checkbox So using the previous code you can call the ajax to reach your backend instead of changing the page your url... and than change the value of your checkbox function myCuteFunction() { var checkBox = document.getElementById("my_awesome_checkbox") if (checkBox.checked == true){ let result = confirm("Hey! You really want to leave me here?"); if (result){ $.ajax({ url: "&lt;your endpoint&gt;", context: &lt;necessary paramenters&gt; }).done(function() { &lt;your response to add your logic to change the checkbox&gt; }); } } }
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51401886
downvote count: 0
has comment: http://stackoverflow.com/comment/89777963
type: Answer
has comment: http://stackoverflow.com/comment/89778088

http://stackoverflow.com/a/51422680
type: Answer
answers question: http://stackoverflow.com/q/51364326
score: 0
has body: I also faced this issue. Python3.6 unable to find Microsoft Visual C++ 14.0, because microsoft changed dll file name from "msvcr" to "vcruntime" Check below issue. https://bugs.python.org/issue32535 But you can installed Twisted using Wheel file, google it. Download wheel file of twisted and install it using pip.
has comment: http://stackoverflow.com/comment/90266145

http://stackoverflow.com/comment/89711076
type: QuestionComment
comment on: http://stackoverflow.com/q/51368696
type: Comment
has text: Using a pandas.multiIndex for the column names may be an option.
score: 0

http://stackoverflow.com/comment/89736121
has text: @MartijnPieters I guess it's not empty due to the previous filter `[line for line in chain_segment.split('\n') if line]`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51382045

http://stackoverflow.com/q/51438813
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51438975
accepted answer: http://stackoverflow.com/a/51438975
downvote count: 2
has body: My Data is like id name status 1 test True 2 prod True 3 Db False 1 test False 4 Staging True 3 Db False 2 prod True I want to group my data based on id and get the data ids which has status as True and also as False. Above data should return as: id name Status 1 Test True
type: Question
score: -1
tagged with: pandas
upvote count: 1
answer count: 1
has title: Get the ids where it has multiple values
has comment: http://stackoverflow.com/comment/89847853
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/89694760
has text: You should use the subprocess module, it allows you to pass on arguments.
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51361333

http://stackoverflow.com/a/51415379
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51415222
downvote count: 0
has body: Use datetime.now() to get the current time, save it, call datetime.now() again when you need to check the time and subtract it by the starting time to get a timedelta to check if it's less than 1 hour: from datetime import datetime, timedelta start = datetime.now() while datetime.now() - start &lt;= timedelta(hours=1): do_work()
accepted answer of: http://stackoverflow.com/q/51415222
type: AcceptedAnswer

pandas-to-sql
tags question: http://stackoverflow.com/q/51461223
type: Tag
tag name: pandas-to-sql

http://stackoverflow.com/a/51350255
score: 4
has body: It seems that the "element" you're talking about is actually the last segment of the string, delimited by a period (.). One way to perform the intended task is to first split the string by .'s, and then increment and re-concatenate from there. version1 = '1151.1' version2 = '4.1.1' version3 = '275.1.2.99' version4 = '369' def increment_last_element(version): return '.'.join(version.split('.')[:-1] + [str(int(version.split('.')[-1]) + 1)]) print(increment_last_element(version1)) # Output: 1151.2 Here's the breakdown: # Join the spliced str back together with periods '.'.join( # Split the str by periods; retain all previous values version.split('.')[:-1] + # Convert to str # (also have to convert the str into a list for list concatenation) [str( # Increment last element in the spliced string by 1 int(version.split('.')[-1]) + 1)])
type: Answer
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/51350232
accepted answer of: http://stackoverflow.com/q/51350232
type: AcceptedAnswer

http://stackoverflow.com/comment/89852112
has text: Also, where do `cs`, `sa` etc. come from, and why aren't you using the parameters passed to the functions but the variables from the outer scope? And why first `upper` and then check both cases anyway?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51440116

http://stackoverflow.com/comment/134649210
has text: Same problem here, but for me the solution was adding the following to the Dockerfile (using a distroless container): `COPY --from=build-env /usr/local/bin/dramatiq /usr/local/bin/dramatiq`
comment on: http://stackoverflow.com/a/55168094
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51343795
tagged with: apache-spark
upvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89660861
downvote count: 2
type: Question
has body: I want to join a dataframe "df_1" with "df_2" on a column named "TrackID". df_1: cluster TrackID 1 a_1 2 a_1 3 a_2 1 a_3 df_2: TrackID Value a_1 5 a_1 6 a_2 7 a_2 8 a_3 9 Output: cluster TrackID Value 1 a_1 Vector(5,6) 2 a_1 Vector(5,6) 3 a_2 Vector(7,8) 1 a_3 Vetor(9) I want the output of the join to look like this. is there a way I can do this?
tagged with: apache-spark-sql
has title: Pyspark Joining dataframes with multiple rows in the second dataframe
score: -2
has answer: http://stackoverflow.com/a/51343838
tagged with: pyspark
has answer: http://stackoverflow.com/a/51347246
answer count: 2

http://stackoverflow.com/comment/89928910
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51480189
has text: What's the dimension of your actual input vector?
type: Comment

http://stackoverflow.com/a/51466472
score: 0
type: Answer
has body: Problem - Always refer to the last button In show_saved_conditions() method, it is always using self.btns.text which is the last button added to the layout. self.label7 = Label(text = str(self.store[self.btns.text], size_hint = (.3,.3), pos_hint = {'x':.3,'y':.5}, color = (0,0,1,1))) Solution In the example, it demonstrates on_touch_down event. Touch event basic By default, touch events are dispatched to all currently displayed widgets. This means widgets receive the touch event whether it occurs within their physical area or not. In order to provide the maximum flexibility, Kivy dispatches the events to all the widgets and lets them decide how to react to them. If you only want to respond to touch events inside the widget, you simply check: def move(self, touch): if self.collide_point(*touch.pos): # The touch has occurred inside the widgets area. Do stuff! pass Example main.py from kivy.app import App from kivy.uix.gridlayout import GridLayout from kivy.uix.button import Button class CreateButton(Button): def on_touch_down(self, touch): if self.collide_point(*touch.pos): if touch.button == "right": print(self.id, "right mouse clicked") elif touch.button == "left": print(self.id, "left mouse clicked") else: print(self.id) return True return super(CreateButton, self).on_touch_down(touch) class OnTouchDownDemo(GridLayout): def __init__(self, **kwargs): super(OnTouchDownDemo, self).__init__(**kwargs) self.build_board() def build_board(self, *args): # make 9 buttons in a grid for i in range(0, 9): button = CreateButton(id=str(i), text=str(i)) self.add_widget(button) class OnTouchDownApp(App): def build(self): return OnTouchDownDemo() if __name__ == '__main__': OnTouchDownApp().run() ontouchdown.kv #:kivy 1.11.0 &lt;CreateButton&gt;: font_size: 50 &lt;OnTouchDownDemo&gt;: rows: 3 cols: 3 row_force_default: True row_default_height: 150 col_force_default: True col_default_width: 150 padding: [10] spacing: [10] Output
answers question: http://stackoverflow.com/q/51463615

http://stackoverflow.com/a/51386074
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51383405
has body: Constructing an indexing tuple from slices: In [88]: a = [1,0,4]; b = [4,1,None] In [89]: idx = [slice(i,j) for i,j in zip(a,b)] In [90]: idx Out[90]: [slice(1, 4, None), slice(0, 1, None), slice(4, None, None)] In [91]: arr = np.arange(5*3*7).reshape(5,3,7) In [92]: arr[tuple(idx)] Out[92]: array([[[25, 26, 27]], [[46, 47, 48]], [[67, 68, 69]]]) In [93]: _.shape Out[93]: (3, 1, 3)
accepted answer of: http://stackoverflow.com/q/51383405
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51327457
has answer: http://stackoverflow.com/a/68491808
answer count: 10
has answer: http://stackoverflow.com/a/63863283
has answer: http://stackoverflow.com/a/76747397
has comment: http://stackoverflow.com/comment/89631957
has title: Cannot import name 'views',.Python, Django
favorite count: 0
has answer: http://stackoverflow.com/a/51327513
tagged with: django
has answer: http://stackoverflow.com/a/71312069
tagged with: python
has answer: http://stackoverflow.com/a/70257606
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/73514504
has comment: http://stackoverflow.com/comment/89631820
type: Question
upvote count: 4
accepted answer: http://stackoverflow.com/a/51327513
has body: I have read many answers in this forum, but they does not solve my problem. I will be very grateful for help. My file views.py returns this error: from . import views ImportError: cannot import name 'views' from '__main__' (C:/Users/tymot/Desktop/weather app/env/Environemnt/the_weather/weather/views.py) views.py (Environemnt\the_weather\weather) from django.shortcuts import render from django.contrib import admin def index(request): return render(request, 'weather/index.html') #returns the index.html urls.py (Environemnt\the_weather\weather) from django.urls import path from . import views urlpatterns = [ path('', views.index), #the path for our index view ] urls.py (Environemnt\the_weather\the_weather) from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('weather.urls')), templates(the_weather\weather\templates\weather) only file index.html Directory -the_weather --the_weather ---__init__ ---setting ---urls ---wsgi --weather ---migrations ----__init__ ---templates ----weather -----index ---__init__ ---admin ---apps ---models ---tests ---urls ---views --db --manage.py I try use to resolved my problem from __future__ import absolute_import, or homepage import views. I else try copy views.py to directory templates (and modify its code) but unfortunately it not work
has comment: http://stackoverflow.com/comment/89630231
downvote count: 0
has answer: http://stackoverflow.com/a/51328581
score: 4
has answer: http://stackoverflow.com/a/61711643
has answer: http://stackoverflow.com/a/61134082
possible better answer: http://stackoverflow.com/a/68491808

http://stackoverflow.com/q/51363749
answer count: 1
has title: CSV Parse + Upload Django ( Error: can't concat bytes to InMemoryUploadedFile)
has comment: http://stackoverflow.com/comment/89700557
tagged with: django
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89700311
has answer: http://stackoverflow.com/a/51364272
accepted answer: http://stackoverflow.com/a/51364272
has body: I parse a CSV and when I try to save it, I get the error 'TypeError: can't concat bytes to InMemoryUploadedFile'. upload_obj = UploadField(csv=True) csv_upload = request.FILES.get('uploads', None) csv_parsed = csv.reader(codecs.iterdecode(csv_upload, 'utf-8'), delimiter=',') [parse loop then...] try: upload_obj.save(request=request, content_list=csv_upload) except Exception as e: print('Error:', e) I get the error when attempting to save.
type: Question
score: 0
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/comment/89876577
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51453349
score: 0
has text: @nonegiven72 I've edited to make the structure clear. You just need to fix exactly what fields you store in `lookup_dict` (like I said, I'm just storing the whole dictionary representing a row)

http://stackoverflow.com/comment/89729683
type: Comment
has text: @Datanovice - You are welcome! But if need the best performance I guess last solution should be fastest (depends of data)
comment on: http://stackoverflow.com/a/51378865
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89759330
type: Comment
comment on: http://stackoverflow.com/a/51379949
type: AnswerComment
has text: `filter_horizontal = ['user_permissions']` says `The value of 'filter_horizontal[0]' refers to 'user_permissions', which is not an attribute of 'accounts.Profile'.`. Using `myuser__user_permissions` does not solve it. user_permissions are defined in `myUser` superclass's superclass (`PermissionsMixin`)
score: 0

http://stackoverflow.com/a/51433019
upvote count: 2
answers question: http://stackoverflow.com/q/51432598
has body: Both, ax1 and ax2 are twin axes. Those have their label up. (This may be unexpected, and may be seen as a bug, indeed.) When working with several axes, it is cumbersome to use pyplot directly. Instead the object oriented approach is much better suited to make sure you set the properties of the object you want to be using. The idea is then to set the label position manually set_label_position to the bottom. import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([1,2,1,4,5],[1,2,3,4,5], marker='o', label='value 1') ax.plot([3,1,3,1,2],[1,2,3,4,5], label='value 2') ax.get_xaxis().set_visible(False) ax1 = ax.twiny() ax2 = ax1.twiny() ax2.xaxis.set_label_position('bottom') ax1.set_xlabel('TOP', labelpad=20) ax2.set_xlabel('BOTTOM', labelpad=20) plt.show() Also some labelpad needs to be set (again for no specific reason, other than probably noone every though about the implications of creating a twin axes from a twin axes).
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/89836933
has comment: http://stackoverflow.com/comment/89842255
has comment: http://stackoverflow.com/comment/89836841
downvote count: 0

http://stackoverflow.com/comment/89905020
has text: @user202729 Looks like I was not completely aware of what the `mod` operator does in Python. Thanks for the thorough answer!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51467186
type: Comment

http://stackoverflow.com/comment/89638322
type: AnswerComment
has text: You were right! I was putting 1.0 with an old habit and it takes only 1 . You saved my day. I want just to say a huge THANK YOU !
comment on: http://stackoverflow.com/a/51331136
type: Comment
score: 1

http://stackoverflow.com/a/51367103
has comment: http://stackoverflow.com/comment/89707430
accepted answer of: http://stackoverflow.com/q/51366819
answers question: http://stackoverflow.com/q/51366819
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
has body: First of all, you really don't need to give your URLs and views such long names. The name doesn't need to reflect the structure of the URL; and 11 elements is far too long. Anyway, the error should be clear: you are asking for a URL which takes a pk parameter, but you're not supplying that parameter. Presumably you want to go back to the view for the user that was originally requested, so you need to pass that parameter: return HttpResponseRedirect(reverse("estado...gerais", kwargs={'pk': pk})) which can be shortened to: return redirect("estado...gerais", pk=pk) But please, please, change those names.
score: 1

http://stackoverflow.com/a/51347911
upvote count: 1
score: 0
downvote count: 1
type: Answer
has body: You want to remove HTML tags? If yes just use:
answers question: http://stackoverflow.com/q/51347871

http://stackoverflow.com/comment/89868731
has text: @ThuanN. You can't select some of the channels and perform convolution on them only. Setting the kernel size to one, performs the convolution in each timestep but on all the channels of that timestep.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51346363
type: Comment

http://stackoverflow.com/q/51351911
favorite count: 0
has comment: http://stackoverflow.com/comment/89678234
accepted answer: http://stackoverflow.com/a/51352902
has comment: http://stackoverflow.com/comment/89679548
tagged with: python
type: AnsweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/89676415
type: Question
possible better answer: http://stackoverflow.com/a/51352220
has comment: http://stackoverflow.com/comment/89676408
score: -2
has answer: http://stackoverflow.com/a/51352220
has body: def calculate_average(runs,games): runs_list = [5, 7, 3, 1, 4] num_games = len(runs_list) total_runs=0 for runs in runs_list: total_runs += runs return total_runs/num_games print(calculate_average(runs, num_games)) This gives me an error saying"runs is not defined".I don't get it.Again I am a newbie.I knew it is a steep learning curve.
answer count: 2
has answer: http://stackoverflow.com/a/51352902
upvote count: 0
has title: <variable name> not defined

http://stackoverflow.com/q/51475126
has answer: http://stackoverflow.com/a/51475725
has body: I am working with large DataFrames containing columns with unique IDs but duplicate values. These columns are dropped through df.T.drop_duplicates().T, but I need to know which ones were equivalent. Example: import pandas as pd import numpy as np df = pd.DataFrame({'A': [1, 2, 3, 4, 5],'B': [2, 4, 2, 1, 9], 'C': [1, 2, 3, 4, 5],'D': [2, 4, 2, 1, 9], 'E': [3, 4, 2, 1, 2],'F': [1, 1, 1, 1, 1],'G': [1, 1, 1, 1, np.nan],'H': [1, 1, 1, 1, np.nan], 'I': [1, 2, 3, np.nan, 5]}, dtype=np.float64) print(df) A B C D E F G H I 0 1.0 2.0 1.0 2.0 3.0 1.0 1.0 1.0 1.0 1 2.0 4.0 2.0 4.0 4.0 1.0 1.0 1.0 2.0 2 3.0 2.0 3.0 2.0 2.0 1.0 1.0 1.0 3.0 3 4.0 1.0 4.0 1.0 1.0 1.0 1.0 1.0 NaN 4 5.0 9.0 5.0 9.0 2.0 1.0 NaN NaN 5.0 Several efficient solutions found here return nothing for columns containing np.nan: First Solution: def group_duplicate_rows(df): a = df.values sidx = np.lexsort(a.T) b = a[sidx] m = np.concatenate(([False], (b[1:] == b[:-1]).all(1), [False] )) idx = np.flatnonzero(m[1:] != m[:-1]) C = df.index[sidx].tolist() return [C[i:j] for i,j in zip(idx[::2],idx[1::2]+1)] In [19]: group_duplicate_cols(df) Out [19]: [['A', 'C'], ['B', 'D']] Second Solution: def view1D(a): # a is array a = np.ascontiguousarray(a) void_dt = np.dtype((np.void, a.dtype.itemsize * a.shape[1])) return a.view(void_dt).ravel() def group_duplicate_cols_v2(df): a = df.values sidx = view1D(a.T).argsort() b = a[:,sidx] m = np.concatenate(([False], (b[:,1:] == b[:,:-1]).all(0), [False] )) idx = np.flatnonzero(m[1:] != m[:-1]) C = df.columns[sidx].tolist() return [C[i:j] for i,j in zip(idx[::2],idx[1::2]+1)] In [20]: group_duplicate_cols_v2(df) Out [20]: [['B', 'D'], ['A', 'C']] Is there a way to adapt these functions to work with missing values?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51475725
tagged with: duplicates
type: Question
tagged with: dataframe
has title: Group duplicate column names in pandas DataFrame with missing values
has comment: http://stackoverflow.com/comment/89918775
score: 0
linked to: http://stackoverflow.com/q/44998223
tagged with: pandas
answer count: 1
tagged with: nan
tagged with: python

http://stackoverflow.com/a/51468614
has comment: http://stackoverflow.com/comment/89905702
has body: Several things off with your code. First, why use eval at all? letters = self.get(first) # will do just fine instead of letters = self.get(eval('first')) Second, the keys of your self dictionary (which is a really bad name for a random variable that is not the instance passed to a method) are strings. But ar contains integers which is why first is an int and self.get(first) returns None. Moreover, as pointed out by AndrejKesely: if not rec: # should probably be if not rest_of_no: And the recursive call with the same arguments will cause infinite recursion while return rec returns a function object which is probably not your intention. Lots of debugging still required ;)
has comment: http://stackoverflow.com/comment/89905810
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89905715
has comment: http://stackoverflow.com/comment/89905738
type: Answer
has comment: http://stackoverflow.com/comment/89905651
score: 2
answers question: http://stackoverflow.com/q/51468492
accepted answer of: http://stackoverflow.com/q/51468492

http://stackoverflow.com/q/51437890
has comment: http://stackoverflow.com/comment/89845880
type: UnansweredQuestion
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51437932
has body: So I have created a function which takes in input from the user and then displays the required output. The function is: def getname(name, place) Then the other code follows. In the end the user is asked name and place. The function searches the dataframe which I have imported and displays the result as the info of that name. I would like these outputs to be exported to a csv file. Not really sure of how to begin my code in this case. Thanks for the help!!
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89845837
tagged with: export-to-csv
downvote count: 4
has title: Save outputs from a function in a csv file in python
answer count: 1
favorite count: 0
tagged with: python-3.x
score: -3
tagged with: python

http://stackoverflow.com/q/51458881
possible better answer: http://stackoverflow.com/a/51458937
has answer: http://stackoverflow.com/a/51458937
has answer: http://stackoverflow.com/a/51459177
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/70366901
accepted answer: http://stackoverflow.com/a/51459177
has answer: http://stackoverflow.com/a/70066328
type: Question
has comment: http://stackoverflow.com/comment/89887130
tagged with: boolean
has answer: http://stackoverflow.com/a/78344600
tagged with: function
has answer: http://stackoverflow.com/a/70060709
answer count: 6
has body: In the exercise: "The squirrels in Palo Alto spend most of the day playing. In particular, they play if the temperature is between 60 and 90 (inclusive). Unless it is summer, then the upper limit is 100 instead of 90. Given an int temperature and a boolean is_summer, return True if the squirrels play and False otherwise." def squirrel_play(temp, is_summer): for temp in range(61,101) and is_summer = True: return True elif is_summer = False and temp &gt; 90: return False else: return True Or this one: def squirrel_play(temp, is_summer): if is_summer = True and temp is in range(61,101): #Changed return True elif is_summer = False and temp &gt; 90: return False else: return True I suspect it won't account for every kind of input given, specially because of the last 2 lines, but when I try to run this code, it gives me an error message on the second line. I don't know what it is and I haven't seen any solution for it.
has title: About a boolean function error
score: 0

http://stackoverflow.com/q/51387195
type: AnsweredQuestion
tagged with: list
duplicate of: http://stackoverflow.com/q/11458239
has title: How can I change an element in a list of lists
has comment: http://stackoverflow.com/comment/89747351
has comment: http://stackoverflow.com/comment/89746545
type: Question
tagged with: numpy
answer count: 2
accepted answer: http://stackoverflow.com/a/51387411
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/89746385
tagged with: tuples
tagged with: python
tagged with: structure
has comment: http://stackoverflow.com/comment/89746653
favorite count: 0
has body: I have the following structure: list_of_tuples = [['portugal', np.nan, 'japan'], [np.nan, 'germany', 'canada'], ['UK', 'US', np.nan]] I want to change the numpy nan values for MissingValue and turning back to a list of tuples: final_structure = [('portugal', 'MissingValue', 'japan'), ('MissingValue', 'germany', 'canada'), ('UK', 'US', 'MissingValue')] How can I replace the elements given a condition without iterating all over the elements? is there any single statement?
possible better answer: http://stackoverflow.com/a/51387516
has answer: http://stackoverflow.com/a/51387411
downvote count: 2
has answer: http://stackoverflow.com/a/51387516
linked to: http://stackoverflow.com/q/11458239

http://stackoverflow.com/q/51436452
tagged with: python
has title: How do I sample text from my LSTM model if the sequence length is greater than 1?
tagged with: recurrent-neural-network
has body: I am trying to sample text from my LSTM model, using model.predict(...). My model has a sequence length of 3. This is not a problem in the context of training, where I take the first sequence_length tokens to input into my model. However, in the context of sampling/generating text, I also require sequence_length tokens to predict the next token. I have made it so at the start of the generated tokens there is always a token indicating the start of a sentence. This would solve the problem if my model was a vanilla RNN rather than LSTM, since vanilla RNN predicts current token based only on the previous token, not previous tokens). In a vanilla RNN, by appending a start token to all inputs it can serve as the previous token on the first iteration. What I have researched/tried: The implementation of a vanilla RNN here is able to sample text, however due to the limitation above I mentioned in the previous can't apply its sampling method to LSTM. I have tried calling model.predict(...) with an input array less than sequence_length. Like I expected, model.predict(...) requires the input array length to be equivalent to sequence_length. How can I allow my model to sample data given less previous tokens than it requires at the beginning of my sampling, where there is not enough previous tokens to feed into the model?
type: Question
tagged with: neural-network
tagged with: lstm
score: 0
has comment: http://stackoverflow.com/comment/89846137
tagged with: keras
answer count: 0
has comment: http://stackoverflow.com/comment/89845887
type: UnansweredQuestion

http://stackoverflow.com/comment/89828253
has text: @ForceBru For large involved sets/lists, this should be a much more significant improvement. Where do you get that number from?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51428466
type: Comment

http://stackoverflow.com/q/51447534
has comment: http://stackoverflow.com/comment/89865766
has answer: http://stackoverflow.com/a/51447601
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/51447645
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89865449
score: -1
has title: Redo a function using else
has body: So i have created a function and inside i had put an if command, to check for the answer, but when the answer is invalid i want to repeat the function so it asks again. It is supposed to ask for either input A or B but when for eg i put C it should call back on the function and repeat. How do i make it re-ask for the input? This is what i tried: def function(): data = input("A/B") if data == "A": print("A") elif data == "B": print("B") else: function() #&lt;-----problem here
type: Question
linked to: http://stackoverflow.com/q/23294658
duplicate of: http://stackoverflow.com/q/23294658
has answer: http://stackoverflow.com/a/51447761
favorite count: 0
has answer: http://stackoverflow.com/a/51447629
accepted answer: http://stackoverflow.com/a/51447629
downvote count: 1
has comment: http://stackoverflow.com/comment/89865558
possible better answer: http://stackoverflow.com/a/51447601
has comment: http://stackoverflow.com/comment/89865411
tagged with: python-3.x
upvote count: 0

http://stackoverflow.com/q/51452089
answer count: 2
has answer: http://stackoverflow.com/a/51452167
tagged with: string
type: UnansweredQuestion
tagged with: python
tagged with: reformatting
has body: I have a line which is read from a text file as follows: line="('18-1', '29-1', '30-1', '42-1', '44-1')" I'd like to convert this into a set of strings as such: expected=['18-1', '29-1', '30-1', '42-1', '44-1'] Any ideas? I tried re.sub() to at least get rid of the brackets, to no avail.
has title: Reformatting a string from a text file into set of strings python
type: Question
has answer: http://stackoverflow.com/a/51452092
score: 0

http://stackoverflow.com/comment/89919206
comment on: http://stackoverflow.com/a/51464247
type: Comment
has text: @HaoWang I've edited my answer to adress this issue. However, I've just realised the second solution only works if your tasks are in time order, ie. if the task after has a higher delay - which makes it very impractical. I'll try and find something else.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89695375
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51351532
type: Comment
has text: Please respond.

http://stackoverflow.com/comment/89630408
score: 0
has text: Are you working with `spark` dataframes?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51324601

http://stackoverflow.com/comment/89678371
comment on: http://stackoverflow.com/q/51352905
type: QuestionComment
has text: i can, but the problem is the number of elements in a and b are in millions
score: 0
type: Comment

http://stackoverflow.com/comment/89767115
type: QuestionComment
has text: Hello @sachindubey value of `time.localtime(df1['d'])` gives `TypeError: cannot convert the series to <type 'float'>`
type: Comment
comment on: http://stackoverflow.com/q/51397961
score: 0

http://stackoverflow.com/q/51412369
has title: Extracting data from specific columns of numpy array for each row
upvote count: 1
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/37897748
has answer: http://stackoverflow.com/a/51412773
score: 1
has answer: http://stackoverflow.com/a/51412408
type: Question
possible better answer: http://stackoverflow.com/a/51412773
tagged with: numpy
answer count: 2
downvote count: 0
linked to: http://stackoverflow.com/q/37897748
favorite count: 0
has body: I am trying to obtain the value corresponding to column b[i] for each row i in A Can I do this without using the for loop? A = np.array([[35, 2, 23, 22], [44, 21, 15, 4], [44, 21, 15, 4], [37, 4, 17, 41], [33, 4, 4, 18], [35, 2, 23, 22]]) b = np.array([0,1,1,2,3,0]) C = zeros(len(b),1) for i in range(6): C[i] = A[i][b[i]]
accepted answer: http://stackoverflow.com/a/51412408
tagged with: python

http://stackoverflow.com/comment/89798323
score: 4
has text: Does the Matlab script generate a correct filter for you? Give an example with actual values for `fcuts`, `mags`, `devs` and `fsamp` in the Matlab script, and show the result `hh`. Then show how you translated those values to the Python script, and show `taps` to let us verify that the outputs are "vastly different". In other words, provide a [minimal, complete and verifiable example](https://stackoverflow.com/help/mcve). Then it will be much easier for someone to help you.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51412955

http://stackoverflow.com/comment/89901382
type: Comment
type: QuestionComment
has text: You have actually fallen for the [gambler's fallacy](https://en.wikipedia.org/wiki/Gambler%27s_fallacy)
score: 0
comment on: http://stackoverflow.com/q/51466445

porter-stemmer
tags question: http://stackoverflow.com/q/51330099
type: Tag
tag name: porter-stemmer

http://stackoverflow.com/q/51453603
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
favorite count: 0
tagged with: python-3.x
has body: I am calling in my script, pytest.main(); although I get no print out unless the test fail. I know that pytest has a -s flag that solve the problem, and in fact if I call my test from console using python3 -m pytest -s mytest.py Works just fine and I get the print statements printed correctly even if the test pass; but I can't find how do you obtain the same outcome while calling pytest.main() from a python script.
has title: Equivalent of `-s` when calling pytest with pytest.main()
has answer: http://stackoverflow.com/a/51453652
accepted answer: http://stackoverflow.com/a/51453652
type: AnsweredQuestion
tagged with: testing
tagged with: pytest
score: 1
type: Question

http://stackoverflow.com/comment/89912709
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51471550
type: Comment
has text: That would be correct if I was trying to access the value returned by db.stores.find({}). The problem here is making this query in pyDAL format: db.stores.find({ 'menu.items.food.category': 'Pizza' })

http://stackoverflow.com/comment/89771023
comment on: http://stackoverflow.com/a/51400114
type: AnswerComment
score: 0
type: Comment
has text: Thanks a lot for your code. I have executed the code. It is giving two different figures each consisting a plot. But, I want one figure to have two plots. Help me.

http://stackoverflow.com/q/51393912
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/51394900
type: AnsweredQuestion
has body: I'm trying to create vbar graph like from bokeh documentation on graph :mean MPG by #cylinders and manufacturer (https://docs.bokeh.org/en/latest/docs/user_guide/categorical.html#userguide-categorical), but keep getting error (BAD_COLUMN_NAME): Glyph refers to nonexistent column name: value". Here is my csv file: id,name,value,vendorname 1, contract abc, "2,000,500.00", company x 2, contract bcd, "1,300,500.00", company y 3, contract cde, "1,344,000.00", company x 4, contract def, "400,000.00", company z 5, contract efg, "566,000.00", company s and so on.... here is the code: from bokeh.io import show, output_file from bokeh.palettes import Viridis256 from bokeh.transform import factor_cmap import pandas as pd from bokeh.core.properties import value from bokeh.models import FactorRange, ColumnDataSource from bokeh.palettes import Spectral5 from bokeh.plotting import figure, show from bokeh.embed import components df = pd.read_csv('contract.csv') group = df.groupby(['vendorname', 'name']) index_cmap = factor_cmap('vendorname_name', palette=Viridis256, factors=sorted(df.vendorname.unique()), end=1) p = figure(plot_width=1000, plot_height=1500, title="Value Contract by # Contract and Vendor", x_range=group, toolbar_location=None, tooltips=[("Value", "@value"), ("vendorname, name", "@vendorname_name")]) p.vbar(x='vendorname_name', top='value', width=1, source=group, line_color="white", fill_color=index_cmap, ) p.y_range.start = 0 p.x_range.range_padding = 0.05 p.xgrid.grid_line_color = None p.xaxis.axis_label = "Contract grouped by # Vendor" p.xaxis.major_label_orientation = 1.2 p.outline_line_color = None output_file("contract.html") show(p)
score: 1
upvote count: 1
type: Question
tagged with: group-by
tagged with: bokeh
has title: create bokeh vbar but error " (BAD_COLUMN_NAME): Glyph refers to nonexistent column name: value"
has answer: http://stackoverflow.com/a/51394900
linked to: http://stackoverflow.com/q/22137723

http://stackoverflow.com/comment/89647144
comment on: http://stackoverflow.com/q/51335930
score: 0
has text: 'it removes duplicate address (if they have same date and IP)' am I wrong or all the sample data has same IP and date?
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51350139
upvote count: 1
type: AcceptedAnswer
has body: urlopen produces an HttpResponse object, not a json string. You need to call its read method to get the json. Change pd.io.json.json_normalize(urlopen('https://api.coinmarketcap.com/v2/ticker/?limit=10')) to pd.io.json.json_normalize(urlopen('https://api.coinmarketcap.com/v2/ticker/?limit=10').read()) Update json_normalize expects deserialised json, so you need to load the json before passing it to json_normalize resp = urlopen('https://api.coinmarketcap.com/v2/ticker/?limit=10') data = json.load(resp) pd.io.json.json_normalize(data)
has comment: http://stackoverflow.com/comment/89673026
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51350121
answers question: http://stackoverflow.com/q/51350121

http://stackoverflow.com/comment/89792044
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51409300
has text: How about `list(Movies[3].values())[0][1]` ?

http://stackoverflow.com/comment/89767134
type: Comment
has text: It depends on the delta which is learning_rate * gradient. Try to print delta value in every iteration. And check the learning_rate is big or small. The learning_rate should be not too big nor too small. Both cases can't be converged. And the iteration count is also important. Try it.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51392949

http://stackoverflow.com/q/51424728
tagged with: python
downvote count: 0
tagged with: cyrillic
type: Question
has title: Once again, UnicodeEncodeError (ascii codec can't encode)
accepted answer: http://stackoverflow.com/a/51425082
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51425082
answer count: 1
has comment: http://stackoverflow.com/comment/89820534
tagged with: unicode
linked to: http://stackoverflow.com/q/43356982
favorite count: 0
has body: I'm running python 3.6 + gunicorn + django 2.0.5 in docker container with some cyrillic project and that's what I see when I try to log cyrillic strings in console with Django. 'ascii' codec can't encode character '\u0410' in position 0: ordinal not in range(128) Also this what happens in shell Python 3.6.5 (default, May 3 2018, 10:08:28) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) &gt;&gt;&gt; :�ириллица The same time, when i'm running python 3.5 outside docker container, everything is ok: Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; Кириллица Any ideas how to make python 3.6 inside docker work ok with cyrillic strings?
upvote count: 3
tagged with: django

http://stackoverflow.com/comment/89789929
has text: Update: Simpy solved it finally after running more than an hour.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51407938
score: 0

http://stackoverflow.com/a/51411420
score: 2
has comment: http://stackoverflow.com/comment/89795656
has body: You should have a look at the following packages: salem and the region of interest example regionmask Both may get you to what you want.
downvote count: 2
answers question: http://stackoverflow.com/q/51398563
upvote count: 4
type: Answer

http://stackoverflow.com/comment/89860166
comment on: http://stackoverflow.com/q/51433214
score: 0
type: Comment
type: QuestionComment
has text: Thanks for the answer. You say only about running the destructor. But it is also about freeing memory, isn't it?

http://stackoverflow.com/comment/89870560
type: QuestionComment
comment on: http://stackoverflow.com/q/51449912
has text: Again, `PyQt4` does not exist. Try `pip install pygame`
score: 0
type: Comment

http://stackoverflow.com/q/51369763
has comment: http://stackoverflow.com/comment/89712080
upvote count: 1
has comment: http://stackoverflow.com/comment/89712218
has title: How to efficiently read specific lines of a CSV?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89712196
score: 1
has comment: http://stackoverflow.com/comment/89712209
has comment: http://stackoverflow.com/comment/89711990
accepted answer: http://stackoverflow.com/a/51383869
type: Question
has body: I am working on training a Keras neural network model on a training set with ~5,000,000 rows. I'm reading in only a few lines of this file at once for training using code similar to the following: n_lines = 5000000 skiprows = np.delete(np.arange(1, n_lines), np.arange(first_line, first_line+batch_size)) X = pd.read_csv('training.csv', skiprows=skiprows) Some transformations are performed on X and it is then passed to the model using model.train_on_batch(X, y). I think this is currently the bottleneck in my training procedure so I want to know if there is a more efficient way to accomplish this. I timed it to check the difference (training_data.csv has 50,000 lines): pd.read_csv('training_data.csv') # 0.86 seconds n_batches = 1000 for i in range(n_batches): skiprows = np.delete(np.arange(1, 50000), np.arange(i*50, (1+i)*50)) pd.read_csv('training_data.csv', skiprows=skiprows) # 152.23 seconds to iterate through all 1000 batches
has comment: http://stackoverflow.com/comment/89712058
downvote count: 0
has comment: http://stackoverflow.com/comment/89711921
tagged with: keras
has comment: http://stackoverflow.com/comment/89711868
has comment: http://stackoverflow.com/comment/89712365
tagged with: pandas
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51383869
favorite count: 0
has comment: http://stackoverflow.com/comment/89712172
has comment: http://stackoverflow.com/comment/89711961

http://stackoverflow.com/q/51385880
upvote count: 1
tagged with: python
tagged with: plot
score: 1
type: Question
has answer: http://stackoverflow.com/a/51386034
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89747154
has comment: http://stackoverflow.com/comment/89743873
has body: How can i convert a dataframe into series of Pandas series. My dataframe below and i want it to plot with stacked bar chart. city soru_id value1 value2 value3 value4 value5 0 1 2 147 119 69 92 106 1 2 2 31 20 12 14 26 2 3 2 37 22 24 18 19 3 4 2 10 13 7 13 10 4 5 2 38 48 18 30 27 5 6 2 401 409 168 354 338 .. ... ... ... ... ... ... ... 76 77 2 12 7 3 12 8 77 78 2 4 2 1 12 3 78 79 2 3 None 1 None None 79 80 2 12 7 4 4 7 80 81 2 18 13 7 10 2 [81 rows x 7 columns] Therefore i need to get the dataframe into form like below to plot it. I can not loop into DataFrame() method. How can i plot it. df = pd.DataFrame([pd.Series([value1,value2,value3,value4,value5]), pd.Series([value1,value2,value3,value4,value5]), pd.Series([value1,value2,value3,value4,value5]), .................................. .................................. pd.Series([value1,value2,value3,value4,value5]), pd.Series([value1,value2,value3,value4,value5]) ], index=[index0,index2,index3,....,index79,index80]) df.plot.bar(stacked=True) plt.show()
tagged with: pandas
has comment: http://stackoverflow.com/comment/89743760
has title: Converting a Dataframe into Series of Pandas Series
type: UnansweredQuestion

http://stackoverflow.com/q/51354097
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/2905965
linked to: http://stackoverflow.com/q/6893968
has body: I have a image list. How to use multi thread to process each image. import cv2 def job(a_img, b_img): # want to use multi thread # do something images = ['1.png', '2.png', '3.png', ..., '100.png'] # images list out = [] for i in range(len(images) - 1): # read image img_1 = cv2.imread(images[i]) img_2 = cv2.imread(images[i + 1]) res = job(img_1, img_2) out.append(res) Every two image is processed individually. How to solve?
has answer: http://stackoverflow.com/a/51354237
type: Question
has comment: http://stackoverflow.com/comment/89681242
score: 0
answer count: 1
has title: How to use multi thread to process each image

http://stackoverflow.com/a/51327564
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51327498
has comment: http://stackoverflow.com/comment/89630432
answers question: http://stackoverflow.com/q/51327498
type: Answer
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/89631514
has comment: http://stackoverflow.com/comment/89632476
has body: I get a bit different output: df['DATE'] = pd.to_datetime(df['DATE']) df['GAP'] = df.groupby('VENDOR ID')['DATE'].diff().dt.days print (df) VENDOR ID DATE GAP 1 33 2018-01-12 NaN 2 33 2018-03-12 59.0 3 12 2018-01-08 NaN 4 12 2018-01-15 7.0 5 12 2018-01-23 8.0 6 33 2018-05-12 61.0 7 89 2018-01-12 NaN Explanation: Convert column to_datetime Then groupby with diff Last convert timedeltass to days

http://stackoverflow.com/q/51394079
has comment: http://stackoverflow.com/comment/89760355
type: Question
accepted answer: http://stackoverflow.com/a/51394607
has comment: http://stackoverflow.com/comment/89759654
answer count: 3
has answer: http://stackoverflow.com/a/51394562
downvote count: 0
has answer: http://stackoverflow.com/a/51395551
favorite count: 0
tagged with: python-3.x
tagged with: pycharm
possible better answer: http://stackoverflow.com/a/51394562
upvote count: 2
tagged with: python
type: AnsweredQuestion
score: 2
has body: I've cloned https://github.com/sarathknv/adversarial-pytorch. The file one_pixel.py finds all imports but If I add adversarial-pytorch as a sub directory to an existing project - myproject -> other -> adversarial-pytorch I receive error : from model import BasicCNN causes error : Unresolved reference BasicCNN I've tried modifying the import line to : from myproject.other.model import BasicCNN but this does not fix issue. How to import python files that exist as a sub-project ?
has answer: http://stackoverflow.com/a/51394607
has title: Import not found when added as sub directory

http://stackoverflow.com/q/51364486
tagged with: pandas-profiling
tagged with: python
tagged with: pycharm
type: UnansweredQuestion
has body: Showing this error while executing Pandas Profiling on pycharm or windows terminal Pycharm latest Python version 3.6 Windows 7 Pandas profiling 1.4 pandas_profiling.ProfileReport(df) : RuntimeError: An attempt has been made to start a new process before the current process has finished its bootstrapping phase. This probably means that you are not using fork to start your child processes and you have forgotten to use the proper idiom in the main module: if __name__ == '__main__': freeze_support() ... The "freeze_support()" line can be omitted if the program is not going to be frozen to produce an executable.
type: Question
has answer: http://stackoverflow.com/a/51397521
tagged with: profiling
answer count: 1
has title: Pandas Profiling 1.4 issue with Pycharm and windows 7 terminal
score: 0
tagged with: pandas

http://stackoverflow.com/q/51381375
has answer: http://stackoverflow.com/a/51385430
has comment: http://stackoverflow.com/comment/89734865
upvote count: 7
has body: I'm sanitizing a pandas dataframe and encounters unicode string that has a u inside it with a backslash than I need to replace e.g. u'\u2014'.replace('\u','') Result: u'\u2014' I've tried encoding it as utf-8 then decoding it but that didn't work and I feel there must be an easier way around this. pandas code merged['Rank World Bank'] = merged['Rank World Bank'].astype(str) Error UnicodeEncodeError: 'ascii' codec can't encode character u'\u2014' in position 0: ordinal not in range(128)
type: AnsweredQuestion
downvote count: 3
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/51381433
has comment: http://stackoverflow.com/comment/89735099
has comment: http://stackoverflow.com/comment/89735101
has title: python unicode replace backslash u with an empty string
score: 4
has comment: http://stackoverflow.com/comment/89735233
favorite count: 0
has comment: http://stackoverflow.com/comment/89735376
has comment: http://stackoverflow.com/comment/89735553
has comment: http://stackoverflow.com/comment/89734553
tagged with: python
possible better answer: http://stackoverflow.com/a/51385430
has answer: http://stackoverflow.com/a/51381433
has comment: http://stackoverflow.com/comment/89735541

http://stackoverflow.com/comment/89895078
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51428725
type: Comment
has text: Thanks. 1) I think I explained well what I mean by "smooth" curve 2) Using dimension+1 points does not produce a curve but a polygon. And it's not what I am talking about. 3) Thanks for your ref. However, it's too scientific for me.

http://stackoverflow.com/q/51442558
accepted answer: http://stackoverflow.com/a/51442829
has comment: http://stackoverflow.com/comment/89854976
type: Question
tagged with: mongodb
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/89855279
has title: Insert document in MongoDB using pymongo
tagged with: python
has comment: http://stackoverflow.com/comment/89855018
has body: I'm using Python for the first time to run a crawler. I've got the crawler to work and now I want to save the results in my MongoDB using pymongo,but for some reason I get this error: "NameError: name 'city' is not defined". If I wrap city in quotes,it works as expected,but I want to save it as it is. Anyone has done something similar or know what the solution is? def gotHolidays(self, response): cityName = response.meta['name'] feriado = [] facult = [] for selector in response.css("span.one"): feriado.append(selector.css("::text").extract()) for selector in response.css("span.two"): facult.append(selector.css("::text").extract()) city = { 'city': cityName, 'holidays':{ 'facult': facult, 'feriado': feriado } } print(json.dumps(city)) from pymongo import MongoClient client = MongoClient() client = MongoClient ('localhost', 27017) db = client['myBank'] myCollection = db.myCollection myCollection_data = { 'cities': city } result = myCollection.insert_one (myCollection_data)
has answer: http://stackoverflow.com/a/51442829
type: AnsweredQuestion

http://stackoverflow.com/a/51415130
score: 0
answers question: http://stackoverflow.com/q/51414103
type: Answer
has comment: http://stackoverflow.com/comment/89801619
has body: #import pandas import pandas as pd #read file1.csv #set index_col as false if file has delimiters at the end file1 = pd.read_csv( 'file1.csv', ' ', index_col = False, names = ['1','2','3','4','5','6']); #read file2.txt, read_csv can read txt files as well #set index_col as false if file has delimiters at the end file2 = pd.read_csv( 'file2.csv', ' ', index_col = False, names = ['1','2','3','4','5']); #drop first column file2.drop( '1', axis = 1, inplace = True ) #concat both frames final = pd.concat([file1, file2], axis = 1) #you might end up with mixed column names you can change it by using final.columns = ['col1', 'col2', ....] #save as csv final.to_csv('out.csv',sep='\t')

http://stackoverflow.com/comment/89670261
has text: you _can_ edit/view it in notepad but that's not the built-in file association like .txt. The .dat file isn't made to be readable, as opposed to json format.
type: Comment
comment on: http://stackoverflow.com/a/51340887
type: AnswerComment
score: 0

http://stackoverflow.com/q/51376286
score: 4
has answer: http://stackoverflow.com/a/51376337
answer count: 1
has body: How can I get current working directory of FTP using python? I have the following code and wanted to store file names into the list in the root directory. from ftplib import FTP ftp = FTP('domainname.com') ftp.login(user='username',passwd = 'password')
upvote count: 4
accepted answer: http://stackoverflow.com/a/51376337
type: AnsweredQuestion
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: Question
has title: How do I get FTP's current working directory using python
tagged with: python

http://stackoverflow.com/comment/89777255
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51403126
has text: It's `import aux`, not `import aux.py`. The directory containing your code *is* implicitly added to the search path, even if your *working* directory is not.

http://stackoverflow.com/a/51409718
score: 4
has body: Use named.values(): import collections import operator Named = collections.namedtuple('Named', ['A', 'B']) named = {'id1': Named(9, 5), 'id2': Named(5, 4), 'id3': Named(7, 3)} print(min(named.values(), key=operator.attrgetter('B'))) Prints: Named(A=7, B=3)
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/51409668
downvote count: 0

http://stackoverflow.com/comment/89780710
type: QuestionComment
has text: isin would be enough
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51404817

http://stackoverflow.com/comment/89734507
score: 0
type: AnswerComment
type: Comment
has text: Ok, so if I have 1200 images (and 1200 floats of course), 200 for each class, then the input would be (1200, 256,256,3) and (1200,1). The Output, or "classes" would be (200,6)? --Yes, marked as solved! Thanks again.
comment on: http://stackoverflow.com/a/51366474

http://stackoverflow.com/comment/89727492
has text: `node.attrib` gives you a dictionary of the node's attributes. You want the node#s textual contents. Try `print(name.text)` instead.
score: 2
comment on: http://stackoverflow.com/q/51377908
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51428129
type: UnansweredQuestion
tagged with: python
has body: So I have a dataframe with numbers (float32) stored in them, whos index's are A1, A2, A3, B1, B2, B3, where A's are the values and B's are the errors associated with that value, I am trying to run it through a loop to plot A1 with A2 (and their errors) and A1 with A3 (again with errors), however partway through the loop I am getting a KeyError: 0. The plotting is done with a function call in a loop, the loop works fine (removing the errorbars commands makes it run, but of course without the plotted errors), it also does several plots before it gets to one that breaks it. This is done in python. Here is the function (with dataframe already loaded in and I can find values in it): fig = plt.figure('hello') ax = fig.add_subplot(111) plt.ylim(-2, 1.5) plt.xlim(-2, 1.5) plt.xlabel('A1') plt.ylabel('A2 (green) A3 (blue)') ax.scatter(df[A1], df[A2], c='g') plt.errorbar(df[A1], df[A2], fmt='g', xerr=df[B1], yerr=df[B2]) ax.scatter(df[A1], df[A3], c='b') plt.errorbar(df[A1], dat[A3], fmt='b', xerr=df[B1], yerr=df[B3]) plt.savefig('figure' +str(df[i])) ax.clear()
answer count: 0
tagged with: matplotlib
type: Question
has comment: http://stackoverflow.com/comment/89829062
has comment: http://stackoverflow.com/comment/89827630
score: 0
tagged with: pandas
has title: Key Error 0 while plotting in a loop

http://stackoverflow.com/comment/89799119
score: 0
comment on: http://stackoverflow.com/q/51413822
type: QuestionComment
type: Comment
has text: Correct, I just want the line to come through, to match the line to come through as well (to match the summary() results)

http://stackoverflow.com/a/51401932
score: 1
answers question: http://stackoverflow.com/q/51399594
accepted answer of: http://stackoverflow.com/q/51399594
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: This cannot be done via Selenium. One quick way to do this would be to use win32 api to simulate a click on the coordinates of your extension button on your screen. First of all find the coordinate of the extension button on your screen. You can use tool like this. I, myself found a rough idea of the location by comparing to the coordinate of my DOM immediately below the button through this chrome extension. Then, use below code to simulate a click on that location: from selenium import webdriver from selenium.webdriver.chrome.options import Options import win32api, win32con chrome_options = Options() chrome_options.add_extension('//path to crx') driver = webdriver.Chrome(chrome_options=chrome_options, executable_path='path to chromedriver') driver.maximize_window() click(1317,51) # the coordinates of the button on my 1366 x 768 screen after maximizing. def click(x,y): win32api.SetCursorPos((x,y)) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0) Additionally you can check out Sikuli. It uses image recognition to identify and perform actions on any desired element on the screen. You first have to take the screenshot of your button and then perform a click function on it inside your sikuli script. After that, you can trigger your sikuli script from python by following suggestions from here.
downvote count: 0

http://stackoverflow.com/comment/89775967
type: Comment
comment on: http://stackoverflow.com/q/51402593
type: QuestionComment
score: 0
has text: Post your code showing what you have done

http://stackoverflow.com/comment/89721718
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51363364
has text: why "Anything going over a wire must be a sequence of bytes"? I'd like a further explanation , I don't know much about computer networks
type: AnswerComment

http://stackoverflow.com/comment/89810390
score: 1
has text: Note that absolute target paths won't work with `pip` anyway because all absolute `data_files` targets will be relativized to `site-packages`, see my answer [here](https://stackoverflow.com/a/47465374/2650249) for more details. For bundling resource files, I'd rather use `package_data` and place the files under some package dir. You can then reference the files with `pkg_resources.resource_file()` etc. in a cross-platform manner.
comment on: http://stackoverflow.com/q/51419256
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89837746
comment on: http://stackoverflow.com/q/51433272
score: 0
type: Comment
has text: @juanpa.arrivillaga regex can be aplied line by line. For performance reasons I said re.MULTILINE
type: QuestionComment

http://stackoverflow.com/q/51361333
type: Question
accepted answer: http://stackoverflow.com/a/51361391
downvote count: 0
has comment: http://stackoverflow.com/comment/89694760
has answer: http://stackoverflow.com/a/51361391
answer count: 1
tagged with: arguments
has title: Calling a python script from another python script with arguments does not work
favorite count: 0
has body: I am well aware that there are multiple threads dealing with this problem because I used them in an attempt to self-teach me how to do it. However, for me it does not work and I wondered if someone could help me find my error. So I got one program (let's call it prog1) that calls a script for every string-variable like this: os.system(r'C:\Users\user\docs\bla\script.py %s'%variable) In script.py I now just wanted to test if this call worked by disabling all code but just doing: def main(string): print(string) root if __name__ == "__main__": print('I got executed') main(sys.argv[1]) The Problem is, if I execute prog1 nothing happens. No errer - so it runs through and the console pops up for a Brief second. However, nothing happens - no string is printed. If I execute script.py directly it works though. EDIT: I got it to execute without error with the subprocess package by using: subprocess.call(r'C:\...\script.py' %s' %variable,shell = True) However, the problem stays the same - nothing happens. Or well, I noticed now that in the Background a Windows window pops up asking me with which program I want to execute files with the ending '.py' but this is not helping me, because I want to execute in console :(
tagged with: python
type: AnsweredQuestion
tagged with: call
score: 1
upvote count: 1

http://stackoverflow.com/a/51387524
has body: It may not be the most space-efficient, but one way to do this is to create a new array and place your existing array in the center of that. &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.random.seed(444) &gt;&gt;&gt; arr = np.zeros((4, 5)) # your image array &gt;&gt;&gt; newsize = tuple(i + 2 for i in arr.shape) &gt;&gt;&gt; new = np.random.randint(low=0, high=50, size=newsize) &gt;&gt;&gt; new[1:-1, 1:-1] = arr &gt;&gt;&gt; new array([[ 3, 48, 23, 8, 3, 39, 12], [47, 0, 0, 0, 0, 0, 15], [34, 0, 0, 0, 0, 0, 0], [ 6, 0, 0, 0, 0, 0, 6], [39, 0, 0, 0, 0, 0, 13], [ 2, 15, 9, 34, 9, 24, 25]]) This is assuming your image is grayscale (2d) rather than a 3-dimensional MxNx4 RGBA array. In that case, you'd want new[1:-1, 1:-1, 1:-1]. You can also do this by passing a callable to np.pad(), but there is a caveat (see below): from functools import partial def _pad_random(vector, pad_width, iaxis, kwargs, low, high): a, b = np.random.randint(low, high, size=2) vector[:pad_width[0]] = a vector[-pad_width[1]:] = b return vector pad_random = partial(_pad_random, low=0, high=50) Usage: &gt;&gt;&gt; np.pad(arr, 1, pad_random) array([[23., 19., 6., 47., 17., 7., 26.], [26., 0., 0., 0., 0., 0., 37.], [39., 0., 0., 0., 0., 0., 39.], [39., 0., 0., 0., 0., 0., 42.], [28., 0., 0., 0., 0., 0., 47.], [11., 32., 37., 2., 38., 30., 44.]]) Caveat: it looks like, when you pass a function to the mode parameter of np.pad(), this function is called multiple times. Here's an example straight from the docs with a few print calls sprinkled in: &gt;&gt;&gt; def pad_with(vector, pad_width, iaxis, kwargs): ... pad_value = kwargs.get('padder', 10) ... print(vector[:pad_width[0]]) ... print(vector[-pad_width[1]:]) ... vector[:pad_width[0]] = pad_value ... vector[-pad_width[1]:] = pad_value ... return vector ... &gt;&gt;&gt; arr = np.arange(6).reshape(3, 2) &gt;&gt;&gt; np.pad(arr, 1, pad_with) [0] [0] [0] [0] [0] [0] [0] [0] [10] [10] [0] [0] [0] [0] [0] [0] [10] [10] array([[10, 10, 10, 10], [10, 0, 1, …
type: Answer
answers question: http://stackoverflow.com/q/51387361
score: 1
upvote count: 1
downvote count: 0

http://stackoverflow.com/q/51343394
tagged with: openapi-generator
tagged with: django
tagged with: python
has title: Does Django Rest Framework have third party apps to auto generate swagger.yaml file?
tagged with: swagger
type: Question
answer count: 1
downvote count: 0
tagged with: django-rest-framework
favorite count: 0
has answer: http://stackoverflow.com/a/51727126
score: 2
has body: I have large amount of API endpoints written in django-rest-framework and it keeps increasing and updating. How can I create &amp; maintain API documentation that should be up-to-date? My current version is Create swagger.yaml file and somehow auto generate everytime any endpoint changes. Then use this file as an input to readme.io, ReDoc or other alternatives to provide visualization to external folks. If you have an experience on this or any similar solution, please share I really appreciate it!
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/q/51375587
score: 0
answer count: 3
tagged with: tensorflow
has answer: http://stackoverflow.com/a/51377804
has comment: http://stackoverflow.com/comment/89724628
has answer: http://stackoverflow.com/a/51384855
possible better answer: http://stackoverflow.com/a/51376004
has answer: http://stackoverflow.com/a/51376004
type: AnsweredQuestion
has body: I train a CNN to detect the presence of hazard ids (example) on images. I get a 99% accuracy in training. Then I try to predict on pictures from the training set and it fails to give the correct estimation. Can you please tell me how this is possible? Code taken from Google's cats and dogs example (https://developers.google.com/machine-learning/practica/image-classification/exercise-1): #!/usr/bin/env python3 import matplotlib.pyplot as plt from tensorflow.keras import layers from tensorflow.keras import Model from tensorflow.keras.optimizers import RMSprop from tensorflow.keras.preprocessing.image import ImageDataGenerator import numpy as np import os import cv2 def predict(frame): frame = cv2.resize(frame, (150, 150)) frame = np.expand_dims(frame, axis=0) frame = np.asarray(frame, dtype='int32') frame = frame / 255 return model.predict(frame) base_dir = './cats_and_dogs_filtered' train_dir = os.path.join(base_dir, 'train') validation_dir = os.path.join(base_dir, 'validation') train_cats_dir = os.path.join(train_dir, 'cats') train_dogs_dir = os.path.join(train_dir, 'dogs') validation_cats_dir = os.path.join(validation_dir, 'cats') validation_dogs_dir = os.path.join(validation_dir, 'dogs') train_cat_fnames = os.listdir(train_cats_dir) print(train_cat_fnames[:10]) train_dog_fnames = os.listdir(train_dogs_dir) train_dog_fnames.sort() print(train_dog_fnames[:10]) img_input = layers.Input(shape=(150, 150, 3)) x = layers.Conv2D(16, 3, activation='relu')(img_input) x = layers.MaxPooling2D(2)(x) x = layers.Conv2D(32, 3, activation='relu')(x) x = layers.MaxPooling2D(2)(x) x = layers.Conv2D(64, 3, activation='relu')(x) x = layers.MaxPooling2D(2)(x) x = layers.Flatten()(x) x = layers.Dense(512, activation='relu')(x) output = layers.Dense(1, activation='sigmoid')(x) model = Model(img_input, output) model.compile(loss='binary_crossentropy', optimizer=RMSprop(lr=0.001), metrics=['acc']) train_datagen = ImageDataGenerator(rescale=1./255) test_datagen = ImageDataGenerator(rescale=…
tagged with: keras
has title: Why does training succeed and predict fail with keras and tensorflow?
accepted answer: http://stackoverflow.com/a/51384855
type: Question
tagged with: python

http://stackoverflow.com/comment/89688179
comment on: http://stackoverflow.com/a/51354974
type: Comment
score: 0
has text: This code does not work. I realize that python indexing starts at 0. I also originally wrote this code but this code brings up an error saying "NoneType" object has no attribute a. It is clearly grabbing something that has no anchor tag, so I would have to leave out one of the 50 elements but I am not sure how. I believe there are 49 members out of a possible 50 so I need the 49 members and then for it to fill in one empty spot with just an empty string.
type: AnswerComment

http://stackoverflow.com/comment/89793803
has text: Well, I am completely fine with your approach, yet they do share the same syntax construct.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51410974
type: Comment

http://stackoverflow.com/a/51655464
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: I'm answering my own question since I figured out the fix. If anyone else is having the same problem, you have to export all the symbols to the dynamic symbol table at link time. To do this, you have to pass a flag -E to the linker i.e -Wl, -E. That should solve the problem. This is a qcc specific flag so if you're experiencing this problem in gcc, you can try passing --whole-archive flag to the linker.
answers question: http://stackoverflow.com/q/51444888
score: 1
accepted answer of: http://stackoverflow.com/q/51444888

http://stackoverflow.com/comment/129108786
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/54449494
has text: There is a small spelling mistake, shoule be 'which geckodriver'. Saved my day.

http://stackoverflow.com/q/51413816
downvote count: 0
tagged with: twitter
type: Question
score: 4
answer count: 2
tagged with: python-3.7
has body: Before I begin, I'd like to preface that I'm relatively new to python, and haven't had to use it much before this little project of mine. I'm trying to make a twitter bot as part of an art project, and I can't seem to get tweepy to import. I'm using macOS High Sierra and Python 3.7. I first installed tweepy by using pip3 install tweepy and this appeared to work, as I'm able to find the tweepy files in finder. However, when I simply input import tweepy into the IDLE, I get this error: Traceback (most recent call last): File "/Users/jacobhill/Documents/CicadaCacophony.py", line 1, in &lt;module&gt; import tweepy File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/tweepy/__init__.py", line 17, in &lt;module&gt; from tweepy.streaming import Stream, StreamListener File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/tweepy/streaming.py", line 358 def _start(self, async): ^ SyntaxError: invalid syntax Any idea on how to remedy this? I've looked at other posts on here and the other errors seem to be along the lines of "tweepy module not found", so I don't know what to do with my error. Thanks!
favorite count: 0
possible better answer: http://stackoverflow.com/a/51413842
has title: Tweepy won't install on python 3.7; shows "syntax error"
has answer: http://stackoverflow.com/a/51413900
accepted answer: http://stackoverflow.com/a/51413900
has answer: http://stackoverflow.com/a/51413842
tagged with: python
upvote count: 4
tagged with: tweepy
type: AnsweredQuestion

http://stackoverflow.com/a/51428489
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51428388
has body: You have to call the ReadData method: # ReadData is a method, so call it: self.ReturnedData = getattr(self.TheData, 'ReadData')() # note the extra '()' # Or, even more obviously, as pointed out in the comments # self.ReturnedData = self.TheData.ReadData() for data in enumerate(self.ReturnedData): # I think this line threw the error
answers question: http://stackoverflow.com/q/51428388
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/51365344
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51351059
downvote count: 0
has body: The first dimension for predict has to be the batch dimension, i.e. predict(np.zeros(shape=(1, 311))) should work. See the documentation for more details.
answers question: http://stackoverflow.com/q/51351059
type: Answer
score: 3

http://stackoverflow.com/comment/89740727
score: 0
type: Comment
type: QuestionComment
has text: ERRORS: ServiceCatalog.HistoricalServer.os_license: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. ServiceCatalog.Server.os_license: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples.
comment on: http://stackoverflow.com/q/51384135

http://stackoverflow.com/a/51433349
score: 0
type: Answer
has body: I might guess that your numpy installation somehow got stepped on. Maybe try "pip install --upgrade --force-reinstall numpy" in your command line? Or maybe it's a line that says "numpy.dtype" somewhere is being used wrong. You'd have to share at least that line of code to see that though. Just wild guesses without having your entire setup.
answers question: http://stackoverflow.com/q/51433041

http://stackoverflow.com/a/51355236
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51354423
has body: In [30]: a=np.arange(1,13) In [31]: a Out[31]: array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) Since you want to keep the first 3 values 'together', we could start with a reshape like: In [32]: a.reshape(2,2,3) Out[32]: array([[[ 1, 2, 3], [ 4, 5, 6]], [[ 7, 8, 9], [10, 11, 12]]]) and then swap a couple of the axes: In [33]: a.reshape(2,2,3).transpose(2,0,1) Out[33]: array([[[ 1, 4], [ 7, 10]], [[ 2, 5], [ 8, 11]], [[ 3, 6], [ 9, 12]]]) In [34]: _[:,0,0] Out[34]: array([1, 2, 3]) Or with a different transpose: In [35]: a.reshape(2,2,3).transpose(2,1,0) Out[35]: array([[[ 1, 7], [ 4, 10]], [[ 2, 8], [ 5, 11]], [[ 3, 9], [ 6, 12]]]) transpose() with an argument, (also invoked with .T) does the same thing. So your question is a bit ambiguous. So does the reshape with order F mentioned in the other answer: In [37]: a.reshape(3,2,2, order='F') Out[37]: array([[[ 1, 7], [ 4, 10]], [[ 2, 8], [ 5, 11]], [[ 3, 9], [ 6, 12]]]) (though the two step, a.reshape(3,4, order='F').reshape(3,2,2) produces my first result Out[33]).
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51354423
upvote count: 1

http://stackoverflow.com/a/51332704
score: 1
type: AcceptedAnswer
downvote count: 0
has body: The reason why it's not working is because you're trying to use href attribute on a &lt;script&gt; tag. As you can see 2 out of 3 of the &lt;script&gt; tags below the &lt;-- This doesn't work line use href instead of src the attribute, change that and as long as the path is the correct one it should work just fine.
accepted answer of: http://stackoverflow.com/q/51329811
type: Answer
answers question: http://stackoverflow.com/q/51329811
upvote count: 1

http://stackoverflow.com/comment/89800307
type: Comment
type: QuestionComment
has text: Is `VolValues` a `list` or a `dictionary`?
score: 0
comment on: http://stackoverflow.com/q/51414262

http://stackoverflow.com/q/51365126
score: 9
type: Question
has comment: http://stackoverflow.com/comment/89703352
has title: Combine 2 images with mask
has body: I am attempting to paint a logo over the top of a landscape image in OpenCV python. I have found answers that can 'blend'/watermark images but I don't want to make the logo transparent, I simply want to display the logo on top of the landscape image and keep the logo opacity (or lack thereof). I have tried both cv2.add() and cv2.bitwise_and() but these are not copying the logo across. src = cv2.imread('../images/pan1.jpg') logo = cv2.imread('../images/logo.png') # the background is black which is good because I dont want the black parts # Ensure the logo image is the same size as the landscape image logo_resized = np.zeros(src.shape, dtype="uint8") # Place the logo at the bottom right logo_resized[ src.shape[0] - logo.shape[0] : src.shape[0], src.shape[1] - logo.shape[1] : src.shape[1]] = logo # Convert the logo to single channel logo_gray = cv2.cvtColor(logo_resized, cv2.COLOR_BGR2GRAY) # Create a mask of the logo image ret, mask = cv2.threshold(logo_gray, 1, 255, cv2.THRESH_BINARY) # Combine the landscape and the logo images but use a mask so the black parts of logo don't get copied across # combined = cv2.bitwise_and(logo_resized, logo_resized, mask=mask) combined = cv2.add(src, logo_resized, mask=mask) My result:
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89702765
upvote count: 9
has answer: http://stackoverflow.com/a/51367486
linked to: http://stackoverflow.com/q/41572887
type: UnansweredQuestion
tagged with: python
tagged with: opencv
downvote count: 0
has comment: http://stackoverflow.com/comment/89703301
has comment: http://stackoverflow.com/comment/89702705

http://stackoverflow.com/q/51428209
has comment: http://stackoverflow.com/comment/89827902
possible better answer: http://stackoverflow.com/a/51428634
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/51428634
favorite count: 0
has body: I have tried to find some Q/A or article about the use of tk.mainloop() vs root.mainloop() with no success. My question is this: Is there any difference between the 2 uses. It seams to me the correct method would be to use tk_instance_variable_name.mainloop() vs just doing tk.mainloop() but from what I can see both appear to work just fine. Is there any reason one would need to avoid tk.mainloop() or is it just a preference. If this has been asked before please provide the Q/A link as I cannot seam to find it. I feel like it would have been asked already but no luck search for it. Can someone maybe explain why tk.mainloop() will work here when I feel like it should not work as it is not being used on the tk instance variable name. Example using root work just as expected: import tkinter as tk root = tk.Tk() tk.Label(root, text="Test").pack() root.mainloop() # using the variable name root Example using tk works fine as well as far as I can tell: import tkinter as tk root = tk.Tk() tk.Label(root, text="Test").pack() tk.mainloop() # using tk
accepted answer: http://stackoverflow.com/a/51428450
tagged with: python
has comment: http://stackoverflow.com/comment/89827840
has comment: http://stackoverflow.com/comment/89828051
score: 2
type: AnsweredQuestion
tagged with: tkinter
tagged with: mainloop
downvote count: 0
has answer: http://stackoverflow.com/a/51428450
has title: tk.mainloop() vs root.mainloop()?
type: Question

http://stackoverflow.com/a/51391898
answers question: http://stackoverflow.com/q/51391488
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89793842
type: Answer
has comment: http://stackoverflow.com/comment/89784496
has body: You are displaying both plots, the problem is that you are drawing one on top of the other. To see this in action you can shift one of the plots as in: import numpy as np import numpy.random import matplotlib.pyplot as plt # Generate some test data x_L = np.random.randn(8873) y_L = np.random.randn(8873) x_H = np.random.randn(1000) y_H = np.random.randn(1000) heatmap_L, xedges_L, yedges_L = np.histogram2d(x_L, y_L, bins=50) extent_L = np.array([xedges_L[0], xedges_L[-1], yedges_L[0], yedges_L[-1]]) heatmap_H, xedges_H, yedges_H = np.histogram2d(x_H, y_H, bins=50) extent_H = np.array([xedges_H[0], xedges_H[-1], yedges_H[0], yedges_H[-1]]) plt.clf() im1 = plt.imshow(heatmap_L.T, extent=extent_L, origin='lower', cmap='Blues') im2 = plt.imshow(heatmap_H.T+2, extent=extent_H+2, origin='lower', cmap='Greens') plt.autoscale() plt.show() You also need the plt.autoscale() call in there as otherwise the limits are not adjusted correctly. One way to show the two plots on top of each other is to use the argument alpha=X to the imshow call (where 0 &lt; X &lt; 1) in order to set transparency on the plot call. Another, possibly clearer way is to transform each value from the histogram2D to an RGBA value. See the imshow docs for both alternatives to displaying the plots on top of each other. One way of transforming the values would be to flatten the data, and augment it with the colours you want. # imports and test data generation as before, removed for clarity... flatHMH = np.reshape(heatmap_H, 2500) # flatten the 2D arrays flatHML = np.reshape(heatmap_L, 2500) maxHMH = flatHMH.max() # Find the maximum in each maxHML = flatHML.max() # Now for each value in the flat array build an RGBA tuple using # 1 for the colour we want - either green or blue, and then scaling # the value by the maximum, finally reshaping back to a 50x50 array augHMH = np.array([(0, 1, 0, x/maxHMH) for x in flatHMH]).reshape((50, 50, 4)) augHML = np.array([(0, 0, 1, x/maxHML) for x in flatHML]).reshape((50, 50,…
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51391488
has comment: http://stackoverflow.com/comment/89783041

http://stackoverflow.com/q/51360932
has comment: http://stackoverflow.com/comment/89693916
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51362016
tagged with: django
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89694434
has title: AttributeError: 'module' object has no attribute 'Name'
has body: i am trying to create a basic form using python which has only one field your_name in the table NameForm. But i am getting the error AttributeError: 'module' object has no attribute 'Name'. I dont understand where this error comes from. Could anyone help me with it? I am using django 1.11. models.py from __future__ import unicode_literals from django.db import models class NameForm(models.Model): your_name = models.CharField(max_length=200) views.py from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponseRedirect from django.views import generic from .models import NameForm class NameView(generic.NameView): model = NameForm template_name = 'home/name.html' def get_name(request): if request.method == 'POST': form = NameForm(request.POST) if form.is_valid(): return HttpResponseRedirect('/thanks/') else: form = NameForm() return render(request, 'name.html', {'form': form}) urls.py from django.conf.urls import url from . import views app_name = 'home' urlpatterns = [ url(r'^$', views.NameView.as_view(), name='name'), ] template/home/name.html Your name:
score: 0
has comment: http://stackoverflow.com/comment/89694211
has answer: http://stackoverflow.com/a/51362016
answer count: 1
has comment: http://stackoverflow.com/comment/89694148
has comment: http://stackoverflow.com/comment/89694819
favorite count: 0
has comment: http://stackoverflow.com/comment/89694778
tagged with: python

http://stackoverflow.com/q/51475911
tagged with: tensorflow
linked to: http://stackoverflow.com/q/26047209
type: Question
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/45201104
score: 1
linked to: http://stackoverflow.com/q/45201104
answer count: 2
possible better answer: http://stackoverflow.com/a/51476795
upvote count: 1
has title: Panda's indexing with double brackets [[]]
favorite count: 0
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/51476671
accepted answer: http://stackoverflow.com/a/51476671
has body: I've been going through google's machine learning crash course and they have a section where there is an exercise teaching you how to use pandas and tensorflow. In the beginning they grab the dataframe and directly after when they grab the series for the "total_rooms" and the "median_house_value". They grab the series for "total_rooms" with double brackets and they grab "median_house_value" series with only one set of brackets. I read through panda's documentation and it seems like the only reason you would need to use double brackets to index into a series would be to to index 2 columns at once i.e. data california_housing_dataframe"median_house_value", "total_rooms". Is there a reason why they used double brackets to index only one column from the dataframe while using single brackets later on to do seeming the same thing? Here is the code I'm talking about. california_housing_dataframe = pd.read_csv("https://dl.google.com/mlcc/mledu-datasets/california_housing_train.csv", sep=",") # Define the input feature: total_rooms. my_feature = california_housing_dataframe"total_rooms" # Configure a numeric feature column for total_rooms. feature_columns = [tf.feature_column.numeric_column("total_rooms")] targets = california_housing_dataframe["median_house_value"] Here is more of the code if you need more context: california_housing_dataframe = pd.read_csv("https://dl.google.com/mlcc/mledu-datasets/california_housing_train.csv", sep=",") # Define the input feature: total_rooms. my_feature = california_housing_dataframe"total_rooms" # Configure a numeric feature column for total_rooms. feature_columns = [tf.feature_column.numeric_column("total_rooms")] targets = california_housing_dataframe["median_house_value"] def my_input_fn(features, targets, batch_size=1, shuffle=True, num_epochs=None): """Trains a linear regression model of one feature. Args: features: pandas DataFrame of features targets: pandas DataFrame of targets batch_size: Size of batches to be passe…
tagged with: python-3.x
downvote count: 0
has answer: http://stackoverflow.com/a/51476795

http://stackoverflow.com/a/51399654
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/89774939
has comment: http://stackoverflow.com/comment/89775119
score: 2
accepted answer of: http://stackoverflow.com/q/51399342
answers question: http://stackoverflow.com/q/51399342
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89777948
has body: Scratch'N'Purr provided the answer for me, thanks very much. If anyone else is having the same issue it's the lack of cnxn.commit() After the statement that is the problem. I have since tested this and it worked perfectly.

http://stackoverflow.com/q/51411315
upvote count: 0
answer count: 1
favorite count: 0
has title: Openpyxl removes sorts that are already part of the excel file
has answer: http://stackoverflow.com/a/51501401
tagged with: python
has body: Right now, I am sorting data with pandas and then adding those values into the excel file and it works great. The problem is that the excel file already has the sort coded in and when I write data to the xlsx it will remove the sort. My colleagues want to be able to use the built-in excel sort and I can't figure out why openpyxl will remove that sort when I write data to the file. Is there a parameter I'm missing or is this just how openpyxl operates? I can include code if it is needed. Using the latest version of python and openpyxl.
has comment: http://stackoverflow.com/comment/89805394
type: UnansweredQuestion
tagged with: openpyxl
downvote count: 1
tagged with: excel
type: Question
score: -1

http://stackoverflow.com/a/51479161
downvote count: 0
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/89963960
accepted answer of: http://stackoverflow.com/q/51465320
score: 1
answers question: http://stackoverflow.com/q/51465320
has body: Solution with lists: Producer puts data into a list with LPUSH Consumer takes data from this list with RPOP or BRPOP (blocking). Limitations: only one consumer reads the message. If you have 2, only one of them will see the message. Speed: for one pair of consumer-producer it will have the same speed. The more consumers (for this or other lists), the faster it will be than pub/sub.
upvote count: 1

http://stackoverflow.com/comment/89863741
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/51446778
type: Comment
has text: [Append on tuples forms a monoid too](https://stackoverflow.com/a/952946/5267751)

http://stackoverflow.com/a/51422095
downvote count: 0
type: Answer
has body: From the pandas documentation: Series.replace(to_replace=None, value=None,...) to_replace : str, regex, list, dict, Series, int, float, or None list of str, regex, or numeric: - First, if to_replace and value are both lists, they must be the same length. - Second, if regex=True then all of the strings in both lists will be interpreted as regexs otherwise they will match directly. This doesn’t matter much for value since there are only a few possible substitution regexes you can use. - str, regex and numeric rules apply as above. Pandas will mistake the to_replace value of [] for a list of strings to match, where it tries to replace its contents rather than the empty list itself. This causes the error. (So whatever the replace function does in this case, it will not work for empty lists - the OP's code snippet does not work in my environment, but I get a different error message.)
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/89816551
accepted answer of: http://stackoverflow.com/q/51421796
answers question: http://stackoverflow.com/q/51421796
type: AcceptedAnswer

http://stackoverflow.com/q/51340693
has comment: http://stackoverflow.com/comment/89655049
has comment: http://stackoverflow.com/comment/89655455
accepted answer: http://stackoverflow.com/a/51382417
type: Question
has title: I am currently creating a calculator in Python and when I execute code, the buttons are in the wrong place
answer count: 1
tagged with: calculator
score: 0
has body: I am using Tkinter to make a graphical calculator in Python. My aim is to make my calculator look similar to this - http://prntscr.com/k6exeu I am currently still building my calculator so there's a lot of stuff missing, but I decided to do the design first. When I execute my code, I get this - http://prntscr.com/k6eyhm I need help fixing this. I'll paste the code so far so you can spot any errors. import sys try: from Tkinter import * import tkMessageBox except ImportError: from tkinter import * from tkinter import messagebox window = Tk() window.title("PyCalc") window.geometry("500x500") user_output = Entry(width=50, state='readonly', justify=CENTER) zero = Button(text="0", height=3, width=3, justify=LEFT) one = Button(text="1", height=3, width=3, justify=LEFT) two = Button(text="2", height=3, width=3, justify=LEFT) three = Button(text="3", height=3, width=3, justify=LEFT) four = Button(text="4", height=3, width=3, justify=LEFT) five = Button(text="5", height=3, width=3, justify=LEFT) six = Button(text="6", height=3, width=3, justify=LEFT) seven = Button(text="7", height=3, width=3, justify=LEFT) eight = Button(text="8", height=3, width=3, justify=LEFT) nine = Button(text="9", height=3, width=3, justify=LEFT) user_output.grid(row=0) zero.grid(row=4, column=3, sticky=N+S+E+W) one.grid(row=1, column=1, sticky=N+S+E+W) two.grid(row=1, column=2, sticky=N+S+E+W) three.grid(row=1, column=3, sticky=N+S+E+W) four.grid(row=2, column=1, sticky=N+S+E+W) five.grid(row=2, column=2, sticky=N+S+E+W) six.grid(row=2, column=3, sticky=N+S+E+W) seven.grid(row=3, column=1, sticky=N+S+E+W) eight.grid(row=3, column=2, sticky=N+S+E+W) nine.grid(row=3, column=3, sticky=N+S+E+W) window.mainloop() If someone would help me, I'd be very happy :) -CodeExecution
tagged with: python
tagged with: tkinter
has answer: http://stackoverflow.com/a/51382417
has comment: http://stackoverflow.com/comment/89705858
type: AnsweredQuestion

http://stackoverflow.com/comment/89929179
score: 0
has text: There are no grayscale shades of rgb; that doesn't mean anything. Do you mean the (relative) values of the three colours, or a three dimensional grayscale picture?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51480238

http://stackoverflow.com/comment/89819562
type: Comment
has text: I could not find the expected answer with your code, so i wnt with a recursive way. However, i'm still interested to solve it in this way as an intellectual challenge. Please see my post
type: AnswerComment
comment on: http://stackoverflow.com/a/51411196
score: 0

http://stackoverflow.com/q/51476517
type: AnsweredQuestion
has body: recently im working using Python with Tkinter gui. The problem is , i want to show some lines by changing its state from hidden to normal within some interval, let's say it 1s. So , the line will show up 1 by 1 within 1 second. When i tried, the commandline works perfectly(i print some text on windows cmd) But, the gui frozen until the end of the computation then all of the lines showed up(not 1 by 1), idk why? im new with python :( here's my dummy code def delay(): allline=mainframe.find_withtag('line') for i in allline: tags=mainframe.gettags(i) print(tags[0]) root.after(1000, mainframe.itemconfigure(tags[0],state='normal')) ...... mainframe.create_line((50,50,100,100),...,tags=('line1','line'),state='hidden') mainframe.create_line((150,150,100,100),...,tags=('line2','line'),state='hidden') let's say i have a button which trigger delay function. Thanks for ur help! sorry for my bad english :)
score: 1
tagged with: loops
type: Question
upvote count: 2
tagged with: user-interface
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51477796
accepted answer: http://stackoverflow.com/a/51477796
has comment: http://stackoverflow.com/comment/89999307
downvote count: 1
tagged with: python
has title: Multiple After on Tkinter made the GUI frozen
has comment: http://stackoverflow.com/comment/89923507
tagged with: tkinter
has comment: http://stackoverflow.com/comment/89924276

http://stackoverflow.com/comment/89914678
has text: Hey, I don't know what gmaps_geoencoder() is. Please attach the includes as well.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51473216

http://stackoverflow.com/comment/89794761
score: 0
has text: [Here's a quick guide](https://support.office.com/en-us/article/Choose-text-encoding-when-you-open-and-save-files-60d59c21-88b5-4006-831c-d536d42fd861) to encoding in Microsoft Word -- per the table near the bottom, it looks like if the Greek isn't encoded in Unicode, then it'll be in Windows 1253.
comment on: http://stackoverflow.com/q/51411434
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51347012
tagged with: apache-spark
downvote count: 0
possible better answer: http://stackoverflow.com/a/61586123
has answer: http://stackoverflow.com/a/61586123
favorite count: 0
has answer: http://stackoverflow.com/a/54265655
has title: How to troubleshoot 'pyspark' is not recognized... error on Windows?
tagged with: python
has body: It has been two weeks during which I have been trying to install Spark (pyspark) on my Windows 10 machine, now I realized that I need your help. When I try to start 'pyspark' in the command prompt, I still receive the following error: The Problem 'pyspark' is not recognized as an internal or external command, operable program or batch file. To me this hints at a problem with the path/environmental variables, but I cannot find the root of the problem. My Actions I have tried multiple tutorials but the best I found was the one by Michael Galarnyk. I followed his tutorial step by step: Installed Java Installed Anaconda Downloaded Spark 2.3.1 (I changed the commands accordingly as Michael's tutorial uses a different version) from the official website. I moved it in line with the tutorial in the cmd prompt: mv C:\Users\patri\Downloads\spark-2.3.1-bin-hadoop2.7.tgz C:\opt\spark\spark-2.3.1-bin-hadoop2.7.tgz Then I untarred it: gzip -d spark-2.3.1-bin-hadoop2.7.tgz and tar xvf spark-2.3.1-bin-hadoop2.7.tar Downloaded Hadoop 2.7.1 from Github: curl -k -L -o winutils.exe https://github.com/steveloughran/winutils/raw/master/hadoop-2.7.1/bin/winutils.exe?raw=true Set my Environmental Variables accordingly: setx SPARK_HOME C:\opt\spark\spark-2.3.1-bin-hadoop2.7 setx HADOOP_HOME C:\opt\spark\spark-2.3.1-bin-hadoop2.7 setx PYSPARK_DRIVER_PYTHON jupyter setx PYSPARK_DRIVER_PYTHON_OPTS notebook Then added C:\opt\spark\spark-2.3.1-bin-hadoop2.7\bin to my path variables. My environmental user variables now look like this: Current Environmental Variables These actions should have done the trick, but when I run pyspark --master local[2], I still get the error from above. Can you help to track down this error using the information from above? Checks I ran a couple of checks in the command prompt to verify the following: Java is installed Anaconda is installed pip is installed Python is installed
type: AnsweredQuestion
score: 7
upvote count: 7
accepted answer: http://stackoverflow.com/a/54265655
type: Question
tagged with: pyspark
linked to: http://stackoverflow.com/q/46849585
answer count: 2

http://stackoverflow.com/a/51382297
score: 3
accepted answer of: http://stackoverflow.com/q/51382266
answers question: http://stackoverflow.com/q/51382266
type: AcceptedAnswer
downvote count: 0
has body: Use fomat from http://strftime.org/ for improve performance with to_datetime: df['date'] = pd.to_datetime(df['date'], format='%B %d, %Y') Or: df['date'] = pd.to_datetime(df['date']) print (df) date 0 2013-12-22 1 2016-11-28 2 2013-12-21
type: Answer
upvote count: 3

http://stackoverflow.com/q/51424647
has body: I am working with a numpy matrix like this: [[ 0 1 2 ..., 97 98 0] [ 100 101 102 ..., 197 198 0] [ 200 201 202 ..., 297 298 1] ..., [9700 9701 9702 ..., 9797 9798 1] [9800 9801 9802 ..., 9897 9898 0] [9900 9901 9902 ..., 9997 9998 0]] How can I remove all the rows that have one in the last column of my numpy matrix?: [[ 0 1 2 ..., 97 98 0] [ 100 101 102 ..., 197 198 0] ..., [9800 9801 9802 ..., 9897 9898 0] [9900 9901 9902 ..., 9997 9998 0]] I tried to transform the matrix into a pandas dataframe and filter by the last column: matrix = pd.DataFrame(data=second_round_mat[1:,1:]) matrix = matrix[matrix['567'] != 1.0] However, this is not very convinient, and maybe there's a similar way to do that in numpy, thus how can I filter by column value in numpy?
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89823855
has comment: http://stackoverflow.com/comment/89821912
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89824255
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89820544
tagged with: scipy
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/89820754
has title: Which is the correct way to efficiently filter a numpy matrix by column values?
has answer: http://stackoverflow.com/a/51424740
accepted answer: http://stackoverflow.com/a/51424740
score: 0

apache-spark
tags question: http://stackoverflow.com/q/51444591
tags question: http://stackoverflow.com/q/51479867
tags question: http://stackoverflow.com/q/51342777
tags question: http://stackoverflow.com/q/51450004
tags question: http://stackoverflow.com/q/51402369
tags question: http://stackoverflow.com/q/51415784
tags question: http://stackoverflow.com/q/51446568
tags question: http://stackoverflow.com/q/51347015
tags question: http://stackoverflow.com/q/51368393
tags question: http://stackoverflow.com/q/51355803
tags question: http://stackoverflow.com/q/51388347
tags question: http://stackoverflow.com/q/51362759
tags question: http://stackoverflow.com/q/51361111
tags question: http://stackoverflow.com/q/51435475
tags question: http://stackoverflow.com/q/51441548
tag name: apache-spark
tags question: http://stackoverflow.com/q/51472810
tags question: http://stackoverflow.com/q/51343795
tags question: http://stackoverflow.com/q/51429005
tags question: http://stackoverflow.com/q/51383298
tags question: http://stackoverflow.com/q/51457539
tags question: http://stackoverflow.com/q/51343827
tags question: http://stackoverflow.com/q/51481489
tags question: http://stackoverflow.com/q/51347012
tags question: http://stackoverflow.com/q/51385657
tags question: http://stackoverflow.com/q/51324601
tags question: http://stackoverflow.com/q/51466068
tags question: http://stackoverflow.com/q/51443114
tags question: http://stackoverflow.com/q/51437111
tags question: http://stackoverflow.com/q/51347411
tags question: http://stackoverflow.com/q/51381038
tags question: http://stackoverflow.com/q/51368378
tags question: http://stackoverflow.com/q/51381806
tags question: http://stackoverflow.com/q/51399180
type: Tag
tags question: http://stackoverflow.com/q/51364443

http://stackoverflow.com/a/51457683
has comment: http://stackoverflow.com/comment/89910744
has comment: http://stackoverflow.com/comment/90120385
has comment: http://stackoverflow.com/comment/90175500
score: 0
answers question: http://stackoverflow.com/q/51456497
has comment: http://stackoverflow.com/comment/89896169
type: Answer
has body: For this you have to make custom message view and show this on calendar date click. its not necessary you have to use library for this, but some calendar libraries have built=in message feature.

http://stackoverflow.com/comment/89806526
has text: You need to update mysql's keepalive timeout (This has nothing to do with SQLAlchemy)
comment on: http://stackoverflow.com/q/51417786
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51466652
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51466610
type: Answer
accepted answer of: http://stackoverflow.com/q/51466610
has comment: http://stackoverflow.com/comment/89901732
upvote count: 12
has comment: http://stackoverflow.com/comment/89901765
has body: A recursive method along the following lines should work: def paths(self): if not self.children: return self.value # one path: only contains self.value paths = [] for child in self.children: for path in child.paths(): paths.append([self.value] + path) return paths
score: 12

http://stackoverflow.com/a/51365338
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51365221
downvote count: 0
has body: You can using pd.cut pd.cut(df.month,[0,4,7,10,13],right=False) Out[298]: 0 [0, 4) 1 [7, 10) 2 [10, 13) Name: month, dtype: category Categories (4, interval[int64]): [[0, 4) &lt; [4, 7) &lt; [7, 10) &lt; [10, 13)] Or pd.to_datetime(df.month,format='%m').dt.quarter Out[308]: 0 1 1 3 2 4 Name: month, dtype: int64
type: Answer

http://stackoverflow.com/comment/89694819
score: 0
comment on: http://stackoverflow.com/q/51360932
type: Comment
type: QuestionComment
has text: if you want to use class-based views you should create method request methods in there. Suggest you to read this: [Django class-based views](https://docs.djangoproject.com/en/2.0/topics/class-based-views/intro/)

http://stackoverflow.com/a/51402124
has body: Once you fix the logic error pointed out by Mike Scotty, the other problems are really just syntax errors. sum.pos_values will give you AttributeError: 'builtin_function_or_method' object has no attribute 'pos_values' (because sum is a built-in function and so needs () not .); and print[all_values] will give you a syntax error (because print is also a built-in function and so needs () not []). Your original code doesn't store zeroes in either list: I haven't changed that. And the output format is a guess on my part. def main(): again = 'y' pos_values = [] neg_values = [] while again == 'y': value = int(input("Please enter value: ")) if value &gt; 0: pos_values.append(value) elif value &lt; 0: neg_values.append(value) else: #edit: terminate also on 0 input break print('Would you like to add another value?') again = input('y = yes; n = no: ') all_values = neg_values + pos_values print(sum(all_values),all_values) print(sum(pos_values),pos_values) print(sum(neg_values),neg_values)
has comment: http://stackoverflow.com/comment/89802737
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/89795703
has comment: http://stackoverflow.com/comment/89800016
has comment: http://stackoverflow.com/comment/89792091
answers question: http://stackoverflow.com/q/51399077

http://stackoverflow.com/comment/89913586
score: 0
type: QuestionComment
type: Comment
has text: I updated the post, could you read the edit?
comment on: http://stackoverflow.com/q/51472151

http://stackoverflow.com/a/51342857
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89659680
type: Answer
has comment: http://stackoverflow.com/comment/89659813
downvote count: 0
score: 1
has body: You have a Dense layer with 6 units and softmax activation as the last layer. So its output would be of shape (?,6) where each of those 6 values indicates the probability of belonging to corresponding class. Since you have used categorical_crossentropy as the loss function, the labels (i.e. y_) should have the same shape (i.e. (2787,6)) as well. You can one-hot encode y_ by using to_categorical method: from keras.utils import to_categorical y_ = to_categorical(y_) This one-hot encodes the labels, i.e. converts 3 to [0,0,0,1,0,0] (assuming label numbers start from zero). If you don't want to one-hot encode your labels you can change the loss argument to 'sparse_categorical_crossentropy'.
answers question: http://stackoverflow.com/q/51342763
accepted answer of: http://stackoverflow.com/q/51342763
upvote count: 1

http://stackoverflow.com/comment/89827623
type: QuestionComment
comment on: http://stackoverflow.com/q/51427907
score: 0
has text: Seems to be a python version related issue, can you try to replicate the exact working environment in windows?
type: Comment

http://stackoverflow.com/comment/89828290
type: Comment
comment on: http://stackoverflow.com/a/51428466
score: 0
type: AnswerComment
has text: @schwobaseggl, I also think so. `set`s are awesome! I just tested this on my machine.

http://stackoverflow.com/q/51432600
score: 2
has answer: http://stackoverflow.com/a/51452043
downvote count: 0
favorite count: 0
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51432656
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/51446187
has body: How can I loop my function as many times = number entered in number_virtuals? Here is my code: import ipaddress import sys import re dataList = [] def CollectData(): ''' this fuction will be used to collect input from user''' number_virtuals = input (" How many virtuals are you requesting? ") realSerName = input("Please Enter Virtual Name: ") realTCPport = input("Please Enter Virtual TCP port :") serName = input("Please Enter Server name, port and IP(format: oser500522:443:172.17.5.1):") # dataCenter = input("Please Enter Data Center: Please") dataList.append({"number_virtuals": number_virtuals, "realSerName": realSerName, "realTCPport": realTCPport, "serName": serName}) def printconfig(dataList): print(dataList) CollectData() printconfig(dataList) Could anyone help me with this?
has answer: http://stackoverflow.com/a/51433018
type: Question
has title: How can I loop my function as many times = number entered in number_virtuals?

http://stackoverflow.com/comment/89708881
score: 0
comment on: http://stackoverflow.com/a/51366875
type: Comment
has text: I would strongly advise against silently updating running stats. This is asking for trouble.
type: AnswerComment

http://stackoverflow.com/q/51428007
linked to: http://stackoverflow.com/q/5246856
has comment: http://stackoverflow.com/comment/89827633
has title: Finding unit digit of large powers
has comment: http://stackoverflow.com/comment/89828507
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/51428575
has comment: http://stackoverflow.com/comment/89827448
has comment: http://stackoverflow.com/comment/89827584
favorite count: 0
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
tagged with: math
linked to: http://stackoverflow.com/q/11448658
has body: I need to find the last digit of large power. When I get simple x^n, I solve problem with this: pow(x, n, 10). But what should I do when I have such example: 103171^(14394^(221515^(441792^507709)))? I noticed the cyclicity of specific digits, but it's not enough. I am afraid I'm missing some important point. As an input of my main function last_digit I get list of numbers (lst), let's say [3, 4, 2]- this means I need to compute 3 ^ (4 ^ 2). I've got about 630 tests to pass and I can only make about 580 (most of them are randomly generated). Here's my code I've tried: CYCLES = { 0 : [0, 0, 0, 0], 1 : [1, 1, 1, 1], 2 : [2, 4, 8, 6], 3 : [3, 9, 7, 1], 4 : [4, 6, 4, 6], 5 : [5, 5, 5, 5], 6 : [6, 6, 6, 6], 7 : [7, 9, 3, 1], 8 : [8, 4, 2, 6], 9 : [9, 1, 9, 1] } def power_rec(lst): remainder = pow(lst[-2], lst[-1], 4) if len(lst) == 2: first_num = int(str(lst[0])[-1]) second_num = int(str(lst[1])[-1]) return CYCLES[first_num][second_num - 1] lst = lst[:-2] + [ remainder ] return power_rec(lst) def last_digit(lst): if len(lst) == 2: return pow(lst[0], lst[1], 10) if lst == []: return 1 if len(lst) == 1: return int(str(lst[0])[-1]) return power_rec(lst) E.g. I cannot pass tests with inputs: [555913, 845991, 261716, 431426, 571315, 456986, 461380, 413475] or [2, 2, 101, 2]. I have to assume that 0 ^ 0 = 1 and that last_digit of an empty list equals to 1. I'd appreciate any helpful tips. UPDATE. Found shortest solution: def last_digit(lst): result = 1 for num in lst[::-1]: result = pow(num, (result if result &lt; 4 else result % 4 + 4) ) return result % 10
linked to: http://stackoverflow.com/q/30785865
type: Question

http://stackoverflow.com/a/51434243
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89839033
score: 0
type: Answer
has body: There’s no need to add a delay. If your serial port code is properly written, it will pause during readline() with minimal load on the cpu, until a new line is available. That is the correct behavior - wait for a new chunk of data, process it, then begin waiting again immediately. Try it and see how high the CPU load is (you can use top in a different terminal for that.). If you want to reduce the cpu usage further, you should send instructions to the GPS chip to reduce the update frequency (increase the interval between each update that it sends on the serial line). But adding a delay in your main loop won't reduce CPU load significantly, and risks falling behind the GPS updates.
accepted answer of: http://stackoverflow.com/q/51434080
answers question: http://stackoverflow.com/q/51434080
has comment: http://stackoverflow.com/comment/89838952
has comment: http://stackoverflow.com/comment/89839004
has comment: http://stackoverflow.com/comment/89845271

http://stackoverflow.com/comment/89883620
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51446966
has text: Sorry. I did not notice that. I've corrected the omission and run the code. It should work now.

http://stackoverflow.com/comment/89772029
has text: It's object of objects, not array...
comment on: http://stackoverflow.com/q/51361316
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89882920
type: QuestionComment
comment on: http://stackoverflow.com/q/51445481
has text: Yes, that was my intention. Mainly administrators/moderators can modify other users profiles. The ModificationInformation() is also used in other classes. Recursive to infinity / error is indeed a problem. Thank you, I would love to hear your suggestions :).
score: 0
type: Comment

http://stackoverflow.com/comment/89794728
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51411210
has text: @ImportanceOfBeingErnest please see question update.

http://stackoverflow.com/a/51332989
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/89705766
has body: Such an error states that there is some mismatch with the depth of the image. The function expects the input image to be 8 bit in depth. Convert your image using the following and then pass it to the function cv2.connectedComponents(): img=img.astype(numpy.uint8)
accepted answer of: http://stackoverflow.com/q/51332842
answers question: http://stackoverflow.com/q/51332842
has comment: http://stackoverflow.com/comment/89706403
score: 0

http://stackoverflow.com/comment/89795026
comment on: http://stackoverflow.com/q/51411622
type: QuestionComment
type: Comment
has text: Your question doesn't make sense. Most iterables *don't have indices*, those that do, frequently provide such a functionality as methods on those objects or, in the case of `numpy`, you can use `numpy.where`
score: 0

http://stackoverflow.com/a/51474573
downvote count: 0
has comment: http://stackoverflow.com/comment/89920477
type: Answer
has comment: http://stackoverflow.com/comment/89921145
has body: For the record, here is how you could animate an lmplot(), provided you don't have any facets and you don't care about regressions: import seaborn as sns; sns.set(color_codes=True) tips = sns.load_dataset("tips") g = sns.lmplot(x="total_bill", y="tip", hue="smoker", data=tips, fit_reg=False) fig = g.fig ax = g.axes[0,0] scatters = [c for c in ax.collections if isinstance(c, matplotlib.collections.PathCollection)] txt = ax.text(0.1,0.9,'frame=0', transform=ax.transAxes) def animate(i): for c in scatters: # do whatever do get the new data to plot x = np.random.random(size=(50,1))*50 y = np.random.random(size=(50,1))*10 xy = np.hstack([x,y]) # update PathCollection offsets c.set_offsets(xy) txt.set_text('frame={:d}'.format(i)) return scatters+[txt] ani = matplotlib.animation.FuncAnimation(fig, animate, frames=10, blit=True) However in this case, you can obtain almost exactly the same result, in a much more straightforward way, by not using lmplot altogether: import seaborn as sns; sns.set(color_codes=True) tips = sns.load_dataset("tips") fig, ax = plt.subplots() scatters = [] for g,d in tips.groupby('smoker'): s = ax.scatter(x="total_bill", y="tip", data=tips, label=g) scatters.append(s) ax.legend(bbox_to_anchor=(1.,1.), loc=1) txt = ax.text(0.1,0.9,'frame=0', transform=ax.transAxes) def animate(i): for c in scatters: x = np.random.random(size=(50,1))*50 y = np.random.random(size=(50,1))*10 xy = np.hstack([x,y]) c.set_offsets(xy) txt.set_text('frame={:d}'.format(i)) return scatters+[txt] ani = matplotlib.animation.FuncAnimation(fig, animate, frames=10, blit=True) From the code above, it is fairly simple to append new values to the previous data, instead of replacing all the points: import seaborn as sns; sns.set(color_codes=True) tips = sns.load_dataset("tips") fig, ax = plt.subplots() scatters = [] for g,d in tips.groupby('smoker'): s = ax.scatter([], [], label=g) scatters.append(s) ax.legend(bbox_to_anchor=(1.,1.), loc=1) txt = ax.text(0.1,0.9,'frame=0', transform=ax…
has comment: http://stackoverflow.com/comment/89928243
upvote count: 3
answers question: http://stackoverflow.com/q/51473032
score: 3
has comment: http://stackoverflow.com/comment/89930934

http://stackoverflow.com/q/51415535
has answer: http://stackoverflow.com/a/51415695
accepted answer: http://stackoverflow.com/a/51415703
tagged with: tuples
score: 0
has title: Python data type behaving some different
has comment: http://stackoverflow.com/comment/89802113
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51415703
tagged with: list
has body: I am finding out difference between data types in python . I am little bit confuse why type of demo2 is giving list instead of tuple . Can anyone tell me why it is printing type list instead of tuple ? Code demo1 = () print ("demo1 {}".format(type(demo1))) demo2 = ([]) print ("demo2 {}".format(type(demo2))) demo3 = ([],[]) print ("demo3 {}".format(type(demo3))) Output demo1 &lt;type 'tuple'&gt; demo2 &lt;type 'list'&gt; demo3 &lt;type 'tuple'&gt;
type: Question
has comment: http://stackoverflow.com/comment/89802321
has comment: http://stackoverflow.com/comment/89802397
answer count: 2
has comment: http://stackoverflow.com/comment/89802233
possible better answer: http://stackoverflow.com/a/51415695
has comment: http://stackoverflow.com/comment/89802191

http://stackoverflow.com/comment/89670285
type: Comment
has text: @JonClements we created a code obfuscator at work, and using the OR technique with 2000+ words took hours, because it's linear. There's no way regex is smart enough to work letter by letter tree-like. Maybe `regex` module can do it. Dunno.
comment on: http://stackoverflow.com/a/51347183
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89844749
score: 0
has text: i've never heard of drf but ill start looking it up and let you know how it goes.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51437271

http://stackoverflow.com/q/51343721
type: Question
has answer: http://stackoverflow.com/a/51343822
has body: I have a long list of numbers (a single column that has 5 million rows), that are not all unique from one another. I want to see which thousand of them are the most frequent occurrences in the list. Any ideas on how I could do this easily? I could use excel or a python script or other means too.
has comment: http://stackoverflow.com/comment/89660744
tagged with: histogram
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/51343815
tagged with: http://stackoverflow.com/tag/csv
upvote count: 1
has comment: http://stackoverflow.com/comment/89660786
favorite count: 0
tagged with: frequency
type: UnansweredQuestion
tagged with: python
tagged with: excel
has answer: http://stackoverflow.com/a/51343804
has title: frequency of millions of data values in a csv column
downvote count: 1

http://stackoverflow.com/comment/89907611
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51469536
has text: @colde I originally got the data encoding by using wireshark, but I will take a look again to see about the headers

http://stackoverflow.com/q/51386761
tagged with: scatter-plot
linked to: http://stackoverflow.com/q/28371674
has comment: http://stackoverflow.com/comment/89745458
duplicate of: http://stackoverflow.com/q/28371674
has comment: http://stackoverflow.com/comment/89749941
has body: My scatter plot looks like this: The following is the command is used to plot the scatter plot: plt.scatter(x,y[:,0],c="c", alpha=0.3) Here, both x and y are numpy arrays. The values look like: x: array([ 36259516, 36259544, 36259600, ..., 9251680654, 9251680675, 9296284549], dtype=int64) y: array([[ 0.91122632], [ 0.79788549], [ 0.87083686], ..., [ 0.77459159], [ 0.69324043], [ 0.77459159]]) Note: In short, I wanna plot all the values 'y' values of unique 'x'. If you could see, even if passing different array on x-axis , when the graph is plotted , I could notice both axis representing y-axis values. Can anyone help me solve this issue.
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89749655
answer count: 0
tagged with: plotly
score: 0
tagged with: matplotlib
type: Question
tagged with: numpy-ndarray
has title: I am getting incorrect value on X- axis of scatterplot in python

http://stackoverflow.com/q/51477357
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51478103
tagged with: matplotlib
has answer: http://stackoverflow.com/a/51477772
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/51477772
has body: I am trying to get colormaps working with the Iris dataset form sklean. Colormaps work as expected when I use de dataset from Seaborn, but I have no clue why it does not work with the sklearn set. Any suggestions? import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt # works iris = sns.load_dataset('iris') colors = {'setosa': 0, 'versicolor': 1, 'virginica': 2} plt.scatter(x=iris.sepal_length, y=iris.sepal_width, c=[colors[i] for i in iris.species], cmap='viridis') plt.show() # does not work from sklearn.datasets import load_iris iris = load_iris() plt.scatter(x=iris.data[:,[0]], y=iris.data[:,[1]], c=iris.target, cmap='viridis') plt.show()
has title: Using colormaps with the Iris-dataset in matplotlib pyplot gives an error
favorite count: 0
has answer: http://stackoverflow.com/a/51478103
tagged with: python
type: AnsweredQuestion
score: 1

http://stackoverflow.com/q/51391300
score: 1
has title: Python list comprehension with multiple loops
downvote count: 1
has answer: http://stackoverflow.com/a/51391364
has answer: http://stackoverflow.com/a/51391490
type: Question
has answer: http://stackoverflow.com/a/51391378
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/89754833
accepted answer: http://stackoverflow.com/a/51391378
has body: My goal is to create a one liner to produce a following list: list_100 = ['ch1%.2d' % x for x in range(1,6)] list_200 = ['ch2%.2d' % x for x in range(1,6)] final_list = list_100 + list_200 [ch101,ch102,ch103,ch104,ch105, ch201,ch202,ch203,ch204,ch205] is there some way to do that in one line: final_list = ['ch%.1d%.2d' % (y for y in range(1,3), x for x in range(1,6)]
favorite count: 0
has answer: http://stackoverflow.com/a/51391454
upvote count: 2
answer count: 5
possible better answer: http://stackoverflow.com/a/51391351
tagged with: python
has answer: http://stackoverflow.com/a/51391351
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/comment/89819617
has text: I changed the system interpreter to another version of Python, and now all libraries mentioned in requirements.txt were properly installed.
type: AnswerComment
comment on: http://stackoverflow.com/a/51424024
type: Comment
score: 1

http://stackoverflow.com/q/51466445
possible better answer: http://stackoverflow.com/a/51466513
has comment: http://stackoverflow.com/comment/89901293
score: 0
has body: I made a dice roller in python recently. However, the outputs seem to be fairly non-random (e.g. numbers coming up regularly twice in a row). Is this to do with my poor code or is the random.randint function not as random as it seems? import random print('Welcome to Dice Rolling simulator! \ Type "Roll" to start.') def DiceRoll(): if input() == (str('Roll')): print(spam) print('Roll again?') for i in range (50): spam = random.randint(1,6) DiceRoll()
has answer: http://stackoverflow.com/a/51466584
has comment: http://stackoverflow.com/comment/89901382
has comment: http://stackoverflow.com/comment/89901372
accepted answer: http://stackoverflow.com/a/51466584
has title: Dice Roller in Python Not Random
answer count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89901449
favorite count: 0
has answer: http://stackoverflow.com/a/51466513
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/89904402
downvote count: 2
tagged with: python

http://stackoverflow.com/comment/89901293
type: QuestionComment
has text: A dice roller where numbers couldn't appear twice in a row would be biased, and not random. Your code doesn't look buggy.
score: 6
comment on: http://stackoverflow.com/q/51466445
type: Comment

http://stackoverflow.com/comment/89628721
has text: @Shubhamoli True, but probably irrelevant. it is highly unlikely Ahmed wants to go to `http://127.0.0.1:8000/drafts{url+post_detail+pk=post.pk}`. A more likely location would be `127.0.0.1:8000/post_detail/12`
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51326642
type: QuestionComment

http://stackoverflow.com/a/51448947
has comment: http://stackoverflow.com/comment/89868625
has comment: http://stackoverflow.com/comment/89868373
type: AcceptedAnswer
downvote count: 0
has body: maybe you need to specify the --host=0.0.0.0 flag? (from here). Can you try to override your command in docker-compose? version: "2.2" services: api: container_name: "pyserver" build: . command: flask run --host=0.0.0.0 volumes: - ".:/usr/src/app" environment: FLASK_APP: server.py ports: - "5000:5000" command: ["flask", "run"] By the way, not sure that the EXPOSE in dockerfile is necessary if you are communicate only from your host machine (rather than other container).
type: Answer
has comment: http://stackoverflow.com/comment/89868497
has comment: http://stackoverflow.com/comment/89868453
score: 2
has comment: http://stackoverflow.com/comment/89868474
upvote count: 2
answers question: http://stackoverflow.com/q/51448634
accepted answer of: http://stackoverflow.com/q/51448634

http://stackoverflow.com/q/51448711
has comment: http://stackoverflow.com/comment/89870366
has title: How to click every link and extract content inside - Python Selenium
tagged with: selenium
has body: I wanna get content inside from all links with id = "LinkNoticia" Actually my code join in first link and extract content, but i cant access to other. How can i do it? this is my code (its works for 1 link) from selenium import webdriver driver= webdriver.Chrome("/selenium/webdriver/chromedriver") driver.get('http://www.emol.com/noticias/economia/todas.aspx') driver.find_element_by_id("LinkNoticia").click() title = driver.find_element_by_id("cuDetalle_cuTitular_tituloNoticia") print(title.text)
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89870058
linked to: http://stackoverflow.com/q/5611963
type: Question
score: 0
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
tagged with: python
tagged with: selenium-webdriver
has answer: http://stackoverflow.com/a/51449942
accepted answer: http://stackoverflow.com/a/51449942

http://stackoverflow.com/q/51386902
has answer: http://stackoverflow.com/a/51387239
score: 6
tagged with: machine-learning
tagged with: python
tagged with: plot
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89746046
type: Question
accepted answer: http://stackoverflow.com/a/51387239
linked to: http://stackoverflow.com/q/60454355
has title: t-SNE map into 2D or 3D plot
answer count: 1
favorite count: 0
has body: features = ["Ask1", "Bid1", "smooth_midprice", "BidSize1", "AskSize1"] client = InfluxDBClient(host='127.0.0.1', port=8086, database='data', username=username, password=password) series = "DCIX_2016_11_15" sql = "SELECT * FROM {} where time &gt;= '{}' AND time &lt;= '{}' ".format(series,FROMT,TOT) df = pd.DataFrame(client.query(sql).get_points()) #Separating out the features X = df.loc[:, features].values # Standardizing the features X = StandardScaler().fit_transform(X) tsne = TSNE(n_components=3, n_jobs=5).fit_transform(X) I would like map my 5 features into a 2D or 3D plot. I am a bit confused how to do that. How can I build a plot from that information?
upvote count: 8
downvote count: 2

http://stackoverflow.com/q/51371495
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51373703
tagged with: selenium
upvote count: 1
has answer: http://stackoverflow.com/a/51387974
has answer: http://stackoverflow.com/a/51374428
score: 1
has body: I am trying to click a 'next' button with Selenium in Python, which source code is: Previous Next I use the line: driver.find_element_by_id('experiment-method-next') but I get this error: Unable to locate element: [id="experiment-method-next"] Same for driver.find_element_by_class_name('btn btn-primary pull-right') Unable to locate element: .btn btn-primary pull-right Any thoughts?
type: Question
has comment: http://stackoverflow.com/comment/89725018
tagged with: css-selectors
downvote count: 0
favorite count: 0
answer count: 3
has title: How to locate an element as per the HTML provided through Selenium and Python
tagged with: python
tagged with: selenium-webdriver
tagged with: xpath

counter
tags question: http://stackoverflow.com/q/51380124
tags question: http://stackoverflow.com/q/51416338
tag name: counter
tags question: http://stackoverflow.com/q/51442589
tags question: http://stackoverflow.com/q/51423217
tags question: http://stackoverflow.com/q/51334434
type: Tag

http://stackoverflow.com/comment/89905654
has text: Start by making a function that checks if a list contains two equal elements. Then, once you have that working to satisfaction, you can use a list comprehension.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51468615

http://stackoverflow.com/q/51386150
has comment: http://stackoverflow.com/comment/89773762
has comment: http://stackoverflow.com/comment/89782835
type: Question
has comment: http://stackoverflow.com/comment/89744999
tagged with: wxwidgets
score: 0
has body: I have the following scenario: An application written in C++/Wxwidgets 2.8 and embedded python interpreter. An extension for python made as shared object. These two components shares a few wxwidgets custom events as following DEFINE_LOCAL_EVENT_TYPE(ID_PRE_PROCESS_X_COMMAND); DEFINE_LOCAL_EVENT_TYPE(ID_POST_PROCESS_X_COMMAND); DEFINE_LOCAL_EVENT_TYPE(ID_PRE_PROCESS_Y_COMMAND); DEFINE_LOCAL_EVENT_TYPE(ID_POST_PROCESS_Y_COMMAND); I launch the application and then import the extension module, upon importing the module these event types are updated to have newer IDs. Example : launched app with ID_PRE_PROCESS_X_COMMAND = 10304 importing python extension module, updates ID_PRE_PROCESS_X_COMMAND = 10308 Here is the output of watch point inside GDB on ID_PRE_PROCESS_X_COMMAND #0 __static_initialization_and_destruction_0 (__initialize_p=1, __priority=65535) at Runner.cpp:8 #1 0x00007fffe1ad02d9 in global constructors keyed to Runner.cpp(void) () at Runner.cpp:73 #2 0x00007fffe1b91fe6 in __do_global_ctors_aux () from /path/to/Dependcy.so #3 0x00007fffe1aacb23 in _init () from /path/to/Dependcy.so #4 0x00007fffe1df8888 in ?? () from /path/to/ExtensionModule.so #5 0x00007ffff7deb1e8 in call_init () from /lib64/ld-linux-x86-64.so.2 #6 0x00007ffff7deb317 in _dl_init_internal () from /lib64/ld-linux-x86-64.so.2 #7 0x00007ffff7def636 in dl_open_worker () from /lib64/ld-linux-x86-64.so.2 #8 0x00007ffff7deae76 in _dl_catch_error () from /lib64/ld-linux-x86-64.so.2 #9 0x00007ffff7deee2b in _dl_open () from /lib64/ld-linux-x86-64.so.2 #10 0x00007ffff6017f9b in dlopen_doit () from /lib64/libdl.so.2 #11 0x00007ffff7deae76 in _dl_catch_error () from /lib64/ld-linux-x86-64.so.2 #12 0x00007ffff601833c in _dlerror_run () from /lib64/libdl.so.2 #13 0x00007ffff6017f01 in dlopen@@GLIBC_2.2.5 () from /lib64/libdl.so.2 #14 0x00007ffff6571064 in _PyImport_GetDynLoadFunc (fqname=<optimized out>, shortname=0x7fffe4085d50 "ExtensionModule", pathname=0x7fffe4086d60 "/path/to/ExtensionModule.so", fp=0…
has comment: http://stackoverflow.com/comment/89751875
has comment: http://stackoverflow.com/comment/89782872
has comment: http://stackoverflow.com/comment/89755428
tagged with: python
tagged with: shared-libraries
tagged with: c++
answer count: 0
type: UnansweredQuestion
has title: Python extension object and wx custom events initialization
has comment: http://stackoverflow.com/comment/89769921

http://stackoverflow.com/q/51331093
type: UnansweredQuestion
has title: accessing Putty outputstream with pywinauto
tagged with: python
tagged with: putty
answer count: 0
upvote count: 1
type: Question
has body: I am trying to automate a ssh connection with pywinauto. I am connecting via Putty to my server and can execute commands. However, I need to get the output of the Putty to verify what exactly is going on the server. Below you find my example code so far which I find on stackoverflow: import time import sys app = Application ().Start (cmd_line=u'putty -ssh root@host') putty = app.PuTTY putty.Wait ('ready') time.sleep (1) putty.TypeKeys ("cd{SPACE}/") putty.TypeKeys ("{ENTER}") time.sleep (1) putty.TypeKeys ("ls") putty.TypeKeys ("{ENTER}") I need a function that gives me the outputstream of the putty window. Something like: stream = putty.ReadConsoleOutputStream() lines = stream.readLines() I tried it with: print(putty.window_text()) but it only gives me the title of the window back. I have heard about paramiko but since the connection is passwordless, I couldn't access it via paramiko because i couldn't find a way to connect it without a password. Thank you in advance for your help.
has comment: http://stackoverflow.com/comment/89648124
tagged with: paramiko
downvote count: 0
score: 1
tagged with: pywinauto
favorite count: 0

http://stackoverflow.com/q/51405545
has body: I wrote some tensorflow code in python 3.6. Now I want to run my code on a workstation that uses the Nvidia GPU cloud docker (NGC) to utilize the GPU. Unfortunately the Nvidia docker only supports python 3.5. Thus the main error is the string formatting (f"{}"). Does anyone know a workaround for this problem or do I have to change every string formatting in my code? And does anyone have other problems in mind, when I downgrade my code to 3.5?
tagged with: docker
has title: Workaroubnd for NGC / Nvidia GPU coud
has answer: http://stackoverflow.com/a/51421142
accepted answer: http://stackoverflow.com/a/51421142
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89804405
tagged with: nvidia
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/89782657
type: AnsweredQuestion
tagged with: tensorflow
type: Question

http://stackoverflow.com/q/51333061
has body: I am exploring Linear Regression with Tensorflow. Here is my code from this notebook. import tensorflow as tf import numpy as np learning_rate = 0.01 x_train = np.linspace(-1,1,101) y_train = 2*x_train + np.random.randn(*x_train.shape) * 0.33 X = tf.placeholder("float") Y = tf.placeholder("float") def model(X, w): return tf.multiply(X,w) w = tf.Variable(0.0, name = "weights") training_epochs = 100 y_model = model(X,w) cost = tf.reduce_mean(tf.square(Y-y_model)) train_op = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cost) with tf.Session() as sess: init = tf.global_variables_initializer() sess.run(init) for epoch in range(training_epochs): for (x,y) in zip(x_train,y_train): sess.run(train_op, feed_dict = {X:x, Y: y}) print(sess.run(w)) It tries to minimize a cost function. According to this question's answers, I think tf.reduce_mean() will work like np.mean(). However, every time a pair of (x,y) is fed to the train_op, the weight w seems to update not according to THE pair but to all previous pairs. What is the explanation for that? Is this related to working together with the optimizer?
has comment: http://stackoverflow.com/comment/89641695
score: 1
has comment: http://stackoverflow.com/comment/89641950
has answer: http://stackoverflow.com/a/51333713
linked to: http://stackoverflow.com/q/34236252
has answer: http://stackoverflow.com/a/51333691
upvote count: 1
has comment: http://stackoverflow.com/comment/89642195
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/89642340
type: Question
has comment: http://stackoverflow.com/comment/89642148
has title: Stochastic gradient descent in Tensorflow seems conceptually wrong
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89642064
favorite count: 0
has comment: http://stackoverflow.com/comment/89642690
has comment: http://stackoverflow.com/comment/89642215
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89641803
tagged with: python

http://stackoverflow.com/a/51330877
score: 1
has body: Try a list comprehension: data_list = ['the gamers playing games','higher scores','sports'] result =[' '.join([ps.stem(w) for w in nltk.tokenize.word_tokenize(words)]) for words in data_list]
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51330793
answers question: http://stackoverflow.com/q/51330793

http://stackoverflow.com/a/51327914
type: Answer
has body: You can reindex a bit. from itertools import product # Get rid of that number in the index, not sure why you'd need it df.index = df.index.droplevel(-1) # Add continents to the index df = df.set_index('continent', append=True) # Determine product of indices ids = list(product(df.index.get_level_values(0).unique(), df.index.get_level_values(1).unique())) # Reindex and fill missing with 0 df = df.reindex(ids).fillna(0).reset_index(level=-1) df is now: continent avg_count_country avg_age Male Asia 55.0 5.0 Male Africa 65.0 10.0 Male Europe 75.0 8.0 Male America 0.0 0.0 Female Asia 50.0 7.0 Female Africa 60.0 12.0 Female Europe 70.0 0.0 Female America 0.0 0.0 Transgender Asia 30.0 6.0 Transgender Africa 40.0 11.0 Transgender Europe 0.0 0.0 Transgender America 80.0 10.0 If you want that other numeric index, then you can just do: df.groupby(df.index).cumcount() to number the values in each group.
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51327745
upvote count: 1

http://stackoverflow.com/comment/89781320
comment on: http://stackoverflow.com/q/51404984
type: Comment
type: QuestionComment
score: 0
has text: @wim https://www.tensorflow.org/install/install_linux#InstallingNativePip

http://stackoverflow.com/comment/89813585
score: 0
has text: What about `UsersSerializer.name.field_name` instead of `"name"`?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51416225

http://stackoverflow.com/comment/113919997
score: 0
type: AnswerComment
type: Comment
has text: I am having the same issue as above and cannot reproduce the solution. Maybe I don't understand what you mean by _Make sure to give the user object returned from the ORM instead:_? Here is my similar app set up https://dpaste.com/CF7YLX27P. The error stems from `post = Post(body = form.comment.data, author = user.username)` Kindly, explain why you suggest the change above to fix the error
comment on: http://stackoverflow.com/a/51351965

http://stackoverflow.com/q/51383352
has comment: http://stackoverflow.com/comment/89762089
has comment: http://stackoverflow.com/comment/89762527
has answer: http://stackoverflow.com/a/51398740
has comment: http://stackoverflow.com/comment/89738588
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: css
type: AnsweredQuestion
has body: I wan't to change a css line from python/Flask/Jinja2 in my css file like this: HTML: {{ title }} {{ text }} CSS: .v-align { font-size: 120px; position: relative; top: 50%; -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%); } .marquee { vertical-align: middle; white-space: nowrap; overflow: hidden; box-sizing: border-box; color: "red"; } .marquee p { display: inline-block; padding-left: 100%; animation: marquee 30s linear infinite; } @keyframes marquee { 0% { transform: translate(0, 0); } 100% { transform: translate(-100%, 0); } } I want to replace the 30s by any value when rendering it with python. Python: return render_template("my_html_file.html", text="this is a test!", animation_time="30s") It seems to be impossible to make it in thr CSS file like this: animation: marquee {{ animation_time }} linear infinite; , but maybe I am wrong.
has comment: http://stackoverflow.com/comment/89758318
has answer: http://stackoverflow.com/a/51384354
score: 1
upvote count: 1
tagged with: jinja2
accepted answer: http://stackoverflow.com/a/51398740
has comment: http://stackoverflow.com/comment/89760709
type: Question
has answer: http://stackoverflow.com/a/51383913
has title: Change CSS with python and Flask
possible better answer: http://stackoverflow.com/a/51383913
has comment: http://stackoverflow.com/comment/89762815
answer count: 3
downvote count: 0
tagged with: flask
favorite count: 0

http://stackoverflow.com/a/51439623
score: 0
type: Answer
has body: Ok, here's what I have so far: class LayerCell(rnn_cell_impl.RNNCell): def __init__(self, tf_layer, **kwargs): ''' :param tf_layer: a tensorflow layer, e.g. tf.layers.Conv2D or tf.keras.layers.Conv2D. NOT tf.layers.conv2d !''' self.layer_fn = tf_layer(**kwargs) def __call__(self, inputs, state, scope=None): ''' Every `RNNCell` must implement `call` with the signature `(output, next_state) = call(input, state)`. The optional third input argument, `scope`, is allowed for backwards compatibility purposes; but should be left off for new subclasses.''' return (self.layer_fn(inputs), state) def __str__(self): return "Cell wrapper of " + str(self.layer_fn) def __getattr__(self, attr): '''credits to https://stackoverflow.com/questions/1382871/dynamically-attaching-a-method-to-an-existing-python-object-generated-with-swig/1383646#1383646''' return getattr(self.layer_fn, attr) @property def state_size(self): """size(s) of state(s) used by this cell. It can be represented by an Integer, a TensorShape or a tuple of Integers or TensorShapes. """ return (0,) @property def output_size(self): """Integer or TensorShape: size of outputs produced by this cell.""" # use with caution; could be uninitialized return self.layer_fn.output_shape (Naturally, don't use with recurrent layers because state-keeping will be destroyed.) Seems to work with: tf.layers.Conv2D, tf.keras.layers.Conv2D, tf.keras.layers.Activation, tf.layers.BatchNormalization Does NOT work with: tf.keras.layers.BatchNormalization. At least it failed for me when using it in a tf.while loop; complaining about combining variables from different frames, similar to here. Maybe keras uses tf.Variable() instead of tf.get_variable() ...? Usuage: cell0 = tf.contrib.rnn.ConvLSTMCell(conv_ndims=2, input_shape=[40, 40, 3], output_channels=16, kernel_shape=[5, 5]) cell1 = LayerCell(tf.keras.layers.Conv2D, filters=8, kernel_size=[5, 5], strides=(1, 1), padding='same') cell2 = LayerCell(tf.layers.BatchNormalization, axis=-1) inputs = n…
answers question: http://stackoverflow.com/q/51376396

http://stackoverflow.com/q/51479140
has title: Convert numpy.array object to PIL image object
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89928465
has answer: http://stackoverflow.com/a/56369813
favorite count: 0
has comment: http://stackoverflow.com/comment/89927584
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89926644
has body: I have been trying to convert a numpy array to PIL image using Image.fromarray but it shows the following error. Traceback (most recent call last): File "C:\Users\Shri1008 Saurav Das\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PIL\Image.py", line 2428, in fromarray mode, rawmode = _fromarray_typemap[typekey] KeyError: ((1, 1, 3062), '|u1') During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:/Users/Shri1008 Saurav Das/AppData/Local/Programs/Python/Python36-32/projects/try.py", line 13, in img = Image.fromarray(IMIR) File "C:\Users\Shri1008 Saurav Das\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PIL\Image.py", line 2431, in fromarray raise TypeError("Cannot handle this data type") TypeError: Cannot handle this data type I extracted the matrix from an hdf5 file and converted it to a numpy array. I then did some basic transformations to enhance contrast(most probable reason for error). Here is the code. import tkinter as tk import h5py as hp import numpy as np from PIL import Image, ImageTk hf = hp.File('3RIMG_13JUL2018_0015_L1C_SGP.h5', 'r') IMIR = hf.get('IMG_MIR') IMIR = np.uint8(np.power(np.double(np.array(IMIR)),4)/5000000000) IMIR = np.array(IMIR) root = tk.Tk() img = Image.fromarray(IMIR) photo = ImageTk.PhotoImage(file = img) cv = tk.Canvas(root, width=photo.width(), height=photo.height()) cv.create_image(1,1,anchor="nw",image=photo) I am running Python 3.6 on Windows 10. Please help.
score: 7
accepted answer: http://stackoverflow.com/a/56369813
upvote count: 7
type: Question
tagged with: numpy
tagged with: python-imaging-library

http://stackoverflow.com/q/51415997
has comment: http://stackoverflow.com/comment/89803096
has answer: http://stackoverflow.com/a/51440066
has answer: http://stackoverflow.com/a/51416862
has answer: http://stackoverflow.com/a/51416746
tagged with: python
has answer: http://stackoverflow.com/a/51416192
tagged with: vim
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89803291
possible better answer: http://stackoverflow.com/a/51417962
has body: I have a .pl file that consists of an unstructured header and some specific X Y Z structure. The header has no "." in there. Below you can find a snippet of this file: Header (in total 29 lines) ILINE VRTX 1 545057.78564453125 3800905.201171875 -15000 VRTX 2 545184.49072265625 3800765.451171875 -15000 VRTX 3 545310.91650390625 3800625.970703125 -15000 SEG 1 2 SEG 2 3 ILINE VRTX 136 551295.84606933594 3799015.443359375 -15000 VRTX 137 551293.82849121094 3798841.880859375 -15000 VRTX 138 551290.57849121094 3798661.892578125 -15000 SEG 136 137 SEG 137 138 What I like to achieve is to shift the decimal point of my X and Y values to the left like this: VRTX 1 5450.5778564453125 38009.05201171875 -15000 VRTX 2 5451.8449072265625 38007.65451171875 -15000 VRTX 3 5453.1091650390625 38006.25970703125 -15000 I think that regular expressions could help but I have no experiences in that using Python nor Shell. Any help is appreciated.
has comment: http://stackoverflow.com/comment/89803213
has answer: http://stackoverflow.com/a/51417962
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/89803322
accepted answer: http://stackoverflow.com/a/51416862
has answer: http://stackoverflow.com/a/51416331
answer count: 6
score: 4
has title: shifting decimal point using vim, shell or python
has comment: http://stackoverflow.com/comment/89803154
has comment: http://stackoverflow.com/comment/89803129
downvote count: 0
tagged with: shell
has comment: http://stackoverflow.com/comment/89803339
favorite count: 0

http://stackoverflow.com/a/51412978
downvote count: 0
score: 1
has body: df_final.loc[df_final['ID'] == 1] returns a DataFrame containing the rows where 'ID' == 1, not a boolean value. Since that produces a frame of only the rows you want anyway, just iterate over it using itertuples(): for row in df_final[df_final['ID'] == 1].itertuples(): data = { 'token': 'xxx', 'number': row.number, 'ID':row.ID + row.ID2, 'link':row.URL, } r = requests.post(url,headers=headers,params=data)
accepted answer of: http://stackoverflow.com/q/51412779
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51412779
type: Answer

http://stackoverflow.com/comment/90078800
has text: Oh, I updated my answer. The main part was about creating the dictionary in order to map your dates to degrees.
comment on: http://stackoverflow.com/a/51387831
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89819823
has text: @my_user Edited per your specification.
comment on: http://stackoverflow.com/a/51420564
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51459592
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51459646
accepted answer: http://stackoverflow.com/a/51459646
has title: Merging Batches of 200 Rows into 1 Row Pandas Dataframe
tagged with: dataframe
type: Question
upvote count: 2
answer count: 1
favorite count: 0
tagged with: pandas
tagged with: python
downvote count: 0
has body: Is there a way to merge 200 rows of a pandas dataframe into one row. The dataset consists of million of posts and i'm attempting to train a model on batches (profile level, instead of message level). Image the next three lines are my pandas dataframe ( data['Body][:2] ): line1 = "I'm a beast" line2 = "Ofocurse, that's great" line3 = "Hey John, what's up?" I'm interested in obtain the following output, with the batch variable representing the first row of my batch pandas dataframe ( batch_data['Body][0] ) : batch = "I'm a beast Ofocurse, that's great Hey John, what's up?" Does anyone have any suggestions, or is able to point me in a direction other than concatenating them one by one Kind regards, Sarah

http://stackoverflow.com/comment/89907361
type: Comment
type: QuestionComment
score: 0
has text: are you sure you are using the right name, from installation looks like it has lowercase letter s
comment on: http://stackoverflow.com/q/51469449

http://stackoverflow.com/comment/89679014
comment on: http://stackoverflow.com/q/51353000
type: Comment
has text: @AhmedFathi, if you go to your admin, what do you see in the Post column?
score: 0
type: QuestionComment

http://stackoverflow.com/q/51352470
tagged with: python
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89677703
answer count: 0
has title: Python passing QtDesigner class as dynamic argument to class in external file
type: UnansweredQuestion
tagged with: object
has comment: http://stackoverflow.com/comment/89677859
has comment: http://stackoverflow.com/comment/89677843
has comment: http://stackoverflow.com/comment/89677698
type: Question
has comment: http://stackoverflow.com/comment/89677522
tagged with: class
score: 0
tagged with: qt-designer
has body: I want to be able to pass in any QT class object between two Python classes in separate *.py files. I researched this on-line and within SO before posting. I'm not that skilled in OO or Python. First py file was created in QT_designer (5.11): rs485ConfigMenu with class Ui_rs485ConfigMenu(object), with from PyQt5 import QtCore, QtGui, QtWidgets. Not touching that code. I wrote a second python (python 3.5) file with a class that should accept the Ui_rs485ConfigMenu. I know that the second argument for the class is wrong, but I don't know how to pass in the Ui class for any Ui object as needed (e.g., Ui_menu01 vs. Ui_menu02, etc.). My code for the second, separate python file and its class is: from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * widgetList = [ "QPushButton", "QCheckBox", "QDialogButtonBox", "QLineEdit", "QRadioButton", "QComboBox", "QLabel"] class widgetListMethod( QMainWindow, Ui_menu ): def __init__(self): super( widgetListMethod, self ).__init__() # Ui_mainMenu.__init__(self) # self.setupUi(self) def iterThroughWidgets(self): menuWidgets = {} i = 0 b = self.mainMenuFrame.children() #need general menuFrame name for all menus #need way of checking all instances in widgetList for w in b: flag1 = 0 string0 = str(type(w)) string1 = string0.split("PyQt5.QtWidgets.") string2 = string1[1] string3 = string2.split("'") if not set(string3).isdisjoint(widgetList): widgetText = w.text() labelValue = widgetText.split("_value") if isinstance( w, QLabel ) and len( labelValue ) &gt; 1: #keep only those QLabels that have .value in label i = i + 1 flag1 = 1 elif not isinstance( w, QLabel ): i = i + 1 flag1 = 1 if flag1 == 1: x = w.geometry().x() y = w.geometry().y() menuWidgets[i] = [x, y, widgetText, w ] return menuWidgets Ui code from QtDesigner alone exceeds length for characters of 3000 by another 3000+. Cannot paste Ui and py code. Happy to send on or provide link from safe-site.

http://stackoverflow.com/q/51482598
tagged with: ipywidgets
downvote count: 0
type: Question
has body: I have a class with a list trait that I'd like to use to call a function any time the list is modified. class MyClass(traitlets.HasTraits): MyTrait = traitlets.List([0]*8, minlen=8, maxlen=8) Foo = MyClass() def Bar(change): print(change['new']) Foo.observe(Bar, names='MyTrait') The problem I have is that if I do something like the following, Bar doesn't get called: Foo.MyTrait[0] = 5 If I want Bar to get called, I have to do something like this: MyTraitCopy = Foo.MyTrait.copy() MyTraitCopy[0] = 5 Foo.MyTrait = MyTraitCopy This doesn't seem like the right way to do this. Is there a better way to register a callback to a change in a member of a List trait?
upvote count: 2
has title: Traitlets List won't run callback if the list is modified in-place
answer count: 1
tagged with: jupyter
favorite count: 0
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/51540859
accepted answer: http://stackoverflow.com/a/51540859
tagged with: python
type: AnsweredQuestion
score: 2

http://stackoverflow.com/q/51444101
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: python
tagged with: valueerror
tagged with: conv-neural-network
has answer: http://stackoverflow.com/a/51445383
tagged with: tensorflow
type: Question
has title: ValueError: Cannot feed value of shape
has body: I'm new to Tensorflow and trying to programm a CNN with it. Im watching a tutorial and do exactly, 100% same code, and still get an error message at the end, that says: ValueError: Cannot feed value of shape (100, 10) for Tensor 'y_2:0', which has shape '(?, 1)' from __future__ import absolute_import, division, print_function import tensorflow as tf import numpy as np get_ipython().run_line_magic('matplotlib', 'inline') import matplotlib import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) training_digits, training_labels = mnist.train.next_batch(1000) test_digits, test_labels = mnist.test.next_batch(200) height = 28 width = 28 channels = 1 n_inputs = height * width conv1_feature_maps = 32 conv1_kernel_size = 3 conv1_stride = 1 conv1_pad = "SAME" conv2_feature_maps = 64 conv2_kernel_size = 3 conv2_stride = 2 conv2_pad = "SAME" pool3_feature_maps = conv2_feature_maps n_fullyconn1 = 64 n_outputs = 10 tf.reset_default_graph() X = tf.placeholder(tf.float32, shape=[None, n_inputs], name="X") X_reshaped = tf.reshape(X, shape=[-1, height, width, channels]) y = tf.placeholder(tf.int32, shape=[None], name="y") conv1 = tf.layers.conv2d(X_reshaped, filters=conv1_feature_maps, kernel_size=conv1_kernel_size, strides=conv1_stride, padding=conv1_pad, activation = tf.nn.relu, name="conv1") conv2 = tf.layers.conv2d(conv1, filters=conv2_feature_maps, kernel_size=conv2_kernel_size, strides=conv2_stride, padding=conv2_pad, activation = tf.nn.relu, name="conv2") pool3 = tf.nn.max_pool(conv2, ksize=[1,2,2,1], strides=[1,2,2,1], padding="VALID") pool3_flat = tf.reshape(pool3, shape=[-1,pool3_feature_maps * 7 *7]) fullyconn1 = tf.layers.dense(pool3_flat, n_fullyconn1, activation = tf.nn.relu, name="fc1") logits = tf.layers.dense(fullyconn1, n_outputs, name="output") xentropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits = logits, labels = y) loss = tf.reduce_mean(xentropy) optimiz…

http://stackoverflow.com/q/51415346
downvote count: 0
has comment: http://stackoverflow.com/comment/89825959
tagged with: flac
has body: I want to convert the channel of flac files. Because I'm now using google cloud speech to recognition audio files. I have .Flac files but i can't achieve my goal because that files are encoded in Channel 2. Google doesn't support the Channel '2' flac files. So I have to convert the channel 2 to 1. Is there any API about the covert channel? I want to see some example. Thanks for reading, and here is my code. audio = types.RecognitionAudio(content=content) config = types.RecognitionConfig( encoding='FLAC', sample_rate_hertz=48000, language_code='ko-KR', )
tagged with: channel
tagged with: python
favorite count: 0
answer count: 0
type: UnansweredQuestion
upvote count: 1
has title: Python, convert flac file's channel
score: 1
tagged with: google-speech-api
type: Question

http://stackoverflow.com/q/51479759
accepted answer: http://stackoverflow.com/a/51479984
linked to: http://stackoverflow.com/q/51481747
downvote count: 1
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/51484968
linked to: http://stackoverflow.com/q/38105507
type: Question
score: 20
has comment: http://stackoverflow.com/comment/89928957
has comment: http://stackoverflow.com/comment/89928124
answer count: 6
has title: Is there a difference between : "file.readlines()", "list(file)" and "file.read().splitlines(True)"?
has body: What is the difference between : with open("file.txt", "r") as f: data = list(f) Or : with open("file.txt", "r") as f: data = f.read().splitlines(True) Or : with open("file.txt", "r") as f: data = f.readlines() They seem to produce the exact same output. Is one better (or more pythonic) than the other ?
has answer: http://stackoverflow.com/a/51480083
has answer: http://stackoverflow.com/a/51479984
has answer: http://stackoverflow.com/a/59519749
has answer: http://stackoverflow.com/a/78332325
has answer: http://stackoverflow.com/a/51480333
tagged with: python
possible better answer: http://stackoverflow.com/a/59519749
favorite count: 0
tagged with: readlines
tagged with: file
upvote count: 21

http://stackoverflow.com/q/51344191
has title: Getting posts from both tables?
has comment: http://stackoverflow.com/comment/89663274
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51345110
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89663379
tagged with: django-models
has comment: http://stackoverflow.com/comment/89663258
type: Question
has comment: http://stackoverflow.com/comment/89663419
score: 0
has body: I have 3 tables. User, Post, and Share. Post is a table that contains all posts. Post has a one to many relationship with Share. That being said, the Share table is a table where it indicates which posts a user has shared. Here's the structure of the tables: class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) status = models.CharField(max_length=200) share_count = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) url = models.CharField(max_length=150) class Share(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) shared_at = models.DateTimeField(auto_now_add=True) What I want specifically is a query that gets what posts the user has shared and the posts the user has created. For example, let's say we have the same data: Post table id user status share_count created_at url 1 1 hello 32 2017-06-01 hello 2 2 What's up 22 2017-07-01 whats-up Share table post user shared_at 2 2 2017-07-02 I want a query that will get a user's shared posts + their posts. So let's say I want to do that for user 1. The result should be post 1 and post 2 since the user posted post 1 and also shared post 2 from user 2. I have made this query, but for some reason only the shared posts are shown and not the user's posts as well. How do I make it so that the user's posts are shown with their shared posts? Is it possible to do it in one query? Share.objects.all().select_related('post').filter(user=1)
answer count: 1
has comment: http://stackoverflow.com/comment/89663560
has comment: http://stackoverflow.com/comment/89663544

http://stackoverflow.com/comment/89733978
type: QuestionComment
comment on: http://stackoverflow.com/q/51374423
has text: One 'Special' T for every 10 Ts and one 'ultra special' T for every 100 Ts.
score: 0
type: Comment

http://stackoverflow.com/comment/89727018
type: QuestionComment
has text: `"/usr/bin/google-chrome"` is a path to `google chrome` web browser, not to a [chrome driver](http://chromedriver.chromium.org/getting-started)
score: 0
comment on: http://stackoverflow.com/q/51377574
type: Comment

http://stackoverflow.com/q/51353201
has title: How to build a generator function to accomplish skipping duplicates
has comment: http://stackoverflow.com/comment/89679197
score: -1
has answer: http://stackoverflow.com/a/51353320
has comment: http://stackoverflow.com/comment/89679332
linked to: http://stackoverflow.com/q/1653970
answer count: 3
downvote count: 1
has body: I want to ake a generator function that loops over an input iterable sequence, yielding one element at a time, but skipping duplicates. An example code is below: numbers = [4, 5, 2, 6, 2, 3, 5, 8] nums = unique(numbers) next(nums) 4 next(nums) 5 next(nums) 2 next(nums) 6 next(nums) 3 next(nums) 8 Does anyone ave any ideas why this code is not printing? def unique(iterable): seen = set() for n in iterable: if n not in seen: seen.add(n) yield n numbers = [4, 5, 2, 6, 2, 3, 5, 8] nums = unique(numbers) print(next(nums))
has answer: http://stackoverflow.com/a/51353296
tagged with: unique
has comment: http://stackoverflow.com/comment/89679407
accepted answer: http://stackoverflow.com/a/51353296
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51353217
has comment: http://stackoverflow.com/comment/89679213
has comment: http://stackoverflow.com/comment/89679398
tagged with: python
possible better answer: http://stackoverflow.com/a/51353320
has comment: http://stackoverflow.com/comment/89679250
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/89679368
has comment: http://stackoverflow.com/comment/89679257
has comment: http://stackoverflow.com/comment/89679269
type: Question
has comment: http://stackoverflow.com/comment/89679320

http://stackoverflow.com/q/51372737
tagged with: numpy
has body: I am new to computer vision concepts and I am trying to learn. I have an image of letters and I performed Otsu binarization on the image so that every actual content in the image is changed to the same color (white 255 in my case). Now I want to segment the image into letters. For example, Now I want to loop through this image to get every single character(sub image of each character in it) from it into a separate numpy array or a separate image so that it can be passed to the model I built. Could you please advise on how to achieve this or is there any algorithm ? I thought of looping, but it seems to be time consuming.
type: UnansweredQuestion
tagged with: image-segmentation
score: 3
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89720657
type: Question
has answer: http://stackoverflow.com/a/51378547
has title: How to segment the image using OpenCV python when using otsu binarization
has comment: http://stackoverflow.com/comment/89718797
tagged with: python
upvote count: 3
answer count: 1

http://stackoverflow.com/q/51419701
type: Question
has comment: http://stackoverflow.com/comment/89816418
has title: For loop operation of a Nested list and list
tagged with: python
favorite count: 0
tagged with: python-3.x
has body: G = [100,200,300] I_cel = [[0.1, 0.2,0.3,0.4],[1,2,3,4],[11, 22,33,44]] for i in list(range(len(G))): V_cel.append([]) Iph_g = Iph_cal[i] Icel_g = I_cel[i] for j in Icel_g: a = math.log((Iph_g - j - I_sat)/I_sat,10) - j*R_se V_cel[i].append(a) print(V_cel[0]) ** output is: ValueError: math domain error The arrow point in output is pointed to a = math.log((Iph_g - j - I_sat)/I_sat,10) - j*R_se. Looks like it is the source of some math error. Some help. Everything else is the loop fine when I set a = i*j(to check the whole program) and code executed successfully.
upvote count: 1
answer count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89812878
tagged with: for-loop
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51419934
has comment: http://stackoverflow.com/comment/89813580
has comment: http://stackoverflow.com/comment/89820830

http://stackoverflow.com/comment/89720561
type: Comment
has text: Thanks, that was my last option. I'm gonna go with that then.
comment on: http://stackoverflow.com/a/51365679
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89869391
has text: You could also try with this: `/thumbs/(.*?).jpg`
comment on: http://stackoverflow.com/q/51449402
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/104211370
comment on: http://stackoverflow.com/q/51349736
type: QuestionComment
type: Comment
has text: Are you calling `get_user_model().objects.create_user(...)` within your custom user model??
score: 1

http://stackoverflow.com/comment/89712819
score: 0
comment on: http://stackoverflow.com/q/51370265
has text: Mine is Python3, and I reproduced the error. It acts as if it wants a blank line to terminate the `while` loop. Simple out-denting gets the syntax error. Continuing with another indented statement defers the error until I out-dent.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51713898
answers question: http://stackoverflow.com/q/51467571
downvote count: 0
has body: Reinstalled Anaconda, updated Pycharm, regenerated the CA in Burp and rebooted, it now works. Not sure what was the cause.
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/89826954
score: 3
has text: Please indent your code properly
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51427800

http://stackoverflow.com/q/51389415
type: AnsweredQuestion
upvote count: 2
type: Question
has answer: http://stackoverflow.com/a/51390827
has title: ImportError in dask distributed clients
tagged with: distributed
downvote count: 0
answer count: 1
favorite count: 0
tagged with: dask
accepted answer: http://stackoverflow.com/a/51390827
has body: We have been using dask distributed on a compute cluster for the past few months. Recently we upgraded all our python packages, and now all the dask clients seem to error out with the following message: distributed.nanny - INFO - Start Nanny at: 'tcp://10.38.37.14:40983' Traceback (most recent call last): File "PYTHON_INSTALL_DIR/lib/python3.6/multiprocessing/forkserver.py", line 178, in main _serve_one(s, listener, alive _r, handler) File "PYTHON_INSTALL_DIR/lib/python3.6/multiprocessing/forkserver.py", line 212, in _serve_one code = spawn._main(child_r) File "PYTHON_INSTALL_DIR/lib/python3.6/multiprocessing/spawn.py", line 115, in _main self = reduction.pickle.load(from_parent) ModuleNotFoundError: No module named 'distributed.http' distributed.nanny - WARNING - Worker process 8566 was killed by unknown signal distributed.nanny - WARNING - Restarting worker Any idea what could be causing this issue ? FYI, I am getting this error with the following version of dask related packages: dask-0.18.1 distributed-1.22.0 Thanks
tagged with: python
score: 2

http://stackoverflow.com/q/51336557
has title: Syntax Error generated
favorite count: 0
downvote count: 3
tagged with: python
has answer: http://stackoverflow.com/a/51336597
accepted answer: http://stackoverflow.com/a/51336597
tagged with: jupyter
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89647912
has comment: http://stackoverflow.com/comment/89647907
type: Question
score: -2
has comment: http://stackoverflow.com/comment/89647850
has body: I am a beginner in Python, and I've just started using jupyter notebook. The following piece of code generates syntax error. #Getting Started with Python ##We have done *Installed Python *Started iPython Notebook Error File "&lt;ipython-input-9-34ece10c4b46&gt;", line 4 *Installed Python ^ SyntaxError: invalid syntax What is the problem? How to fix it?
upvote count: 1
answer count: 1

http://stackoverflow.com/q/51438911
has comment: http://stackoverflow.com/comment/89847956
answer count: 2
favorite count: 0
upvote count: 3
score: 0
downvote count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/89847818
tagged with: regex
has body: I do not get it. Why people down vote this without explanation? What mistake I made? How to extract Apple Recipe, 3, pages, 29.4KB from the following string? '\r\n\t\t\t\t\t\r\n\t\t\t\t\tApple Recipe\r\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n \t\t\t\t\t3\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tpages\r\n \t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\r\n \t\t\t\t\t\r\n\t\t\t\t\t\t29.4KB\r\n \t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t' I've tried re.compile('\w+') but can only get results like: Apple Recipe 29 . 4 KB However, I want to get them together as they are, not separately. For example, I want to get Apple Recipe together but not as two separate tokens.
has title: python regex: extract string from escaped sequences
accepted answer: http://stackoverflow.com/a/51439094
type: Question
possible better answer: http://stackoverflow.com/a/51439388
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51439388
has answer: http://stackoverflow.com/a/51439094
has comment: http://stackoverflow.com/comment/89847778

http://stackoverflow.com/comment/89882992
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51456472
has text: @RoryDaulton no you can't except if the algorithm works at the same or greater magnitude of time than the sorting. I will edit the question and add my attempt to solving this.
score: 0

http://stackoverflow.com/q/51326388
has comment: http://stackoverflow.com/comment/89628417
favorite count: 0
accepted answer: http://stackoverflow.com/a/51327217
upvote count: 2
has title: How to find an element dynamically loaded by jQuery in page through Selenium, WebDriver and Python
has comment: http://stackoverflow.com/comment/89627928
tagged with: python
linked to: http://stackoverflow.com/q/50327132
tagged with: selenium-webdriver
type: AnsweredQuestion
score: 1
tagged with: selenium
downvote count: 1
has comment: http://stackoverflow.com/comment/89627944
possible better answer: http://stackoverflow.com/a/51350047
has comment: http://stackoverflow.com/comment/89628563
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51350047
has comment: http://stackoverflow.com/comment/89628976
has answer: http://stackoverflow.com/a/51327217
tagged with: jquery
has comment: http://stackoverflow.com/comment/89628648
has body: I'm having a problem getting an item within a page, this item is loaded after loading the page via ajax or iframe, is there any way to create a condition for the script to wait until the item appear? To exemplify my problem I did the following test: Python: 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 from selenium.common.exceptions import TimeoutException browser = webdriver.Firefox() browser.get("http://localhost/test_time.php") delay = 10 # seconds try: myElem = WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.ID, 'id_2'))) print ("Elememento encontrado") except TimeoutException: print ('Nao foi dessa vez :(') pass I search for id_2 which is displayed 5 seconds after completion of loading the page by JavaScript HTML: Teste Python Main page DIV 1 This is the HTML I have 2 div if you do the search for div id_1 it finds no problem, but the div id_2 which is displayed 5 seconds after page loading is not found by selenium even though I determine the wait time of 10 seconds. I would like a light to find a solution to this problem.
tagged with: css-selectors

http://stackoverflow.com/comment/91334204
type: QuestionComment
has text: This is the official report for this issue: https://github.com/pypa/pipenv/issues/2611
comment on: http://stackoverflow.com/q/51411699
score: 0
type: Comment

http://stackoverflow.com/q/51387255
type: Question
tagged with: date
tagged with: pandas
answer count: 1
linked to: http://stackoverflow.com/q/1060279
favorite count: 0
accepted answer: http://stackoverflow.com/a/51387635
linked to: http://stackoverflow.com/q/30564610
score: -3
has comment: http://stackoverflow.com/comment/89746711
tagged with: python
has body: I have this dataframe: d = {'Region':['And','And'], 'country': ['ES','ES'], 'Date': [01/01/2016,01/01/2017,], 'holiday': [1,1] df = pd.DataFrame(d) I would like to add to the dataframe rows for all dates between those two, with a 0 in holiday and the same region and country as the extremes. I would need to do that for several countries, regions and date gaps of different length.
has title: Fill days between dates with certain conditions in dataframe
has answer: http://stackoverflow.com/a/51387635
type: AnsweredQuestion
upvote count: 0
downvote count: 3

http://stackoverflow.com/q/51388443
type: UnansweredQuestion
has body: I have a string obtained from rendering a Jinja template. In the template I have the absolute path to the css file. For example: &lt;link rel='stylesheet' href="C:\Users\User\project\reports\template\css"&gt; But, when I set the html in QWebEngineView only appear the plain HTML, without CSS. How can I make to detect the css reference? This is my code class WidgetEdificioCirsoc(QtWidgets.QWidget): def __init__(self): super().__init__() self._tab_edificio = widgets.TabEdificio() self._webview = QtWebEngineWidgets.QWebEngineView() layout_horizontal_principal = QtWidgets.QHBoxLayout() layout_horizontal_principal.addWidget(self._tab_edificio) layout_horizontal_principal.addWidget(self._webview) self.setLayout(layout_horizontal_principal) def calcular(self): edificio = self._tab_edificio() reporte = edificio.reporte.html() # Generate the string self._webview.setHtml(reporte) # Set the string
tagged with: python
has comment: http://stackoverflow.com/comment/116330947
upvote count: 2
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/89748948
type: Question
has comment: http://stackoverflow.com/comment/89772116
has comment: http://stackoverflow.com/comment/89772015
tagged with: qwebengineview
has comment: http://stackoverflow.com/comment/89753049
has answer: http://stackoverflow.com/a/51389886
score: 2
tagged with: pyqt
has comment: http://stackoverflow.com/comment/89748833
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89769699
has title: CSS doesn't work in QWebEngineView.setHtml()
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/89705794
type: AnswerComment
comment on: http://stackoverflow.com/a/51366482
type: Comment
has text: Okay i have a second question, how can i change the looks of the popup window? Like make it fit the text or other cosmetics
score: 0

http://stackoverflow.com/comment/89816254
type: Comment
comment on: http://stackoverflow.com/q/51422591
type: QuestionComment
has text: No it is not executing because it does not do what it should be doing
score: 0

timer
tag name: timer
type: Tag
tags question: http://stackoverflow.com/q/51462749

http://stackoverflow.com/comment/90661155
type: QuestionComment
has text: Hi, Sorry for the late reply. I found hygull and cosmic_inquiry's answers are useful. Couldn't try the below answers though. Their answers are also seem reasonable, too. If you are willing to try them, it would be very great if you update me the results. Very thanks and have a wonderful day :)
type: Comment
comment on: http://stackoverflow.com/q/51345024
score: 0

numpy
tags question: http://stackoverflow.com/q/51387915
tags question: http://stackoverflow.com/q/51360599
tags question: http://stackoverflow.com/q/51394993
tags question: http://stackoverflow.com/q/51456397
tags question: http://stackoverflow.com/q/51387195
tags question: http://stackoverflow.com/q/51480238
tags question: http://stackoverflow.com/q/51362331
tags question: http://stackoverflow.com/q/51330239
tags question: http://stackoverflow.com/q/51397389
tags question: http://stackoverflow.com/q/51455805
tags question: http://stackoverflow.com/q/51326574
tags question: http://stackoverflow.com/q/51436036
tags question: http://stackoverflow.com/q/51381112
tags question: http://stackoverflow.com/q/51349738
tags question: http://stackoverflow.com/q/51461762
tags question: http://stackoverflow.com/q/51411388
tags question: http://stackoverflow.com/q/51368902
tags question: http://stackoverflow.com/q/51419122
tags question: http://stackoverflow.com/q/51413076
tags question: http://stackoverflow.com/q/51432666
tags question: http://stackoverflow.com/q/51473387
tags question: http://stackoverflow.com/q/51461337
tags question: http://stackoverflow.com/q/51371902
tags question: http://stackoverflow.com/q/51346630
tags question: http://stackoverflow.com/q/51457734
tags question: http://stackoverflow.com/q/51466808
tags question: http://stackoverflow.com/q/51478920
tags question: http://stackoverflow.com/q/51410665
tags question: http://stackoverflow.com/q/51445617
tags question: http://stackoverflow.com/q/51391713
tags question: http://stackoverflow.com/q/51374423
tags question: http://stackoverflow.com/q/51372009
tags question: http://stackoverflow.com/q/51328718
tags question: http://stackoverflow.com/q/51325424
tags question: http://stackoverflow.com/q/51413245
tags question: http://stackoverflow.com/q/51332319
tags question: http://stackoverflow.com/q/51431160
tags question: http://stackoverflow.com/q/51463911
tags question: http://stackoverflow.com/q/51327767
tags question: http://stackoverflow.com/q/51364320
tags question: http://stackoverflow.com/q/51354466
tags question: http://stackoverflow.com/q/51358324
tags question: http://stackoverflow.com/q/51427180
tags question: http://stackoverflow.com/q/51354526
tags question: http://stackoverflow.com/q/51440840
tags question: http://stackoverflow.com/q/51471097
tags question: http://stackoverflow.com/q/51408675
tags question: http://stackoverflow.com/q/51461298
tags question: http://stackoverflow.com/q/51425552
tags question: http://stackoverflow.com/q/51462787
tags question: http://stackoverflow.com/q/51345105
tags question: http://stackoverflow.com/q/51371070
tags question: http://stackoverflow.com/q/51370484
tags question: http://stackoverflow.com/q/51342354
tags question: http://stackoverflow.com/q/51325979
tags question: http://stackoverflow.com/q/51431380
tags question: http://stackoverflow.com/q/51401832
tags question: http://stackoverflow.com/q/51365660
tags question: http://stackoverflow.com/q/51355151
tags question: http://stackoverflow.com/q/51451400
tags question: http://stackoverflow.com/q/51424857
tags question: http://stackoverflow.com/q/51332325
tags question: http://stackoverflow.com/q/51466137
tags question: http://stackoverflow.com/q/51366648
tags question: http://stackoverflow.com/q/51475114
tags question: http://stackoverflow.com/q/51410742
tags question: http://stackoverflow.com/q/51328373
tags question: http://stackoverflow.com/q/51418002
tags question: http://stackoverflow.com/q/51466553
tags question: http://stackoverflow.com/q/51449039
tags question: http://stackoverflow.com/q/51335766
tags question: http://stackoverflow.com/q/51420951
tags question: http://stackoverflow.com/q/51418152
tags question: http://stackoverflow.com/q/51425642
tags question: http://stackoverflow.com/q/51412973
tags question: http://stackoverflow.com/q/51366329
tags question: http://stackoverflow.com/q/51401118
tags question: http://stackoverflow.com/q/51444630
tags question: http://stackoverflow.com/q/51351059
tags question: http://stackoverflow.com/q/51327332

http://stackoverflow.com/comment/89713277
type: Comment
score: 1
has text: Yes, it's correct and my function don't have incoming argument I fix it in my question and now it's working good
type: AnswerComment
comment on: http://stackoverflow.com/a/51370499

http://stackoverflow.com/a/51633176
answers question: http://stackoverflow.com/q/51345135
has body: Thanks Mike, The error goes away, after I added: if __name__ == '__main__' Before calling: pool = Pool().imap REF: RuntimeError on windows trying python multiprocessing
score: 0
type: Answer

http://stackoverflow.com/a/51400717
answers question: http://stackoverflow.com/q/51399804
score: 1
upvote count: 1
has body: To handle the query parameters (the part after the question mark ?) use request.GET, which behaves like a python dictionary. In your case, ?search=id will result in request.GET containing {'search': 'id'}. You could use something along the lines of the following code: urlpatterns = [ path('', app_views.contract, name='my_contract'), ] def view_contract(request): search_value = request.GET.get('search', '') # do something if it meets certain conditions if search_value == 'id': # here you could do your redirect if its still needed return redirect('...') return render(request, 'template_name.html', {'search': search_value})
downvote count: 0
type: Answer

http://stackoverflow.com/a/51344741
answers question: http://stackoverflow.com/q/51344717
has body: Since this is running on a Raspberry Pi, I assume you're using systemd. You need the correct dependencies to tell systemd that your script needs MySQL to be running. From https://serverfault.com/questions/482730/systemd-dependencies-and-boot-order#725684 After=dirsrv.target - Will ensure the smb.service is started after dirsrv.target. In this case, you probably want something like 'After=mysqld.targetor whatever Raspbian'ssystemd` calls MySQL this week. If you're using SysV init, which it appears you are, even though that is uncommon on a Raspberry Pi, make sure your init script launches after MySQL does. For example, if MySQL is launched from /etc/init.d/rc2.d/S45mysql or /etc/rc2.d/S45mysql, place or symlink your script in the same directory/directories as S45mysql, with the name S46query_mysql. By starting with S46, it will run after all of the scripts whose names start with S45 have finished. If you have other dependencies, number your script after the last of them. That is, if you depend upon, as in my example, S45mysql, but also S55httpd and S86tomcat (all of these being made-up examples), your script's name or symlink should start with S87 or higher.
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/89662790

http://stackoverflow.com/q/51353000
favorite count: 0
has comment: http://stackoverflow.com/comment/89678979
has comment: http://stackoverflow.com/comment/89678601
tagged with: django-templates
upvote count: 2
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89678583
has comment: http://stackoverflow.com/comment/89679014
downvote count: 1
has title: Django 1.11: Error during template rendering , __str__ returned non-string (type NoneType)
has answer: http://stackoverflow.com/a/63294807
score: 1
has comment: http://stackoverflow.com/comment/89678658
has comment: http://stackoverflow.com/comment/89679137
type: Question
has comment: http://stackoverflow.com/comment/89678997
has comment: http://stackoverflow.com/comment/89678562
answer count: 1
has body: Django Version: 1.11 Python Version: 3.5 I am trying to follow a Django tutorial and I have a problem that I can not solve, I can not remove this error Exception Type: TypeError at /posts/new/ Exception Value: __ str__ returned non-string (type NoneType) the traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/posts/new/ Django Version: 1.11 Python Version: 3.6.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'bootstrap3', 'accounts', 'groups', 'posts'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template E:\Private\django_project\social_clone\simplesocial\templates \base.html, error at line 10 __str__ returned non-string (type NoneType) 1 : 2 : {% load staticfiles %} 3 : 4 : 5 : 6 : Egy Social 7 : 8 : 9 : 10 : 11 : 12 : 13 : 14 : 15 : 16 : 17 : 18 : 19 : 20 : Traceback: File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\core\handlers\exception.py" in inner 41.response = get_response(request) File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\core\handlers\base.py" in _get_response 217.response = self.process_exception_by_middleware(e, request) File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\core\handlers\base.py" in _get_response 215. response = response.render() File "C:\Users\Ahmed-Fathi\Anaconda2\envs\myDjangoEnv\lib\site-packages\django\template\response.py" in render 107. self.content = self.rendered_content File "C:\Users\Ahme…

http://stackoverflow.com/comment/89749477
type: QuestionComment
score: 0
has text: I actually just had a friend look it over and he pointed out the problem. I named the button the same name as the function it calls to. I changed the button name to self.replay_button1 and it fixed.
comment on: http://stackoverflow.com/q/51388712
type: Comment

executable
tags question: http://stackoverflow.com/q/51372094
tags question: http://stackoverflow.com/q/51377550
tag name: executable
type: Tag
tags question: http://stackoverflow.com/q/51369821
tags question: http://stackoverflow.com/q/51429740
tags question: http://stackoverflow.com/q/51390207

http://stackoverflow.com/q/51463058
linked to: http://stackoverflow.com/q/3136689
tagged with: python
type: AnsweredQuestion
upvote count: 0
has title: Iterate through list of strings and replace certain characters
type: Question
score: -1
duplicate of: http://stackoverflow.com/q/3136689
downvote count: 1
answer count: 1
tagged with: string
has answer: http://stackoverflow.com/a/51463066
favorite count: 0
accepted answer: http://stackoverflow.com/a/51463066
tagged with: python-3.x
has body: I have a list of string in python. header_row = ['column 1', 'column 2', 'column 3'] I want to replace the empty space with underscore. The converted list will look like this; converted_header_row = ['column_1', 'column_2', 'column_3'] The conversion can be done individually with the line below; mystring.replace(" ", "_") How do I iterate this replacement operation through all the strings in the list? I welcome any other method to do the conversion. I am using python v3.6

dataframe
tags question: http://stackoverflow.com/q/51443725
tags question: http://stackoverflow.com/q/51414404
tags question: http://stackoverflow.com/q/51378412
tags question: http://stackoverflow.com/q/51354996
tags question: http://stackoverflow.com/q/51382266
tags question: http://stackoverflow.com/q/51437954
tags question: http://stackoverflow.com/q/51408873
tags question: http://stackoverflow.com/q/51465663
tags question: http://stackoverflow.com/q/51480694
tags question: http://stackoverflow.com/q/51344674
tags question: http://stackoverflow.com/q/51342788
tags question: http://stackoverflow.com/q/51469336
tags question: http://stackoverflow.com/q/51442688
tags question: http://stackoverflow.com/q/51338508
tags question: http://stackoverflow.com/q/51364764
tags question: http://stackoverflow.com/q/51343512
tags question: http://stackoverflow.com/q/51356152
tags question: http://stackoverflow.com/q/51344660
tags question: http://stackoverflow.com/q/51357253
tags question: http://stackoverflow.com/q/51394906
tags question: http://stackoverflow.com/q/51374595
tags question: http://stackoverflow.com/q/51358293
tags question: http://stackoverflow.com/q/51392944
tags question: http://stackoverflow.com/q/51420768
tags question: http://stackoverflow.com/q/51391438
tags question: http://stackoverflow.com/q/51383773
tags question: http://stackoverflow.com/q/51372462
tags question: http://stackoverflow.com/q/51338087
tags question: http://stackoverflow.com/q/51346750
tags question: http://stackoverflow.com/q/51401832
tags question: http://stackoverflow.com/q/51335085
tags question: http://stackoverflow.com/q/51368733
tags question: http://stackoverflow.com/q/51363075
tags question: http://stackoverflow.com/q/51473273
tags question: http://stackoverflow.com/q/51347828
tags question: http://stackoverflow.com/q/51453809
tags question: http://stackoverflow.com/q/51457474
tags question: http://stackoverflow.com/q/51371819
tags question: http://stackoverflow.com/q/51466042
tags question: http://stackoverflow.com/q/51432641
tags question: http://stackoverflow.com/q/51343370
tags question: http://stackoverflow.com/q/51334836
tags question: http://stackoverflow.com/q/51410486
tags question: http://stackoverflow.com/q/51454544
tags question: http://stackoverflow.com/q/51391315
tags question: http://stackoverflow.com/q/51480105
tags question: http://stackoverflow.com/q/51459592
tags question: http://stackoverflow.com/q/51348759
tags question: http://stackoverflow.com/q/51439245
tags question: http://stackoverflow.com/q/51358770
tags question: http://stackoverflow.com/q/51429786
tags question: http://stackoverflow.com/q/51401962
tags question: http://stackoverflow.com/q/51327745
tags question: http://stackoverflow.com/q/51342473
tags question: http://stackoverflow.com/q/51468969
tags question: http://stackoverflow.com/q/51452279
tags question: http://stackoverflow.com/q/51329510
tags question: http://stackoverflow.com/q/51329666
tags question: http://stackoverflow.com/q/51383673
tags question: http://stackoverflow.com/q/51428216
tags question: http://stackoverflow.com/q/51341162
tags question: http://stackoverflow.com/q/51417242
tags question: http://stackoverflow.com/q/51351718
tags question: http://stackoverflow.com/q/51481489
tags question: http://stackoverflow.com/q/51459663
tags question: http://stackoverflow.com/q/51408351
tags question: http://stackoverflow.com/q/51367776
tags question: http://stackoverflow.com/q/51481521
tags question: http://stackoverflow.com/q/51425202
tags question: http://stackoverflow.com/q/51328454
tags question: http://stackoverflow.com/q/51476060
tags question: http://stackoverflow.com/q/51379938
tags question: http://stackoverflow.com/q/51371734
tags question: http://stackoverflow.com/q/51363230
tags question: http://stackoverflow.com/q/51473833
tags question: http://stackoverflow.com/q/51444091
tags question: http://stackoverflow.com/q/51366189
tags question: http://stackoverflow.com/q/51366217
tags question: http://stackoverflow.com/q/51344681
tags question: http://stackoverflow.com/q/51415395

http://stackoverflow.com/comment/89845556
score: 0
has text: Please post how your dataframes look like after point 1 as you said that this is done and show the code how you tried to solve point 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51437549

http://stackoverflow.com/comment/89721639
score: 0
has text: I don't know what "Mamp mysql phpadmin" means. But `brew install mysql` just installs one copy of MySQL, into `Cellar/mysql`, and then puts a bunch of symlinks into `/usr/local/bin` that link to that Cellar.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51374762

http://stackoverflow.com/a/51482042
upvote count: 3
has comment: http://stackoverflow.com/comment/89932907
has comment: http://stackoverflow.com/comment/89937195
has body: Question 1: So, for the targets, you need it shaped as (batch_size, time_steps, 1). Just use: y_train = np.stack([y_train]*time_steps, axis=1) Question 2: You're correct, but TimeDistributed is optional in Keras 2. Question 3: I don't know how class weights will behave, but a regular loss function should go like: from keras.losses import binary_crossentropy def target_replication_loss(alpha): def inner_loss(true,pred): losses = binary_crossentropy(true,pred) return (alpha*K.mean(losses[:,:-1], axis=-1)) + ((1-alpha)*losses[:,-1]) return inner_loss model.compile(......, loss = target_replication_loss(alpha), ...) Question 3a: Since the above doens't work well with class weights, I created an alternative where the weights go into the loss: def target_replication_loss(alpha, class_weights): def get_weights(x): b = class_weights[0] a = class_weights[1] - b return (a*x) + b def inner_loss(true,pred): #this will only work for classification with only one class 0 or 1 #and only if the target is the same for all classes true_classes = true[:,-1,0] weights = get_weights(true_classes) losses = binary_crossentropy(true,pred) return weights*((alpha*K.mean(losses[:,:-1], axis=-1)) + ((1-alpha)*losses[:,-1])) return inner_loss Question 4: To avoid complexity, I'd say you should use an additional metric in validation: def last_step_BC(true,pred): return binary_crossentropy(true[:,-1], pred[:,-1]) model.compile(...., loss = target_replication_loss(alpha), metrics=[last_step_BC]) Question 5: This is a hard one and I'd need to research a little.... As an initial workaround, you can set the model with an input shape of (None, features), and train each sequence individually. Working example without class_weight def target_replication_loss(alpha): def inner_loss(true,pred): losses = binary_crossentropy(true,pred) #print(K.int_shape(losses)) #print(K.int_shape(losses[:,:-1])) #print(K.int_shape(K.mean(losses[:,:-1], axis=-1))) #print(K.int_shape(losses[:,-1])) return (alpha*K.mean(losses…
type: Answer
accepted answer of: http://stackoverflow.com/q/51481676
answers question: http://stackoverflow.com/q/51481676
has comment: http://stackoverflow.com/comment/89935153
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/89932936
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89936548

http://stackoverflow.com/a/51410872
has comment: http://stackoverflow.com/comment/89841205
upvote count: 2
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/51410508
answers question: http://stackoverflow.com/q/51410508
has comment: http://stackoverflow.com/comment/89862440
has body: Given that your data is in a pd.DataFrame called df, the following should do the trick: import pandas as pd import numpy as np step = 5 df.groupby(pd.cut(df.index, np.arange(start=df.index.min(), stop=df.index.max(), step=step, dtype=float)))\ .agg({'volume':['mean', 'std'], 'temperature':['mean']}) We are using pd.cut to create an IntervalIndex which we can groupby. Finally we use pd.DataFrame.agg to calculate summary statistics for each group; mean and std for the volume column and just mean for the temperature column. I haven't tested this but if you provide a minimal, complete and verifiable example, I can do that. EDIT Given the updated data, I have written the code below: In [1]: import pandas as pd In [2]: import numpy as np In [3]: from io import StringIO In [4]: s = """T,H,L,C,label ...: 1000.1,23.18,27.272,426,1 ...: 1000.2,23.15,27.2675,429.5,1 ...: 1000.3,23.15,27.245,426,1 ...: 1000.4,23.15,27.2,426,1 ...: 1000.5,23.1,27.2,426,1 ...: 1000.6,23.1,27.2,419,1 ...: 1000.7,23.1,27.2,419,1 ...: 1000.8,23.1,27.2,419,1 ...: 1000.9,23.1,27.2,419,1 ...: 1001,23.075,27.175,419,1 ...: 1001.1,23.075,27.15,419,1 ...: 1001.2,23.1,27.1,419,1 ...: 1001.3,23.1,27.16666667,419,1 ...: 1001.4,23.05,27.15,419,1 ...: 1001.5,23,27.125,419,1 ...: 1001.6,23,27.125,418.5,1 ...: 1001.7,23,27.2,0,0 ...: 1001.8,22.945,27.29,0,0 ...: 1001.9,22.945,27.39,0,0 ...: 1002,22.89,27.39,0,0 ...: 1002.1,22.89,27.39,0,0 ...: 1002.2,22.89,27.39,0,0 ...: 1002.3,22.89,27.445,0,0""" In [5]: df = pd.read_csv(StringIO(s), index_col='T') Again we use an IntervalIndex and groupby, as well as agg to calculate summary statistics. In [6]: step = 0.5 ...: ...: grouped = df.groupby(pd.cut(df.index, ...: np.arange(start=df.index.min(), stop=df.index.max(), step=step, dtype=float ...: ))) ...: In [7]: grouped.agg({'H':['mean', 'std'], 'L':['mean', 'std'], 'C':['mean', 'std']}) Out[7]: H L C mean std mean std mean std (1000.1, 1000.6] 23.130 0.027386 27.222500 0.031820 425.3 3.834058 (1000.6, 1001.1] 23.090 0…
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/89912942
type: QuestionComment
has text: Timezone is exacly the same :( But database is different, I have mysql on the server and sqlite locally
comment on: http://stackoverflow.com/q/51472151
score: 0
type: Comment

http://stackoverflow.com/comment/90702350
score: 0
type: Comment
type: QuestionComment
has text: Also please provide the updates here.
comment on: http://stackoverflow.com/q/51457401

http://stackoverflow.com/q/51386610
tagged with: python
has body: Using Textfsm I am attempting to get the output for : Name: Valid from: Valid to: I think the problem is the location in my template to search after == [ Fortinet_CA_SSL ] but would love some help. Output: == [ Fortinet_CA_SSL ] Name: Fortinet_CA_SSL Subject: C = US, ST = California, L = Sunnyvale, O = Fortinet, OU = Certificate Authority, CN = FG200D3913804332, emailAddress = support@fortinet.com Issuer: C = US, ST = California, L = Sunnyvale, O = Fortinet, OU = Certificate Authority, CN = FG200D3913804332, emailAddress = support@fortinet.com Valid from: 2018-02-08 16:43:27 GMT Valid to: 2028-02-09 16:43:27 GMT Fingerprint: 78:DA:31:59:9D:A6:D7:98:79:51:1F:EE:0E:C0:C6:45 Serial Num: 25:4d:55:ca:b8:e6:b5:54 Template: Value Name (\S*) Value Valid_from (\S*) Value Valid_to (\S*) Start ^Name: ${Name} ^Valid from: ${Valid_from} ^Valid to: ${Valid_to}
has answer: http://stackoverflow.com/a/51387525
has title: Python - Textfsm - Fortigate - Parse Name:, Valid from:, Valid to:
tagged with: python-textfsm
type: Question
score: 0
answer count: 1
type: UnansweredQuestion

http://stackoverflow.com/a/51525325
score: 1
accepted answer of: http://stackoverflow.com/q/51461102
answers question: http://stackoverflow.com/q/51461102
has body: You cannot have return inside a loop and expect the loop the work def f(): for i in range(100): return i f() # &gt;&gt;&gt; 0 Your page and route need to by reactive, so pass the current the step number to the page as a render argument: render_template("add_step.html", form=form, step=steps) and then pass back that number to the add step route and an input argument and remove your inner loop that doesn't work: @app.route("/new_step/&lt;int:project_id&gt;/&lt;int:step&gt;", methods=("POST", "GET")) @login_required def add_step(project_id, step): You will need to update your form action html link to include the step
upvote count: 1
has comment: http://stackoverflow.com/comment/90469816
has comment: http://stackoverflow.com/comment/90469987
type: AcceptedAnswer
type: Answer
downvote count: 0

http://stackoverflow.com/q/51331053
type: Question
has title: Run a Principal Component Analysis (PCA) on the dataset to reduce the number of features (components) from 64 to 2
has answer: http://stackoverflow.com/a/51331237
tagged with: pandas
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89637987
tagged with: scikit-learn
favorite count: 0
has body: I'm trying to reduce my components to 2 instead of 64 but I keep getting this error: "Length mismatch: Expected axis has 64 elements, new values have 4 elements" Why is the PCA I'm running on the data set not changing the number to 2? This is what I have: import matplotlib.pyplot as plt from sklearn import datasets from sklearn.cluster import KMeans import sklearn.metrics as sm import pandas as pd import numpy as np import scipy from sklearn import decomposition digits = datasets.load_digits() #load the digits dataset instead of the iris dataset x = pd.DataFrame(digits.data) #was(iris.data) x.columns = ['Sepal_L', 'Sepal_W', 'Sepal_L', 'Sepal_W'] plt.cla() pca = decomposition.PCA(n_components=2) pca.fit(x) x = pca.transform(x) y = pd.DataFrame(digits.target) y.columns = ['Targets'] # this line actually builds the machine learning model and runs the algorithm # on the dataset model = KMeans(n_clusters = 10) #Run k-means on this datatset to cluster the data into 10 classes model.fit(x) #print(model.labels_) colormap = np.array(['red', 'blue', 'yellow', 'black']) # Plot the Models Classifications plt.subplot(1, 2, 2) plt.scatter(x.Petal_L, x.Petal_W, c=colormap[model.labels_], s=40) plt.title('K Means Classification') plt.show()
accepted answer: http://stackoverflow.com/a/51331237
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/89638120
type: AnsweredQuestion
downvote count: 2
tagged with: scipy

http://stackoverflow.com/a/51427744
downvote count: 0
has body: You can use a conditional in a list comprehension to get only those lines that contain the pattern: pattern = '251212' matching_lines = [line for line in open('file.txt').readlines() if pattern in line] print(matching_lines) How it works: open('file.txt') opens the text file; .readlines() reads all lines in the file and results in a list of strings, with each string being a line in the file; finally, [line for line in open('file.txt').readlines() if pattern in line] will select only those lines that contain the pattern.
type: Answer
has comment: http://stackoverflow.com/comment/89827088
answers question: http://stackoverflow.com/q/51427543
upvote count: 1
has comment: http://stackoverflow.com/comment/89826760
score: 1

http://stackoverflow.com/comment/89714659
type: QuestionComment
comment on: http://stackoverflow.com/q/51371024
has text: Thanks for clarification. You could implement this as a priority queue of stacks. That is, each element in the priority queue is a stack of items with the same priority.
score: 1
type: Comment

sparse-matrix
tags question: http://stackoverflow.com/q/51413016
tag name: sparse-matrix
tags question: http://stackoverflow.com/q/51469825
tags question: http://stackoverflow.com/q/51385657
tags question: http://stackoverflow.com/q/51479586
tags question: http://stackoverflow.com/q/51476588
tags question: http://stackoverflow.com/q/51327235
tags question: http://stackoverflow.com/q/51422840
type: Tag
tags question: http://stackoverflow.com/q/51407237

http://stackoverflow.com/comment/89798147
comment on: http://stackoverflow.com/q/51413186
has text: I got what you are asking. I'll try to simplify and post it again!! Thankyou
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51465737
score: 1
has comment: http://stackoverflow.com/comment/89901470
has body: To get NumPy to return a diagonal array of real eigenvalues when the complex part is small, you could use In [116]: np.real_if_close(np.diag(w)) Out[116]: array([[ 4., 0., 0.], [ 0., -2., 0.], [ 0., 0., -2.]]) According to the Matlab docs, [E, D] = eig(A) returns E and D which satisfy A*E = E*D: I don't have Matlab, so I'll use Octave to check the result you posted: octave:1&gt; A = [[1, -3, 3], [3, -5, 3], [6, -6, 4]] octave:6&gt; E = [[ -0.4082, -0.8103, 0.1933], [ -0.4082, -0.3185, -0.5904], [ -0.8165, 0.4918, -0.7836]] octave:25&gt; D = [[4.0000, 0, 0], [0, -2.0000, 0], [0, 0, -2.0000]] octave:29&gt; abs(A*E - E*D) ans = 3.0000e-04 0.0000e+00 3.0000e-04 3.0000e-04 2.2204e-16 3.0000e-04 0.0000e+00 4.4409e-16 6.0000e-04 The magnitude of the errors is mainly due to the values reported by Matlab being displayed to a lower precision than the actual values Matlab holds in memory. In NumPy, w, v = np.linalg.eig(A) returns w and v which satisfy np.dot(A, v) = np.dot(v, np.diag(w)): In [113]: w, v = np.linalg.eig(A) In [135]: np.set_printoptions(formatter={'complex_kind': '{:+15.5f}'.format}) In [136]: v Out[136]: array([[-0.40825+0.00000j, +0.24400-0.40702j, +0.24400+0.40702j], [-0.40825+0.00000j, -0.41622-0.40702j, -0.41622+0.40702j], [-0.81650+0.00000j, -0.66022+0.00000j, -0.66022-0.00000j]]) In [116]: np.real_if_close(np.diag(w)) Out[116]: array([[ 4., 0., 0.], [ 0., -2., 0.], [ 0., 0., -2.]]) In [112]: np.abs((np.dot(A, v) - np.dot(v, np.diag(w)))) Out[112]: array([[4.44089210e-16, 3.72380123e-16, 3.72380123e-16], [2.22044605e-16, 4.00296604e-16, 4.00296604e-16], [8.88178420e-16, 1.36245817e-15, 1.36245817e-15]]) In [162]: np.abs((np.dot(A, v) - np.dot(v, np.diag(w)))).max() Out[162]: 1.3624581677742195e-15 In [109]: np.isclose(np.dot(A, v), np.dot(v, np.diag(w))).all() Out[109]: True
answers question: http://stackoverflow.com/q/51465229
upvote count: 1
has comment: http://stackoverflow.com/comment/89901120
type: Answer
has comment: http://stackoverflow.com/comment/89902660
downvote count: 0

http://stackoverflow.com/comment/89658184
comment on: http://stackoverflow.com/q/51338541
score: 0
type: Comment
type: QuestionComment
has text: @JamesPhillips I am the worst... sorry. I added all the code in the question. Moreover if you look in the `edit` you will see a link to the original dataset (the previous link I had was to an already altered version) and a link to a google doc containing a transcript of my jupyter notebook which contains comments about the procedure. Sorry again for the failed attempt and thank you for your time!

http://stackoverflow.com/q/51435258
type: Question
score: 0
tagged with: time-series
answer count: 1
tagged with: scatter-plot
has title: Multi color -Time series scatter plot in python
accepted answer: http://stackoverflow.com/a/51435426
tagged with: python
linked to: http://stackoverflow.com/q/51471241
has body: I'm a newbie to python. I have time series data for which I need a scatter plot. I basically want the normal and abnormal tags to have different colors. See below images of the data and plot: Actual data Expected rearrangement in Data Expected Plot I'll be very thankful for any leads in this! Thanks in advance!
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51435426

http://stackoverflow.com/comment/89929241
has text: @9769953 Relative values
comment on: http://stackoverflow.com/q/51480238
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89630231
type: Comment
type: QuestionComment
has text: You write `urlpatterns` in `views.py`?
comment on: http://stackoverflow.com/q/51327457
score: 0

http://stackoverflow.com/comment/89762333
comment on: http://stackoverflow.com/q/51394990
score: 0
type: Comment
type: QuestionComment
has text: what do you mean create a record?

http://stackoverflow.com/comment/89800180
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51413483
has text: Can you do it *this* time? As a maintainer of Bokeh, having unanswered questions on SO is actually a burden for me and others. It will only take you a few moments to post a proper answer, and it will help other users.
type: Comment

http://stackoverflow.com/q/51418913
has body: I would need to insert variables for the input file in a 'with' function while reading/writing in it. Here is the part of code that I am currently interested in: import argparse parser=argparse.ArgumentParser(description="My script") parser.add_argument('-i','--input',help='Input log file name',required=True) parser.add_argument('-o','--output',help='Desired name for the Excel file',required=True) parser.add_argument('-s','--sheet',help='Desired name of the Excel sheet(Default: Sheet1)',default='Sheet1',required=False) args=parser.parse_args() with open('%s',%args.input, 'r') as file : filedata = file.read() filedata = filedata.replace('destination', 'destination xxx') with open('%s',%args.input, 'w') as file: file.write(filedata) '%s',%args.input, 'r' is not valid, but I would need something that does this thing. The same for 'w'. Any ways for a workaround? Many thanks, Romain
has comment: http://stackoverflow.com/comment/89809012
type: Question
accepted answer: http://stackoverflow.com/a/51419032
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/51419032
answer count: 1
tagged with: args
has title: Arg parse inside with Python 2.7
has comment: http://stackoverflow.com/comment/89808938
tagged with: python
has comment: http://stackoverflow.com/comment/89808856
type: AnsweredQuestion

http://stackoverflow.com/a/51344419
upvote count: 2
type: AcceptedAnswer
has body: Assuming that your variables are strings like you claim, and not integers like they are in the question, you are looking for rstrip: &gt;&gt;&gt; s1 = '203502000000' &gt;&gt;&gt; s1.rstrip('0') '203502' This will remove all trailing zeros from the string, but none anywhere else. To apply this to your entire list, you may use a list comprehension: [s.rstrip('0') for s in my_list]
type: Answer
accepted answer of: http://stackoverflow.com/q/51344411
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51344411

http://stackoverflow.com/comment/89773442
comment on: http://stackoverflow.com/q/51401330
score: 0
type: Comment
type: QuestionComment
has text: aside: you could create a `set` instead of a `dict` for this. Your approach looks all right. I don't see what you need to improve. hashing is very efficent on integers BTW

http://stackoverflow.com/a/51424171
downvote count: 1
has comment: http://stackoverflow.com/comment/105392998
score: 5
has comment: http://stackoverflow.com/comment/124607108
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/105385981
has comment: http://stackoverflow.com/comment/124607112
accepted answer of: http://stackoverflow.com/q/51423766
type: Answer
upvote count: 6
has body: You probably don't have an int dtype. Doing df['x0'] = df['x0'].astype(int) + 1 should work
answers question: http://stackoverflow.com/q/51423766
has comment: http://stackoverflow.com/comment/105372908

http://stackoverflow.com/q/51453650
score: 0
duplicate of: http://stackoverflow.com/q/44634972
answer count: 1
has body: How can I use colname_1 to get a value for an attribute foo of a namedtuple? from collections import namedtuple colname_1 = 'foo' colname_2 = 'bar' Farm = namedtuple('Farm', 'foo bar') farm = Farm('apple', 'banana') farm.foo # OK farm.colname_1 # of course this doesn't work!
linked to: http://stackoverflow.com/q/1167398
duplicate of: http://stackoverflow.com/q/1167398
tagged with: python
has title: Python namedtuple : How can I reuse variables used to create attributes in a namedtuple to get values from the namedtuple?
tagged with: namedtuple
has comment: http://stackoverflow.com/comment/89877077
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51453707
type: Question
linked to: http://stackoverflow.com/q/44634972

http://stackoverflow.com/comment/89679593
type: Comment
comment on: http://stackoverflow.com/a/51353203
type: AnswerComment
has text: @NateWalker No worries.
score: 0

http://stackoverflow.com/a/51425186
has comment: http://stackoverflow.com/comment/89842579
score: 0
has comment: http://stackoverflow.com/comment/89845729
has body: Python is quite good at this. The following function worked for me in many cases. from dateutil.parser import parse parse('2016-12-02 22:25:44').strftime("%s") (just read the comments, thought you meant a string, not sure if this answer applies to what you ask but seems not clear yet)
answers question: http://stackoverflow.com/q/51425105
type: Answer

http://stackoverflow.com/comment/92725234
has text: @SebSilas Make the modules you need submodules of your addon package. Read [the Python tutorial page on modules](https://docs.python.org/3/tutorial/modules.html) to understand.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52894781
type: Comment

http://stackoverflow.com/q/51426581
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/89824243
has comment: http://stackoverflow.com/comment/89840430
upvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/51426833
tagged with: numpy
type: AnsweredQuestion
score: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/51426833
has body: I have a 3D numpy array of shape (3,3,3). I would like to obtain indices of maximum values in a plane,"plane" according to me is as follows: a = np.random.rand(3,3,3) &gt;&gt;&gt; a[:,:,0] array([[0.98423332, 0.44410844, 0.06945133], [0.69876575, 0.87411547, 0.53595041], [0.53418486, 0.16186808, 0.60579623]]) &gt;&gt;&gt; a[:,:,1] array([[0.38969199, 0.80202126, 0.62189662], [0.66609605, 0.09771614, 0.74061269], [0.77081531, 0.20068743, 0.72762023]]) &gt;&gt;&gt; a[:,:,2] array([[0.57110332, 0.29021439, 0.15433043], [0.21762439, 0.93112448, 0.05763075], [0.77880124, 0.36637245, 0.29070822]]) I have a solution but I would like to have something shorter and quicker without for loops, my solution is as belows: for i in range(3): x=a[:,:,i].argmax()/3 y=a[:,:,i].argmax()%3 z=i print(x,y,z) print a[x][y][z] (0, 0, 0) 0.9842333247061394 (0, 1, 1) 0.8020212566990867 (1, 1, 2) 0.9311244845473187
favorite count: 0
has comment: http://stackoverflow.com/comment/89826477
has title: Index of maximum values along and plane in a numpy 3D array

http://stackoverflow.com/comment/89875011
score: 2
comment on: http://stackoverflow.com/q/51452562
type: QuestionComment
type: Comment
has text: Why aren't 11:55 and 12:00 of interest? They are part of the decreasing series. And what do you mean by "%age of lower value compared to %age of starting Value"? Please provide your expected output.

http://stackoverflow.com/comment/89899084
comment on: http://stackoverflow.com/q/51464962
score: 0
has text: I do not understand you, explain yourself better please.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51388282
type: Answer
upvote count: 1
score: 1
has body: If you run df.to_json(orient="records") it should provide you with the output that you want (note: as of Pandas version 0.23.3)
downvote count: 0
answers question: http://stackoverflow.com/q/51378617

http://stackoverflow.com/comment/89672309
comment on: http://stackoverflow.com/a/51349248
type: AnswerComment
score: 0
has text: I have added the reproducible dataset in the chat
type: Comment

http://stackoverflow.com/comment/89845892
type: Comment
type: QuestionComment
has text: do you know the set of numbers that should exist?
comment on: http://stackoverflow.com/q/51437954
score: 0

http://stackoverflow.com/comment/89879419
comment on: http://stackoverflow.com/q/51454895
score: 0
has text: Are you able to click on drop down? I see it is not made using select and span tag though.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51424012
upvote count: 3
has body: You can sort_values and then drop_duplicates: res = df.sort_values(['EFFDT','EFFSEQ'])\ .drop_duplicates(subset=['EMPLID','EMPL_RCD']) Alternatively, you can sort and then use groupby + first: res = df.sort_values(['EFFDT','EFFSEQ'])\ .groupby(['EMPLID','EMPL_RCD']).first() Your code does not work because you are applying first to a dataframe rather than a GroupBy object. You need to pass first to groupby as an aggregating function.
has comment: http://stackoverflow.com/comment/104084526
accepted answer of: http://stackoverflow.com/q/51423948
score: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51423948
type: Answer

http://stackoverflow.com/comment/89781803
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51405032
has text: @Yuca What else example do you need. Example is already there.
score: 0

http://stackoverflow.com/q/51444091
linked to: http://stackoverflow.com/q/31593201
upvote count: 1
has body: Executing my Python code containing pandas df slicing with .ix, I get a warning about its future deprecation. I have been trying to find a replacement. But can for the life of me not get the code to work. I have followed this answer pandas iloc vs ix vs loc explanation, how are they different? and many more If you try to remove the 2 lines with .loc slicing, and replace it with the line above that uses .ix, you may see the code work properly. Please help. My code that fetches updated excange-rates from the US Federal Reserve Bank. module = __name__ import pandas as pd pd.core.common.is_list_like = pd.api.types.is_list_like from pandas_datareader import data as web import numpy as np import datetime xratelist = ['DEXDNUS', 'DEXUSEU'] xrts = [] def xRateList_pd(xratelist, modus='sim'): years = 1.2 days = int(252 * years) # ant. arb. dage pr år = 252 if modus == 'sim': start = datetime.datetime(2016,1,1) # indstil manuelt end = datetime.datetime(2018,5,18) # indstil manuelt if modus == 'trading': end = pd.Timestamp.utcnow() start = end - days * pd.tseries.offsets.BDay() # Pick all rates simultaneously print('Fetching xratelist from Fred: ', xratelist) for xrt in xratelist: r = web.DataReader(xrt, 'fred', start = start, end = end) # add a symbol column xrts.append(r) # concatenate all the dfs into one df_xrates = pd.concat(xrts, axis='columns') df_xrates['DEXDNUS'] = np.round(df_xrates['DEXDNUS'], decimals=4) df_xrates['DEXUSEU'] = np.round(df_xrates['DEXUSEU'], decimals=4) # xrateDNUS = float(df_xrates.ix[-1, 'DEXDNUS']) # Works but deprecated... xrateDNUS = float(df_xrates.loc[-1, 'DEXDNUS']) # Finds last x-rate in pd xratedateDNUS = df_xrates.index[-1] # Finds date for this xrate, index.. print('Found xrateDNUS DKK/USD : %1.2f DKK, from: %s' %(xrateDNUS, xratedateDNUS)) # xrateUSEU = float(df_xrates.ix[-1, 'DEXUSEU']) # Works but deprecated... xrateUSEU = float(df_xrates.loc[-1, 'DEXUSEU']) xratedateUSEU = df_xrates.index[-1] print('Found xrateUSEU USD/EUR : %1.2f $,…
type: Question
has comment: http://stackoverflow.com/comment/89858463
has answer: http://stackoverflow.com/a/51454124
accepted answer: http://stackoverflow.com/a/51454124
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89858263
tagged with: slice
downvote count: 4
has comment: http://stackoverflow.com/comment/89858328
tagged with: pandas
answer count: 1
duplicate of: http://stackoverflow.com/q/31593201
favorite count: 0
has title: pandas .ix slicing deprecated - how to replace?
score: -3
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/51333501
tagged with: tensorflow
score: 2
type: AnsweredQuestion
downvote count: 0
tagged with: neural-network
type: Question
has title: Tensorflow: Training models with graphs that won't fit into memory of a single GPU
favorite count: 0
has answer: http://stackoverflow.com/a/51333686
tagged with: out-of-memory
upvote count: 2
tagged with: python
answer count: 1
accepted answer: http://stackoverflow.com/a/51333686
has comment: http://stackoverflow.com/comment/89643461
has body: The MemoryError is raised when building the graph, and before anything will be transferred to the GPU. The MemoryError is caused by trying to allocate more memory than the machine has available. What I have: Multiple GPUs What I don't have: Not large enough memory to fit the graph on any single GPU What I want to do: Train the model in a single GPU in several passes, or even better, use all the GPUs simultaneously to train different parts of my model (if that's even possible). But how do I train a model which requires a massive graph to be loaded into the memory (which it won't fit into)? Training in parts? Freezing layers? A quick google search does not give any hints at all :/ What is the right and perhaps the best way to do this?

http://stackoverflow.com/comment/89751102
type: Comment
comment on: http://stackoverflow.com/a/51389397
has text: Thanks I might have been overthinking this. If I have something like totalData = [data for j in headers for z in j for data in z] openData, closeData = totalData[1::6], totalData[4::6] , is there a way to combine the two lines
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89947455
comment on: http://stackoverflow.com/q/51461881
has text: urrgghhh why do I keep on mistyping! I meant `import Cookie` *annoyed loud sigh*
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90323777
type: AnswerComment
type: Comment
has text: perhaps try installing spacy as well then run `python -m spacy download en`?
score: 0
comment on: http://stackoverflow.com/a/51676055

http://stackoverflow.com/q/51468958
tagged with: anaconda
has body: I want to install chaco by anaconda, I got the following results : conda install -c anaconda chaco UnsatisfiableError: The following specifications were found to be in conflict: - chaco - mkl_fft enable is a dependency of chaco, conda install -c anaconda enable UnsatisfiableError: The following specifications were found to be in conflict: - enable - mkl_fft I have already installed mkl_fft. I am new to using anaconda. Do you have any solution? regards
tagged with: installation
answer count: 0
type: Question
downvote count: 0
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has title: installing chaco [anaconda] UnsatisfiableError conflict chaco mkl_fft
tagged with: python
score: 2

http://stackoverflow.com/comment/89667315
score: 0
type: AnswerComment
has text: @JonClements Good thinking! I didn't use `re.escape` originally, since I figured that the strings might already be regexes, but I guess it is a Good Idea. But I won't bother with `.finditer`, since there's probably not much benefit if the OP is searching single lines of text.
type: Comment
comment on: http://stackoverflow.com/a/51347183

class
tags question: http://stackoverflow.com/q/51461137
tags question: http://stackoverflow.com/q/51372555
tags question: http://stackoverflow.com/q/51352470
tags question: http://stackoverflow.com/q/51400001
tags question: http://stackoverflow.com/q/51443620
tags question: http://stackoverflow.com/q/51344890
tags question: http://stackoverflow.com/q/51469627
tags question: http://stackoverflow.com/q/51336958
tags question: http://stackoverflow.com/q/51333358
tags question: http://stackoverflow.com/q/51431837
tags question: http://stackoverflow.com/q/51382120
tags question: http://stackoverflow.com/q/51391338
tags question: http://stackoverflow.com/q/51436042
tags question: http://stackoverflow.com/q/51334640
tags question: http://stackoverflow.com/q/51344120
tags question: http://stackoverflow.com/q/51452159
tags question: http://stackoverflow.com/q/51390521
type: Tag
tags question: http://stackoverflow.com/q/51435095
tags question: http://stackoverflow.com/q/51353218
tags question: http://stackoverflow.com/q/51448331
tags question: http://stackoverflow.com/q/51351360
tags question: http://stackoverflow.com/q/51480392
tags question: http://stackoverflow.com/q/51417411
tag name: class
tags question: http://stackoverflow.com/q/51353162
tags question: http://stackoverflow.com/q/51459784
tags question: http://stackoverflow.com/q/51379017
tags question: http://stackoverflow.com/q/51385553
tags question: http://stackoverflow.com/q/51397555
tags question: http://stackoverflow.com/q/51461210
tags question: http://stackoverflow.com/q/51437443
tags question: http://stackoverflow.com/q/51353066
tags question: http://stackoverflow.com/q/51362432
tags question: http://stackoverflow.com/q/51447968
tags question: http://stackoverflow.com/q/51384403
tags question: http://stackoverflow.com/q/51389769
tags question: http://stackoverflow.com/q/51334255
tags question: http://stackoverflow.com/q/51419169
tags question: http://stackoverflow.com/q/51479908
tags question: http://stackoverflow.com/q/51360294

http://stackoverflow.com/comment/109193625
score: 1
has text: Also need to add `django_heroku.settings(config=locals(), staticfiles=False,logging=False)` logging =False
comment on: http://stackoverflow.com/a/56456466
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89858875
has text: please edit the last segment of code and give an explicit definition of what segment is. Apparently you want to map when a user's trip changes transportation method, correct?
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51444391

http://stackoverflow.com/q/51337842
tagged with: scope
has comment: http://stackoverflow.com/comment/89650216
answer count: 1
downvote count: 0
favorite count: 0
has body: I am continuously getting NameError: name 'max_col' is not defined. After some research I realized that if I wanted to use max_col inside a function as a global variable I had to declare it that way. However, even after that modification, it seems not to work. After banging my head for over an hour I put the variable max_col inside an array, popped it inside explore_color and and then used max. For some funny reason that seemed to work. Does someone know what I am missing here. Why can't I use the max function in a global variable? def max_area(grid): max_col = float('-inf') def explore_color(color, row, col, size): grid[row][col] = float('inf') global max_col max_col = max(max_col, size) directions = [(-1,0), (1,0), (0,1), (0,-1)] for dir in directions: next_x, next_y = row + dir[0], col + dir[1] if next_x &gt;= 0 and next_x &lt; len(grid) and next_y &gt;= 0 and next_y &lt; len(grid[0]) and grid[next_x][next_y] == color: explore_color(color, next_x, next_y, size + 1) for row in range(len(arr)): for col in range(len(arr[0])): if grid[row][col] != float('inf'): explore_color(grid[row][col], row, col, 1)
tagged with: python-3.x
has title: Why can't I use the max() function in a global variable in Python?
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/8447947
linked to: http://stackoverflow.com/q/30157655
tagged with: python
has comment: http://stackoverflow.com/comment/89650262
has comment: http://stackoverflow.com/comment/89650266
linked to: http://stackoverflow.com/q/1261875
duplicate of: http://stackoverflow.com/q/8447947
has comment: http://stackoverflow.com/comment/89650316
score: 1
has answer: http://stackoverflow.com/a/51337909
upvote count: 1
type: Question

http://stackoverflow.com/comment/89828173
score: 0
type: Comment
type: QuestionComment
has text: awesome, greatly appreciate the feedback
comment on: http://stackoverflow.com/q/51428057

http://stackoverflow.com/comment/89793705
comment on: http://stackoverflow.com/a/51410930
type: Comment
type: AnswerComment
score: 1
has text: I have no clue. Any constructive criticism, please?

http://stackoverflow.com/comment/89941141
comment on: http://stackoverflow.com/q/51471909
score: 0
type: Comment
type: QuestionComment
has text: What is the purpose of `tst_str`? Do you want to write a test and then run it multiple times for different inputs?

http://stackoverflow.com/comment/124389041
score: 0
type: Comment
has text: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
comment on: http://stackoverflow.com/a/70366901
type: AnswerComment

http://stackoverflow.com/comment/89839787
comment on: http://stackoverflow.com/q/51434771
score: 1
type: Comment
type: QuestionComment
has text: Since you are sorting at the end anyway, just concatenate the frames together and sort: `df = pd.concat([df, df1]).sort_values('Row ID')`

http://stackoverflow.com/q/51325224
has body: How to split image to RGB colors and why doesn't split() function work? from PIL import Image pil_image = Image.fromarray(some_image) red, green, blue = pil_image.split() red.show() Why does red.show() shows image in greyscale instead of red scale? PS. The same situation using green.show() and blue.show().
downvote count: 0
type: UnansweredQuestion
has title: Python PIL image split to RGB
type: Question
has answer: http://stackoverflow.com/a/51325280
tagged with: python-imaging-library
has answer: http://stackoverflow.com/a/51555134
tagged with: image-processing
has answer: http://stackoverflow.com/a/66402427
tagged with: python-3.6
tagged with: image
has comment: http://stackoverflow.com/comment/89625514
score: 5
answer count: 3
favorite count: 0
upvote count: 5
tagged with: python

http://stackoverflow.com/q/51350585
tagged with: python
has comment: http://stackoverflow.com/comment/89673945
favorite count: 0
has comment: http://stackoverflow.com/comment/89675627
type: UnansweredQuestion
tagged with: machine-learning
has answer: http://stackoverflow.com/a/51378825
has comment: http://stackoverflow.com/comment/89733150
score: -1
tagged with: svm
type: Question
answer count: 2
downvote count: 2
tagged with: scikit-learn
has body: In my problem there are four features(X); a,b,c,d and two dependents(Y); e,f. I have with me a data set containing a set of values for all these variables. How can I predict the values through Support Vector Regression using scikit-learn, for the e,f variables when new a,b,c,d values are given? I found it very difficult to follow the scikit-learn documentation on SVR. This is what I have done so far with the help of an example in the sklearn documentation. train = pd.read_csv('/Desktop/test.csv') X = train.iloc[:, 4] y = train.iloc[:, 4:5] svr_rbf = SVR(kernel='rbf', C=1e3, gamma=0.1) y_rbf = svr_rbf.fit(X, y).predict(X) lw = 2 plt.scatter(X, y, color='darkorange', label='data') plt.plot(X, y_rbf, color='navy', lw=lw, label='RBF model') plt.xlabel('data') plt.ylabel('target') plt.title('Support Vector Regression') plt.legend() plt.show() This gives the error, ValueError: Expected 2D array, got 1D array instead: : Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.
has title: Predictions using Support Vector Regression
has answer: http://stackoverflow.com/a/51351091
has comment: http://stackoverflow.com/comment/89686839
upvote count: 1

http://stackoverflow.com/comment/89820867
has text: To help I have explained my question further
type: AnswerComment
comment on: http://stackoverflow.com/a/51402264
score: 0
type: Comment

http://stackoverflow.com/a/51419311
upvote count: 2
type: AcceptedAnswer
type: Answer
has body: There is a fast way to do that in numpy with searchsorted. I converted your lists to numpy arrays, and then, with searchsorted, find indices where elements should be inserted to maintain order: ss = np.array([ 488, 1223, 1958, 2693, 3428]) ca = np.array([ 100, 190, 340, 540, 590, 940, 1340, 1410, 1640, 2040, 2940, 3396, 3630, 3675]) idx=np.searchsorted(ca,ss) Since you want the previous value, substract one: result=ca[idx-1] #array([ 340, 940, 1640, 2040, 3396])
accepted answer of: http://stackoverflow.com/q/51419122
answers question: http://stackoverflow.com/q/51419122
score: 2
downvote count: 0

http://stackoverflow.com/q/51457330
has comment: http://stackoverflow.com/comment/89884195
tagged with: google-colaboratory
favorite count: 0
has comment: http://stackoverflow.com/comment/89886421
has body: I need to get access to a dataset of images (600MB dataset) in Google Colab. I already uploaded all of my project files in my drive. The problem is that it seems that Google Colab is not recognizing data_config.py which is as file with all the functions that I need to get my datasets. What should I do to use my data_config.py? Error displayed
has title: Accessing drive files in Google Colab
tagged with: python
tagged with: drive
answer count: 0
score: 0
type: UnansweredQuestion
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89886988
type: Question
has comment: http://stackoverflow.com/comment/89884121
linked to: http://stackoverflow.com/q/47744131

http://stackoverflow.com/comment/89814179
has text: Also, i believe RGB = [[255,255,255], [127,127,127], [10,10,10]] is indeed a 2D list, at least according to: https://www.tutorialspoint.com/python/python_2darray.htm
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51421044

pytorch
tags question: http://stackoverflow.com/q/51335354
tags question: http://stackoverflow.com/q/51348833
tags question: http://stackoverflow.com/q/51361407
tags question: http://stackoverflow.com/q/51469194
tag name: pytorch
type: Tag
tags question: http://stackoverflow.com/q/51329159
tags question: http://stackoverflow.com/q/51376673
tags question: http://stackoverflow.com/q/51425436
tags question: http://stackoverflow.com/q/51477977
tags question: http://stackoverflow.com/q/51364273
tags question: http://stackoverflow.com/q/51412473
tags question: http://stackoverflow.com/q/51438232
tags question: http://stackoverflow.com/q/51392046
tags question: http://stackoverflow.com/q/51433378
tags question: http://stackoverflow.com/q/51416825
tags question: http://stackoverflow.com/q/51433774
tags question: http://stackoverflow.com/q/51371070
tags question: http://stackoverflow.com/q/51444059
tags question: http://stackoverflow.com/q/51353066
tags question: http://stackoverflow.com/q/51366521
tags question: http://stackoverflow.com/q/51448897
tags question: http://stackoverflow.com/q/51373919
tags question: http://stackoverflow.com/q/51369419

http://stackoverflow.com/comment/89757072
type: AnswerComment
has text: But anyway, that means the resolutions in the 100ns-500ns range that modern Windows boxes seem to report (while actually being correct) are definitely believable. Cache coherency issues could easily add a couple hundreds cycles, but the actual work when there's only one thread going is probably still single-digit cycles.
type: Comment
comment on: http://stackoverflow.com/a/51392436
score: 0

http://stackoverflow.com/comment/89889671
has text: What about abc.loc[abc['failure']==1, 'failure_date'] = abc['date'] ? Your method is faster than df.assign() which would make a copy of the dataframe.
comment on: http://stackoverflow.com/a/51460128
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51357601
has body: The underscore is a valid variable name and is commonly used to imply that the value will be unused. Only the second value of the pair returned by divmod will be used via the task_style_choice variable. _, task_style_choice = divmod(len(self.tasks), 2)
type: AcceptedAnswer
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51357531
score: 6
answers question: http://stackoverflow.com/q/51357531
upvote count: 6

http://stackoverflow.com/a/51327995
has body: # assuming list is sorted: pattern = ["ABCDE", "ABCDEFG", "ABCDEFGH", "ABCDEFGHIJKLMNO", "CEST", "DBTSFDE", "DBTSFDEO", "EOEUDNBNUW", "EAEUDNBNUW", "FG", "FGH"] pattern = list(reversed(pattern)) def iterate_patterns(): while pattern: i = pattern.pop() throw_it_away = False for p in pattern: if p.startswith(i): throw_it_away = True break if throw_it_away == False: yield i print(list(iterate_patterns())) Output: ['ABCDEFGHIJKLMNO', 'CEST', 'DBTSFDEO', 'EOEUDNBNUW', 'EAEUDNBNUW', 'FGH']
type: Answer
upvote count: 4
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/51327765

http://stackoverflow.com/comment/89877251
comment on: http://stackoverflow.com/q/51453681
has text: @Bryan Oakley your comments would be helpful?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51456271
has body: Well, sure. You only need one iteration: data = [ { 'mem_used': '14868480', 'rsrc_name': 'node-5b5cf484-g582f' }, { 'mem_used': '106618880', 'rsrc_name': 'infrastructure-656cf59bbb-xc6bb' }, { 'mem_used': '27566080', 'rsrc_name': 'infrastructuret-l6fl' }, { 'mem_used': '215556096', 'rsrc_name': 'node-62lnc' } ] def get_group(item): rsrc_name = item['rsrc_name'] index = rsrc_name.index('-'); return rsrc_name[0:index] def summary(list): data = {}; for item in list: group = get_group(item) if not (group in data): data[group] = 0 data[group] += int(item['mem_used']) result = [] for rsrc_name, mem_used in data.items(): result.append({ 'rsrc_name': rsrc_name, 'mem_used': str(mem_used) }) return result if __name__ == '__main__': print(summary(data)) Result: [{'mem_used': 230424576, 'rsrc_name': 'node'}, {'mem_used': 106618880, 'rsrc_name': 'infrastructure'}, {'mem_used': 27566080, 'rsrc_name': 'infrastructuret'}] Note, that get_group might be too simple for your use case. The result has three groups since one of the resources has key 'infrastructuret' with a "t" at the end.
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89881999
upvote count: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51456060
answers question: http://stackoverflow.com/q/51456060

http://stackoverflow.com/a/51331596
answers question: http://stackoverflow.com/q/51330310
has body: Try to run a query from the pyodbc connection and see if it gives you the same result, you can run a simple query something like this: conn = pyodbc.connect("Driver={SQL Server};" "Server=myServer;" "Database=myDB;" "Trusted_Connection=yes;") cursor = conn.cursor() cursor.execute(''' SELECT TOP 100 * FROM table.db WHERE COLUMN.2 = 'something' ''' ) for row in cursor: # print(row[1:3]) row1 = row[2] return row1 conn.close()
type: Answer
score: 0

http://stackoverflow.com/q/51355052
tagged with: python
score: 2
has title: use of 'ir.attachment' in binary field-- odoo
answer count: 0
tagged with: attachment
type: Question
tagged with: odoo
downvote count: 0
tagged with: odoo-10
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has body: what is the use of 'ir.attachment' in Binary filed of ODOO 10? How does it differ if it is not used ? attachments1 = fields.Binary('Attachments') attachments2 = fields.Binary('ir.attachment', string = 'Attachments')

http://stackoverflow.com/a/51406418
downvote count: 0
answers question: http://stackoverflow.com/q/51405934
accepted answer of: http://stackoverflow.com/q/51405934
has comment: http://stackoverflow.com/comment/89855081
has comment: http://stackoverflow.com/comment/89854939
upvote count: 2
type: AcceptedAnswer
has body: Here's what I have found: You should use the gitlab api to interface with the project's wiki repository and upload the file that way. Look at how you can clone the wiki repository and also how to upload a file. Check the answer to this question for more information about the location to upload the file. Then, simply edit the wiki page with the hyperlink to the uploaded file using the wiki APIs which you are already using in your example. I do not use gitlab, or this API, but these links should get you started on solving your problem.
has comment: http://stackoverflow.com/comment/89920694
type: Answer
score: 2

http://stackoverflow.com/a/51418823
has comment: http://stackoverflow.com/comment/89809118
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89809188
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/89808747
has body: Sanitize your input first and then loop over it: sentences = ['THISISASENTENCE', 'ANDHEREISONEMOREEXAMP', 'ALLFROMDIFFERENTBOOKS', 'ANDFROMDIFFERENTPAGES', 'MOSLTYTHESAMELENGTHS', 'THISISSHORT' ] max_len = len(max(sentences, key=len)) # kudos ZachGates print max_len # 21 sentences = filter(lambda x: len(x)==max_len, sentences) print sentences # ['ANDHEREISONEMOREEXAMP', 'ALLFROMDIFFERENTBOOKS', 'ANDFROMDIFFERENTPAGES'] Now you can proceed as you did.
has comment: http://stackoverflow.com/comment/89809034
answers question: http://stackoverflow.com/q/51418579

http://stackoverflow.com/a/51431998
score: 1
has body: Taking your row calculations outside the inner loop would help a little. Therefore these calculations will only be made once for each row. A few other tidy-ups gives: classim = np.zeros_like(temp1) predict_args = predict.argmax(axis=-1) for rows in range(temp1.shape[0]//SAMPLE_SIZE): row_0 = rows * SAMPLE_SIZE row_1 = (rows+1) * SAMPLE_SIZE for cols in range(temp1.shape[1]//SAMPLE_SIZE): col_0 = cols * SAMPLE_SIZE col_1 = (cols+1) * SAMPLE_SIZE classim[row_0:row_1,col_0:col_1] = predict_args[Count] Count+=1 You would need to tell us more about the predict object before I could do much more. But these changes will help a little. --EDIT-- You could take advantage of the numpy.repeat function. Then there is no need to iterate through the whole classim: SAMPLE_SIZE = 2 temp1 = np.arange(20*20).reshape((20,20)) sample_shape = (temp1.shape[0]//SAMPLE_SIZE, temp1.shape[0]//SAMPLE_SIZE) #This line should work as per your question, but returns a single value #predict_args = predict.argmax(axis=-1) #Use this for illustration purposes predict_args = np.arange(sample_shape[0] * sample_shape[1]) subsampled = predict_args.reshape(sample_shape) classim = np.repeat(np.repeat(subsampled,SAMPLE_SIZE,axis =1),SAMPLE_SIZE, axis=0) print(subsampled) print(classim)
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/89836878
accepted answer of: http://stackoverflow.com/q/51431385
answers question: http://stackoverflow.com/q/51431385
has comment: http://stackoverflow.com/comment/89835156
downvote count: 0
has comment: http://stackoverflow.com/comment/89837618
has comment: http://stackoverflow.com/comment/89904372
type: AcceptedAnswer

http://stackoverflow.com/comment/89697632
score: 0
has text: You posted [a question with the same title](https://stackoverflow.com/questions/51320167/how-to-get-a-tensors-value-in-tensorflow-without-making-another-session) recently — you should at least state why this question is different.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51357584

http://stackoverflow.com/q/51358964
tagged with: statistics
score: 0
has title: Fitting data to a probability distribution, maybe skew normal?
answer count: 1
has comment: http://stackoverflow.com/comment/89704527
type: UnansweredQuestion
tagged with: python
has body: I am trying to fit my data to some kind of a probability distribution, so I can then generate random numbers based on the distribution. Below is what the data points look like, with x-axis behind the data values and y-axis the probabilities. Data plot They look like they would fit to a skew normal distribution, with mean around 10^-4. The plot's data is actually binned from an original data set. I tried using scipy.stats library to fit to a skew normal on the original data, but the fit does not work at all. I was wondering if anyone knows a way to fit this to any PDF? The data in my plot is below (can't post the original, raw data as it is far too large): x = [2.0030289496413441e-07, 6.021220996561269e-07, 1.8100138940039783e-06, 5.4410065638820868e-06, 1.6355980761406714e-05, 4.916702516834233e-05, 0.00014779892439152631, 0.00044429212417263257, 0.0013355678494582283, 0.0040147942838919017, 0.012068704071088232, 0.036279223206999923, 0.10905744550124194, 0.32783299552460016, 0.98548496584223111, 2.9624248661943691, 8.9052206700550585, 26.769608940074498, 80.470994415019419, 241.90046842440222, 727.16681394735679, 2185.9055451626773, 6570.9586311220974, 19752.682098944373] y (or P(x) in the diagram) = [2.2554525565554728e-05, 2.2554525565554728e-05, 3.1576335791776624e-05, 0.0013140978842667934, 0.00029833486088983759, 0.00083417571068968434, 0.0013023224717182351, 0.00030292744905932074, 0.00018784462533064236, 0.00015960011900197359, 5.231239486282394e-05, 4.8227744123750205e-05, 3.8972462681781172e-05, 2.9372389964277703e-05, 3.3001942979800356e-05, 2.8061790992628833e-05, 2.6056781088158009e-05, 2.522638138246609e-05, 2.4144908778509908e-05, 2.5086756895368843e-05, 2.3095834179128078e-05, 2.2554525565554745e-05, 2.2554525565554755e-05, 2.2554525565554728e-05]
tagged with: scipy
has answer: http://stackoverflow.com/a/51361216
type: Question

http://stackoverflow.com/a/51454110
has comment: http://stackoverflow.com/comment/89893996
has comment: http://stackoverflow.com/comment/89878007
has body: It's great that you have acknowledged a problem like this . But , its true that you can't do this task in O(1) operation ,or simply putting - one cannot access the specific dictionary from a list without traversing the list. So , what's the alternative ? If your requirements include no extra space usage then instead of using a linear search go for binary search .This will reduce time complexity drastically from O(n) to O(log n). If you can allow extra O(n) space , you can go for other solutions as they will be more time efficient . For constant space solution Prerequisite : List has to be in sorted order by the hello_values See the code below to do this : def by_hello_value(elem): return elem['Hello'] my_list.sort(key=by_hello_value) Now this list is ready for binary search : def find_dictionary(hello_value): l=0 r=len(my_list)-1 while(l&lt;=r): m = (int)((l+r)/2) if(my_list[m]['Hello']==hello_value): return my_list[m] if(my_list[m]['Hello']&lt;hello_value): l=m+1 else: r=m-1 # return empty dictionary if required hello_valued dictionary is not present in list return {} Hope this will help . And yes,do not forget to share the time taken by this method on your data .You can use the comment section for that. Keep asking , keep growing :)
score: 0
has comment: http://stackoverflow.com/comment/89878111
type: Answer
answers question: http://stackoverflow.com/q/51453844

http://stackoverflow.com/a/51415695
downvote count: 0
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51415535
has body: To create an empty tuple, use tuple(). It will print as (), but that's not how you create an empty tuple. As minimum, a tuple must contain one item. So you need to create it as ([],). Your code ([]) is the same as [], the parenthesis in this case act as continuation characters` and not an empty tuple. Expressions in parentheses, square brackets or curly braces can be split over more than one physical line without using backslashes. See the documentation on lexical analysis for more details. You can also verify this at the interpreter: &gt;&gt;&gt; ([]) == [] True

http://stackoverflow.com/a/51424450
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51422244
answers question: http://stackoverflow.com/q/51422244
has body: To perform line removal for a list of files in the working directory (and put the resulting output into pdfs) run LibreOffice in a Linux command line: soffice --headless --accept="socket,host=localhost,port=2002;urp;StarOffice.ServiceManager" and then in the Python interpreter import uno import socket import os import subprocess from pythonscript import ScriptContext from com.sun.star.beans import PropertyValue # list docfiles in working dir files = [x for x in os.listdir('.') if x.endswith(".docx")] # iterate on files for file in files: localContext = uno.getComponentContext() resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext) ctx = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext") smgr = ctx.ServiceManager desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx) # open file model = desktop.loadComponentFromURL(uno.systemPathToFileUrl(os.path.realpath(file)), "_blank", 0, ()) # remove line numbers model.getLineNumberingProperties().IsOn = False # prepare to save output to pdf XSCRIPTCONTEXT = ScriptContext(ctx, None, None) p = PropertyValue() p.Name = 'FilterName' p.Value = 'writer_pdf_Export' oDoc = XSCRIPTCONTEXT.getDocument() # create pdf oDoc.storeToURL("file://" + os.getcwd() + "/" + file + ".pdf", tuple([p])) This should create pdf files with no line numbering in your working directory. Useful links: Add line numbers and export to pdf via macro on OpenOffice forums LineNumberingProperties documentation Info on running a macro from the command line
upvote count: 3
type: AcceptedAnswer
type: Answer
score: 3

http://stackoverflow.com/comment/89716513
has text: Thanks for the help, Massoud!
comment on: http://stackoverflow.com/a/51344457
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51468863
type: Answer
has body: isalpha tests that each member of the string is a letter. isspace tests that each member of the string is a whitespace character. Neither of those is what you want. Instead you could do: if all(lett.isalpha() or lett.isspace() for lett in name): which will pass if every letter is EITHER a letter or a space. Alternatively you can match a regular expression: import re # at the top of your module if re.match(r"[\s\w]+$", name): which is arguably cleaner, and certainly more powerful. The square brackets denote a character class, \s is all whitespaces and \w is all word character, the + means "matches 1 or more times," and the $ is the end of string. [\s\w]+$ then means "one or more characters that are either whitespace or word characters, and nothing afterwards.
upvote count: 4
answers question: http://stackoverflow.com/q/51468800
downvote count: 0
has comment: http://stackoverflow.com/comment/89906574
score: 4

http://stackoverflow.com/a/51706227
accepted answer of: http://stackoverflow.com/q/51440475
score: 5
type: AcceptedAnswer
upvote count: 5
has body: Tensorflow or Tensorflow-gpu is supported only for 3.5.X versions of Python. Try installing with any Python 3.5.X version. This should fix your problem.
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/51440475
has comment: http://stackoverflow.com/comment/111259607

http://stackoverflow.com/comment/89768847
type: QuestionComment
has text: I was hoping this might sound familiar. I’ve seen the question asked with slightly different variations. When I have time later, I will login with my laptop and paste the code/errors.
comment on: http://stackoverflow.com/q/51398847
type: Comment
score: 0

http://stackoverflow.com/comment/89635468
score: 0
comment on: http://stackoverflow.com/q/51328613
type: Comment
type: QuestionComment
has text: @eyllanesc I will try this Monday, thank you. Still curious as to why i need to force the chart to update instead of it being automated.

http://stackoverflow.com/q/51349340
type: AnsweredQuestion
score: 7
has body: I am attempting to scrape some data from a website using a POST request with the Python requests library. Unfortunately I am unable to post a link to the page as you must be signed in to the website to site to use it. The request I am trying to replicate has the file extension .ehtml and this is part of the Request payload I am looking to recreate: ------WebKitFormBoundary8rntuVzldIBHkILv Content-Disposition: form-data; name="session_id" W0pNKn8AAQEAACD-XkYAAAAJ ------WebKitFormBoundary8rntuVzldIBHkILv Content-Disposition: form-data; name="p_session_id" W0pMOH8AAQEAABZSUVkAAAAD ------WebKitFormBoundary8rntuVzldIBHkILv Content-Disposition: form-data; name="attach_key" ------WebKitFormBoundary8rntuVzldIBHkILv Content-Disposition: form-data; name="chosen" 0 ------WebKitFormBoundary8rntuVzldIBHkILv Content-Disposition: form-data; name="debug" ------WebKitFormBoundary8rntuVzldIBHkILv Content-Disposition: form-data; name="language" en ------WebKitFormBoundary8rntuVzldIBHkILv Content-Disposition: form-data; name="game_system_id" NULL ------WebKitFormBoundary8rntuVzldIBHkILv Content-Disposition: form-data; name="collection_detail_id" NULL ------WebKitFormBoundary8rntuVzldIBHkILv Content-Disposition: form-data; name="competition_id" NULL Using some help from some of the questions on stackoverflow, I have managed to recreate it this far: --30b11983bde849109a3dc93e139e16d4 Content-Disposition: form-data; name="session_id" --30b11983bde849109a3dc93e139e16d4 Content-Disposition: form-data; name="p_session_id" --30b11983bde849109a3dc93e139e16d4 Content-Disposition: form-data; name="attach_key" --30b11983bde849109a3dc93e139e16d4 Content-Disposition: form-data; name="chosen" 0 --30b11983bde849109a3dc93e139e16d4 Content-Disposition: form-data; name="debug" --30b11983bde849109a3dc93e139e16d4 Content-Disposition: form-data; name="language" en --30b11983bde849109a3dc93e139e16d4 Content-Disposition: form-data; name="game_system_id" NULL --30b11983bde849109a3dc93e139e16d4 Content-Disposi…
has title: Recreate POST request with WebKitFormBoundary using Python's requests
type: Question
has answer: http://stackoverflow.com/a/51363672
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/68466990
answer count: 5
has answer: http://stackoverflow.com/a/64763197
tagged with: python
accepted answer: http://stackoverflow.com/a/51363672
has answer: http://stackoverflow.com/a/59306408
possible better answer: http://stackoverflow.com/a/60371485
upvote count: 7
tagged with: python-requests
has answer: http://stackoverflow.com/a/60371485

http://stackoverflow.com/comment/89892526
type: QuestionComment
has text: Please consider adding a code sample, or revising the one you posted in this question. As it currently stands, its formatting and scope make it hard for us to help you; here is a [great resource](http://stackoverflow.com/help/mcve) to get you started on that. Good luck with your code!
comment on: http://stackoverflow.com/q/51461696
score: 0
type: Comment

http://stackoverflow.com/comment/89682530
type: QuestionComment
comment on: http://stackoverflow.com/q/51355035
score: 0
has text: You want an exact algorithm or a probabilistic one with arbitrarily low error would do?
type: Comment

http://stackoverflow.com/comment/89865989
type: QuestionComment
score: 1
has text: @W Stokvis, thanks I believe this is what I am looking for. Can you post it as an answer so I can mark it as solved!
comment on: http://stackoverflow.com/q/51447695
type: Comment

http://stackoverflow.com/a/51467032
score: 1
type: AcceptedAnswer
has body: Depending on how long you mind your lines being, the first conditional can be reduced to the unnested if exclude and any(exclude_name in view_name for exclude_name in exclude.split(',')): return None The entire method can be boiled down to the (more or less unreadable) two-liner if not (exclude and any(exclude_name in view_name for exclude_name)) and (exact and name == view_name or not exact and name in view_name): return 'active' You mention that you ultimately want to check if something is 'active' or not. With the above observation, the function returns 'active' exactly if not (exclude and any(exclude_name in view_name for exclude_name)) and (exact and name == view_name or not exact and name in view_name) so if you only care about the truth value of that expression, you could simply return not (exclude and any(exclude_name in view_name for exclude_name)) and (exact and name == view_name or not exact and name in view_name) and not have any conditionals.
upvote count: 1
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/51466996
accepted answer of: http://stackoverflow.com/q/51466996

http://stackoverflow.com/q/51390104
has comment: http://stackoverflow.com/comment/89752489
type: Question
upvote count: 2
tagged with: python-2.7
tagged with: api
answer count: 1
has body: I bought a proxy service which gives me an API that when opened, shows what seems like a big text file of stacked proxies like this, example: 39.134.10.2:8080 139.59.2.223:8888 39.134.10.250:8080 61.5.207.102:80 39.134.146.130:8088 60.194.46.119:3128 161.139.222.254:9000 39.134.10.21:8080 148.217.94.54:3128 60.194.46.118:3128 39.134.10.28:8080 39.134.10.250:90 200.255.122.174:8080 219.239.142.253:3128 118.190.210.227:3128 I want to make it an updating dictionary in python 2.7. Most of what i've seen is people either webscraping proxies or using json to get them. My API link gets an error: ValueError: No JSON object could be decoded I just need to send the ip(s) to a dictionary in Python which then I can make selenium use. I tried to do this: import urllib2, json ipadd = urllib.urlop('link to API') json.load(ipadd) I could always copy-paste the ip(s) to a notepad every 24 hours but that defeats the purpose of the API and I'm sure it's something easy that I don't see. I'm new to network programming. Thank you
favorite count: 0
has title: How can I grab data from an already parsed non-json API in python containing proxies?
has comment: http://stackoverflow.com/comment/89752321
has comment: http://stackoverflow.com/comment/89752413
tagged with: python
has comment: http://stackoverflow.com/comment/89752362
score: 2
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/51390181
accepted answer: http://stackoverflow.com/a/51390181
tagged with: selenium

http://stackoverflow.com/a/51416465
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/51415425
has body: Since writing this answer I have realised it is more convenient and better style in my humble opinion to install the package with pip install -e . and use absolute imports. So even within a package writing from package.sub.module import thing. This makes refactoring a lot easier and there's no need to ever manipulate module variables or sys.path. When running a script directly, Python consideres the name (a special variable, __name__) of that script to be "__main__". In case of an import, the name is set to the name of the module. In the latter case relative imports are fine. But import actually looks at the combination of __name__ and another special variable, __package__, which is None for an executed script, but the path to a module for an imported module, e.g. parent.sub. The searched variable is... drumroll... __package__ + '.' + __name__ The secret ingredient is manipulating __package__: # script.py __package__ = 'package_name' # or parent.sub.package from . import module This lets Python know you are inside a package even though the script is executed directly. However, the top level folder needs to be in sys.path and the package name has to reflect that directory structure. See this very comprehensive answer on the topic of relative imports.
score: 4
accepted answer of: http://stackoverflow.com/q/51415425
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/51449752
type: AcceptedAnswer
type: Answer
has body: Pandas indexing doesn't work the way you are expecting. You can't use df[rows, cols] instead you use .loc (https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html) So yes - you're right in that the error is caused by your line : test[test['predictions'] &gt; (i/100), "temp"] = 1. To fix it you would use: test.loc[test['predictions'] &gt; (i/100), "temp"] = 1. ... then you'll run into issues on the following 4 lines that follow the format: TP[i+1] = test[test["actual"]==1 and test["temp"]==1,].shape[0] You need wrap each evaluation statement in parenthese and change your and to &amp;. There's a good discussion of why this is here: Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). So your code should look like: TP[i+1] = len(test[(test["actual"]==1) &amp; (test["temp"]==1)]) Note; we can use the len function rather than the first element of the dataframes shape attribute to count the number of rows. That's just my preference though. Finally; you can't set 'NA' values that way in python; you would use np.NAN. The final if statement will fail because you have made arrays of strings as placeholders. I think np.zeros(101) would work for you. Your full code with my edits: predictions = pd.DataFrame(predictions[1]) actual = pd.DataFrame(y_test) test = pd.concat([actual.reset_index(drop=True), predictions], axis=1) # Rename column Renew to 'actual' and '1' to 'predictions' test.columns = ['actual', 'predictions'] #&lt;- You can assign column names using a list TP = np.zeros(101) FN = np.zeros(101) FP = np.zeros(101) TN = np.zeros(101) Sensitivity = np.zeros(101) Specificity = np.zeros(101) AUROC = 0 for i in range(10): test['temp'] = 0 test.loc[test['predictions'] &gt; (i / 100), 'temp'] = 1 TP[i+1] = len(test[(test["actual"]==1) &amp; (test["temp"]==1)]) FN[i+1] = len(test[(test["actual"]==1) &amp; (test["temp"]==0)]) FP[i+1] = len(test[(test["actual"]==0) &amp; (test["temp"]==1)]) TN[i+1] = len(test[(test["a…
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51449292
answers question: http://stackoverflow.com/q/51449292
upvote count: 1

odoo-10
tags question: http://stackoverflow.com/q/51329505
tags question: http://stackoverflow.com/q/51358511
tag name: odoo-10
tags question: http://stackoverflow.com/q/51384272
tags question: http://stackoverflow.com/q/51455829
tags question: http://stackoverflow.com/q/51364741
tags question: http://stackoverflow.com/q/51355052
type: Tag
tags question: http://stackoverflow.com/q/51374562

http://stackoverflow.com/a/51337214
downvote count: 0
type: Answer
has body: You don't really need to save HTML entities. There are only five HTML entities that are actually vital in HTML: &amp;lt;, &amp;gt;, &amp;amp; and the less important &amp;quot; and &amp;apos;. All the others are merely a convenience facility, not a necessity. When writing HTML by hand, they can come in handy for entering a character that has no key on the keyboard, or to distinguish characters that would otherwise look the same in the source code, like the regular space and the non-breaking space (&amp;nbsp;). But - it's perfectly possible to replace those entities with the actual characters they represent, given that you use the proper character encoding everywhere. And that is precisely your problem here. This is what happened: You downloaded the HTML file, encoding was correctly specified by the server. You used BeautifulSoup to parse it. In the process, the &amp;nbsp; was converted to a non-breaking-space character. This is a normal part of parsing, every HTML parser does that. You processed the DOM tree and saved parts of it to a CSV file. You chose UTF-8 encoding for that file. The non-breaking space is represented by two bytes 0xC2 and 0xA0 in UTF-8. You loaded the CSV file again, possibly in another part of your code, or another application entirely (maybe Excel?) but you did not specify that it was UTF-8 (a multi-byte encoding). So the application used whatever "default encoding" is configured on your system to interpret the bytes in the file - I suspect Windows-1252 (a single-byte encoding) was used. In Windows-1252, the two bytes 0xC2 and 0xA0 represent two characters: Â and, ironically, the non-breaking space. In other words, everything up to this point was correct, it was reading the data the wrong way that broke it. Ways to solve this, from most favorable to least favorable: Tell the application or piece of code that loads the CSV file that the encoding is UTF-8. Add a UTF-8 BOM (Byte Order Mark) to the CSV file. Especially Excel might need this in orde…
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51330761

http://stackoverflow.com/a/51347053
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51346710
type: Answer
has body: To keep the records without duplicates (row 5 and 6), use drop_duplicates function: dfA = df.drop_duplicates(subset = ['column_B', 'column_C'], keep = False) Output: column_A column_B column_C column_D 4 10 3 charlie 1 5 100 3 davis 2 To keep the records with duplicates (rows 1 to 4), use duplicated function: dfB = df[df.duplicated(subset = ['column_B', 'column_C'], keep = False)] Output: column_A column_B column_C column_D 0 1 1 anna 123 1 2 1 anna 7 2 30 2 bob 42 3 20 2 bob 12
score: 2

http://stackoverflow.com/comment/89656247
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51341361
has text: `data` is a single dictionary, one that you appened to a list multiple times and keep updating. Either create a copy to append to the list, or create a new dictionary each time in the loop, rather than outside of the loop.

http://stackoverflow.com/comment/123078998
comment on: http://stackoverflow.com/a/51331557
score: 5
type: AnswerComment
has text: @Md.MusfiqurRahaman, As shown in `in [110] grid_img.shape`, the dimensions of grid_img are [# color channels x image height x image width]. Conversely, the input to matplotlib.pyplot.imshow() *needs to be* [image heigth x image width x # color channels] (i.e., the shape needs to be `[518, 1292, 3]`). The `.permute(1, 2, 0)` action is a Torch-specific function that permutes the axes of the original in exactly that order: [axis 1 x axis 2 x axis 0] = [image heigth x image width x # color channels].
type: Comment

http://stackoverflow.com/a/60495058
score: 8
has comment: http://stackoverflow.com/comment/122792378
has body: from pydub import AudioSegment from pydub import effects root = r'audio.wav' velocidad_X = 1.5 # No puede estar por debajo de 1.0 sound = AudioSegment.from_file(root) so = sound.speedup(velocidad_X, 150, 25) so.export(root[:-4] + '_Out.mp3', format = 'mp3')
upvote count: 8
downvote count: 0
has comment: http://stackoverflow.com/comment/129410791
answers question: http://stackoverflow.com/q/51434897
type: Answer

http://stackoverflow.com/q/51389443
answer count: 3
has title: using python to pull href tags
tagged with: beautifulsoup
score: 0
has answer: http://stackoverflow.com/a/51389613
tagged with: python
has body: tyring to pull the href links for the products on this webpage. The code pulls all of the href's except the products that are listed on the page. from bs4 import BeautifulSoup import requests url = "https://www.neb.com/search#t=_483FEC15-900D-4CF1-B514-1B921DD055BA&amp;sort=%40ftitle51880%20ascending" response = requests.get(url) data = response.text soup = BeautifulSoup(data, 'lxml') tags = soup.find_all('a') for tag in tags: print(tag.get('href'))
has comment: http://stackoverflow.com/comment/89751312
has answer: http://stackoverflow.com/a/51547907
has answer: http://stackoverflow.com/a/51389586
type: UnansweredQuestion
type: Question
tagged with: href

http://stackoverflow.com/comment/89783788
comment on: http://stackoverflow.com/a/51406030
score: 0
type: AnswerComment
type: Comment
has text: @fdmillion The only case that can be a bit of a pain is if you’re switching back and forth between conflicting git branches rapidly. For that case, you might want something extra. But just a git hook that uninstalls (or even force-reinstalls) the library on checkout (maybe also testing that you’re in a venv and raising an error if not) solves that.

http://stackoverflow.com/q/51325227
possible better answer: http://stackoverflow.com/a/51325348
has comment: http://stackoverflow.com/comment/89641007
has body: I have some data in a pandas dataframe, where the date column is the index, as follows: date value A value B country category ddmmyy A1 B1 US Red ddmmyy A2 B2 US Red ddmmyy A3 B3 UK Green ddmmyy A4 B4 UK Green ddmmyy A5 B5 US Red ddmmyy A6 B6 US Red There are multiple countries (other than UK, US) and multiple categories (other than red and green). The dates represent transactions and occur at an irregular frequency. I want to regroup the data as follows: date UK US mmyy num11 num21 mmyy num12 num22 mmyy num13 num23 mmyy num14 num24 Where 1. The dates are regular consecutive monthly dates 2. num11 for the UK is the weighted average of A1xB1, A2xB2 etc i.e. weighted average for a given month = sum {An x Bn} in the given month, divided by sum of Bn in the given month. And likewise for US. I have tried using e.g. dataframe['Val A'].resample('M', how='sum') Which resamples col A into monthlu buckets by summing the number e.g. A1, A2 etc. per month. But doesnt give me the weighted average I want per country. Whats the best way to do this in Pandas/Python?
has title: How to pivot a pandas dataframe to include a weighted average?
score: 0
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/89636518
accepted answer: http://stackoverflow.com/a/51325572
tagged with: python
has answer: http://stackoverflow.com/a/51325348
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51325572
has comment: http://stackoverflow.com/comment/89640309
type: Question

http://stackoverflow.com/q/51438283
has title: Required radio buttons HTML / Flask
answer count: 1
has comment: http://stackoverflow.com/comment/89900508
favorite count: 0
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has answer: http://stackoverflow.com/a/51446750
score: 2
downvote count: 0
type: UnansweredQuestion
type: Question
tagged with: flask
upvote count: 2
has body: I'm making a sentiment analysis UI using Flask and HTML5. On the homepage html page (linked from Flask using render_template), I have radio buttons. I have a custom message and a "required" setting so that if a radio button is not selected and the user tries to hit "submit", a message shows up and the user is not able to submit. The problem is that if a radio button is not selected, the message will not go away, and will not allow the user to submit their answer even if they do select a button. The page must be refreshed to escape this. If I remove the whole "onvalid" part and just leave the "required" part, it works totally fine, but then I lose the custom message and just have a default one. I would be grateful if somebody could help me understand why this is happening and how to fix it. Thanks very much in advance. Here's the section of the code that's bugging (specifically the 4th line): Very negative Negative Neutral Positive Very Positive This sentence is in English

http://stackoverflow.com/q/51361111
has answer: http://stackoverflow.com/a/52069584
has answer: http://stackoverflow.com/a/51817547
has body: I'm writing a spark job using pyspark; I should only read from mongoDB collection and print the content on the screen; the code is the following: import pyspark from pyspark.sql import SparkSession my_spark = SparkSession.builder.appName("myApp").config("spark.mongodb.input.uri", "mongodb://127.0.0.1/marco.weather_test").config("spark.mongodb.output.uri", "mongodb://127.0.0.1/marco.out").getOrCreate() df = my_spark.read.format("com.mongodb.spark.sql.DefaultSource").option("uri", "mongodb://127.0.0.1/marco.weather_test").load() #df.printSchema() df.show() the problem is that when I want to print the schema the job works, but when I want to print the content of the dataFrame with show() function I get back the error: #java.lang.NoSuchFieldError: DECIMAL128 the command I use is: #bin/spark-submit --packages org.mongodb.spark:mongo-spark-connector_2.11:2.2.3 /home/erca/Scrivania/proveTesi/test_batch.py
tagged with: apache-spark
answer count: 3
has answer: http://stackoverflow.com/a/57229426
downvote count: 0
favorite count: 0
has title: java.lang.NoSuchFieldError: DECIMAL128 mongoDB spark
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90541108
score: 1
upvote count: 1
type: Question
tagged with: mongodb

http://stackoverflow.com/a/51389807
score: 1
has body: def __str__(self): return '{} : {}'.format(Point.__str__(self), self.label) Your _str_ method only has single underscores around it. It also doesn't do anything with the value Point.__str__(self) @Patrick Haugh (couldn't say it better myself)
has comment: http://stackoverflow.com/comment/89751913
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51389769
has comment: http://stackoverflow.com/comment/89751982
upvote count: 1

http://stackoverflow.com/comment/89659655
comment on: http://stackoverflow.com/q/51342724
score: 0
type: QuestionComment
has text: Looking forward to your updated question. Anyway, if you "should rewrite" then you should do some reading first. "Just running" classification algorithms will shoot you in the leg sooner or later. For sure.
type: Comment

http://stackoverflow.com/a/51410781
has body: Took me a while, but here are thee possible solution. Hope they are self explanatory. Written in Python 3.x in Jupyter Notebook. One remark: if your coordinates are world coordinates, you may think of using the Haversine distance (circular distance) instead of the Euclidean distance which is a straight line. First, create your data import pandas as pd import numpy as np values = [ { 'x':-1.0, 'y':7.0, 'z':0.0, 'ind':21, 'pos':[-2.76788330078, 217.786453247, 26.6822681427] }, { 'z':0.0, 'ind':22, 'pos':[-7.23852539062, 217.274139404, 26.6758270264] }, { 'y':0.0, 'z':1.0, 'ind':152, 'pos':[-0.868591308594, 2.48404550552, 48.4036369324] }, { 'y':6.0, 'z':2.0, 'ind':427, 'pos':[-0.304443359375, 182.772140503, 79.4475860596] } ] def dist(a, b): """ Calculates the Euclidean distance between two 3D-vectors. """ diff = np.array(a) - np.array(b) d = np.sqrt(np.dot(diff, diff)) return d df_initial = pd.DataFrame(values) The following three solutions will generate this output: pairs distance 1 (21, 22) 4.499905 3 (21, 427) 63.373886 7 (22, 427) 63.429709 First solution is based on a full join of the data with itself. Downside is that it may exceed your memory if the dataset is huge. Advantages are the easy readability of the code and the usage of Pandas only: #%%time df = df_initial.copy() # join data with itself, each line will contain two geo-positions df['tmp'] = 1 df = df.merge(df, on='tmp', suffixes=['1', '2']).drop('tmp', axis=1) # remove rows with similar index df = df[df['ind1'] != df['ind2']] # calculate distance for all df['distance'] = df.apply(lambda row: dist(row['pos1'], row['pos2']), axis=1) # filter only those within a specific distance df = df[df['distance'] &lt; 70] # combine original indices into a tuple df['pairs'] = list(zip(df['ind1'], df['ind2'])) # select columns of interest df = df'pairs', 'distance' def sort_tuple(idx): x, y = idx if y &lt; x: return y, x return x, y # sort values of each tuple from low to high df['pairs'] = df['pairs'].apply(sort…
has comment: http://stackoverflow.com/comment/89793190
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/89793142
score: 2
accepted answer of: http://stackoverflow.com/q/51409927
answers question: http://stackoverflow.com/q/51409927
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89794989

http://stackoverflow.com/a/51330691
has body: To get the desired output: Read the file line by line. Remove the last character if it is '\'. Join the modified lines. The above operations should provide the required result. I think using regex would just complicate the solution without any added benefits. Quoting the doc on lexical analysis: When an 'r' or 'R' prefix is present, a character following a backslash is included in the string without change, and all backslashes are left in the string. For example, the string literal r"\n" consists of two characters: a backslash and a lowercase 'n'. String quotes can be escaped with a backslash, but the backslash remains in the string; for example, r"\"" is a valid string literal consisting of two characters: a backslash and a double quote; r"\" is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character). Note also that a single backslash followed by a newline is interpreted as those two characters as part of the string, not as a line continuation.
type: Answer
has comment: http://stackoverflow.com/comment/89637711
has comment: http://stackoverflow.com/comment/89638683
score: 1
accepted answer of: http://stackoverflow.com/q/51330160
has comment: http://stackoverflow.com/comment/89739288
upvote count: 1
answers question: http://stackoverflow.com/q/51330160
has comment: http://stackoverflow.com/comment/89638075
has comment: http://stackoverflow.com/comment/89810277
has comment: http://stackoverflow.com/comment/89637893
has comment: http://stackoverflow.com/comment/89638654
has comment: http://stackoverflow.com/comment/89638396
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89918237
type: QuestionComment
comment on: http://stackoverflow.com/q/51466241
has text: @PydPiper the question has been removed from the hold queue; you can now post your solution as an answer.
score: 0
type: Comment

http://stackoverflow.com/a/51439946
accepted answer of: http://stackoverflow.com/q/51439770
answers question: http://stackoverflow.com/q/51439770
has body: Use {{form}} instead of using {{ login_form }} that's what you are sending to the frontend.
type: AcceptedAnswer
score: 0
type: Answer

docker-api
tag name: docker-api
type: Tag
tags question: http://stackoverflow.com/q/51348473

http://stackoverflow.com/a/51346836
score: 1
answers question: http://stackoverflow.com/q/51346126
upvote count: 1
has comment: http://stackoverflow.com/comment/89674803
accepted answer of: http://stackoverflow.com/q/51346126
has comment: http://stackoverflow.com/comment/89675124
has comment: http://stackoverflow.com/comment/89675836
has body: I think you make it quite complex. The core problem is here that your collection contains two types of elements Posts and shares. I really advice you not to do this, since it will only make it harder to process it. We can however construct for example a queryset that will return posts that are either posted by the user, or shared by that user. For example with: from django.db.models import Q from django.db.models.functions import Coalesce Post.objects.filter( Q(user=some_user) | Q(share__user=some_user) ).annotate( shared_or_created=Coalesce('share__shared_at', 'created_at') ).order_by('-shared_or_created') So now we have a list of posts that are either created by some_user, or shared by some_user. Next we annotate each post with a shared_or_created field that either contains the time when it was shared, or in case it was not shared (so created by the user), the time when it was created. Finally we sort on that attribute in descending order. The advantage of encoding this into a query, is that it is processed at the database level. Furthermore it is still a queryset, so you can add extra filters, slicing, etc. on it.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89675319
has comment: http://stackoverflow.com/comment/89675872
type: Answer
has comment: http://stackoverflow.com/comment/89675353

http://stackoverflow.com/comment/89729587
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51378928
type: Comment
has text: Yeap, ChromeDriver team explicitly have kept an announcement that `maximize_window()` is still WIP.

http://stackoverflow.com/q/51474868
score: 1
type: Question
has title: object type columns to float32 type using Pandas python 35
has answer: http://stackoverflow.com/a/51474979
has body: Here is what I have tried and the result with error: df.info() df'volume', 'open', 'high', 'low', 'close' =pd.Series( df'volume', 'open', 'high', 'low', 'close', dtype='float32') Output with Error: &lt;class 'pandas.core.frame.DataFrame'&gt; Index: 4999 entries, 2018-06-01T00:01:00.000000000Z to 2018-06-06T14:20:00.000000000Z Data columns (total 6 columns): volume 4999 non-null object close 4999 non-null object high 4999 non-null object low 4999 non-null object open 4999 non-null object complete 4999 non-null object dtypes: object(6) memory usage: 273.4+ KB --------------------------------------------------------------------------- ValueError Traceback (most recent call last) c:\python35\lib\site-packages\pandas\core\common.py in _asarray_tuplesafe(values, dtype) 398 result = np.empty(len(values), dtype=object) --&gt; 399 result[:] = values 400 except ValueError: ValueError: could not broadcast input array from shape (4999,5) into shape (4999) During handling of the above exception, another exception occurred: ValueError Traceback (most recent call last) &lt;ipython-input-23-b205607bf5cf&gt; in &lt;module&gt;() 1 df'volume', 'open', 'high', 'low', 'close'.iloc[50:60] #, 'complete' 2 df.info() ----&gt; 3 df'volume', 'open', 'high', 'low', 'close' =pd.Series( df'volume', 'open', 'high', 'low', 'close', dtype='float32') 4 # df = pd.to_numeric(df, errors='ignore') c:\python35\lib\site-packages\pandas\core\series.py in __init__(self, data, index, dtype, name, copy, fastpath) 262 else: 263 data = _sanitize_array(data, index, dtype, copy, --&gt; 264 raise_cast_failure=True) 265 266 data = SingleBlockManager(data, index, fastpath=True) c:\python35\lib\site-packages\pandas\core\series.py in _sanitize_array(data, index, dtype, copy, raise_cast_failure) 3275 raise Exception('Data must be 1-dimensional') 3276 else: -&gt; 3277 subarr = _asarray_tuplesafe(data, dtype=dtype) 3278 3279 # This is to prevent mixed-type Series getting all casted to c:\python35\lib\…
tagged with: pandas
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/51474979
type: AnsweredQuestion

http://stackoverflow.com/comment/89628206
type: Comment
has text: @MichaelDz - You need unfortunately sorting columns by `df = df.sort_index(axis=1)`, so order of columns should be changed, se also [docs](http://pandas.pydata.org/pandas-docs/stable/advanced.html#sorting-a-multiindex)
comment on: http://stackoverflow.com/a/51326399
score: 0
type: AnswerComment

http://stackoverflow.com/a/51375423
has comment: http://stackoverflow.com/comment/101697887
upvote count: 1
downvote count: 1
has body: n_estimators is the parameter of the model constructor in sklearn API, that controls the number of trees to be built. You can also set it via model.set_params().
answers question: http://stackoverflow.com/q/51337593
score: 0
has comment: http://stackoverflow.com/comment/101587616
has comment: http://stackoverflow.com/comment/101605637
has comment: http://stackoverflow.com/comment/101716437
type: Answer

http://stackoverflow.com/comment/89649347
comment on: http://stackoverflow.com/a/51337308
score: 1
has text: I'm tempted to edit in the Jupyter tag to your question because I think this sidesteps some of the weirdness that even iPython can introduce (I can't reproduce), so it seems more localised. But I'll leave that decision to you.
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51404032
accepted answer: http://stackoverflow.com/a/51404186
has title: Python Pandas slice column string up to a character based on condition
type: Question
has answer: http://stackoverflow.com/a/51404186
tagged with: pandas
upvote count: 1
answer count: 1
has body: I tried different ways to slice Panda column strings up to a specific character based on a condition. For example, consider the Kaggle's Titanic data set where I would like to slice all names in column "Name" up to '(' character in case that they include that character so that there exist no brackets in names and names only include the characters before the beginning of the bracket. So you can think of it as getting rid of the brackets to stay with what was before the bracket. Sample of my data set I used this way: df.loc[df['Name'].str.rfind('(') &gt; -1, 'Name'] = df['Name'].str.slice(0, df['Name'].str.rfind('(')) which essentially when finds a name which contains '(' it proceeds into slicing it, otherwise it returns the name (which does not include the opening bracket. The slicing is all about finding and take the characters before the opening bracket. My solution does not work since it produces "NaN", how can I fix it?
favorite count: 0
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1

http://stackoverflow.com/q/51429286
has comment: http://stackoverflow.com/comment/89829750
tagged with: dataframe
has body: My dataset has a few interesting columns that I want to aggregate, and hence create a metric that I can use to do some more analysis. The algorithm I wrote takes around ~3 seconds to finish, so I was wondering if there is a more efficient way to do this. def financial_score_calculation(df, dictionary_of_parameters): for parameter in dictionary_of_parameters: for i in dictionary_of_parameters[parameter]['target']: index = df.loc[df[parameter] == i].index for i in index: old_score = df.at[i, 'financialliteracyscore'] new_score = old_score + dictionary_of_parameters[parameter]['score'] df.at[i, 'financialliteracyscore'] = new_score for i in df.index: old_score = df.at[i, 'financialliteracyscore'] new_score = (old_score/27.0)*100 #converting score to percent value df.at[i, 'financialliteracyscore'] = new_score return df Here is a truncated version of the dictionary_of_parameters: dictionary_of_parameters = { # money management parameters "SatisfactionLevelCurrentFinances": {'target': [8, 9, 10], 'score': 1}, "WillingnessFinancialRisk": {'target': [8, 9, 10], 'score': 1}, "ConfidenceLevelToEarn2000WithinMonth": {'target': [1], 'score': 1}, "DegreeOfWorryAboutRetirement": {'target': [1], 'score': 1}, "GoodWithYourMoney?": {'target': [7], 'score': 1} } EDIT: generating toy data for df df = pd.DataFrame(columns = dictionary_of_parameters.keys()) df['financialliteracyscore'] = 0 for i in range(10): df.loc[i] = dict(zip(df.columns,2*i*np.ones(6)))
score: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/89829725
has comment: http://stackoverflow.com/comment/89829796
accepted answer: http://stackoverflow.com/a/51430003
tagged with: python
has comment: http://stackoverflow.com/comment/89830316
type: AnsweredQuestion
has title: Generating new column of data by aggregating specific columns of dataset
has answer: http://stackoverflow.com/a/51430003
has comment: http://stackoverflow.com/comment/89831105
type: Question

http://stackoverflow.com/a/70095176
score: 1
upvote count: 1
has body: The recommended answer is good, but will struggle when dealing with arrays with a large number of rows. An alternative is: baseval = np.max([a.max(), b.max()]) + 1 a[:,1] = a[:,1] * baseval b[:,1] = b[:,1] * baseval c = np.isin(np.sum(a, axis=1), np.sum(b, axis=1)) This uses the maximum value contained in either array plus 1 as a numeric base and treats the columns as baseval^0 and baseval^1 values. This ensures that the sum of the columns are unique for each possible pair of values. If the order of the columns is not important then both input arrays can be sorted column-wise using np.sort(a,axis=1) beforehand. This can be extended to arrays with more columns using: baseval = np.max([a.max(), b.max()]) + 1 n_cols = a.shape[1] a = a * baseval ** np.array(range(n_cols)) b = b * baseval ** np.array(range(n_cols)) c = np.isin(np.sum(a, axis=1), np.sum(b, axis=1)) Overflow can occur when baseval ** (n_cols+1) &gt; 9223372036854775807 if using int64. This can be avoided by setting the numpy arrays to use python integers using dtype=object.
has comment: http://stackoverflow.com/comment/126475347
type: Answer
answers question: http://stackoverflow.com/q/51352527
downvote count: 0

http://stackoverflow.com/a/51459733
type: AcceptedAnswer
upvote count: 17
has body: Either sort_values and drop_duplicates, df1.sort_values('Count').drop_duplicates('Name', keep='last') Name Count 1 Mary 22 2 John 50 Or, like miradulo said, groupby and max. df1.groupby('Name')['Count'].max().reset_index() Name Count 0 John 50 1 Mary 22
type: Answer
has comment: http://stackoverflow.com/comment/89888916
downvote count: 0
has comment: http://stackoverflow.com/comment/89889424
score: 17
answers question: http://stackoverflow.com/q/51459651
accepted answer of: http://stackoverflow.com/q/51459651
has comment: http://stackoverflow.com/comment/89888829

http://stackoverflow.com/a/51344319
downvote count: 0
answers question: http://stackoverflow.com/q/51344283
type: Answer
upvote count: 1
has body: When iterating over the dictionary try calling the dict.items() method: sessions1 = {10000:'val1',100000:'val2',2000:'val3',3000:'val4',4000:'val5',5000:'val6',6000:'val7',7000:'val8',8000:'val9',9000:'val10',10000:'val11'} def buildDF(result_set): master_dm = [] for k,v in result_set.items(): master_dm.append(v) return(master_dm) sessions1DF = buildDF(sessions1) print(sessions1DF) # ['val11', 'val2', 'val6', 'val5', 'val3', 'val8', 'val4', 'val9', 'val7', 'val10']
score: 1

http://stackoverflow.com/a/51410140
has comment: http://stackoverflow.com/comment/89795375
has comment: http://stackoverflow.com/comment/89793485
accepted answer of: http://stackoverflow.com/q/51409685
upvote count: 2
has body: Short version The MATLAB code should have been written like this: function [kf, Ek]=hysime(y, n, Rn, verbose); error(nargchk(3, 4, nargin)) if nargin &lt; 4 verbose = true; else verbose = ~strcmpi(verbose ,'off'); end If you know MATLAB, this should be clearer. The (mostly) corresponding Python code can be written like this: def hysime(y, n, Rn, verbose=True): # rest of the function here return kf, Ek Long Version This function expects 3 or 4 input arguments, with a default value set if the fourth argument is not provided. However, it is done in a way that is much more complicated than it needs to be (although I see this pattern a lot). Ideally in MATLAB you would specify the same thing like this: function [varargout]=hysime(y, n, Rn, verbose) error(nargchk(3, 4, nargin)) if nargin &lt; 4 verbose = true; else verbose = ~strcmpi(verbose ,'off'); end So what it is doing is putting the first argument in the variable y, the second in the variable n, the third in Rn, and if the fourth is specified put it in verbose (based on how it compares to the string 'off'), otherwise set verbose to true. In python, handling of optional arguments is built-in. You can specify default value for arguments right in the function definition by setting name=value, where name is the argument name and value is the default value. Also, for historical reasons MATLAB often uses 'on' and 'off' instead of true and false. This is almost never done in Python, people just use True and False. So you can specify the same thing in Python like so: def hysime(y, n, Rn, verbose=True): This makes y, n, and Rn required arguments, but lets verbose be optional. This doesn't handle the case where verbose is set to the string 'off'. As I said, this is common in MATLAB for historical reasons, but you really shouldn't be doing it in MATLAB anymore when you can avoid it, and you definitely shouldn't be doing it in Python. But if you really, really need to handle that case, you can just do: def hysime(y, n, Rn, verb…
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51409685
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89835277
type: Comment
type: QuestionComment
has text: Your attempts would be nice to see. Did you try `print u'\xc2'.encode('utf8') `, for instance? (Probably not, since it says `Â`.)
comment on: http://stackoverflow.com/q/51432164
score: 0

http://stackoverflow.com/a/51338475
has comment: http://stackoverflow.com/comment/89651926
has comment: http://stackoverflow.com/comment/89669771
type: Answer
has body: Yes, you must call the functions within your code or they will not be called and will not run. You just call a class you must instantiate the class, try and instantiate your class and call the functions appropriately. More information on functions can be found here.
has comment: http://stackoverflow.com/comment/89651976
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89651895
has comment: http://stackoverflow.com/comment/89669761
answers question: http://stackoverflow.com/q/51338380
upvote count: 1

http://stackoverflow.com/a/51414361
score: 1
has body: &gt;&gt;&gt; import re &gt;&gt;&gt; re.sub(',,+', ',', '30121,long,Mehtab,10,20,,30') '30121,long,Mehtab,10,20,30'
answers question: http://stackoverflow.com/q/51414271
upvote count: 1
type: Answer
downvote count: 0

http://stackoverflow.com/comment/89684314
comment on: http://stackoverflow.com/q/51356024
score: 0
has text: Which column corresponds to name identifier ?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51394955
tagged with: pybind11
favorite count: 0
has comment: http://stackoverflow.com/comment/89779603
tagged with: python
has body: I know how to remove the module prefix for functions in automodule directive by set "add_module_names = False". Remove package and module name from sphinx function However it can't remove the module prefix for the args in automodule directive. Below is the document generated by automodule. you can see the data type of self arg has a long prefix like "PyPhysLeo.data_core". data_core submodule class BufferDataD a class which manage CPU buffer and GPU buffer simultaneously, data type is double CPU2GPU(self: PyPhysLeo.data_core.BufferDataD) → None GPU2CPU(self: PyPhysLeo.data_core.BufferDataD) → None allocateCPU(self: PyPhysLeo.data_core.BufferDataD) → None allocateGPU(self: PyPhysLeo.data_core.BufferDataD) → None setZeroCPU(self: PyPhysLeo.data_core.BufferDataD) → None setZeroGPU(self: PyPhysLeo.data_core.BufferDataD) → None size(self: PyPhysLeo.data_core.BufferDataD) → int
has comment: http://stackoverflow.com/comment/89764685
tagged with: python-sphinx
type: UnansweredQuestion
upvote count: 7
linked to: http://stackoverflow.com/q/20864406
score: 7
has title: sphinx remove module prefix for args in automodule
has comment: http://stackoverflow.com/comment/89778496
type: Question
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/51407944

http://stackoverflow.com/a/51376492
downvote count: 1
has comment: http://stackoverflow.com/comment/89773025
answers question: http://stackoverflow.com/q/51376341
has comment: http://stackoverflow.com/comment/89724503
has comment: http://stackoverflow.com/comment/89724733
upvote count: 0
has comment: http://stackoverflow.com/comment/89773147
has comment: http://stackoverflow.com/comment/89772842
has comment: http://stackoverflow.com/comment/89726786
has comment: http://stackoverflow.com/comment/89772880
has body: I can't understand why you're doing any of this. All you need to do is to load the YAML, add your new items, and then dump it again. with open('thing.yaml', 'r') as infile: d = yaml.load(infile) d['new'] = {'x': 5, 'y': 6} with open('newthing.yaml', 'w') as outfile: yaml.dump(d, outfile, default_flow_style=False, allow_unicode=True)
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/89772638
has comment: http://stackoverflow.com/comment/89772875

http://stackoverflow.com/q/51461004
tagged with: python
has title: Django unique "username" when using local user authentication and "Django Social auth" application
score: 1
has comment: http://stackoverflow.com/comment/89892604
type: Question
has body: I am using Django local user registration as well as some social media authentication using Django-social_auth webapp. When I go to user table to check the usernames, It looks to me that Django might compromise the uniqueness of the username. For example, if i have two emails "abcdef@gmail.com" and "abcdef@yahoo.com" how would it store such things in the user table as it stores "abcdef" part in the username column.
tagged with: django-socialauth
answer count: 1
has answer: http://stackoverflow.com/a/51482624
has comment: http://stackoverflow.com/comment/89892089
upvote count: 1
favorite count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: django

http://stackoverflow.com/comment/89902872
has text: Hey I have altered my post so as to include the first 10 inputs for the x values (which is days where for example 0.0.015239999629557 is the partial of the day (24*60*0.015239999629557 ~ 00:22). My y values are just amplitudes.Thanks
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51465283

http://stackoverflow.com/comment/90008629
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51463480
score: 0
has text: I don't see any duplicates there either. Which two entries are duplicates?

http://stackoverflow.com/q/51333966
tagged with: list
has title: Sorting a list of lists in a list
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/89643299
possible better answer: http://stackoverflow.com/a/51334667
tagged with: sorting
score: 4
has answer: http://stackoverflow.com/a/51334667
has answer: http://stackoverflow.com/a/51333992
answer count: 2
has body: Say I have a list inside a list, that is contained inside a list. For example: foo = [[[2, 2, 2], [1, 1, 1], [3, 3, 3]], [[2, 2, 2], [1, 1, 1], [3, 3, 3]]] And I wanted to sort it in order: foo = [[[1, 1, 1], [2, 2, 2], [3, 3, 3]], [[1, 1, 1], [2, 2, 2], [3, 3, 3]]] I could use [sorted(i) for i in foo] to achieve this. However is there some way to sort this list without list comprehension (or creating a new list)? The values inside the lists themselves will change but do not need to be sorted. Everything I have tried just boils down to the same method as above.
has comment: http://stackoverflow.com/comment/89643253
downvote count: 0
has comment: http://stackoverflow.com/comment/89643263
favorite count: 0
has comment: http://stackoverflow.com/comment/89643268
tagged with: python-3.x
tagged with: python
accepted answer: http://stackoverflow.com/a/51333992
has comment: http://stackoverflow.com/comment/89643236
type: AnsweredQuestion

http://stackoverflow.com/comment/89694691
type: Comment
comment on: http://stackoverflow.com/a/51347924
has text: each activity has different goal .. the majority holds one goal but it is possible for an activity to have more than one. same goes for events. The real problem is date locations as each activity has easily +2 of these with distinct values. I would like to do something like ordering them all by the start date. and then take the distinct activity id and present them as "being ordered by the start date"
type: AnswerComment
score: 0

chocolatey
tag name: chocolatey
tags question: http://stackoverflow.com/q/51341034
type: Tag

http://stackoverflow.com/comment/89886603
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51458555
has text: Also, you appear to be making the common mistake of inheriting from `dict` *and* having another dict as an instance variable. Don't do that; pick one or the other, or you'll end up wasting space and having very confusing bugs where data ends up in one dict when you were expecting it to land in the other.

http://stackoverflow.com/comment/89812516
comment on: http://stackoverflow.com/a/51377771
score: 0
type: AnswerComment
type: Comment
has text: @raam - Can you explain more? Because here is completely changed structure of origianl DataFrame.

http://stackoverflow.com/a/51406764
has comment: http://stackoverflow.com/comment/89785020
type: Answer
score: 3
has comment: http://stackoverflow.com/comment/89784669
upvote count: 3
has body: sure, they are normal files. Only difference is that they define that the folder is a package. From python official basic tutorial: The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later. Note that you usually don't put your code in __init__.py but instead define it in the packages' modules and import only the names you want to expose in the package namespace. Here's an example on how to access then, suppose you have this directory structure: Development/ main.py setup.py myprogram/ __init__.py other.py The myprogram folder is considered a package because of __init__.py so in main.py you can do: import myprogram myprogram.something() # defined in `__init__.py` import myprogram.other # the submodule other.py inside the package
accepted answer of: http://stackoverflow.com/q/51406756
has comment: http://stackoverflow.com/comment/134584421
answers question: http://stackoverflow.com/q/51406756
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89740220
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51383790
has text: could you please post some code?

http://stackoverflow.com/a/51450438
has comment: http://stackoverflow.com/comment/96875101
answers question: http://stackoverflow.com/q/51448972
upvote count: 2
score: 2
has body: There are several reasons why UDP packets can be lost, and certainly the speed of being able to take them off the socket queue and store them can be a factor, at least eventually. However, even if you had a dedicated C language program handling them, it's unlikely you'll be able to receive all the UDP packets if you expect to receive more than a million a second. The first thing I'd do is to determine if python performance is actually your bottleneck. It is more likely in my experience that, first and foremost, you're simply running out of receive buffer space. The kernel will store UDP datagrams on your socket's receive queue until the space is exhausted. You might be able to extend that capacity a little with a C program, but you will still exhaust the space faster than you can drain the socket if packets are coming in at high enough speed. Assuming you're running on linux, take a look at this answer for how to configure the socket's receive buffer space -- and examine the system-wide maximum value, which is also configurable and might need to be increased. https://stackoverflow.com/a/30992928/1076479 (If you're not on linux, I can't really give any specific guidance, although the same factors are likely to apply.) It is possible that you will be unable to receive packets fast enough, even with more buffer space and even in a C program. In that case, @game0ver's idea of using tcpdump might work better if you only need to withstand a short intense burst of packets as it uses a much lower-level interface to obtain packets (and is highly optimized). But then of course you won't just have the UDP payload, you'll have entire raw packets and will need to strip the IP and Ethernet layer headers as well before you can process them.
has comment: http://stackoverflow.com/comment/90052971
downvote count: 0
has comment: http://stackoverflow.com/comment/90023128
type: Answer

http://stackoverflow.com/comment/89775459
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51400919
has text: `pip install --user <your_user> pymongo`
type: Comment

http://stackoverflow.com/comment/89756522
type: Comment
comment on: http://stackoverflow.com/q/51392321
has text: Possible duplicate of [Print in terminal with colors?](https://stackoverflow.com/questions/287871/print-in-terminal-with-colors)
score: 4
type: QuestionComment

http://stackoverflow.com/a/51458822
has body: class numbers: def __init__(self, first, second): self.first=first self.second=second def swap(self, x): def swapp(a): i=0 rev=0 a=int(a) while (a&gt;0): i=a%10 a=int(a/10) rev=rev*10+i return rev return swapp(x) var1=numbers(int(input("num1 \n")),int(input("num2 \n"))) var1_1=var1.swap(12) print(var1_1) &gt;&gt; 21 # i.e. Reverse of 12 meant as an output of swapp method. I believe you tend to utilise it that way. Couple of things wrong with your code. Your swap() method doesn't return anything. I assume it needs to call and return you nested swapp() method. Your name swap is misleading as actually it is reversing an integer. You can pass a self instance as in the above code i.e. the . operator not by var1_1=numbers.swap(var1). Instance.method() automatically implies the first argument to the method would be self. Your swapp method needs an argument. A single argument. In my case I passed a constant but you can pass any instance.variable like var1.first to it.
type: Answer
has comment: http://stackoverflow.com/comment/89887059
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89887010
has comment: http://stackoverflow.com/comment/89887083
answers question: http://stackoverflow.com/q/51458685
upvote count: 1

http://stackoverflow.com/a/51385397
type: Answer
answers question: http://stackoverflow.com/q/51384894
has body: You could just edit the textfile and add the non-array data values that way: np.savetxt(fp, I[None], fmt='%e', delimiter=',') with open(fp,'a') as f: f.write("non-array data values")
score: 0

http://stackoverflow.com/a/51369106
has comment: http://stackoverflow.com/comment/89725104
has comment: http://stackoverflow.com/comment/89723260
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51365267
type: Answer
accepted answer of: http://stackoverflow.com/q/51365267
upvote count: 6
score: 6
has body: pytest is very good at doing all kind of metaprogramming stuff for the tests. If I understand your question correctly, the code below will do the dynamic tests marking with pytestrail.case marker. In the project root dir, create a file named conftest.py and place this code in it: import csv from pytest_testrail.plugin import pytestrail with open('website1.csv') as f: reader = csv.reader(f) next(reader) tests = [r for r in reader] def pytest_collection_modifyitems(items): for item in items: for testid, testname in tests: if item.name == testname: item.add_marker(pytestrail.case(testid)) Now you don't need to mark the test with @pytestrail.case()at all - just write the rest of code and pytest will take care of the marking: def test_login(): assert True When pytest starts, the code above will read website1.csv and store the test IDs and names just as you did in your code. Before the test run starts, pytest_collection_modifyitems hook will execute, analyzing the collected tests - if a test has the same name as in csv file, pytest will add the pytestrail.case marker with the test ID to it.

http://stackoverflow.com/q/51404873
tagged with: python
has title: Python is taking a very long time to execute code
has body: I'm using PyCharm community 2018. I'm trying to find the sum of prime numbers from 1 to two million and this is my code. primes = [x for x in range (1,2000000) if all (x%y!=0 for y in range (2,x))] total = 0 for x in primes: total = total + x print (total) It's been 20 minutes and I've still got no output. Do you have any suggestions to make it run faster or is my method wrong?
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51404998
has comment: http://stackoverflow.com/comment/89780641
type: Question
has answer: http://stackoverflow.com/a/51404937
has answer: http://stackoverflow.com/a/51404986
tagged with: performance
has comment: http://stackoverflow.com/comment/89780812
tagged with: execution
score: 0
has comment: http://stackoverflow.com/comment/89780671
answer count: 3
accepted answer: http://stackoverflow.com/a/51404937
linked to: http://stackoverflow.com/q/2068372
has answer: http://stackoverflow.com/a/51404998

http://stackoverflow.com/q/51419541
score: 1
accepted answer: http://stackoverflow.com/a/51419886
type: Question
tagged with: missing-data
has answer: http://stackoverflow.com/a/51419886
has title: Python - Replace missing values with mean
upvote count: 1
answer count: 1
has body: As a beginner I'm doing a python course. In this course they use a dataset dataset with resp. the column names: "Country", "Age", "Salary" and "Purchased". In the 2nd and 3rd column (Age and Salary) are a few missing values. For Python starts counting the columns with 0, I would expect the following code does the job: from sklearn.preprocessing import Imputer imputer = Imputer(missing_values="NaN",strategy="mean", axis=0) imputer=imputer.fit(X[:,1:2]) X[:,1:2] =imputer.transform(X[:,1:2]) However, in this course they say that we need to use everywhere X[:,1:3] and I don't understand why.
tagged with: scikit-learn
favorite count: 0
tagged with: python
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/a/52566528
has body: I believe this is a Python bug, specific to the embeddable (ZIP file without an installer) Windows distribution. I’ve filed https://bugs.python.org/issue34841. Removing the python37._pth file (presumably python36._pth in your case) from the distribution fixed it for me.
downvote count: 0
type: Answer
upvote count: 13
score: 13
answers question: http://stackoverflow.com/q/51403126

http://stackoverflow.com/q/51470198
has answer: http://stackoverflow.com/a/51470356
has comment: http://stackoverflow.com/comment/89908704
tagged with: python
upvote count: 1
answer count: 1
tagged with: discord.py
has comment: http://stackoverflow.com/comment/89912263
type: UnansweredQuestion
has title: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Command' object has no attribute 'server'
has body: @FiveStarBot.command(pass_context=True) async def globalmessage(cxt, *, text : str): x = message.server.members for member in x: await FiveStarBot.send_message(member.name, text) Why doesn't this work? I'm beginner programmer
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89909854
has comment: http://stackoverflow.com/comment/89908752
type: Question

http://stackoverflow.com/comment/89766568
has text: `HAVING` keyword in SQL is not used to `SELECT` values
comment on: http://stackoverflow.com/q/51397747
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89635438
score: 0
type: AnswerComment
has text: You are the MVP! I admit I should have seen that mistake myself :P but thx for the prompt reply!
type: Comment
comment on: http://stackoverflow.com/a/51329653

http://stackoverflow.com/comment/89749005
comment on: http://stackoverflow.com/a/51387794
has text: Tnx so much! understand now! I thought like C base languages need to define all variables first, and I had problem with these special cases! but your answer was helpful :)
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89857669
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51443526
has text: Can we help me? How you can combine or simplify my list with special symbols? May be Python have got a something function or module with them?

http://stackoverflow.com/q/51428597
accepted answer: http://stackoverflow.com/a/51428645
has comment: http://stackoverflow.com/comment/89828683
type: Question
has comment: http://stackoverflow.com/comment/89828927
answer count: 2
has comment: http://stackoverflow.com/comment/89828850
score: -3
has comment: http://stackoverflow.com/comment/89828864
tagged with: pandas
has title: How can I count the number of cycles in a column with cyclic values?
has comment: http://stackoverflow.com/comment/89828977
favorite count: 0
has answer: http://stackoverflow.com/a/51428645
has body: I have this DataFrame: import pandas as pd data = {'c': [1,2,1,2,3,2,3], 'b': [5,6,4,5,5,6,4]} df = pd.DataFrame(data = data) and I want to create the column N with the cycle number of c: b c N 0 5 1 1 1 6 2 1 2 4 1 2 3 5 2 2 4 5 3 2 5 6 2 3 6 4 3 3 How can I do that?
tagged with: python
has comment: http://stackoverflow.com/comment/89828370
downvote count: 6
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51428724
upvote count: 3
has answer: http://stackoverflow.com/a/51428724
has comment: http://stackoverflow.com/comment/89828713

http://stackoverflow.com/comment/89725220
has text: Think of it this way: "Amadan" is a name that identifies me, but we shortcut and say "Amadan" is me (although when you take a closer look, it should be rather obvious that I am a person, and not a string of six letters). Just so, we shortcut our speech when we talk about programming: `result` is the name that _identifies_ a variable which _contains_ a function... but that's a mouthful, and all programmers will understand when we say "`result` is a function" we mean the former. Obviously, this might not make immediate sense to new programmers, just like aliens might wonder about me as "Amadan".
score: 1
comment on: http://stackoverflow.com/q/51376326
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89750814
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51388938
type: Comment
has text: You're probably right - I hadn't done it previously because it allowed me to plot, but it could be that the numbers being plotted are the numerical representations of the data...

http://stackoverflow.com/q/51451093
score: 1
favorite count: 0
tagged with: python
answer count: 0
has title: Passing data from conditional/chained drop boxes in a form to a view or directly to URL
type: UnansweredQuestion
has body: I am in the process of implementing a feature to allow users to query, through a set of conditional drop boxes, to find other users by grouping. For example, my drop downs chain from Departments->Teams->Users. I have that part setup correctly, but I can't figure out how to use the data from the last (Users) to either send it to my view or redirect the user to a URL. If the user is test I want to send them to http://example.com/user/test or I want to send them to my view which accepts user as a parameter. I have a FormView, form, and 2 functions which work with Ajax to get the conditional drop boxes. See below for my code: Views.py class UserQuery(FormView): template_name = 'people/users_form.html' model = People form_class = UsersListForm def load_teams(request): department = request.GET.get('department') teams = Teams.objects.filter(department=department).order_by('team') return render(request, 'people/team_dropdown_list_options.html', {'teams': teams}) def load_users(request): team = request.GET.get('team') people = People.objects.filter(team=team).order_by('people') return render(request, 'people/people_dropdown_list_options.html', {'people': people}) def load_one(request): selected_person = request.GET.get('people') one = People.objects.get(id=selected_person).people return render(request, 'index.html', {'username': one}) So load_one() has the data I need. It has the username that I want to pass to http://example.com/user/{} -- I have a view already for that URL, but I need to figure out how to get them there any the form is submitted. Right now it seems like I am using the FormView incorrectly as it wants to create something, rather than just query. Forms.py class PeopleListForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['team'].queryset = Teams.objects.none() self.fields['people'].queryset = People.objects.none() if 'department' in self.data: try: department_id = int(self.data.get('department')) self.fi…
tagged with: django
upvote count: 1
type: Question
tagged with: django-views
tagged with: django-forms
downvote count: 0

http://stackoverflow.com/comment/89668785
has text: Better way ? can you explain what you mean ?
comment on: http://stackoverflow.com/q/51348084
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/89644829
comment on: http://stackoverflow.com/q/51333185
score: 4
type: QuestionComment
has text: Unless writing your ssh/ssl library in Python counts, I think the answer is no.
type: Comment

http://stackoverflow.com/a/51405092
downvote count: 4
answers question: http://stackoverflow.com/q/51404930
upvote count: 1
has comment: http://stackoverflow.com/comment/89825274
score: -3
type: Answer
has body: I like to pickle them for retrieval later - especially when I have a class instance or something that takes a long time to recreate when I'm using it for testing. import pickle with open('pickled_var', 'wb') as picklefile: pickle.dump('asdf', picklefile) with open('pickled_var', 'rb') as picklefile: unpickled_var = pickle.load(picklefile) print(unpickled_var) asdf in your case, you could pickle it when it's the values you want, and then just load over the "bad" variable to get back to a "good" state.
has comment: http://stackoverflow.com/comment/89782444

http://stackoverflow.com/comment/101605637
score: 0
type: AnswerComment
type: Comment
has text: @JanmejayaNanda In sklearn API of lightgbm the number of trees (what OP seems to call "number of iterations") is controlled by the `n_estimators` parameter, see [this link](https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.LGBMModel.html#lightgbm.LGBMModel.__init__). The only argument with "iteration" in the name is `num_iteration` in the `predict()` method, but it has nothing to do with training, but only with prediction step. This is true for the latest release at least
comment on: http://stackoverflow.com/a/51375423

http://stackoverflow.com/comment/89916491
type: Comment
has text: Ok, the second code works with the `break` after the `try`. Thanks. But the first code still does not work.
comment on: http://stackoverflow.com/a/51473371
type: AnswerComment
score: 0

http://stackoverflow.com/q/51367763
has title: UVa 11450 in python - dp
has comment: http://stackoverflow.com/comment/89708267
score: 0
tagged with: dynamic-programming
has comment: http://stackoverflow.com/comment/89708184
has body: I struggle with task from UVa Online Judge 11450 - Wedding shopping. I have managed to code it in C++ and get AC. Unfortunately, I cannot do the same in python - TLE. I would like to learn to code in python, that's why I am using it. I know that C++ is significantly faster and better for competitive programming etc. Any ideas what's wrong with this code ? How can I improve it go get AC? from sys import stdin, stdout def shop(money, curr_g): if money &lt; 0: return -1 if curr_g == c: return m - money if memo[money][curr_g] is not -1: return memo[money][curr_g] ans = -1 for model in range(1, price[curr_g][0] + 1): ans = max(ans, shop(money - price[curr_g][model], curr_g + 1)) memo[money][curr_g] = ans return ans price = list(list() for i in range(21)) memo = list(list(-1 for j in range(21)) for i in range(201)) n = int(input()) for i in range(n): m, c = map(int, stdin.readline().split()) for a in range(c): price[a] = [int(x) for x in stdin.readline().split()] for a in range(201): for b in range(21): memo[a][b] = -1 ans = shop(m, 0) stdout.write(str(ans) + "\n") if ans &gt;= 0 else stdout.write('no solution\n')
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89708234
type: Question

http://stackoverflow.com/q/51393699
score: 1
tagged with: python-requests
type: Question
has body: Building a webscraper to query the USGA golf course database for a list of all courses and ratings. A form submission generates a table of links to different courses, which can then be scraped for the data I'm curious about. How do I use requests.post to submit all possible queries into the form. Currently, I have: import csv from BeautifulSoup import BeautifulSoup from requests import Session import requests url = "https://ncrdb.usga.org/NCRDB/NCRListing.aspx" data = {'txtClubCity': r"Newton"} r = requests.post(url, data=data) print r.content I've tried this a bunch of different ways, but the page doesn't update after posting. Does anyone have a sense of what's wrong here?
upvote count: 1
has comment: http://stackoverflow.com/comment/89759372
tagged with: asp.net
favorite count: 0
has title: Using requests.post to submit a form
type: UnansweredQuestion
tagged with: python
answer count: 0
downvote count: 0

http://stackoverflow.com/q/51408675
tagged with: python
has comment: http://stackoverflow.com/comment/89789066
has comment: http://stackoverflow.com/comment/89789480
tagged with: seaborn
type: UnansweredQuestion
type: Question
tagged with: numpy
answer count: 1
has comment: http://stackoverflow.com/comment/89788683
has comment: http://stackoverflow.com/comment/89788833
has title: ValueError: Buffer has wrong number of dimensions (expected 1, got 2) when using seaborn
score: 0
tagged with: data-visualization
has body: I am trying to plot a count plot using seaborn. However, I keep getting the error: ValueError: Buffer has wrong number of dimensions (expected 1, got 2) The data is in array format like this: kmeans_updated_transform Output : array([[ 69.86249185, 420.73371599, 293.97930338, ..., 75.0959945 , 1324.91605382, 695.82952194], [ 653.72679905, 173.0166009 , 881.79444099, ..., 519.62763564, 737.738956 , 114.53013382], [ 137.60270124, 621.0421363 , 93.48686268, ..., 271.48007915, 1525.69688999, 896.4147582 ], ..., pca_original_transform Output: array([[ 9.43214091e+01, -1.89435531e+01, 1.07357663e+01, ..., 1.23508040e-02, -4.93779143e-03, 4.85990628e-13], [ 6.82436757e+02, 3.43334711e+01, 9.96130809e+00, ..., 1.91267574e-02, 8.14910013e-03, -1.38680181e-13], [-1.06579511e+02, -6.68715037e+00, -1.84056983e+00, ..., -1.90794427e-02, -4.22592696e-03, -2.87145744e-13], ..., Finally, I have a data frame known as cat. This is the code I am using ax = sns.countplot(x=pca_orignal_transform, hue=kmeans_updated_transform, data=cat) Why is the count plot throwing an error when I try to plot it. Any help would be appreciated. Thanks
has answer: http://stackoverflow.com/a/51409193

http://stackoverflow.com/q/51472657
tagged with: queue
type: Question
has title: Assigning multiple queues in python
tagged with: python-import
has answer: http://stackoverflow.com/a/51472793
answer count: 1
type: UnansweredQuestion
tagged with: python
has body: I want to assign values of dictionary as queue but I don't want to create a loop. import queue queues = dict({el:"q"+str(el) for el in range(5)}) queue for queue in queues.values() = queue.Queue() It gives me an error. How can I do this
score: 0

http://stackoverflow.com/q/51439969
tagged with: airflow
has title: airflow xcom.pull() access to a implicitly returned value of upstream task
score: 0
answer count: 2
tagged with: python
has body: I am new to Python and new to Airflow. I am using the Snowflake database. I have created an operator SnowflakeGetDataOperator that returns the snowflake hook.get_records method (i am returning a small amount of kines - usually a single cell) so now I have this task in the dag: check_last_run_date=SnowflakeGetDataOperator( task_id='check_last_run_date', sql="SELECT COALESCE (max(update_date), '2000-01-01') FROM poc.dwh.fact_collector", snowflake_conn_id='snowflake_default', dag=dag) when this task runs I see in the Airfow backend the xcom object of this task (the returned value of the operator - i did not use xcom.push() ) My question is how do I access this value from the next downstream task? I need to use it as a parameter for my next sql operator. I have tried the following line within the dag code {{ task_instance.xcom_pull(task_ids='check_last_run_date') }} but the code doesn't recognize the task_instance attribute. EDIT The next task should be something like fill_agg_table = SnowflakeOperator( task_id='fill_cust_agg_data', sql= str.replace ("""INSERT INTO oc.TEMP_COMPUTING.collector_customer_aggregative_data ( SELECT * FROM POC.STG."stg_atg_data" WHERE XXXXX &lt; current_date)""", 'XXXXX', {{ task_instance.xcom_pull(task_ids='check_last_run_date') }}, snowflake_conn_id='snowflake_default', dag=dag ))
has answer: http://stackoverflow.com/a/61779103
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51454450
possible better answer: http://stackoverflow.com/a/61779103
type: Question
has answer: http://stackoverflow.com/a/51454450

http://stackoverflow.com/q/51447877
has comment: http://stackoverflow.com/comment/89866275
has comment: http://stackoverflow.com/comment/89866361
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/32662123
has comment: http://stackoverflow.com/comment/89866452
has comment: http://stackoverflow.com/comment/89866388
tagged with: python
tagged with: pyodbc
linked to: http://stackoverflow.com/q/46045834
has comment: http://stackoverflow.com/comment/89866241
type: Question
has body: I've searched through about 50 posts that have the IM002 error and can't seem to figure out why I'm getting it. The full error is: Traceback (most recent call last): File "crc-upload-touchscreen-email-to-socketlabs.py", line 70, in &lt;module&gt; "password =" + password + ";" pyodbc.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') I'm using an instance file to insert the relevant information. here is what I have: logger.info('Connect to database') server = config.get('connection', 'server') dbname = config.get('connection', 'dbname') user = config.get('connection', 'username') password = config.get('connection', 'password') pyodbc.connect("DRIVER = {ODBC Driver 13 for SQL Server};" "Server =" + server + ";" "Database =" + dbname + ";" "username =" + user + ";" "password =" + password + ";" "Trusted_Connection = yes;")
tagged with: sql-server-2014
tagged with: sql-server
score: 0
has comment: http://stackoverflow.com/comment/89866454
has comment: http://stackoverflow.com/comment/102068991
has title: Error when connecting to MSSQL with pyodbc

http://stackoverflow.com/q/51332015
has body: I want to return None if a dictionary x doesn't have the key field or if it does have the key but the value is an empty dict. I had results = x.get('field') which returns None if the key isn't present. If it is present x.get('field') will return an dict. I want results to also be None if x.get('field') returns {}. Is there a nice pythonic way of doing this? Currently I have results = x.get('field') if x.get('field') else None. This seems very convoluted.
answer count: 2
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51332031
has comment: http://stackoverflow.com/comment/89639666
favorite count: 0
has answer: http://stackoverflow.com/a/51332139
type: Question
has title: python return None if dict doesn't have key or is value is empty
tagged with: python
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/51332139
upvote count: 2
accepted answer: http://stackoverflow.com/a/51332031
has comment: http://stackoverflow.com/comment/89639953
downvote count: 1

http://stackoverflow.com/q/51470209
accepted answer: http://stackoverflow.com/a/51470736
has body: I'm using python 2.7.10 on a 64-bit Mac OS X machine. Why does time.sleep() raise an IOError beyond 100000000? In the example below, time.sleep(100000000) works, but time.sleep(100000001) raises IOError $ python Python 2.7.10 (default, Oct 6 2017, 22:29:07) [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import time &gt;&gt;&gt; time.sleep(100000000) ^CTraceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; KeyboardInterrupt &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; time.sleep(100000001) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; IOError: [Errno 22] Invalid argument
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51470736
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/89908711
upvote count: 3
has title: Why does `time.sleep()` raise an `IOError` beyond 100000000?
has comment: http://stackoverflow.com/comment/89908771
type: Question
has comment: http://stackoverflow.com/comment/89908733
answer count: 1
downvote count: 0

http://stackoverflow.com/q/51478951
has answer: http://stackoverflow.com/a/51479226
has comment: http://stackoverflow.com/comment/89926376
type: Question
has title: AttributeError: 'str' object has no attribute 'decode' Having this error on the second line of my code
tagged with: algorithm
has comment: http://stackoverflow.com/comment/89926321
score: 0
linked to: http://stackoverflow.com/q/3283984
answer count: 1
has comment: http://stackoverflow.com/comment/89926226
type: UnansweredQuestion
has body: This is my code, if __name__ == "__main__": key = "0123456789abcdef0123456789abcdef".decode('hex') /this line is having error plain_1 = "1weqweqd" plain_2 = "23444444" plain_3 = "dddd2225" print(plain_1) print(plain_2) print(plain_3) cipher = Present(key) Output AttributeError: 'str' object has no attribute 'decode'
tagged with: encryption
tagged with: python
has comment: http://stackoverflow.com/comment/89926387

http://stackoverflow.com/comment/89880579
type: QuestionComment
score: 1
has text: You can define an [`overload`](https://docs.python.org/3/library/typing.html#typing.overload), though.
comment on: http://stackoverflow.com/q/51455491
type: Comment

http://stackoverflow.com/comment/90177482
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51477865
has text: This works. Thank you so much :)

http://stackoverflow.com/q/51413187
accepted answer: http://stackoverflow.com/a/51413233
has body: I am looking at the dis module source code in Python 3.7, one thing puzzles me, I do not see opname is defined yet it is directly used. E.g. here is how it is accessed: 348 yield Instruction(opname[op], op, 349 arg, argval, argrepr, 350 offset, starts_line, is_jump_target) But where is opname populated? Here is a list of all the occurrances of "opname": Lib&gt;grep -n "\&lt;opname\&gt;" dis.py 185: "opname opcode arg argval argrepr offset starts_line is_jump_target") 187:_Instruction.opname.__doc__ = "Human readable name for operation" 203: opname - human readable name for operation 241: fields.append(self.opname.ljust(_OPNAME_WIDTH)) 348: yield Instruction(opname[op], op, I greped "opname" in C source code also, does not find any.
upvote count: 2
tagged with: python
type: AnsweredQuestion
score: 2
type: Question
has title: How/where is opname populated?
downvote count: 0
has answer: http://stackoverflow.com/a/51413233
answer count: 1
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/89875170
type: Comment
has text: Thank you, it does exactly what I need! My real dataset is much larger however (Multiple 'fruit' columns and about 30 'Sales/Shipments' columns, so I hope this method will work on that.
comment on: http://stackoverflow.com/a/51452470
type: AnswerComment
score: 0

http://stackoverflow.com/a/51393856
has comment: http://stackoverflow.com/comment/89759550
has comment: http://stackoverflow.com/comment/89759504
score: 1
has body: For the first for loop, you are multiplying a list with a number and appending to another list(temp_1). Multiplying a list with a number n is equivalent to repeating the elements of the list n times. Since you are appending to another list after every iteration of x, the value: x*y will get appended on a new line. When you do b[x] = temp_1, it is repeating the value of temp_1 for every iteration of x. Hence a 2D list. The second and third cases of for loops are essentially the same because range(0, 4) will generate a list [0, 1, 2, 3] as you've done manually in case 3. When y takes on values from range(4,6), we go through each value individually and multiply by x (which takes on individual values from range(0,4)). Hence, we keep multiplying individual elements and get temp_1 = [0, 0, 4, 5, 8, 10, 12, 15]. Similar to the previous case where you used b[x] = temp_1, this value repeats for each iteration of x. To get the result you mentioned above, you can use the method mentioned by Massoud Hosseinali. Hope this helps!
upvote count: 1
answers question: http://stackoverflow.com/q/51393576
has comment: http://stackoverflow.com/comment/89759406
type: Answer
downvote count: 0

http://stackoverflow.com/comment/89708215
comment on: http://stackoverflow.com/q/51367447
type: Comment
type: QuestionComment
has text: `date.fromtimestamp` classmethod restricted to years from 1970 through 2038. I guess you have a timestamp in your data that is out of this range. If you can edit the file that error occurred, you can choose `timedelta` for more range to work.
score: 0

http://stackoverflow.com/a/51449705
has comment: http://stackoverflow.com/comment/89882944
has comment: http://stackoverflow.com/comment/89869931
has body: There're two reasons why your colour coding get messed up. 1) You did not define the colour coding for 0, therefore there is always a big formatting gap for zero with other numbers in your code. 2) Your width function did not change with colour function but actually the string length for colored output is much more larger than without one. Therefore I suggest you use a constant number, like 22 or something bigger in your code. Alternately, you can change widths = [max(len(str(nlist[row * 4 + col])) for row in range(4)) + 2 for col in range(4)] to widths = [max(len(str(nlist[row * 4 + col]))+21 for row in range(4)) + 2 for col in range(4)] To simplify the if structure, I suggest you use a dictionary to lookup for the desired color: example: WHITE_COLOR = "#ffffff" BACKGROUND_COLOR_GAME = "#92877d" BACKGROUND_COLOR_CELL_EMPTY = "#9e948a" BACKGROUND_COLOR_DICT = { 2:"#eee4da", 4:"#ede0c8", 8:"#f2b179", 16:"#f59563", \ 32:"#f67c5f", 64:"#f65e3b", 128:"#edcf72", 256:"#edcc61", \ 512:"#edc850", 1024:"#edc53f", 2048:"#edc22e" } CELL_COLOR_DICT = { 2:"#776e65", 4:"#776e65", 8:"#f9f6f2", 16:"#f9f6f2", \ 32:"#f9f6f2", 64:"#f9f6f2", 128:"#f9f6f2", 256:"#f9f6f2", \ 512:"#f9f6f2", 1024:"#f9f6f2", 2048:"#f9f6f2" } FONT = ("Verdana", 40, "bold") SCORE_FONT=("Verdana", 20, "bold") For your code, you can make it like nlist = [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 128, 2, 2, 16, 16] color_dict = {0:' \033[1;37;106m0\033[0m ', 2:' \033[1;37;106m2\033[0m ',4:' \033[1;37;104m4\033[0m ', 8:' \033[1;37;106m8\033[0m ',16:' \033[1;37;106m16\033[0m ', 32:' \033[1;37;106m32\033[0m ',64:' \033[1;37;106m64\033[0m ', 128:' \033[1;37;106m128\033[0m ',256:' \033[1;37;106m256\033[0m ', 512:' \033[1;37;106m512\033[0m ',1024:' \033[1;37;106m1024\033[0m ', 2048:' \033[1;37;106m2048\033[0m ',4096:' \033[1;37;106m4096\033[0m '} count = 0 for i in range(16): print('|{:^{width}}'.format(color_dict[nlist[i]], width=22), end = '') #This line is modified. count += 1 if count == 4: print("|\n"…
has comment: http://stackoverflow.com/comment/89882903
accepted answer of: http://stackoverflow.com/q/51449636
has comment: http://stackoverflow.com/comment/89882937
score: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51449636
has comment: http://stackoverflow.com/comment/89870374
has comment: http://stackoverflow.com/comment/89870931
has comment: http://stackoverflow.com/comment/89882863
has comment: http://stackoverflow.com/comment/89870398
has comment: http://stackoverflow.com/comment/89882935
type: Answer
has comment: http://stackoverflow.com/comment/89882997
has comment: http://stackoverflow.com/comment/89871072
upvote count: 3
has comment: http://stackoverflow.com/comment/89870244
has comment: http://stackoverflow.com/comment/89882808

http://stackoverflow.com/q/51404963
has body: I am dealing with a regression dataset, and I wish to fit a particular model to my dataset after evaluating various model's performances. I used cross_val_score from sklearn.model_selection for this purpose. After I chose scoring parameter as 'r2' I got highly negative values for some of my models. demo = pd.read_csv('demo.csv') X_train = demo.iloc[0:1460, : ] Y_train = pd.read_csv('train.csv').loc[:, 'SalePrice':'SalePrice'] X_test = demo.iloc[1460: , : ] regressors = [] regressors.append(LinearRegression()) regressors.append(Ridge()) regressors.append(Lasso()) regressors.append(ElasticNet()) regressors.append(Lars()) regressors.append(LassoLars()) regressors.append(OrthogonalMatchingPursuit()) regressors.append(BayesianRidge()) regressors.append(HuberRegressor()) regressors.append(RANSACRegressor()) regressors.append(SGDRegressor()) regressors.append(GaussianProcessRegressor()) regressors.append(DecisionTreeRegressor()) regressors.append(RandomForestRegressor()) regressors.append(ExtraTreesRegressor()) regressors.append(AdaBoostRegressor()) regressors.append(GradientBoostingRegressor()) regressors.append(KernelRidge()) regressors.append(SVR()) regressors.append(NuSVR()) regressors.append(LinearSVR()) cv_results = [] for regressor in regressors: cv_results.append(cross_val_score(regressor, X = X_train, y = Y_train, scoring = 'r2', verbose = True, cv = 10)) After the above mentioned code is compiled and run, cv_results is as follows. It is a list of float64 arrays. Each array contains 10 'r2' value (due to cv = 10). I open the first array and notice that for this particular model, some of the 'r2' values are extremely negative. Since 'r2' values should be between 0 and 1, why are there very large negative values?
has answer: http://stackoverflow.com/a/51424116
answer count: 1
has title: Unexpected R^2 loss value in corss_val_score
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51424116
tagged with: regression
tagged with: machine-learning
type: Question
tagged with: loss-function
score: 0

http://stackoverflow.com/q/51473904
tagged with: reinforcement-learning
tagged with: python
has body: I am trying to understand how policy gradient works and build a pong game agent from sketch using Tensorflow but it seems doesn't work. I am not sure if I have some misunderstanding for the policy gradient. Here I post my code with explanations. Create placeholder first for holding the input frame obtained from the environmant input_frame = tf.placeholder(tf.float32, [380*400, None], name='input_frame') Define the parameter for the simple network and the model W1 = tf.get_variable(name='w1', shape=[200, 380*400],initializer=tf.contrib.layers.xavier_initializer(seed=2)) b1 = tf.get_variable(name='b1', shape=[200, 1], initializer=tf.zeros_initializer()) W2 = tf.get_variable(name='w2', shape=[3, 200],initializer=tf.contrib.layers.xavier_initializer(seed=2)) b2 = tf.get_variable(name='b2', shape=[3, 1], initializer=tf.zeros_initializer()) def build_model(): L_1 =tf.nn.relu(tf.add(tf.matmul(W1, input_frame), b1)) L_2 =tf.nn.relu(tf.add(tf.matmul(W2, L_1), b2)) Y = tf.nn.softmax(L_2, axis=0) return Y Discount reward function def discount_rewards(r): discounted_r = np.zeros_like(r) running_add = 0 for t in reversed(range(0, discounted_r.size)): if r[t] != 0: running_add = 0 #https://github.com/hunkim/ReinforcementZeroToAll/issues/1 running_add = running_add * gamma + r[t] discounted_r[t] = running_add return discounted_r Build the model Y = build_model() Sample operation sample_op = tf.multinomial(logits=tf.reshape(Y, (1, 3)), num_samples=1) Y_action = sample_op - 1 #Move up: -1, stay still: 0, move down: 1 Routine initialisation global_step = tf.train.get_or_create_global_step() init = tf.global_variables_initializer() sess = tf.Session() sess.run(init) Retrieve next frame from the environment with cropping next_frame = my_pong.get_next_frame().T[pong_game.SCOREBOARD_HEIGHT + 6 : pong_game.WINDOW_HEIGHT, 0 + pong_game.PADDLE_THICKNESS:pong_game.WINDOW_WIDTH - pong_game.PADDLE_THICKNESS].reshape(380*400, 1) Get the observation by subtracting the current frame and the last …
type: UnansweredQuestion
tagged with: machine-learning
upvote count: 1
tagged with: tensorflow
type: Question
has title: Issue on using policy gradients with Tensorflow to train a pong game agent
score: 1
tagged with: deep-learning
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51483389
has comment: http://stackoverflow.com/comment/89935389

http://stackoverflow.com/q/51466042
tagged with: python
tagged with: merge
upvote count: 3
possible better answer: http://stackoverflow.com/a/51466170
answer count: 2
has answer: http://stackoverflow.com/a/51466170
downvote count: 1
has answer: http://stackoverflow.com/a/51466085
tagged with: dataframe
has title: Python: how to drop rows in Pandas if two columns don't appear in another pandas column?
accepted answer: http://stackoverflow.com/a/51466085
tagged with: pandas
type: AnsweredQuestion
score: 2
has body: I have two dataframes df and df1. df contains name and attributes of people. df Name Age 0 Jack 33 1 Anna 25 2 Emilie 49 3 Frank 19 4 John 42 while df1 contains the info of the number of contacts between two people. In df1 we can have some people that don't appear in df. df1 Name1 Name2 c 0 Frank Paul 2 1 Julia Anna 5 2 Frank John 1 3 Emilie Jack 3 4 Tom Steven 2 5 Tom Jack 5 I want to drop all the rows from df1 in Name1 or Name2 don't appear in df. df1 Name1 Name2 c 0 Frank John 1 1 Emilie Jack 3
favorite count: 0
type: Question

http://stackoverflow.com/q/51393304
upvote count: 1
has body: I run crossbar client with the runner of crossbar which run in the asyncio event loop. I want to call RPC by the trigger in tkinter. Is there any solution to combine them together?
type: Question
tagged with: crossbar
answer count: 1
downvote count: 0
favorite count: 0
has title: How I can integrate crossbar client (python3,asyncio) with tkinter
type: UnansweredQuestion
tagged with: python
tagged with: integrate
tagged with: tkinter
score: 1
has answer: http://stackoverflow.com/a/51432246

http://stackoverflow.com/a/51387288
has comment: http://stackoverflow.com/comment/105353154
has body: You must not use postgresql as a key-value store. The key-value store (except in rare cases) is structured around a schema based on key composition that layout the data in multidimensional space that may or may not map directly the concepts of SQL tables. Otherwise said, there is a database abstraction that lives in the key-value store. There is not enough information to say, simply replace the key-value store with a 2 columns table. If you do that you will most likely end up with the worst of both worlds.
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/105349220
answers question: http://stackoverflow.com/q/51370752
type: Answer
accepted answer of: http://stackoverflow.com/q/51370752

http://stackoverflow.com/comment/89727054
has text: You can't only consider `i+1`, for example this fails for `pattern = ['ACD', 'AD', 'BACD']`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51328156
type: Comment

http://stackoverflow.com/comment/89862960
type: Comment
score: 0
type: QuestionComment
has text: DB: Postgresql.
comment on: http://stackoverflow.com/q/51446299

http://stackoverflow.com/q/51374423
type: Question
tagged with: numpy
has title: Generating random numbers randomly
has comment: http://stackoverflow.com/comment/89725733
score: 0
has comment: http://stackoverflow.com/comment/89724921
has comment: http://stackoverflow.com/comment/89721331
tagged with: random
answer count: 3
accepted answer: http://stackoverflow.com/a/51376683
possible better answer: http://stackoverflow.com/a/51374531
has answer: http://stackoverflow.com/a/51374531
has answer: http://stackoverflow.com/a/51374977
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89733978
has comment: http://stackoverflow.com/comment/89721587
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89721684
has comment: http://stackoverflow.com/comment/89724861
has answer: http://stackoverflow.com/a/51376683
has body: I have a column T, which decides the range of the value in the value column. T is incremented in steps of 0.5 and always has 4 occurrences. If T=0.5,1.5,2.5 etc., I want to generate a random number between 1 and 2. If T=1,2,3,4 etc., I want to generate a random number between 2 and 3. ^This is the easy bit, switching the random generator or generating the random numbers separately and ordering them should do the trick. However, once in every 10 integer Ts i.e. 1,2,3,4...10, I want a random function to pick a random T and set the value between 5 and 6, instead of 2 and 3. Similarly, once in every 100 integer values of T, I want to pick a random T and make the Value column to be between 15 and 16. T Value 0.5 1.01 0.5 1.05 0.5 1.85 0.5 1.49 1 2.45 1 2.52 1 2.48 1 2.95 1.5 1.78 1.5 1.45 1.5 1.65 1.5 1.77 2 2.96 2 2.75 2 2.74 2 2.95 2.5 1.75 2.5 7.89 2.5 1.33 2.5 1.58 3 5.78 3 5.44 3 5.36 3 5.24

http://stackoverflow.com/comment/89789747
score: 0
comment on: http://stackoverflow.com/q/51408734
type: Comment
type: QuestionComment
has text: for some odd reason it doesn't work for me. Getting an empty output. Would love to know what I was doing wrong. Both solutions above worked for me. @Thefourthbird

http://stackoverflow.com/comment/89918563
comment on: http://stackoverflow.com/q/51440692
score: 0
type: Comment
type: QuestionComment
has text: A solution would be to do a FOR loop and trigger the function "n" times, but I would really like to avoid this...

http://stackoverflow.com/q/51427540
tagged with: nginx
has body: I have 2 django projects that are configured to be served on sockets. They are at the same server. Django project names are proj1 and proj2. So i gave them 2 different names proj1.cr.tm and proj2.cr.tm on /etc/hosts file and both of them are pointing to same local 127.0.0.1 address. So when i ping proj1.cr.tm it pings 127.0.0.1 , when i ping proj2.cr.tm it pings 127.0.0.1 also. So the thing i want is serving 2 projects on these two different domain names on same server ip on port 80. The differentiation with names and projects will be made by nginx. I also prepared 2 nginx configurations proj1.conf and proj2.conf under /etc/nginx/conf.d directory and added proj1.cr.tm and proj2.cr.tm as servers in these configurations. I also included them in main nginx.conf file under /etc/nginx/nginx.conf file. I also prepared 2 ini files for uwsgi and run uwsgi with emperor. When i run uwsgi and nginx i can see that socket files are created. And i can also see nginx is working on http:/127.0.0.1 with default nginx page. I also see that uwsgi processes with project modules are working in linux processes behind. But when i try http://proj1.cr.tm and http://proj2.cr.tm addresses i still cannot see my django web sites. I still see nginx default page. I checked directory and socket and conf files and ini files permissions. They look ok. When i run django sites with runserver or when i run them with "uwsgi --http :8081 --module proj1.wsgi" they are working. But i cannot serv them with nginx. UPDATE : nginx config for proj 1 : server { listen 80; server_name proj1.cr.tm; access_log /var/log/nginx/proj1_access.log; error_log /var/log/nginx/proj1_errors.log; sendfile on; client_max_body_size 20M; keepalive_timeout 0; location = favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/proj1/work/proj1; } location /media/ { root /home/proj1/work/proj1; } location / { include uwsgi_params; uwsgi_read_timeout 9000; uwsgi_send_timeout 9000; uwsgi_connect_timeout 9000; …
has title: Nginx is not serving django projects that is running on uwsgi
tagged with: uwsgi
type: Question
favorite count: 0
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89828128
has comment: http://stackoverflow.com/comment/89827245
answer count: 0
type: UnansweredQuestion
tagged with: django
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/89933367
comment on: http://stackoverflow.com/q/51482276
type: Comment
type: QuestionComment
score: 2
has text: You need to tell csv reader that it is utf8 https://stackoverflow.com/questions/904041/reading-a-utf8-csv-file-with-python#904085

http://stackoverflow.com/comment/89641108
has text: I'm not sure I understand what you mean. In my `DetailView` I hide the `update` button when the `Invoice` date is out of the established range, so a user shouldn't accidentally get to the update page (he can only get there by typing the URL directly into the address bar).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51331067
score: 0

http://stackoverflow.com/comment/89788570
type: Comment
type: QuestionComment
has text: @IgnacioVazquez-Abrams That doesn't seem to be the case in practice. I have a bunch of print statements in modA.py and none of them are printed out just by importing it.
comment on: http://stackoverflow.com/q/51408544
score: 0

http://stackoverflow.com/comment/89679141
score: 0
type: Comment
type: QuestionComment
has text: pls do not use the comments space for such kind of clarifications & addditional info - edit & update your post instead!
comment on: http://stackoverflow.com/q/51346750

http://stackoverflow.com/comment/89761308
comment on: http://stackoverflow.com/q/51394993
score: 0
type: Comment
type: QuestionComment
has text: And you're printing an empty array

http://stackoverflow.com/q/51382250
type: Question
has comment: http://stackoverflow.com/comment/89740448
tagged with: pandas
has answer: http://stackoverflow.com/a/51384598
tagged with: k-means
tagged with: scikit-learn
favorite count: 0
possible better answer: http://stackoverflow.com/a/53026088
has answer: http://stackoverflow.com/a/64339890
tagged with: python
has comment: http://stackoverflow.com/comment/89737634
upvote count: 22
has title: ValueError: Number of labels is 1. Valid values are 2 to n_samples - 1 (inclusive) when using silhouette_score
answer count: 4
has comment: http://stackoverflow.com/comment/89740791
downvote count: 0
has comment: http://stackoverflow.com/comment/89740401
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/89741510
has comment: http://stackoverflow.com/comment/89740525
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/53026088
accepted answer: http://stackoverflow.com/a/51384598
has body: I am trying to calculate silhouette score as I find the optimal number of clusters to create, but get an error that says: ValueError: Number of labels is 1. Valid values are 2 to n_samples - 1 (inclusive) I am unable to understand the reason for this. Here is the code, that I am using to cluster and calculate silhouette score. I read the csv that contains the text to be clustered and run K-Means on the n cluster values. What could be the reason I am getting this error? #Create cluster using K-Means #Only creates graph import matplotlib #matplotlib.use('Agg') import re import os import nltk, math, codecs import csv from nltk.corpus import stopwords from gensim.models import Doc2Vec from sklearn.cluster import KMeans import matplotlib.pyplot as plt import pandas as pd from sklearn.metrics import silhouette_score model_name = checkpoint_save_path loaded_model = Doc2Vec.load(model_name) #Load the test csv file data = pd.read_csv(test_filename) overview = data['overview'].astype('str').tolist() overview = filter(bool, overview) vectors = [] def split_words(text): return ''.join([x if x.isalnum() or x.isspace() else " " for x in text ]).split() def preprocess_document(text): sp_words = split_words(text) return sp_words for i, t in enumerate(overview): vectors.append(loaded_model.infer_vector(preprocess_document(t))) sse = {} silhouette = {} for k in range(1,15): km = KMeans(n_clusters=k, max_iter=1000, verbose = 0).fit(vectors) sse[k] = km.inertia_ #FOLLOWING LINE CAUSES ERROR silhouette[k] = silhouette_score(vectors, km.labels_, metric='euclidean') best_cluster_size = 1 min_error = float("inf") for cluster_size in sse: if sse[cluster_size] &lt; min_error: min_error = sse[cluster_size] best_cluster_size = cluster_size print(sse) print("====") print(silhouette)
score: 22
has answer: http://stackoverflow.com/a/63208691

http://stackoverflow.com/comment/89881770
type: Comment
comment on: http://stackoverflow.com/q/51456060
score: 0
type: QuestionComment
has text: isn't condition `if(item['rsrc_name'] == tmp_rsrc):` always going to be `True` since you are assigning `tmp_rsrc = item['rsrc_name']` just above?

http://stackoverflow.com/comment/89871418
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51448030
type: QuestionComment
has text: @abarnert I am calling PyCFunction_NewEx because PyCFunction_New is a marco in the source code. And I am passing only two parameters because that's the definition I always got from the source code. But I can try to add a third parameter. What crystal does I guess is something like a dlopen with the python library...

http://stackoverflow.com/comment/89766649
has text: @DanielArteaga The [specification](https://docs.python.org/3/reference/datamodel.html#object.__iter__) for the `__iter__` method is "It must return an iterator". If you `return self`, then `self` must be an iterator (which means it has to have a `__next__`). But you can return any kind of iterator, and using `yield` in a function does exactly that - it makes the function return an iterator. (Technically a generator, but generators are also iterators.)
type: AnswerComment
comment on: http://stackoverflow.com/a/51397640
type: Comment
score: 1

http://stackoverflow.com/comment/89833924
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51431241
has text: What is the output of request.POST ?
type: Comment

http://stackoverflow.com/comment/89699700
type: Comment
type: QuestionComment
has text: `open` bash command (on a Mac?) will open Office application, not read a file (regardless if from svn)
comment on: http://stackoverflow.com/q/51363727
score: 0

http://stackoverflow.com/a/51426846
upvote count: 3
has comment: http://stackoverflow.com/comment/89825361
score: 3
answers question: http://stackoverflow.com/q/51426716
type: AcceptedAnswer
has body: You can use recursion: nested_dict = {1 : {'a' :[1,2,3], 'b': [4,5]}, 2 : {'a' : [6], 'b' : [7,8,9]}} def get_lists(d): r = [b if isinstance(b, list) else get_lists(b) for b in d.values()] return [i for b in r for i in b] Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51426716
type: Answer

http://stackoverflow.com/comment/89684377
score: 0
has text: sample data????
comment on: http://stackoverflow.com/q/51356116
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89787887
has text: you need to specify the *levels* to use for your contour (the fouth argument). However, you will then run into the problem that percentiles for discrete data may not be unique, e.g. both the 10 and the 15 percentile may actually be the same number. What should happen in such case?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51397212

http://stackoverflow.com/q/51461294
possible better answer: http://stackoverflow.com/a/51462541
has answer: http://stackoverflow.com/a/51462541
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/51461492
accepted answer: http://stackoverflow.com/a/51461492
answer count: 2
favorite count: 0
has title: How to continue function if Django object can't be found
tagged with: python
has comment: http://stackoverflow.com/comment/89892034
tagged with: django
has body: I want to check if an object exists - if it doesn't exist I want to still continue the function and not return a 404 error. How can I achieve this? def check(request): if request.is_ajax(): # print('Working') #prints id = request.POST.get('id') post = Post.objects.get(hash=id) obj = get_object_or_404(Post, post=post) if obj: # do stuff else: #do something else The above code returns: Not Found: /check/ [22/Jul/2018 01:15:03] "POST /check/ HTTP/1.1" 404 1729
score: 2
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/89669328
type: AnswerComment
type: Comment
has text: No, only when you explicitly do `from tkinter import *` and this kind of weird side effect is precisely one of the reasons you shouldn't.
comment on: http://stackoverflow.com/a/51348342
score: 7

http://stackoverflow.com/q/51441275
has body: I have the following JSON data: [ { "urls": [ "outlook.office.com", "outlook.office365.com" ], "ips": [ "192.168.0.0/16" ] }, { "urls": [ "*.mail.protection.outlook.com" ], "ips": [ "172.16.0.0/12" ] }, { "urls": [ "r1.res.office365.com", "r3.res.office365.com", "r4.res.office365.com", "xsi.outlook.com" ], } ] I would like to pull all IP addresses relating to the "*.mail.protection.outlook.com" URL. The code I currently have is: import json with open('ips.json') as i: ip = json.load(i) for urls in ip: print(urls["ips"]) which prints all members of the "ips" array for every object, but I only want the array from the object that contains: [ { urls: [ "*.mail.protection.outlook.com" ] } ] A pure Python (no non-standard libraries) solution is preferable to make deployment to AWS Lambda easier
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
type: Question
score: -1
accepted answer: http://stackoverflow.com/a/51441341
answer count: 1
has answer: http://stackoverflow.com/a/51441341
favorite count: 0
has title: Selecting a JSON key from another object that contains a different key/value
tagged with: python-3.x
downvote count: 2
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/89907981
comment on: http://stackoverflow.com/q/51469825
score: 0
type: Comment
type: QuestionComment
has text: You are talking about two different types of hashes, one identifies the frame and one is used for efficient lookup in the set.

http://stackoverflow.com/a/51358687
answers question: http://stackoverflow.com/q/51358324
type: Answer
has body: First, you ought to use np.arctan2 rather than np.arctan since the former takes care of choosing the correct quadrant. By default both np.arctan2 and np.arctan return values in [-pi, pi] range, so in order to get [0, 360] range in degrees you can use degrees = np.mod(np.degrees(inv), 360). import numpy as np v = np.array([[-3, 4], [-2, -5], [2, 6], [3, -10]]) inv = np.arctan2(v[:, 1], v[:, 0]) degree = np.mod(np.degrees(inv), 360) print(degree) # get [-53.13010235, 68.19859051, 71.56505118, -73.30075577]
upvote count: 5
score: 5
downvote count: 0

http://stackoverflow.com/comment/89637746
comment on: http://stackoverflow.com/q/51331018
has text: i am using a list and iterating from last to first element of the strings to find the longest common sub word between them. So the value for the current iteration(LC[i][j]) will depend both on the previous iteration LC[i+1][j+1] and the current matching of the element.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51352147
has body: Here's a start import os location = '/Users/user 1/Desktop/' f = open(os.path.join(location, 'xvp.log'), "w+") for line in f.readlines(): index_ = line.index(']') + 2 new_line = line[index_:] # TODO: save the new_line to the file f.close()
downvote count: 0
answers question: http://stackoverflow.com/q/51351934
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/89759777
comment on: http://stackoverflow.com/q/51394093
score: 0
type: QuestionComment
type: Comment
has text: thanks @Karacken. I didn't clone it. I used a different model to do the learning. I needed the inspiration for the UI. That's where I got stuck :(

http://stackoverflow.com/comment/89921854
type: Comment
has text: This could also be a problem for very isolated nodes like Skegness or Cardigan, which seem not to be in the "closest four" for any of the nodes around them.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51418474

http://stackoverflow.com/comment/89844570
comment on: http://stackoverflow.com/q/51437280
has text: Please can you edit your question and add a sample from this STL file?
score: 0
type: Comment
type: QuestionComment

python-turtle
tags question: http://stackoverflow.com/q/51466389
type: Tag
tag name: python-turtle

http://stackoverflow.com/q/51353038
has comment: http://stackoverflow.com/comment/89678988
has comment: http://stackoverflow.com/comment/89696014
has answer: http://stackoverflow.com/a/51371309
tagged with: cosine-similarity
tagged with: numpy
downvote count: 0
type: Question
has comment: http://stackoverflow.com/comment/89687420
tagged with: pandas
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/51371309
has title: fastest way to perform cosine similarity for 10 million pairs of 1x20 vectors
has comment: http://stackoverflow.com/comment/89678953
has comment: http://stackoverflow.com/comment/89678945
favorite count: 0
has comment: http://stackoverflow.com/comment/89679097
has comment: http://stackoverflow.com/comment/89686296
tagged with: python
answer count: 1
has body: I have a pandas df of 2 columns each containing 2.7 million rows of normalized vectors of length 20. I want to take the cosine sim of column1 - row1 vs column2- row1, column1 - row2 vs column2 - row2... so and and so forth until 2.7 million. I have tried looping but this is extremely slow. What is the fastest way to do this? here is what im using now: for index, row in df.iterrows(): x = 1 - spatial.distance.cosine(tempdf['unit_vector'][index], tempdf['ave_unit_vector'][index]) print(index,x) data: tempdf['unit_vector'] Out[185]: 0 [0.7071067811865475, 0.7071067811865475, 0.0, ... 1 [0.634997029655247, 0.634997029655247, 0.43995... 2 [0.5233710392524532, 0.5233710392524532, 0.552... 3 [0.4792468085399227, 0.4792468085399227, 0.505... 4 [0.4937468195427678, 0.4937468195427678, 0.492... 5 [0.49444897739151283, 0.49444897739151283, 0.5... 6 [0.49548793862403173, 0.49548793862403173, 0.4... 7 [0.5027211862475275, 0.5027211862475275, 0.495... 8 [0.5136216906905179, 0.5136216906905179, 0.489... 9 [0.5035958124287837, 0.5035958124287837, 0.508... 10 [0.5037995208120967, 0.5037995208120967, 0.493... tempdf['ave_unit_vector'] Out[186]: 0 [0.5024525269125278, 0.5024525269125278, 0.494... 1 [0.5010905514059507, 0.5010905514059507, 0.499... 2 [0.4993456468410199, 0.4993456468410199, 0.501... 3 [0.5005492367626839, 0.5005492367626839, 0.498... 4 [0.4999384715200533, 0.4999384715200533, 0.501... 5 [0.49836832120891517, 0.49836832120891517, 0.5... 6 [0.49842376222388335, 0.49842376222388335, 0.5... 7 [0.4984869391887457, 0.4984869391887457, 0.500... 8 [0.4990867844970344, 0.4990867844970344, 0.499... 9 [0.49977780370532715, 0.49977780370532715, 0.4... 10 [0.5003161478128204, 0.5003161478128204, 0.499... This isnt the same dataset but will create a usable df. Columns 'B' and 'C': df = pd.DataFrame(list(range(0,1000)),columns = ['A']) for i in range(0,5): df['New_{}'.format(i)] = df['A'].shift(i).tolist() cols = len(df.columns) start_col = cols - 6 df['B'] = df.iloc[:,start_col:cols…
has comment: http://stackoverflow.com/comment/89679023
upvote count: 3

http://stackoverflow.com/q/51345198
type: Question
answer count: 2
score: 0
tagged with: bash
has body: So I'm creating a command line program using python and the cmd module which gives you an interactive prompt to which you can define commands and it has support for help and whatnot. Lots of fun. One of the built in commands is "!" which maps to a defined function called "do_shell" and in conjunction with "import.os" you can run normal command line... commands. So, if I'm running python from bash and am in a python interactive prompt and type ! clear, it'll run the bash command clear and clear the screen. (Same with windows but with cls). Otherwise, the interactive prompt simply runs commands you define for it. Say I have defined a command def do_greet(self,line) print "Welcome to the interactive prompt user\n" ANYWAY... Question: Can I use this implementation of "do shell" to reverse up a level and call a defined python command? Say, could I do something like this, from the python interactive prompt ! (for i in {1..5}; do greet; done) For the record, the for loop works just fine, obviously "greet" does not. And I don't know what the correct syntax would be for that, if it was possible. to end up with an output of Welcome to the interactive prompt user Welcome to the interactive prompt user Welcome to the interactive prompt user Welcome to the interactive prompt user Welcome to the interactive prompt user Please tell me this is possible.... please tell me I can utilize bash's loops and crap without having to explicitly define them in my command prompt.
tagged with: shell
tagged with: cmd
accepted answer: http://stackoverflow.com/a/51345522
possible better answer: http://stackoverflow.com/a/51345469
tagged with: python
has answer: http://stackoverflow.com/a/51345522
type: AnsweredQuestion
has title: Python cmd and do_shell (!) implementation, can I use the shell to loop through python commands?
has answer: http://stackoverflow.com/a/51345469

http://stackoverflow.com/a/51478779
has body: You are mixing python2 and python3. What you are using when running pip or python are all python2.7 (see also the output of pip show tensorflow where it is referring to /usr/local/lib/python2.7/dist-packages). The library you are trying to use only has .whl for python 3.6 (note the py36 in the .whl files name) Therefore, you need to either: Switch to using pip3 and python3 Find another library that works with python 2.7
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51478588
accepted answer of: http://stackoverflow.com/q/51478588
type: AcceptedAnswer
upvote count: 1

http://stackoverflow.com/q/51407329
type: Question
upvote count: 4
downvote count: 0
answer count: 1
score: 4
favorite count: 0
has title: nargin functionality (from Matlab) in Python
tagged with: python
has comment: http://stackoverflow.com/comment/89786191
has comment: http://stackoverflow.com/comment/89786725
has answer: http://stackoverflow.com/a/51407867
accepted answer: http://stackoverflow.com/a/51407867
has body: I am attempting to translate these lines of code: error(nargchk(3, 4, nargin)) if nargout &gt; 2, error('too many output parameters'); end I want to translate it into Python. I have yet to find an equivalent for error (although I could perhaps just throw an exception here?), nargchk and nargin. Can anybody provide any input as to how this line of code can be translated?
tagged with: matlab
type: AnsweredQuestion

http://stackoverflow.com/q/51385138
upvote count: 1
tagged with: minimize
tagged with: scipy
type: Question
has answer: http://stackoverflow.com/a/51402821
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51402821
has body: Is there a way to directly retrieve the minimized error after scipy.minimize has converged or must that be directly coded into the cost function? I can only retrieve the converged to coefficients it seems. def errorFunction(params,series,loss_function,slen = 12): alpha, beta, gamma = params breakUps = int(len(series) / slen) end = breakUps * slen test = series[end:] errors = [] for i in range(2,breakUps+1): model = HoltWinters(series=series[:i * 12], slen=slen, alpha=alpha, beta=beta, gamma=gamma, n_preds=len(test)) model.triple_exponential_smoothing() predictions = model.result[-len(test):] actual = test error = loss_function(predictions, actual) errors.append(error) return np.mean(np.array(errors)) opt = scipy.optimize.minimize(errorFunction, x0=x, args=(train, mean_squared_log_error), method="L-BFGS-B", bounds = ((0, 1), (0, 1), (0, 1)) ) #gets the converged values optimal values = opt.x #I would like to know what the error with errorFunction is when using opt.x values, without having to manually run the script again #Is the minimum error stored somewhere in the returned object opt
has comment: http://stackoverflow.com/comment/89766881
has comment: http://stackoverflow.com/comment/89751921
tagged with: python
type: AnsweredQuestion
score: 1
has title: Retrieve scipy minimize function lowest error

http://stackoverflow.com/comment/89874259
comment on: http://stackoverflow.com/q/51450334
score: 0
has text: Since you're only creating the table if it doesn't already exist, are you sure there is a unique constraint on `ChatID`? Have you checked the actual schema?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51358511
tagged with: http://stackoverflow.com/tag/xml
tagged with: xpath
type: UnansweredQuestion
tagged with: python
has body: I'am using Odoo10 community, and I'am trying to inherit the sale order form and edit lock button, to make it visible only where state = sale and my own condition (based on an other field value ('Costum_field','=', 'Value1')). The originale code from sale module : This is my code : ['|' , ('state','!=', 'sale'), ('Costum_field','=', 'Value1')] Now the button is invisble whatever the value of state and my costume field Thank an advance
has answer: http://stackoverflow.com/a/51454471
type: Question
score: 0
tagged with: odoo-10
has title: hide lock button on sale order form based on state & condition in odoo10
answer count: 1

http://stackoverflow.com/q/51343674
type: Question
tagged with: registration
linked to: http://stackoverflow.com/q/36414804
score: 0
tagged with: api
answer count: 1
has body: I have my first project as junior in my work. It is old (Django 1.8) and it is normal django framework... not REST. It supports web, and mobile. I have to create endpoint for mobile to create user. I think it is not a problem (to create) but I want to make sure it will be save. First of all I thought that I will create normal ModelForm (RegisterAPIForm based on model=User with full validation (I mean init all fields that are in "backend" not visible for user | cleaned_data for all fields | special overwriten method save() that in addition hashes password, and send email) and in Views I'll add something like this: class RegistrationAPITestView(View): def post(self, request): form = RegistrationAPIForm( request.POST ) if form.is_valid(): form.save() return JsonResponse({}) else: #check errors and send error code back Or I should do it other way, by using User object? class RegistrationAPITestView(View): def post(self, request): #check if user does not exist #password1 and password2 validation user = User.objects.create() user.name = request.POST['username'] user.set_password(request.POST['password']) #init all fields that user can't choose like groups etc user.save() What do you think? Do I need ModelForm that I won't even render? It seems to be safer, but maybe I should check it other way? with User object? Btw. Registration form already exists for web but there is a lot of "web" stuff that I don't need and I don't have to check and there is another method of saving password, so I believe I should create new one. My code will be revieved in 2 weeks (senior vacations) but now I'm alone and want to do my best.
has answer: http://stackoverflow.com/a/51345673
has title: Django not REST - API user registration
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/51345673
type: AnsweredQuestion

http://stackoverflow.com/comment/89789735
has text: No. Suppose I do not know 'Toy Story' is the value there.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51409114
score: 0

http://stackoverflow.com/q/51418142
has title: Python list comprehension: Skip elements that raise exception
has comment: http://stackoverflow.com/comment/89807298
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/1528237
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/89807473
type: Question
has body: I want to apply a function in a list comprehension that does not "work" for certain values. A simple example would be [1/x for x in [-2, -1, 0, 1, 2]]. I would like to write something that skips the 0 and returns the following list: [-0.5, -1.0, 1.0, 0.5]. My best shot so far was wrapping the division in a try statement: def try_div(x): try: return 1/x except ZeroDivisionError: pass result_with_none = [try_div(x) for x in [-2, -1, 0, 1, 2]] result = [x for x in result_with_none if x is not None] This seems a bit inconvenient. Can I rewrite try_div in a way that makes the list comprehension skip the 0 element? Remark: In this simple example, I could of course write [try_div for x in [-2, -1, 0, 1, 2] if x != 0]. This is not practicable in my actual use case, because it is not easy to check a priori which values will raise an exception. Remark 2: In contrast to this question, I am fine with explicitly handling exceptions in a function (like try_div). My question is mostly about how I could combine the last two steps (result_with_none = ... and result = ...) into one.
has answer: http://stackoverflow.com/a/51418275
accepted answer: http://stackoverflow.com/a/51418275
has comment: http://stackoverflow.com/comment/89807325
has comment: http://stackoverflow.com/comment/89807388
score: 0
tagged with: exception
has comment: http://stackoverflow.com/comment/89807814
answer count: 1

http://stackoverflow.com/a/51346092
score: 0
type: AcceptedAnswer
has body: Use tf.nn.softmax(self.logits) to get probabilistic scores. Also see this question: What is logits, softmax and softmax_cross_entropy_with_logits?
type: Answer
has comment: http://stackoverflow.com/comment/89672906
accepted answer of: http://stackoverflow.com/q/51345440
has comment: http://stackoverflow.com/comment/89666355
answers question: http://stackoverflow.com/q/51345440

http://stackoverflow.com/comment/89811418
type: Comment
comment on: http://stackoverflow.com/q/51420110
type: QuestionComment
score: 1
has text: Can you please be more precise? What is wrong with your code? Any error? Files are not written? What is excatly expected result?

http://stackoverflow.com/comment/89657667
type: Comment
type: QuestionComment
has text: `Share.objects.all().select_related('post').filter(user=1)` ?
comment on: http://stackoverflow.com/q/51342112
score: 0

http://stackoverflow.com/comment/89632099
comment on: http://stackoverflow.com/a/51327194
type: AnswerComment
score: 0
type: Comment
has text: @Zahid: without an error, that's very hard to answer.

http://stackoverflow.com/a/51442071
has comment: http://stackoverflow.com/comment/89858111
has comment: http://stackoverflow.com/comment/89860491
has comment: http://stackoverflow.com/comment/89860873
type: Answer
has comment: http://stackoverflow.com/comment/89860563
has comment: http://stackoverflow.com/comment/89860422
answers question: http://stackoverflow.com/q/51441302
has comment: http://stackoverflow.com/comment/89860728
has comment: http://stackoverflow.com/comment/89860624
has body: I do new spider with your configs, and the problem is in robots.txt. DEBUG: Forbidden by robots.txt: https://www6.hertsmere.gov.uk/online-applications/weeklyListResults.do?action=firstPage> Crawl first need to downloads robots.txt before crawling. To change it you need to give False valut to ROBOTSTXT_OBEY. Go to you settings.py and change it. ROBOTSTXT_OBEY = False Some output that i received. http://www.w3.org/1999/xhtml" xml:lang="en" cla$s="js"&gt;&lt;head&gt; &lt;!-- #BeginEditable "doctitle" --&gt; &lt;title&gt; Error &lt;/title&gt;
has comment: http://stackoverflow.com/comment/89860370
score: 0
has comment: http://stackoverflow.com/comment/89858079
has comment: http://stackoverflow.com/comment/89860147

http://stackoverflow.com/q/51394411
tagged with: unit-testing
has comment: http://stackoverflow.com/comment/89765123
type: Question
answer count: 8
has answer: http://stackoverflow.com/a/51399767
tagged with: mocking
has answer: http://stackoverflow.com/a/60676702
has body: When I was trying to mock an async function in unittest with MagicMock, I got this exception: TypeError: object MagicMock can't be used in 'await' expression With sample code like: # source code class Service: async def compute(self, x): return x class App: def __init__(self): self.service = Service() async def handle(self, x): return await self.service.compute(x) # test code import asyncio import unittest from unittest.mock import patch class TestApp(unittest.TestCase): @patch('__main__.Service') def test_handle(self, mock): loop = asyncio.get_event_loop() app = App() res = loop.run_until_complete(app.handle('foo')) app.service.compute.assert_called_with("foo") if __name__ == '__main__': unittest.main() How should I fix it with built-in python3 libraries?
has answer: http://stackoverflow.com/a/78834904
score: 55
has answer: http://stackoverflow.com/a/63429558
upvote count: 55
downvote count: 0
has answer: http://stackoverflow.com/a/63488859
tagged with: asynchronous
has answer: http://stackoverflow.com/a/74114601
favorite count: 0
has comment: http://stackoverflow.com/comment/89760501
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/48761985
has answer: http://stackoverflow.com/a/54300292
linked to: http://stackoverflow.com/q/32480108
has title: Python - object MagicMock can't be used in 'await' expression
has answer: http://stackoverflow.com/a/71526225
has comment: http://stackoverflow.com/comment/89760299

http://stackoverflow.com/q/51372223
has body: So I have a problem same as this question. Except I cannot find out which name is clashing. Can you please point out where exactly the variable name clash is occurring, I have tried a lot to no avail. Or you can suggest some methods to find out the point of error. Here is my TensorFlow code: def convolutionForwardPropagation(features, labels, mode, params): img = features['x'] c1 = tf.layers.conv2d(img, filters = 32, kernel_size = [1,3], padding = 'VALID', activation = tf.nn.relu, kernel_regularizer = tf.contrib.layers.l2_regularizer(20.0)) c2 = tf.layers.conv2d(c1, filters = 64, kernel_size = [1,3], padding = 'VALID', activation = tf.nn.relu, kernel_regularizer = tf.contrib.layers.l2_regularizer(20.0)) c3 = tf.layers.conv2d(c2, filters = 64, kernel_size = [1,3], padding = 'VALID', activation = tf.nn.relu, kernel_regularizer = tf.contrib.layers.l2_regularizer(20.0)) c4 = tf.layers.conv2d(c3, filters = 64, kernel_size = [1,3], padding = 'VALID', activation = tf.nn.relu, kernel_regularizer = tf.contrib.layers.l2_regularizer(20.0)) c5 = tf.layers.conv2d(c4, filters = 128, kernel_size = [1,3], padding = 'VALID', activation = tf.nn.relu, kernel_regularizer = tf.contrib.layers.l2_regularizer(20.0)) shape1 = c5.get_shape().as_list() fr = tf.reshape(c5, shape = (-1, shape1[3] * shape1[2])) fc1 = tf.contrib.layers.fully_connected(fr, 20, activation_fn = tf.nn.relu, weights_regularizer = tf.contrib.layers.l2_regularizer(500.0)) fc2 = tf.contrib.layers.fully_connected(fc1, 2, activation_fn = tf.nn.sigmoid, weights_regularizer = tf.contrib.layers.l2_regularizer(500.0)) entropy = tf.nn.softmax_cross_entropy_with_logits_v2(logits = fc2, labels = labels, name = 'cross_entropy') loss = tf.reduce_mean(entropy, name = 'loss') optimizer = tf.train.AdamOptimizer(params) hypothesis = tf.nn.softmax(fc2) y_pred_class = tf.argmax(hypothesis, axis = 1) sparseLabels = tf.argmax(labels, axis = 1) if(mode == tf.estimator.ModeKeys.PREDICT): spec = tf.estimator.EstimatorSpec(mode = mode, predict…
linked to: http://stackoverflow.com/q/38306330
type: Question
accepted answer: http://stackoverflow.com/a/51372477
tagged with: python-3.x
tagged with: python
answer count: 1
score: 0
has title: Variable clash inTensorFlow
tagged with: tensorflow
has answer: http://stackoverflow.com/a/51372477
type: AnsweredQuestion

http://stackoverflow.com/comment/89635428
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51329504
has text: Similar https://stackoverflow.com/q/51049975/5320906

http://stackoverflow.com/comment/89965547
score: 0
type: Comment
type: QuestionComment
has text: Why didn't you use a ConvLSTM layer ?
comment on: http://stackoverflow.com/q/51462603

http://stackoverflow.com/a/51463725
answers question: http://stackoverflow.com/q/51463643
upvote count: 7
has comment: http://stackoverflow.com/comment/127514293
has body: You can use get_level_values for select levels, convert to floats and last : a = my_dataframe.index.get_level_values(0).astype(float) b = my_dataframe.index.get_level_values(1).astype(float) my_dataframe.index = [a,b] Or: my_dataframe = my_dataframe.set_index([a,b]) Another solution with MultiIndex.set_levels: a = my_dataframe.index.levels[0].astype(float) b = my_dataframe.index.levels[1].astype(float) my_dataframe.index = my_dataframe.index.set_levels([a,b]) Or: my_dataframe = my_dataframe.set_index(my_dataframe.index.set_levels([a,b]))
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/127514353
has comment: http://stackoverflow.com/comment/89896280
type: Answer
has comment: http://stackoverflow.com/comment/127514263
accepted answer of: http://stackoverflow.com/q/51463643
score: 7

http://stackoverflow.com/comment/126735805
type: AnswerComment
has text: I had the same issue! I had all the proper permissions, but using the wrong bucket name resulted in a "permission" error, which was pretty misleading.
comment on: http://stackoverflow.com/a/69313644
score: 3
type: Comment

http://stackoverflow.com/comment/89859452
type: Comment
type: QuestionComment
has text: I used your code and I can't see where it's failing
score: 1
comment on: http://stackoverflow.com/q/51444391

http://stackoverflow.com/comment/89816422
comment on: http://stackoverflow.com/q/51421916
score: 0
type: Comment
type: QuestionComment
has text: I have edited the question.

http://stackoverflow.com/comment/89711640
has text: replace `print()` with `eval()`?
score: 0
comment on: http://stackoverflow.com/q/51369572
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89847800
has text: @tripleee you know more than I do. You know when the above code was written? I don't.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51437287
type: Comment

http://stackoverflow.com/a/51357529
has comment: http://stackoverflow.com/comment/89768297
has comment: http://stackoverflow.com/comment/89752357
has comment: http://stackoverflow.com/comment/89688940
accepted answer of: http://stackoverflow.com/q/51356927
answers question: http://stackoverflow.com/q/51356927
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89687154
has comment: http://stackoverflow.com/comment/89752268
has comment: http://stackoverflow.com/comment/89687217
has comment: http://stackoverflow.com/comment/89752419
has comment: http://stackoverflow.com/comment/89687347
type: Answer
has comment: http://stackoverflow.com/comment/89760853
score: 1
has body: You got the following error: AttributeError: 'module' object has no attribute 'dates' Your error message is telling you that matplotlib.pyplot.dates (plt.dates) doesn't exist. (The error says that there's a module that you're calling 'dates' but it doesn't exist). So you need to fix that error before you worry about converting anything. Did you mean to call matplotlib.dates.date2num instead? In your code you have the following: import matplotlib.dates as mdate So maybe you meant to call mdate.date2num instead? That should eliminate the AttributeError. If that doesn't work for you, you could try what is suggested in the link provided by one of the other commenters, to use pandas to_pydatetime. I'm not familiar with it, but in this example page, it is accessed as Series.dt.to_pydatetime() All of this converting is just necessary because you are trying to use df.plot; maybe you should consider just calling matplotlib directly. For example, could you just use plt.plot_date instead? (here's the link to it). Pandas is excellent, but the plotting interface isn't as mature as the rest of it. As an example (I'm not saying this is the exact problem you are having) but here is a known bug in pandas regarding plotting dates. Here is an older stack overflow thread where someone stubs out a plt.plot_date method for you.
upvote count: 1
has comment: http://stackoverflow.com/comment/89728303
has comment: http://stackoverflow.com/comment/89721688
has comment: http://stackoverflow.com/comment/89703375
has comment: http://stackoverflow.com/comment/89687272
has comment: http://stackoverflow.com/comment/89725497

http://stackoverflow.com/a/51444993
type: Answer
answers question: http://stackoverflow.com/q/51444913
has comment: http://stackoverflow.com/comment/89861109
has body: Check out pandas. It can do all the things you need. Start with: df = pandas.read_csv(&lt;filename&gt;, usecols = ['ticker', 'price', quantity'])) Use usecols if your csv has column names. Otherwise, set them afterwards: df.columns = ['ticker', 'price', quantity']. Then you can operate on the columns like: df['result'] = df['price'] * df['quantity']
score: 0

http://stackoverflow.com/q/51452243
tagged with: django
tagged with: python
has body: I am having issues with installing django and upgrading pip. I don't know how I began running into these issues, but when I go to type django-admin startproject mysite it gives me an error: -bash: django-admin: command not found I go ahead and type pip install Django and I then receive this error: Could not fetch URL https://pypi.python.org/simple/django/: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590) - skipping When upgrading pip... Could not fetch URL https://pypi.python.org/simple/pip/: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590) - skipping I believe the issue lies within [SSL: TLSV1_ALERT_PROTOCOL_VERSION]. I don't know how to go about fixing it so that I can use django and upgrade my pip version. If I type python3 -c "import ssl; print(ssl.OPENSSL_VERSION)", I get OpenSSL 1.0.2n 7 Dec 2017. Do note that I was running django with no issues before these issues came to fruition.
score: 2
type: AnsweredQuestion
has title: Upgrading pip/installing django - [SSL: TLSV1_ALERT_PROTOCOL_VERSION]
tagged with: ssl
has answer: http://stackoverflow.com/a/51625284
type: Question
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51625284
favorite count: 0
upvote count: 2

http://stackoverflow.com/q/51377076
score: 0
has title: How to filter dictionary of datatime objects based on weeks
answer count: 1
has answer: http://stackoverflow.com/a/51377519
has comment: http://stackoverflow.com/comment/89725865
tagged with: python
has comment: http://stackoverflow.com/comment/89726084
tagged with: dictionary
type: AnsweredQuestion
has body: So, I've pulled data from fitbit API and got dictionary in following format: weightData = {'January': {datetime.date(2018, 1, 1): {'weight': 0, 'fat': 0}, datetime.date(2018, 1, 2): {'weight': 0, 'fat': 0} Now I want to calculate averages for every week. I searched google and found datetime.isocalendar() method. It works great but I can't figure out how to loop through dict. This is my attempt: for i in range (1, 30): for month in data: for date in data[month]: if date.isocalendar()[1] == i: tmpWeight += data[month][date]["weight"] tmpFat += data[month][date]["fat"] counter += 1 elif date.isocalendar()[1] &gt; i: continue avgWeight.append(tmpWeight/counter) avgFat.append(tmpFat/counter) tmpWeight = 0 tmpFat = 0 counter = 0 But I'm getting "ZeroDivisionError: division by zero". I assume it happens when date.isocalendar()[1] != i and it tries to divide some values by "counter" which has value of 0. Can someone point me my mistake?
accepted answer: http://stackoverflow.com/a/51377519
type: Question

http://stackoverflow.com/comment/89827221
score: 0
comment on: http://stackoverflow.com/q/51426697
has text: which autocomplete library you are using? and do you want to add JSON data on page load only?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51377329
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89742181
has comment: http://stackoverflow.com/comment/89803611
answer count: 0
upvote count: 3
tagged with: celery
type: Question
has title: Celery doesn't acknowledge tasks if stopped too quickly
score: 3
downvote count: 0
favorite count: 0
has body: For a project using Celery, I would like to test the execution of a task. I know that the documentation advises to mock it but since I'm not using the official client I would want to check for a specific test that everything works well. Then I set up a very simple task that takes as parameters an Unix socket name and a message to write to it: the task opens the connection on the socket, writes the message and closes the connection. Inside the tests, the Celery worker is launched with a subprocess: I start it before sending the task, send it a SIGTERM when I receive the message on the socket and then wait for the process to close. Everything goes well : the message is received, it matches what is expected and the worker correctly terminates. But I found that when the tests stop, a message still remains within the RabbitMQ queue, as if the task had never been acknowledged. I confirmed this by looking at the RabbitMQ graphical interface: a "Deliver" occurs after the task is executed but no "Acknowledge". This seems strange because using the default configuration the acknowledge should be sent before task execution. Going further in my investigations I noticed that if I add a sleep of a split second just before sending SIGTERM to the worker, the task is acknowledged. I tried to inspect the executions with or without sleep using strace, here are the logs: Execution with a sleep of 0.5s. Execution without sleep. The only noticeable difference I see is that with sleep the worker has time to start a new communication with the broker. It receives an EAGAIN from a recvfrom and sends a frame "\1\0\1\0\0\0\r\0&lt;\0P\0\0\0\0\0\0\0\1\0\316". Is this the acknowledge? Why does this occur so late? I give you the parameters with which I launch the Celery worker: celery worker --app tests.functional.tasks.app --concurrency 1 --pool solo --without-heartbeat. The --without-heartbeat is just here to reduce differences between executions with or without sleep. Otherwise an additional hea…

qfilesystemmodel
tag name: qfilesystemmodel
type: Tag
tags question: http://stackoverflow.com/q/51338059

http://stackoverflow.com/a/51445220
accepted answer of: http://stackoverflow.com/q/51442725
has body: The overview of NumPy history gives an indication of why not everything is consistent: it has two predecessors that were developed independently. Backward compatibility requires the project to keep array methods like max. Ongoing development favors the function syntax np.fun(array). I suppose one reason for the latter is that it allows array_like input (the term used throughout NumPy documentation): anything that NumPy can turn into an ndarray.
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/51442725
type: AcceptedAnswer
upvote count: 3
type: Answer

http://stackoverflow.com/a/51447533
has comment: http://stackoverflow.com/comment/89870489
has comment: http://stackoverflow.com/comment/89901555
has comment: http://stackoverflow.com/comment/90019282
answers question: http://stackoverflow.com/q/51446622
has comment: http://stackoverflow.com/comment/90019229
has comment: http://stackoverflow.com/comment/89901006
has comment: http://stackoverflow.com/comment/89870531
score: 0
has body: You can use re for parsing the text: import re from collections import defaultdict from pprint import pprint data_from_file = """ 0 3 3.0277 0 14 4.8251 1 6 2.8984 2 3 4.5238 2 12 1.9643 3 2 4.5238""" def transform_to_my_format(data): d = defaultdict(dict) for (i1, i2, i3) in re.findall(r'([\d\.]+)\s+([\d\.]+)\s+([\d\.]+)', data): d[i1].update({i2: float(i3)}) return d pprint(transform_to_my_format(data_from_file)) Outputs: defaultdict(&lt;class 'dict'&gt;, {'0': {'14': 4.8251, '3': 3.0277}, '1': {'6': 2.8984}, '2': {'12': 1.9643, '3': 4.5238}, '3': {'2': 4.5238}})
type: Answer

http://stackoverflow.com/comment/89812282
type: QuestionComment
has text: Working fine, thank you @jezrael
comment on: http://stackoverflow.com/q/51420557
score: 0
type: Comment

http://stackoverflow.com/q/51434149
tagged with: python
has answer: http://stackoverflow.com/a/51434191
type: AnsweredQuestion
tagged with: list
has body: I have a list with 1550500 numbers, and all of them with quotes. Example: list('100', '150', '200', '250') etc... I need to sum all the numbers, but before that I need to convert it to INT. List Name: trip_list My code: mean_tripstr = str(trip_list) mean_trip = [int(x) for x in mean_tripstr] print(type(mean_trip)) Error message: Traceback (most recent call last): File "projeto1.py", line 235, in &lt;module&gt; mean_trip = [int(x) for x in mean_tripstr] File "projeto1.py", line 235, in &lt;listcomp&gt; mean_trip = [int(x) for x in mean_tripstr] ValueError: invalid literal for int() with base 10: '[' What am I doing wrong? I am new to coding...
type: Question
answer count: 2
tagged with: string
possible better answer: http://stackoverflow.com/a/51434191
score: 0
has comment: http://stackoverflow.com/comment/89838683
accepted answer: http://stackoverflow.com/a/51434213
tagged with: integer
has title: Converting list to string then integer
has answer: http://stackoverflow.com/a/51434213

http://stackoverflow.com/comment/89861212
score: 0
type: Comment
type: QuestionComment
has text: Ok i will look into that, just create a series or list with all the ID's for the names in the combos file, i dont need to add the column to combos @Ben.T
comment on: http://stackoverflow.com/q/51445026

http://stackoverflow.com/comment/89902147
score: 0
type: QuestionComment
has text: The example at the end of the documentation for [`fft`](https://pytorch.org/docs/stable/torch.html?highlight=fft#torch.fft) seems to return an array the same size as the input.
type: Comment
comment on: http://stackoverflow.com/q/51466553

http://stackoverflow.com/q/51352347
tagged with: barcode-scanner
type: Question
has comment: http://stackoverflow.com/comment/89677485
has body: I have a Python application that is able to read scan data using https://github.com/trezor/cython-hidapi The problem is I have no idea what the HID commands are to enable/disable the scanner. I think this might be generic across most scanning devices, but hunting for those commands and I have come up empty. Thanks.
score: 0
tagged with: symbols
tagged with: hid
answer count: 1
has comment: http://stackoverflow.com/comment/89677892
has answer: http://stackoverflow.com/a/51352971
type: UnansweredQuestion
tagged with: python
has title: USB/HID Commands to enable/disable a Symbol barcode scanner
has comment: http://stackoverflow.com/comment/89677269

http://stackoverflow.com/q/51387361
upvote count: 3
has body: I want to be able to border an array (really, an image file) with a set of random values. The numpy.pad() function does not have any mode to do this. Is there a shorthand way to achieve this or would I have to create a function from scratch?
tagged with: numpy
has title: Pad a numpy array with random values within a given range?
has comment: http://stackoverflow.com/comment/89746665
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51387971
tagged with: random
tagged with: padding
score: 3
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51387524
type: Question
answer count: 2
tagged with: python

http://stackoverflow.com/comment/91969650
has text: Does the code in the Update section now solve your issue?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51468724

http://stackoverflow.com/comment/89945266
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51469428
type: Comment
has text: You are most welcome. Updated post with link for [Kivy Dynamic Classes](https://kivy.org/docs/guide/lang.html#dynamic-classes). Noted.

http://stackoverflow.com/q/51439892
tagged with: python
has comment: http://stackoverflow.com/comment/89850107
answer count: 4
score: 15
has answer: http://stackoverflow.com/a/51440114
has comment: http://stackoverflow.com/comment/89850077
accepted answer: http://stackoverflow.com/a/51440114
has answer: http://stackoverflow.com/a/51440138
has answer: http://stackoverflow.com/a/65267049
has body: How can I calculate symmetric mean absolute error in python using numpy or pandas? Is there are metric present in scikit sklearn ? Example data: Actual value: 2,3,4,5,6,7,8,9 Forecast value: 1,3,5,4,6,7,10,7 Formula for SMAPE see screenshot below: How can I do it in python using pandas or numpy and calculate SMAPE. Note: More info about SMAPE: https://en.wikipedia.org/wiki/Symmetric_mean_absolute_percentage_error
has comment: http://stackoverflow.com/comment/89849770
possible better answer: http://stackoverflow.com/a/74244286
has answer: http://stackoverflow.com/a/74244286
tagged with: numpy
upvote count: 15
has comment: http://stackoverflow.com/comment/89849980
has title: How to find symmetric mean absolute error in python?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89850015
downvote count: 0
has comment: http://stackoverflow.com/comment/89849864
favorite count: 0
tagged with: statistics
type: Question

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/51379750
tags question: http://stackoverflow.com/q/51348718
tags question: http://stackoverflow.com/q/51472284
tags question: http://stackoverflow.com/q/51463334
type: Tag
tags question: http://stackoverflow.com/q/51385356
tags question: http://stackoverflow.com/q/51465212
tags question: http://stackoverflow.com/q/51463223
tags question: http://stackoverflow.com/q/51463025
tags question: http://stackoverflow.com/q/51411231
tags question: http://stackoverflow.com/q/51347054
tags question: http://stackoverflow.com/q/51351785
tags question: http://stackoverflow.com/q/51351472
tags question: http://stackoverflow.com/q/51445930
tags question: http://stackoverflow.com/q/51474515
tags question: http://stackoverflow.com/q/51435579
tags question: http://stackoverflow.com/q/51341901

http://stackoverflow.com/a/51433377
has comment: http://stackoverflow.com/comment/89837438
type: Answer
answers question: http://stackoverflow.com/q/51433342
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51433342
has body: We can use a dictionary comprehension. We also don't need the nested zip {x+y: (z, w) for x, y, z, w in zip(a, b, c, d)} # {'0201': ('10G', '08'), '0202': ('10G', '07'), '0301': ('10G', '09')}
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89723896
type: QuestionComment
has text: I've added expected output
score: 0
comment on: http://stackoverflow.com/q/51374604
type: Comment

http://stackoverflow.com/q/51463061
type: Question
has title: What is the shape of 3D tensor by 3D tensor multiplication in tensorflow?
tagged with: matrix-multiplication
score: 0
has comment: http://stackoverflow.com/comment/89909892
has body: So I have a code from github on NLP task that multiples 3D tensor by another 3D tensor, both of which have the same shape so the multiplication looks like (batch,bucket,bucket)*(batch,bucket,bucket). Exact code with some modification, though of not so big importance is as follows: bilin = tf.batch_matmul(lin,inputs2, adj_y=True) where lin and inputs2 is of the above shape. So what would be the resulting shape? PS. I know this is very old version of tensorflow, but this is not so important I guess.
has comment: http://stackoverflow.com/comment/89912308
tagged with: python
answer count: 0
tagged with: tensor
type: UnansweredQuestion
tagged with: tensorflow

http://stackoverflow.com/q/51330300
type: Question
has title: sqlalchemy: how to return list of objects joining 3 tables?
has comment: http://stackoverflow.com/comment/89636850
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/89636612
tagged with: sql
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51330725
has body: @hybrid_method # @paginate def investors(self, **kwargs): """All investors for a given Custodian""" ind_inv_type_id = InvestorType.where(description="Individual").first().id inv_query = Investor.with_joined(InvestorAddress, InvestmentAddress, CustodianAddress) \ .filter_by(custodians_id=self.id) \ .with_joined(Investment) \ .filter_by(investor_types_id=ind_inv_type_id) investors = Investor.where(None, False, inv_query, **kwargs) temp_inv_query = Investor.with_joined(CustodianInvestor, Custodian)\ .filter_by(Custodian.id==self.id) temp_investors = Investor.where(None, False, temp_inv_query, **kwargs) return list(set(investors + temp_investors)) # end def investors # @auth.access_controlled class InvestorAddress(db.Model, EntityAddressMixin): # Metadata __tablename__ = 'investor_addresses' # Database Columns investors_id = db.Column(db.ForeignKey("investors.investors_id"), nullable=False) investor = db.relationship("Investor", foreign_keys=[investors_id], backref=db.backref("InvestorAddress")) # end class InvestorAddress class InvestmentAddress(db.Model): """This model differs from other EntityAddress Models because it links to either an investor_address or an custodian_address.""" # Metadata __tablename__ = 'investment_addresses' # Database Columns address_types_id = db.Column( db.ForeignKey("address_types.address_types_id"), nullable=False) address_type = db.relationship("AddressType", foreign_keys=[address_types_id], backref=db.backref("InvestmentAddress")) investments_id = db.Column(db.ForeignKey("investments.investments_id"), nullable=False) investment = db.relationship("Investment", foreign_keys=[investments_id], backref=db.backref("InvestmentAddress")) investor_addresses_id = db.Column(db.ForeignKey( "investor_addresses.investor_addresses_id")) investor_address = db.relationship("InvestorAddress", foreign_keys=[investor_addresses_id], backref=db.backref("InvestmentAddress")) custodian_addresses_id = db.Column(db.ForeignKey( "custodian_addresses.custodian_addres…
tagged with: python
score: 2
upvote count: 2
tagged with: mysql

http://stackoverflow.com/comment/89830755
type: QuestionComment
type: Comment
score: 1
has text: Works fine for me...`print(listsum(weight))`
comment on: http://stackoverflow.com/q/51429878

http://stackoverflow.com/comment/89642032
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51333249
has text: C:\Users\lovel\Anaconda3\S4>make mkdir build mkdir build/S4k The syntax of the command is incorrect. make: *** [objdir] Error 1

http://stackoverflow.com/q/51392012
has answer: http://stackoverflow.com/a/51392708
has title: convert irregular time series to hourly data in python and have normal distribution
type: Question
has comment: http://stackoverflow.com/comment/89756174
has comment: http://stackoverflow.com/comment/89756046
tagged with: pandas
upvote count: 1
has comment: http://stackoverflow.com/comment/89756027
has body: I have a data frame that looks like the following: Date Time Entry Exist 2013-01-07 05:00:00 29.0 12.0 2013-01-07 10:00:00 98.0 83.0 2013-01-07 15:00:00 404.0 131.0 2013-01-07 20:00:00 2340.0 229.0 2013-01-08 05:00:00 3443.0 629.0 2013-01-08 10:00:00 6713.0 1629.0 2013-01-08 15:00:00 9547.0 2965.0 2013-01-08 20:00:00 10440.0 4589.0 I would like to convert it and normalize so that it shows the hourly consumption over time. DateTime Entry Exist 2013-01-07 00:00:00 2.0 1.0 2013-01-07 01:00:00 9.0 4.0 2013-01-07 02:00:00 16.0 6.0 2013-01-07 03:00:00 23.0 9.0 2013-01-07 04:00:00 26.0 10.0 2013-01-07 05:00:00 29.0 12.0 2013-01-07 06:00:00 37.0 19.0 2013-01-07 07:00:00 56.0 32.0 2013-01-07 08:00:00 62.0 57.0 2013-01-07 09:00:00 77.0 63.0 2013-01-07 10:00:00 98.0 83.0 2013-01-07 11:00:00 104.0 95.0 ....... I would like to first concatenate the date and time into one single column as DateTime and then achieve the above result. New to python, any help would be much appreciated. Thank you.
answer count: 1
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/22604564
tagged with: datetime
tagged with: python
accepted answer: http://stackoverflow.com/a/51392708
linked to: http://stackoverflow.com/q/17978092
type: AnsweredQuestion
downvote count: 0
score: 1

http://stackoverflow.com/a/51425236
type: AcceptedAnswer
has body: You can use the csv module with skipinitialspace=True Ex: import csv with open(filename, "r") as infile: reader = csv.reader(infile, delimiter=",", skipinitialspace=True) for line in reader: print([i.strip("'") for i in line]) Output: ['0xe1b04048', 'FUTEX_WAIT', '0', 'NULL ', 'Hey, World, how, are, you']
type: Answer
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51425084
answers question: http://stackoverflow.com/q/51425084
downvote count: 0

http://stackoverflow.com/q/51447460
type: Question
tagged with: numpy
has title: Location of documentation on special methods recognized by numpy
has body: One of the differences between math.exp and numpy.exp is that, if you have a custom class C that has a C.exp method, numpy.exp will notice and delegate to this method whereas math.exp will not: class C: def exp(self): return 'hey!' import math math.exp(C()) # raises TypeError import numpy numpy.exp(C()) # evaluates to 'hey!' However, if you go to the web documentation of numpy.exp, this seems to be taken for granted. It isn't explicitly stated anywhere. Is there a place where this functionality is documented? More generally, is there a place with a list of all such methods recognized by numpy?
downvote count: 0
score: 3
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51447793
upvote count: 3

http://stackoverflow.com/comment/89628695
score: 0
type: Comment
type: QuestionComment
has text: I don't see any `StringVar` in the code, are you using one for the `textvariable` of the label? (see https://stackoverflow.com/questions/46981834/tkinter-label-textvariable-not-changing)
comment on: http://stackoverflow.com/q/51326592

http://stackoverflow.com/q/51449471
type: AnsweredQuestion
tagged with: django-views
has comment: http://stackoverflow.com/comment/107573860
has title: What's the point of using namespace inside include? (Django 2.0)
type: Question
answer count: 2
score: 5
has answer: http://stackoverflow.com/a/51450073
accepted answer: http://stackoverflow.com/a/51450003
has body: What's the point of using namespace inside include, if adding app_name in the app's urls is the one that actually lets me use the "app:view" syntax. Blog_app/urls.py from django.urls import path from django.views.generic.base import RedirectView from . import views app_name = 'posts' #APP_NAME urlpatterns = [ path('',RedirectView.as_view(url='posts/'), name='home'), path('posts/',views.post_list, name='list'), path('posts/detail/&lt;int:pk&gt;',views.post_detail, name='detail'), path('posts/delete',views.post_delete, name='delete'), path('posts/create',views.post_create, name='create'), path('posts/update',views.post_update, name='update'),] Project/urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog_app.urls',namespace='posts')),] this code works for reversing the url to posts/detail like this example.html &lt;a href="{% url 'posts:list' %}"&gt; Example &lt;a/&gt; but if delete the namespace it stills reverses my url to posts/detail Project/urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog_app.urls')), #NAMESPACE DELETED ]
has answer: http://stackoverflow.com/a/51450003
favorite count: 0
tagged with: django-templates
possible better answer: http://stackoverflow.com/a/51450073
tagged with: django
tagged with: python
downvote count: 1
upvote count: 6

http://stackoverflow.com/a/51440114
has comment: http://stackoverflow.com/comment/89850518
has comment: http://stackoverflow.com/comment/89850404
has comment: http://stackoverflow.com/comment/89850516
has comment: http://stackoverflow.com/comment/89850568
accepted answer of: http://stackoverflow.com/q/51439892
upvote count: 40
has comment: http://stackoverflow.com/comment/92593795
answers question: http://stackoverflow.com/q/51439892
has comment: http://stackoverflow.com/comment/89850614
score: 40
has comment: http://stackoverflow.com/comment/89850677
has comment: http://stackoverflow.com/comment/92592728
has body: It's pretty straightforward to convert the equation to numpy import numpy as np def smape(A, F): return 100/len(A) * np.sum(2 * np.abs(F - A) / (np.abs(A) + np.abs(F))) A = np.array([2,3,4,5,6,7,8,9]) F = np.array([1,3,5,4,6,7,10,7]) print(smape(A, F))
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92588493
has comment: http://stackoverflow.com/comment/92592799
has comment: http://stackoverflow.com/comment/115385513
has comment: http://stackoverflow.com/comment/92590214
type: Answer
has comment: http://stackoverflow.com/comment/133915644
has comment: http://stackoverflow.com/comment/92589839

http://stackoverflow.com/comment/89730134
has text: It's `from package.module import function`, you can also do it like this : `from package import module` then use your module `module.function`
comment on: http://stackoverflow.com/a/51378942
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51456809
upvote count: 13
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/7828867
has answer: http://stackoverflow.com/a/51460558
has title: Removing duplicate content from a list of lists while not preserving any order
has answer: http://stackoverflow.com/a/51457057
downvote count: 1
has answer: http://stackoverflow.com/a/51503241
type: Question
has answer: http://stackoverflow.com/a/51458433
has answer: http://stackoverflow.com/a/51457162
has comment: http://stackoverflow.com/comment/89893643
has comment: http://stackoverflow.com/comment/89894931
has answer: http://stackoverflow.com/a/51457172
score: 12
has answer: http://stackoverflow.com/a/51457261
has body: I was writing a code in python to find factor pairs for an integer. But making pairs resulted in reverse pairs as well. I want to eliminate those reverse pairs using a simple method without importing any modules. for eg. [[1, 200], [2, 100], [4, 50], [5, 40], [8, 25], [10, 20], [20, 10], [25, 8], [40, 5], [50, 4], [100, 2], [200, 1]] the output should be: [[1, 200], [2, 100], [4, 50], [5, 40], [8, 25], [10, 20]] This is what I've got so far: N = [] J = [] F = [] Z = [] S = [] num = input("Enter no. of elements in list") print ('Enter numbers') prod = 1 for i in range(int(num)): n = input("num :") N.append(int(n)) for x in N: prod = prod*x print (prod) k = input("Enter no. of splits:") for o in range(1,prod+1): if prod%o == 0: J.append(o) F.append(o) print (J) Z = [[a, b] for a in J for b in F if a*b == prod] print (Z)
accepted answer: http://stackoverflow.com/a/51457057
possible better answer: http://stackoverflow.com/a/51456827
answer count: 10
has answer: http://stackoverflow.com/a/51464726
has answer: http://stackoverflow.com/a/51456827
has answer: http://stackoverflow.com/a/51456937
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89883149

http://stackoverflow.com/q/51472873
has comment: http://stackoverflow.com/comment/89914177
has body: I'm parsing system arguments in my Python project using sys.argv. At some point i had to modify the script after having written the logic that parses system args. I added a line the basically appends a string to sys.argv so the logic that parses it won't be changed - sys.argv.append('some string here') Is it a bad practice to modify the system arguments after they have been created for the program ?
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51473054
tagged with: command-line-arguments
accepted answer: http://stackoverflow.com/a/51473045
has answer: http://stackoverflow.com/a/51473054
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/74354202
downvote count: 0
favorite count: 0
has title: Python append to system arguments - bad practice?
answer count: 3
has answer: http://stackoverflow.com/a/51473045
score: 4

http://stackoverflow.com/comment/89857036
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51443490
has text: @chepner I appreciate that you deleted your answer when you closed, lots out there that don't

http://stackoverflow.com/comment/89926079
score: 0
comment on: http://stackoverflow.com/q/51478210
type: Comment
has text: You have a space between `name` and the underscore in `__name__`. They need to be together.
type: QuestionComment

http://stackoverflow.com/q/51348085
has comment: http://stackoverflow.com/comment/89668793
has answer: http://stackoverflow.com/a/51348190
has body: I am trying to follow this Keras tutorial, but I encounter the following error when compiling using the command python3 test.py: Traceback (most recent call last): File "test.py", line 13, in &lt;module&gt; layers.Dense(64, activation='sigmoid') NameError: name 'layers' is not defined My code is as follows: import tensorflow as tf from tensorflow import keras model = keras.Sequential() # Adds a densely-connected layer with 64 units to the model: model.add(keras.layers.Dense(64, activation='relu')) # Add another: model.add(keras.layers.Dense(64, activation='relu')) # Add a softmax layer with 10 output units: model.add(keras.layers.Dense(10, activation='softmax')) # Create a sigmoid layer: layers.Dense(64, activation='sigmoid') # A linear layer with L1 regularization of factor 0.01 applied to the kernel matrix: layers.Dense(64, kernel_regularizer=keras.regularizers.l1(0.01)) # A linear layer with L2 regularization of factor 0.01 applied to the bias vector: layers.Dense(64, bias_regularizer=keras.regularizers.l2(0.01)) # A linear layer with a kernel initialized to a random orthogonal matrix: layers.Dense(64, kernel_initializer='orthogonal') Python version: 3.6.6 Operating System: MacOS High Sierra I am also doing this all in the command line (tensorflow)$ environment.
accepted answer: http://stackoverflow.com/a/51348190
tagged with: keras-layer
answer count: 2
score: 5
has comment: http://stackoverflow.com/comment/89668820
has comment: http://stackoverflow.com/comment/89668806
tagged with: keras
favorite count: 0
tagged with: python-3.x
upvote count: 5
has comment: http://stackoverflow.com/comment/89668850
tagged with: python
possible better answer: http://stackoverflow.com/a/69910282
has title: Keras Tutorial Error: NameError: name 'layers' is not defined
type: AnsweredQuestion
downvote count: 0
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/89668833
type: Question
has comment: http://stackoverflow.com/comment/89668865
has answer: http://stackoverflow.com/a/69910282

group-by
tags question: http://stackoverflow.com/q/51467866
tags question: http://stackoverflow.com/q/51326602
tags question: http://stackoverflow.com/q/51408907
tags question: http://stackoverflow.com/q/51334434
tag name: group-by
type: Tag
tags question: http://stackoverflow.com/q/51446989
tags question: http://stackoverflow.com/q/51377779
tags question: http://stackoverflow.com/q/51384210
tags question: http://stackoverflow.com/q/51349572
tags question: http://stackoverflow.com/q/51411193
tags question: http://stackoverflow.com/q/51383074
tags question: http://stackoverflow.com/q/51471914
tags question: http://stackoverflow.com/q/51424613
tags question: http://stackoverflow.com/q/51393912
tags question: http://stackoverflow.com/q/51372240

http://stackoverflow.com/a/51389401
answers question: http://stackoverflow.com/q/51389216
type: Answer
score: 0
has body: Using get_dummies with sum df=pd.DataFrame({'type':['big,green','big','small,red']}) df.type.str.get_dummies(sep=',').sum(1) Out[382]: 0 2 1 1 2 2 dtype: int64

http://stackoverflow.com/comment/89689430
comment on: http://stackoverflow.com/q/51358661
has text: How can we tell that a "card" is "done"?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51333713
has comment: http://stackoverflow.com/comment/89642964
answers question: http://stackoverflow.com/q/51333061
score: -1
has comment: http://stackoverflow.com/comment/89642932
downvote count: 1
has comment: http://stackoverflow.com/comment/89643005
has body: If you change this piece of your code for epoch in range(training_epochs): for (x,y) in zip(x_train,y_train): sess.run(train_op, feed_dict = {X:x, Y: y}) by this for (x,y) in zip(x_train,y_train): for epoch in range(training_epochs): sess.run(train_op, feed_dict = {X:x, Y: y}) do you get what you expect? In your original code, the first loop refers to the iterations, so you are fixing the first iteration of gradient descent and then applying it with respect to all previous pairs (because your second loop refers to all previous pairs), then you're fixing a second iteration and again you're applying gradient descent with respect to all previous pairs, and so on. If you interchange your loops as above, then you're fixing a pair and then applying all your iterations of gradient descent to that single pair. I'm not sure if this is what you wanted.
has comment: http://stackoverflow.com/comment/89642901
type: Answer
upvote count: 0
has comment: http://stackoverflow.com/comment/89642748

http://stackoverflow.com/q/51392748
tagged with: python
favorite count: 0
has body: Actually i m making a hospital management GUI software. But there is some problems are arise , when i login as a admin then it will open a new window and when i click any button then it will again open a new window. So i want that there will be only a root window and when i press any button then just the frame will change but window will remain same root. I had used destroy() and tk.raies() as well but when i use these then old window will destroy and that will never come back. So please suggest me a code for frame switching in a same root windows. And when i switch the frame the old frame will go disappear and can come back when it will call.
tagged with: tkinter
type: UnansweredQuestion
score: -5
has comment: http://stackoverflow.com/comment/89757639
type: Question
upvote count: 0
answer count: 1
downvote count: 5
has title: How make a complete gui softwaree in a single windows in tkinter
has answer: http://stackoverflow.com/a/51392904

http://stackoverflow.com/a/51456917
answers question: http://stackoverflow.com/q/51456897
has comment: http://stackoverflow.com/comment/89883413
has comment: http://stackoverflow.com/comment/89883369
type: Answer
score: 2
downvote count: 0
has body: I think you are looking for range, which returns a list in Python 2, but in Python 3 returns a generator. However this is easily converted to a list: print(list(range(20,30,2))) &gt;&gt;&gt; [20, 22, 24, 26, 28] Note: the second argument is a non-inclusive upper bound, so in order to get your desired output you would need to feed it: print(list(range(20,31,2))) &gt;&gt;&gt; [20, 22, 24, 26, 28, 30]
has comment: http://stackoverflow.com/comment/89883384
has comment: http://stackoverflow.com/comment/89883383
upvote count: 2
has comment: http://stackoverflow.com/comment/89883489

http://stackoverflow.com/comment/89742825
type: QuestionComment
has text: Instead of merging here could you just set the value of `lunchable` in `prev_staff` to `True` if the email is in `new_staff`?
comment on: http://stackoverflow.com/q/51385417
score: 0
type: Comment

http://stackoverflow.com/a/51329744
type: Answer
has comment: http://stackoverflow.com/comment/89635141
upvote count: 2
answers question: http://stackoverflow.com/q/51329642
has body: Make a dictionary of products to prices. Then loop over that dictionary to ask how many of a particular product the user wants. Use that data to build a second dictionary representing the order itself. products = { "apple": 1.00, "pear": .70, "banana": .10, "kiwi": 1.50, "melon": 5.75, "pineapple": 12.0, } def get_order(): order = {} for product, price in products.items(): amount = int(input(f"How many {product} do you want at {price:.2f} each?")) order[product] = (price, amount) print("Your total is {:.2f}".format(sum(x*y for x, y in order.values()))) return order
score: 2
downvote count: 0

http://stackoverflow.com/comment/89826899
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51427829
has text: What is it you want fixed?

http://stackoverflow.com/q/51447100
downvote count: 4
upvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
has body: i am new to python and am still learning. I wanted to know what is the difference between these two commands and why do they output different results. Without white space hello = [] for letter in 'word': hello.append(letter) print(hello) Output ['w', 'o', 'r', 'd'] With White space hello = [] for letter in 'word': hello.append(letter) print(hello) output ['w'] ['w', 'o'] ['w', 'o', 'r'] ['w', 'o', 'r', 'd']
has answer: http://stackoverflow.com/a/51447183
tagged with: python
has comment: http://stackoverflow.com/comment/89864564
score: -4
type: Question
has comment: http://stackoverflow.com/comment/89864407
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51447183
has title: different result in print command because of in python 3
has comment: http://stackoverflow.com/comment/89864374

http://stackoverflow.com/comment/89822251
has text: @PeterRincker because the macro won't stop then. `n` will jump back to top (to the first `.`) and move the `.` further left again. But I may miss something, as always I am happy to get corrected/improved.
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51416862

http://stackoverflow.com/q/51349738
has comment: http://stackoverflow.com/comment/89672098
has comment: http://stackoverflow.com/comment/89672174
linked to: http://stackoverflow.com/q/21008858
score: 7
has body: I have this array: arr = np.array([66.5, 89.4000015, 57.2000008, 86.9000015, 64.5999985, 92.3000031, 74.1999969, 76.0999985, 92.0999985, 81.6999969, 72.0999985, 78.8000031, 81.4000015, 95.4000015, 73.5 , 58.5999985, 68.3000031, 68.9000015, 68.6999969, 92. ]) I tried to round each number, and used np.around: [in] np.around(arr, 2) [out] array([66.5, 89.4, 57.2, 86.9, 64.6, 92.3, 74.2, 76.1, 92.1, 81.7, 72.1, 78.8, 81.4, 95.4, 73.5, 58.6, 68.3, 68.9, 68.7, 92. ]) [in] np.around(arr, 4) [out] array([66.5, 89.4, 57.2, 86.9, 64.6, 92.3, 74.2, 76.1, 92.1, 81.7, 72.1, 78.8, 81.4, 95.4, 73.5, 58.6, 68.3, 68.9, 68.7, 92. ]) [in] np.around(arr, 5) [out] array([66.5, 89.4, 57.2, 86.9, 64.6, 92.3, 74.2, 76.1, 92.1, 81.7, 72.1, 78.8, 81.4, 95.4, 73.5, 58.6, 68.3, 68.9, 68.7, 92. ]) [in] np.around(arr, 6) [out] array([66.5 , 89.400002, 57.200001, 86.900002, 64.599998, 92.300003, 74.199997, 76.099998, 92.099998, 81.699997, 72.099998, 78.800003, 81.400002, 95.400002, 73.5 , 58.599998, 68.300003, 68.900002, 68.699997, 92. ]) When the number of decimals is less than 5, the np.around() does not work. When it is larger than 6, the np.around is working well. Any help is appreciated. Anne
linked to: http://stackoverflow.com/q/1995615
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/89672180
has comment: http://stackoverflow.com/comment/89672254
has comment: http://stackoverflow.com/comment/89672089
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/89672020
has comment: http://stackoverflow.com/comment/89672019
has comment: http://stackoverflow.com/comment/89672228
has title: np.round, or np.around doesn't work
answer count: 1
has comment: http://stackoverflow.com/comment/89672092
has comment: http://stackoverflow.com/comment/89672079
favorite count: 0
has comment: http://stackoverflow.com/comment/89672107
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51350067
tagged with: python
upvote count: 7

http://stackoverflow.com/a/77844771
has comment: http://stackoverflow.com/comment/137372333
accepted answer of: http://stackoverflow.com/q/51361356
type: Answer
has comment: http://stackoverflow.com/comment/138252736
upvote count: 60
has body: In 2024 the decision should be obvious: use pyarrow instead of fastparquet: Pandas 3.0 will require pyarrow What’s new in 2.1.0 (Aug 30, 2023). fastparquet is deprecated in Dask 2024.1.0, and "users should migrate to the pyarrow engine" fastparquet is from the dask team. If dask itself does not want to use it, why should you? See the discussion in dask / #8900. Some picks from there: In our recent parquet benchmarking and resilience testing we generally found the pyarrow engine would scale to larger datasets better than the fastparquet engine, and more test cases would complete successfully when run with pyarrow than with fastparquet. The pyarrow library has a larger development team maintaining it and seems to have more community buy-in going forward.
downvote count: 0
has comment: http://stackoverflow.com/comment/137543479
score: 60
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51361356

http://stackoverflow.com/comment/89896533
score: 0
comment on: http://stackoverflow.com/q/51463614
has text: My question is what is wrong with this realisation and why it keeps getting stuck on 6 unhit queens and can't make a final move. I've already examined every bit of code and I think there's some misinterpretation of algorithm itself evolved. So I hope that someone would tell me where I did wrong.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89667354
type: QuestionComment
comment on: http://stackoverflow.com/q/51347059
has text: I wouldn't call that *'custom column(s)'*, just crosstabulation of the Language column
score: 0
type: Comment

http://stackoverflow.com/comment/90108445
comment on: http://stackoverflow.com/q/51413834
type: Comment
type: QuestionComment
has text: To update with pip, you need to explicitly use the `--upgrade` flag (with pip install), otherwise it keeps whatever version you had before, if there was a version installed
score: 0

http://stackoverflow.com/a/51350886
has body: This code is for windows file system, i didnt check the unlink part(which is correct, my assumption ): code explain in the code comments. btw 24 * 3600 == 86400 ( 24 hours in seconds) import os import time import win32file import win32con from datetime import datetime #convert float to datetime obj, current time current_time = datetime.strptime(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())),'%Y-%m-%d %H:%M:%S') for f in os.listdir(): #file's time to datetime object creation_time = datetime.strptime(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(os.path.getctime(f))),'%Y-%m-%d %H:%M:%S') #subtract both the time --&gt;timedelta object z= current_time - creation_time #get windows attribute for the file file_flag = win32file.GetFileAttributesW(f) #check the attribute value for files in windows, for hidden files the attribute should be '2' is_hidden = file_flag &amp; win32con.FILE_ATTRIBUTE_HIDDEN if ((z.seconds &gt;= 86400) and (is_hidden != 2)): os.unlink(f) print('{} removed'.format(f)) windows file system code reference : link
type: Answer
has comment: http://stackoverflow.com/comment/89684969
has comment: http://stackoverflow.com/comment/89674528
has comment: http://stackoverflow.com/comment/89674579
has comment: http://stackoverflow.com/comment/89674596
answers question: http://stackoverflow.com/q/51350288
score: 0

http://stackoverflow.com/q/51330103
has comment: http://stackoverflow.com/comment/89636816
tagged with: python
score: 2
has title: Python from two methods got different result
answer count: 0
has body: Every day, I spend time looking inside deeper of 2 different method written in a Python class. The first one uses vectors, the second one is a stepper and computes the value each time ... but it is identically here the class. class LeapFrog(Multistep): ''' perform the solution of a SODE using 2 step ''' solved = False um1 = 0.0 stepper_start = True def __init__(self, dydt : Rhs, filename: str=None, save: bool= True ): self.save = save self.file = filename super().__init__(dydt) def solve(self): ''' Perform the leap-frog (mid point scheme) ''' self.time , self.u = self.dydt.createArray() # start-up the method k1 = self.dydt.f(self.time[0],self.u[0]) k2 = self.dydt.f(self.time[0]+ self.dt , self.u[0]+ self.dt*k1 ) self.u[1] = self.u[0] + self.dt/2.*(k1+k2) for i in range(1,len(self.time)-1): self.u[i+1] = self.u[i-1] + 2. * self.dt * self.dydt.f(self.time[i],self.u[i]) if self.save: return self.time,self.u LeapFrog.solved = True @classmethod def step(cls ,func , t : np.float , u : np.float , dt ): def f(ti,ui): return np.array([function(ti,ui) for function in func]) # start-up the method if LeapFrog.stepper_start == True: LeapFrog.um1 = u.copy() u = rungekutta.RK2.Heun.step(func,t,u,dt) LeapFrog.stepper_start = False #yield unext = LeapFrog.um1 + 2. * dt * f(t,u) LeapFrog.um1 = u return unext EDIT in both case I use dt = 2/100 Sorry !! I forgot to sayd that the iterative method is called as follow : dt = 2/100 t,u = t0,u0 with open('LeapFrog_p1.dat', 'w') as f: while True: f.write('%10.4f %14.10f \n' %(t, u[0]) ) u = multistep.LeapFrog.step(func0,t,u,dt) t += dt if t &gt;= tf: break lft = np.genfromtxt('LeapFrog_p1.dat',usecols=(0,)) lfu = np.genfromtxt('LeapFrog_p1.dat',usecols=(1,)) EDIT @Iguananaut thank you for your hint ! t0 =0 tf = 2.0 u0 = np.exp(-5) Runge Kutta is another class it's stepper is : @classmethod def step(cls,func , t : np.float , u : np.float , dt ): def f(ti,ui): return np.array([function(ti,ui) for function in func]) k1 = f(t,u) k2 = f(t+dt , u …
tagged with: differential-equations
upvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/89636701
has comment: http://stackoverflow.com/comment/89636037
has comment: http://stackoverflow.com/comment/89636749
downvote count: 0
has comment: http://stackoverflow.com/comment/89636854
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/51459221
downvote count: 0
type: Question
linked to: http://stackoverflow.com/q/29958999
upvote count: 2
tagged with: dynamic-programming
has answer: http://stackoverflow.com/a/70981970
has answer: http://stackoverflow.com/a/64842683
tagged with: palindrome
favorite count: 0
has answer: http://stackoverflow.com/a/72849387
has answer: http://stackoverflow.com/a/72335602
has body: Here is the algorithm for finding longest palindromic substring given a string s using bottom-up dynamic programming. So the algorithm explores all possible length j substring and checks whether it is a valid palindrome for j in 1 to n. The resulting time and space complexity is O(n^2). def longestPalindrome(s): n = len(s) if n &lt; 2: return s P = [[False for _ in range(n)] for _ in range(n)] longest = s[0] # j is the length of palindrome for j in range(1, n+1): for i in range(n-j+1): # if length is less than 3, checking s[i] == s[i+j-1] is sufficient P[i][i+j-1] = s[i] == s[i+j-1] and (j &lt; 3 or P[i+1][i+j-2]) if P[i][i+j-1] and j &gt; len(longest): longest = s[i:i+j] return longest I am trying to implement the same algorithm in top-down approach with memoization. Question: Is it possible to convert this algorithm to top-down approach? There are many questions about longest palindromic substring, but they are mostly using this bottom-up approach. The answer in https://stackoverflow.com/a/29959104/6217326 seems to be the closest to what I have in mind. But the answer seems to be using different algorithm from this one (and much slower).
has answer: http://stackoverflow.com/a/53620100
answer count: 5
type: UnansweredQuestion
tagged with: memoization
tagged with: python
score: 2
has title: Longest palindromic substring top down dynamic programming

http://stackoverflow.com/a/51346100
has body: The functions in your class all have wrong indentation. Try this - import hashlib class Block: def __init__(self, index, timestamp, data, previous= ''): self.index = index self.timestamp = timestamp self.data= data self.previous = previous self.hash = '' def calculateHash(self): return hashlib.sha256(self.index + self.previous + self.timestamp+ (self.data).__str__() class BlockChain: def __init__(self): self.chain= [self.createGenesisBlock()] def createGenesisBlock(self): return block(0, "01/01/2017", "Genesis Block", "0") def getLatestBlock(self): return self.chain[len(self.chain)-1] def addBlock(self, newBlock): newBlock.previous = self.getLatestBlock().hash newBlock.hash= newBlock.calculateHash() self.chain.push(newBlock) korCoin = BlockChain() korCoin.addBlock(block(1, "10/07/2017", 4)) korCoin.addBlock(block(2, "12/07/2017", 40)) if __name__ == "__main__": print(korCoin) Follow python's indentation here
type: Answer
upvote count: 0
answers question: http://stackoverflow.com/q/51346021
has comment: http://stackoverflow.com/comment/89665385
score: -1
has comment: http://stackoverflow.com/comment/89667110
downvote count: 1
has comment: http://stackoverflow.com/comment/89667284

http://stackoverflow.com/a/51424755
answers question: http://stackoverflow.com/q/51424648
downvote count: 0
type: Answer
upvote count: 1
has body: Try use pd.Series.map(). A toy example here: s = s.map({"Private": "Private-changed", "Public": "Public_changed", "?": "What is this"}) s This gives you: 0 Private-changed 1 Public_changed 2 What is this
score: 1

http://stackoverflow.com/comment/89785787
score: 0
has text: To answer OP's question, ````x[x['A']>3]['A'] = 33```` does not modify the dataframe inplace; rather it is making a copy of a slice of the dataframe and modifying the copy. Use ````.loc```` and have your indices (row and column) within the same square bracket to modify the dataframe itself.
type: Comment
comment on: http://stackoverflow.com/q/51407175
type: QuestionComment

http://stackoverflow.com/a/51449277
type: AcceptedAnswer
downvote count: 0
score: 6
accepted answer of: http://stackoverflow.com/q/51448897
answers question: http://stackoverflow.com/q/51448897
type: Answer
upvote count: 6
has body: "As per my understanding, the NLL is calculated between two probability values?" No, NLL is not calculated between two probability values. As per the pytorch docs (See shape section), It is usually used to implement cross entropy loss. It takes input which is expected to be log-probability and is of size (N, C) when N is data size and C is the number of classes. Target is a long tensor of size (N,) which tells the true class of the sample. Since in your case, target for sure is not the true class, you might have to implement your own version of loss and you may not be able to use NLLLoss. If you add more details about what loss you want to code up, I can help/explain more on how to do that (if possible by using existing function in torch).

http://stackoverflow.com/a/51474914
answers question: http://stackoverflow.com/q/51474661
upvote count: 1
downvote count: 0
type: Answer
has body: You could put the database connection parameters in an external file, eg connections_settings.ini [credentials] host=localhost dbname=test username=me password=secret and then read them with the configparser module, and create the connection url with string interpolation import configparser config = configparser.ConfigParser('connection_settings')['credentials'] connection_settings = { 'host': config['host'], 'dbname': config['dbname'], 'user': config['username'], 'password': config['password'] } SQLALCHEMY_DATABASE_URI = f'postgresql+psycopg2://{host}/{dbname}'
score: 1

http://stackoverflow.com/q/51426379
upvote count: 1
tagged with: tensorflow
type: Question
has body: I am trying to calculate the power consumption of a tensorRT script written in Python. With CUDA there is nvprof cuda_script, but couldn't find something like that for my Python script. Is there something similar for Python? How are people calculating the power consumption of p100/v100? Something like this for Nvidia GPUs - How to profile CPU usage of a Python script?
answer count: 2
tagged with: tensorrt
downvote count: 0
has answer: http://stackoverflow.com/a/51548381
has answer: http://stackoverflow.com/a/75135236
favorite count: 0
has title: TensorFlow: Determine tensorRT power consumption with Python
linked to: http://stackoverflow.com/q/49197916
tagged with: gpu
tagged with: python
type: UnansweredQuestion
score: 1

http://stackoverflow.com/a/51439629
downvote count: 0
score: 10
has body: You could also use the numpy function np.tril_indices: arr = np.array([10,20,40,46,33,14,12,46,52,30,59,18,11,22,30,2,11,58,22,72,12]) n = int(np.sqrt(len(arr)*2))+1 Generate zeros matrix and fill the lower part with your values: idx = np.tril_indices(n, k=-1, m=n) matrix = np.zeros((n,n)).astype(int) matrix[idx] = arr array([[ 0, 0, 0, 0, 0, 0, 0], [10, 0, 0, 0, 0, 0, 0], [20, 40, 0, 0, 0, 0, 0], [46, 33, 14, 0, 0, 0, 0], [12, 46, 52, 30, 0, 0, 0], [59, 18, 11, 22, 30, 0, 0], [ 2, 11, 58, 22, 72, 12, 0]])
upvote count: 10
type: Answer
answers question: http://stackoverflow.com/q/51439271

http://stackoverflow.com/a/51335458
upvote count: 1
has comment: http://stackoverflow.com/comment/89646018
has comment: http://stackoverflow.com/comment/89646225
has body: First and foremost please read about Floating Point Arithmetic: Issues and Limitations Maybe that was the reason why you ask, not clear. However, I suggest to save each part as an integer, e.g. main_version_number = 1151 minor_version_number = 1 sub_version_number = 0 You could maybe have a data structure with those fields (a Version class maybe?) with appropriate methods. Do not rely on floating point arithmetic.
answers question: http://stackoverflow.com/q/51335411
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/comment/89842285
score: 0
type: Comment
has text: Sorry, Francisco, I cannot see easy way to write you feedback. I have modified fit function : https://imgur.com/gallery/pDeGSu7 .The fit is still quite poor.
comment on: http://stackoverflow.com/a/51415993
type: AnswerComment

http://stackoverflow.com/q/51455781
has body: I am pretty new to Python in general and recently started messing with the Google Cloud environment, specifically with the Natural Language API. One thing that I just cant grasp is how do I make use of this environment, running scripts that use this API or any API from my local PC in this case my Anaconda Spyder environment? I have my project setup, but from there I am not exactly sure, which steps are necessary. Do I have to include the authentication somehow in the Script inside Spyder? Some insights would be really helpful.
tagged with: python
favorite count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 1
score: 1
has answer: http://stackoverflow.com/a/53506151
type: Question
has title: How do I use Google Cloud API's via Anaconda Spyder?
answer count: 2
tagged with: google-cloud-platform
has answer: http://stackoverflow.com/a/51455824

http://stackoverflow.com/q/51331133
tagged with: python
has comment: http://stackoverflow.com/comment/89639831
score: 0
has comment: http://stackoverflow.com/comment/89638783
has comment: http://stackoverflow.com/comment/89638727
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89638071
answer count: 1
has title: getting error "modulenotfounderror: No module named 'google'" but when trying to install through command prompt it says requirement already satisfied
has body: Pretty self-explanatory, trying to do a small web scraper from a google search, but when trying to import, using "from google import search" I get the error: ModuleNotFoundError: No module named 'google'. When trying to install google again from the command prompt using "pip install google" I get the error: Requirement already satisfied: google in c:\users\dsimard\python\lib\site-packages (2.0.1) Requirement already satisfied: beautifulsoup4 in c:\users\dsimard\python\lib\site-packages (from google) (4.6.0) I am writing this program in eclipse.
has comment: http://stackoverflow.com/comment/89638886
has comment: http://stackoverflow.com/comment/89637967
type: UnansweredQuestion
tagged with: eclipse
has answer: http://stackoverflow.com/a/51573332
favorite count: 0
type: Question

http://stackoverflow.com/q/51358618
has answer: http://stackoverflow.com/a/51358883
linked to: http://stackoverflow.com/q/4383571
has title: Error: pytesseract module is not found
score: 0
answer count: 1
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: python-tesseract
has body: When I am trying to install pytesseract in anaconda prompt. It says "package already installed". But when I run command "import pytesseract " error show "module is not found"
type: Question

http://stackoverflow.com/comment/89888710
score: 0
type: Comment
type: QuestionComment
has text: Thanks for responding, a dict would always be ok! The answer was given, so no need to respond
comment on: http://stackoverflow.com/q/51457500

http://stackoverflow.com/a/70782758
has body: I was working on a project which used the GPU instead of CPU. I did some Googling and found out that the best way to do this is by using the Anaconda. As you can see I ended up here due to errors I faced. All the answers in this tread is insightful but the recent working answer that has worked for me is a combination previous answers. I'll try to sum up one simple answer and step that can be followed for developers like me to solve this issue. Change the path in system settings> advanced system settings > Environment Variables> System variables > path > edit > add "C:ProgramData\Anaconda3\Scripts" Make sure the python is 3.4+ Open CMD in admin mode, change directory to the anaconda then type conda update conda if there is SSL error type conda config --set ssl_verify no or conda config --set ssl_verify false Then type conda update anaconda-navigator Then to avoid HTTP and SSL error. Copy the following files: libcrypto-1_1-x64.* (.dll and .pdb files) libssl-1_1-x64.* (.dll and .pdb files) From C:ProgramData\Anaconda3\Library\bin to C:ProgramData\Anaconda3\DLLs. Now open Anaconda prompt(Anaconda3) type(one by one) pip install PySide2 pip uninstall pyqt pip uninstall PyQt5 6.Then while in Anaconda3 type pip install pyqt test if you can open anaconda-navigator in anaconda prompt. (if it works you're almost there) Close everything, Fire up the CMD in Admin mode and type pip install PyQt5. Open anaconda-navigator in CMD. if It is not working properly, repeat the process after step 4. I'm not a very pro coder. but this is the process that worked for me! Good luck!!
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51435579

http://stackoverflow.com/q/51338573
has answer: http://stackoverflow.com/a/51338772
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/51338772
type: Question
has comment: http://stackoverflow.com/comment/89653440
downvote count: 0
has comment: http://stackoverflow.com/comment/89651893
has body: Let's say I have a list of lists my_list. I want to sort my_list using some operation on each element of my_list which is also a list (let us call them inner_list). def fun(inner_list): # do some calculation on inner list time.sleep(1) # simulate expensive operation return cost sorted_list = sorted(my_list, key=lambda inner_list: fun(inner_list)) Since fun is expensive in terms of time, is there any way to calculate the cost using fun in parallel? If yes, would threading be a good choice? AFAIK due to GIL threading can't actually do stuff in parallel. However, if the expensive nature is due to iterating over items of a long list, can threading help? What other ways can I speed this up? Note: I am limited to python 2.7. Edit : Added details Here is the exact code. fun is an abstraction for get_delay. graph is a networkx graph with each link (u, v) having some value for delay. Basically, I am iterating over all edges on the path and calculating the cumulative delay. The path is a list of nodes. For example if path = [1, 2, 3, 4] then the (u, v) links would be [ (1, 2) , (2, 3), (3, 4)]. def get_delay(path): return sum([float(graph.get_edge_data(u, v)['delay']) for u, v in zip(path[:-1], path[1:])])
tagged with: python-2.7
has title: Python sort using key : possible to parallelize?
answer count: 1
has comment: http://stackoverflow.com/comment/89652051
favorite count: 0
has comment: http://stackoverflow.com/comment/89651960
has comment: http://stackoverflow.com/comment/89651719
tagged with: multithreading
has comment: http://stackoverflow.com/comment/89651991
tagged with: python
has comment: http://stackoverflow.com/comment/89652040
tagged with: parallel-processing
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89651985

http://stackoverflow.com/comment/89896046
comment on: http://stackoverflow.com/q/51463507
type: Comment
type: QuestionComment
score: 0
has text: do you need to keep returning `Person` objects or would you also be fine with returning some kind of serialised version of a `Person`?

http://stackoverflow.com/comment/89843118
type: AnswerComment
score: 0
type: Comment
has text: I tried your code as it is and i get an error which looks something like this: **File "energychannelconversion.py", line 17, in get_energy_details df = pd.DataFrame(data_list, columns=column_names, index=row_names) ValueError: Shape of passed values is (5, 8), indices imply (5, 7)**
comment on: http://stackoverflow.com/a/51409186

http://stackoverflow.com/comment/89819277
has text: Here is my code: with open(file, 'U') as f: line=f.read() while not '" f3="' in line: line=line.replace('" f4="', '" f3="NA" f4="') else: line=line.replace('" f3="', '" f3="') with open(file, "w") as f: f.write(line)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51423317

http://stackoverflow.com/q/51329974
type: AnsweredQuestion
tagged with: recurrent-neural-network
tagged with: tensorflow
has answer: http://stackoverflow.com/a/51340461
type: Question
answer count: 1
score: 0
tagged with: deep-learning
has body: I have an RNN that is stacked on top of a CNN. The CNN was created and trained separately. To clarify things, let's suppose the CNN takes input in the form of a [BATCH SIZE, H, W, C] placeholder (H = height, W = width, C = number of channels). Now, when stacked on top of the RNN, the overall input to the combined network will have the shape: [BATCH SIZE, TIME SEQUENCE, H, W, C], i.e. each sample in the minibatch consists of TIME_SEQUENCE many images. Moreover, the time sequences are variable in length. There is a separate placeholder called sequence_lengths with shape [BATCH SIZE] that contains scalar values corresponding to the length of each sample in the minibatch. The value of TIME SEQUENCE corresponds to the maximum possible time sequence length, and for samples with smaller lengths, the remaining values are padded with zeros. What I want to do I want to accumulate the output from the CNN in a tensor of shape [BATCH SIZE, TIME SEQUENCE, 1] (the last dimension just contains the final score output by the CNN for each time sample for each batch element) so that I can forward this entire chunk of information to the RNN that is stacked on top of the CNN. The tricky thing is, I also want to be able to back-propagate the error from the RNN to the CNN (the CNN is already pre-trained, but I would like to fine-tune the weights a bit), so I have to stay inside the graph, i.e. I can't make any calls to session.run(). Option A: The easiest way would be to just reshape the overall network input tensor to [BATCH SIZE * TIME SEQUENCE, H, W, C]. The problem with this is that BATCH SIZE * TIME SEQUENCE may be as large as 2000, so I'm bound to run out of memory when trying to feed a batch that big into my CNN. And the batch size is too large for training anyway. Also, a lot of sequences are just padded zeros, and it'd be a waste of computation. Option B: Use the tf.while_loop. My idea was to treat all the images along the time axis for a single minibatch element as a minibatch fo…
accepted answer: http://stackoverflow.com/a/51340461
has title: Accumulating output from a graph using tf.while_loop
tagged with: python

http://stackoverflow.com/q/51463912
answer count: 1
has body: I am trying to get a query into a variable called results, in which I query the database to find the books with a title like the input from the search bar received from a post method. The query I am running is as follows: results = db.execute("SELECT * FROM books WHERE title LIKE (%:search%)", {"search": search}).fetchall(); With the above query, I get the following error: sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) syntax error at or near "%". This works as expected if I remove the %, or if I manually give the LIKE a parameter (eg: LIKE ('%the%')), but this does not really give back any results unless the search is exactly as one of the book titles in the database, and it defeats the purpose of using variable substitution by hard coding the parameters. I am also wondering if it's possible to use ILIKE for case insensitive when querying with SQLAlchemy. I am aware that I could use Object Relational Mapping, and use different functions such as the filter function and whatnot, but for this assignment we are meant to not use ORM and use simple queries. Any suggestions?
favorite count: 0
has title: CS50: LIKE operator, variable substitution with % expansion
tagged with: python
type: AnsweredQuestion
score: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/51464790
tagged with: sqlalchemy
type: Question
has answer: http://stackoverflow.com/a/51464790
tagged with: postgresql
tagged with: cs50
upvote count: 3

http://stackoverflow.com/comment/89845520
type: Comment
has text: i need to find it since it is installed not to installed it again.Am i not saying it right?
comment on: http://stackoverflow.com/a/51437753
type: AnswerComment
score: 0

http://stackoverflow.com/q/51351359
tagged with: http://stackoverflow.com/tag/html
tagged with: python
possible better answer: http://stackoverflow.com/a/65642126
accepted answer: http://stackoverflow.com/a/51351398
favorite count: 0
has body: So I passed a render with directory as an argument in my views.py. Something like this: def foo(request): return render(request, 'webapp/foo.html', {'key': ['one', 'two', 'three']}) Now i want to use Jinja in my HTML file to get exactly one element from directory value, let's say first. All I know for know is how to get all elements with for loop: {% block content %} {% for val in key %} &lt;p&gt; {{ val }} &lt;/p&gt; {% endfor %} {% endblock %} My question is if is there something like this? {% block content %} &lt;p&gt; {{ key[0] }} &lt;/p&gt; {% endblock %}
tagged with: django
has answer: http://stackoverflow.com/a/65642126
tagged with: jinja2
has answer: http://stackoverflow.com/a/51351398
type: AnsweredQuestion
downvote count: 0
score: 7
type: Question
answer count: 2
upvote count: 7
has title: How to get exactly one element from list in Jinja?

http://stackoverflow.com/q/51396525
score: 1
has title: How to create a unique reference for the result each time?
has comment: http://stackoverflow.com/comment/89764259
accepted answer: http://stackoverflow.com/a/51397556
type: Question
has body: In general, I make a page on the site. The meaning is this: a person comes in, loads an xml file, selects several parameters, and outputs the result. I did not find how to handle the xml file at once. So I upload its file with the parameters to the database, and then redirect us to the page with the result. Everything works fine, but there is a problem. I have not figured out how to create a unique link for the result each time. Now I have one link for the results and it just shows the last one ... views.py of uploader def upload_file(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('lessons:index') else: form = DocumentForm() return render(request, 'templates/upload/upload.html', {'form': form}) downloader views.py of handler def lessons_view(request): a = keker() return render(request, 'templates/lessons/ocenki.html', {'ocenki': a}) keker if handler function
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89764855
has comment: http://stackoverflow.com/comment/89764105
has answer: http://stackoverflow.com/a/51397556
favorite count: 0
tagged with: django
upvote count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/51351439
downvote count: 0
has body: I am trying to parse some coordinates using gpxpy and this project, but when trying to import smoo1 from oceans library I encounter this error: from pandas import rolling_mean ImportError: cannot import name 'rolling_mean' I have tried to read about this error and fix it, but as far as I understood the library tries to import a function that was depreciated. I am not sure about what to do in a situation like this one. I am using python 3.6.
has title: Pandas: Cannot import rolling_mean
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51351459
accepted answer: http://stackoverflow.com/a/51351459
upvote count: 2
tagged with: pandas
answer count: 1
tagged with: gpx
favorite count: 0
tagged with: python
score: 2

nlp
tags question: http://stackoverflow.com/q/51377870
tags question: http://stackoverflow.com/q/51412826
tags question: http://stackoverflow.com/q/51369210
tags question: http://stackoverflow.com/q/51369041
tags question: http://stackoverflow.com/q/51346918
tags question: http://stackoverflow.com/q/51430249
tags question: http://stackoverflow.com/q/51406066
tags question: http://stackoverflow.com/q/51345806
tags question: http://stackoverflow.com/q/51442688
tags question: http://stackoverflow.com/q/51431112
tags question: http://stackoverflow.com/q/51326704
tags question: http://stackoverflow.com/q/51359808
tags question: http://stackoverflow.com/q/51447720
tags question: http://stackoverflow.com/q/51432641
tags question: http://stackoverflow.com/q/51371356
tags question: http://stackoverflow.com/q/51353593
tags question: http://stackoverflow.com/q/51454759
tags question: http://stackoverflow.com/q/51474407
tag name: nlp
tags question: http://stackoverflow.com/q/51369858
tags question: http://stackoverflow.com/q/51342763
type: Tag
tags question: http://stackoverflow.com/q/51482502
tags question: http://stackoverflow.com/q/51385662
tags question: http://stackoverflow.com/q/51400498
tags question: http://stackoverflow.com/q/51426107
tags question: http://stackoverflow.com/q/51335911
tags question: http://stackoverflow.com/q/51412095
tags question: http://stackoverflow.com/q/51343373
tags question: http://stackoverflow.com/q/51371008
tags question: http://stackoverflow.com/q/51390568

http://stackoverflow.com/a/51358670
upvote count: 6
type: AcceptedAnswer
type: Answer
score: 6
accepted answer of: http://stackoverflow.com/q/51358324
has body: You can use modulus to get all the angles in the range 0 - 360. import numpy as np v = [ [-3, 4], [-2, -5], [2, 6], [3, -10], ] v = np.array(v) inv = np.degrees(np.arctan2(*v.T[::-1])) % 360.0 print(inv) output [ 126.86989765 248.19859051 71.56505118 286.69924423]
downvote count: 0
answers question: http://stackoverflow.com/q/51358324

http://stackoverflow.com/comment/89814047
type: AnswerComment
type: Comment
has text: no problem, but beside that it woud be really helpful if you explain your code at least with some comments ;)
comment on: http://stackoverflow.com/a/51421241
score: 0

http://stackoverflow.com/comment/89900632
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51448858
has text: You can use this API: http://coverage.readthedocs.io/en/coverage-4.5.1a/api_coveragedata.html

http://stackoverflow.com/q/51328929
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51329102
accepted answer: http://stackoverflow.com/a/51329381
downvote count: 3
has comment: http://stackoverflow.com/comment/89633781
score: -3
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/51329429
has comment: http://stackoverflow.com/comment/89633799
tagged with: rainbowtable
answer count: 6
has answer: http://stackoverflow.com/a/51329656
possible better answer: http://stackoverflow.com/a/51329429
has answer: http://stackoverflow.com/a/51329077
has comment: http://stackoverflow.com/comment/89634087
has comment: http://stackoverflow.com/comment/89634068
has answer: http://stackoverflow.com/a/51329381
favorite count: 0
tagged with: hex
has comment: http://stackoverflow.com/comment/89633690
has title: python intelligent hexadecimal numbers generator
tagged with: python
has answer: http://stackoverflow.com/a/51329100
has body: I want to be able to generate 12 character long chain, of hexadecimal, BUT with no more than 2 identical numbers duplicate in the chain: 00 and not 000 Because, I know how to generate ALL possibilites, including 00000000000 to FFFFFFFFFFF, but I know that I won't use all those values, and because the size of the file generated with ALL possibilities is many GB long, I want to reduce the size by avoiding the not useful generated chains. So my goal is to have results like 00A300BF8911 and not like 000300BF8911 Could you please help me to do so? Many thanks in advance!

http://stackoverflow.com/q/51457267
tagged with: function
score: 0
has body: I have this Python function: def main(n,x): g=0 for i in range(1,n): g+=((-1)^i)*(x^(2*i+1))/(2*i+1) return g print main(3,2) and the output is -6, when I think it should be 86/15. Where is my mistake? I want to find the n-value of x-(x^3)/3+(x^5)/5+...
tagged with: python
tagged with: output
has comment: http://stackoverflow.com/comment/89884012
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89883994
has answer: http://stackoverflow.com/a/51457365
has title: Python function-unexpected output
possible better answer: http://stackoverflow.com/a/51457344
type: Question
has answer: http://stackoverflow.com/a/51457344
answer count: 2
accepted answer: http://stackoverflow.com/a/51457365

http://stackoverflow.com/q/51440490
favorite count: 0
accepted answer: http://stackoverflow.com/a/51440803
upvote count: 1
tagged with: python
answer count: 1
tagged with: tensorflow
has answer: http://stackoverflow.com/a/51440803
has comment: http://stackoverflow.com/comment/89851017
downvote count: 0
has body: I successfully installed Tensorflow with Virtualenv. However, when I run it, I get a warning about the fact that AVX2 FMA is not used: (tensorflow) MacBook-Pro-van-Niels:Tensorflow NielsRogge$ python Python 2.7.10 (default, Jul 15 2017, 17:16:57) [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import tensorflow as tf &gt;&gt;&gt; hello = tf.constant('Hello, TensorFlow!') &gt;&gt;&gt; sess = tf.Session() 2018-07-20 12:00:37.904867: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA &gt;&gt;&gt; print(sess.run(hello)) Hello, TensorFlow! I probably have to run the following command in my virtual environment: pip install --ignore-installed --upgrade "Download URL" However, I'm unsure about the download URL I have to use from this website. As you can see in the code snippet above, I have Python 2.7.10 and GCC 4.2.1. I have a Macbook Pro with the following specs. My OS is Mac OS High Sierra 10.13. Is it a problem that I have Python version 2.7.10, whereas on the website Python 2.7.15 is required?
has title: Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
type: Question
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/89660201
has text: Is it possible to pull this function out and run it in a script that just constructs `params` statically and calls this function, then profile that? Because there's clearly other stuff going on in that profile dump that's unrelated here. Which _shouldn't_ be preventing us from seeing how the 1.461s per `loc_procs` breaks down, but it does seem to be anyway.
comment on: http://stackoverflow.com/q/51343403
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/51377806
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/89727328
has comment: http://stackoverflow.com/comment/89758501
has answer: http://stackoverflow.com/a/51378066
score: 0
tagged with: compare
has title: How can i check the pattern of data set is similar
type: UnansweredQuestion
tagged with: similarity
tagged with: python
has comment: http://stackoverflow.com/comment/89756024
has body: I am using python and i would like to check is the pattern of a group of data set compare with one specific data-set is similar, e.g. [1,11,21,31,41] is similar to [1,10,24,32,44] and i would like to set some threshold to identify is that similar, for example i would like to set the similarity percentage at 90%. Please help, i have stuck at this programming for a week
has comment: http://stackoverflow.com/comment/89727317
has answer: http://stackoverflow.com/a/51378123

http://stackoverflow.com/comment/100606860
type: Comment
has text: Hi, please tell me if you has a answer, I have the same problem.
comment on: http://stackoverflow.com/q/51369835
score: 0
type: QuestionComment

http://stackoverflow.com/q/51408990
upvote count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/30357276
type: Question
tagged with: dataframe
score: 0
has comment: http://stackoverflow.com/comment/89789706
tagged with: pandas
has title: How to fill column' value with another column and keep existing?
answer count: 1
has comment: http://stackoverflow.com/comment/89789685
favorite count: 0
duplicate of: http://stackoverflow.com/q/30357276
has body: I have this dataframe with two column['c1','c2'], and I want to fill c2 with its corresponding c1 if exist, also if c1 already have a value keep it don't change it with c2. Here is an example: input c1 c2 HP_0003470 HP_8362789 HP_0093723 MP_0000231 MP_0000231 output c1 c2 HP_0003470 HP_8362789 HP_0093723 MP_0000231 MP_0000231 MP_0000231 MP_0000231 It's look easy, but I'm beginner in python :( Any help please.
has comment: http://stackoverflow.com/comment/89789797
has comment: http://stackoverflow.com/comment/89789641
tagged with: python
has comment: http://stackoverflow.com/comment/89789396
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51409150
accepted answer: http://stackoverflow.com/a/51409150

http://stackoverflow.com/q/51326512
tagged with: python
upvote count: 0
has comment: http://stackoverflow.com/comment/89636735
tagged with: python-pptx
tagged with: powerpoint
accepted answer: http://stackoverflow.com/a/51326603
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89628128
has title: Using a powerpoint file with existing template
has answer: http://stackoverflow.com/a/51326603
has body: I am working on generating a powerpoint file using python-pptx. How do I make the file maintain the existing template on the file without overwriting the template on the file.
has comment: http://stackoverflow.com/comment/89631369
downvote count: 2
score: -2
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/89647744
type: Comment
has text: just: WOW. I joined yesterday and gave it a 20% or so chance and 12 hours later I have something to work with. THANK YOU. I'll try and tweak it a little more and get back to you
comment on: http://stackoverflow.com/a/51333816
type: AnswerComment
score: 0

http://stackoverflow.com/a/51351013
has comment: http://stackoverflow.com/comment/89675666
has comment: http://stackoverflow.com/comment/91079869
downvote count: 0
answers question: http://stackoverflow.com/q/51350945
has comment: http://stackoverflow.com/comment/89675265
has comment: http://stackoverflow.com/comment/89676391
type: Answer
has body: from decimal import Decimal print('%.8f' % Decimal(10**-8)) Outputs: 0.00000001 To specify decimal places dynamically you can use this: from decimal import Decimal power = 10 print('%.*f' % (power, Decimal(10**-power))) Prints: 0.0000000001
score: 3
upvote count: 3

http://stackoverflow.com/q/51379017
has comment: http://stackoverflow.com/comment/89729805
type: AnsweredQuestion
has body: I have two classes: Vehicle() and Route_plan() as follows: class Vehicle(): def __init__(self,unique_id): self.capacity = 9000 self.unique_id = unique_id self.routes = [] class Plan(): def assignment(self): # create a vehicle as 'this_vehicle' with id = 0 from class Vehicle() this_vehicle = Vehicle(0) this_vehicle.routes.append(5) this_vehicle.routes.append(8) #run the route_plan process to assgin the specfic routes to vehicle 0 Plan().assignment() output: [5,8] Now, I have another drawing function to try to plot the routes of each vehicle (in this case the vehicle 0): def Draw(): # if I have 10 vehicles (with id = 0,1,....9), how do I access them and their updated routes? # Is there a simple way to update the vehicle's own variable (routes) directly using the vehicle ID and have it being flexibly called by any other classes and functions? # plotting process
has comment: http://stackoverflow.com/comment/89730062
type: Question
has comment: http://stackoverflow.com/comment/89729492
tagged with: object
has answer: http://stackoverflow.com/a/51379153
has comment: http://stackoverflow.com/comment/89729716
tagged with: class
possible better answer: http://stackoverflow.com/a/51379605
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/51379153
has answer: http://stackoverflow.com/a/51379605
has title: Python - access Class_A object created and processed in a function of Class_B
has comment: http://stackoverflow.com/comment/89729688
has comment: http://stackoverflow.com/comment/89729562
tagged with: python
has comment: http://stackoverflow.com/comment/89729701

http://stackoverflow.com/q/51384734
has answer: http://stackoverflow.com/a/51384843
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51385085
has body: My dataframe somewhat looks like this: df: Col1 Col2 A 123 B 154 A 123 C 199 A 201 B 199 C 123 If , I group by Col1, then I want to display all groups sharing common value of Col2. The output currently looks like: 123 [A,C,A] 199 [B,C] But, it should always remove duplicate 'col1' from the list if it has any. Hence, the output should look like: 123 [A,C] 199 [B,C] Here the duplicate value A displayed only once as duplicate is removed.
downvote count: 1
type: Question
tagged with: dataframe
score: -1
answer count: 2
tagged with: pandas-groupby
tagged with: pandas
upvote count: 0
has title: How to return groups sharing comman values in Pandas dataframe?
favorite count: 0

http://stackoverflow.com/q/51459580
has body: I am new to python and SO. I want to multiply each element of lists in a list of lists to another list lying in the same list of lists and compare it with a reference value. This will be more clear with an example: for L = [[1,2,3,4,5,10],[3,2,4,1,5,10]] ##there can be more than 2 lists in this list of lists I want only those pairs whose product results in 10. Out: L = [[1,10],[2,5]] Edit: I prefer a method without any imports, since I am doing this for building logic and my editor doesn't contain any modules to import. Also, if there are more than 2 lists in a list of lists For eg. there are 3 Lists in a list of lists: then I want triplets for that sake. ANd if 4 lists then I need quadruples. Here's my code attempt as requested. N = [] J = [] F = [] Z = [] S = [] O = [] num = input("Enter no. of elements in list") print ('Enter numbers') prod = 1 for i in range(int(num)): n = input("num :") N.append(int(n)) for x in N: prod = prod*x print (prod) k = int(input("Enter no. of splits:")) ##d = [[] for x in xrange(k)] ##var_dict = [] for o in range(1,prod+1): if prod%o == 0: J.append(o) print (J) for g in range(k): O.append(J*(k-1)) print (O) for a in range(len(O)): for b in range(len(O)): if O[i]*O[i+1] == prod: Z.extend(O) ##Z = [[a, b] for a in J for b in F if a*b == prod] ##imp print (Z) for e in Z: if e not in S and sorted(e) not in S: S.append(e) print (S)
has comment: http://stackoverflow.com/comment/89888746
has answer: http://stackoverflow.com/a/51459687
answer count: 2
favorite count: 0
possible better answer: http://stackoverflow.com/a/51459687
has title: How to multiply two sublists within the same list?
has answer: http://stackoverflow.com/a/51460555
downvote count: 2
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89888499
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/89890573
type: Question
accepted answer: http://stackoverflow.com/a/51460555
has comment: http://stackoverflow.com/comment/89888642
score: -1
has comment: http://stackoverflow.com/comment/89888564

http://stackoverflow.com/comment/89630384
comment on: http://stackoverflow.com/q/51327206
has text: Sorry then for misunderstanding and thanks for your answer and help
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89754048
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51388829
score: 0
has text: Do you know of a library that supports a few different string formats being passed in, or to some extent I would always need to define the directives ?

http://stackoverflow.com/a/51461207
score: 1
has body: Well, what is the problem with str(True) being 'True'? That's quite the expected. Now, if you convert boolean to integer, it's obvious that the result must be a number. And, naturally, not True evaluates to False. That is str(False), then: 'False'. About the bool() function, it's supposed to return True for anything that is not empty, zero, None or False. So any string that is not '' fits this and returns True. See more: https://docs.python.org/3/library/stdtypes.html#truth
has comment: http://stackoverflow.com/comment/89891667
upvote count: 1
answers question: http://stackoverflow.com/q/51461177
type: Answer
downvote count: 0

http://stackoverflow.com/comment/89789771
score: 0
has text: sharing what you did will help us help you :)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51408987

http://stackoverflow.com/comment/89671763
score: 0
has text: Yeah after I messed around a bit with the other answer, (and went to bed) I realized that doing it this way wouldn't have access to the data from the main program, and that somewhat defeats the point. I suppose I could output the variables to disk then read them again in any function that's called...
type: Comment
comment on: http://stackoverflow.com/a/51345469
type: AnswerComment

http://stackoverflow.com/a/52866867
score: 4
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51469451
has body: I got the same problem. And I am using Anaconda on windows 10, i.e., using Anaconda Prompt. After some searching, it is found that the twine.exe is located in the folder: C:\Users\myname\AppData\Roaming\Python\Python36\Scripts From the output provided by you, I guess the twine.exe is located in your folder: c:\users\amirh\appdata\roaming\python\python36\Scripts Hence, you can add this folder path to your environment variable PATH: System Properties -> Environment Variables -> System variables -> PATH (Edit) Then, reopen your Anaconda Prompt (or Command Prompt) and type twine upload -r pypitest dist/packagename-0.1.2.tar.gz
upvote count: 4

http://stackoverflow.com/comment/119475319
has text: @Alistair: Does this work the same way in C?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51554471
type: AnswerComment

http://stackoverflow.com/a/52492906
downvote count: 0
answers question: http://stackoverflow.com/q/51342429
type: Answer
score: 2
has body: I have not found a nice library for Python but using hachoir with subprocess is a dirty workaround. You can grab the library itself from pip, the instructions for Python 3 are here: https://hachoir.readthedocs.io/en/latest/install.html def get_media_properties(filename): result = subprocess.Popen(['hachoir-metadata', filename, '--raw', '--level=3'], stdout = subprocess.PIPE, stderr = subprocess.STDOUT) results = result.stdout.read().decode('utf-8').split('\r\n') properties = {} for item in results: if item.startswith('- duration: '): duration = item.lstrip('- duration: ') if '.' in duration: t = datetime.datetime.strptime(item.lstrip('- duration: '), '%H:%M:%S.%f') else: t = datetime.datetime.strptime(item.lstrip('- duration: '), '%H:%M:%S') seconds = (t.microsecond / 1e6) + t.second + (t.minute * 60) + (t.hour * 3600) properties['duration'] = round(seconds) if item.startswith('- width: '): properties['width'] = int(item.lstrip('- width: ')) if item.startswith('- height: '): properties['height'] = int(item.lstrip('- height: ')) return properties hachoir supports other properties as well but I am looking for just those three. For the mov files I tested it also appears to print out the creation date and modification dates. I am using a priority level of 3 so you can try playing with that to see more stuff.
upvote count: 2

http://stackoverflow.com/q/51444888
has body: This question was asked few times on stackoverflow. However, what I'm trying to do is a little bit different. I'm trying to port python to QNX. Compiling all the source files and statically linking it to a "Hello World" script using python c API works. I'm having problem with the struct module. I tried compiling struct into a shared library and placing it at the exec_prefix path specified by python. When I try to import it, It tries to load the module but it complains about unknown symbols. It says something like Unknown symbol: _PyUnicode_FormatAdvancedWriter referenced by _struct.so I get a lot of unknown symbol errors like this. I included the header and source files of all these unknown symbols and it ends up throwing other unknown symbol errors. I might be doing something completely wrong. Any ideas on how I can link them?
has title: How to statically link the python interpreter?
has comment: http://stackoverflow.com/comment/89859873
has comment: http://stackoverflow.com/comment/89859832
favorite count: 0
tagged with: python-3.x
score: 2
accepted answer: http://stackoverflow.com/a/51655464
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/89860522
type: AnsweredQuestion
tagged with: linker-errors
type: Question
has answer: http://stackoverflow.com/a/51655464
answer count: 1
downvote count: 0
tagged with: qnx-neutrino
tagged with: http://stackoverflow.com/tag/c

http://stackoverflow.com/q/51381329
possible better answer: http://stackoverflow.com/a/51382224
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51383650
has answer: http://stackoverflow.com/a/51382224
tagged with: data-generation
type: Question
has body: I followed this tutorial to create the following data generator. However, it takes too much time for training. How can I make it run faster knowing that I have already created all the data files read by the reader object? ps: The method __data_generation performs 2 disc access per iteration. import numpy as np import keras class DataGenerator(keras.utils.Sequence): """ Generates data for Keras :return: data generator object """ def __init__(self, reader, list_IDs, labels, relations_list, batch_size=32, shuffle=True): # Initialization self.reader = reader self.batch_size = batch_size self.labels = labels self.list_IDs = list_IDs self.shuffle = shuffle self.on_epoch_end() self.relations = relations_list self.data_num = 0 def __len__(self): """ Denotes the number of batches per epoch :return: int """ return int(np.floor(len(self.list_IDs) / self.batch_size)) def __getitem__(self, index): """ Generate one batch of data :param index: index of the current training item :return: tuple """ # Generate indexes of the batch indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size] # Find list of IDs list_IDs_temp = [self.list_IDs[k] for k in indexes] # Generate data X, y = self.__data_generation(list_IDs_temp) return X, y def on_epoch_end(self): """ Updates indexes after each epoch :return: """ self.indexes = np.arange(len(self.list_IDs)) if self.shuffle: np.random.shuffle(self.indexes) def __data_generation(self, list_IDs_temp): """ Generates data containing batch_size samples' :param list_IDs_temp: the list of IDs of the target batch :return: tuple """ # Initialization y = [] v_q_words = [] v_d_words = [] # Generate data for i, ID in enumerate(list_IDs_temp): # Store sample q_words = self.reader.get_query(self.relations[ID][0]) # corresponds to 1 file read from disc v_q_words.append(q_words) d_words = self.reader.get_document(self.relations[ID][1]) # corresponds to another file read from disc v_d_words.append(d_words) # Store class y.append(self.labels[ID]) X =…
accepted answer: http://stackoverflow.com/a/51383650
score: 0
answer count: 2
has title: How to use data generator to generate data faster while training keras model?
tagged with: training-data
tagged with: keras
tagged with: python

libvlc
tags question: http://stackoverflow.com/q/51374965
type: Tag
tag name: libvlc

http://stackoverflow.com/comment/89819382
comment on: http://stackoverflow.com/q/51424177
score: 0
type: Comment
has text: This isn't even a valid Python dictionary.
type: QuestionComment

http://stackoverflow.com/comment/89638880
score: 0
type: AnswerComment
type: Comment
has text: @Vin It seems like you typed 'Los Angeles' to the second answer. Anyway. I updated my answer.
comment on: http://stackoverflow.com/a/51330979

http://stackoverflow.com/q/51474751
downvote count: 0
has body: I am trying to use re.sub() in my Python script to remove some String. The sed command I used is (on Linux): echo "helloworld-5b5cf484-g582f" | sed 's/-[a-z0-9]\{5\}$//' | sed 's/-[0-9]\{10\}$//' | sed 's/-[a-z0-9]\{8,10\}$//' Which would output helloworld. Now, with Python, I tried to do this for the first sed group: newstring = re.sub(r'(s/-[a-z0-9]\{5\}$//)', r'\1', 'helloworld-5b5cf484-g582f') But it only outputs the copy, which is helloworld-5b5cf484-g582f How can I perform such sed command ? Edit: My question is not about my regex expression. The inputs String are more complex than the one I presented as an example. Question is about how to prorperly use re.sub() with the regex I used :)
has answer: http://stackoverflow.com/a/51474947
favorite count: 0
tagged with: python-3.x
upvote count: 1
tagged with: python
tagged with: regex
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89917905
score: 1
accepted answer: http://stackoverflow.com/a/51474947
has title: Python sed regex matching
has comment: http://stackoverflow.com/comment/89917838
has comment: http://stackoverflow.com/comment/89917826
type: Question
answer count: 2
tagged with: sed
possible better answer: http://stackoverflow.com/a/51475208
has answer: http://stackoverflow.com/a/51475208
has comment: http://stackoverflow.com/comment/89917972
has comment: http://stackoverflow.com/comment/89917929

http://stackoverflow.com/q/51451951
has body: I am having a weird error when selecting multiple columns in pandas dataframe. Here is the code: import pandas as pd df = pd.read_csv("./Dataset/train.csv", engine='python') df['eviv1', 'v2a1'] I get this error message: KeyError: ('eviv1', 'v2a1') but I don't get an error message when running df['eviv1'] df[v2a1] separately. PS: I am using python 3 and Jupyter Notebook with pandas version 0.23.0.
answer count: 2
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51451993
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/72400024
upvote count: 2
has answer: http://stackoverflow.com/a/72400024
tagged with: python
type: AnsweredQuestion
score: 2
has title: keyError in pandas on selecting multiple columns
tagged with: dataframe
has answer: http://stackoverflow.com/a/51451993
type: Question

web-crawler
tags question: http://stackoverflow.com/q/51379850
tags question: http://stackoverflow.com/q/51423482
tags question: http://stackoverflow.com/q/51354714
tags question: http://stackoverflow.com/q/51454895
tag name: web-crawler
tags question: http://stackoverflow.com/q/51372622
tags question: http://stackoverflow.com/q/51418354
tags question: http://stackoverflow.com/q/51432471
type: Tag
tags question: http://stackoverflow.com/q/51341655
tags question: http://stackoverflow.com/q/51430163
tags question: http://stackoverflow.com/q/51388018
tags question: http://stackoverflow.com/q/51372158

http://stackoverflow.com/q/51337460
has comment: http://stackoverflow.com/comment/89649763
has comment: http://stackoverflow.com/comment/89649707
type: AnsweredQuestion
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51337528
upvote count: 0
has title: Make it to throw errors if no records found using .filter
has comment: http://stackoverflow.com/comment/89649494
score: -1
has body: When I search for a record which does not recorded in database, it return a null In [15]: a = Article.objects.filter(title="hello") In [16]: a Out[16]: &lt;QuerySet []&gt; This mean, it silence if I use try and except arr = [] try: a = Article.objects.filter(title="strange title") arr.append(a) except SyntaxError: print("typo, double check") How to make it report error if no records qualified?
answer count: 1
has comment: http://stackoverflow.com/comment/89649724
favorite count: 0
has answer: http://stackoverflow.com/a/51337528
tagged with: django
tagged with: python

http://stackoverflow.com/comment/89767944
comment on: http://stackoverflow.com/a/51398222
type: Comment
has text: Thank you very much for the answer! It seems the absolute imports are the way to go. Now that I've been [struggling](https://softwareengineering.stackexchange.com/questions/375324/referencing-custom-python-modules-and-data-files) with this for a while, may I ask a few direct questions that may not be in the best style of these forums? I hope you'll humor me. Do these absolute imports work if this is installed with setuptools and executed as a cmd script? If not, how would you, however briefly explained, install and execute scripts that need custom modules to run to a different environment?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89859120
type: QuestionComment
score: 2
has text: Your code is working fine with me
comment on: http://stackoverflow.com/q/51444391
type: Comment

http://stackoverflow.com/comment/89861222
has text: Good answer, just had to change i = 0 inside the if to i = -1, or a continue because i will be incremented after. Thanks
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51445359

http://stackoverflow.com/comment/89648622
type: Comment
comment on: http://stackoverflow.com/q/51336785
has text: but this error is when i perform encryption
score: 0
type: QuestionComment

http://stackoverflow.com/q/51428730
tagged with: python
downvote count: 4
type: AnsweredQuestion
type: Question
tagged with: numpy
has body: I have a list of values for example: [1,2,3,4,5,6,7,8,9,10] And specific indexes like: [0,3,5] I want something that returns deleting the values which the index belongs to the [0,3,5] array: [2,3,5,7,8,9,10] Any ideas for Python 3? Thanks
has title: Delete specific elements from a list in python 3
duplicate of: http://stackoverflow.com/q/11303225
linked to: http://stackoverflow.com/q/11303225
duplicate of: http://stackoverflow.com/q/497426
upvote count: 1
answer count: 1
tagged with: arrays
has answer: http://stackoverflow.com/a/51428745
accepted answer: http://stackoverflow.com/a/51428745
favorite count: 0
score: -3

http://stackoverflow.com/q/51330863
downvote count: 0
linked to: http://stackoverflow.com/q/11214175
has title: Django - How do I create a model that contains a collection of its own type?
tagged with: django-models
tagged with: containment
type: Question
upvote count: 2
has body: One of the fields in a model I'm creating is for a list of instances of its own type. How do I do this in django? I couldn't find any documentation on how to do this.. This is something like what I am talking about, but doesn't work because the Component class isn't defined yet (and probably for other reasons too). class Component(models.Model): name = models.CharField() description = models.CharField() status_ok = models.BooleanField() subcomponents = models.ForeignKey(Component) A regular class that briefly demonstrates the concept: class Component: def __init__(self, name, description, status_ok, *subcomponents): self.name = name self.description = description self.status_ok = status_ok self.subcomponents = [] for subcomponent in subcomponents: if isinstance(subcomponent, Component): self.subcomponents.append(subcomponent) else: raise TypeError(subcomponent)
has comment: http://stackoverflow.com/comment/89637537
has answer: http://stackoverflow.com/a/51330889
accepted answer: http://stackoverflow.com/a/51330889
answer count: 1
has comment: http://stackoverflow.com/comment/89637597
favorite count: 0
tagged with: python-3.x
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89637431
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/89688201
type: AnswerComment
has text: @AnketPadwalkar As I said: you must be doing something wrong.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51357681

http://stackoverflow.com/comment/89854520
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51439723
type: Comment
has text: @Bart I got it! Thank you so much.

http://stackoverflow.com/a/63271805
answers question: http://stackoverflow.com/q/51340386
upvote count: 2
downvote count: 0
type: Answer
score: 2
has body: The question was asked two years ago so I'll post an answer or rather a suggestion here. You may want to try the deep_translator package if it matches your needs. from deep_translator import GoogleTranslator translated = GoogleTranslator(source='auto', target='ru').translate(text='happy coding')

neo4j-python-driver
type: Tag
tag name: neo4j-python-driver
tags question: http://stackoverflow.com/q/51345894

http://stackoverflow.com/q/51473354
score: 1
has comment: http://stackoverflow.com/comment/89925240
tagged with: peewee
downvote count: 0
answer count: 1
has title: Peewee atomic updates complex logic
favorite count: 0
has body: I need to update fields for a whole users table. It is stated in the docs that I shouldn't iterate through all table records. But to calculate a new field value I need to perform calculations using loops, user's relations and other complex logic relied on a concrete model. I tried to include this calculations in the model's property, but I got: peewee.InterfaceError: Error binding parameter 0 - probably unsupported type. Atomic update: query = User.update(balance=(User.balance + User.partners_reward))\ .where(User.deposit &gt;= 3) Model: class User(peewee.Model): deposit = peewee.DecimalField(default=0) balance = peewee.DecimalField(default=0) @property def partners(self): query = ( User.select(User, Partnership) .join(Partnership, JOIN.INNER, on=Partnership.invited) .where(Partnership.referral == self.id) ) partners = query.execute() return partners @property def partners_reward(self): partners = self.partners sum_reward = 0 partner_reward = 0.02 for partner in partners: reward = partner.deposit * partner_reward sum_reward += reward return sum_reward Prop description: Each user has partners (other users invited by him) and depending on them he gets bonuses. So to accomplish the update I need to collect user partners using relations and then calculate the actual bonus using loops. Changing property to a method solves this, but I don't know how I can get access to a concrete user instance. So how can some complex logic be implemented in atomic updates or should I do it using loop as not recommended?
has comment: http://stackoverflow.com/comment/90072714
accepted answer: http://stackoverflow.com/a/51485849
tagged with: python
tagged with: atomic
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89925640
has answer: http://stackoverflow.com/a/51485849
upvote count: 1
has comment: http://stackoverflow.com/comment/89940753
has comment: http://stackoverflow.com/comment/90063188
type: Question

http://stackoverflow.com/comment/89667142
type: AnswerComment
comment on: http://stackoverflow.com/a/51347183
has text: Although it doesn't matter here - you could possibly make use of `.finditer` to avoid creation of a list... eg: `words.issubset(m.group() for m in pat.finditer(s))`
type: Comment
score: 0

http://stackoverflow.com/q/51343217
has answer: http://stackoverflow.com/a/51343283
tagged with: beautifulsoup
has title: Python Module Not found error (Requests)
tagged with: python
tagged with: module
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89659990
tagged with: python-requests
has body: I am relatively new to Python and I was installing a couple of modules - BeautifulSoup and Requests (learning how to scrape). So I installed Requests $ pip install requests Requirement already satisfied: requests in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (2.19.1) Requirement already satisfied: certifi&gt;=2017.4.17 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from requests) (2018.4.16) Requirement already satisfied: idna&lt;2.8,&gt;=2.5 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from requests) (2.7) Requirement already satisfied: urllib3&lt;1.24,&gt;=1.21.1 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from requests) (1.23) Requirement already satisfied: chardet&lt;3.1.0,&gt;=3.0.2 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from requests) (3.0.4) But then I when I run my file, I keep getting this error message $ python test5.py Traceback (most recent call last): File "test5.py", line 1, in &lt;module&gt; import requests Could you help me with why I am having this issue? On a separate note, all of a sudden BBEdit started asking me when I save a .py file "BBEDIT is trying to install a helper tool" and asking for a PW. Then it asks again "BBEDIT is trying to make modifications, allow it"? WHy is it doing that? Is it safe? Thanks everyone and sorry for basic questions
type: Question
answer count: 1

http://stackoverflow.com/q/51451124
has answer: http://stackoverflow.com/a/51460562
upvote count: 1
has comment: http://stackoverflow.com/comment/89909722
type: Question
has title: Python 2.7 C++ extensions with CMake and SetupTools?
has comment: http://stackoverflow.com/comment/89890426
has comment: http://stackoverflow.com/comment/89889967
has comment: http://stackoverflow.com/comment/89895460
accepted answer: http://stackoverflow.com/a/51460562
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89896095
score: 1
has comment: http://stackoverflow.com/comment/89872815
favorite count: 0
linked to: http://stackoverflow.com/q/9698614
linked to: http://stackoverflow.com/q/42585210
has comment: http://stackoverflow.com/comment/89909767
has comment: http://stackoverflow.com/comment/89876662
tagged with: python
tagged with: cmake
tagged with: c++
duplicate of: http://stackoverflow.com/q/42585210
type: AnsweredQuestion
has body: Overview I have a C++ project that provides a Python 2.7 wrapper. I'm building that project using CMake and I would like to have a setup.py file so that I can easily pip install git+https://mygitrepo/my_project this project into a virtualenv. I have successfully gotten to the point where I can get pip to build my project, but I have no idea how to specify in my setup.py file or my CMakeLists.txt where my binaries should be installed. Details When I build my project with CMake (e.g. mkdir /path/to/my_project/build &amp;&amp; cd /path/to/my_project/build &amp;&amp; cmake .. &amp;&amp; make) everything gets built correctly and I end up with a libmy_project.so and a pymy_project.so file that I can succesfully import and use in Python. When I build the project with pip in a virtualenv (e.g. pip install /path/to/my_project -v) I can watch CMake and my compiler cranking away to compile things as expected. However they're built in a temp directory and immediately thrown away. How do I tell my setup.py which files to keep, and where will it put them? Relevant files My CMakeLists.txt looks like the following: cmake_minimum_required (VERSION 3.0.0) project (my_project) # Find SomePackage find_package(SomePackage REQUIRED COMPONENTS cool_unit great_unit) include_directories(${SomePackage_INCLUDE_DIR}) # Find Python find_package(PythonLibs 2.7 REQUIRED) include_directories(${PYTHON_INCLUDE_DIR}) # Build libmy_project add_library(my_project SHARED src/MyProject.cpp) target_link_libraries(my_project ${SomePackage_LIBRARIES} ${PYTHON_LIBRARIES}) # Build py_my_project add_library(py_my_project SHARED src/python/pyMyProject.cpp) set_target_properties(py_my_project PROPERTIES PREFIX &quot;&quot;) target_link_libraries(py_my_project ${SomePackage_LIBRARIES} ${PYTHON_LIBRARIES} my_project) file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/__init__.py &quot;__all__ = ['py_my_project']&quot;) and my setup.py file looks like this: import os import subprocess from setuptools import setup, Extension fr…
tagged with: setuptools

http://stackoverflow.com/q/51375678
has answer: http://stackoverflow.com/a/51376516
favorite count: 0
has body: I have the following code (Python 2.7): df = pd.DataFrame() pages = [i for i in range(1, int(math.ceil(reports.get_reports_count()/page_size)+1))] with ThreadPoolExecutor(max_workers=len(pages)) as executor: futh = [executor.submit(reports.fill_dataframe, page) for page in pages] for data in as_completed(futh): df = df.append(data.result(), ignore_index=True) cuttent_time = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') df["timestamp"] = cuttent_time df.columns = [c.lower().replace(' ', '_') for c in df.columns] df = df.replace(r'\n', ' ', regex=True) file_name = "{0}.csv.gz".format(tab_name) df.to_csv(path_or_buf=file_name, index=False, encoding='utf-8', compression='gzip', quoting=QUOTE_NONNUMERIC) This creates a compressed csv file from the data stream. Now, I want to make sure that the column in the file are the ones I expect (order does not matter). Meaning that if for any reason the data stream contains more columns than this columns will be removed. Note that I add a column of my own to the data stream called timestamp. The allowed columns are: cols_list = ['order_id', 'customer_id', 'date', 'price'] I'm aware that there is del df['column_name'] option but this doesn't work for me as I have no idea what will be the redundant column name. I'm looking for something like: if col_name not it cols_list: del df[???] #delete column and it's data. print [???] #print the name of the redundant column for log I think there are two approaches here: not to add the redundant column to the df in the first place. remove the redundant column after the df.append is finished. I prefer the 1st option as it should be with better performance (?) One of my attempts was: for i, data in enumerate(df): for col_name in cols_list: if col_name not in data.keys(): del df[col_name ] but it doesn't work.. if col_name not in data.keys(): AttributeError: 'str' object has no attribute 'keys' I'm not sure I enumerate over df itself
tagged with: python
answer count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51376452
has comment: http://stackoverflow.com/comment/89723377
has comment: http://stackoverflow.com/comment/89724276
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89723984
has comment: http://stackoverflow.com/comment/89724335
possible better answer: http://stackoverflow.com/a/51375886
has comment: http://stackoverflow.com/comment/89723467
has answer: http://stackoverflow.com/a/51375915
has answer: http://stackoverflow.com/a/51375886
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/51376452
has title: how to remove a column from Pandas dataframe using Python?
has comment: http://stackoverflow.com/comment/89723609

http://stackoverflow.com/q/51459448
has title: How to add next and previous in a quiz [python]
type: Question
tagged with: testing
has comment: http://stackoverflow.com/comment/89888267
score: 0
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51459582
accepted answer: http://stackoverflow.com/a/51459582
has comment: http://stackoverflow.com/comment/89888372
has body: I've got the following code that converts a list into a multiple choice quiz: def practise_test(test): score = 0 for question in test: while True: print(question[question]) reaction = input (question[options] + '\n') if reaction == question[answer]: print ('\nright answered!') print('The answer is indeed {}. {}\n'.format(question[answer], question[explanation])) score += 1 break else: print ('\nIncorrect answer.') print ('The correct answer is {}. {}\n'.format(question[answer], question[explanation])) break print (score) But now I have to add some code to the practise_test function so that when you type: 'previous' you go to the previous question. Anyone have an idea to fix this?
type: AnsweredQuestion

http://stackoverflow.com/q/51349893
linked to: http://stackoverflow.com/q/721928
tagged with: lxml
has body: I would like to search an XML file for multiple tags. I can evaluate these command separately: tree.findall('.//title') tree.findall('.//p') but how can I evaluate them together in the same time. I am looking for a syntax like .// title or .//p I tried this command from an SO post tree.findall('.//(p|title)') but I get this traceback error SyntaxError: invalid descendant
has answer: http://stackoverflow.com/a/71379493
possible better answer: http://stackoverflow.com/a/51349931
tagged with: python
score: 8
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51349931
type: Question
has title: Finding multiple types of tags with lxml findall() with xpath?
accepted answer: http://stackoverflow.com/a/51354083
answer count: 3
has comment: http://stackoverflow.com/comment/89672478
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51354083
upvote count: 8

http://stackoverflow.com/q/51464681
has title: Does anyone know what the function 'Parse_vars' in python does?
tagged with: initialization
tagged with: parsing
tagged with: pyramid
tagged with: python
accepted answer: http://stackoverflow.com/a/51465098
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51464920
type: Question
possible better answer: http://stackoverflow.com/a/51464759
has answer: http://stackoverflow.com/a/51465098
has answer: http://stackoverflow.com/a/51464759
has body: I am fairly new to python and particularly the pyramid framework - I am trying to initialize the database and am getting this parse_vars is not defined error. Does anyone know what the function parse_vars does? I can't find information anywhere on the internet about it? Maybe if i understand what its doing I can solve the error, Here is the code def main(argv=sys.argv): if len(argv) &lt; 2: usage(argv) config_uri = argv[1] options = parse_vars(argv[2:]) setup_logging(config_uri) settings = get_appsettings(config_uri, options=options) engine = get_engine(settings) Base.metadata.create_all(engine) session_factory = get_session_factory(engine) with transaction.manager: dbsession = get_tm_session(session_factory, transaction.manager) editor = User(name='editor', role='editor') editor.set_password('editor') dbsession.add(editor) basic = User(name='basic', role='basic') basic.set_password('basic') dbsession.add(basic) FTIRModel = FTIRModel( name='FrontPage', creator=editor, data='This is the front page', ) dbsession.add(FTIRModel) and here is the error
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/89898570

http://stackoverflow.com/comment/121874404
score: 0
type: AnswerComment
has text: Please add further details to expand on your answer, such as working code or documentation citations.
type: Comment
comment on: http://stackoverflow.com/a/68958618

http://stackoverflow.com/comment/89737752
score: 0
comment on: http://stackoverflow.com/q/51371293
type: Comment
type: QuestionComment
has text: @Jeronimo - I think I'll stick with `Event` as it is thread-safe out of the box.

http://stackoverflow.com/q/51366452
type: Question
has body: I'm using Python's Pathlib and I want to take something like p = Path('/path/to/foo') And then try a couple of different extensions. I can do for ext in ['.txt', '.md', '.note'] filename = Path(str(p) + ext) but that feels a little awkward. Is there a better way to do this?
upvote count: 102
tagged with: pathlib
possible better answer: http://stackoverflow.com/a/62742532
has answer: http://stackoverflow.com/a/62742532
answer count: 3
has answer: http://stackoverflow.com/a/51367068
tagged with: python
accepted answer: http://stackoverflow.com/a/51367068
favorite count: 0
tagged with: python-3.x
score: 102
has answer: http://stackoverflow.com/a/78212337
type: AnsweredQuestion
has title: Is there an idiomatic way to add an extension using Python's Pathlib?
has comment: http://stackoverflow.com/comment/122619526
downvote count: 0
has comment: http://stackoverflow.com/comment/89705401

http://stackoverflow.com/comment/89778838
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51402746
has text: Thanks for the reply! Theres a lot of material you directed me to there so I'm going to take a day or two to review it all and see if it gets me where I need to be. If it does I'll be sure to accept your answer and if not I'm sure my follow up question will be vastly more targeted than my original. Either way these are great leads you gave me!

http://stackoverflow.com/comment/89757652
has text: Both optimize.root and optimize.least_squares give me a solution in which x[0]*x[4], for instance, is several orders of magnitude off from Kw (which is 10^-14): I end up getting something like 10^-6 for that product (in case you're familiar with chemistry, Kw is the self-ionization constant of water, and needs to be close to 10^-14 for my model to reflect reality....). K1 is 10^-5.86 and K2 is 10^-0.92. Can you say any more about floating point arithmetic and how I can get around this? Thanks
score: 0
comment on: http://stackoverflow.com/q/51392040
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89922243
type: Comment
has text: @heemayl I don't understand what you want to say. This is what docs say `If the optional argument count is given, only the first count occurrences are replaced`
comment on: http://stackoverflow.com/a/51476906
score: 0
type: AnswerComment

dictionary
tags question: http://stackoverflow.com/q/51342521
tags question: http://stackoverflow.com/q/51328609
tags question: http://stackoverflow.com/q/51437045
tags question: http://stackoverflow.com/q/51469622
tags question: http://stackoverflow.com/q/51400461
tags question: http://stackoverflow.com/q/51360098
tags question: http://stackoverflow.com/q/51446912
tags question: http://stackoverflow.com/q/51332015
tags question: http://stackoverflow.com/q/51462442
tags question: http://stackoverflow.com/q/51413212
tags question: http://stackoverflow.com/q/51478949
tags question: http://stackoverflow.com/q/51338443
tags question: http://stackoverflow.com/q/51350349
tags question: http://stackoverflow.com/q/51387189
tags question: http://stackoverflow.com/q/51439442
tags question: http://stackoverflow.com/q/51349508
tags question: http://stackoverflow.com/q/51421916
tags question: http://stackoverflow.com/q/51414622
tags question: http://stackoverflow.com/q/51387498
tags question: http://stackoverflow.com/q/51372523
tags question: http://stackoverflow.com/q/51332160
tags question: http://stackoverflow.com/q/51377076
tags question: http://stackoverflow.com/q/51360949
tags question: http://stackoverflow.com/q/51420373
tags question: http://stackoverflow.com/q/51429969
tags question: http://stackoverflow.com/q/51421495
tags question: http://stackoverflow.com/q/51394842
tags question: http://stackoverflow.com/q/51335930
tags question: http://stackoverflow.com/q/51398843
tags question: http://stackoverflow.com/q/51409852
tags question: http://stackoverflow.com/q/51424336
tags question: http://stackoverflow.com/q/51381112
tags question: http://stackoverflow.com/q/51345639
tags question: http://stackoverflow.com/q/51461306
tags question: http://stackoverflow.com/q/51350195
tags question: http://stackoverflow.com/q/51373165
tags question: http://stackoverflow.com/q/51405148
tags question: http://stackoverflow.com/q/51405745
tags question: http://stackoverflow.com/q/51324530
tags question: http://stackoverflow.com/q/51325708
tags question: http://stackoverflow.com/q/51371169
tags question: http://stackoverflow.com/q/51353519
tags question: http://stackoverflow.com/q/51453844
tags question: http://stackoverflow.com/q/51390499
tags question: http://stackoverflow.com/q/51468492
tags question: http://stackoverflow.com/q/51352094
tags question: http://stackoverflow.com/q/51347828
tags question: http://stackoverflow.com/q/51396547
tags question: http://stackoverflow.com/q/51325476
tags question: http://stackoverflow.com/q/51391271
tag name: dictionary
tags question: http://stackoverflow.com/q/51334197
tags question: http://stackoverflow.com/q/51350683
tags question: http://stackoverflow.com/q/51464548
tags question: http://stackoverflow.com/q/51408627
tags question: http://stackoverflow.com/q/51347844
tags question: http://stackoverflow.com/q/51348988
tags question: http://stackoverflow.com/q/51331758
tags question: http://stackoverflow.com/q/51435299
tags question: http://stackoverflow.com/q/51338037
tags question: http://stackoverflow.com/q/51375389
tags question: http://stackoverflow.com/q/51476932
tags question: http://stackoverflow.com/q/51393957
tags question: http://stackoverflow.com/q/51334434
tags question: http://stackoverflow.com/q/51344283
tags question: http://stackoverflow.com/q/51469892
tags question: http://stackoverflow.com/q/51419621
tags question: http://stackoverflow.com/q/51361420
tags question: http://stackoverflow.com/q/51325540
tags question: http://stackoverflow.com/q/51383150
tags question: http://stackoverflow.com/q/51387434
tags question: http://stackoverflow.com/q/51344106
tags question: http://stackoverflow.com/q/51405822
tags question: http://stackoverflow.com/q/51413998
tags question: http://stackoverflow.com/q/51440540
tags question: http://stackoverflow.com/q/51375866
tags question: http://stackoverflow.com/q/51414133
tags question: http://stackoverflow.com/q/51374604
tags question: http://stackoverflow.com/q/51379302
tags question: http://stackoverflow.com/q/51450258

http://stackoverflow.com/comment/89781558
score: 0
type: Comment
type: QuestionComment
has text: Entry would be:
comment on: http://stackoverflow.com/q/51405006

http://stackoverflow.com/comment/89688707
score: 0
type: Comment
has text: I print 'cur' and found most of them are empty,a few not,the result of next(cur) is always the first one ,I write a while loop to extend the value to the data list.Thanks.
type: AnswerComment
comment on: http://stackoverflow.com/a/51346292

http://stackoverflow.com/comment/89738243
type: QuestionComment
has text: yes both vertical and horizontal lines
comment on: http://stackoverflow.com/q/51380692
score: 0
type: Comment

http://stackoverflow.com/q/51473248
has title: Python Flask posting large file to api
tagged with: python
has body: I am building my first api using python flask and the client would be posting images to the api. While the api works perfectly for smaller files 50kb size, it throws error while uploading 500kb - 2mb files. I have read many posts here as well as other blogs and github issues and I understand that the server throws the error as it gets timed out before receiving the complete file. Some of the options that I came across were: using from requests_toolbelt.multipart import encoder and use encoder.MultipartEncoder to encode the image. add app.config['MAX_CONTENT_LENGTH'] = 100 * 1024 * 1024 to the server.py - which I did and this did not help. The current api does not use wsgi or nginx (frankly i don't know how to use them or their purpose and currently testing my api for response) and runs on debugging mode. My client is as follows: client.py import requests from requests_toolbelt.multipart import encoder session = requests.Session() with open('124430597.jpg', 'rb') as f: files = encoder.MultipartEncoder({ "image_data": ("124430597.jpg", f, "application/octet-stream"), "composite": "NONE", }) url = 'http://10.7.104.57:5000/julytest' headers = {"Prefer": "respond-async", "Content-Type": files.content_type} resp = session.get(url, headers=headers, data=files) print(resp.text) server.py #!/usr/bin/env python from PIL import Image import io import requests import numpy as np import os from os.path import basename from flask import Flask, flash, request, redirect, url_for,jsonify, make_response from werkzeug.utils import secure_filename from flaskext.mysql import MySQL from imagesearch.cbir import HSVDescriptor from imagesearch.cbir import Searcher import MySQLdb import datetime import cv2 UPLOAD_FOLDER = '/home/magesh/imgdb/' ALLOWED_EXTENSIONS = set(['jpg', 'jpeg']) app = Flask(__name__) app.config['MYSQL_DATABASE_USER'] = 'root' app.config['MYSQL_DATABASE_PASSWORD'] = 'Abc@123def' app.config['MYSQL_DATABASE_DB'] = 'tamprint' app.config['MYSQL_DATABASE_HOST'] = 'localhost'…
type: Question
has answer: http://stackoverflow.com/a/51473369
score: 0
answer count: 1
tagged with: flask
type: UnansweredQuestion

http://stackoverflow.com/a/51440919
answers question: http://stackoverflow.com/q/51440800
has body: I think you need pivot_table, df.pivot_table(values='Score', index='Tag', columns='Tag2', aggfunc='sum', fill_value='')
upvote count: 1
has comment: http://stackoverflow.com/comment/89852063
score: 1
downvote count: 0
type: Answer

http://stackoverflow.com/a/51330550
downvote count: 0
has body: As other said, it resolves to the current path and therefore exists, but here's why, pathlib.Path is acutally a subclass of pathlib.PurePath which assumes the current directory when the pathsegments (argument) is empty (equivalent to ''). You can prove that empirically like this, from pathlib import PurePath print(PurePath()) &gt;&gt;&gt;&gt; . I assume there is an advantage gained by defining the Path('') to be the same as Path('.'). Correct. Even though I'm not the creator of that lib, I assume this is for syntax and logical reasons. Indeed, people often want to refer to the current directory to compute something dynamically. Therefore, for the same reason . points to the current directory, the lib creator probably wanted to let you write something like this, &gt;&gt;&gt;&gt; p = Path() # or possibly Path('.') &gt;&gt;&gt; [x for x in p.iterdir() if x.is_dir()] that would list sub directories. Basically, see this as a default. It was logic that the default path returned by Path() was the current directory. Thus, logically, an empty string value should have the same behavior.
score: 20
answers question: http://stackoverflow.com/q/51330297
type: Answer
has comment: http://stackoverflow.com/comment/108671924
upvote count: 20

http://stackoverflow.com/a/51391664
accepted answer of: http://stackoverflow.com/q/51391545
downvote count: 0
score: 7
upvote count: 7
type: AcceptedAnswer
has body: By default Django will look for a pk or a slug field when you use a DetailView. You must override get_object() method to change this behaviour: get_object() looks for a pk_url_kwarg argument in the arguments to the view; if this argument is found, this method performs a primary-key based lookup using that value. If this argument is not found, it looks for a slug_url_kwarg argument, and performs a slug lookup using the slug_field. That being said, your approach has other problems. It is always better to use a slug instead of a name for other reasons. For example, name is not guaranteed to be unique and also it may have characters which are not URL safe. See this question for a detailed discussion on how to use slug fields.
answers question: http://stackoverflow.com/q/51391545
type: Answer

http://stackoverflow.com/q/51340471
has comment: http://stackoverflow.com/comment/90140680
has comment: http://stackoverflow.com/comment/89658097
tagged with: visual-studio-2017
tagged with: python-2.7
score: 0
type: UnansweredQuestion
has title: Visual Studio 2017 Python "KeyError: 'BREAK_SYSTEMEXIT_ZERO' "
tagged with: python
has body: I use Visual Studio 2017. When I try to debug python code like this: print " hello " I get this error : warning: Debugger speedups using cython not found. Run '"C:\Program Files\Python37\python.exe" "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\Extensions\Microsoft\Python\Core\Packages\ptvsd\pydevd\setup_cython.py" build_ext --inplace' to build. pydev debugger: starting Traceback (most recent call last): File "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\Extensions\Microsoft\Python\Core\Packages\ptvsd\wrapper.py", line 796, in done fut.result() File "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\Extensions\Microsoft\Python\Core\Packages\ptvsd\futures.py", line 40, in result reraise(self._exc_info) File "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\Extensions\Microsoft\Python\Core\Packages\ptvsd\reraise3.py", line 8, in reraise raise exc_info[1].with_traceback(exc_info[2]) File "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\Extensions\Microsoft\Python\Core\Packages\ptvsd\futures.py", line 149, in callback x = next(it) File "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\Extensions\Microsoft\Python\Core\Packages\ptvsd\wrapper.py", line 1004, in on_launch args.get('options', options)) File "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\Extensions\Microsoft\Python\Core\Packages\ptvsd\wrapper.py", line 959, in _parse_debug_options options[key] = DEBUG_OPTIONS_PARSER[key](value) KeyError: 'BREAK_SYSTEMEXIT_ZERO'
tagged with: visual-studio
answer count: 0
has comment: http://stackoverflow.com/comment/89664553
type: Question
tagged with: debugging

http://stackoverflow.com/a/51461809
has comment: http://stackoverflow.com/comment/89892967
has comment: http://stackoverflow.com/comment/89892849
has comment: http://stackoverflow.com/comment/89892933
has comment: http://stackoverflow.com/comment/89892755
type: Answer
has comment: http://stackoverflow.com/comment/89892961
has comment: http://stackoverflow.com/comment/89892720
score: 0
has comment: http://stackoverflow.com/comment/89892707
has comment: http://stackoverflow.com/comment/89892894
has comment: http://stackoverflow.com/comment/89892989
has body: I would just do: df = pd.DataFrame(data=[10,9,7,4], columns=['A']) df['B'] = abs(df['A'].diff()) The reason for abs() is because diff() computes the difference between current - previous whereas you want previous - current. This method is already built-in to the Series class, so using abs() will get you the correct result by taking the absolute value either way. To support: import pandas as pd df = pd.DataFrame(data=[10,9,7,4], columns=['A']) df['B'] = abs(df['A'].diff()) &gt;&gt;&gt; df # Output A B 0 10 NaN 1 9 1.0 2 7 2.0 3 4 3.0 df2 = pd.DataFrame(data=[10,4,7,9], columns=['A']) df2['B'] = abs(df2['A'].diff()) &gt;&gt;&gt; df2 # Output A B 0 10 NaN 1 4 6.0 2 7 3.0 3 9 2.0 To still out perform that of @cosmic_inquiry's solution: import pandas as pd df = pd.DataFrame(data=[10,9,7,4], columns=['A']) df2 = pd.DataFrame(data=[10,4,7,9], columns=['A']) df['B'] = df['A'].diff() * -1 df2['B'] = df2['A'].diff() * -1 &gt;&gt;&gt; df # Output: A B 0 10 NaN 1 9 1.0 2 7 2.0 3 4 3.0 &gt;&gt;&gt; df2 # Output: A B 0 10 NaN 1 4 6.0 2 7 -3.0 3 9 -2.0
has comment: http://stackoverflow.com/comment/89892812
has comment: http://stackoverflow.com/comment/89892946
has comment: http://stackoverflow.com/comment/89892964
answers question: http://stackoverflow.com/q/51461728
has comment: http://stackoverflow.com/comment/89892906

http://stackoverflow.com/a/51398561
type: Answer
accepted answer of: http://stackoverflow.com/q/51394080
answers question: http://stackoverflow.com/q/51394080
score: 0
type: AcceptedAnswer
has body: After debugging this issue further, there seems to be an issue with how .replace method handles timezone information to the datetime object. If we use .replace method to add timezone, tzinfo object in the start_date has _tzname = "LMT" and tzinfo object in the current_est_time has _tzname = "EDT". And that's why comparison result is not consistent. By referring to Why doesn&#39;t pytz localize() produce a datetime object with tzinfo matching the tz object that localized it? ,it looks like "EDT" is the correct value. So In my opinion here is the correct way of implementing this, from datetime import datetime import pytz def main(): process_date_time(25) process_date_time(26) def process_date_time(min): # All the dates are in US/Eastern time zone. Time zone for USA, North Carolina # These dates are received from REST call in JSON # I need to compare the current date time, if that falls within this range take some action tz = pytz.timezone('US/Eastern') start_date_str = "7/17/2018 11:30:00 AM" end_date_str = "7/17/2018 2:30:00 PM" # To simulate current date time within the range, I will update the current date time value. dt = datetime.now() current_est_time = tz.localize(dt) current_est_time = current_est_time.replace(year=2018, month=7, day=17, hour=12, minute=min) print current_est_time start_date_1 = datetime.strptime(start_date_str, "%m/%d/%Y %I:%M:%S %p") end_date_1 = datetime.strptime(end_date_str, "%m/%d/%Y %I:%M:%S %p") start_date = tz.localize(start_date_1) end_date = tz.localize(end_date_1) print start_date &lt;= current_est_time &lt;= end_date if __name__ == '__main__': main()

http://stackoverflow.com/comment/89649372
type: Comment
type: QuestionComment
score: 0
has text: yes, it's just for example.
comment on: http://stackoverflow.com/q/51337313

http://stackoverflow.com/a/51446187
downvote count: 0
type: Answer
has body: How many virtuals are you requesting? 1 Please Enter Virtual Name: nifi-prod-pci Please Enter Virtual TCP port :8081 8082 Please Enter Server name, port and IP(format: oser500522:443:172.17.5.1):oser502687:8081:156.92.161.232 oser50268956.92.161.233:8081 [{'number_virtuals': '1', 'realSerName': ['n', 'i', 'f', 'i', '-', 'p', 'r', 'o', 'd', '-', 'p', 'c', 'i'], 'realTCPport': ['8', '0', '8', '1', ' ', '8', '0', '8', '2'], 'serName': ['o', 's', 'e', 'r', '5', '0', '2', '6', '8', '7', ':', '8', '0', '8', '1', ':', '1', '5', '6', '.', '9', '2', '.', '1', '6', '1', '.', '2', '3', '2', ' ', '5', '6', '.', '9', '2', '.', '1', '6', '1', '.', '2', '3', '3', ':', '8', '0', '8', '1', ' ']}]
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51432600

http://stackoverflow.com/q/51476866
tagged with: pandas
upvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89939509
tagged with: python
type: AnsweredQuestion
has title: Attribute Error bytes object has no object ‘encode’
has answer: http://stackoverflow.com/a/51477103
downvote count: 1
type: Question
has body: TESTDATA = io.StringIO(file.encode('utf-8').strip()) df = pd.read_csv(TESTDATA, sep=",") This give my error, I’m trying to read in a csv string into my data frame
score: -1
accepted answer: http://stackoverflow.com/a/51477103

http://stackoverflow.com/q/51390860
tagged with: django
tagged with: python
has body: I'm having problems to return my object after I add some items into my "countries" ManytomanyField. I can see my data being saved class CompanyProfileManager(models.Manager): @transaction.atomic def register_company(self, name, description, tag_name, email, is_private, uses_credits, pays_subscription, pool, facebook, twitter, web, country, videocall_doctor_to_patient, micro_type, can_move, fixed_percentage, fixed_price, fixed_tariff, instagram, subdomain, banner_description, banner_title, countries, **kwargs): tag = Tag(name=tag_name, description=tag_name, is_active=True) tag.save() company = self.create_instance(name, description, email, is_private, uses_credits, pays_subscription, pool, facebook, twitter, web, country, videocall_doctor_to_patient, micro_type, can_move, fixed_percentage, fixed_price, fixed_tariff, instagram, subdomain, banner_description, banner_title) company.tag = tag company.save() for item in countries: company.countries.add(item) return company #Using Debug Mode, My project breaks right here I'm really lost, the only thing I've seen so far related to my problem is using .all() to get as a queryset
upvote count: 5
type: Question
score: 5
downvote count: 0
answer count: 1
favorite count: 0
has title: Django - ManyRelatedManager object is not iterable when returning Object
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51391001
type: UnansweredQuestion

http://stackoverflow.com/q/51404196
tagged with: words
tagged with: python
tagged with: text
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51404349
has title: Get phrases with 3 words
downvote count: 2
has answer: http://stackoverflow.com/a/51404612
type: Question
score: -2
possible better answer: http://stackoverflow.com/a/51404612
answer count: 2
has answer: http://stackoverflow.com/a/51404349
upvote count: 0
has comment: http://stackoverflow.com/comment/89779298
favorite count: 0
has comment: http://stackoverflow.com/comment/89780629
has body: I have tried to figure this one out for some time now. I want to take a large text/string and split it into phrases of 3 words, and add them to an array. I have tried using spilt() but it dosen't work as I hoped. What I was thinking of doinig, to get it to work: Start with the first 3 words in the string, when I got those, I put it in an array and move 1 word and take the next 3 words and so on and so on. Is this a bad way of doing this? Kind regards :)

http://stackoverflow.com/comment/89966199
comment on: http://stackoverflow.com/a/51413053
has text: I didnt quite understand what you wanted to do with this allow_settings, I guess it was a way to hardcode which settings could be changed and which shouldnt be. In my case, only the constance settings should be changed. I will mark this as correct as it worked for me to figure out how to do it. Thanks! :)
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51446989
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51447686
accepted answer: http://stackoverflow.com/a/51447686
score: 1
has comment: http://stackoverflow.com/comment/89864148
type: Question
possible better answer: http://stackoverflow.com/a/51447752
answer count: 2
tagged with: group-by
downvote count: 0
has body: I am a super beginner for Python. Long story short, I want to groupby with one column, apply one function to one column, apply another function to another column, and plot the results(the first column to the x-axis, the second column to the y-axis). I have a pandas data frame df which contains many columns. Two columns of them are tour_id and tour_distance. tour_id tour_distance A 10 A 10 A 10 A 10 B 20 B 20 C 40 C 40 C 40 C 40 C 40 : : : : Since I assume that the longer tour_distance becomes, the more rows each tour_id has, I want to plot a histogram of tour_distance vs row counts in each group of tour_id. Question 1: what's the simplest solution for this groupby and plot problem? Question 2: how can I improve my failed attempt? My attempt: I thought it would be easier to make a new data frame like this. tour_id tour_distance row_counts A 10 3 B 20 2 C 40 5 : : : In this way I can use matplotlib and do like this, import matplotlib.pyplot as plt x = df.tour_distance y = df.row_counts plt.bar(x,y) However, I can't make this data frame. df_tour_distance = df.groupby('tour_id').tour_distance.head(1) df_tour_distance = pd.DataFrame(df_tour_distance) df_size = df.groupby('tour_id').tour_distance.size() df_size = pd.DataFrame(df_size) df = pd.merge(df_size, df_tour_distance, on='tour_id') &gt;&gt;&gt; KeyError: 'tour_id' This also failed: g = df.groupby('tour_id') result = g.agg({'Count':lambda x:x.size(), 'tour_distance_grouped':lambda x:x.head(1)}) result &gt;&gt;&gt; KeyError: 'Count'
tagged with: pandas
upvote count: 1
tagged with: histogram
has title: Pandas data frame: groupby and plot with two different columns
favorite count: 0
has answer: http://stackoverflow.com/a/51447752
tagged with: python

http://stackoverflow.com/comment/89760711
score: 0
comment on: http://stackoverflow.com/q/51388281
type: Comment
type: QuestionComment
has text: @Azhy I just show a simple example, the fact is that g contains several random runs, but after that we need to calculate an equation constructed by those random results. But we hope the equation every time is the same after once running g i.e. keep it fixed when call test. Is this clear for your question?

http://stackoverflow.com/comment/89800642
type: QuestionComment
comment on: http://stackoverflow.com/q/51407143
has text: I reproduced the issue on MySQL, so I assume that is the backend you are using. See my answer.
score: 0
type: Comment

http://stackoverflow.com/comment/89795275
type: AnswerComment
type: Comment
score: 1
has text: Sure, so assume we want two groups per dataframe, I’d expect to have a dataframe with a, a, a, a, b, b - a dataframe with c, v, v and a dataframe with ‘f’ given the above example
comment on: http://stackoverflow.com/a/51411561

http://stackoverflow.com/comment/89673827
type: QuestionComment
has text: My list has no way to convert to utf8 because he has been encrypted He will return that I can't convert utf8
comment on: http://stackoverflow.com/q/51350548
score: 0
type: Comment

http://stackoverflow.com/q/51355369
tagged with: dataframe
has answer: http://stackoverflow.com/a/51355423
type: Question
has title: split column values into one to one mapping
answer count: 2
downvote count: 0
has body: An extension to following question : Split (explode) pandas dataframe string entry to separate rows df : STATE CITY ALT_NAMES 0 S1 C1 A1@A2 1 S2 C2 A3@A4@A5 How can I achieve following result: out_df : STATE CITY CITY_VAR 0 S1 C1 A1 1 S1 C1 A2 2 S2 C2 A3 3 S2 C2 A4 4 S2 C2 A5 sample data : STATE CITY ALT_NAMES FL FT. MYERS FORT MYERS@FT MYERS FL NORTH FT MYERS N.FT.MYERS@N. FORT MYERS@NORTH FORT MYERS
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51355423
linked to: http://stackoverflow.com/q/12680754
tagged with: python
has answer: http://stackoverflow.com/a/51355481
favorite count: 0
possible better answer: http://stackoverflow.com/a/51355481
upvote count: 1
type: AnsweredQuestion
score: 1

http://stackoverflow.com/q/51414098
answer count: 5
tagged with: python
type: AnsweredQuestion
score: -4
has answer: http://stackoverflow.com/a/51416405
type: Question
has answer: http://stackoverflow.com/a/60412547
possible better answer: http://stackoverflow.com/a/51416405
has comment: http://stackoverflow.com/comment/89799602
has comment: http://stackoverflow.com/comment/89799546
downvote count: 6
has title: Taking input for dictionary in python
has answer: http://stackoverflow.com/a/77542874
upvote count: 2
has answer: http://stackoverflow.com/a/51414372
accepted answer: http://stackoverflow.com/a/51414372
has answer: http://stackoverflow.com/a/75620327
has body: Can anyone please tell me if it is possible to take the key and value for a dictionary as input in python? Suppose I have made an empty dictionary. I want to include the key name by taking input from user as well as its corresponding value as well.
favorite count: 0
linked to: http://stackoverflow.com/q/15456158

http://stackoverflow.com/a/51470809
has body: For reference only. Not sure if it's efficient enough. On my machine it's a little faster than np.fromiter combined with python map. lower_bounds = np.full((1000,5), -np.inf) upper_bounds = np.random.rand(1000, 5) bounds = np.concatenate([lower_bounds, upper_bounds], axis=1) func1d = lambda bound: mvnun(bound[:5], bound[5:], means, cov_mtx)[0] out = np.apply_along_axis(func1d, -1, bounds)
answers question: http://stackoverflow.com/q/51470334
score: 0
type: Answer

http://stackoverflow.com/q/51375306
tagged with: python
linked to: http://stackoverflow.com/q/39593275
accepted answer: http://stackoverflow.com/a/51400091
type: AnsweredQuestion
score: 3
upvote count: 3
type: Question
downvote count: 0
tagged with: rpy2
tagged with: http://stackoverflow.com/tag/r
has answer: http://stackoverflow.com/a/51400091
has title: Extracting returned value from rpy2
answer count: 1
linked to: http://stackoverflow.com/q/46010397
favorite count: 0
has body: I am using a Jupyter notebook (Python 3 kernel) with rpy2 (V2.9.1) to run commands in R from Python. I can pass values to and from R, but my problem is I do not know how to extract the information I need from the variable returned from R. I have the following code: %Rpush blood %%R library("mice") memory.limit(56000) imp &lt;- mice(blood, seed = 23109) %Rpull imp print(imp) [out]&lt;rpy2.rinterface.ListSexpVector - Python:0x00000178FC1BDA20 / R:0x00000178BCF236F0&gt; imp is a list with 21 elements. I would like to be able to access the elements by name. According to this post: rpy2 access R named list items by name, low-level interface I should be able to do the following for example: m = imp.rx('m') or m = imp[imp.names.index('m')] Both of these give the error message "'rpy2.rinterface.ListSexpVector' object has no attribute 'rx' (or 'names' in the 2nd case).Yet the post referenced above was using ListSexpVector. Is there a way of doing this?

http://stackoverflow.com/a/51354024
accepted answer of: http://stackoverflow.com/q/51353817
answers question: http://stackoverflow.com/q/51353817
type: AcceptedAnswer
upvote count: 6
type: Answer
downvote count: 0
score: 6
has body: Referring to the Python manual str() is used when: You want the string representation of an object You want to convert bytes (or other byte sequence, like bytearray) into a string In all other cases, you should use ''. The fact that an empty str() call returns a blank string is a side effect and not the intended primary use of the method.

http://stackoverflow.com/a/51404937
downvote count: 0
has comment: http://stackoverflow.com/comment/89780905
has body: This is most likely because your method to find primes is inefficient and your range is too large. Your algorithm is a brute force way of finding prime numbers and it's time complexity is O(n²). If you time your algorithm for smaller numbers you will see that as you increase n, time taken does not increase linearly, but is in fact quadratic. +--------+---------------+ | n | time(in sec) | +--------+---------------+ | 1000 | 0.007979 | | 2000 | 0.038865 | | 5000 | 0.137037 | | 10000 | 0.499688 | | 20000 | 1.892315 | | 50000 | 10.29843 | | 100000 | 1374.101 | | ... | ... | +--------+---------------+ I would suggest you to take a look at Sieve of Eratosthenes. You will find many implementations of it in whichever language you want if you search for this.
has comment: http://stackoverflow.com/comment/89780913
has comment: http://stackoverflow.com/comment/89780821
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/51404873
answers question: http://stackoverflow.com/q/51404873
has comment: http://stackoverflow.com/comment/89781884
score: 2
type: AcceptedAnswer

http://stackoverflow.com/q/51389664
has answer: http://stackoverflow.com/a/51390024
has comment: http://stackoverflow.com/comment/89751702
linked to: http://stackoverflow.com/q/1294382
has comment: http://stackoverflow.com/comment/89751774
linked to: http://stackoverflow.com/q/868568
answer count: 1
downvote count: 0
has body: My question is related to parallelizing a python code and I want to know how we can run a function for different instances of a class to decrease the runtime. What I have: I have multiple instances of a class A (stored in a list called instances). This class has a function add. Now, we have multiple independent tasks, one for each instance of class A where the input to all these tasks is one thing (number n in my example). Each instance needs to apply function add to n and return a number. We want to store the returned numbers of all instances in a list (list results in my example). What I want: As you can see, in this example, the tasks can be parallelized as there is no need for one to wait for the other one to gets done. How can we parallelize the simple code below? Since nothing is shared between the different instances, I guess we can even use multithreading, right? Or the only way is to use multiprocessing? class A(object): def __init__(self, q): self.p = q def add(self, num): return self.p + num instances = [] for i in xrange(5): instances.append(A(i)) n = 20 results = [] for inst in instances: results.append(inst.add(n)) print(results) Output: [20, 21, 22, 23, 24]
favorite count: 0
linked to: http://stackoverflow.com/q/51411098
accepted answer: http://stackoverflow.com/a/51390024
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89751701
linked to: http://stackoverflow.com/q/5442910
score: 1
tagged with: multithreading
has comment: http://stackoverflow.com/comment/89751615
has title: Parallelizing a python code for different instances of a class
linked to: http://stackoverflow.com/q/2846653
upvote count: 1
type: Question
linked to: http://stackoverflow.com/q/9038711

http://stackoverflow.com/a/51357946
has comment: http://stackoverflow.com/comment/89691945
has comment: http://stackoverflow.com/comment/89692245
has comment: http://stackoverflow.com/comment/89710018
has comment: http://stackoverflow.com/comment/89690864
has comment: http://stackoverflow.com/comment/89693720
score: 0
accepted answer of: http://stackoverflow.com/q/51357343
type: AcceptedAnswer
has body: What you are looking for is the ParseInt method. Instead of using read in a loop and constructing your number, Serial.ParseInt does exactly that for you. The correct code would be: #include &lt;Servo.h&gt; Servo myservo; int pin = 9; void setup() { myservo.attach(9); pinMode(pin, OUTPUT); digitalWrite(pin, LOW); Serial.setTimeout(100); Serial.begin(9600); } void loop() { int number; if (Serial.available()) { number = Serial.parseInt(); myservo.write(number); delay(0.5); } } Notice that I set the serial timeout period to 100ms. This is to prevent parseInt to wait too much before deciding that it has read an entire int; otherwise when receiving a value (say, 42) it waits for about 1 second waiting for some other digits. The Python script also has a problem or two. First, you should wait for a bit after establishing the connection because every time the serial is opened the Arduino resets, so it won't read the first couple of values. You could also get a cleaner solution by printing some string from the Arduino when ready (as the last instruction of the setup function, for example) and wait for it in the Python script with readLine. Secondly, arduinoData.write takes a byte array as input, whereas you pass an int. You need to encode such int in bytes, first converting it to a string with str and then encoding it with encode. I got the following program working: import serial import time import random arduinoData = serial.Serial('/dev/ttyUSB0',9600) # Let Arduino some time to reset time.sleep(2) while True: low = 0; high = 180 ran_number = random.randint(low, high) print(ran_number) arduinoData.write(str(ran_number).encode()) time.sleep(1)
answers question: http://stackoverflow.com/q/51357343
has comment: http://stackoverflow.com/comment/89689041
has comment: http://stackoverflow.com/comment/89693158
has comment: http://stackoverflow.com/comment/89691299
has comment: http://stackoverflow.com/comment/89710719
type: Answer

http://stackoverflow.com/comment/101746937
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51406902
has text: so if I already have a myScript.m, then I can just do oc.myScript(7)?
score: 0

http://stackoverflow.com/comment/89674115
has text: Hi thanks for the answer! No I mean I need a circle at radius 150 ( which should represent the value 15 with a color), than a circle at radius 170 (which should represent the value 17 with another color), than a circle at radius 200 (which should represent the value 18 with another color again) and so on... Ideally it should look like a filled contour plot.
comment on: http://stackoverflow.com/q/51349254
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51478208
type: AnsweredQuestion
tagged with: list
score: 1
accepted answer: http://stackoverflow.com/a/51478275
upvote count: 1
type: Question
has body: I have a pandas DataFrame with a MultiIndex. I want to get a list which includes MultiIndex level0 and level1 like this [level0,[level1-1,level1-2,(...)]. For example: arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']] df = pd.DataFrame(np.random.randn(8), index=arrays,columns=['values']) df out: values bar one 2.171200 two -0.665047 baz one 0.474036 two 0.082408 foo one 1.820585 two 0.698537 qux one 1.163479 two 0.129044 I want to output a dataframe like this: output bar ['one','two'] baz ['one','two'] foo ['one','two'] qux ['one','two'] How? Thanks a lot.
possible better answer: http://stackoverflow.com/a/51478262
has answer: http://stackoverflow.com/a/51478262
has title: How to get pandas MultiIndex's values in the form of a list?
answer count: 2
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/51478275
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/89725039
score: 0
type: Comment
has text: That needs a lot more work, since the boxes need to be detected and then split. Maybe it would also be useful if you could also post what you wish to see as the output to the example image you have posted.
type: AnswerComment
comment on: http://stackoverflow.com/a/51362159

sidebar
type: Tag
tag name: sidebar
tags question: http://stackoverflow.com/q/51463166

http://stackoverflow.com/q/51437086
tagged with: python
has comment: http://stackoverflow.com/comment/89844287
tagged with: machine-learning
accepted answer: http://stackoverflow.com/a/51439205
type: AnsweredQuestion
tagged with: tflearn
type: Question
score: 0
has title: How to predict label only instead of probability
answer count: 1
tagged with: neural-network
has body: When i am predicting the output i am getting probability of each label (Example Output = [0.002345, 0.997655] ) instead of correct label. Is there any way to get the label only instead of their probability? import tflearn from tflearn.layers.core import input_data, dropout, fully_connected from tflearn.layers.estimator import regression from tflearn.data_utils import load_csv import numpy as np data, labels = load_csv("C:/Users/Animkush/Desktop/train.csv", categorical_labels=True, n_classes=2, target_column=30) def preprocess(data, col): for id in sorted(col, reverse=True): [r.pop(id) for r in data] return np.array(data, dtype=np.float32) ignore = [0] data = preprocess(data, ignore) network = input_data(shape=[None, 28], name="input") network = tflearn.fully_connected(network, 32, activation="relu") network = tflearn.fully_connected(network, 64, activation="relu") network = tflearn.fully_connected(network, 128, activation="relu") network = tflearn.fully_connected(network, 64, activation="relu") network = tflearn.fully_connected(network, 32, activation="relu") network = dropout(network, 0.8) network = fully_connected(network, 2, activation='softmax') network = regression(network, optimizer='adam', learning_rate=0.001, loss='categorical_crossentropy', name='targets') model = tflearn.DNN(network) model.fit(data, labels, n_epoch=100, batch_size=500, show_metric=True) p = np.array([[-3.043540624,-3.157307121,1.08846278,2.288643618,1.35980513,-1.064822523,0.325574266,-0.067793653,-0.270952836,-0.838586565,-0.414575448,-0.50314086,0.676501545,-1.692028933,2.000634839,0.666779696,0.599717414,1.725321007,0.28334483,2.102338793,0.661695925,0.435477209,1.375965743,-0.293803153,0.279798032,-0.145361715,-0.252773123,0.035764225]]) print(model.predict(p))
has answer: http://stackoverflow.com/a/51439205

http://stackoverflow.com/comment/89795607
comment on: http://stackoverflow.com/q/51411981
has text: It is, but not in a way that's documented or guaranteed to exist a year from now.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51401704
downvote count: 0
favorite count: 0
has title: converting a bz2 xml file to json in python
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
has body: I have downloaded a file from planet.openstreetmap.org which is a .xml.bz2 file. I cannot extract it onto my hard drive because of how big it is (73GB compressed). I know that I can read the file in python using the bz2 module, but what's the best way to convert it from XML to JSON? It just needs to be able to read from the bz2 file a little bit at a time and then write the JSON to a new file. I have tried looking at xmljson, but it doesn't seem to be able to stream
linked to: http://stackoverflow.com/q/29401068
answer count: 0
upvote count: 3
type: UnansweredQuestion
type: Question
score: 3
tagged with: http://stackoverflow.com/tag/json
duplicate of: http://stackoverflow.com/q/29401068

http://stackoverflow.com/comment/89910048
type: QuestionComment
score: 3
has text: `yield from islice(iterator, size)`, I believe you are running code meant for Python 3. You seem to be running that in Python 2.
comment on: http://stackoverflow.com/q/51470864
type: Comment

http://stackoverflow.com/a/51394607
has body: You might need to add "myproject/other" to the system path like following: import sys sys.path.append('yourpathstring') from model import BasicCNN
downvote count: 0
answers question: http://stackoverflow.com/q/51394079
has comment: http://stackoverflow.com/comment/136547157
score: 2
upvote count: 2
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51394079

http://stackoverflow.com/comment/113967563
type: Comment
comment on: http://stackoverflow.com/a/51465479
score: 0
type: AnswerComment
has text: Just a small comment: There is a typo: StandardScalar should be StandardScaler. I tried to suggest an edit, but it says the suggested edit queue is full

http://stackoverflow.com/a/51417605
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51417506
upvote count: 2
answers question: http://stackoverflow.com/q/51417506
type: AcceptedAnswer
has body: solution as follows: while True: encoder = hashlib.md5() OString = input("Input some text here &gt;") encoder.update(OString.encode()) hashedString = encoder.hexdigest() print(hashedString) Ostring = None hashedString = None Essentially you're rehashing the first value because encoder = hashlib.md5() object variable is outside of the while loop. Hope this helps.
type: Answer
score: 2

http://stackoverflow.com/q/51408344
has answer: http://stackoverflow.com/a/51410148
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/89788579
favorite count: 0
has comment: http://stackoverflow.com/comment/89787929
accepted answer: http://stackoverflow.com/a/51408670
has comment: http://stackoverflow.com/comment/89788979
has comment: http://stackoverflow.com/comment/89790988
has comment: http://stackoverflow.com/comment/89788364
tagged with: python
has title: pandas dataframe interleaved reordering
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/89788275
upvote count: 3
has body: Sorry for the not so good title and probably worse question. I need to perform a super simple operation on a pandas dataframe but I'm apparently missing how it is called and hence cannot find the correct keywords to search. Given a dataframe like a b c 0 0 46 14 1 0 7 14 2 0 46 19 3 0 7 19 4 1 46 14 5 1 7 14 6 1 46 19 7 1 7 19 I need to reorder rows to obtain a b c 0 0 46 14 4 1 46 14 1 0 7 14 5 1 7 14 2 0 46 19 6 1 46 19 3 0 7 19 7 1 7 19 Another simple and maybe less ambiguous example. I'd like to get from a 0 0 1 0 2 1 3 1 4 2 5 2 to a 0 0 2 1 4 2 1 0 3 1 5 2 EDIT: some clarification about the complete picture For what it's worth, the dataframe in the first example is the cartesian product of the dictionary 'a': [0, 1], 'b': array([46, 7]), 'c': array([14, 19])} i.e. [{'a': 0, 'b': 46, 'c': 14}, {'a': 0, 'b': 7, 'c': 14}, {'a': 0, 'b': 46, 'c': 19}, {'a': 0, 'b': 7, 'c': 19}, {'a': 1, 'b': 46, 'c': 14}, {'a': 1, 'b': 7, 'c': 14}, {'a': 1, 'b': 46, 'c': 19}, {'a': 1, 'b': 7, 'c': 19}] I needed to sort it so that for each combination of parameters all a values are grouped and cycled together.
has comment: http://stackoverflow.com/comment/89788393
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/89788457
has comment: http://stackoverflow.com/comment/89788422
has answer: http://stackoverflow.com/a/51408670
possible better answer: http://stackoverflow.com/a/51410148

http://stackoverflow.com/comment/89714643
type: AnswerComment
comment on: http://stackoverflow.com/a/51352489
has text: To accentuate the problem, I took PM 2Ring's code and doubled the canvas size (800 x 600), then reduced the after method delay back to the original 15ms. The clipping is pretty bad this way. Then I took jasonharper's suggestion and moved the chi and cwid lines down to right after the dash.grid call. This had no effect.
type: Comment
score: 0

http://stackoverflow.com/comment/89673802
type: Comment
has text: @Aran-Fey they do not - but this is another mistake :)
comment on: http://stackoverflow.com/q/51350600
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89789448
type: Comment
has text: Yes, both the terminal and the Pycharm python console are using 3.7
comment on: http://stackoverflow.com/q/51408828
score: 0
type: QuestionComment

http://stackoverflow.com/a/51332304
upvote count: 1
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51332269
has body: You are using discovery before it is declared on the function call. Also, as you declare it in the function, it will be destroyed at the end of it and wont be available in the main scope.
score: 0

http://stackoverflow.com/q/51479198
has answer: http://stackoverflow.com/a/51479280
tagged with: python-3.x
has body: Here is the code of my application I am trying to run: from flask import Flask, request, render_template import json import requests import socket from datetime import datetime import pickle import time import pandas as pd import numpy as np @app.route('/index.html') def index(): return render_template('index.html') @app.route('/tables.html') def tables(): return render_template('tables.html') @app.route('/flot.html') def flot(): return render_template('flot.html') @app.route('/morris.html') def morris(): return render_template('morris.html') @app.route('/forms.html') def forms(): return render_template('forms.html') @app.route('/panels-wells.html') def panelswells(): return render_template('panels-wells.html') @app.route('/buttons.html') def buttons(): return render_template('buttons.html') @app.route('/notifications.html') def notifications(): return render_template('notifications.html') @app.route('/typography.html') def typography(): return render_template('typography.html') @app.route('/icons.html') def icons(): return render_template('icons.html') @app.route('/blank.html') def blank(): return render_template('blank.html') @app.route('/login.html') def login(): return render_template('login.html') if __name__ == '__main__': app.run(host='0.0.0.0', port=8080, debug=True, threaded=True) pass Here is how I ran it: C:\Users\aims\Desktop\forex>python forex_app.py * Serving Flask app "forex_app" (lazy loading) * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: on * Restarting with stat * Debugger is active! * Debugger PIN: 122-288-656 * Running on http://0.0.0.0:8080/ (Press CTRL+C to quit) * Detected change in 'C:\\Users\\aims\\Desktop\\forex\\forex_app.py', reloading * Restarting with stat * Debugger is active! * Debugger PIN: 122-288-656 After hitting the url as: http://0.0.0.0:8080 or even http://0.0.0.0:8080/index.html I see the following screen: Kindly, help me wh…
tagged with: python
has answer: http://stackoverflow.com/a/51479277
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/51479277
tagged with: flask
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/51479280
has title: Flask application not giving output after running Python35

http://stackoverflow.com/q/51395853
tagged with: python
has comment: http://stackoverflow.com/comment/89763435
tagged with: jupyter-notebook
has title: Prediction and forecasting with Python tensorflow
upvote count: 1
downvote count: 1
tagged with: tensorflow
type: Question
tagged with: algorithm
has body: I have created a prediction model and used RNN in it offered by the tensorflow library in Python. Here is the complete code I have created and tried: Jupyter Notbook of the Code But I have doubts. 1) Whether RNN is correct for what I am trying to predict? 2) Is there a better algorithm I can try? 3) Can anyone suggest me how I can give multiple inputs and get the necessary output using tensorflow model? Can anyone guide me please. I hope I am clear on my points. Please do tell me if anything else required.
score: 0
has answer: http://stackoverflow.com/a/51401088
answer count: 1
has comment: http://stackoverflow.com/comment/89763072
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/a/51459622
type: Answer
has comment: http://stackoverflow.com/comment/89890092
answers question: http://stackoverflow.com/q/51457993
has comment: http://stackoverflow.com/comment/89889501
downvote count: 0
upvote count: 6
has comment: http://stackoverflow.com/comment/89889276
has comment: http://stackoverflow.com/comment/89889665
has comment: http://stackoverflow.com/comment/89889221
has comment: http://stackoverflow.com/comment/89889575
has body: You can write a PPM file like this without OpenCV or numpy or anything that hates you :- import array width,height = 800,600 PPMheader = 'P6\n' +str(width) + ' ' +str(height) + '\n255\n' # Create and fill a red PPM image image = array.array('B', [255, 0, 0] * width * height) # Save as PPM image with open('result.ppm', 'wb') as f: f.write(bytearray(PPMheader, 'ascii')) image.tofile(f) I wrote a really simplistic PPM reader too - it only reads 24-bit P6 PPM files matching the ones written above. I guess it could be fleshed out to handle comments, 16-bit data and greyscale data, but it's a start: #!/usr/local/bin/python3 import array def ppmread(filename): with open(filename, 'rb') as f: # Read first line - expecting "P6" line = f.readline().decode('latin-1') if not line.startswith('P6'): print("ERROR: Expected PPM file to start with P6") return False # Read second line - expecting "width height" line = f.readline().decode('latin-1') dims = line.split() width,height=int(dims[0]),int(dims[1]) # Read third line - expecting "255" line = f.readline().decode('latin-1') if not line.startswith('255'): print("ERROR: Expected 8-bit PPM with MAXVAL=255") return False image= f.read(width*height*3) ppmread('test.ppm') Convert PPM to PNG or JPEG with ImageMagick in Terminal: convert result.ppm -auto-level image.png Or: convert result.ppm -resize 1024x768 image.jpg Likewise, convert JPEG to PPM with ImageMagick in Terminal: convert image.jpg -depth 8 image.ppm
has comment: http://stackoverflow.com/comment/89889435
score: 6

http://stackoverflow.com/comment/89719665
comment on: http://stackoverflow.com/q/51374080
score: 0
has text: I get a bit different output, can you check it?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51378878
linked to: http://stackoverflow.com/q/332289
score: 0
tagged with: 3d
tagged with: matplotlib-basemap
has comment: http://stackoverflow.com/comment/89758897
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89731310
tagged with: python
has body: I have plotted axis 3d using plot_trisurf but i am not able to plot this with earth map /basemap. some of the questions: How i can plot same figure as above in Map in 3d? How i can increase my figure size? fig.size(8,6) function is not working .
has comment: http://stackoverflow.com/comment/89729446
answer count: 0
has comment: http://stackoverflow.com/comment/89750288
has title: How to plot this 3d Axes matplotlib with earth map plot?
tagged with: plot
type: Question
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/89731284

http://stackoverflow.com/q/51367038
has title: I can't openning a session in ALM 12.5x
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51410787
has comment: http://stackoverflow.com/comment/89707057
tagged with: alm
has comment: http://stackoverflow.com/comment/89707221
tagged with: hp-quality-center
answer count: 1
has body: I'am new in ALM. I just read some guides from REST API and try to repeat this. But I face up to the situation. In my last request I have 401 return (User not authenticated). What am I doing wrong? import requests from requests.auth import HTTPBasicAuth url = "https://almalmqc1250saastrial.saas.hpe.com" login = "+++++++" password = "+++++" cookies = dict() headers = {} r = requests.get(url + "/qcbin/rest/is-authenticated") print(r.status_code, r.headers.get('WWW-Authenticate')) r = requests.get(url + "/qcbin/authentication-point/authentication", auth=HTTPBasicAuth(login, password), headers=headers) print(r.status_code, r.headers) cookie = r.headers.get('Set-Cookie') LWSSO_COOKIE_KEY = cookie[cookie.index("=") + 1: cookie.index(";")] cookies['LWSSO_COOKIE_KEY'] = LWSSO_COOKIE_KEY print(cookies) r = requests.post(url + "/qcbin/rest/site-session", cookies=cookies) print(r.status_code, r.headers)
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51410787
tagged with: python

http://stackoverflow.com/a/51329656
has body: You could use a generator iterating a window over the strings your current implementation yields. Sth. like (hex_str[i:i + 3] for i in range(len(hex_str) - window_size + 1)) Using len and set you could count the number of different characters in the slice. Although in your example it might be easier to just compare all 3 characters.
type: Answer
answers question: http://stackoverflow.com/q/51328929
score: 0

http://stackoverflow.com/comment/89792978
comment on: http://stackoverflow.com/q/51410508
score: 0
type: Comment
type: QuestionComment
has text: why is rolling not the solution?

http://stackoverflow.com/comment/89709328
type: QuestionComment
score: 0
has text: @Roshan It returns the User object.
type: Comment
comment on: http://stackoverflow.com/q/51367753

http://stackoverflow.com/q/51480786
tagged with: python
has answer: http://stackoverflow.com/a/51480857
type: AnsweredQuestion
downvote count: 1
type: Question
upvote count: 0
score: -1
accepted answer: http://stackoverflow.com/a/51480857
tagged with: command-line-interface
has title: Argparse won't parse any arguments I pass in the command line
tagged with: argparse
answer count: 1
has comment: http://stackoverflow.com/comment/89933148
favorite count: 0
tagged with: python-3.x
has body: I'm trying to run my program in Terminal: py program.py -t and it's not setting the boolean to False. From what I can see, all of my code looks correct. isTitle = True a = argparse.ArgumentParser(prog='program.py', usage='%(prog) [options]', description='The fooiest of bar') a.add_argument('-t', '--title', action='store_const', const=False, dest='isTitle', help='show title') r = a.parse_args() I have a statement after the parse_args that prints the isTitle boolean to verify it's been set, and it always returns True. Do you guys have any recommendations? I can add more code/diagnostic statements if need be. Thank you!

http://stackoverflow.com/a/51422559
has comment: http://stackoverflow.com/comment/89816435
answers question: http://stackoverflow.com/q/51422519
has comment: http://stackoverflow.com/comment/89821837
has body: Simply replace math.exp by np.exp. The former is a Python built-in which only understands scalars (hence the error message). Also note that np.append() returns the result, and does not modify its arguments. So you'll need to assign the result back to s. Also note that repeatedly appending to a NumPy array is an anti-pattern--you should allocate the entire array at the start.
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51422519
type: Answer
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/51362250
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89698888
has body: I'm trying to rotate a image in python using cv2. I have so far just copied examples from the net, but can't get them to work as intended. My code is as follows: import cv2 image = cv2.imread('test.jpg') (h, w) = image.shape[:2] center = (w / 2, h / 2) M = cv2.getRotationMatrix2D(center, 270, 1.0) rotated = cv2.warpAffine(image, M, (h, w)) cv2.imshow("rotated", rotated) cv2.waitKey(0) cv2.destroyAllWindows() original image: and my results: I'm using python3.7 through Thonny. EDIT and ANSWER: Thanks to @jeru-luke for pointing me in the right direction. Code below modified from this post by Adrian Rosebrock. import cv2 import imutils image = cv2.imread('test.jpg') rotated = imutils.rotate_bound(image, 90) cv2.imshow("Rotated (Correct)", rotated) cv2.waitKey(0) cv2.destroyAllWindows()
tagged with: opencv
answer count: 0
has comment: http://stackoverflow.com/comment/89696903
type: Question
has comment: http://stackoverflow.com/comment/89697735
has comment: http://stackoverflow.com/comment/89700203
downvote count: 0
has comment: http://stackoverflow.com/comment/89698705
score: 1
has title: Rotating image in python (cv2) won't center
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/89685473
comment on: http://stackoverflow.com/q/51356556
has text: Possible duplicate of [My regular expression matches too much. How can I tell it to match the smallest possible pattern?](https://stackoverflow.com/questions/7014903/my-regular-expression-matches-too-much-how-can-i-tell-it-to-match-the-smallest)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89933108
type: Comment
type: QuestionComment
has text: This feels a lot like you want someone to help with a complete design. You will probably not get much traction with this. Break your problem down into pieces and then if you run into problems ask about that focused problem. If this is not the case, it's hard to discern the actual question here. Maybe you can [edit] the question and make it clear what specific problem you have.
score: 2
comment on: http://stackoverflow.com/q/51481114

http://stackoverflow.com/q/51383664
tagged with: instagram
answer count: 3
tagged with: sql
has answer: http://stackoverflow.com/a/51385818
tagged with: python
has body: I get this error when I run the script bellow, I am able to connect to Instagram API and to print nr of followers: mysql.connector.errors.InterfaceError: Failed executing the operation; Could not process parameters followers = str(followers) followersdata = [followers] conn = mysql.connector.connect(user='root', password='XXX', host='127.0.0.1', database='InstagramStore') cursor = conn.cursor() q = """INSERT INTO InstagramFollowers (followers) VALUES (%s)""" cursor.executemany(q, followersdata) conn.commit()
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51384008
has title: Cannot insert data from Python List into SQL
type: Question
has answer: http://stackoverflow.com/a/51385094
score: 0

http://stackoverflow.com/comment/89680303
type: QuestionComment
comment on: http://stackoverflow.com/q/51353624
has text: Stick it in the response when rendering the template.
score: 0
type: Comment

http://stackoverflow.com/q/51391713
has comment: http://stackoverflow.com/comment/89755514
accepted answer: http://stackoverflow.com/a/51391806
has title: Efficient way of writing numpy arrays to file in Python
has answer: http://stackoverflow.com/a/51391878
upvote count: 1
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51391878
score: 1
has answer: http://stackoverflow.com/a/51391796
has comment: http://stackoverflow.com/comment/89755891
has comment: http://stackoverflow.com/comment/89756126
has comment: http://stackoverflow.com/comment/89755937
tagged with: numpy
answer count: 3
has body: The data that I process is ~ 6 Million and it takes a lot of time to write to a file. How do I improve it ? The following are the two approaches that I tried: import numpy as np import time test_data = np.random.rand(6000000,12) T1 = time.time() np.savetxt('test',test_data, fmt='%.4f', delimiter=' ' ) T2 = time.time() print "Time:",T2-T1,"Sec" file3=open('test2','w') for i in range(6000000): for j in range(12): file3.write('%6.4f\t' % (test_data[i][j])) file3.write('\n') T3 = time.time() print "Time:",T3-T2,"Sec" Time: 56.6293179989 Sec Time: 115.468323946 Sec I am dealing with atleast 100 files like this and the total time is a lot, please help. Also, I am not writing in .npy or compressed format as I need to read them in matlab and do further processing.
has answer: http://stackoverflow.com/a/51391806
has comment: http://stackoverflow.com/comment/89767729
downvote count: 0
has comment: http://stackoverflow.com/comment/89755918
favorite count: 0
has comment: http://stackoverflow.com/comment/89755409
has comment: http://stackoverflow.com/comment/89755582
tagged with: python
has comment: http://stackoverflow.com/comment/89755849
has comment: http://stackoverflow.com/comment/89755442

http://stackoverflow.com/a/51463517
score: 1
type: Answer
has body: Solution should be simplify by specify column for check max values by DataFrameGroupBy.idxmax: np.random.seed(234) arrays = [np.array(['bar', 'bar', 'bar', 'baz', 'baz','foo', 'foo', 'qux', 'qux']),np.array(['AA', 'AB', 'AC','BA', 'BB', 'CA', 'CB', 'DA', 'DB'])] df = pd.DataFrame(np.random.randn(9, 1), index=arrays) print (df) 0 bar AA 0.818792 AB -1.043551 AC 0.350901 baz BA 0.921578 BB -0.087382 foo CA -3.128885 CB -0.969733 qux DA 0.934666 df = df.loc[df.groupby(level=0)[0].idxmax()] print (df) 0 bar AA 0.818792 baz BA 0.921578 foo CB -0.969733 qux DA 0.934666
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51462766
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51462766

http://stackoverflow.com/q/51381874
has comment: http://stackoverflow.com/comment/89735665
has comment: http://stackoverflow.com/comment/89735680
tagged with: return
has comment: http://stackoverflow.com/comment/89735826
has title: second return value from first function is printing twice
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89735808
has comment: http://stackoverflow.com/comment/89735731
upvote count: 1
has comment: http://stackoverflow.com/comment/89735789
has body: I am attempting to simply print out the values(ports) that I have appended to their respective lists. I am separating this by tcp and udp. My dictionary that I am passing to _does_port_dict_have_type looks like this {'22': 'TCP', '53': 'UDP', '31337': 'TCP', '80': 'TCP', '515': 'UDP'} Here is my code x = _expected_ports_type_to_dict(ET.parse('scanme.nmap.org.xml')) TCP_LIST = [] UDP_LIST = [] def _does_port_dict_have_type(port_dict): for port, typee in port_dict.iteritems(): if (typee is not None) and len(typee) &gt; 0: if typee == "TCP": TCP_LIST.append(port) else: UDP_LIST.append(port) else: pass return ','.join(UDP_LIST), ','.join(TCP_LIST) UDP = _does_port_dict_have_type(x)[0] TCP = _does_port_dict_have_type(x)[1] def print_value(func): print func print_value(UDP) print_value(TCP) Here is my output 80,31337,22 515,53,515,53 The TCP variable or the [1] position of _does_port_dict_have_type() is the value that always shows up twice. It doesn't matter if I pass it UDP_LIST or TCP_LIST. Does anyone have any ideas to why this may be happening?
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89735940
tagged with: function
has comment: http://stackoverflow.com/comment/89735721
has comment: http://stackoverflow.com/comment/89735624
score: 0
has comment: http://stackoverflow.com/comment/89735806
has comment: http://stackoverflow.com/comment/89735679
has answer: http://stackoverflow.com/a/51382131
answer count: 1
has comment: http://stackoverflow.com/comment/89735666
favorite count: 0

http://stackoverflow.com/q/51383505
upvote count: 3
accepted answer: http://stackoverflow.com/a/51390345
answer count: 2
favorite count: 0
has answer: http://stackoverflow.com/a/53504761
has answer: http://stackoverflow.com/a/51390345
has title: Field override for bdh() in pdblp
tagged with: python
tagged with: blpapi
type: AnsweredQuestion
downvote count: 0
has body: Bloomberg help isn't very helpful for their API. Can anyone please explain how to replace PX_LAST with the dividend adjusted price field. I have attempted the following but have been unsuccessful import pdblp con = pdblp.BCon() con.start() df2 = con.bdh(['NQ1 Index', 'DM1 Index'], ['PX_LAST'], '20061227', '20061231', elms=[("periodicityAdjustment", "ACTUAL")])
tagged with: pdblp
type: Question
score: 3
possible better answer: http://stackoverflow.com/a/53504761
tagged with: bloomberg

http://stackoverflow.com/a/51390785
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51389349
answers question: http://stackoverflow.com/q/51389349
has body: Your current attempt at reverse() creates brand new OptionMenus - and never actually displays them. You don't actually need to touch the OptionMenus themselves, just swap the values in the two variables they are tied to: temp = self.currency_1.get() self.currency_1.set(self.currency_2.get()) self.currency_2.set(temp)
score: 0

http://stackoverflow.com/a/51435840
has body: Found the solution. Under Tools > Options > Python > Advanced there is a "Committed by typing the following characters: {}.,:;+-*/%&amp;|^~=&lt;>#@\". I thought these were characters that opened up intellisense dropdown suggestions but rather commit the intellisense option. I just deleted all the characters and it fixed the issue. I still haven't found the answer to my second question but since the title is named after the first issue, I'll open up a new topic for that question if I do a more thorough search and can't figure it out.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51435429

http://stackoverflow.com/a/51335782
has comment: http://stackoverflow.com/comment/89646564
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/51335083
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51335083
has body: You aren't obligated to have the inner loop: for row_cells in sheet.iter_rows(min_col=1, max_col=8): print('%s: cell.value=%s' % (row_cells[0], row_cells[0].value)) print('%s: cell.value=%s' % (row_cells[-1], row_cells[-1].value)) A better approach might be to zip the iterators over just those two columns: for c1, c8 in zip(sheet.iter_rows(min_col=1, max_col=1), sheet.iter_rows(min_col=8, max_col=8)): print('%s: cell.value=%s' % (c1, c1.value)) print('%s: cell.value=%s' % (c8, c8.value))
type: Answer

http://stackoverflow.com/q/51388911
score: -1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51388929
downvote count: 2
has comment: http://stackoverflow.com/comment/89749987
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51388929
has comment: http://stackoverflow.com/comment/89749808
has title: How to detect and remove trailing backslash from end of string?
answer count: 1
tagged with: string
favorite count: 0
has body: An entry of any file has a trailing backslash cache[path] = file.read() for file_name, multi_line_content in cache.items(): for line in multi_line_content.splitlines(): // this line may or maynot have trailing backslash Ex: dsf dff dfdf \ cvcs dsd sdds\ How to process this line, detect trailing backslash and remove it, before the copying the complete line as string?
tagged with: python

http://stackoverflow.com/a/51416192
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51415997
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89804063
has body: import re new_data = '' for line in data.splitlines(): if '.' in line: mod_line = '' for word in line.split(): if '.' in word: try: float(word) word = re.sub(r'(\d\d)\.', r'.\1', word) except: pass mod_line += word + ' ' new_data += mod_line.rstrip() +'\n' else: new_data += line + '\n' new_data = new_data.rstrip() print (new_data) Output ILINE VRTX 1 5450.5778564453125 38009.05201171875 -15000 VRTX 2 5451.8449072265625 38007.65451171875 -15000 VRTX 3 5453.1091650390625 38006.25970703125 -15000 SEG 1 2 SEG 2 3 ILINE VRTX 136 5512.9584606933594 37990.15443359375 -15000 VRTX 137 5512.9382849121094 37988.41880859375 -15000 VRTX 138 5512.9057849121094 37986.61892578125 -15000 SEG 136 137 SEG 137 138
has comment: http://stackoverflow.com/comment/89803723

http://stackoverflow.com/comment/89840252
comment on: http://stackoverflow.com/q/51433622
score: 0
type: Comment
type: QuestionComment
has text: The image with 11 nodes that you linked to looks fine. Can you share the image that you are calling ugly? And what makes it so? Thanks

http://stackoverflow.com/q/51448642
type: Question
linked to: http://stackoverflow.com/q/8560166
accepted answer: http://stackoverflow.com/a/51460517
has title: Installing all .msi files within a folder
tagged with: powershell
tagged with: windows-installer
answer count: 2
has comment: http://stackoverflow.com/comment/89868320
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51460517
has comment: http://stackoverflow.com/comment/89873929
tagged with: python
has comment: http://stackoverflow.com/comment/89867992
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51450691
has body: I'm trying to write a powershell script that I am kicking off from a python script that will allow me to go through and install each .msi file that is contained within a certain folder. This is what I have so far: $msiFiles = Get-ChildItem -Path "***PATH TO FOLDER***" -Recurse -Include *.msi foreach($file in $msiFiles) { Write-Host "$file is being installed" Start-Process "msiexec.exe" -arg "/I $file /qb ADDLOCAL=ALL ALLUSERS=TRUE" -Wait Write-Host "$file is finished being installed" } I want to install these msi's in silent mode so I don't see or need ant GUI interaction. When it goes to install the msi's I get a pop up from the installer with all the possible commands to use to install stuff, but it doesn't actually install it. What is the proper command to install these in silent mode?
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/89891258
possible better answer: http://stackoverflow.com/a/51450691
has comment: http://stackoverflow.com/comment/89868016

http://stackoverflow.com/a/51330317
upvote count: 24
has body: I believe you're looking for groupby. You can find documentation here df.groupby('Column1')['Column2'].sum() Column1 Column2 1 44 2 65 3 30 4 18
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51330281
type: Answer
accepted answer of: http://stackoverflow.com/q/51330281
score: 24

http://stackoverflow.com/comment/89753505
has text: Might be nice to add a complete implementation with [FuzzySet](https://pythonhosted.org/fuzzpy/fuzz.fset.FuzzySet-class.html#intersection) if you want to keep the fuzzy matching OP used
type: AnswerComment
comment on: http://stackoverflow.com/a/51390656
type: Comment
score: 1

http://stackoverflow.com/comment/115771517
has text: Thanks for the benchmarks! Folks should definitely measure on their particular machine. I have a ~300 MB text file, with a line count in the low millions, and on my 2019 MacBook Pro, `f.read().splitlines()` (regardless of the `keepends` parameter) is about 2 seconds slower than `f.readlines()`.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51480083
type: AnswerComment

http://stackoverflow.com/comment/89718521
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51358490
has text: @ jezrael i have improved the question with week missing and quarter missing how can i achieve this one.Can you do it.

http://stackoverflow.com/q/51362314
accepted answer: http://stackoverflow.com/a/51506056
has answer: http://stackoverflow.com/a/51469272
score: 7
has comment: http://stackoverflow.com/comment/89857360
answer count: 2
has body: I have two blocks that call the same method with same variables. I want to call the method only once, but the result is then outsite the scope of the block tags. I've tried calling this method in the parent template header.html and with a with tag, but nothing seems to work. This is the layout: {% extends "header.html" %} {% load navigation_tags %} {% block header %} {% get_section site=site as section %} {% include "foobar.html" with section=section %} {% endblock header %} {% block navigation %} &lt;nav&gt; &lt;div class="container"&gt; {% get_section site=site as section %} {% navigation section.slug %} &lt;/div&gt; &lt;/nav&gt; {% endblock navigation %} navigation_tags.py @register.assignment_tag def get_parent_section(site): if site.id == settings.FOOBAR_SITE_ID: section = Section.objects.get(id=settings.FOOBAR_SECTION_ID) else: # This is also a section instance. return site.default_section
has title: Variable context between two blocks in Django templates?
has comment: http://stackoverflow.com/comment/89697704
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89859373
has comment: http://stackoverflow.com/comment/89859985
tagged with: python
tagged with: templates
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89697300
has answer: http://stackoverflow.com/a/51506056
has comment: http://stackoverflow.com/comment/89724340
has comment: http://stackoverflow.com/comment/89699006
tagged with: django
upvote count: 7
possible better answer: http://stackoverflow.com/a/51469272
type: Question

http://stackoverflow.com/comment/89663369
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51345001
has text: not sure at all. literally my first attempt. Just tried this and it worked. Thanks friend!

http://stackoverflow.com/q/51413855
has comment: http://stackoverflow.com/comment/89834433
tagged with: loops
has body: list = [] for df in lp: list.append(list(df.loc[985191])) list(list of list) T = pd.DataFrame(list) Hi I have this code to python but when I returned, shows me an error IndentationError: unindent does not match any outer indentation level what can be the error?
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51413875
score: -2
downvote count: 4
linked to: http://stackoverflow.com/q/45621722
tagged with: indentation
answer count: 1
has comment: http://stackoverflow.com/comment/89799109
favorite count: 0
duplicate of: http://stackoverflow.com/q/45621722
accepted answer: http://stackoverflow.com/a/51413875
has comment: http://stackoverflow.com/comment/89827737
has comment: http://stackoverflow.com/comment/89834004
linked to: http://stackoverflow.com/q/492387
tagged with: python
has title: What does mean this error in python?
has comment: http://stackoverflow.com/comment/89839021
upvote count: 2
has comment: http://stackoverflow.com/comment/89799094

http://stackoverflow.com/comment/89850516
type: AnswerComment
score: 1
type: Comment
has text: @gyx-hh: depends on whether you want it as a percentage or not. Usually, in mathematics you don't put *100%*, you express percentages as values in [0, 1], but that's how the OP defined it
comment on: http://stackoverflow.com/a/51440114

http://stackoverflow.com/a/51408724
answers question: http://stackoverflow.com/q/51408615
type: AcceptedAnswer
downvote count: 0
has body: You can use subprocess.run import subprocess as sub args = ["vcsi", r"C:\users\testuser\dropbox\python\testdata\test.mp4", "-t", "-w 850", "-g 3x5", "--end-delay-percent 20", r"-o C:\temp\output.png"] cp = sub.run(args)
type: Answer
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/51408615

http://stackoverflow.com/comment/89693284
score: 0
type: Comment
type: QuestionComment
has text: Yes.SALES will be always there.
comment on: http://stackoverflow.com/q/51360034

http://stackoverflow.com/q/51451594
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/89873431
answer count: 1
has title: How to replace in pandas dataframe with for loop from lists?
type: UnansweredQuestion
tagged with: python
tagged with: loops
type: Question
has answer: http://stackoverflow.com/a/51451627
tagged with: dataframe
has body: I'm trying to replace a single column values row by row (for now settling with overall dataframe replace) based off of a list of words to replace if words are found in a different list. They have matched length so indexing should work. Ex. If "friend" in list one, replace with "buddy" from list two. data = {'col_1': [3, 2, 1, 0], 'col_2': ['a', 'b', 'c', 'd']} pd.DataFrame.from_dict(data) numlist = [1,2,3] abclist = ["z","x","y"] for n in numlist: pd.DataFrame.replace(n, abclist[numlist.index(n)]) Getting error: Please Help TypeError Traceback (most recent call last) &lt;ipython-input-12-4e44f23fd530&gt; in &lt;module&gt;() 6 7 for n in numlist: ----&gt; 8 pd.DataFrame.replace(n,abclist[numlist.index(n)]) 9 DataFrame /anaconda3/lib/python3.6/site-packages/pandas/core/frame.py in replace(self, to_replace, value, inplace, limit, regex, method) 3790 def replace(self, to_replace=None, value=None, inplace=False, limit=None, 3791 regex=False, method='pad'): -&gt; 3792 return super(DataFrame, self).replace(to_replace=to_replace, 3793 value=value, inplace=inplace, 3794 limit=limit, regex=regex, TypeError: super(type, obj): obj must be an instance or subtype of type

http://stackoverflow.com/comment/89807719
has text: Do you really need to use Python 2 for this? Moving to Python 3 should definitely be in your near-term roadmap anyway, and will solve this issue at least partially out of the box. Try Python 3.6 or newer for a slightly overhauled version of the `email` library.
type: QuestionComment
comment on: http://stackoverflow.com/q/51395752
score: 0
type: Comment

http://stackoverflow.com/comment/89853731
has text: Why is the distance between 0 and 3 not equal to distance from 3 to 0?
comment on: http://stackoverflow.com/q/51418113
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/68491808
downvote count: 0
score: 1
has body: You would need to put your views.py file in your weather folder. Make sure it is in the right weather folder, I am guessing you have two weather folders. Also make sure these codes are right; #Path : the_weather/weather/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index), #the path for our index view ] #Path : the_weather/weather/views.py from django.shortcuts import render from django.contrib import admin def index(request): return render(request, 'weather/index.html') #returns the index.html template
upvote count: 1
answers question: http://stackoverflow.com/q/51327457
type: Answer

http://stackoverflow.com/comment/89762663
comment on: http://stackoverflow.com/a/51394825
has text: There is not need to call `list` on a `set` just to pass to `sorted`, which accepts any iterable, (it will be converted to a list internally anyway). You could just use a set-comprehension as well. `{n for l in numbers for n in l}`
type: AnswerComment
type: Comment
score: 3

http://stackoverflow.com/comment/89857711
has text: @EbramSherif Check your git settings. Maybe you have windows line endings. https://stackoverflow.com/questions/10418975/how-to-change-line-ending-settings
type: Comment
comment on: http://stackoverflow.com/a/51423509
score: 0
type: AnswerComment

http://stackoverflow.com/q/51428359
has title: Python: Speed up matching in multiple lists
accepted answer: http://stackoverflow.com/a/51428466
favorite count: 0
tagged with: tuples
type: Question
linked to: http://stackoverflow.com/q/993984
tagged with: python
has answer: http://stackoverflow.com/a/51428466
has body: I have four lists like these: L = [ (1,2), (3,5), (6,10), (7,8) ] M = [ (1,3), (8,9), (12,13) ] N = [ (6,10), (3,4), (5,6), (10,11), (12,13) ] T = [ (6,10) , (1,4) ] I want to check the presence/absence of every tuple of T inside L, M, and N: [[True, False, True], [False, False, False]] The following works but it is incredibly inefficient when the size of T, L, M, and N grows. [[ y in x for x in [L, M, N] ] for y in T ] What is the most efficient way to speed up this for large lists?
tagged with: list
upvote count: 1
possible better answer: http://stackoverflow.com/a/51428596
has answer: http://stackoverflow.com/a/51509853
has answer: http://stackoverflow.com/a/51428596
tagged with: performance
tagged with: matching
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51428705
downvote count: 0
score: 1

http://stackoverflow.com/a/51559801
has body: The problem is here: array_type_out(*Wout). That takes Wout and creates an array_type_out instance but it copies the values from Wout, so Wout and array_type_out(*Wout) will be independent (modifying one won't impact the other). The solution would be to construct the output np arrays (Wout and Vout) out of the data that has been modified by lib.modwtj (array_type_out(*Wout) and array_type_out(*Vout) that should have been saved into variables). I prepared a "small" example. modwtj.c: #if defined(_WIN32) # define DLL_EXPORT __declspec(dllexport) #else # define DLL_EXPORT #endif DLL_EXPORT void modwtj(const double *vIn, int n, int j, int l, const double *ht, const double *gt, double *wOut, double *vOut) { int batches = n / l, last = n % l, i = 0; for (i = 0; i &lt; batches; i++) for (int k = 0; k &lt; l; k++) { wOut[i * l + k] = vIn[i * l + k] + ht[k] + j; vOut[i * l + k] = vIn[i * l + k] + gt[k] + j; } for (int k = 0; k &lt; last; k++) { wOut[i * l + k] = vIn[i * l + k] + ht[k] + j; vOut[i * l + k] = vIn[i * l + k] + gt[k] + j; } } code.py: import sys import ctypes import numpy as np modwtj_lib = ctypes.CDLL("libmodwtj.so") modwtj_func = modwtj_lib.modwtj modwtj_func.argtypes = [ ctypes.POINTER(ctypes.c_double), ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double) ] modwtj_func.restype = None data_array_dim = 10 # Size for v_in, w_out, v_out arrays coeff_array_dim = 4 # Size for ht, gt arrays scale = 1 double_data_array = ctypes.c_double * data_array_dim double_coeff_array = ctypes.c_double * coeff_array_dim def print_ctypes_array(array, array_name=None): print("{:s}en: {:d}:\n {:s}".format(str(array_name) + " - l" if array_name else "L", len(array), ", ".join(["{:.3f}".format(item) for item in array]))) def print_ctypes_arrays(*arrays_data): print("\nPrinting ctypes arrays...") for array_data in arrays_data: array, array_name = array_data print_ctyp…
answers question: http://stackoverflow.com/q/51481025
type: Answer
score: 0

http://stackoverflow.com/q/51460320
tagged with: pandas
tagged with: python
answer count: 0
type: UnansweredQuestion
has title: using pandas apply() to create new columns based on condition
has body: I have a pandas DataFrame that looks like this: Col1 Col2 0 A code1 1 B code1 2 C code2 3 A code1 I want to add a column to the DataFrame for each unique code value in Col 2 and put a 1 in the column that matches the code value and a 0 in all other newly-created columns. In other words, I want a DataFrame that looks like this: Col1 Col2 Code1 Code2 0 A code1 1 0 1 B code1 1 0 2 C code2 0 1 3 A code1 1 0 The following code works for this small data sample: def assign_code1(row): if row['Col2'] == 'code1' : return 1 else :return 0 def assign_code2(row): if row['Col2'] == 'code2' : return 1 else :return 0 df['Code1'] = df.apply(assign_code1 ,axis=1) df['Code2'] = df.apply(assign_code2 ,axis=1) However, I really hate this code because: I have to know all the values in Col2; I have to write a separate function for each unique value in Col2; and I have read in other posts that using apply() to create new columns is frowned upon (though I didn't fully understand why - I have only been working with pandas for a couple of weeks). I'd like to have code that obtains a list of all the unique values in Col2, creates a column for each, and correctly populates all the 1's and 0's in those columns. Is there an elegant way to do this?
type: Question
duplicate of: http://stackoverflow.com/q/37292872
has comment: http://stackoverflow.com/comment/89890294
has comment: http://stackoverflow.com/comment/89890025
tagged with: dataframe
linked to: http://stackoverflow.com/q/37292872
score: 0

http://stackoverflow.com/a/51584312
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51449038
score: 1
upvote count: 1
has body: I focused my answer on the strange fact that you can get around the problem using a SOCKS5 proxy. (I believe you. There was no time to ask you for details.) You verified that your example solution by SOCKS5 works for you. Django uses the same smtplib and you can easily wrap it the same way by this code added to wsgi.py. import smtplib import socks # it is the package SocksiPy or PySocks socks.setdefaultproxy(socks.SOCKS5, '192.168.1.5', 8080) socks.wrapmodule(smtplib) Http(s) proxy (paragraph 5)) is not related because it does not affect SMTP and other protocols except http(s) because "SOCKS operates at a lower level than HTTP proxying".

http://stackoverflow.com/q/51324797
has comment: http://stackoverflow.com/comment/89626325
has title: Finding weights for conv2d layer in Tensorflow
accepted answer: http://stackoverflow.com/a/51326933
tagged with: python
type: AnsweredQuestion
tagged with: conv-neural-network
has comment: http://stackoverflow.com/comment/89628846
has comment: http://stackoverflow.com/comment/89628583
tagged with: tensorflow
linked to: http://stackoverflow.com/q/46211730
type: Question
has comment: http://stackoverflow.com/comment/89628069
has comment: http://stackoverflow.com/comment/89627911
tagged with: neural-network
has answer: http://stackoverflow.com/a/51326933
has comment: http://stackoverflow.com/comment/89627817
has body: I am pretty confused when it comes to the shape of a convolutional layer in tensorflow. kernels = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, "conv1d(_.)?/kernel:0") Running this line returns me a kernel with 4 dimensions and a bias. I expected that the kernel would return me [filter_width, filter_height, filter_number] and a 2D matrix with weights. Instead i have a fourth dimensions and no weights at all. Maybe I should not interchange dense with convolutional layers in my mind. However most of the explanations I find on the internet stay on a simple level without going into the details of tensorflows model. So most important for me would be getting the interconnected weights of the edges between the layers. Like seen on this picture: This link regards to my problem: Something I want from Tensorflow I hope someone can follow my trouble in understanding, otherwise do not hesitate adding comments.
score: 0
answer count: 1

http://stackoverflow.com/q/51456992
type: UnansweredQuestion
score: 0
tagged with: java
tagged with: http://stackoverflow.com/tag/json
type: Question
tagged with: apache-kafka
has comment: http://stackoverflow.com/comment/89893126
has answer: http://stackoverflow.com/a/51469350
has comment: http://stackoverflow.com/comment/89884032
answer count: 1
has body: I recently tried to use python to send messages to Kafka. When using simple byte messages, it works. But now, I have a json data, that I need to send to Kafka topic which will then be consumed by a Java application. I tried to find out how to convert json to byteArray (that is what the Java application is expecting as the payload). So, I came up with the below python script. But it failed as there are a few boolean variables in the json and I am getting a type error as Json true and Python True are different in case. I tried to enclose the json in single quotes, but again I got the error 'EOL while scanning string literal'. Only once I fix this error, will I know whether I am able to send this data to Kafka or not, so as of now I am struggling with the conversion part. Below is my code and the json. Json: { "header": { "activityId": "550", "timeStamp": "1490093093000", "sequencingId": 1 }, "queueId": "604", "contextRef": "SLIP.UPDATE" , "state": { "slips": [{ "id": "550", "creationDate": "2017-01-30T14:14:14.000+0000", "accountRef": "1", "customerRef": "2", "source": { "channelRef": "K" }, "receipt": "O/0000002/0000487", "isSettled": true, "isConfirmed": true, "lines": { "number": 1, "win": 1, "lose": 0, "voided": 0 } }] } } Python script: #!/usr/bin/python from kafka import KafkaProducer KAFKA_TOPIC = 'slips' KAFKA_BROKERS = '172.17.0.1:9092' producer = KafkaProducer(value_serializer=lambda v:json.dumps(v).encode('utf-8'),bootstrap_servers=KAFKA_BROKERS) messages = '{ "header": { "activityId": "550", "timeStamp": "1490093093000", "sequencingId": 1 }, "queueId": "604", "contextRef": "SLIP.UPDATE" }, "state": { "slips": [{ "id": "550", "creationDate": "2017-01-30T14:14:14.000+0000", "accountRef": "1", "customerRef": "2", "source": { "channelRef": "K" }, "receipt": "O/0000002/0000487", "isSettled": true, "isConfirmed": true, "lines": { "number": 1, "win": 1, "lose": 0, "voided": 0 } }] } }' info_as_json = json.loads(messages) producer.send(KAFKA_TOPIC, info_as_json) T…
tagged with: python
has comment: http://stackoverflow.com/comment/89893782
has title: Send a json as bytearray to send to kafka with Python
has comment: http://stackoverflow.com/comment/89888250
has comment: http://stackoverflow.com/comment/89884043
linked to: http://stackoverflow.com/q/10660435

http://stackoverflow.com/comment/89652025
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51338756
has text: What if you only use `[c]`? Maybe the wordpress website is doing something weird and running out of memory.
type: Comment

http://stackoverflow.com/q/51411878
upvote count: 0
has comment: http://stackoverflow.com/comment/89795678
has comment: http://stackoverflow.com/comment/89795489
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89795347
has comment: http://stackoverflow.com/comment/89795650
tagged with: algorithm
score: -1
has title: How to find a sequence of elements in an (only kinda) ordered list
answer count: 1
has answer: http://stackoverflow.com/a/51413058
favorite count: 0
has comment: http://stackoverflow.com/comment/89795399
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89795558
tagged with: python
has body: So I have a list of log entries, which looks somewhat like this: a = [ {‘log’: ‘abc’, ‘time’: 0}, {‘log’: ‘123’, ‘time’: 1}, {‘log’: ‘def’, ‘time’: 2}, {‘log’: ‘abc’, ‘time’: 2}, {‘log’: ‘ghi’, ‘time’: 3}, {‘log’: ‘def’, ‘time’: 3} ] Where time is accurate to the second, but events marked as happening at the same time, may have occurred at any order relative to each other. For example, in the above list, a[5] may have happened chronologically before a[4]. Now say have a sequence of logs I want to match against a: b = [ {‘log’: ‘abc’, ‘time’: 0}, {‘log’: ‘def’, ‘time’: 1}, {‘log’: ‘ghi’, ‘time’: 2} ] I would hope to find the ordered sebset of a with the log entries from b, where subset[0]['time'] is as close as possible to subset[-1]['time'] (in other words, where the duration of time spanned by the subset is as small as possible): &gt;&gt;&gt; f(a, b) [{‘log’: ‘abc’, ‘time’: 2}, {‘log’: ‘ghi’, ‘time’: 3}, {‘log’: ‘def’, ‘time’: 3}] EDIT for further clarification: If the subsets of a, which match b are: # a[0], a[4], a[5] a1 = [ {‘log’: ‘abc’, ‘time’: 0}, {‘log’: ‘ghi’, ‘time’: 3}, {‘log’: ‘def’, ‘time’: 3} ] # a[3], a[4], a[5] a2 = [ {‘log’: ‘abc’, ‘time’: 2}, {‘log’: ‘ghi’, ‘time’: 3}, {‘log’: ‘def’, ‘time’: 3} ] Then the entries in a1 occurred over a period of 3 seconds, and the entries in a2 occurred over a period of 1 second. As the duration of the entries in a2 is shorter than that of a1, I would hope to be returned a2.

http://stackoverflow.com/q/51440840
linked to: http://stackoverflow.com/q/43453707
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/51446313
tagged with: vector
has comment: http://stackoverflow.com/comment/89852135
has title: Numpy Performance - Outer Product of a vector with its transpose
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51446313
has comment: http://stackoverflow.com/comment/89851746
tagged with: transpose
tagged with: python
has comment: http://stackoverflow.com/comment/89858220
has body: It is my understanding that the Outer Product of a vector with its transpose is symmetric in value. Does Numpy take this into account to only do the multiplications for the upper triangle part of the output or does it calculate the whole output matrix (even though it is symmetric and time + memory could go to waste?)
has comment: http://stackoverflow.com/comment/89858265
has comment: http://stackoverflow.com/comment/89860215
type: AnsweredQuestion
score: 2
linked to: http://stackoverflow.com/q/50733148
has comment: http://stackoverflow.com/comment/89855350
upvote count: 3
has comment: http://stackoverflow.com/comment/89857446
downvote count: 1

http://stackoverflow.com/a/51420449
score: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51413500
has body: Thanks to tripleee, my code has started working. I am posting the working code as follows: import os import glob import netCDF4 path = 'C:/Users/Win-8.1/Desktop/omi/no2' for filename in glob.glob(os.path.join(path,'*.nc')): data=netCDF4.Dataset(filename,'r') print data
upvote count: 2

http://stackoverflow.com/comment/89704835
comment on: http://stackoverflow.com/q/51366170
score: 0
type: QuestionComment
type: Comment
has text: I think you actually managed to detract from your question with your last edit. Please provide enough code for us to copy paste and see the error when we run the code. You just don't have enough here do anything with.

http://stackoverflow.com/comment/90717476
score: 0
has text: @TheCrystalShip try it
comment on: http://stackoverflow.com/a/51431109
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51343164
has comment: http://stackoverflow.com/comment/89659698
answers question: http://stackoverflow.com/q/51343097
has comment: http://stackoverflow.com/comment/89659777
has body: Because list is a callable that takes one object as parameter which must be an iterable, while [] is list literal and understands that the single int supplied should be the only element for the list. If you want to use list, you have to wrap the number in an iterable, for example list((123,)).
has comment: http://stackoverflow.com/comment/89659799
has comment: http://stackoverflow.com/comment/89659666
has comment: http://stackoverflow.com/comment/89702925
score: 0
has comment: http://stackoverflow.com/comment/89659764
has comment: http://stackoverflow.com/comment/89703120
type: Answer
has comment: http://stackoverflow.com/comment/89716262

http://stackoverflow.com/comment/89794810
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51411098
has text: @zwer I am not calling one object instance from multiple processes. I am calling different object instances. "instances" is a list of object instances, I am calling them one by one and assign each one to one process.

http://stackoverflow.com/a/51414257
downvote count: 0
score: 2
answers question: http://stackoverflow.com/q/51414138
accepted answer of: http://stackoverflow.com/q/51414138
upvote count: 2
has body: The problem with your existing code is that you don't have a global function (or anything else) named student2dict, because you indented it under the class Student definition. Just dedent it, and it will work: class Student(object): def __init__(self,name,age,score): self.name = name self.age = age self.score = score def student2dict(std): return{ 'name':std.name, 'age':std.age, 'score':std.score } s= Student('Penny',20,88) std_data = json.dumps(s,default=student2dict) print('Dump Student:',std_data) However, it seems like you wanted it to be a method, not a plain function: before I tried to use default=s.student2dict instead of dedault=student2dict A normal method needs a self parameter. That's how it knows which instance you're calling it on. The error you got was presumably about calling student2dict with two arguments (the s from s.student2dict, and the same s again passed in by json.dumps) when it only wanted one (std). You could fix this: class Student(object): def __init__(self,name,age,score): self.name = name self.age = age self.score = score def student2dict(self, std): return{ 'name':std.name, 'age':std.age, 'score':std.score } And now you could pass default=s.student2dict and it would work. But this really isn't a very good design. If you're not actually using self for anything, you're not really writing an instance method. (You could make it a static method, because they neither get nor need a self, but I don't see any point to doing that here. If that's what you want, a global function probably makes more sense.) But… what if you got rid of std, and used self instead? class Student(object): def __init__(self,name,age,score): self.name = name self.age = age self.score = score def student2dict(self): return{ 'name':self.name, 'age':self.age, 'score':self.score } Now, you don't want to pass s.student2dict, because that's a bound method, owned by the instance s. It can't be called with an argument, because the argument is already bound in. You're going to …
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/51431968
has body: Use pd.concat on axis=0, which is default, so you don't need to include axis: pd.concat([Employee, new_observations], sort=False) Output: Education Sex Year Department Title Name Bob Bachelor M 1 IT analyst Sam PHD M 3 Trade associate Peter Master M 8 HR VP Jake Master M 2 IT analyst Mary F 9 IT VP Amy PHD F 5 ? associate Jennifer Master F NaN Trade associate John Master M 2 HR analyst Judy Bachelor F 2 HR analyst
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51431762

http://stackoverflow.com/q/51365051
has title: Returning 'Error' in a While Loop python
favorite count: 0
has answer: http://stackoverflow.com/a/51365097
score: 0
linked to: http://stackoverflow.com/q/23294658
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89702932
has comment: http://stackoverflow.com/comment/89702646
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
has body: I'm new to python and was hoping if someone could help me with this problem. Here's The code: uninput1=input('&gt; ') while True: if 'existing' in uninput1 or 'existing file' in uninput1: print ('Please enter the directory of your file.') dirfile=input('&gt; ') print (space) time.sleep(1) print ('Now enter the name of your file.') nmfile=input('&gt; ') print (space) time.sleep(1) txtmod.existing(dirfile, nmfile) elif 'new' in uninput1 or 'create' in uninput1: print ('Please enter the directory where you want to create your file.') dirfile=input('&gt; ') print (space) time.sleep(1) print ('Now enter the name you want to give to your file.') nmfile=input('&gt; ') print (space) time.sleep(1) txtmod.newfile(dirfile, nmfile) else: print ('Error! Please Try again') What i'm trying to do is to return an error when the user types a certain thing and restart the loop.But what happens is that instead of restarting the loop it just displays my 'error' forever. Can anyone help? I don't know if this makes sense or not but i hope it does to someone.
tagged with: loops
type: Question
accepted answer: http://stackoverflow.com/a/51365097
upvote count: 1

http://stackoverflow.com/comment/89947500
comment on: http://stackoverflow.com/a/51469391
has text: What you need to do is a little bit of math: new y position = old y position + (full image height - duck image height).
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51368349
favorite count: 0
has body: So I have this inventory dict and an empty items list that I want to fill it with the keys in the inventory dict. Any clues on how do I fill the list? # Inventory Dict inventory = {} inventory["item a"] = 12 inventory["item b"] = 10 inventory["item x"] = 25 print(inventory) # Item List items = []
tagged with: python
has title: How to fill a list with dict of keys in Python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/51368427
downvote count: 1
has comment: http://stackoverflow.com/comment/89709039
type: AnsweredQuestion
tagged with: list
linked to: http://stackoverflow.com/q/3294889
has comment: http://stackoverflow.com/comment/89709131
score: -1
has comment: http://stackoverflow.com/comment/89709093
type: Question
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89712693
has answer: http://stackoverflow.com/a/51368427
has comment: http://stackoverflow.com/comment/89709312

http://stackoverflow.com/comment/89927594
has text: also use `out.decode()` not `str(out)`
comment on: http://stackoverflow.com/q/51479516
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/a/51517680
type: Answer
answers question: http://stackoverflow.com/q/51433372
has body: Here is some code that TensorFlow sent me to solve the problem. Rather than use tf.set_random_seed, with estimators you use tf.estimator.RunConfig. import tensorflow as tf tf.reset_default_graph() config = tf.estimator.RunConfig(tf_random_seed=234) input1_col = tf.feature_column.numeric_column('input1') input2_col = tf.feature_column.numeric_column('input2') model = tf.estimator.DNNClassifier(hidden_units=[20,20], feature_columns=[input1_col, input2_col],n_classes=2,config=config) import numpy as np input1 = np.random.random(size=(100, 1)) input2 = np.random.random(size=(100, 1)) target = np.where(np.sum(input1 + input2, axis = 1) &gt; 0, 1, 0) def train_input_fn(): return ({'input1': input1, 'input2': input2}, target) model.train(input_fn=train_input_fn, steps = 10)
score: 0

http://stackoverflow.com/comment/89791296
type: Comment
score: 2
comment on: http://stackoverflow.com/q/51409852
type: QuestionComment
has text: `the k/v pair to be placed in the first section of the list is specified`. Where is it specified? **Dictionaries in Python 2.7 are unordered.**

http://stackoverflow.com/comment/89638616
has text: please try to follow usual conventions too, and change `login` to `self`
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51331387

http://stackoverflow.com/comment/89627977
has text: @Vincent However, it might need more adaptation of the code especially to do array-wide operation to obtain mindex instead of this double for loop.
type: Comment
comment on: http://stackoverflow.com/a/51326130
score: 0
type: AnswerComment

http://stackoverflow.com/a/51617305
has body: Try changing your _init_plot() function to the following, seems to update a little better... if not self._figure: self._figure = plt.figure(num=1) canvas = FigureCanvasTkAgg(self._figure, app) canvas.show() canvas.get_tk_widget().grid(columnspan=4) if not self._axes: print('New Axes!') self._axes = plt.axes() self._axes.set_xlim(self._Xmin, self._Xmax) self._axes.set_xlabel('Radial Distance from Separatrix (along Outer Midplane) [m]') self._axes.set_ylabel('Normalized Coefficient Magnitude') self._axes.set_ylim(self._Ymin, self._Ymax) self._axes.grid(b=True,which="both") self._figure.sca(self._axes) self._figure.canvas.mpl_connect('button_press_event', self._on_click) self._figure.canvas.mpl_connect('button_release_event', self._on_release) self._figure.canvas.mpl_connect('motion_notify_event', self._on_motion) self._figure.canvas.draw()
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51341050
type: Answer
answers question: http://stackoverflow.com/q/51341050
has comment: http://stackoverflow.com/comment/90210092

http://stackoverflow.com/a/51428450
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89828169
has comment: http://stackoverflow.com/comment/89828493
has comment: http://stackoverflow.com/comment/89828243
accepted answer of: http://stackoverflow.com/q/51428209
answers question: http://stackoverflow.com/q/51428209
type: Answer
has comment: http://stackoverflow.com/comment/89828125
score: 6
upvote count: 6
has body: I have tried to find some Q/A or article about the use of tk.mainloop() vs root.mainloop() with no success. My question is this: Is there any difference between the 2 uses. Short answer: there is no difference in the normal use case. Every widget has an associated tcl interpreter that is created when a root widget is created, whether either explicitly or implicitly. When you call mainloop from any widget, it will run the mainloop function in the interpreter associated with the root window of that widget. If you call the mainloop method that is part of the tkinter module (eg: tk.mainloop() in your example), it will call the mainloop function of the default interpreter. The default interpreter is the first interpreter that was created. Thus, in the normal case of a single instance of Tk, tk.mainloop() and root.mainloop() call the exact same code.
has comment: http://stackoverflow.com/comment/89828215

http://stackoverflow.com/q/51459579
has comment: http://stackoverflow.com/comment/89888754
linked to: http://stackoverflow.com/q/50257101
has title: RuntimeError: Model class xxx.xxx doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
has comment: http://stackoverflow.com/comment/89892114
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/51483204
linked to: http://stackoverflow.com/q/35388637
favorite count: 0
has comment: http://stackoverflow.com/comment/89894126
has comment: http://stackoverflow.com/comment/89902997
has answer: http://stackoverflow.com/a/51483204
tagged with: django
has comment: http://stackoverflow.com/comment/89902586
tagged with: python
has body: i am getting the following error when trying to run the django 2 app few lines from stacktrace File "/Users/shobi/Projects/emailtool/emailtool/frontend/models/AwsSettings.py", line 4, in from emailtool.frontend.models.AwsRegions import AwsRegions File "/Users/shobi/Projects/emailtool/emailtool/frontend/models/AwsRegions.py", line 4, in class AwsRegions(models.Model): File "/Users/shobi/Projects/emailtool/env/lib/python3.6/site-packages/django/db/models/base.py", line 108, in new "INSTALLED_APPS." % (module, name) RuntimeError: Model class emailtool.frontend.models.AwsRegions.AwsRegions doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I tried Django: Model class user.models.Users doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS RuntimeError: Model class django.contrib.sites.models.Site doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS and many google results as well, what is missing? Django2, Python 3.6 Edit: INSTALLED_APPS = [ 'frontend', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ]
has comment: http://stackoverflow.com/comment/89902952
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question

http://stackoverflow.com/q/51441450
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/90126630
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/89853679
score: 1
has comment: http://stackoverflow.com/comment/89853017
has comment: http://stackoverflow.com/comment/89859772
type: Question
has comment: http://stackoverflow.com/comment/89854199
has comment: http://stackoverflow.com/comment/89853474
has comment: http://stackoverflow.com/comment/89853060
has body: FYI: New to python. I have a csv file (with {','} as a delimiter) that has some sensor data. There is a heading with just a hyphen {'-'} that occurs many times that is not required. Since it does not correspond to any data, it causes the data columns to shift and hence not match with the column heading. To resolve this, after looking through the internet, I do this: specials = '\'-\'' new_line = str.replace(line, specials, '') This replaces the hyphen with nothing. However now it is a blank space and the issue is not resolved. If I do this: specials = ',\'-\'' #see the , added new_line = str.replace(line, specials, '') nothing happens i.e. even the hyphen {'-'} is not removed. Probably this is due to the {','} being the delimiter. Apart from changing the delimiter (assuming it would work), how can I remove the extra heading that pops up in the first row and causes the mismatch between data and heading? It is clear that by just making any exact sequence {,'-'} removed solves the issue for me but I am not able to do it. Please ask if unclear. Edit: Here is the complete code import csv import sys output_file = open('sensor_data.csv', 'w') with open(sys.argv[1],'r') as input_file: data = csv.reader(input_file) writer = csv.writer(output_file, quoting=csv. QUOTE_ALL) # special characters to be removed specials = ",'-'" for line in data: line = str(line) new_line = str.replace(line, specials, '') writer.writerow(new_line.split(',')) input_file.close() output_file.close() Put in a good csv file with {,} as delimiter and put an extra {-} as heading without adding corresponding column data (so you have one more heading than the columns with data).
has title: Removing special characters from csv file
has comment: http://stackoverflow.com/comment/89859602
upvote count: 1
has comment: http://stackoverflow.com/comment/89856772
has comment: http://stackoverflow.com/comment/89853061
favorite count: 0
has comment: http://stackoverflow.com/comment/89854346
has comment: http://stackoverflow.com/comment/89853146

http://stackoverflow.com/a/51345757
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51333319
accepted answer of: http://stackoverflow.com/q/51333319
score: 1
type: AcceptedAnswer
downvote count: 0
has body: Edit 2018-07-16 Here I post a corrected answer taking into account the drag by air. Below is a python script to compute the set of (v0,theta) values so that the air-dragged trajectory passes through (x,y) = (xstar,0) at some time t=tstar. I used the trajectory without air-drag as the initial guess and also to guess the dependence of x(tstar) on v0 for the first refinement. The number of iterations needed to arrive at the correct v0 was typically 3 to 4. The script finished in 0.99 seconds on my laptop, including the time for generating figures. The script generates two figures and one text file. fig_xdrop_v0_theta.png The black dots indicates the solution set (v0,theta) The yellow line indicates the reference (v0,theta) which would be a solution if there were no air drag. fig_traj_sample.png Checking that the trajectory (blue solid line) passes through (x,y)=(xstar,0) when (v0,theta) is sampled from the solution set. The black dashed line shows a trajectory without drag by air as a reference. output.dat contains the numerical data of (v0,theta) as well as the landing time tstar and number of iteration needed to find v0. Here begins script. #!/usr/bin/env python3 import numpy as np import scipy.integrate import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.image as img mpl.rcParams['lines.linewidth'] = 2 mpl.rcParams['lines.markeredgewidth'] = 1.0 mpl.rcParams['axes.formatter.limits'] = (-4,4) #mpl.rcParams['axes.formatter.limits'] = (-2,2) mpl.rcParams['axes.labelsize'] = 'large' mpl.rcParams['xtick.labelsize'] = 'large' mpl.rcParams['ytick.labelsize'] = 'large' mpl.rcParams['xtick.direction'] = 'out' mpl.rcParams['ytick.direction'] = 'out' ############################################ len_ref = 1.95 xstar = 8.0*len_ref ystar = 4.0*len_ref g_earth = 9.81 # mass = 118 area = 1.9/2. cw = 0.78 rho = 1.293 lam = cw * area * rho /(2.0 * mass) ############################################ ngtheta=51 theta_min = -0.1*np.pi theta_max = 0.4*np.pi theta_gr…
has comment: http://stackoverflow.com/comment/90246699

http://stackoverflow.com/a/51485846
type: AcceptedAnswer
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51447614
has body: I found the solution was to write cleaner, more organized code. In addition to cleaner code, I included the following at the bottom of MainFrame. # finally, put the notebook in a sizer for the panel to manage # the layout sizer = wx.BoxSizer() sizer.Add(nb, 1, wx.EXPAND) p.SetSizer(sizer) sizer.Fit(p) p.Layout() Working code below: import wx # Some classes to use for the notebook pages. Obviously you would # want to use something more meaningful for your application, these # are just for illustration. class ExamplePanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) # create some sizers mainSizer = wx.BoxSizer(wx.VERTICAL) grid = wx.GridBagSizer(hgap=5, vgap=5) hSizer = wx.BoxSizer(wx.HORIZONTAL) self.quote = wx.StaticText(self, label="Your quote: ") grid.Add(self.quote, pos=(0,0)) # A multiline TextCtrl - This is here to show how the events work in this program, don't pay too much attention to it self.logger = wx.TextCtrl(self, size=(200,300), style=wx.TE_MULTILINE | wx.TE_READONLY) # A button self.button =wx.Button(self, label="Save") # the edit control - one line version. self.lblname = wx.StaticText(self, label="Your name :") grid.Add(self.lblname, pos=(1,0)) self.editname = wx.TextCtrl(self, value="Enter here your name", size=(140,-1)) grid.Add(self.editname, pos=(1,1)) # the combobox Control self.sampleList = ['friends', 'advertising', 'web search', 'Yellow Pages'] self.lblhear = wx.StaticText(self, label="How did you hear from us ?") grid.Add(self.lblhear, pos=(3,0)) self.edithear = wx.ComboBox(self, size=(95, -1), choices=self.sampleList, style=wx.CB_DROPDOWN) grid.Add(self.edithear, pos=(3,1)) # add a spacer to the sizer grid.Add((10, 40), pos=(2,0)) # Checkbox self.insure = wx.CheckBox(self, label="Do you want Insured Shipment ?") grid.Add(self.insure, pos=(4,0), span=(1,2), flag=wx.BOTTOM, border=5) # Radio Boxes radioList = ['blue', 'red', 'yellow', 'orange', 'green', 'purple', 'navy blue', 'black', 'gray'] rb = wx.RadioBox(self, …
answers question: http://stackoverflow.com/q/51447614

http://stackoverflow.com/comment/89796860
comment on: http://stackoverflow.com/q/51412530
has text: Assuming you have it, try running `type -P python3.7`, then `ldd FULLPATHTOPYTHON3.7`. There is a decent chance you're dynamic linking an older `libpython.so` (and as a consequence, not really running Python 3.7) while trying to analyze `dis.py` from Python 3.7.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89671843
score: 0
has text: I have tried that too. It works just fine until it gets to running setup.py. When it gets to that it just sits there and never completes the installation.
comment on: http://stackoverflow.com/q/51343961
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89680321
comment on: http://stackoverflow.com/a/51353852
type: AnswerComment
type: Comment
has text: Might as well use `random.sample`, that's what it's made for.
score: 1

http://stackoverflow.com/q/51377812
type: Question
tagged with: numpy
answer count: 2
score: 0
has answer: http://stackoverflow.com/a/51379344
has body: i am trying to construct a function which gives me interpolated values of a piecewise linear function. I tried linear spline interpolation (which should be able to do exactly this?)- but without any luck. The problem is most visible on a log scale plot. Below there is the code of a small example i prepared: %matplotlib inline import matplotlib.pyplot as plt import pandas as pd import numpy as np import os from scipy import interpolate #Original Data pwl_data = np.array([[0,1e3, 1e5, 1e8], [-90,-90, -90, -130]]) #spine interpolation pwl_spline = interpolate.splrep(pwl_data[0], pwl_data[1]) spline_x = np.linspace (0,1e8, 10000) legend = [] plt.plot(pwl_data[0],pwl_data[1]) plt.plot(spline_x,interpolate.splev(spline_x,pwl_spline ),'*') legend.append("Data") legend.append("Interpolated Data") plt.xscale('log') plt.legend(legend) plt.grid(True) plt.grid(b=True, which='minor', linestyle='--') plt.show() What am I doing wrong?
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/72424826
has title: Python piecewise function interpolation
tagged with: scipy

http://stackoverflow.com/q/51424630
type: UnansweredQuestion
has body: Lets say I have an incoming string which is a python function and I would like to convert that to a python signature. I can do that using the importlib function. For example lets say I have an incoming string "os.getenv" and I want to resolve to the corresponding function signature. I can do something like below. &gt;&gt;&gt; import importlib &gt;&gt;&gt; fn = "os.getenv" &gt;&gt;&gt; package_signature = importlib.import_module("os") &gt;&gt;&gt; getattr(package_signature, "getenv") How can I parse and return functions when the functions are lambda functions. For example something like fn = "lambda x: 'a' + x"
type: Question
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/89821954
tagged with: lambda
answer count: 1
has title: Convert lambda string into lambda function signature
linked to: http://stackoverflow.com/q/37320401
score: 0
has comment: http://stackoverflow.com/comment/89820580
has answer: http://stackoverflow.com/a/51425002

http://stackoverflow.com/comment/89791414
comment on: http://stackoverflow.com/q/51400185
score: 0
type: Comment
type: QuestionComment
has text: @VikasNS i added the full code from the site that i metioned before with my extra code for prediction-

http://stackoverflow.com/a/51402264
has comment: http://stackoverflow.com/comment/89776808
has comment: http://stackoverflow.com/comment/89820867
has comment: http://stackoverflow.com/comment/89778119
accepted answer of: http://stackoverflow.com/q/51401963
score: 0
answers question: http://stackoverflow.com/q/51401963
type: AcceptedAnswer
type: Answer
has body: Intersection will only find matching elements. Here are the lists you are comparing: ["Good to Soft","Slow","Standard to Slow","Standard","Standard to Fast","Fast","Heavy","Soft to Heavy","Soft","Yeliding to Soft","Yeilding","Good to Yeilding","Good","Good to Firm","Firm","Hard"] testtext[0].split() == ["Standard", "to", "Slow"] If you only want it to match what is in testtext[0], then you shouldn't use split() to create your list: Going = stopwords.intersection({testtext[0]})
has comment: http://stackoverflow.com/comment/89778203

http://stackoverflow.com/q/51465981
has comment: http://stackoverflow.com/comment/89900830
score: -2
has comment: http://stackoverflow.com/comment/89900852
answer count: 1
tagged with: javascript
tagged with: flask
has comment: http://stackoverflow.com/comment/89900849
tagged with: ajax
has answer: http://stackoverflow.com/a/51466129
has comment: http://stackoverflow.com/comment/89900767
tagged with: python
has comment: http://stackoverflow.com/comment/89900862
favorite count: 0
upvote count: 0
type: UnansweredQuestion
has title: How to send information back and forth from a javascript file to a python file
has comment: http://stackoverflow.com/comment/89900468
has comment: http://stackoverflow.com/comment/89900904
has comment: http://stackoverflow.com/comment/89900867
has body: So I have an html file with javascript and a python file. In the javascript file, the user enters a string. In the python, I would like it to search it in an api, and then return the string to be displayed in the html file. How do I do this? I have looked up how to use AJAX and get/post methods, but nothing has worked so far. Also, I should mention I am using flask.
type: Question
has comment: http://stackoverflow.com/comment/89900877
downvote count: 2

http://stackoverflow.com/comment/89631742
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51327600
score: 0
has text: why not simply do a dump from production and restore it in test? By the time your script finishes the checking (or even start) the production may already have changed. The dump **may** be faster than this manual difference checking... or dump and restore just that one table

http://stackoverflow.com/comment/89733240
type: QuestionComment
comment on: http://stackoverflow.com/q/51380714
has text: Okay So can you tell little bit more about fix ?
score: 0
type: Comment

homebrew
tags question: http://stackoverflow.com/q/51388985
tag name: homebrew
type: Tag
tags question: http://stackoverflow.com/q/51374762
tags question: http://stackoverflow.com/q/51468497

http://stackoverflow.com/comment/89698128
comment on: http://stackoverflow.com/a/51362822
score: 0
type: Comment
has text: Oh okay i get it now, I got confused with how return works. Thank you
type: AnswerComment

http://stackoverflow.com/comment/89791676
comment on: http://stackoverflow.com/q/51410104
score: 0
has text: If the folder has no log files, you're not going to get `logs = None` in the loop, you're just not going to get the loop run at all.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89681040
comment on: http://stackoverflow.com/q/51352883
score: 0
type: Comment
type: QuestionComment
has text: thanks, @jasonharper for the clarification. I learned this one now.

http://stackoverflow.com/q/51357691
has body: referring to this question here: LINK How can I set up a config, that will only log my root script and my own sub-scripts? The question of the link asked for disabling all imported modules, but that is not my intention. My root setup: import logging from exchangehandler import send_mail log_wp = logging.getLogger(__name__) logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s [%(filename)s]: %(name)s %(funcName)20s - Message: %(message)s', datefmt='%d.%m.%Y %H:%M:%S', filename='C:/log/myapp.log', filemode='a') handler = logging.StreamHandler() log_wp.addHandler(handler) log_wp.debug('This is from root') send_mail('address@eg.com', 'Request', 'Hi there') My sub-module exchangehandler.py: import logging log_wp = logging.getLogger(__name__) def send_mail(mail_to,mail_subject,mail_body, mail_attachment=None): log_wp.debug('Hey this is from exchangehandler.py!') m.send_and_save() myapp.log: 16.07.2018 10:27:40 - DEBUG [test_script.py]: __main__ &lt;module&gt; - Message: This is from root 16.07.2018 10:28:02 - DEBUG [exchangehandler.py]: exchangehandler send_mail - Message: Hey this is from exchangehandler.py! 16.07.2018 10:28:02 - DEBUG [folders.py]: exchangelib.folders get_default_folder - Message: Testing default &lt;class 'exchangelib.folders.SentItems'&gt; folder with GetFolder 16.07.2018 10:28:02 - DEBUG [services.py]: exchangelib.services get_payload - Message: Getting folder ArchiveDeletedItems (archivedeleteditems) 16.07.2018 10:28:02 - DEBUG [services.py]: exchangelib.services get_payload - Message: Getting folder ArchiveInbox (archiveinbox) My problem is, that the log-file contains also a lot of information of the exchangelib-module, that is imported in exchangehandler.py. Either the imported exchangelib-module is configured incorrectly or I have made a mistake. So how can I reduce the log-output only to my logging messages? EDIT: An extract of the folder.py of the exchangelib-module. This is not anything that I have written: import loggi…
favorite count: 0
tagged with: python
tagged with: logging
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51358969
linked to: http://stackoverflow.com/q/1956142
score: 12
type: Question
has title: Python Logging - Only for own imported modules
upvote count: 12
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51358969
linked to: http://stackoverflow.com/q/35325042

http://stackoverflow.com/comment/89815794
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51418581
has text: @Tpeeters - hmmm, but then it is logic problem - some values need be splitted like `Marketing, Sales` and some not ( "Finance, Accounting" from commens above)? How is possible distingusih it?
score: 0

http://stackoverflow.com/q/51409215
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89794895
tagged with: netcdf4
type: Question
downvote count: 0
favorite count: 0
has title: How to copy variables from one netCDF4 file to another?
has body: I'm trying to duplicate a netCDF4 file with only a subset of the original variables. After creating a new variable using the netCDF4-python library, how do I set it to be equal to a variable in a different file?
tagged with: python
has comment: http://stackoverflow.com/comment/89891232
linked to: http://stackoverflow.com/q/48755957
score: 2

http://stackoverflow.com/a/51325684
has body: You may need to issue the CTRL+C command before the data is returned. Send a signal and catch the exception to deal with what is returned. import os import time import signal import subprocess stream = [] try: p = subprocess.Popen("sudo rfcomm connect /dev/rfcomm0 XX:XX:XX:XX:XX:XX 1",shell=True) #(stderr, stdout) = p.communicate() #print 'stderr: [%s]' % stderr #print 'stdout: [%s]' % stdout #time.sleep(5) #print "Device is ready" time.sleep(5) os.kill(p.pid, signal.CTRL_C_EVENT) p.wait() except KeyboardInterrupt: #except Exception: for line in p.stdout: #May also be p.stderr stream.append(line) for x in stream: print(x)
has comment: http://stackoverflow.com/comment/89626992
answers question: http://stackoverflow.com/q/51325187
has comment: http://stackoverflow.com/comment/89626756
has comment: http://stackoverflow.com/comment/89626665
downvote count: 0
has comment: http://stackoverflow.com/comment/89626559
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89626845

http://stackoverflow.com/comment/89825916
has text: sorry for the late response. Removing the covariance parameter did resolve the error and plot a regression line. However the regression line will not include the covariance by doing this. Still a good solution though when this is not the aim. I will upvote your answer!
comment on: http://stackoverflow.com/a/51423312
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51347988
has comment: http://stackoverflow.com/comment/89673470
has comment: http://stackoverflow.com/comment/89697849
type: Question
tagged with: jit
accepted answer: http://stackoverflow.com/a/51455700
answer count: 1
score: 0
tagged with: gpu
tagged with: python
favorite count: 0
tagged with: numba-pro
has answer: http://stackoverflow.com/a/51455700
tagged with: numba
upvote count: 1
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89670560
has title: How to accelerate this function using Numba?
has comment: http://stackoverflow.com/comment/89892343
has body: I was trying to optimize this function using Numba, but I am unable to do it. I think this has no part of the code which can be accelerated. If anyone can help me with an optimized version of this, My program would become blazing fast. Please tell if any dataset or other info is needed. When I apply direct @jit on this, It is not working. def c_a(x, y, z, counter, p_l): # start = time.time() if counter == 1: l = x m = y n = z path = "c_r.pdb" global r_a_t p = Bio.PDB.PDBParser() structure = p.get_structure('mSN1', path) c_r = [a.get_coord() for a in structure.get_atoms()] lengthnew = len(c_r) m_d = np.array([-45, -45, -45]) a_s_r = np.zeros((128, 128, 128), np.complex) for i in range(0, lengthnew): x = int(math.floor((c_r[i][0] - m_d[0]) / 1.2)) y = int(math.floor((c_r[i][1] - m_d[1]) / 1.2)) z = int(math.floor((c_r[i][2] - m_d[2]) / 1.2)) with open("Ei.txt", 'r') as ei_values: for row in ei_values: s_v = row.split() if s_v[0] == r_a_t[i] : a_s_r[x, y, z] = np.complex(s_v[1]) n_n = lambda x, y, z : [(x2, y2, z2) for x2 in range(x - 5, x + 6) for y2 in range(y - 5, y + 6) for z2 in range(z - 5, z + 6) if (-1 &lt; x &lt; X and -1 &lt; y &lt; Y and -1 &lt; z &lt; Z and (x != x2 or y != y2 or z != z2) and (0 &lt;= x2 &lt; X) and (0 &lt;= y2 &lt; Y) and (0 &lt;= z2 &lt; Z) and ((( abs(x - x2)) ** 2 + (abs(y - y2)) ** 2 + (abs(z - z2)) ** 2 ) &lt;= 25))] m = n_n(l, m, n) result = 0 for i in range(0, len(m)): a = m[i][0] b = m[i][1] c = m[i][2] result = result + a_s_r[a][b][c] return result else: l = x m = y n = z path = p_l global l_a_t p = Bio.PDB.PDBParser() structure = p.get_structure('mSN1', path) c_l = [a.get_coord() for a in structure.get_atoms()] lengthnew = len(c_l) m_d = np.array([-45, -45, -45]) a_s_l = np.zeros((128, 128, 128), np.complex) for i in range(0, lengthnew): x = int(math.floor((c_l[i][0] - m_d[0]) / 1.2)) y = int(math.floor((c_l[i][1] - m_d[1]) / 1.2)) z = int(math.floor((c_l[i][2] - m_d[2]) / 1.2)) with open("E.txt", 'r') as e_v: for row in e_v: s_v…

http://stackoverflow.com/comment/89714014
type: QuestionComment
has text: I see. Following up with csevier's comments and answer, I was able to apply what you said. Thank you for your help and time.
comment on: http://stackoverflow.com/q/51370261
score: 0
type: Comment

http://stackoverflow.com/comment/89932154
type: QuestionComment
score: 0
has text: Yeah, same target
type: Comment
comment on: http://stackoverflow.com/q/51481676

http://stackoverflow.com/a/51416872
downvote count: 0
has body: try this, read the files without header, by default it will put range(length_of_the_columns). then concat your df's finally create your header. import os import pandas as pd df=pd.DataFrame() for file_ in os.listdir(folder_path): temp=pd.read_csv(folder_path+'/'+file_,header=None,skiprows=1) df=pd.concat([df,temp],ignore_index=True) df.columns=[new_column_names] df.to_csv('single_file.csv',index=False)
type: Answer
has comment: http://stackoverflow.com/comment/96498613
accepted answer of: http://stackoverflow.com/q/51416700
upvote count: 3
answers question: http://stackoverflow.com/q/51416700
score: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/89870157
type: Comment
comment on: http://stackoverflow.com/a/51449835
type: AnswerComment
score: 0
has text: Why do you think this is the best practice?

http://stackoverflow.com/q/51331863
favorite count: 0
answer count: 1
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51334579
type: UnansweredQuestion
upvote count: 1
tagged with: python
downvote count: 3
has comment: http://stackoverflow.com/comment/89639618
type: Question
has comment: http://stackoverflow.com/comment/89639464
score: -2
has title: why do we have to open file multiple times in a function in python?
has body: a = open("prime_numbers.txt", 'r+') b = open('happy_numbers.txt','r+') c = a.read().split() d = b.read().split() def overlap(list1,list2): e= open('final_number_list.txt','r+') for i in list1: for j in list2: if i == j: e.write(i+'\n') else:continue e = open('final_number_list.txt', 'r+') print(e.read().split()) overlap(c,d) Why i have to use open command for the 2nd time? If i will not use it for the 2nd time the command overlap(c,d) will print a empty list but using it gives the correct result.

http://stackoverflow.com/comment/89861277
type: Comment
has text: Have you already saved data on your db? The problem with `INSERT IGNORE` is that your data won't be inserted if it already exists. Also, can you try debugging if `placestr` contains the information you need (and in the correct structure)?
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51445473

http://stackoverflow.com/a/51347183
has body: One way to do this is to make a pattern that matches either word (using \b so we only match complete words), use re.findall to check the string for all matches, and then use set equality to ensure that both words have been matched. import re stringA = "spam" stringB = "egg" words = {stringA, stringB} # Make a pattern that matches either word pat = re.compile(r"\b{}\b|\b{}\b".format(stringA, stringB)) data = [ "this string has spam in it", "this string has egg in it", "this string has egg in it and another egg too", "this string has both egg and spam in it", "the word spams shouldn't match", "and eggs shouldn't match, either", ] for s in data: found = pat.findall(s) print(repr(s), found, set(found) == words) output 'this string has spam in it' ['spam'] False 'this string has egg in it' ['egg'] False 'this string has egg in it and another egg too' ['egg', 'egg'] False 'this string has both egg and spam in it' ['egg', 'spam'] True "the word spams shouldn't match" [] False "and eggs shouldn't match, either" [] False A slightly more efficent way to do set(found) == words is to use words.issubset(found), since it skips the explicit conversion of found. As Jon Clements mentions in a comment, we can simplify and generalize the pattern to handle any number of words, and we should use re.escape, just in case any of the words contain regex metacharacters. pat = re.compile(r"\b({})\b".format("|".join(re.escape(word) for word in words))) Thanks, Jon! Here's a version that matches the words in the specified order. If it finds a match it prints the matching substring, otherwise it prints None. import re stringA = "spam" stringB = "egg" words = [stringA, stringB] # Make a pattern that matches all the words, in order pat = r"\b.*?\b".join([re.escape(word) for word in words]) pat = re.compile(r"\b" + pat + r"\b") data = [ "this string has spam and also egg, in the proper order", "this string has spam in it", "this string has spamegg in it", "this string has egg in it", "this string h…
has comment: http://stackoverflow.com/comment/89670285
answers question: http://stackoverflow.com/q/51346977
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89668763
has comment: http://stackoverflow.com/comment/89668829
has comment: http://stackoverflow.com/comment/89670982
has comment: http://stackoverflow.com/comment/89667421
has comment: http://stackoverflow.com/comment/89667102
type: Answer
has comment: http://stackoverflow.com/comment/89667463
accepted answer of: http://stackoverflow.com/q/51346977
has comment: http://stackoverflow.com/comment/89667896
has comment: http://stackoverflow.com/comment/89667315
has comment: http://stackoverflow.com/comment/89668620
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89667142
has comment: http://stackoverflow.com/comment/89670658

http://stackoverflow.com/comment/89943658
comment on: http://stackoverflow.com/q/51404184
score: 0
type: Comment
type: QuestionComment
has text: Did you see if it works without the `[ ]` around `login-required`?

http://stackoverflow.com/comment/116638416
type: Comment
has text: @NabeelAyub any lucky?
comment on: http://stackoverflow.com/a/51456120
score: 0
type: AnswerComment

http://stackoverflow.com/q/51347732
has comment: http://stackoverflow.com/comment/89668430
upvote count: 1
has answer: http://stackoverflow.com/a/51347963
has comment: http://stackoverflow.com/comment/89668082
downvote count: 1
tagged with: string
favorite count: 0
accepted answer: http://stackoverflow.com/a/51347752
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51347963
has comment: http://stackoverflow.com/comment/127514691
has comment: http://stackoverflow.com/comment/89668164
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/51347752
has comment: http://stackoverflow.com/comment/89668100
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51348154
has comment: http://stackoverflow.com/comment/89668157
has comment: http://stackoverflow.com/comment/89668897
has title: re.sub for replacing block(multi line) of text in python
type: Question
has comment: http://stackoverflow.com/comment/89669590
has body: I am trying to replace a block of text which is spanning over multiple lines of text file using python. Here is how my input file looks like. input.txt: ABCD abcd ( . X (x), .Y (y) ); ABCD1 abcd1 ( . X1 (x1), .Y1 (y1) ); I am reading the above file with the below code and trying to replace the text but failed to do so. Below is my code. fo = open(input.txt, 'r') input_str = fo.read() find_str = '''ABCD abcd ( .X (x), .Y (y) );''' replace_str = '''ABCDE abcde ( . XX (xx), .YY (yy) );''' input_str = re.sub(find_str, replace_str, input_str) But the input_str seems to be unchanged. Not sure what am I missing. Any clues?
score: 0
answer count: 3

http://stackoverflow.com/comment/89831598
has text: `_, *rest = your_iterator`
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/51430304

http://stackoverflow.com/a/51467388
score: 0
type: AcceptedAnswer
has body: To fetch calendars and events from google first you need a client_secret.json to get access to google calendar resources. Do not use the oauth2client library, because it's deprecated. Instead, use google auth. You can use Flow or InstalledAppFlow from google auth oauthlib to gain access to google calendar account resources. from google_auth_oauthlib.flow import InstalledAppFlow flow = InstalledAppFlow.from_client_secrets_file( 'secret_file.json', scopes=['https://www.googleapis.com/auth/calendar'] ) credentials = flow.run_console() Dump this credentials into a file, so you won't need to ask for permission access again. service = build( 'calendar', 'v3', credentials=credentials ) With this service you can use all the google calendar api from here. Update: Since I don't use oauth2client library I dump the credentials manually: with open('credentials.json', 'w') as f: f.write(json.dumps({ 'token': credentials.token, 'refresh_token': credentials.refresh_token, 'token_uri': credentials.token_uri, 'client_id': credentials.client_id, 'client_secret': credentials.client_secret, 'scopes': credentials.scopes}))
accepted answer of: http://stackoverflow.com/q/51461341
type: Answer
answers question: http://stackoverflow.com/q/51461341
has comment: http://stackoverflow.com/comment/89953912

http://stackoverflow.com/a/51478212
has body: Sockets in python is modeled after linux sockets API ( Check the link to know more about differences in socket types and what linux APIs say). Also it looks you didn't read the documentation of sockets in python, so read it Now for you question, your issue is as following, in both examples you use socket.SOCK_DGRAM which stands for data-gram. It's used for connection-less protocols like UDP. For TCP, you need a socket type that supports two-way reliable ( you will know if a packet is lost ) which is SOCK_STREAM. But because it's reliable, it must be stateful and can't be connection-less. So you have to create socket with SOCK_STREAM type. create a connection to the server. send/receive. close the connection # create socket of SOCK_STREAM type sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # connect to your server sock.connect((TCP_IP, TCP_PORT)) # do the sending/receiving part sock.sendall(b'Hello, world') data = sock.recv(1024) # close the connection s.close()
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51477487
answers question: http://stackoverflow.com/q/51477487
type: Answer
downvote count: 0

http://stackoverflow.com/q/51370752
upvote count: 1
tagged with: psycopg2
has answer: http://stackoverflow.com/a/51387288
type: Question
score: 1
tagged with: key-value-store
has comment: http://stackoverflow.com/comment/89746477
tagged with: sqlalchemy
has title: How to use postgresql as key-value store from python?
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51387288
favorite count: 0
has comment: http://stackoverflow.com/comment/89746977
tagged with: postgresql
tagged with: python
has comment: http://stackoverflow.com/comment/89713871
type: AnsweredQuestion
has body: I need to convert from gdbm to postgresql for my key/value store. It appears that I will have to replace import dbm.gnu def get_value(db, key): return json.loads(db[key]) db = dbm.gnu.open(...) v = get_value(db, "foo") with import sqlalchemy from sqlalchemy import Column, Text from sqlalchemy.dialects.postgresql import JSONB db = sqlalchemy.create_engine("...") engine = db.connect() meta = sqlalchemy.MetaData(engine) id_col = Column('id', Text, primary_key=True) data_col = Column('data', JSONB) sqlalchemy.Table("my_table", meta, id_col, data_col) meta.create_all() # populate the table with 40M "id"-->JSON records engine.execute( my_table.update(), id="foo", data={"a":3, "b":17, "c":[2,6,0]}) my_table = sqlalchemy.table("my_table", id_col, data_col) def get_value(db, key): res = engine.execute(db.select().where(db.c.id == key)).fetchall() assert len(res) == 1 return res[0][1] v = get_value(my_table) this looks somewhat scary (especially if I add echo and see all the SQL generated for these simple key-value operations). Is there a better way? PS. I could also use psycopg instead of sqlalchemy directly, but that would make me write SQL myself ;-(

http://stackoverflow.com/comment/89698073
comment on: http://stackoverflow.com/a/51362874
type: AnswerComment
score: 0
type: Comment
has text: thanks for continuous help on this. i get this as error: TypeError: don't know how to convert scalar number to float

http://stackoverflow.com/q/51418002
has comment: http://stackoverflow.com/comment/89808878
has comment: http://stackoverflow.com/comment/89839091
linked to: http://stackoverflow.com/q/51336074
has comment: http://stackoverflow.com/comment/89827323
has comment: http://stackoverflow.com/comment/89874758
has comment: http://stackoverflow.com/comment/89840256
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89875942
tagged with: python
answer count: 0
type: Question
tagged with: numpy
has title: How to show masked foreground image into background image of different size
tagged with: opencv
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/89838070
has body: Further to my previous question I like to put a video frame in the background of the extracted masked foreground pixels My foreground frame is resizedFrame[mask] where mask is essentially mask = labels == 0 and labels contains indices of pixels with values greater than 0 I want to be able to put a video in the background, the video frame I'm reading from the file using OpenCV VideoCapture in python, the video is of different size than the foreground image I have tried background.paste(foreground, box) approach using PIL.Image but it doesn't help with a masked foreground image
score: 0

http://stackoverflow.com/q/51370377
has body: I'm wanting to take photos from 2 different cameras at exactly the same time (or as close as possible). If I use multithreading or multiprocessing, it still runs the threads/processes consecutively.. For instance if I start the following processes: Take_photo_1.start() Take_photo_2.start() While those processes would run in parallel, the commands to start the processes are still executed sequentially. Is there any way to execute both those processes at exactly the same time?
answer count: 1
downvote count: 0
favorite count: 0
has title: Is it possible to execute two functions at EXACTLY the same time
has answer: http://stackoverflow.com/a/51370594
tagged with: python
tagged with: parallel-processing
accepted answer: http://stackoverflow.com/a/51370594
type: AnsweredQuestion
tagged with: multithreading
upvote count: 1
tagged with: multiprocessing
type: Question
score: 1
has comment: http://stackoverflow.com/comment/89713102
has comment: http://stackoverflow.com/comment/89973337

http://stackoverflow.com/comment/89678703
has text: https://github.com/pytorch/pytorch/blob/master/CONTRIBUTING.md#writing-documentation → https://sphinxcontrib-napoleon.readthedocs.io/en/latest/index.html
score: 1
comment on: http://stackoverflow.com/q/51353066
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51448102
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/95051856
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/51385223
accepted answer of: http://stackoverflow.com/q/51385223
has body: Stumbled upon the answer to my own question. Thanks everyone for the answers/comments. https://keras.io/layers/about-keras-layers/ The first few lines of this source detail how to load and set weights. Essentially, appending an output neuron to a Keras model can be accomplished by loading the old output layer, appending the new weights, and setting weights for a new layer. Code is below. # Load weights of previous output layer, set weights for new layer old_layer_weights = model.layers.pop().get_weights() new_neuron_weights = np.ndarray(shape=[1,bottleneck_size]) # Set new weights # Append new weights, add new layer new_layer = Dense(num_classes).set_weights(np.append(old_layer_weights,new_neuron_weights)) model.add(new_layer)
type: AcceptedAnswer

http://stackoverflow.com/a/51446997
has body: Problem in your referenced Question is that index of given dataframe is integer, but does not start from 0. Pandas behaviour when asking for df.B[0] is ambiguous and depends on data type of index and data type of value passed to python slice syntax. It can behave like df.B.loc[0] (index label based) or df.B.iloc[0] (position based) or probably something else I'm not aware of. For predictable behaviour I recommend using loc and iloc. To illustrate this with your example: d = [0.0, 1.0, 2.0] e = pd.Series(d, index = ['a', 'b', 'c']) df = pd.DataFrame({'A': 1., 'B': e, 'C': pd.Timestamp('20130102')}) df.B[0] # 0.0 - fall back to position based df.B['0'] # KeyError - no label '0' in index df.B['a'] # 0.0 - found label 'a' in index df.B.loc[0] # TypeError - string index queried by integer value df.B.loc['0'] # KeyError - no label '0' in index df.B.loc['a'] # 0.0 - found label 'a' in index df.B.iloc[0] # 0.0 - position based query for row 0 df.B.iloc['0'] # TypeError - string can't be used for position df.B.iloc['a'] # TypeError - string can't be used for position With example from referenced article: d = [0.0, 1.0, 2.0] e = pd.Series(d, index = [4, 5, 6]) df = pd.DataFrame({'A': 1., 'B': e, 'C': pd.Timestamp('20130102')}) df.B[0] # KeyError - label 0 not in index df.B['0'] # KeyError - label '0' not in index df.B.loc[0] # KeyError - label 0 not in index df.B.loc['0'] # KeyError - label '0' not in index df.B.iloc[0] # 0.0 - position based query for row 0 df.B.iloc['0'] # TypeError - string can't be used for position
type: Answer
score: 11
downvote count: 0
upvote count: 11
accepted answer of: http://stackoverflow.com/q/51445631
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51445631

http://stackoverflow.com/q/51383298
tagged with: arrays
downvote count: 0
has title: How to create new column based on values in array column in Pyspark
favorite count: 0
tagged with: apache-spark
tagged with: python
has answer: http://stackoverflow.com/a/51384118
score: 4
possible better answer: http://stackoverflow.com/a/51384798
has answer: http://stackoverflow.com/a/51384798
has body: I have the following dataframe with codes which represent products: testdata = [(0, ['a','b','d']), (1, ['c']), (2, ['d','e'])] df = spark.createDataFrame(testdata, ['id', 'codes']) df.show() +---+---------+ | id| codes| +---+---------+ | 0|[a, b, d]| | 1| [c]| | 2| [d, e]| +---+---------+ Let's say codes a and b represent t-shirts and code c represents sweaters. tshirts = ['a','b'] sweaters = ['c'] How can I create a column label which checks whether these codes are in the array column and returns the name of the product. Like so: +---+---------+--------+ | id| codes| label| +---+---------+--------+ | 0|[a, b, d]| tshirts| | 1| [c]|sweaters| | 2| [d, e]| none| +---+---------+--------+ I have already tried a lot of things, amongst others the following which does not work: codes = { 'tshirts': ['a','b'], 'sweaters': ['c'] } def any_isin(ref_values, array_to_search): for key, values in ref_values.items(): if any(item in array_to_search for item in values): return key else: return 'none' any_isin_udf = lambda ref_values: (F.udf(lambda array_to_search: any_isin_mod(ref_values, array_to_search), StringType())) df_labeled = df.withColumn('label', any_isin_udf(codes)(F.col('codes'))) df_labeled.show() +---+---------+-------+ | id| codes| label| +---+---------+-------+ | 0|[a, b, d]|tshirts| | 1| [c]| none| | 2| [d, e]| none| +---+---------+-------+
has comment: http://stackoverflow.com/comment/89738466
type: AnsweredQuestion
tagged with: pyspark
accepted answer: http://stackoverflow.com/a/51384118
type: Question
upvote count: 4
answer count: 2
tagged with: apache-spark-sql

http://stackoverflow.com/q/51410881
tagged with: python
favorite count: 0
has body: Is there a built-in python equivalent of std::find_if to find the first element of a list for which a given condition is true? In other words, something like the index() function of a list, but with an arbitrary unary predicate rather than just a test for equality. I don't want to use list comprehension, because the specific predicate I have in mind is somewhat expensive to compute.
possible better answer: http://stackoverflow.com/a/51410974
accepted answer: http://stackoverflow.com/a/51411190
has answer: http://stackoverflow.com/a/51410974
type: AnsweredQuestion
has title: Python equivalent of c++ find_if
tagged with: syntax
score: 10
has comment: http://stackoverflow.com/comment/89793349
upvote count: 10
has comment: http://stackoverflow.com/comment/89793433
type: Question
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51411190
has comment: http://stackoverflow.com/comment/89793318
linked to: http://stackoverflow.com/q/9542738

http://stackoverflow.com/q/51349283
type: AnsweredQuestion
has title: Categorical Variables pandas
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/51349343
type: Question
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51349343
tagged with: python
has body: I would like to compare stats such as mean,std etc of my dataset conditional on a dummy variable. I saw a command for that somewhere but I cannot remember (or google search was not succesful). I would like to produce an output like this: dummy mean(var1) mean(var2) 0 1.5 3 1 10 10 Maybe something with groupby?? This is a min example: dict1 = [{'dummy': '0', 'var1': 1, 'var2': 2}, {'dummy': '0', 'var1': 2, 'var2': 4}, {'dummy': '1', 'var1': 5, 'var2': 8}, {'dummy': '1', 'var1': 15, 'var2': 12},] df = pd.DataFrame(dict1, index=['s1', 's2','s3','s4'])

http://stackoverflow.com/comment/89748445
type: AnswerComment
type: Comment
score: 0
has text: I edited the question to make it more clear what I am trying to do. Each row of the column contains a list `L_i`, and I want to dot each list with `query_ebd`, thus the output I want is a dot product for each row, and I want to vectorize this. `query_ebd` has the same length (256) as each list `L_i`.
comment on: http://stackoverflow.com/a/51388179

http://stackoverflow.com/a/51400093
has body: First you should rename your class, Python naming convention are really strong and class should always start with a capital letter. Then to answer: You simply forgot the () ave = Average() ave.myinput() And you should put the class instance in each method: def myinput(self): ... def lol(self, mylist):
accepted answer of: http://stackoverflow.com/q/51400001
has comment: http://stackoverflow.com/comment/89771427
score: 1
answers question: http://stackoverflow.com/q/51400001
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/89771030

http://stackoverflow.com/a/51409184
type: Answer
has body: Movies["Toy Story"][1] should be sufficient. values gets you a list of the values for all movies, in an arbitrary order.
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51409114
upvote count: 1

http://stackoverflow.com/a/51375444
has comment: http://stackoverflow.com/comment/89722891
answers question: http://stackoverflow.com/q/51375065
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer
has body: You may get the value inside array['...'] and then use it as a key later, then collect the values between array[' and '] that are after &lt;@ type_list (to be used as values later), and then build the result: import re strs=["[(array['X'] &lt;@ type_list AND (array['X6'] &lt;@ value_list OR array['A6.5'] &lt;@ value_list OR array['YZ'] &lt;@ value_list)]", "[(array['Z'] &lt;@ type_list AND array['30'] &lt;@ value_list)]", "[(array['KZA'] &lt;@ type_list AND (array['AM'] &lt;@ value_list OR array['UA'] &lt;@ value_list OR array['RC'] &lt;@ value_list OR array['WEQZ4.5'] &lt;@ value_list)]"] r = re.compile(r"array\['(.*?)']") # Compile the regex for s in strs: m = r.search(s) # Get the key value if m: # If we found it array_vals = r.findall(s, s.index("&lt;@ type_list")) # Get the values if len(array_vals) &gt; 0: # If there is at least 1 value, build the result print("(type_value LIKE ANY ({}))".format(",".join(["'%{}={};%'".format(m.group(1), x) for x in array_vals]))) Output: (type_value LIKE ANY ('%X=X6;%','%X=A6.5;%','%X=YZ;%')) (type_value LIKE ANY ('%Z=30;%')) (type_value LIKE ANY ('%KZA=AM;%','%KZA=UA;%','%KZA=RC;%','%KZA=WEQZ4.5;%')) See the Python demo. You will probably want to add a check if array_vals contain at least one value, e.g. using if len(array_vals) &gt; 0:.
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51375065
has comment: http://stackoverflow.com/comment/89723371

http://stackoverflow.com/comment/89705293
has text: Thank you, Joshua. Yes, I would like to understand on how to count status for each IP per day. Can you please give me overview on how to solve this? I want to try by myself.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51366371

http://stackoverflow.com/q/51460131
tagged with: python-2.7
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89890019
has comment: http://stackoverflow.com/comment/89889716
has comment: http://stackoverflow.com/comment/89889591
has answer: http://stackoverflow.com/a/51460306
has comment: http://stackoverflow.com/comment/89889616
has body: I'm trying to write a code which solves the reduced fractions problem seen online. For small values of n and d I get an answer out, however when trying to solve for large values of n and d, the for loop takes so long that I get a memory error (after waiting for the code to run for about an hour). "By listing the set of reduced proper fractions for d ≤ 1,000,000 in ascending order of size..." Is there a way I can check all possible fractions for large values of n without using a lengthy for loop? fraction_list = [] for d in range(1000000): for n in range(1000000): if n&lt;d and n/d ==0 : frac = float(n) / float(d) #print(frac) fraction_list.append(frac) index_num = (fraction_list.index(float(2.0/7.0))) sorted(fraction_list, key=float) print(fraction_list[index_num]) print("the fraction which is to the left is" + fraction_list[index_num -1])
tagged with: python
upvote count: 2
has comment: http://stackoverflow.com/comment/89889561
has title: Python: for loop taking too long
downvote count: 1
has comment: http://stackoverflow.com/comment/89889589
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51460306
score: 1
type: Question

http://stackoverflow.com/comment/89931824
comment on: http://stackoverflow.com/q/51481431
score: 0
has text: @madmatrix He's basically trying to get all lines transcribed on a given date but they are not all tagged with the date, so simply checking for the date at the beginning of the string doesn't work
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89773562
comment on: http://stackoverflow.com/a/51395348
type: AnswerComment
type: Comment
score: 0
has text: Thanks - so that works, but I am not sure why? Can you explain your solution to me a little?

http://stackoverflow.com/comment/89851350
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51439529
has text: Yes, that's true. In your timing code shoudn't it be `n*(n-1)`?

http://stackoverflow.com/comment/89816651
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51422883
has text: My data frame is currently type string but need to converted it to float, will this work?

http://stackoverflow.com/comment/89837422
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51433031
has text: OK, `f output: # write the output to a file with the specified name` Yeah, that's obviously not going to work with a file object. The first thing it does with it is calls `os.path.exists(output)`. More to the point, it looks like this is just a wrapper around subprocessing the command-line tool, so all `output=spam` does is add `--output spam` to a list of args.

http://stackoverflow.com/q/51362432
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89697060
answer count: 5
downvote count: 2
tagged with: python
has title: How to create several classes in a loop?
possible better answer: http://stackoverflow.com/a/51362550
has comment: http://stackoverflow.com/comment/89697538
has answer: http://stackoverflow.com/a/51362550
has answer: http://stackoverflow.com/a/51362707
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51362519
tagged with: loops
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51362630
has answer: http://stackoverflow.com/a/51362533
score: -1
has comment: http://stackoverflow.com/comment/89703638
tagged with: class
has body: I have a script, where I have to define several classes: class track1: number = 0 min_class = 0 members = [] class track2: number = 0 min_class = 0 members = [] class track3: number = 0 min_class = 0 members = [] And so on... Later I change in some classes the values. For example: min_class will be 10 in the classes 2,5 and 6. Or the members list will contain different members in every different track. But sometimes I have to define four classes, sometimes 16. So my question is: Is there a way, to define classes in Python in a loop? for i in range(x): #define class track i
accepted answer: http://stackoverflow.com/a/51362630

http://stackoverflow.com/comment/89703301
score: 0
has text: can you provide both original images? the logo and the landscape. Actually you just need to set to 0 everything that is not black in the logo in the image and then add it with the logo
comment on: http://stackoverflow.com/q/51365126
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51422967
upvote count: 5
answer count: 5
tagged with: python
duplicate of: http://stackoverflow.com/q/3052793
has comment: http://stackoverflow.com/comment/89816802
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89816789
possible better answer: http://stackoverflow.com/a/51423136
has comment: http://stackoverflow.com/comment/128087794
has title: Use the result of the return of one function in another function
linked to: http://stackoverflow.com/q/19256989
has answer: http://stackoverflow.com/a/51423012
type: Question
score: 3
has comment: http://stackoverflow.com/comment/89816822
linked to: http://stackoverflow.com/q/3052793
has answer: http://stackoverflow.com/a/51423010
accepted answer: http://stackoverflow.com/a/51423010
has body: I know there are several questions about this, I read but I could not understand. I'm trying to use the result of the return of one function in another: def multiplication(a): c = a*a return c def subtraction(c): d = c - 2 return d print(subtraction(c)) Output: NameError: name 'c' is not defined I know that there is a possibility of using global variables, but I have seen that this is not a good idea since the variables can change their value. EDIT: These two functions are just idiotic examples. I have two functions with words and I need to use the return of the first function in the second function. In case of this my idiotic example, I need the result of the first function (c) in the second function.
downvote count: 2
has answer: http://stackoverflow.com/a/51423136
has comment: http://stackoverflow.com/comment/128694651
has comment: http://stackoverflow.com/comment/89816801
has answer: http://stackoverflow.com/a/51423091
favorite count: 0
has answer: http://stackoverflow.com/a/51423092

http://stackoverflow.com/q/51346119
accepted answer: http://stackoverflow.com/a/51346159
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51346159
score: 1
has body: I have two excel Excel 1 files language blank comment code 15 C++ 66 35 354 1 C/C++ Header 3 7 4 Excel 2 files language blank comment code 16 C++ 33 35 354 1 C/C++ Header 3 7 4 1 Python 1 1 1 Trying to get combined excel files language blank comment code 31 C++ 99 70 708 2 C/C++ Header 6 14 8 1 Python 1 1 1 Any tips in pandas
upvote count: 1
tagged with: excel
type: Question
possible better answer: http://stackoverflow.com/a/51347480
has title: Pandas Combining data in two excel
has answer: http://stackoverflow.com/a/51347480

http://stackoverflow.com/comment/106294935
type: Comment
comment on: http://stackoverflow.com/a/51387713
has text: Note that this answer doesn't sort the sequences; it only tries to sort any maps nested within the sequence. If you also want the sequences to be sorted (such as if 'k', 'l', 'm' were a seq instead of a map, you'll want to add `data.sort()` before the first return after the for loop where it iterates through the list.
type: AnswerComment
score: 0

http://stackoverflow.com/q/51348084
upvote count: 1
has comment: http://stackoverflow.com/comment/89668892
downvote count: 1
type: Question
has title: regex output to a text file
has answer: http://stackoverflow.com/a/51348339
score: 0
answer count: 1
has body: I'm trying to write a python Script that write regex output (IP Addresses) to a text file. The script will rewrite the file each time it runs. Is there any better way to do it? import re pattern = re.compile(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}') with open('test.txt', 'r') as rf: content = rf.read() matches = pattern.findall(content) open('iters.txt', 'w').close() for match in matches: with open('iters.txt', 'a') as wf: wf.write(match + '\n')
favorite count: 0
has comment: http://stackoverflow.com/comment/89668785
tagged with: python
accepted answer: http://stackoverflow.com/a/51348339
tagged with: regex
type: AnsweredQuestion

http://stackoverflow.com/comment/89687217
type: Comment
has text: I think it's the answer. The original question asks for how to convert `datetime` to `numeric`, but that code is irrelevant without fixing the source of the attribute error. Once that is fixed, I don't think the conversion will be needed.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51357529

http://stackoverflow.com/a/51328129
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51327767
answers question: http://stackoverflow.com/q/51327767
type: AcceptedAnswer
has body: If you're willing to consider other packages, take a look at pandas which is built on top of numpy. You can read sql statements directly into a dataframe, then filter. For example, import pandas sql = '''SELECT * FROM &lt;table&gt; WHERE &lt;condition&gt;''' df = pandas.read_sql(sql, &lt;connection&gt;) # Your output might look like the following: 0 1 2 0 12346 (135:2345678, 212:4354670, 198:9876545) (Flag1, Flag2, Flag3) 1 12345 (136:2343678, 212:4354670, 198:9876545) (Flag1, Flag2, Flag4) # Format your records into rows # This part will take some work, and really depends on how your data is formatted # Do you have repeated values? Are the records always the same size? # Select only the rows where relationship = 125 rel_125 = df[df['Relationship'] = 125] The pandas formatting is more in depth than fits in a Q&amp;A, but some good resources are here: 10 Minutes to Pandas. You can also filter the rows directly, though it may not be the most efficient. For example, the following query selects only the rows where a relationship starts with '212'. df[df['Relationship'].apply(lambda x: any(y.startswith('212') for y in x))]

http://stackoverflow.com/comment/89814448
score: 0
has text: Thanks Elliad, I did look at this but it is definately a good link to include in the post!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51420951

http://stackoverflow.com/comment/89706890
score: 0
type: Comment
type: QuestionComment
has text: I updated the error to the specific one caused by the code given. I am sure, there are no other entries in the User table. Any thoughts?
comment on: http://stackoverflow.com/q/51361689

http://stackoverflow.com/q/51446661
type: Question
has answer: http://stackoverflow.com/a/51446784
tagged with: optimization
has answer: http://stackoverflow.com/a/51446738
score: 0
upvote count: 1
has body: So I have the following example of code; simultaneously iterates over multiple sequences combined with enumerate, assigning the values to tuple variable after which outputs it. def PairValuesWithIndexToTuples(self,val1,val2): t =() for i, (a,b) in enumerate(zip(val1,val2)): t += (i,a,b) return t What I want to achieve is something like this if it is possible: I have been searching around but I could not find yet a solution which achieves my results from the method written above: def PairValuesWithIndexToTuples(self,val1,val2): t =() t += for i, (a,b) in enumerate(zip(val1,val2)) return t or return t+= for i, (a,b) in enumerate(zip(val1,val2))
downvote count: 1
has comment: http://stackoverflow.com/comment/89863538
tagged with: simplify
has answer: http://stackoverflow.com/a/51446778
favorite count: 0
has title: How to assign the for loop values in variable in one line
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51446791
tagged with: python
answer count: 4
linked to: http://stackoverflow.com/q/952914

http://stackoverflow.com/comment/89754128
score: 0
has text: @roganjosh Yes i am pressing enter after each input. Also I editted the trackeback error. Thanks
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51390930

http://stackoverflow.com/comment/89783290
type: QuestionComment
comment on: http://stackoverflow.com/q/51406066
score: 0
has text: Question, is your LTCG Holdings Corp and Long Term Care Group Inc. example reversed by chance?
type: Comment

http://stackoverflow.com/q/51409040
type: Question
tagged with: graph
has body: I'm having a hard time returning the exact information I'm looking for. Essentially, I want to return all edges (in either direction) of a certain type. I'd like to get the vertex IDs and the edge parameters in a list. Ideally, my output format looks like this: { "from": "vertex_id_1", "to": "vertex_id_2", "similarity": 0.45 } I've been using g.both().vertexMap().toList() to get the similarities, but I'm not able to get the vertex IDs this way.
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51409102
tagged with: python
favorite count: 0
upvote count: 1
tagged with: amazon-neptune
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51409102
has title: Gremlin Python: Returning vertex IDs and edge properties in a list
tagged with: gremlin

http://stackoverflow.com/q/51352479
type: Question
accepted answer: http://stackoverflow.com/a/51352502
answer count: 2
has answer: http://stackoverflow.com/a/51352502
score: 0
has answer: http://stackoverflow.com/a/51352522
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89677461
tagged with: python
has body: I want to create a function which returns the lengths of different input objects and returns -1 if there is not length.The expected output is below: my_dict = {'a': 23, 'b': 8} len_safe(my_dict) 2 len_safe(7) -1 I want to use exception handling but am confused as to how to start.
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51352522
has title: Creating a function which return lengths

http://stackoverflow.com/q/51364868
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51365215
tagged with: kivy
favorite count: 0
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has body: So I am working off of this tutorial: https://youtu.be/j9PqNe3J_Cc?t=1m55s At the time stamp in that link (1:55) the guy goes over to another file he created. This file is a .kv file. When I try to create a new file, there are multiple options, but no kivy file type option. Should I just create a text file, or is there something I am missing? For the record, I am using PyCharm, just like the guy in the video (also I'm using Mac) Lastly, the guy's first file is called kivytut.py. Is that simply what he chose to name it, or are there generally accepted names for kivy files that people usually use? Thanks in advance!
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/60702598
has title: How to create a Kivy file (.kv)
score: 1

http://stackoverflow.com/comment/89811241
comment on: http://stackoverflow.com/a/51395145
has text: I originally tried line by line using jupyter and ran into that error. I just tried it again on the python shell and it worked perfectly. You are amazing!!! I can't thank you enough!!! =) Would it be difficult to add the other stat categories, too? No worries if it is. I will study this code and see if I can figure it out. Thanks again @gangabass!
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/139879394
has text: This is a very misleading wrong answer. Should be removed.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/66845103

http://stackoverflow.com/comment/89680261
has text: No, it's not creating a local `GV`, or a local `GV.weapon`. I think I know where your mind is heading, but that's a rare problem, and one you only run into if you start doing `import`s inside a function definition.
type: Comment
comment on: http://stackoverflow.com/q/51353743
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89823003
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51425564
has text: I get a different error this time - ValueError: Location based indexing can only have [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] types.

http://stackoverflow.com/comment/89921397
score: 0
type: QuestionComment
type: Comment
has text: Does your gif have more than 255 colors?
comment on: http://stackoverflow.com/q/51476405

http://stackoverflow.com/q/51326285
has comment: http://stackoverflow.com/comment/89627664
has title: print(raw_message['altitude']) TypeError
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51326444
downvote count: 2
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89627756
has comment: http://stackoverflow.com/comment/89628747
accepted answer: http://stackoverflow.com/a/51326444
type: Question
has comment: http://stackoverflow.com/comment/89627785
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/89628065
has body: I have tried on all forums how to fix this error, but I do not understand what I'm doing wrong. If you can give me a hand you do me a big favor, thank you very much. Want to clarify that I looked for solutions for all and this post is my last chance Error output: Traceback (most recent call last): File "test2.py", line 35, in &lt;module&gt; client.run(callback=process_beacon, autoreconnect=True) File "/Users/gionatadonati/Desktop/python-ogn-client/ogn/client/client.py", line 74, in run callback(packet_str) File "test2.py", line 29, in process_beacon print(raw_message['altitude']) TypeError: string indices must be integers Code: from ogn.client import AprsClient from ogn.parser import parse, ParseError def inRange_square(s, minLat, maxLat, minLon, maxLon, minAlt, maxAlt): if s.get('longitude', 0) &lt; minLon or s['longitude'] &gt; maxLon or s['latitude'] &lt; minLat or s['latitude']&gt;maxLat or s['altitude']&lt;minAlt or s['altitude']&gt;maxAlt : return False return True def processPlane(plane): #if(inRange_square(plane, 46.158593, 46.166797, 8.891647, 8.869160, 210, 1000)): if(inRange_square(plane, 46.127356, 46.441491, 9.276551, 8.460816, 210, 1000)): print("The plane is in range") print('Received {raw_message}'.format(**beacon)) else: #print("The plane is not in range") 'odd' def process_beacon(raw_message): try: beacon = parse(raw_message) #print('Received {raw_message}'.format(**beacon)) processPlane(beacon) except ParseError as e: print('Error, {}'.format(e.message)) print(raw_message['altitude']) client = AprsClient(aprs_user='N0CALL') client.connect() try: client.run(callback=process_beacon, autoreconnect=True) except KeyboardInterrupt: print('\nStop ogn gateway') client.disconnect() Output of print(raw_message): RND000000&gt;APRS,qAS,EKHG:/131942h6505.31S/18136.75W^054/325/A=002591 !W31! idA4000000 +099fpm +1.8rot FL029.04 21.5dB 4e +1.6kHz gps11x17

http://stackoverflow.com/a/56140828
has comment: http://stackoverflow.com/comment/98925524
has body: If you want further information, you will need to examine the frame argument that is passed into the tracing function. In particular, you want to look at frame.f_lasti to find the last instruction executed and frame.f_code.co_code to access that instruction. Using those two together will give you the actual opcode. If you want the mnemonic, then you will want to use dis.opname; but if you simply what to match it with another opcode, then you can use dis.opmap instead. The following example is contrived, but it demonstrates some of what is possible using the hints just provided: #! /usr/bin/env python3 import dis import sys def main(): dis.dis(add) sys.settrace(get_trace(False, get_callback(celebrate))) total = add(1, 2) print(f'total = {total}') sys.settrace(None) total = add(3, 4) print(f'total = {total}') print('Done') def get_trace(trace_lines=True, opcode_callback=None): trace_opcodes = callable(opcode_callback) # noinspection PyUnusedLocal def trace(frame, event, arg): frame.f_trace_lines = trace_lines frame.f_trace_opcodes = trace_opcodes if trace_opcodes and event == 'opcode': opcode = frame.f_code.co_code[frame.f_lasti] opname = dis.opname[opcode] opcode_callback(frame, opcode, opname) return trace return trace def get_callback(return_handler=None): handle_return = callable(return_handler) def echo_opcode(frame, opcode, opname): print(f'# {opname} ({opcode}) #') if handle_return and opcode == dis.opmap['RETURN_VALUE']: return_handler(frame) return echo_opcode # noinspection PyUnusedLocal def celebrate(frame): print('/-------------------\\') print('| We are returning! |') print('\\-------------------/') def add(a, b): return a + b if __name__ == '__main__': main()
type: Answer
answers question: http://stackoverflow.com/q/51349074
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/98914321
accepted answer of: http://stackoverflow.com/q/51349074
has comment: http://stackoverflow.com/comment/98925754
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51415520
score: 0
tagged with: pandas
answer count: 1
type: UnansweredQuestion
has title: matplotlib show minutes time-series in hour (change xticklabels)
tagged with: python
has comment: http://stackoverflow.com/comment/89825662
has answer: http://stackoverflow.com/a/51415753
tagged with: timeserieschart
type: Question
tagged with: time-series
tagged with: matplotlib
has body: My code which show if product is stockout in every minutes in a day: sq_t = df_stock_quantity_log'is_stockout'.resample('T').ffill().fillna(0).astype(int).squeeze() nrows =10 fig, axs = plt.subplots(nrows=nrows, figsize=(18, 40)) for idx, date in enumerate(df.index[:nrows]): s = sq_t[date.strftime('%Y-%m-%d')] if len(s) &lt; 24*60: s = np.concatenate((np.zeros(24*60-len(s)),s)) axs[idx].plot(s, label=idx) plt.legend(loc='best') plt.show() The output is I want to change xtick to 0 ~ 23 and alter code to fig, axs = plt.subplots(nrows=nrows, figsize=(18, 40)) for idx, date in enumerate(df.index[:nrows]): s = sq_t[date.strftime('%Y-%m-%d')] if len(s) &lt; 24*60: s = np.concatenate((np.zeros(24*60-len(s)),s)) axs[idx].plot(s, label=idx) axs[idx].set_xticks(s) axs[idx].set_xticklabels(['h %d' % (ii/ 60,) for ii in range(0, 24*60 , 60)]) plt.legend(loc='best') plt.show() But the result is very bad: sq_t information: PS: I know the xticklabel of first day pic is wrong, because I don't set proper datetime index to it. It just for example here .

http://stackoverflow.com/comment/89686608
comment on: http://stackoverflow.com/a/51340427
has text: Thanks for the solution. Indeed, I want to do something with AWS tags actually want to filter them. I already had figured out a solution (long version of it) but I want to understand the other ways I could have done it. I asked this question because I didn't find any proper help on how to do it. Maybe your solution would help people solve such queries in many different ways. :)
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89790677
has text: Duplicate of many, many questions: https://stackoverflow.com/search?q=%E2%80%9Cunexpected+EOF+while+parsing%E2%80%9D
comment on: http://stackoverflow.com/q/51409601
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/a/54719150
answers question: http://stackoverflow.com/q/51334970
type: Answer
has body: The contribution to the cost(loss) from each data point (xi, yi), in your system is . `Li = (1/N) * (yi - (m*xi + b))**2 The total cost will be the sum of all Li-s. You have N data points and (1/N) is a normalizing term, so that the value of your cost is consistent even if you change N. Now partial differentiation of Li wrt m gives Li_m = (1/N) *2 * (yi - (m*xi + b)) * -xi = -(2/N) * xi * (yi - (m*xi + b)) And partial differentiation of Li wrt b gives Li_b = (1/N) * 2 * (yi -(m*xi + b)) * -1 = (-2/N) * (yi - (m*xi + b))
score: 0

http://stackoverflow.com/comment/89796522
has text: Python functions don't represent mathematical functions. They represent instructions for doing things. For Python functions, supporting the `*` operator would be more confusing than useful.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51412366

http://stackoverflow.com/q/51338005
upvote count: 0
tagged with: string
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/51340779
has answer: http://stackoverflow.com/a/51338143
has title: How do I remove a specific character if and only if it repeats consecutively using Python?
answer count: 3
has body: I have provided an elaborate version of my question below: Consider the string "apples----are-the--best---fruits" I want to remove all '-'s only if they repeat consecutively. So my output should be "apples-are-the-best-fruits". How can I accomplish this? Thanks.
has answer: http://stackoverflow.com/a/51338120
type: UnansweredQuestion
score: -4
has comment: http://stackoverflow.com/comment/89650470
downvote count: 4

http://stackoverflow.com/a/51411723
has body: As you can see in the picture, site submit an AJAX request to www.way2sms.com/re-login so it would be better to submit your request directly here and then check response (returned content) Something like this would help: session = requests.Session() URL = 'http://www.way2sms.com/re-login' data = {'mobileNo': '94########', 'password': 'pass'} # Make sure to remove '+' from your number post = session.post(URL, data=data) if post.text != 'login-reg': # This returned when i did input invalid credentials print('Login successful') else: print(post.text) Since i don't have an account there you may also need to check success response
has comment: http://stackoverflow.com/comment/89805126
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51400941
score: 1

http://stackoverflow.com/comment/89862265
type: QuestionComment
has text: FYI, you can check the version with `import sys; print(sys.version)`
comment on: http://stackoverflow.com/q/51445945
score: 0
type: Comment

http://stackoverflow.com/a/51420975
has body: As per your code trials I am still not sure about your usecase and the reason why you want to use the until condition as until_not as in: page_loaded = wait.until_not(lambda driver: driver.current_url == "http://www.demo.guru99.com/V4/manager/Managerhomepage.php") Incase your usecase is to validate whether on effective/wrong credentials the application takes the user to the page with url as http://www.demo.guru99.com/V4/manager/Managerhomepage.php or not, you can use the following solution: To validate the successful/unsuccessful login, you can either check for the new URL to contain Managerhomepage or the new Page Title to contain Guru99 Bank Manager HomePage. Hence you can use WebDriverWait with expected-conditions set either as url_contains() or title_contains() as follows: Code Block: from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException from selenium.common.exceptions import UnexpectedAlertPresentException options = webdriver.ChromeOptions() options.add_argument("start-maximized") options.add_argument('disable-infobars') driver=webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe') driver.get("http://www.demo.guru99.com/V4/") driver.find_element_by_xpath('/html/body/form/table/tbody/tr[1]/td[2]/input').send_keys('mngr144003') driver.find_element_by_xpath('/html/body/form/table/tbody/tr[2]/td[2]/input').send_keys('bUtymYr') driver.find_element_by_xpath('/html/body/form/table/tbody/tr[3]/td[2]/input[1]').click() try: WebDriverWait(driver, 10).until(EC.url_contains("Managerhomepage")) #WebDriverWait(driver, 10).until(EC.title_contains("Manager")) print("Login is successful. Page Title is : %s" %driver.title) except (TimeoutException,UnexpectedAlertPresentException): print("Loading timeout expired") driver.quit() Console Output(successful login): Login is successful…
type: Answer
answers question: http://stackoverflow.com/q/51419229
score: 0

http://stackoverflow.com/a/51408751
has comment: http://stackoverflow.com/comment/89829767
has body: Is it binary classification problem? Sigmoid is applicable in binary classification problems only. Softmax and Sigmoid theoretically are same but practically softmax gives at maximum 1% better accuracy. Since your result has dropped from 95% which indicates some other problem with the way you provide labels to the network or may be the problem with the network itself. Verify labels are in the right format or any inherent issue with the network. Also, verify with sigmoid there must be one output otherwise the number of outputs is the number of classes.
type: Answer
has comment: http://stackoverflow.com/comment/89810865
score: 0
answers question: http://stackoverflow.com/q/51408417
has comment: http://stackoverflow.com/comment/89792021

http://stackoverflow.com/a/51409653
score: 1
has body: Those plots are not identical. You are plotting open/close prices of a stock. They are very similar - but not identical: You can see this if you overlay them - I used gimp for that, coloring one black and using a partially overlay. Open/Close prises for the same stock will vary a little, but not much - and you are dealing with about 20 $ (?) per cm resolution. Unless your stock crashes you won't see wildly different plots.
answers question: http://stackoverflow.com/q/51409457
upvote count: 1
type: Answer
downvote count: 0

http://stackoverflow.com/a/51468737
score: 87
upvote count: 87
has body: SQLAlchemy effectively translates your query expressed in Python into SQL. But it does that at a relatively superficial level, based on the data type that you assign to the Column when defining your model. This means that it won't necessarily replicate Python's datetime.datetime API on its DateTime construct - after all, those two classes are meant to do very different things! (datetime.datetime provides datetime functionality to Python, while SQLAlchemy's DateTime tells its SQL-translation logic that it's dealing with a SQL DATETIME or TIMESTAMP column). But don't worry! There are quite a few different ways for you to do achieve what you're trying to do, and some of them are super easy. The three easiest I think are: Construct your filter using a complete datetime instance, rather than its component pieces (day, month, year). Using SQLAlchemy's extract construct in your filter. Define three hybrid properties in your model that return the payment month, day, and year which you can then filter against. Filtering on a datetime Object This is the simplest of the three (easy) ways to achieve what you're trying, and it should also perform the fastest. Basically, instead of trying to filter on each component (day, month, year) separately in your query, just use a single datetime value. Basically, the following should be equivalent to what you're trying to do in your query above: from datetime import datetime todays_datetime = datetime(datetime.today().year, datetime.today().month, datetime.today().day) payments = Payment.query.filter(Payment.due_date &gt;= todays_datetime).all() Now, payments should be all payments whose due date occurs after the start (time 00:00:00) of your system's current date. If you want to get more complicated, like filter payments that were made in the last 30 days. You could do that with the following code: from datetime import datetime, timedelta filter_after = datetime.today() - timedelta(days = 30) payments = Payment.query.filter(Payment.due_d…
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51451768
answers question: http://stackoverflow.com/q/51451768
type: Answer

http://stackoverflow.com/q/51328479
tagged with: logging
has body: I am using a dictConfig to configure my logging: logconfig = { 'version': 1, 'disable_existing_loggers': False, 'formatters': {'standard': {'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s', 'datefmt': '%d-%m-%Y %H:%M:%S'}, }, 'handlers': {'debug': {'level': 'DEBUG', 'formatter': 'standard', 'class': 'logging.FileHandler', 'filename': 'Ops Log Debug.log', }, 'general': {'level': 'INFO', 'formatter': 'standard', 'class': 'logging.FileHandler', 'filename': 'Ops Log.log', }, }, 'loggers': {'': {'handlers': ['debug'], 'level': 'DEBUG', 'propagate': False}, 'mainlogger': {'handlers': ['general'], 'level': 'INFO', 'propagate': False}, } } In case it matters, it is stored in a separate .py file and imported into my main script. The code I'm using to run it is: import LoggerConfig import logging logging.config.dictConfig(LoggerConfig.logconfig) my_logger = logging.getLogger('main') How do I get my script to use the 'mainlogger' logger in my dict instead of root? Am I going about this the wrong way? - I wanted 2 loggers: 1 for debug level+ and 1 for info level+ each writing to their own file.
type: Question
has comment: http://stackoverflow.com/comment/89632490
has title: How to access a named logger in a dictConfig? i.e. not root
score: 0
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89635977
tagged with: python

http://stackoverflow.com/comment/89827966
score: 0
type: Comment
type: QuestionComment
has text: @jpp I think this example using `enumerate` might be sufficiently weird to deserve its own answer
comment on: http://stackoverflow.com/q/51428183

http://stackoverflow.com/comment/89805369
type: QuestionComment
has text: The issue is that the request goes directly to the pre-defined /updateuser endpoint. I need to be able to intercept this request, since I can't change the logic in the actual endpoint.
score: 0
comment on: http://stackoverflow.com/q/51415879
type: Comment

http://stackoverflow.com/a/51448410
has body: A short &amp; simple change in your existing code: &gt;&gt;&gt; class Factorial: ... def __call__(self,n): ... if n == 0: ... return 1 ... else: ... return n * self.__call__(n - 1) ... &gt;&gt;&gt; Factorial = Factorial() &gt;&gt;&gt; Factorial(4) 24 &gt;&gt;&gt;
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51447968

http://stackoverflow.com/comment/89861149
type: Comment
has text: Technically yes, but I have no idea what the csv look like, with the structure you could limit the filter to only the relevant column. ( "selected_details in x[0]" for example)
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51445241

http://stackoverflow.com/comment/90367731
comment on: http://stackoverflow.com/a/51435188
type: AnswerComment
score: 0
type: Comment
has text: thanks again @merv. I hope the edit makes the question cleared. Timofey's answer does the job for me.

http://stackoverflow.com/comment/89815514
has text: "However, I am working now with tables of more than 100 fields for a complex UI" => you may want to use some lightweight ORM (peewee for example) instead then.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51421518
type: QuestionComment

http://stackoverflow.com/comment/89869502
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51447720
type: Comment
has text: 3. Are you looking for [collocations](https://en.wikipedia.org/wiki/Collocation)? 4. `my_string.replace('3', 'three')`?

http://stackoverflow.com/a/51432971
upvote count: 1
has comment: http://stackoverflow.com/comment/89837102
has body: numpy.vstack? import numpy as np myArray = np.arange(10) lowLimit = 2 highLimit = 5 n = 10 z = myArray[lowLimit:highLimit] q = np.vstack((z,)*n) OR numpy.tile: q = np.tile(z, n).reshape(n, z.shape[0])
answers question: http://stackoverflow.com/q/51432666
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/comment/89994365
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51439143
type: AnswerComment
has text: Not sure I get your first question: some fields (`"filler"`, `"subjtext"`, `"objtext"`, ...) in the items of `reldicts` contain strings in the format `"token/POS token/POS"`, so you can add conditions to match them in the filter. Padding: if I understood correctly [semi_rel2reldict](https://www.nltk.org/_modules/nltk/sem/relextract.html#semi_rel2reldict) stops if there is no right context, instead of considering an empty right context, padding just simulates an empty right context (which was necessary to match (cat, sit on, mat) in your example).

http://stackoverflow.com/q/51373351
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/9546324
has title: Adding to PATH via Python in Windows
type: Question
has body: I want to add GeckoDriver exe to PATH environment variable via a python script, I found an answer on StackOverflow but this didn't work for me. My code says the path was added, but when I check in cmd or through the system settings, it isn't there: cwd = os.getcwd()+"\\driver\\" if 'geckodriver' not in os.environ: print("Added") os.environ["Path"] = cwd
answer count: 2
has answer: http://stackoverflow.com/a/51373451
score: 0
possible better answer: http://stackoverflow.com/a/51373407
has answer: http://stackoverflow.com/a/51373407
linked to: http://stackoverflow.com/q/531998
accepted answer: http://stackoverflow.com/a/51373451
tagged with: path

http://stackoverflow.com/q/51413068
favorite count: 0
upvote count: 10
tagged with: python
type: AnsweredQuestion
downvote count: 0
tagged with: image-processing
tagged with: scipy
tagged with: signal-processing
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/51414253
score: 10
has answer: http://stackoverflow.com/a/51414253
answer count: 1
has title: Calculate Signal to Noise ratio in python scipy version 1.1
has body: I have looked around online and it seems that the signaltonoise ratio function inside the scipy.stats is deprecated and is not available in version 1.1. Is there any other equivalent method inside scipy package since I have not been able to find it online. And if not scipy then is there any other library recommended for such calculations ?

http://stackoverflow.com/comment/89985628
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51460571
has text: @AbhijeetArora Make sure that you set `keep_cross_validation_predictions = True` or it will not store the CV predictions.
type: Comment

http://stackoverflow.com/comment/89755409
type: QuestionComment
type: Comment
score: 2
comment on: http://stackoverflow.com/q/51391713
has text: You really shouldn't be using `time` for benchmarking, and a single-run test for something that's mostly disk I/O is especially bad, but since you've already done it, why don't you tell us what the results were?

http://stackoverflow.com/comment/123220918
has text: ```import pandas as pd x = pd.DataFrame(np.random.rand(10, 10), index=pd.date_range(end='1/1/2018', periods=10), columns=list('abcdefghij')) x.iloc[:5, :].to_hdf('append.h5', format='table', key='part1', mode='a', complevel=9, complib="blosc:zstd") y = pd.read_hdf('append.h5', key='part1', mode='r')``` works for me under pandas 1.2.1 . Did you open a separate issue?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/54889005

http://stackoverflow.com/comment/89825668
score: 1
has text: the code shown here works, what I can't achieve is to import News model into tasks.py @HemanthSP
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51426895

http://stackoverflow.com/a/51373030
answers question: http://stackoverflow.com/q/51372886
upvote count: 1
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/89717852
has comment: http://stackoverflow.com/comment/89717950
downvote count: 0
score: 1
has body: You can use SKLearn CountVectorizer or TF-IDF. Here's a rough outlay for an approach: from sklearn.feature_extraction.text import CountVectorizer from sklearn.ensemble import RandomForestClassifier from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split count_vect = CountVectorizer() text = ['text1', ..] targets = ['abuse', ...] matrix = count_vect.fit_transform(text) encoder = LabelEncoder() targets = encoder.fit_transform(targets) randomForest = RandomForestClassifier() randomForest.fit(matrix, targets)
has comment: http://stackoverflow.com/comment/89717922
accepted answer of: http://stackoverflow.com/q/51372886
has comment: http://stackoverflow.com/comment/89717808

http://stackoverflow.com/comment/89761037
comment on: http://stackoverflow.com/a/51394825
score: 0
has text: thanks, it works as expected
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89808971
type: Comment
type: QuestionComment
has text: Can you provide example input and expected output?
comment on: http://stackoverflow.com/q/51419025
score: 4

http://stackoverflow.com/comment/89796372
score: 0
type: Comment
has text: I got the folowing: `----> 3 new_list.append(i.split(' ')) 4 print(new_list) AttributeError: 'list' object has no attribute 'split'`
comment on: http://stackoverflow.com/a/51412348
type: AnswerComment

http://stackoverflow.com/q/51343313
type: UnansweredQuestion
tagged with: python
has title: JSON Data formatting incorrectly in Python Requests JSON API POST statement
score: 1
has body: I am trying to post a set of json data to a server. I seem to be missing something because I am getting errors that include the following: (Note:CPAPI is the name of the API) "SerializationException - could not deserialize "application/json' request using CPAPI.ServiceModule.AddCustomerRequest" \nError: System.Runtime.Serialization.SerializationException:Type definitions should start with a '{', expecting serialized type > > 'AddCustomerRequest' got string starting with: \"{\\"SY_WRKGRP\\":{\\"WRKGRP_ID\\":\\"7\\"},\\"AR_CUST\\":\r\n Here is my code: import requests, json url = "https://shipping:52000/customer/" payload1 = '{"SY_WRKGRP":{"WRKGRP_ID":"7"},"AR_CUST": {"CUST_NO":"6377123456","NAM":"Rob O","NAM_UPR":"ROBO","FST_NAM":"Rob","FST_NAM_UPR":"ROB","LST_NAM":"O"}}' headers = { "Accept": "application/json", "Authorization": "XXXX", "APIKey": "YYYY", "Content-Type": "application/json" } r = requests.post(url, json=payload1, headers=headers,verify=False) print() print(r) print(r.text) Any idea what I am missing here?
upvote count: 1
tagged with: python-requests
type: Question
tagged with: http://stackoverflow.com/tag/json
tagged with: api
answer count: 1
has answer: http://stackoverflow.com/a/51343570
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/51417815
has comment: http://stackoverflow.com/comment/89806817
has comment: http://stackoverflow.com/comment/89806942
score: 0
has body: I think you have misspelled over here for i in nodos2: for j in nodos2: if i!=j: model.addConstr(u[i]-u[j]+(len(Cnew)-1)*x[i,j]&lt;=len(Cnew)-2,name="R3[%s][%s]"%(i,j)) it should be for i in nodos: for j in nodos2: if i!=j: model.addConstr(u[i]-u[j]+(len(Cnew)-1)*x[i,j]&lt;=len(Cnew)-2,name="R3[%s][%s]"%(i,j)) see the first i loop should have nodos but you mistyped it nodos2 You should name your variables properly your function takes 3 parameters you're passing only one
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89806906
has comment: http://stackoverflow.com/comment/89807148
accepted answer of: http://stackoverflow.com/q/51417739
has comment: http://stackoverflow.com/comment/89807093
has comment: http://stackoverflow.com/comment/89806720
answers question: http://stackoverflow.com/q/51417739
has comment: http://stackoverflow.com/comment/89806776
type: Answer
has comment: http://stackoverflow.com/comment/89806894

http://stackoverflow.com/q/51325660
accepted answer: http://stackoverflow.com/a/52538582
tagged with: tensorflow-estimator
score: 3
favorite count: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52538582
has body: How can I obtain the last global_step from a tf.estimator.Estimator after train(...) finishes? For instance, a typical Estimator-based training routine might be set up like this: n_epochs = 10 model_dir = '/path/to/model_dir' def model_fn(features, labels, mode, params): # some code to build the model pass def input_fn(): ds = tf.data.Dataset() # obviously with specifying a data source # manipulate the dataset return ds run_config = tf.estimator.RunConfig(model_dir=model_dir) estimator = tf.estimator.Estimator(model_fn=model_fn, config=run_config) for epoch in range(n_epochs): estimator.train(input_fn=input_fn) # Now I want to do something which requires to know the last global step, how to get it? my_custom_eval_method(global_step) Only the evaluate() method returns a dictionary containing the global_step as a field. How can I get the global_step, if for some reason, I can't have or don't want to use this method?
upvote count: 3
possible better answer: http://stackoverflow.com/a/51325661
has answer: http://stackoverflow.com/a/51325661
has title: How to get the last global_step from an tf.estimator.Estimator
tagged with: tensorflow
type: Question
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/89714691
has text: You're asking for a silver bullet solution for a huge problem in machine learning (the [bias variance tradeoff](https://en.wikipedia.org/wiki/Bias%E2%80%93variance_tradeoff)). If you want an easy start, get more data and don't expect that a model fit on 4 samples will be perfect.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51368466
type: Comment

http://stackoverflow.com/a/51434154
type: Answer
has comment: http://stackoverflow.com/comment/89839201
has body: There's no url /signup in your web. You're url is for accounts/signup/
score: 0
answers question: http://stackoverflow.com/q/51434119

http://stackoverflow.com/comment/89695886
score: 4
has text: " it doesn't work." is not really helpful. Did you install things they way I suggested? If so, what error did you get?
type: Comment
comment on: http://stackoverflow.com/q/51361797
type: QuestionComment

http://stackoverflow.com/q/51418114
has answer: http://stackoverflow.com/a/51418334
type: Question
has title: How to increment filename if destination file already exists in python?
score: -3
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89807188
favorite count: 0
has comment: http://stackoverflow.com/comment/89807504
type: UnansweredQuestion
has body: I want to copy a file like for example Ubuntu Nautilus file manager does. If destination already exists it creates new filename with larger index. I tried shutil.copyfile but it overwrites destination file. How to increment filename if destination file already exists in python?
tagged with: python
tagged with: copy-paste
has comment: http://stackoverflow.com/comment/89808258
downvote count: 3

http://stackoverflow.com/comment/89830812
type: Comment
type: QuestionComment
score: 0
has text: How are you attempting to run this code? if this is from an interactive window, did you remember to hit "ENTER" after your last line? If you're running from the command line, there's no output because you didn't print anything.
comment on: http://stackoverflow.com/q/51429878

http://stackoverflow.com/q/51401989
duplicate of: http://stackoverflow.com/q/10434599
tagged with: python
linked to: http://stackoverflow.com/q/34562950
has answer: http://stackoverflow.com/a/51402283
duplicate of: http://stackoverflow.com/q/34562950
duplicate of: http://stackoverflow.com/q/24279563
upvote count: 1
downvote count: 1
type: Question
tagged with: audio
duplicate of: http://stackoverflow.com/q/2017414
score: 0
answer count: 1
has body: I am really new to programming Flask APIs. Is there any way to send a audio file which is recorded on an android device to my flask server? Should I send audio file byte by byte or is there a way to send it directly ?
tagged with: flask
favorite count: 0
has title: Is there a way to send audio files to a Flask server?
type: UnansweredQuestion
tagged with: android

http://stackoverflow.com/comment/89856650
score: 0
type: Comment
has text: I got some errors when running your code. I have suggested some edits that seem to make it work as desired but I am not sure if it is good practice. Please look it over and let me know!
type: AnswerComment
comment on: http://stackoverflow.com/a/51432716

http://stackoverflow.com/a/51468726
score: 1
answers question: http://stackoverflow.com/q/51468593
type: Answer
upvote count: 1
has body: I would map pandas indices to numpy indicies: keys_dict = dict(zip(idxlbls, range(len(idxlbls)))) Then you may use the dictionary keys_dict to address the array elements by a pandas index: array[keys_dict[some_df_index], :]
downvote count: 0

http://stackoverflow.com/comment/89745379
comment on: http://stackoverflow.com/q/51385356
score: 0
type: Comment
type: QuestionComment
has text: That would be great, when I'm in the office tomorrow I will check it! Sadly I have the following error and couldn't solve it: ImportError: /home/mattes/anaconda3/envs/gmt-python2/lib/python3.6/site-packages/osgeo/../../../libgdal.so.20: undefined symbol: _ZN11xercesc_3_211InputSource11setEncodingEPKDs

http://stackoverflow.com/a/51397065
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/89816143
has comment: http://stackoverflow.com/comment/89835739
upvote count: 3
has comment: http://stackoverflow.com/comment/89845002
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89791822
accepted answer of: http://stackoverflow.com/q/51390692
has body: The same question has been posted as a GitHub issue. In particular, the solution suggested by @allanlavoie is likely relevant here as well: Sounds like a half-updated version of TensorFlow. Could you try removing TensorFlow entirely (e.g. pip uninstall tf-nightly or whichever package is installed), making sure import tensorflow fails, then reinstalling? Since it is apparent from your question that you're using Anaconda to manage your Python environments, if the above fails to solve your problem, you can try to install TensorFlow in a clean conda environment as follows: Create a new environment through conda create --name tftest. (You can replace tftest with e.g. the name of your current project.) Activate that new environment through activate tftest (or source activate tftest if you happen to be using MSYS2's bash, or something similar to that). Install TF into this environment through conda install tensorflow. Ensure that you're in the right environment through where python (which should produce a path containing "tftest"). Run Python through python. import tensorflow as tf in a shell in that environment. Since you are using PyCharm (cf. the comments for this answer), you will then want to set up PyCharm for using this new environment instead. Indeed, using a new environment for every project, while disk space-intensive, is a good way of avoiding dependency issues for these rather dependency-heavy numerical packages.
type: Answer
answers question: http://stackoverflow.com/q/51390692

http://stackoverflow.com/comment/89893020
type: QuestionComment
has text: Are you running on Windows, Linux or OSX?
comment on: http://stackoverflow.com/q/51461968
type: Comment
score: 1

http://stackoverflow.com/comment/89748516
score: 1
comment on: http://stackoverflow.com/q/51388335
has text: Your view is wrongly indented. Please fix that.
type: Comment
type: QuestionComment

axis-labels
tags question: http://stackoverflow.com/q/51328098
type: Tag
tag name: axis-labels

http://stackoverflow.com/comment/89757714
type: Comment
has text: If you want this page not refresh,i'm be afraid of you need to use ajax and djangorestframework to achieve this
score: 0
comment on: http://stackoverflow.com/q/51392756
type: QuestionComment

python-behave
tags question: http://stackoverflow.com/q/51405580
tag name: python-behave
type: Tag

http://stackoverflow.com/q/51424690
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/52586086
score: 0
answer count: 3
has title: KeyError: "The name 'loss:0' refers to a Tensor which does not exist. The operation, 'loss', does not exist in the graph."
has answer: http://stackoverflow.com/a/56316221
tagged with: python-3.x
tagged with: tensor
type: UnansweredQuestion
tagged with: tensorboard
tagged with: python
has comment: http://stackoverflow.com/comment/92106691
has answer: http://stackoverflow.com/a/53842224
has body: KeyError: "The name 'loss:0' refers to a Tensor which does not exist. The operation, 'loss', does not exist in the graph." Hey guys, i'm facing an issue while using the tensorflow model. The code is running fine when it compiled in terminal but when i try to make it an python API it shows the above error output_layer = 'loss:0' input_node = 'Placeholder:0' # Crop the center for the specified network_input_Size augmented_image = crop_center(augmented_image, network_input_size, network_input_size) with tf.Session() as sess: prob_tensor = sess.graph.get_tensor_by_name(output_layer) predictions = sess.run(prob_tensor, {input_node: [augmented_image] }) The above code is saying an error at prob_tensor = sess.graph.get_tensor_by_name(output_layer)
has comment: http://stackoverflow.com/comment/92618894

wifi
tag name: wifi
type: Tag
tags question: http://stackoverflow.com/q/51336638

http://stackoverflow.com/a/51340531
downvote count: 0
has comment: http://stackoverflow.com/comment/89654740
score: 1
has body: The command you should use is sudo apt-get --reinstall install python-pip or sudo yum reinstall python27-python-pip dependent of packaging system you use (DEB or RPM)
has comment: http://stackoverflow.com/comment/89654714
answers question: http://stackoverflow.com/q/51340142
upvote count: 1
type: Answer

http://stackoverflow.com/tag/html
tags question: http://stackoverflow.com/q/51349215
tags question: http://stackoverflow.com/q/51460122
tags question: http://stackoverflow.com/q/51360522
tags question: http://stackoverflow.com/q/51413541
tags question: http://stackoverflow.com/q/51461726
tags question: http://stackoverflow.com/q/51479824
tags question: http://stackoverflow.com/q/51468834
tags question: http://stackoverflow.com/q/51359325
tags question: http://stackoverflow.com/q/51334045
tags question: http://stackoverflow.com/q/51370650
tags question: http://stackoverflow.com/q/51365558
tags question: http://stackoverflow.com/q/51347871
tags question: http://stackoverflow.com/q/51346454
tags question: http://stackoverflow.com/q/51438283
tags question: http://stackoverflow.com/q/51371150
tags question: http://stackoverflow.com/q/51463064
tags question: http://stackoverflow.com/q/51370889
tags question: http://stackoverflow.com/q/51326930
type: Tag
tags question: http://stackoverflow.com/q/51345112
tags question: http://stackoverflow.com/q/51402140
tags question: http://stackoverflow.com/q/51328747
tags question: http://stackoverflow.com/q/51409289
tags question: http://stackoverflow.com/q/51354279
tags question: http://stackoverflow.com/q/51432887
tags question: http://stackoverflow.com/q/51354616
tags question: http://stackoverflow.com/q/51435649
tags question: http://stackoverflow.com/q/51408915
tags question: http://stackoverflow.com/q/51407461
tags question: http://stackoverflow.com/q/51326940
tags question: http://stackoverflow.com/q/51369320
tags question: http://stackoverflow.com/q/51444626
tags question: http://stackoverflow.com/q/51441100
tags question: http://stackoverflow.com/q/51460112
tags question: http://stackoverflow.com/q/51462475
tags question: http://stackoverflow.com/q/51453469
tags question: http://stackoverflow.com/q/51351359
tags question: http://stackoverflow.com/q/51451345
tags question: http://stackoverflow.com/q/51467440
tags question: http://stackoverflow.com/q/51433725
tags question: http://stackoverflow.com/q/51389843
tags question: http://stackoverflow.com/q/51356651
tags question: http://stackoverflow.com/q/51365527
tags question: http://stackoverflow.com/q/51477628
tags question: http://stackoverflow.com/q/51354098
tags question: http://stackoverflow.com/q/51413605
tags question: http://stackoverflow.com/q/51481690
tags question: http://stackoverflow.com/q/51463999
tags question: http://stackoverflow.com/q/51389783
tags question: http://stackoverflow.com/q/51447147
tags question: http://stackoverflow.com/q/51472218
tags question: http://stackoverflow.com/q/51383508
tags question: http://stackoverflow.com/q/51370223
tags question: http://stackoverflow.com/q/51399703
tags question: http://stackoverflow.com/q/51455027
tags question: http://stackoverflow.com/q/51383352
tag name: html
tags question: http://stackoverflow.com/q/51369407
tags question: http://stackoverflow.com/q/51379850
tags question: http://stackoverflow.com/q/51374189
tags question: http://stackoverflow.com/q/51441302
tags question: http://stackoverflow.com/q/51412042
tags question: http://stackoverflow.com/q/51351065
tags question: http://stackoverflow.com/q/51330796
tags question: http://stackoverflow.com/q/51358717

http://stackoverflow.com/q/51374107
tagged with: hex
tagged with: python-3.x
type: Question
tagged with: python
linked to: http://stackoverflow.com/q/8186965
score: 0
has answer: http://stackoverflow.com/a/51374546
answer count: 1
has body: Trying to understand hexadecimal 0x notation in regards to memory locations and sizes in MiB (mebibytes) and KiB (kibibytes). Specifically, in a partition layout table I can see the following columns: size hex '0x' notation 1 MiB 0x0010 0000 12 MiB 0x00c0 0000 128 KiB 0x0002 0000 But I find it hard to translate/extract the logic to calculate and do the conversions for myself (for example convert from 24 MiB, 125 KiB, 16 MiB, to '0x' hex notation etc.). Hence, I thought of writing a Python script (as you do) to do the conversions from MiB/KiB to 'Ox' and additions of '0x'. I found this [https://stackoverflow.com/a/8186974/6167676] but I failed to do anything meaningful from it. To my surprise I could not find something online to help me do the conversions from MiB/KiB to the hex '0x' notation. In Python I found the hex function in an attempt to do basic additions between hex values in the hex '0x' notation: def hex_add(h1, h2): return hex(int(h1, 0) + int(h2, 0)) How can use Python (built-in or not functions) to automatically calculate the conversion from MiB to the hex '0x' notation? Also, is the hex_add adequate to perform additions on '0x' notation? Some code examples to demonstrate the conversion and addition in Python would be very useful.
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51374546
has title: Script to convert MiB/KiB to Hex '0x' notation and do additions (Python)

http://stackoverflow.com/comment/89898671
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51465045
has text: Hi Andrej, Thank you for your response but after trying your code I am still getting same error.this below code is used to get value of main list import requests from bs4 import Beautifulsoup r=requests.get("https://forums.oneplus.com/") s=BeautifulSoup(r.content) links=s.find_all("a",{"class" : "focus-content"}) url2=[] for link in links : url2.append(link.get("href")) url1="https://forums.oneplus.com/" for u in url2: main=url1+u please let me know where I am making mistake
type: AnswerComment

http://stackoverflow.com/a/51381442
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51379101
answers question: http://stackoverflow.com/q/51379101
type: Answer
upvote count: 7
has comment: http://stackoverflow.com/comment/127104140
score: 7
has body: Maybe not the best way, but, inspired by this comment on the official repository: iterator = bucket.list_blobs(delimiter='/', prefix=prefix) response = iterator._get_next_page_response() for prefix in response['prefixes']: print('gs://'+bucket_name+'/'+prefix) Gives: gs://gcp-public-data-sentinel-2/tiles/01/ gs://gcp-public-data-sentinel-2/tiles/02/ gs://gcp-public-data-sentinel-2/tiles/03/ gs://gcp-public-data-sentinel-2/tiles/04/ gs://gcp-public-data-sentinel-2/tiles/05/ gs://gcp-public-data-sentinel-2/tiles/06/ gs://gcp-public-data-sentinel-2/tiles/07/ gs://gcp-public-data-sentinel-2/tiles/08/ gs://gcp-public-data-sentinel-2/tiles/09/ gs://gcp-public-data-sentinel-2/tiles/10/ ...

http://stackoverflow.com/q/51350025
has comment: http://stackoverflow.com/comment/89673421
has answer: http://stackoverflow.com/a/51353621
tagged with: python
has comment: http://stackoverflow.com/comment/89676781
has answer: http://stackoverflow.com/a/51350362
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/89679293
tagged with: normal-distribution
score: 1
has title: How can i apply Chebyshev's inequality to this case?
has answer: http://stackoverflow.com/a/51352070
tagged with: standard-deviation
type: Question
answer count: 3
has comment: http://stackoverflow.com/comment/89672924
has body: I have the a dataframe which includes heights. The data can not go below zero. That's why i can not use standard deviation as this data is not a normal distribution. I can not use 68-95-99.7 rule here because it fails in my case. Here is my dataframe, mean and SD. 0.77132064 0.02075195 0.63364823 0.74880388 0.49850701 0.22479665 0.19806286 0.76053071 0.16911084 0.08833981 Mean: 0.41138725956196015 Std: 0.2860541519582141 If I get 2 std, as you can see the number becomes negative. -2 x std calculation = 0.41138725956196015 - 0.2860541519582141 x 2 = -0,160721044354468 I have tried using percentile and not satisfied with it to be honest. How can i apply Chebyshev's inequality to this problem? Here what i did so far: np.polynomial.Chebyshev(df['Heights']) But this returns numbers not a SD level i can measure. Or do you think Chebyshev is the best choice in my case? Expected solution: I am expecting to get a range like 75% next height will be between 0.40 - 0.43 etc. EDIT1: Added histogram To be more clear, I have added my real data's histogram EDIT2: Some values from real data Mean: 0.007041500928135767 Percentile 50: 0.0052000000000000934 Percentile 90: 0.015500000000000047 Std: 0.0063790857035425025 Var: 4.06873389299246e-05 Thanks a lot
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/51460552
accepted answer: http://stackoverflow.com/a/51460594
tagged with: python
has title: Removing duplicate output from list of Dictionary in JSON Python
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/51460594
score: 1
type: Question
tagged with: python-2.7
upvote count: 1
answer count: 1
favorite count: 0
has body: I have following JSON file that I am trying to parse and encountering some issues. [ { "ballot_name": "LAPP, David", "office": "MAYOR", "votes": "7", "voting_station": "3", "voting_station_id": "703", "voting_station_name": "Branton JR High School", "voting_station_type": "Regular", "ward": "7" }, { "ballot_name": "SMITH, Bill", "office": "MAYOR", "votes": "683", "voting_station": "1", "voting_station_id": "1101", "voting_station_name": "St. Mary's Parish Hall", "voting_station_type": "Regular", "ward": "11" }, { "ballot_name": "HEATHER, Larry R", "office": "MAYOR", "votes": "1", "voting_station": "37", "voting_station_id": "737", "voting_station_name": "Clover Living", "voting_station_type": "Special", "ward": "7" }, { "ballot_name": "OLSON, Curtis", "office": "MAYOR", "votes": "0", "voting_station": "32", "voting_station_id": "1432", "voting_station_name": "Lake Bonavista Village", "voting_station_type": "Special", "ward": "14" }, { "ballot_name": "LIN, Jun", "office": "COUNCILLOR", "votes": "2", "voting_station": "66", "voting_station_id": "366", "voting_station_name": "Memorial Park Library", "voting_station_type": "Advance", "ward": "3" }, { "ballot_name": "HEJDUK, Marek", "office": "COUNCILLOR", "votes": "0", "voting_station": "67", "voting_station_id": "767", "voting_station_name": "Saddletowne Library", "voting_station_type": "Advance", "ward": "7" }, My objectives so far to do the following 1> Print the list of voting_station_name removing all the duplicates - Which I can print but not able to remove duplicates? Below is the code I have tried so far. import json import urllib print "This is Json Data Parser Program \nThis program will download the Election Results from 2017 file from OpenData Portal" _url_= "https://data.cityname.ca/resource/kqmd-3dsq.json" _response_ = urllib.urlopen(_url_) _data_= json.loads(_response_.read()) #with open('data.json', 'w') as outfile: # json.dump(_data_,outfile,indent=4,sort_keys=True) def _ward_(_no_): print "Your choosen…

http://stackoverflow.com/q/51364975
has body: I have come across the following statement in numpy: x=numpy.zeros((2,2),dtype=[('x','i4'),('y','i4')]) and the output is like this: [[(0,0)(0,0)] [(0,0)(0,0)]] What is the meaning of [('x','i4'),('y','i4')]? Please explain.
has answer: http://stackoverflow.com/a/51365191
type: UnansweredQuestion
has title: Datatype in NumPy
type: Question
score: 1
downvote count: 3
tagged with: numpy
has comment: http://stackoverflow.com/comment/89702422
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/51365260
upvote count: 4
has answer: http://stackoverflow.com/a/51365320
favorite count: 0

http://stackoverflow.com/a/51410258
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51409861
upvote count: 2
has body: You are using the the first element like a key of a dictionary or an index of a Pandas series. So I used those tools which are better suited for the combination you are looking to do. I then convert back to the array you are looking for. import pandas as pd import numpy as np a = np.array([[1, 10], [2, 12], [3, 5]]) b = np.array([[1, 0.78], [3, 0.23]]) pd.concat( map(pd.Series, map(dict, (a, b))), axis=1 ).fillna(0).reset_index().values array([[ 1. , 10. , 0.78], [ 2. , 12. , 0. ], [ 3. , 5. , 0.23]]) Notes: I map dict and pd.Series on the iterable (a, b) I pass those to pd.concat which produces a Pandas DataFrame Fill in missing values with 0 Reset the index to get back those keys of yours Get at just the values If you have another array a = np.array([[1, 10], [2, 12], [3, 5]]) b = np.array([[1, 0.78], [3, 0.23]]) c = np.array([[1, 3.14], [2, 3.14]]) pd.concat( map(pd.Series, map(dict, (a, b, c))), axis=1 ).fillna(0).reset_index().values array([[ 1. , 10. , 0.78, 3.14], [ 2. , 12. , 0. , 3.14], [ 3. , 5. , 0.23, 0. ]]) If you want to quickly convert you arrays to the Pandas series Notice that I wrote to new names a_, b_, and c_ to avoid overwriting your other names a_, b_, c_ = map(pd.Series, map(dict, (a, b, c))) To get a DataFrame df = pd.concat(map(pd.Series, map(dict, (a, b, c))), axis=1).fillna(0) df 0 1 2 1 10 0.78 3.14 2 12 0.00 3.14 3 5 0.23 0.00
has comment: http://stackoverflow.com/comment/89792170
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/89792227
answers question: http://stackoverflow.com/q/51409861
has comment: http://stackoverflow.com/comment/89794051
has comment: http://stackoverflow.com/comment/89792208
type: AcceptedAnswer

http://stackoverflow.com/a/51363739
type: Answer
answers question: http://stackoverflow.com/q/51359418
has comment: http://stackoverflow.com/comment/89740489
accepted answer of: http://stackoverflow.com/q/51359418
downvote count: 1
has body: I ended up using nltk after browsing Google. I just need to compare simple words at this stage to get the basic functioning of my program. Will consider the more complex solutions later on. Appreciate the help. import nltk nltk.edit_distance("word1", "word2") Source: https://datascience.stackexchange.com/a/12583/56244
has comment: http://stackoverflow.com/comment/89700857
upvote count: 0
score: -1
type: AcceptedAnswer

http://stackoverflow.com/comment/89774763
type: AnswerComment
has text: It's working with the minimal exemple, don't know what's wrong in my test suite, I'll investigate more
type: Comment
comment on: http://stackoverflow.com/a/51400486
score: 0

http://stackoverflow.com/q/51417159
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51418581
type: UnansweredQuestion
tagged with: python
has body: I have the following use case: I want to make a dataframe where for each row I have a column where I can see how many interactions there have been for this ID (user) in the categories. The hardest thing to me is that they can't be double counted, while a match in just one of the categories is enough to be counted as 1. So for example I have: richtingen id 0 Marketing, Sales 1110 1 Marketing, Sales 1110 2 Finance 220 3 Marketing, Engineering 1110 4 IT 3300 Now I want to create a third row where I can see how many times this ID has interacted with any of these categories in total. Each comma is a category on it's own so for example: "Marketing, Sales" are the two categories Marketing and Sales. To get a +1 you only need to have a match with another row where ID is the same and one of the categories matches, so for example for the index 0 it would be 3 (indexes 0, 1 and 3 match). The output data for the example should be: richtingen id freq 0 Marketing, Sales 1110 3 1 Marketing, Sales 1110 3 2 Finance 220 1 3 Marketing, Engineering 1110 3 4 IT 3300 1 The hard part for me seems to be that I can't all categories into new rows, as then you perhaps will start counting double. For example index 0 matches both Marketing and Sales of index 1 and I want it just to add 1, not 2. The code I have so far is: df['freq'] = df.groupby(['id', 'richtingen'])['id'].transform('count') this only matches identical combination of categories though. Other things I've tried: - creating a new column with all vacancies split into an array: df['splitted'] = df.richtingen.apply(lambda x: str(x.split(","))) and then the plan was to use something along this code in combination with groupby on id to count number of times it is true per item: if any(t &lt; 0 for t in x): # do something I couldn't get this to work either. I tried splitting categories in new rows, or columns but then got an issue of double counting. For example using code suggested: df['richtingen'].str.split(', ',expand=True) Gives me…
has title: Pandas dataframe: count number of string value is in row for specific ID
has comment: http://stackoverflow.com/comment/89805619
tagged with: dataframe
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89806354
has answer: http://stackoverflow.com/a/51421554
tagged with: numpy
has answer: http://stackoverflow.com/a/51418049
tagged with: data-manipulation
downvote count: 0
answer count: 3
tagged with: pandas

http://stackoverflow.com/comment/89862066
has text: I don't get any error when I run the code above. So the problem is related to your own code because the error is telling you that you are trying to feed a `tf.Tensor` object in your dictionary. Note that I'm not feeding a `tf.Tensor` object in my example but rather a `np.ones` object.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51428145
type: AnswerComment

http://stackoverflow.com/a/51397155
type: Answer
has body: You're importing a different pynput, file C:\Users\Andrey\AppData\Local\Programs\Python\Python36-32\pynput.py, probably your own. And that's where your error is. Move this file out of your Python path.
score: 0
answers question: http://stackoverflow.com/q/51381763

http://stackoverflow.com/comment/89632904
score: 0
has text: Oh wow I feel dumb but thank you still!
comment on: http://stackoverflow.com/q/51328381
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51336853
has comment: http://stackoverflow.com/comment/89648435
accepted answer: http://stackoverflow.com/a/51336986
type: Question
has comment: http://stackoverflow.com/comment/89648398
downvote count: 0
has title: create rows from database column
tagged with: sql
answer count: 1
tagged with: mariadb
has answer: http://stackoverflow.com/a/51336986
favorite count: 0
tagged with: pivot-table
upvote count: 1
tagged with: python
type: AnsweredQuestion
has body: currently i have this data retrieved from database as follows, +------------+--------------+-------+-----+-------------+-----------+------------------+-----------------+ | Monitor ID | Casting Date | Label | AGE | Client Name | Project | Average Strength | Average Density | +------------+--------------+-------+-----+-------------+-----------+------------------+-----------------+ | 1082 | 2018-07-05 | b52 | 1 | Trial Mix | Trial Mix | 21.78 | 2.436 | | 1082 | 2018-07-05 | b52 | 2 | Trial Mix | Trial Mix | 33.11 | 2.406 | | 1082 | 2018-07-05 | b52 | 4 | Trial Mix | Trial Mix | 43.11 | 2.447 | | 1082 | 2018-07-05 | b52 | 8 | Trial Mix | Trial Mix | 48.22 | 2.444 | | 1083 | 2018-07-05 | B53 | 1 | Trial Mix | Trial Mix | 10.44 | 2.421 | | 1083 | 2018-07-05 | B53 | 2 | Trial Mix | Trial Mix | 20.0 | 2.400 | | 1083 | 2018-07-05 | B53 | 4 | Trial Mix | Trial Mix | 27.78 | 2.397 | | 1083 | 2018-07-05 | B53 | 8 | Trial Mix | Trial Mix | 33.33 | 2.409 | | 1084 | 2018-07-05 | B54 | 1 | Trial Mix | Trial Mix | 12.89 | 2.430 | | 1084 | 2018-07-05 | B54 | 2 | Trial Mix | Trial Mix | 24.44 | 2.427 | | 1084 | 2018-07-05 | B54 | 4 | Trial Mix | Trial Mix | 34.22 | 2.412 | | 1084 | 2018-07-05 | B54 | 8 | Trial Mix | Trial Mix | 41.56 | 2.501 | +------------+--------------+-------+-----+-------------+-----------+------------------+-----------------+ how can i change the table to something like this? +------------+--------------+-------+-----------+-----------+---------+-------------+---------+-------------+---------+-------------+---------+-------------+ | Monitor Id | Casting Date | Label | Client | Project | 1 Day | | 2 Days | | 4 Days | | 8 Days | | +------------+--------------+-------+-----------+-----------+---------+-------------+---------+-------------+---------+-------------+---------+-------------+ | | | | | | avg str | avg density | avg str | avg density | avg str | avg density | avg str | avg density | | | | | | | | | | | | | | | | 1082 | 05/07/2018 | B52 | Trial Mix | Trial…
score: 1

http://stackoverflow.com/q/51470073
answer count: 2
downvote count: 1
favorite count: 0
has title: Django: How would you constantly check an API even when web app is not loaded?
tagged with: django
has answer: http://stackoverflow.com/a/51556499
tagged with: python
type: AnsweredQuestion
upvote count: 0
type: Question
possible better answer: http://stackoverflow.com/a/51556499
score: -1
has body: My website needs to send an email to users even when the web app is not running. I have an API and each time I receive data I need to send my users an email. I need to be guided to the right direction. Thanks in advance.
has answer: http://stackoverflow.com/a/51470430
accepted answer: http://stackoverflow.com/a/51470430

http://stackoverflow.com/q/51469810
favorite count: 0
answer count: 0
type: UnansweredQuestion
has title: Changing the language of google assistant API
tagged with: python
downvote count: 0
score: 1
type: Question
has body: I'm using google assistant API but i cant find ho to change the language when used with the command "python hotword.py --device_model_id $model_id* Can someone help me?
upvote count: 1
tagged with: google-assistant-sdk

http://stackoverflow.com/a/51558280
score: 3
answers question: http://stackoverflow.com/q/51422553
upvote count: 3
type: Answer
downvote count: 0
has body: There are different BigQuery libraries depending on the language. For Python you would find this one. But if what you want is the exactly piece of code to upload CSV from Google Cloud Storage to Bigquery, this example might work for you: "Loading CSV data into a new table" You can see also in the same documentation page "Appending to or overwriting a table with CSV data". You can go also to the GitHub in order to check all the methods available for Python.

http://stackoverflow.com/comment/89757770
type: Comment
comment on: http://stackoverflow.com/a/51375226
score: 0
type: AnswerComment
has text: In that case, I prefer `f.read().splitlines()` over `f.readlines()`, as this automagically removes all those pesky trailing newlines.

http://stackoverflow.com/comment/89899617
comment on: http://stackoverflow.com/q/51465483
score: 0
type: Comment
type: QuestionComment
has text: What is `middle` before you convert it to `int` and return it?

http://stackoverflow.com/a/51455419
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51455196
score: 1
upvote count: 1
has body: the output is q queryset not string to split. you can iterate over all items and split them into a list fp_items = SWTypes.objects.filter(pk__in=id,swtype__in=swtype).values_list('fp_items', flat=True) res = [] for item in fp_items: res += item.split(";") and use res as merged list of all splited content into a list
answers question: http://stackoverflow.com/q/51455196

http://stackoverflow.com/comment/89640136
has text: @mysticalstick it is not, `d.get("missing_key")` will default to `None` with or without the second argument explicitly as `None`.
type: AnswerComment
comment on: http://stackoverflow.com/a/51332031
score: 0
type: Comment

http://stackoverflow.com/comment/89827969
type: Comment
score: 1
has text: Thanks for the reply, but I am looking for something native to python, rather than going through a server and a browser.
type: AnswerComment
comment on: http://stackoverflow.com/a/51425464

http://stackoverflow.com/comment/89844557
type: Comment
has text: I don't have osx so I can't test it, but have you tried to set `borderwidth=0` in the button options (you might lose the button relief though)?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51420771

http://stackoverflow.com/comment/89860454
has text: Why does the code you posted say `path="images/"` but the error says `path="plasmodium_images/"` ?
type: QuestionComment
comment on: http://stackoverflow.com/q/51424616
score: 0
type: Comment

http://stackoverflow.com/a/51365169
has comment: http://stackoverflow.com/comment/89703857
upvote count: 2
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51364933
has comment: http://stackoverflow.com/comment/89713566
has body: The problem is you are searching for the exact string 'cliente problema' not 'cliente' OR 'problema'. This is what you want to do: Term1 = 'cliente' Term2 = 'problema' x_word = df_pentagrams.Name[df_pentagrams.Name.str.contains(Term1) | df_pentagrams.Name.str.contains(Term2)]

http://stackoverflow.com/a/51455341
has comment: http://stackoverflow.com/comment/89880689
accepted answer of: http://stackoverflow.com/q/51455280
has body: I would do: # create a group df['group'] = df['complete'].cumsum() # find which groups to add vals = df.group.value_counts() groups_to_consider = vals[vals &gt; 1].index.tolist() ## add values df[df['group'].isin(groups_to_consider)].groupby('group')['num'].sum().tolist() # [6.83, 1.24]
has comment: http://stackoverflow.com/comment/89900599
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89880225
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51455280

http://stackoverflow.com/comment/89745928
type: QuestionComment
type: Comment
has text: So, if you're passing `cmd.split(' ')`, then `print(repr(cmd.split(' ')))` in your code, and [edit] the output into your question. If you're using `shlex.split(cmd)`, likewise, [edit] the output of `print(repr(shlex.split(cmd)))` into the question.
comment on: http://stackoverflow.com/q/51386039
score: 1

http://stackoverflow.com/comment/89714446
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51353082
type: Comment
has text: @hoefling you are right, I apologize. I have updated the question with my use case and a minimal example of my project structure.

http://stackoverflow.com/a/51451814
type: Answer
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/51451400
accepted answer of: http://stackoverflow.com/q/51451400
upvote count: 3
has body: Use the new * unpacking generalizations and list multiplication. &gt;&gt;&gt; [1.2, 3.2, *2*[0.0], 3.9, *3*[0.0]] [1.2, 3.2, 0.0, 0.0, 3.9, 0.0, 0.0, 0.0] You can also multiply strings and tuples in Python. &gt;&gt;&gt; 'abc'*3 'abcabcabc' &gt;&gt;&gt; (1, 2, 3)*2 (1, 2, 3, 1, 2, 3) You can unpack any iterable, and this also works in tuple displays, etc. &gt;&gt;&gt; (1.2, 3.2, *'xy'*2, 3.9, *3*(0.0,), *'foo') (1.2, 3.2, 'x', 'y', 'x', 'y', 3.9, 0.0, 0.0, 0.0, 'f', 'o', 'o')
type: AcceptedAnswer

http://stackoverflow.com/a/51326307
type: Answer
has body: The reason for your error is that you are trying to append to the result of mydict.setdefault() which is actually None as that method returns nothing. Apart from that do also take note of other answers that to a dictionary in python, you do not append
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51325708
downvote count: 0

aws-lambda
tags question: http://stackoverflow.com/q/51450780
tags question: http://stackoverflow.com/q/51391458
type: Tag
tags question: http://stackoverflow.com/q/51441240
tags question: http://stackoverflow.com/q/51403364
tags question: http://stackoverflow.com/q/51386930
tags question: http://stackoverflow.com/q/51328532
tag name: aws-lambda
tags question: http://stackoverflow.com/q/51471753
tags question: http://stackoverflow.com/q/51431947
tags question: http://stackoverflow.com/q/51466179
tags question: http://stackoverflow.com/q/51432323

http://stackoverflow.com/q/51435902
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51435968
has title: TypeError: processingTime() missing 1 required positional argument: 'num_job'
linked to: http://stackoverflow.com/q/735975
type: Question
has answer: http://stackoverflow.com/a/51435968
score: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/51435955
has answer: http://stackoverflow.com/a/51436002
has answer: http://stackoverflow.com/a/51435955
has body: I try to convert these code below to script: import pandas as pd import numpy as np num_job=10 # number of jobs pt_tmp=pd.read_excel("JSP_dataset.xlsx",sheet_name="Processing Time",index_col =[0]) pt=[list(map(int, pt_tmp.iloc[i])) for i in range(num_job)] to ExcelReadFile.py import pandas as pd class ExcelReadFile(object): def __init__(self,fileName, num_job): self.fileName = fileName self.num_job = num_job def processingTime(self, fileName, num_job): pt_tmp=pd.read_excel(fileName,sheet_name="Processing Time", index_col =[0]) pt=[list(pt_tmp.iloc[i]) for i in range(num_job)] return pt and in run.py import pandas as pd import numpy as np import time from src.fjsls.io.ExcelReadFile import ExcelReadFile num_job=10 fileName = "JSP_dataset.xlsx" pt = ExcelReadFile.processingTime(fileName, num_job) it shows `TypeError: processingTime() missing 1 required positional argument: 'num_job' when i call processingTime() Could you please help to check and a little explanation about script creation in Python?
tagged with: python

http://stackoverflow.com/a/51352741
upvote count: 1
answers question: http://stackoverflow.com/q/51352544
type: AcceptedAnswer
downvote count: 0
has body: You are looking for 'size'. For common functions, you should trust strings are mapped to efficient algorithms. For example: d = {'media': 'mean', 'contador': 'size'} res = homedata.groupby('local')['r1'].agg(d) I would expect a column of integers in 'contador'. This is not what you should expect. First note that pd.Series.value_counts returns a pd.Series object of counts, not an integer. It's unclear what integers you expect this method to return. The reason why some values are integers and others lists indicates that groupby is performing some transformation: it assumes that if value_counts returns a series of length 1 you are only interested in the first value of that series. To illustrate, let's look at a minimal example of what you're seeing: import pandas as pd df = pd.DataFrame([['A', 1], ['B', 2], ['B', 2], ['C', 4], ['B', 2], ['B', 6]], columns=['Group', 'Value']) res = df.groupby('Group')['Value'].agg({'counts': lambda x: x.value_counts()}) print(res) counts Group A 1 B [3, 1] C 1
type: Answer
accepted answer of: http://stackoverflow.com/q/51352544
score: 1

http://stackoverflow.com/comment/89781131
comment on: http://stackoverflow.com/q/51404171
score: 1
type: Comment
type: QuestionComment
has text: speedymcs: The `root.after()` isn't calling `load_image`, it's just scheduling a call to it later—so it's not recursion, it's looping.

http://stackoverflow.com/comment/89902051
comment on: http://stackoverflow.com/a/51466224
type: AnswerComment
type: Comment
has text: @dxxg-syz35 I gave you a duplicate I wrote that explains how to stop this happening. The behaviour is really unintuitive and I got bitten by it myself in Spyder
score: 1

http://stackoverflow.com/comment/89885042
score: 1
type: AnswerComment
has text: No I haven't dug into `numpy` code in that depth. It might help if you explained why you want to know this? Is it just the end result that matters, or are you trying to replicate the action in your own C code?
type: Comment
comment on: http://stackoverflow.com/a/51457275

http://stackoverflow.com/comment/89708929
type: QuestionComment
comment on: http://stackoverflow.com/q/51364142
has text: Those links are getting populated using xhr requests. These are the URLs. http://www.hl.co.uk/ajax/menus/16508, http://www.hl.co.uk/ajax/menus/16512, http://www.hl.co.uk/ajax/menus/16516, http://www.hl.co.uk/ajax/menus/16526 you can use network tab in developer console to see them.
score: 0
type: Comment

http://stackoverflow.com/q/51392643
has title: a PYTHON program that takes its input from a file of numbers and calculates the average
answer count: 2
has comment: http://stackoverflow.com/comment/89757121
downvote count: 0
has comment: http://stackoverflow.com/comment/89757099
has comment: http://stackoverflow.com/comment/89757169
favorite count: 0
tagged with: programming-languages
tagged with: python-3.x
tagged with: python
possible better answer: http://stackoverflow.com/a/51392683
has comment: http://stackoverflow.com/comment/89757137
has answer: http://stackoverflow.com/a/51392697
has answer: http://stackoverflow.com/a/51392683
has body: def main(): numbersFile=open("numbers.txt" , 'r') line=numbersFile.readline() total=0 numberoflines=0 while line != " ": numberoflines+=1 total+=int(line) line=numbersFile.readline() average=total/numberoflines print("The average is: " , average) main() this program displays an error message- ValueError: invalid literal for int() with base 10: '\n'
score: 1
has comment: http://stackoverflow.com/comment/89757089
upvote count: 1
has comment: http://stackoverflow.com/comment/89757124
type: Question
has comment: http://stackoverflow.com/comment/89757120
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51392697

http://stackoverflow.com/comment/89677522
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51352470
score: 0
has text: What type of form did you create the .ui in Qt Designer?

http://stackoverflow.com/a/71945936
downvote count: 0
has body: I just find this way for that. Options its a list, so you have to find the "--headless" element in there. opc = Options() opc.add_argument('headless') in this case, the position of the element in the list is [0], so you only have to to something like this: if (opc.arguments[0]=="--headless"): print("Do something")
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51327306
type: Answer

http://stackoverflow.com/a/51460688
has comment: http://stackoverflow.com/comment/89891577
type: Answer
has comment: http://stackoverflow.com/comment/89892315
has comment: http://stackoverflow.com/comment/89891517
accepted answer of: http://stackoverflow.com/q/51460603
downvote count: 0
answers question: http://stackoverflow.com/q/51460603
has body: The problem is in your def get_context_data(request, **kwargs), you need to have self as first argument. You need to remove request from the arguments and use self.request to access it: def get_context_data(self, **kwargs): filtered_orders = Order.objects.filter(owner=self.request.user.user_profile, is_ordered=False)
score: 1
has comment: http://stackoverflow.com/comment/89891784
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89892598

http://stackoverflow.com/comment/89830260
type: Comment
has text: What did you try (what Python code did you write) to solve this?
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/51429612

http://stackoverflow.com/comment/89935778
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51462467
has text: I was referring to line 5-6 in your `numb_fact` function
score: 0

http://stackoverflow.com/a/51460301
has body: For killing the job: 0 18 * * 0,1,2,3,4 /usr/bin/pkill -f MotionDetector.py pkill kills a process by name. While the default search criteria is to find the process by its full name, -f argument allows you to search by any of the parts in the process name. Updated solution to account for the scenario raised by @håken-lid: When the script is executed by cron or by the user, the process name would be in the format: cron: /home/pi/venv/bin/python /home/pi/MotionDetector.py user: python MotionDetectory.py Using simple regex patterns we can kill the process started by, cron or user: 0 18 * * 0,1,2,3,4 /usr/bin/pkill -f 'python.*MotionDetector.py' only cron 0 18 * * 0,1,2,3,4 /usr/bin/pkill -f ^'/home/pi/venv/bin/python /home/pi/MotionDetector.py'
has comment: http://stackoverflow.com/comment/89890156
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51459874
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51459874
downvote count: 0

http://stackoverflow.com/comment/89848162
has text: Obviously, maintaining Python 2 code is going to be a thing for a long time still. Your question reads like you are trying to actually develop Python 2 code, though.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51437287
score: 0

http://stackoverflow.com/q/51421796
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51422095
upvote count: 2
tagged with: python
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/89814549
has body: I have a pandas Series containing lists. I wanted to replace empty lists with NaN. My first approach was using .replace, but that unexpectedly gave me a maximum recursion error: import numpy as np import pandas as ts = pd.Series([[1], [2, 3], [], [4]]) ts.replace([], np.nan) RuntimeError: maximum recursion depth exceeded in comparison I achieved my result using ts[ts.apply(len) == 0] = np.nan but can anyone help me understand why the .replace approach fails?
type: Question
accepted answer: http://stackoverflow.com/a/51422095
has title: Pandas Series: maximum recursion error when replacing empty lists
has answer: http://stackoverflow.com/a/51421978
has comment: http://stackoverflow.com/comment/89814647
has comment: http://stackoverflow.com/comment/89814434
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/51421978
has comment: http://stackoverflow.com/comment/89814633

http://stackoverflow.com/q/51467803
has title: Python script to save bookmarks into a json file
type: UnansweredQuestion
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: python
has body: I actually wanted my bookmarks for a text classifier .It needs data in .json format .So i want to know a python script which will retrieve data from the bookmarks directory and store it in a .json file.(I am using ubuntu)
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/51473699
upvote count: 1
tagged with: google-chrome
answer count: 1

http://stackoverflow.com/comment/89855353
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51431016
has text: open(), write(), close()
score: 0

http://stackoverflow.com/comment/89817031
type: Comment
has text: I cant used localhost( to create_enigne) because I get this message: Blanks, if dynamic ports are not enabled. To use dynamic ports, set to 0..
comment on: http://stackoverflow.com/a/51421628
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89797745
comment on: http://stackoverflow.com/a/51391334
score: 0
type: AnswerComment
type: Comment
has text: @NeverTellMeTheStack You're right for 1) and 2), but "obj cannot inherit x" is weird terminology here—you don't inherit variables. Methods in `obj`'s type can access either kind of `x`, but neither kind is part of the object. 1) is shared with the whole program, 2) is just local to that method. Meanwhile, 3) doesn't make sense—you can only do `self.x` where `self` exists, which generally means only inside a method (where it's the first parameter). 4) is wrong; `self.x` does _not_ create a local variable, it creates an attribute on `self`, which (unlike a local variable) can be accessed later.

http://stackoverflow.com/q/51369473
accepted answer: http://stackoverflow.com/a/51369517
favorite count: 0
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/89711284
type: AnsweredQuestion
score: 2
has body: I have the following dictionary, which i got when applied to_dict() method on a pandas dataframe. { 'name' : { 0: 'abc', 1: 'xyz' }, 'email': { 0: 'abc@abc.com', 1: 'xyz@xyz.com', }, 'category': { 0: 'category 1', 1: 'category 2', } } How do I transform it into the following structure? [ { 'name': 'abc', 'email' : 'abc@abc.com', 'category': 'category 1', }, { 'name': 'xyz', 'email' : 'xyz@xyz.com', 'category': 'category 2', } ] I tried applying many variations of for loop, but came out as bogus code, if anyone could help or point to some links it would be great, python newbie here :| EDIT: changed the desired structure to a list of dicts, as dicts are not hashble,
possible better answer: http://stackoverflow.com/a/51369611
upvote count: 2
has answer: http://stackoverflow.com/a/51369774
has answer: http://stackoverflow.com/a/51369611
has answer: http://stackoverflow.com/a/51369517
type: Question
tagged with: for-loop
has comment: http://stackoverflow.com/comment/89711254
has title: How to transform a python dictionary to a desired format
answer count: 3
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/89711973

mqtt
tags question: http://stackoverflow.com/q/51392184
tags question: http://stackoverflow.com/q/51471361
tag name: mqtt
tags question: http://stackoverflow.com/q/51357410
tags question: http://stackoverflow.com/q/51382338
tags question: http://stackoverflow.com/q/51481720
tags question: http://stackoverflow.com/q/51429167
type: Tag
tags question: http://stackoverflow.com/q/51479867

http://stackoverflow.com/a/68660641
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51397109
has body: I had a problem with the code posted here so I revised it and had to add a small section (it deals with the case that both sides are the same but there is still a comparison present): from sklearn.tree._tree import TREE_LEAF, TREE_UNDEFINED def is_leaf(inner_tree, index): # Check whether node is leaf node return (inner_tree.children_left[index] == TREE_LEAF and inner_tree.children_right[index] == TREE_LEAF) def prune_index(inner_tree, decisions, index=0): # Start pruning from the bottom - if we start from the top, we might miss # nodes that become leaves during pruning. # Do not use this directly - use prune_duplicate_leaves instead. if not is_leaf(inner_tree, inner_tree.children_left[index]): prune_index(inner_tree, decisions, inner_tree.children_left[index]) if not is_leaf(inner_tree, inner_tree.children_right[index]): prune_index(inner_tree, decisions, inner_tree.children_right[index]) # Prune children if both children are leaves now and make the same decision: if (is_leaf(inner_tree, inner_tree.children_left[index]) and is_leaf(inner_tree, inner_tree.children_right[index]) and (decisions[index] == decisions[inner_tree.children_left[index]]) and (decisions[index] == decisions[inner_tree.children_right[index]])): # turn node into a leaf by "unlinking" its children inner_tree.children_left[index] = TREE_LEAF inner_tree.children_right[index] = TREE_LEAF inner_tree.feature[index] = TREE_UNDEFINED ##print("Pruned {}".format(index)) def prune_duplicate_leaves(mdl): # Remove leaves if both decisions = mdl.tree_.value.argmax(axis=2).flatten().tolist() # Decision for each node prune_index(mdl.tree_, decisions)

http://stackoverflow.com/comment/89791034
comment on: http://stackoverflow.com/q/51409824
has text: `word_index.get(w)` is obviously not a int
type: QuestionComment
score: 6
type: Comment

http://stackoverflow.com/comment/89714220
comment on: http://stackoverflow.com/q/51370775
score: 0
has text: It seems that you have included other HTML pages
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89844449
type: QuestionComment
has text: Can you please just post the desired dataframe as text, formatted as you want, not a description of it?
comment on: http://stackoverflow.com/q/51437045
score: 0
type: Comment

http://stackoverflow.com/comment/89759174
has text: Possible duplicate of [Reading line by line from STDIN](https://stackoverflow.com/questions/11968244/reading-line-by-line-from-stdin)
score: 3
comment on: http://stackoverflow.com/q/51393842
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89734539
comment on: http://stackoverflow.com/a/51366474
type: AnswerComment
score: 0
type: Comment
has text: The output would be `(1200,6)`. 6 classes per image.

http://stackoverflow.com/q/51392232
upvote count: 1
tagged with: python
has body: I have a flask app running on my webserver to make calls to different remote servers based on hostname POST'ed from user selection. The webserver flask app makes SSH calls (using paramiko) to user desired hostnames to run a python script. Currently, I have to manually create a python script for each function I want to call in the backend or else I would run into import errors (since my webserver flask does not have the same python environment as the remote server). For example, on my backend remote server if I want to call a function from my backend Python module I have to create something like this: myScript.py: #!/usr/bin/python3 from myPackage import myModule myModule.myFunction() And call it from the webserver flask app like this: client.exec_command('(cd /myDir; ./myScript.py:)') My question is, is there a way to stimulate the backend python environment and make calls directly to the python modules, or even some how be able to import the modules from the backend, so I don't have to create a separate script for each function I want to call?
type: AnsweredQuestion
has title: Flask app running on webserver to call remote server python modules
score: 1
type: Question
has comment: http://stackoverflow.com/comment/89759986
downvote count: 0
answer count: 1
tagged with: flask
favorite count: 0
linked to: http://stackoverflow.com/q/373639
has answer: http://stackoverflow.com/a/51417924
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51417924
has comment: http://stackoverflow.com/comment/89788059

http://stackoverflow.com/a/51594513
score: 0
answers question: http://stackoverflow.com/q/51423240
has comment: http://stackoverflow.com/comment/90356298
has body: Pull request #355 is incomplete and untested, so you'll have to do some real work to get it working. The PR has useful comments to get you started :-)
type: Answer

http://stackoverflow.com/comment/89867810
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51448648
has text: @Talar Open your project. Go to: File:Default Settings. Hit the green + button on the far right to add packages.
score: 0

http://stackoverflow.com/comment/89787029
comment on: http://stackoverflow.com/a/51369506
type: Comment
type: AnswerComment
score: 0
has text: Is the `TextInput` inside a `Layout`? Normally, the `build()` method of an `App` returns the `root` of your app display, which is typically some variety of `Layout`. If you want more than one widget (like the Button in your example), then you will want to create a `Layout`. Also, from the `pos_hint` documentation. ` pos_hint is not used by all layouts. Check the documentation of the layout in question to see if it supports pos_hint.`.

http://stackoverflow.com/comment/89762393
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51393216
has text: Then why don't you just [edit](https://stackoverflow.com/posts/51393216/edit) your question and correct the errors? ;)

http://stackoverflow.com/comment/89662311
type: QuestionComment
has text: It is syntactically correct, but maybe I should post a smaller example.
score: 0
comment on: http://stackoverflow.com/q/51344329
type: Comment

http://stackoverflow.com/comment/89800877
comment on: http://stackoverflow.com/q/51414702
has text: @IonicSolutions@user3483203 Thanks your help. I have update the problems, if you have any method, please tell me. Thank a lot.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51368003
has title: Plotting a group of pandas dataframes
tagged with: pandas
has answer: http://stackoverflow.com/a/51368361
upvote count: 1
accepted answer: http://stackoverflow.com/a/51368361
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89709027
has comment: http://stackoverflow.com/comment/89708824
has comment: http://stackoverflow.com/comment/89709156
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89708984
downvote count: 0
score: 1
has body: I have a few pandas DataFrames that can be thought of as time-points. They look something like this: Time 1: pd.DataFrame({'type':[1,2],'b':[200,400]}) b type 0 200 1 1 400 2 Time 2: pd.DataFrame({'type':[1,4],'b':[100,300]}) b type 0 100 1 1 300 4 I am trying to combine the DataFrames together and plot them. I am thinking it would be best to plot as a line graph, where data is grouped by the type column, and the b column is used as the y-axis value.
has comment: http://stackoverflow.com/comment/89708789
type: Question

http://stackoverflow.com/comment/89758569
score: 3
has text: Sorry, but this is not how StackOverflow works. This is your homework and you should at least try to do something.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51393470

http://stackoverflow.com/a/72335602
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/129261684
has body: This problem can be solved by adding memorization to the brute force approach, We need to generate each substring this will take O(n^2) time, and we need to check whether the generated substring is a palindrome, this will take an additional O(n), in total it will be an O(n^3) time complexity. Now, adding and storing the states that we already encountered to speed up the process, the time complexity can be reduced by O(n). So the total time complexity will be O(n^2) here's the solution: class Solution: def longestPalindrome(self, s: str) -&gt; str: memo = {} def isPalindrome(left,right): state = (left, right) if state in memo: return memo[state] if left &gt;= right: return True if s[left] != s[right]: return False memo[state] = isPalindrome(left+1, right-1) return memo[state] N = len(s) result = '' for i in range(N): for j in range(i,N): if (j-i+1) &gt; len(result) and isPalindrome(i,j): result = s[i:j+1] return result
has comment: http://stackoverflow.com/comment/129257751
answers question: http://stackoverflow.com/q/51459221

http://stackoverflow.com/a/51348776
has comment: http://stackoverflow.com/comment/89670069
score: -1
upvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89670036
answers question: http://stackoverflow.com/q/51347869
has comment: http://stackoverflow.com/comment/105873321
type: Answer
accepted answer of: http://stackoverflow.com/q/51347869
downvote count: 1
has body: I have some experience using Raspberry GPIOs. You can not control the 5V pins, there are always set as high. Only 3.3V pins can be controlled. If you need 5V you can create a electric circuit with a relay that activates with 3.3V. Hope this can be useful.

http://stackoverflow.com/comment/89689592
type: Comment
has text: By executing the code, I receive a empty values like: 0 [] 1 [] 2 [] 3 [] 4 []
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51358652

http://stackoverflow.com/comment/89845895
type: AnswerComment
comment on: http://stackoverflow.com/a/51366710
score: 0
has text: here it is https://stackoverflow.com/questions/51322445/how-to-drop-all-columns-with-null-values-in-a-pyspark-dataframe
type: Comment

http://stackoverflow.com/q/51405807
has comment: http://stackoverflow.com/comment/89803622
type: UnansweredQuestion
tagged with: wap
tagged with: python
tagged with: node.js
has body: I know this question sounds kinda dumb but I'll explain. In Switzerland there is a law that for every competition there must be a free way to enter the competition. Normally that free way is WAP. This is easy. Just go on the internet with a mobile phone in a mobile network and type in the address. Now I want to build a bot that joins the (daily) competition automatically. But that will only work if the Website thinks you are in a mobile network. Is there any possible way to open the webpage with Nodejs/JavaScrip/Python with the page thinking it is mobile network when it actually isn't? Thanks in advance
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/89783163
tagged with: javascript
has title: Simulate mobile network in nodejs or javascript?
score: 0

http://stackoverflow.com/comment/89767219
has text: @NeerajJoon It's generally a bad behavior not to be precise about the exception you want to catch. I recommand you to replace `except:` by `except ObjectDoesNotExist:` . You'll have to do `from django.core.exceptions import ObjectDoesNotExist`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51381335

apache-spark-dataset
tag name: apache-spark-dataset
tags question: http://stackoverflow.com/q/51342777
type: Tag

http://stackoverflow.com/a/51471235
upvote count: 1
answers question: http://stackoverflow.com/q/51471063
type: Answer
downvote count: 0
score: 1
has body: Putting all of this code into one line would be very inadvisable. Although I personally like list comprehensions, some people find them complicated. If this code has a possibility of being edited later, it would be better not write this on one line for maintenance purposes. The true cost of code is maintenance. AND, with my current knowledge, it is impossible to get that requested_set variable before its declaration. The code is simply too convoluted for it to be on one line. However, it is not my place to tell you how to write your code. Because of the requested-set variable, it is impossible to put this all on one line, but it is possible in two lines: for requested_set in self.roles[server.id]['sets']: requested_sets[requested_set] = [role for role in self.collections[server.id][user.id] if role in self.roles[server.id]['sets'][requested_set]['roles']]

http://stackoverflow.com/q/51461210
type: AnsweredQuestion
has body: I am wanting to initiate multiple instances of a sub classes that each take their attributes from a specific instance of a class, rather than the general class. For example if I have buildings and rooms, every room needs to belong to a specific instance of a building, taking its attributes and methods. class Building: def __init__(self, buildingName, location): self.buildingName = buildingName self.location = location # lots more intersting stuff def Evacuate_Building(self): # do some stuff pass class Room(Building): def __init__(self, roomName, roomType): self.roomName = roomName self.roomType = roomType # lots more intersting stuff def Directions(self, Current_Location): '''do some stuff involving this.roomName and this.location which comes from the specific instance of the class''' pass So say I have three buildings: 'North', 'South' and 'West'. Each building has its own rooms. Looking at just the North Building it has the rooms 'N1', 'N2', 'N3', 'N4'. In my code I would go through and initiate the three Buildings first, then I would initiate the Rooms, some how linking them back to its corresponding Building. This allows me to use the Directions method, which utalises the attribute location from its parent class instance, which is unique to that Building, not a general value. It also needs to be be able to use the method from the parent class, Evacuate_Building. I could get around this by passing the location data every time I initiate a room in the more standard setup using super(buildingName, location) or Building.__ init__(self, buildingName, location) however this means I have to write the location for every single Room and if I add or change something in the Building, I need to change every single room initialisation and the init code if additional attributes have been added. I can also copy a the attributes out by passing the instance of the Building as a parameter to the init and then going this.location = building.location but this also has the same prob…
tagged with: oop
has comment: http://stackoverflow.com/comment/89891792
type: Question
score: 5
answer count: 3
has comment: http://stackoverflow.com/comment/89891700
has answer: http://stackoverflow.com/a/51461253
accepted answer: http://stackoverflow.com/a/51461253
possible better answer: http://stackoverflow.com/a/51461230
tagged with: inheritance
has comment: http://stackoverflow.com/comment/89892251
favorite count: 0
tagged with: class
tagged with: python
has comment: http://stackoverflow.com/comment/89891714
linked to: http://stackoverflow.com/q/1081253
has answer: http://stackoverflow.com/a/66506739
upvote count: 5
has comment: http://stackoverflow.com/comment/89892214
downvote count: 0
has comment: http://stackoverflow.com/comment/89891949
has answer: http://stackoverflow.com/a/51461230
has title: Inherit from Instance rather than Class [Python 3]

http://stackoverflow.com/comment/89649799
has text: An important part of any programming is checking - you clearly didn't check your question after submitting it...
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51337563

http://stackoverflow.com/q/51471284
has comment: http://stackoverflow.com/comment/89910918
has answer: http://stackoverflow.com/a/51471394
score: 0
has title: Why is the following while condition not stopping in Python?
answer count: 3
tagged with: while-loop
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89910895
has answer: http://stackoverflow.com/a/51471377
has answer: http://stackoverflow.com/a/51471347
has body: I have a location that I want to find the coordinates of. But my function gmaps_geoencoder is interpreting the address wrongly as belonging to a different country. So, my logic is, keep removing words one by one from the address until the latitudes and longitudes returned are in the correct range(i.e., until it interprets the address correctly). To illustrate the issue, here's the code: place = "*LORENZO GOMEZ &amp; CO CPA'S RM 202 DON RAFAEL CASTILLO BLDG LEGASPI ST DAVAO CITY DAVAO DEL SUR PHILIPPINES" gmaps_geoencoder(place) &gt;&gt;&gt; "{'results': [{'address_components': [{'long_name': 'San Diego', `'short_name': 'San Diego', 'types': ['locality', 'political']}, {'long_name': 'California', 'short_name': 'CA', 'types': ['administrative_area_level_1', 'political']}, {'long_name': 'United States', 'short_name': 'US', 'types': ['country', 'political']}, {'long_name': '92123', 'short_name': '92123', 'types': ['postal_code']}], 'place_id': 'ChIJAy3bGzT-24ARmX-IpDjdadk', 'types': ['doctor', 'establishment', 'health', 'point_of_interest'], 'formatted_address': '4715 Viewridge Avenue Suite 230, San Diego, CA 92123, San Diego, CA 92123, United States', 'geometry': {'location': {'lat': 32.8238366, 'lng': -117.119949}, 'location_type': 'GEOMETRIC_CENTER', 'viewport': {'southwest': {'lat': 32.8224876197085, 'lng': -117.1212979802915}, 'northeast': {'lat': 32.8251855802915, 'lng': -117.1186000197085}}}}], 'status': 'OK'}"` As we can see, its interpreting the address as belonging to the United States, when its actually in the Philippines. When I remove the first few words from the address though, it interprets it correctly: place = "RM 202 DON RAFAEL CASTILLO BLDG LEGASPI ST DAVAO CITY DAVAO DEL SUR PHILIPPINES" gmaps_geoencoder(place) &gt;&gt;&gt; "{'results': [{'address_components': [{'long_name': 'Rafael Castillo', 'short_name': 'Rafael Castillo', 'types': ['administrative_area_level_5', 'political']}, {'long_name': 'Agdao', 'short_name': 'Agdao', 'types': ['political', '…
type: Question
has comment: http://stackoverflow.com/comment/89910997

http://stackoverflow.com/a/51361770
has comment: http://stackoverflow.com/comment/89696171
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51361540
answers question: http://stackoverflow.com/q/51361540
type: Answer
score: 0
has body: You should be able to set the size of your plots with matplotlib.Figure.set_size_inches To use this you will need to save the Figure object. You can include this in your code like this : for graph in range(1,13): name = all_results[graph-1] fig, axs = plt.subplot(4,3,graph, title = name) plt.tight_layout() current_model = name plt.hist(all_val_accuracies[current_model], #range = (0.49, 0.58), bins = 50) fig.set_size_inches(12, 12) plt.xlabel('Accuracy') plt.ylabel('Frequency') plt.axis([0.48, 0.58, 0, 50])

opengl
tags question: http://stackoverflow.com/q/51338079
tags question: http://stackoverflow.com/q/51391749
type: Tag
tags question: http://stackoverflow.com/q/51346196
tag name: opengl

http://stackoverflow.com/a/51475582
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51472720
has body: You can use collections.defaultdict to construct a mapping of list values to key(s). Data from @jezrael. from collections import defaultdict d = defaultdict(list) for k, v in sampleDict.items(): for w in v: d[w].append(k) print(d) defaultdict(list, {'123': ['a'], '272': ['b'], '456': ['a'], '789': ['a', 'b']}) Then use pd.Series.map to map inputs to keys in a new series: df = pd.DataFrame({'Input':['789','456','100']}) df['found'] = df['Input'].map(d) print(df) Input found 0 789 [a, b] 1 456 [a] 2 100 NaN

http://stackoverflow.com/comment/89891959
comment on: http://stackoverflow.com/q/51461378
score: 2
type: Comment
type: QuestionComment
has text: Only if you can get the original code.

http://stackoverflow.com/comment/89869094
type: QuestionComment
comment on: http://stackoverflow.com/q/51449319
has text: To clarify, are the lists `temps1` and `temps2` of the same length or no?
score: 0
type: Comment

http://stackoverflow.com/q/51366343
has answer: http://stackoverflow.com/a/51366522
favorite count: 0
has body: I have this dataframe: d = {'city':['Barcelona','Madrid','Rome','Torino','London','Liverpool','Manchester','Paris'], 'country': ['ES','ES','IT','IT','UK','UK','UK','FR'], 'revenue': [1,2,3,4,5,6,7,8], 'amount': [8,7,6,5,4,3,2,1] df = pd.DataFrame(d) I want to obtain this for each country: españa = {'city':['Barcelona','Madrid'] 'revenue':[1,2] 'amount':[8,7]} ES = pd.DataFrame(españa) So that in the end I will have 4 dataframes named ES,IT,UK and FR. I have tried this so far: a = set(df.loc[:]["country"]) for country in a: country = df.loc[(df["country"]== country),['date','sum']] But that only gave me one dataframe with one value.
has answer: http://stackoverflow.com/a/51366427
upvote count: 1
tagged with: python
type: AnsweredQuestion
has title: How to create dataframes iterating over a set?
score: 1
tagged with: set
tagged with: loops
type: Question
possible better answer: http://stackoverflow.com/a/51366427
has answer: http://stackoverflow.com/a/51366507
accepted answer: http://stackoverflow.com/a/51366507
answer count: 3
tagged with: pandas
downvote count: 0

http://stackoverflow.com/comment/89917419
type: Comment
has text: No, it only looks like the green block is behind the lines, due to its transparency. Use `alpha=0.7` or higher to see it more clearly.
comment on: http://stackoverflow.com/a/51464693
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89678997
type: Comment
type: QuestionComment
score: 0
has text: @M.ike i did and nothing changed
comment on: http://stackoverflow.com/q/51353000

http://stackoverflow.com/q/51446156
tagged with: django
tagged with: excel
type: Question
has body: I'm running Django on a localhost (Later to run on a LAN) where the idea is I can go onto the webpage, click a button where you're prompted to select an excel file from your computer. Pandas will do work on said excel file and Django/Pandas will make excel file of this Pandas data frame as a download prompt. I've got Django running and using the code below from the module 'Django-Excel' does the basics of what I want. Excel file in ---> excel file out, no saving the file to a database or anything just keeping it in the memory. However, I cannot find a way to shoehorn Pandas into it. The main problem I have is I'm unsure how to return an excel file using Pandas. I've been using '.to_excel()' in my offline python code, however, haven't found a way to use it in a localhost running Django. I'm sure I'm missing something really simple but I just can't get it. Maybe if someone could show a simple example of say, uploading an excel, pandas will multiply a column of numbers in the excel by 2, new excel is outputted to read/save. from django.shortcuts import render, redirect from django.http import HttpResponseBadRequest, HttpResponse from _compact import JsonResponse from django import forms import django_excel as excel from polls.models import Question, Choice class UploadFileForm(forms.Form): file = forms.FileField() # Create your views here. def upload(request): if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): filehandle = request.FILES['file'] # do pandas here to filehandle/ put filehandle into a function return excel.make_response(filehandle.get_sheet(), "csv", file_name="download") else: form = UploadFileForm() return render( request, 'upload_form.html', { 'form': form, 'title': 'Excel file upload and download example', 'header': ('Please choose any excel file ' + 'from your cloned repository:') }) Thank you very much, sorry if this isn't clear It's my first time posting on this website, if you don't understand what I…
upvote count: 2
accepted answer: http://stackoverflow.com/a/51480876
tagged with: pandas
answer count: 1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51480876
has comment: http://stackoverflow.com/comment/89863728
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
has title: Django upload excel file, process with pandas, download as csv

http://stackoverflow.com/a/51391384
type: AcceptedAnswer
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/51391014
has body: Your first sentence was enough of a clue for me to unravel the rest of your posting. Your main problems are loop handling and logic of determining a prime factor. In general, I see your program design as Input target number Find each factor of the number For each factor, determine whether the factor is prime. If so, print it. Now, let's look at the innermost loop: while(c &lt; b - 1): c = c + 1 if((b / c) % 1 != 0): d = b counter = counter + 1 if(counter == 2): print(d) As a styling note, please explain why you are building for logic from while loops; this makes your program harder to read. Variable d does nothing for you. Also, your handling of counter is an extra complication: any time you determine that b is a prime number, then simply print it. The main problem is your logical decision point: you look for factors of b. However, rather than waiting until you know b is prime, you print it as soon as you discover any smaller number that doesn't divide b. Since b-1 is rarely a factor of b (only when b=2), then you will erroneously identify any b value as a prime number. Instead, you have to wait until you have tried all possible factors. Something like this: is_prime = True for c in range(2, b): if b % c == 0: is_prime = False break if is_prime: print(b) There are more "Pythonic" ways to do this, but I think that this is more within your current programming sophistication. If it's necessary to fulfill your assignment, you can add a point only when you've found no factors, and then check the count after you leave the for loop. Can you take it from there?
answers question: http://stackoverflow.com/q/51391014

http://stackoverflow.com/comment/108077784
type: Comment
comment on: http://stackoverflow.com/a/51429868
score: 0
type: AnswerComment
has text: `joblib` is deprecated as of scikit 0.21 and will be removed in 0.23. Now, it needs to be installed as a separate package either through pip (`pip install joblib`) or [conda](https://anaconda.org/anaconda/joblib) (`conda install -c anaconda joblib`)

http://stackoverflow.com/a/51463048
has body: Found answer here v = df.groupby(level=0).idxmax().values df.loc[v.ravel()]
type: Answer
answers question: http://stackoverflow.com/q/51462766
score: 1
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/89636185
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51330180
score: 0
has text: You mean the `tabulate` function?

http://stackoverflow.com/comment/89663826
has text: Added the answer but "You can accept your own answer in 2 days"
score: 0
comment on: http://stackoverflow.com/q/51345136
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89759869
comment on: http://stackoverflow.com/q/51394119
has text: Dictionaries cannot be sorted as they are not ordered.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89860823
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/51444874
has text: @Yuca to be honestly , I learnt those skill from Jz, PiR ,Coldspeed, Scott and Zero and so on . :-)

http://stackoverflow.com/q/51466026
tagged with: python
upvote count: 1
type: Question
has body: I have tried below code x=dd.groupby(['name','sal'])['sal'].agg({'Frequency':'count'}) nombre=x.columns.tolist()[0] x.rename(columns={nombre:'Freq'},inplace=True) x['Pct']=round((x['Freq']/x.Freq.sum())*100,2) x['Freq Acum'],x['Cumm Percent']=x.Freq.cumsum(),x.Pct.cumsum() x.sort_values(['Freq'],ascending=[0],inplace=True) pd.set_option('display.max_columns',500) print(' Frequency on : '+nombre) print('\n') print(x) print('\n') and I am able to get below result which I expected: Frequency on : Frequency Freq Pct Freq Acum Cumm Percent name sal Amit 100 2 50.0 2 50.0 gupta 200 1 25.0 3 75.0 hello 300 1 25.0 4 100.0 But when I am trying to put this code into function as below : def cross_freq_2way(dataset,arg1,arg2): x= dataset.groupby([arg1,arg2],axis=1).agg(({'Frequency':'count'}),axis=1) nombre=x.columns.tolist()[0] x.rename(columns={nombre:'Freq'},inplace=True) x['Pct']=round((x['Freq']/x.Freq.sum())*100,2) x['Freq Acum'],x['Cumm Percent']=x.Freq.cumsum(),x.Pct.cumsum() x.sort_values(['Freq'],ascending=[0],inplace=True) pd.set_option('display.max_columns',500) print(' Frequency on : '+nombre) print('\n') print(x) print('\n') print(cross_freq_2way(dd,['name'],['sal'])) I am getting ValueError: Grouper and axis must be same length. Please help.
downvote count: 0
has comment: http://stackoverflow.com/comment/89900495
has answer: http://stackoverflow.com/a/51466406
tagged with: pandas
answer count: 1
score: 1
favorite count: 0
type: UnansweredQuestion
has title: python groupby aggregate function error

http://stackoverflow.com/comment/89844712
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51418830
score: 1
has text: You're right, I'm not particularly locked in for JSON, I can change the reader easily. I've already spent more time on the CSV solution, as I'm making the most progress there. Thanks @Tomalak!

http://stackoverflow.com/a/51342418
type: Answer
answers question: http://stackoverflow.com/q/51342228
score: 16
upvote count: 16
downvote count: 0
has body: If you use python3.7 you get data classes as @dataclass. Official doc here - 30.6. dataclasses — Data Classes from dataclasses import dataclass @dataclass class CustomerOrder: order_id: int customer_id: str item_name: str order = CustomerOrder(1, '001', 'Guitar') print(order) Make sure to upgrade python3 to python 3.7 or if you use python 3.6 install dataclass from pypi In macos: brew upgrade python3 While above data class in scala looks like, scala&gt; final case class CustomerOrder(id: Int, customerID: String, itemName: String) defined class CustomerOrder

http://stackoverflow.com/q/51337030
has title: python networkx: How to get a random path?
has answer: http://stackoverflow.com/a/51337353
type: AnsweredQuestion
has body: In the networkx there is such a function nx.all_simple_paths(G,source=0,target=5) it returns all the paths, but if there are a lot of possible paths, it will work very long. How can one immediately get just any path?
upvote count: 2
tagged with: networkx
has answer: http://stackoverflow.com/a/51337088
type: Question
linked to: http://stackoverflow.com/q/4741243
answer count: 2
score: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/51337088
favorite count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/51337353

http://stackoverflow.com/q/51371365
tagged with: processing-efficiency
tagged with: python
has comment: http://stackoverflow.com/comment/89714950
has answer: http://stackoverflow.com/a/51372109
has comment: http://stackoverflow.com/comment/89715223
accepted answer: http://stackoverflow.com/a/51372109
has title: Algorithm Efficiency - Data Processing Efficiency using Pandas (three nested for loops)
type: AnsweredQuestion
tagged with: algorithm
has comment: http://stackoverflow.com/comment/89715283
has comment: http://stackoverflow.com/comment/89714930
has body: The data comes in two data sets which I need to check for if a single time event in the first data set at a specific location coincides with a time range in the second dataset at the same specific location, and append the ID of the second set to the first accordingly if the conditions are met. I have a list of specific locations that I want to check. My problem is that the first data set contains about 500,000 rows, and the second contains about 90,000 rows. Running through both data sets takes forever and my computing power is limited. Here is the Python code: import datetime import pandas as pd def assign_tRangeID(singleEventDF, timeRangeDF): margin = datetime.timedelta(minutes=15) for i, single in singleEventDF.iterrows(): for j, timeRange in timeRangeDF.iterrows(): if timeRange['start_time']-margin &lt;= single['singleEvent_time'] &lt;= timeRange['end_time'] singleEventDF.at[i, 'tRange_ID'] = timeRangeDF['ID'] for i, location in location_list.iterrows(): single_subset = singleEvent['loc'].loc[[singleEvent['loc'] = location['loc']] tRange_subset = timeRange['loc'].loc[[timeRange['loc'] = location['loc']] assign_eventID(single_subset, tRange_subset) I am a beginner in Python, so I'm just wondering if I can do this in a more efficient manner without having to use a database or some big data solution. Thanks for all the help!
has comment: http://stackoverflow.com/comment/89715260
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/51371967
tagged with: data-science
score: 0
has answer: http://stackoverflow.com/a/51371967
tagged with: pandas

http://stackoverflow.com/comment/89900916
type: QuestionComment
has text: No. Do I really have to ?
type: Comment
comment on: http://stackoverflow.com/q/51466192
score: 0

http://stackoverflow.com/q/51441996
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has title: python pandas - merge data conditionally
has body: I have two panda tables with identical columns, what id like to do is merge these columns if the data in the circuit column is None &gt;&gt; site_routing_data[0] circuit errors route site mask next_hop error 0 MPLS None 10.10.1.0 Manchester 255.255.255.0 172.5.1.5 NaN 1 MPLS None 10.10.2.0 London 255.255.255.0 172.5.1.5 NaN 2 None None 10.10.3.0 Birmingham 255.255.255.0 172.5.1.5 NaN 3 MPLS None 10.10.4.0 Sheffield 255.255.255.0 172.5.1.5 NaN &gt;&gt; site_routing_data[1] circuit errors route site mask next_hop error 0 FTTC None 10.10.1.0 Manchester 255.255.255.0 172.10.1.6 NaN 1 FTTC None 10.10.2.0 London 255.255.255.0 172.10.1.7 NaN 2 FTTC None 10.10.3.0 Birmingham 255.255.255.0 172.10.1.8 NaN 3 FTTC None 10.10.4.0 Sheffield 255.255.255.0 172.10.1.9 NaN I would like to merge these two together, but only replace any records in table 0 that have a None value for the circuit column. The final table would look like circuit errors route site mask next_hop error 0 MPLS None 10.10.1.0 Manchester 255.255.255.0 172.5.1.5 NaN 1 MPLS None 10.10.2.0 London 255.255.255.0 172.5.1.5 NaN 2 FTTC None 10.10.3.0 Birmingham 255.255.255.0 172.10.1.8 NaN 3 MPLS None 10.10.4.0 Sheffield 255.255.255.0 172.5.1.5 NaN Thanks
tagged with: pandas
has answer: http://stackoverflow.com/a/51442176
accepted answer: http://stackoverflow.com/a/51442176
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/89664280
type: Comment
has text: The existing call is `X.__getattr__('append')(4)`.
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51345545

http://stackoverflow.com/comment/89882038
type: Comment
comment on: http://stackoverflow.com/a/51456120
score: 0
type: AnswerComment
has text: In my program when login button is clicked it checks in database and then os.system ('mainwindow.exe') is called which should open the mainwindow but it is not opening while when I exit mainwindow then os.system ('loginform.exe') is called which works perfectly. Is this the right way to call the forms or not?

http://stackoverflow.com/a/51344403
answers question: http://stackoverflow.com/q/51343097
type: Answer
upvote count: 3
downvote count: 1
score: 2
has body: For an empty list, using [] is much better because it's faster and avoid name look-up The list() built-in is useful to convert some other iterable to a list.

http://stackoverflow.com/q/51409824
has comment: http://stackoverflow.com/comment/89791090
tagged with: python
tagged with: operand
has comment: http://stackoverflow.com/comment/89791430
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/89791089
has comment: http://stackoverflow.com/comment/89791128
downvote count: 5
has body: in this statement stop_words_index = [word_index.get(w) + 3 for w in stop_words] word_index.get(w) is an int, but this statement generates TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' How to fix this?
tagged with: nonetype
upvote count: 0
has answer: http://stackoverflow.com/a/51409843
score: -5
has comment: http://stackoverflow.com/comment/89791033
answer count: 1
has title: adding an int to int in a list comprehension fails
favorite count: 0
has comment: http://stackoverflow.com/comment/89791034

http://stackoverflow.com/a/51345716
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51345639
downvote count: 0
has body: Since the question specifically mentions that it should be in a loop (perhaps there is further processing that needs to be done that was taken out), here's what that would look like (modifying @Andrej Kesely's strong approach) sort_ = { str(4213) : ("STEM Center",0), str(4201) : ("Foundations Lab",1), str(4204) : ("CS Lab",2), str(4218) : ("Workshop Room",3), str(4205) : ("Tiled Room",4), "Out" : ("Outside",5) } result = [] for key, (name, count) in sort_.items(): result.append((key, name, count)) I renamed sort to sort_. Even though it isn't in this namespace (sort is a method on lists), I don't like using key words. [('4213', 'STEM Center', 0), ('4201', 'Foundations Lab', 1), ('4204', 'CS Lab', 2), ('4218', 'Workshop Room', 3), ('4205', 'Tiled Room', 4), ('Out', 'Outside', 5)]

http://stackoverflow.com/q/51411212
type: AnsweredQuestion
has title: TensorFlow tf.map_fn removes a dimension
upvote count: 1
has body: I am trying to remap values in an input Tensor using a defaultdict. class MyDataSet(object): def __init__(self): self.class_map = MyDataSet.remap_class() @staticmethod def remap_class(): class_remap = defaultdict(lambda: 11) class_remap[128] = 0 class_remap[130] = 1 class_remap[132] = 2 # ... def parser(self, serialized_example): features = tf.parse_single_example( serialized_example, features={ 'image': tf.FixedLenFeature([], tf.string), 'label': tf.FixedLenFeature([], tf.string), }) label = tf.decode_raw(features['label'], tf.uint8) label.set_shape([256 * 512]) label = tf.cast(tf.reshape(label, [256, 512]), tf.int32) output_label = tf.map_fn(lambda x: self.class_map(x), label) #... dataset = tf.data.TFRecordDataset(filenames).repeat() dataset = dataset.map(self.parser, num_parallel_calls=batch_size) The label shape is (256,512) but the output_label shape is (256,). If I try to change the output_label with output_label = tf.reshape(output_label, [256, 512]) I get the exception ValueError: Cannot reshape a tensor with 256 elements to shape [256,512] (131072 elements) for 'Reshape_2' (op: 'Reshape') with input shapes: [256], [2] and with input tensors computed as partial shapes: input[1] = [256,512]. If I try to change the output_label with output_label.set_shape([256, 512]) I get the exception ValueError: Shapes (256,) and (256, 512) must have the same rank How do I map values and maintain the same shape in output_label as in label?
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/51428836
score: 1
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51428836
favorite count: 0
tagged with: python

http://stackoverflow.com/q/51416970
has comment: http://stackoverflow.com/comment/89805620
has title: How to find the index of all minimum elements in a numpy array in python?
favorite count: 0
tagged with: python
has body: Suppose I have a numpy array a = np.array([0,2,3,4,5,1,9,0,0,7,9,0,0,0]).reshape(7,2) I want to find out the indices of all the times the minimum element (here 0) occurs in the 2nd column. Using argmin I can find out the index of when 0 is occurring for the first time. How can I do this in Python?
type: UnansweredQuestion
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89805488
score: -1
linked to: http://stackoverflow.com/q/6294179
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/51418480
upvote count: 0
has answer: http://stackoverflow.com/a/51420196

http://stackoverflow.com/comment/89798945
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51413646
has text: @ScottHunter thought you may have been referring to something else........... is that all you came here to say? lol
score: 0

http://stackoverflow.com/comment/89925805
type: Comment
has text: @MaMo - I think [`boolean indexing`](http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing) is fine, call `df = df[df.ref_value == 'B2']` before `df[cols] = df[cols].mul(df[col_ref].map(ref.set_index('SOURCE')['VALUE']), axis=0)`
score: 0
comment on: http://stackoverflow.com/a/51475111
type: AnswerComment

http://stackoverflow.com/comment/89847042
has text: I'd say it chooses the first one that the numerical routine converges to. Also I believe that MATLAB and numpy may not output the same ones.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51438411
score: 1

http://stackoverflow.com/q/51476114
has title: Reproducing the camera angle of the following figure in Mayavi in Python
tagged with: plot
score: 2
downvote count: 0
type: Question
has answer: http://stackoverflow.com/a/51476381
linked to: http://stackoverflow.com/q/25783180
upvote count: 2
has body: I have the following image that illustrates how a box is sheared: I want to plot my data as follows (note that the coordinates of the spheres are not sheared, i.e. the spheres reside in a perfectly cubic box) I have achieved the current positioning using mlab and the following code # Achieve x-y view. mlab.view(azimuth=0, elevation=0, distance=3.0) # Rotate along x axis to expose part of the top of the box. pts.actor.actor.rotate_x(30) # Move camera down to compensate for rotation. mlab.move(up=-0.37) Is there a way to maneuver the camera such that the data look more like the illustration, by exposing some of the right side of the cube, while keeping the x-axis completely horizontal? Edit: mlab.view(azimuth=0, elevation=0, focalpoint=[4, 4, 0], distance=30.0) produces the perspective I want. However, I am only able to see the box off to the side and into the distance. Zooming the camera causes the box to disappear from the image, since it zooms in to the point x, y, z = [4, 4, 0]. Is there a way I can "zoom back into" the relevant parts of the picture?
answer count: 1
favorite count: 0
tagged with: mayavi
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/89919740
comment on: http://stackoverflow.com/q/51475495
type: QuestionComment
type: Comment
has text: I am sorry for what I don't add some information because it's my first time to use stack overflow. And indeed I tried to test and rewrite my code all days and this version is the best one I could make. I don't know how to edit the question. If I find the way, I'll do better.
score: 0

http://stackoverflow.com/a/51467933
has body: I made a few changes and make it work: First, change which html element you read the data from in javascript part: var formDataRaw = $('#FileForm')[0]; var form_data = new FormData(formDataRaw); Second, I tried to obtain the uploaded image as follows: (@cross_origin() is only required if you try to upload to your localhost) @app.route("/demo-upload", methods=["GET", "POST"]) @cross_origin() def ProcessImage(): if request.method == "POST": print(request.files) try: if 'file' in request.files: imageFile = request.files['file'] savePath = "/somewhere/somewhere/something.png" imageFile.save(savePath) except Exception as e: print(e) return jsonify("Ok")
accepted answer of: http://stackoverflow.com/q/51467036
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51467036
score: 3
has comment: http://stackoverflow.com/comment/89934310
type: AcceptedAnswer
upvote count: 3

http://stackoverflow.com/a/51370013
score: 0
accepted answer of: http://stackoverflow.com/q/51369889
type: AcceptedAnswer
has body: For this web site you need to target with id="ProductJson-product-template". It contains JSON with all variants: import bs4 as bs import urllib.request import json link = urllib.request.urlopen('https://www.deadstock.ca/products/adidas-futurepacer-grey-one').read() soup = bs.BeautifulSoup(link,'lxml') variant = soup.find('script', id='ProductJson-product-template') data = json.loads(variant.text) print(json.dumps(data, indent=4, sort_keys=True)) Prints: { "available": true, "compare_at_price": null, "compare_at_price_max": 0, "compare_at_price_min": 0, "compare_at_price_varies": false, "content": " adidas digs into its vault to redesign the 1984 Micropacer, a computerized shoe that was designed to track running statistics. Today, the adidas Futurepacer takes cues from the Micropacer, and the more recent NMD collection, to deliver a futuristic lifestyle runner. Featuring a premium leather upper, complete with a modernized lace cover, the adidas Futurepacer sits on a Boost midsole for lightweight cushioning and responsiveness. NMD inspired bumpers are found at the heel and forefoot for added style and stability. \n \n Premium leather upper \n Premium leather lace cover \n Subtle adidas branding \n Boost midsole \n adidas midsole plugs \n Grey One \n \n Product Code: AQ0907 ", "created_at": "2018-03-05T14:23:57-08:00", "description": " adidas digs into its vault to redesign the 1984 Micropacer, a computerized shoe that was designed to track running statistics. Today, the adidas Futurepacer takes cues from the Micropacer, and the more recent NMD collection, to deliver a futuristic lifestyle runner. Featuring a premium leather upper, complete with a modernized lace cover, the adidas Futurepacer sits on a Boost midsole for lightweight cushioning and responsiveness. NMD inspired bumpers are found at the heel and forefoot for added style and stability. \n \n Premium leather upper \n Premium leather lace cover \n Subtle adidas branding \n Boost midsole \n adidas midsole plug…
answers question: http://stackoverflow.com/q/51369889
has comment: http://stackoverflow.com/comment/89712386
type: Answer
has comment: http://stackoverflow.com/comment/89712347
has comment: http://stackoverflow.com/comment/89712552

reindex
tag name: reindex
tags question: http://stackoverflow.com/q/51335085
type: Tag

http://stackoverflow.com/q/51464791
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89898235
has comment: http://stackoverflow.com/comment/89898210
favorite count: 0
has comment: http://stackoverflow.com/comment/89898930
has body: So, I am trying to get my head around regexp. The first query doesn't give me the result but the second one does. I am not able to make sense, why that is. I am trying to tokenize the sentence, text = 'The interest does not exceed 8.25%.' pattern = r'\w+|\d+\.\d+\%|[^\w+\s]+' tokenizer = RegexpTokenizer(pattern) tokenizer.tokenize(text) This gives me ['The', 'interest', 'does', 'not', 'exceed', '8', '.', '25', '%'] And I want ['The', 'interest', 'does', 'not', 'exceed', '8.25%'] I get my result with, pattern = r'\d+\.\d+\%|\w+|[^\w+\s]+' Why does it work with the second pattern? Shouldn't both the queries work?
upvote count: 1
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/51464858
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/51464858
has comment: http://stackoverflow.com/comment/89898991
type: Question
has title: Regular expression (Reg exp). Why this works?
has comment: http://stackoverflow.com/comment/89898252
has comment: http://stackoverflow.com/comment/89898226

http://stackoverflow.com/a/51479545
type: Answer
accepted answer of: http://stackoverflow.com/q/51467800
answers question: http://stackoverflow.com/q/51467800
has body: Okay, so I found some kind of solution to my problem. Inspired by this post: tkinter Canvas Scrollbar with Grid?. I came up with the following solution. Python is new to me so it could probably be done more elegant:-) The problem that I am facing now is that the label width is given in text units and wraplength in screen units. Is there a method to find the conversion factor between the two? from tkinter import * import math class MyApp(Tk): def __init__(self): Tk.__init__(self) #self.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) self.geometry('950x500+100+100') label = Label(self,text='Table with some data', font=("Arial Bold", 25)) label.pack() master_frame = Frame(self, bd=3, relief=RIDGE) master_frame.pack(side=BOTTOM) # Create a frame for the canvas and scrollbar(s). frame2 = Frame(master_frame) frame2.pack(side = BOTTOM) # Add a canvas in that frame. canvas = Canvas(frame2) canvas.grid(row=0, column=0) # Create a vertical scrollbar linked to the canvas. vsbar = Scrollbar(frame2, orient=VERTICAL, command=canvas.yview) vsbar.grid(row=0, column=1, sticky=NS) canvas.configure(yscrollcommand=vsbar.set) # Create a frame on the canvas to contain the buttons. self.table_frame = Frame(canvas) #Add some info to table newLine = ["Step#","Process Type","Tool Info","Process details","Cost","Comments"] self.newRow(0,newLine) newLine = ["Step# Step#","Process Type","Tool Info","Process details","Cost","Comments"] self.newRow(1,newLine) newLine = ["Step# Step# Step#","Process Type","Tool Info","Process details","Cost","Comments"] self.newRow(2,newLine) newLine = ["Step# Step# Step# Step#","Process Type","Tool Info","Process details","Cost","Comments"] self.newRow(3,newLine) newLine = ["Step# Step# Step# Step# Step#","Process Type","Tool Info","Process details","Cost","Comments"] self.newRow(4,newLine) # Create canvas window to hold the buttons_frame. canvas.create_window((0,0), window=self.table_frame, anchor=NW) self.table_frame.update_idletasks() # Needed to m…
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/89902209
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51466437
has text: What are the 3 output labels that you are trying to get? Are you trying to predict a single label or trying to get separate probability for each label?
type: Comment

http://stackoverflow.com/comment/114883497
has text: See also [How to plot a mean line on a distplot between 0 and the y value of the mean?](https://stackoverflow.com/questions/63307440/how-to-plot-a-mean-line-on-a-distplot-between-0-and-the-y-value-of-the-mean) for drawing such lines up till the kde curve.
type: Comment
comment on: http://stackoverflow.com/q/51417483
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89888577
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51459586
has text: You should add a few lines of html to your question to make your [mcve] complete - format it as code.. The example html should have a mixture of *good* cells and *bad* cells.
score: 0

http://stackoverflow.com/comment/89633276
has text: Ok, I can't seem to install the `win32com` module to test this myself. But it does look like the `Department` property *exists*. See [here](https://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook._contactitem.department.aspx).
comment on: http://stackoverflow.com/q/51328169
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89748744
score: 0
type: Comment
type: QuestionComment
has text: Yes, i did put the link to that in the comment right above yours.
comment on: http://stackoverflow.com/q/51387969

http://stackoverflow.com/comment/89675338
type: Comment
type: QuestionComment
has text: yes. The probability distribution
score: 0
comment on: http://stackoverflow.com/q/51350267

http://stackoverflow.com/comment/90192488
has text: It's not a syntax error, it seems like you have a lib installed in conflict with robotframework, can you try installing your project environment in a separate virtualenv ? That would resolve the problem
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51380249

http://stackoverflow.com/comment/92874129
comment on: http://stackoverflow.com/a/51678589
type: AnswerComment
score: 0
has text: I believe that I ended up using Keras 2.1.3/ Tensorflow 1.8.0. Hope that helps!
type: Comment

http://stackoverflow.com/a/51463474
has comment: http://stackoverflow.com/comment/89993359
answers question: http://stackoverflow.com/q/51463449
has body: Use this: import csv header_list = ['column_1', 'column_2', 'column_3'] mystring = ",".join(header_list) def line_prepender(filename, line): with open(filename, 'r+') as csvfile: content = csvfile.read() csvfile.seek(0, 0) csvfile.write(line.rstrip('\r\n') + '\n' + content) line_prepender("text.csv", mystring)
has comment: http://stackoverflow.com/comment/89898935
has comment: http://stackoverflow.com/comment/89895833
has comment: http://stackoverflow.com/comment/89895961
score: 4
has comment: http://stackoverflow.com/comment/90008841
type: Answer
has comment: http://stackoverflow.com/comment/90015627
upvote count: 4
downvote count: 0

http://stackoverflow.com/comment/89795736
score: 1
type: AnswerComment
has text: Holy cow what a thorough answer.
type: Comment
comment on: http://stackoverflow.com/a/51411995

http://stackoverflow.com/comment/89709589
has text: @dimstudio I don't get this warning, so I assume it's an issue with your `df`, which might be a slice of your original data or something similar. It's not link to these two lines of codes, so not sure how to help, but the link provides in the warning is a good way to understand why :)
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51364268

http://stackoverflow.com/q/51465351
has answer: http://stackoverflow.com/a/51473521
answer count: 1
favorite count: 0
type: UnansweredQuestion
has title: Using a 1-channel image as a mask in opencv python
tagged with: python
score: 1
tagged with: mask
upvote count: 1
type: Question
tagged with: opencv
downvote count: 0
has body: I am new to OpenCV and trying to impliment the basic optical flow example here: https://docs.opencv.org/3.3.1/d7/d8b/tutorial_py_lucas_kanade.html I only want goodFeaturesToTrack() to analyze a small static circular part of my webcam input. The goodFeaturesToTrack function takes a mask argument, to which I am trying to pass in a 1-channel .png image of the same size as the input with cv2.imread('mask.png',0), but with no luck (it returns a mask.empty() error). I feel like I am going about this in the wrong way, perhaps. Am I missing something obvious here? Or would it be easier for me to draw a circle within OpenCV itself?

http://stackoverflow.com/comment/89673072
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51349076
has text: `global labelAns` in a different function does not magically override the fact that `labelAns` is local in the function that actually sets it.
score: 0

tkinter
tags question: http://stackoverflow.com/q/51481114
tags question: http://stackoverflow.com/q/51387783
tags question: http://stackoverflow.com/q/51372555
tags question: http://stackoverflow.com/q/51346102
tags question: http://stackoverflow.com/q/51394482
tags question: http://stackoverflow.com/q/51467800
tags question: http://stackoverflow.com/q/51392748
tags question: http://stackoverflow.com/q/51455193
tags question: http://stackoverflow.com/q/51455808
tags question: http://stackoverflow.com/q/51476153
tags question: http://stackoverflow.com/q/51338338
tags question: http://stackoverflow.com/q/51469814
tags question: http://stackoverflow.com/q/51327044
tags question: http://stackoverflow.com/q/51352515
tags question: http://stackoverflow.com/q/51336716
tags question: http://stackoverflow.com/q/51343002
tags question: http://stackoverflow.com/q/51403779
tags question: http://stackoverflow.com/q/51411314
tags question: http://stackoverflow.com/q/51340693
tags question: http://stackoverflow.com/q/51329802
tags question: http://stackoverflow.com/q/51376597
tags question: http://stackoverflow.com/q/51382099
tags question: http://stackoverflow.com/q/51379449
tags question: http://stackoverflow.com/q/51448289
tags question: http://stackoverflow.com/q/51453576
tag name: tkinter
tags question: http://stackoverflow.com/q/51332986
tags question: http://stackoverflow.com/q/51429266
tags question: http://stackoverflow.com/q/51406731
tags question: http://stackoverflow.com/q/51458657
tags question: http://stackoverflow.com/q/51470277
tags question: http://stackoverflow.com/q/51404171
tags question: http://stackoverflow.com/q/51388712
tags question: http://stackoverflow.com/q/51384898
tags question: http://stackoverflow.com/q/51371355
tags question: http://stackoverflow.com/q/51349974
tags question: http://stackoverflow.com/q/51442035
tags question: http://stackoverflow.com/q/51449044
tags question: http://stackoverflow.com/q/51463139
tags question: http://stackoverflow.com/q/51383767
tags question: http://stackoverflow.com/q/51420771
tags question: http://stackoverflow.com/q/51446419
tags question: http://stackoverflow.com/q/51399744
tags question: http://stackoverflow.com/q/51445820
tags question: http://stackoverflow.com/q/51479822
tags question: http://stackoverflow.com/q/51341050
tags question: http://stackoverflow.com/q/51434913
tags question: http://stackoverflow.com/q/51342472
tags question: http://stackoverflow.com/q/51390918
tags question: http://stackoverflow.com/q/51379934
tags question: http://stackoverflow.com/q/51392532
tags question: http://stackoverflow.com/q/51331426
tags question: http://stackoverflow.com/q/51389968
tags question: http://stackoverflow.com/q/51324740
tags question: http://stackoverflow.com/q/51354333
tags question: http://stackoverflow.com/q/51367022
tags question: http://stackoverflow.com/q/51453745
tags question: http://stackoverflow.com/q/51459932
tags question: http://stackoverflow.com/q/51391398
tags question: http://stackoverflow.com/q/51348271
tags question: http://stackoverflow.com/q/51349076
tags question: http://stackoverflow.com/q/51386979
tags question: http://stackoverflow.com/q/51326592
tags question: http://stackoverflow.com/q/51352047
tags question: http://stackoverflow.com/q/51428209
tags question: http://stackoverflow.com/q/51354280
tags question: http://stackoverflow.com/q/51329675
tags question: http://stackoverflow.com/q/51385622
tags question: http://stackoverflow.com/q/51338209
tags question: http://stackoverflow.com/q/51381932
tags question: http://stackoverflow.com/q/51351360
tags question: http://stackoverflow.com/q/51393304
tags question: http://stackoverflow.com/q/51346955
tags question: http://stackoverflow.com/q/51383095
tags question: http://stackoverflow.com/q/51389349
tags question: http://stackoverflow.com/q/51329265
tags question: http://stackoverflow.com/q/51364849
tags question: http://stackoverflow.com/q/51466921
tags question: http://stackoverflow.com/q/51467512
tags question: http://stackoverflow.com/q/51428388

http://stackoverflow.com/q/51473734
linked to: http://stackoverflow.com/q/43697311
type: Question
has comment: http://stackoverflow.com/comment/89915723
has comment: http://stackoverflow.com/comment/89916561
score: 0
tagged with: hashlib
has title: Python Hashlib Returning Different Values
type: UnansweredQuestion
tagged with: python
tagged with: sha256
duplicate of: http://stackoverflow.com/q/43697311
answer count: 0
has body: ~~SOLUTION AT END~~ I need to check the integrity of two files sent over FTP. I have everything set up except SHA256 hashes. Let me explain it from code. BLOCK_SIZE = 65536 hasher = hashlib.sha256() with open('/home/pi/' + fname, "rb") as targ: buf = targ.read(BLOCK_SIZE) while len(buf) &gt; 0: hasher.update(buf) buf = targ.read(BLOCK_SIZE) checkfile = open("osha256.txt", "w+") checkfile.write(hasher.hexdigest()) and hasher = hashlib.sha256() with open("/home/pi/" + xr, "rb") as targ: buf = targ.read(BUF_SIZE) while len(buf) &gt; 0: hasher.update(buf) buf = targ.read() hashfile = open("/home/pi/vercheck/sha256.txt", "w+") hashfile.write(str("{0}".format(hasher.hexdigest()))) First one returns hash value(?) of: c8a31cb076b21999bd2cdcfa5f446a7a6644de88037087112fa18bd90cc13984 Second one returns hash value of: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 File names and directories are same. Also md5 = hashlib.md5() with open('/home/pi/cd.jpg', "rb") as targ1: buf = targ1.read(bufsize) while len(buf) &gt; 0: md5.update(buf) buf = targ1.read(bufsize) checkfile = open("1md5.txt", "w+") checkfile.write(md5.hexdigest()) ## RETURNS e1d147695131c7682372e26a36c4f6fa with open('/home/pi/cd.jpg', "rb") as targ1: buf = targ1.read(bufsize) while len(buf) &gt; 0: md5.update(buf) buf = targ1.read(bufsize) checkfile = open("2md5.txt", "w+") checkfile.write(md5.hexdigest() ##RETURNS 3966cdd94eaf06d30c5e6f25eecb6015 EDIT You can solve this by adding (in my case) another md5 = hahslib.md5() top of with open('/home/pi/cd.jpg', "rb") as targ1: buf = targ1.read(bufsize) while len(buf) &gt; 0: md5.update(buf) buf = targ1.read(bufsize) checkfile = open("2md5.txt", "w+") checkfile.write(md5.hexdigest()
tagged with: md5
has comment: http://stackoverflow.com/comment/89915693

http://stackoverflow.com/a/51382392
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51382099
type: Answer
has body: The OptionMenu is a button with a menu attached. The menu typically grows in height until it reaches the edge of the screen. The choices are fixed, and the user can't type in their own value. A Combobox is in effect an Entry widget with a dropdown listbox. The user has the ability (if properly configured) to type into the combobox or pick from the dropdown list. The dropdown list is typically constrained to a handful of rows, with a scrollbar when the list gets to long to fit. The Combobox is also a bit easier to add and remove items after the widget has been created. The OptionMenu was designed to have a static number of items that are set when the widget is created.
score: 14
upvote count: 14
accepted answer of: http://stackoverflow.com/q/51382099

http://stackoverflow.com/comment/89784443
type: AnswerComment
comment on: http://stackoverflow.com/a/51406561
type: Comment
score: 1
has text: @SamJereriaManuel I just tried it, it works fine. You must have a space after the `+` or something.

http://stackoverflow.com/comment/89702310
score: 0
comment on: http://stackoverflow.com/q/51364892
type: Comment
type: QuestionComment
has text: The [documentation](https://docs.djangoproject.com/en/2.0/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment) specifically addresses this issue.

http://stackoverflow.com/comment/89770922
type: QuestionComment
score: 1
has text: Have a look at [find](https://ss64.com/bash/find.html#examples)
comment on: http://stackoverflow.com/q/51400077
type: Comment

http://stackoverflow.com/comment/89731088
comment on: http://stackoverflow.com/a/51363364
type: Comment
has text: This is a very fundamental issue that I can't elaborate here. I advise you start from the [Wikipedia article for serialization](https://en.wikipedia.org/wiki/Serialization) and keep on reading…
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89704955
comment on: http://stackoverflow.com/q/51366241
has text: I got something similar in rotating the plot. I would like a tool to separate both clouds or just put inside a bubble. So it can be a red bubble for red dots and blue bubble for blue dots.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51444696
favorite count: 0
has body: i have a dataset like: index id col1 col2 col3 1 1 a 2 1 b 3 1 a 4 2 a 5 2 b 6 2 a I want to filter the database so that I get the first value of duplicates "a" for each group of IDs. The remaining lines can be deleted. For example I should get: index id col1 col2 col3 1 1 a 4 2 a Can this be implemented easily?
tagged with: filter
tagged with: pandas
duplicate of: http://stackoverflow.com/q/49767227
upvote count: 2
tagged with: python
has title: Filter within groups in python pandas
has answer: http://stackoverflow.com/a/51444863
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89859481
type: Question
has comment: http://stackoverflow.com/comment/89859563
score: 2
accepted answer: http://stackoverflow.com/a/51444863
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/49767227

http://stackoverflow.com/comment/89724276
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51375678
type: Comment
has text: append will throw an error if the number of columns are different.

http://stackoverflow.com/comment/89689594
type: QuestionComment
has text: `fabric` also contains `abr`. Do you wish to match words where `crb`,`abr` and `dbr`are preceded and followed by numbers?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51358674

http://stackoverflow.com/comment/92725019
has text: Hello, I followed the Anki support and still had the error listed above. I don't really understand what you mean by: ma.py can be a sort of configure-and-load-myaddon file, and __init__.py (myaddon proper) can from . import pygame.
comment on: http://stackoverflow.com/a/52894781
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51383750
downvote count: 0
score: 1
upvote count: 1
has body: One way is to use a Window to get the count for each product and use that to filter before the groupBy(): import pyspark.sql.functions as f from pyspark.sql import Window df.withColumn('count', f.count('*').over(Window.partitionBy('product')))\ .where('count &gt; 1')\ .groupBy('id')\ .agg(f.collect_list('product').alias('items'))\ .show() #+---+---------+ #| id| items| #+---+---------+ #| 0|[5, 1, 2]| #| 1|[5, 1, 2]| #| 2| [1, 2]| #+---+---------+ Unfortunately the HAVING statement does not exist in spark-sql.
answers question: http://stackoverflow.com/q/51355803
type: Answer

http://stackoverflow.com/comment/95217899
type: QuestionComment
score: 0
has text: modelweights.h5
comment on: http://stackoverflow.com/q/51429593
type: Comment

http://stackoverflow.com/comment/89744532
type: QuestionComment
score: 0
has text: Sounds like you want a Setup, something that runs before each test?
comment on: http://stackoverflow.com/q/51384360
type: Comment

http://stackoverflow.com/comment/89841031
type: AnswerComment
comment on: http://stackoverflow.com/a/51362159
type: Comment
has text: I will try after a few days and comment here. Right now I am a bit occupied :)
score: 0

http://stackoverflow.com/comment/89686532
has text: OK now I see.. you want to add your admin model with two times for `Patient` model, right?
score: 0
comment on: http://stackoverflow.com/q/51356650
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89788637
type: Comment
comment on: http://stackoverflow.com/q/51408463
score: 0
type: QuestionComment
has text: Add two more...

variables
tags question: http://stackoverflow.com/q/51423317
tag name: variables
tags question: http://stackoverflow.com/q/51351065
tags question: http://stackoverflow.com/q/51345738
tags question: http://stackoverflow.com/q/51418416
tags question: http://stackoverflow.com/q/51327737
tags question: http://stackoverflow.com/q/51348246
tags question: http://stackoverflow.com/q/51325187
tags question: http://stackoverflow.com/q/51468808
tags question: http://stackoverflow.com/q/51383697
tags question: http://stackoverflow.com/q/51435407
type: Tag
tags question: http://stackoverflow.com/q/51477283
tags question: http://stackoverflow.com/q/51396342
tags question: http://stackoverflow.com/q/51353743

http://stackoverflow.com/comment/89847241
has text: http://www.sphinx-doc.org/en/master/templating.html#jinja-sphinx-templating-primer Do you have a `_templates` dir?
comment on: http://stackoverflow.com/q/51438493
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89860390
type: AnswerComment
comment on: http://stackoverflow.com/a/51427815
score: 0
type: Comment
has text: As a workaround, try Installing with anaconda section here, https://www.tensorflow.org/install/install_windows

http://stackoverflow.com/comment/89825141
type: Comment
comment on: http://stackoverflow.com/a/51425939
score: 1
has text: Actually, `dot` doesn't do broadcasting.
type: AnswerComment

http://stackoverflow.com/q/51343002
has answer: http://stackoverflow.com/a/51344111
has comment: http://stackoverflow.com/comment/89661342
answer count: 1
tagged with: user-interface
favorite count: 0
tagged with: tkinter
type: UnansweredQuestion
has body: I am currently building my own text editor in Tkinter, and I am struggling to understand what event and geometry propagation is and how it works. I have dug all over the internet to find a definite answer, but I have yet to find one. With that said, can someone please give me the rundown of what propagation is for events and the geometry manager? I feel like having a post focused on propagation will be beneficial to me and many other Tk/Tkinter users. Here are some specific examples of what confuses me: This method autocompletes curly braces, but why must I return "break" to have this work properly? Some other StackOverflow post (can't find it anymore) said that it stops the event from further propagating, but I do not know what this means. def _curly_pressed(self, event): self.text_field.insert(INSERT, "{}") self.text_field.mark_set(INSERT, f"{self.text_field.index(INSERT).split('.')[0]}.{int(self.text_field.index(INSERT).split('.')[1]) - 1}") return "break" Furthermore, I wanted to keep the window from resizing when the Text widget fills with text. To do this, I had to use the grid_propogate method on the Frame containing the Text widget. I do not understand this, though. self.grid_propagate(False)
tagged with: python
linked to: http://stackoverflow.com/q/11541262
score: 1
tagged with: tk-toolkit
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89661359
has title: Tkinter Event/Geometry Propagation
downvote count: 0

http://stackoverflow.com/comment/89859373
has text: @FernandoCezar hmm, not entirely sure what you mean by `the context being injected by the view`?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51362314
score: 0

http://stackoverflow.com/a/51419512
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51419229
has body: You need to instantiate WebDriverWait wait = WebDriverWait(webdriver, 5) And you can use wait object.
upvote count: 1

http://stackoverflow.com/comment/89910288
comment on: http://stackoverflow.com/a/51470980
type: AnswerComment
score: 0
has text: @abarnert thanks a lot. python -m pip install pylint==1.9.2 sloved this issue.
type: Comment

http://stackoverflow.com/q/51432323
tagged with: aws-lambda
favorite count: 0
tagged with: python-3.x
score: 6
tagged with: python
possible better answer: http://stackoverflow.com/a/51432918
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/53642148
accepted answer: http://stackoverflow.com/a/53642148
type: Question
answer count: 2
has title: Is it possible to share a piece of code betwen AWS Lambda functions?
upvote count: 6
has answer: http://stackoverflow.com/a/51432918
tagged with: amazon-web-services
has body: I am designing a serverless application with AWS Lambda. There's a piece of code on one of the functions that process the request in a certain way. I am going to make another function that's going to make the same processing with the request data, in the same way. The problem is that, if I change the processing function in one of the Lambda functions, I'm going to have to copy the function and paste it into the other Lambda function. Every time I make a change I will have to do this. This will be even more cumbersome if I want to do the same processing function in more than two Lambda functions. Is there a way to share pieces of code between Lambda functions, so I may respect DRY principles? Thanks.

package
tags question: http://stackoverflow.com/q/51478481
tag name: package
type: Tag
tags question: http://stackoverflow.com/q/51445190
tags question: http://stackoverflow.com/q/51418377
tags question: http://stackoverflow.com/q/51469451
tags question: http://stackoverflow.com/q/51437443
tags question: http://stackoverflow.com/q/51480971
tags question: http://stackoverflow.com/q/51405139
tags question: http://stackoverflow.com/q/51342007
tags question: http://stackoverflow.com/q/51434866
tags question: http://stackoverflow.com/q/51397669
tags question: http://stackoverflow.com/q/51415425
tags question: http://stackoverflow.com/q/51441521
tags question: http://stackoverflow.com/q/51445338

http://stackoverflow.com/comment/89785898
has text: @nosklo: They can't.
type: AnswerComment
score: 5
type: Comment
comment on: http://stackoverflow.com/a/51407294

http://stackoverflow.com/q/51452376
tagged with: anaconda
accepted answer: http://stackoverflow.com/a/51452490
answer count: 1
score: 0
has title: Jupyter Notebook can't create or open a file after remove extension
tagged with: python
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/51452490
has body: After I tried to add and remove an extension in Jupyter Notebook, I can't open or create a new python document anymore. the browser shows: "500 : Internal Server Error" terminal shows (quite long, I only copied part of it which indicates an error): ... [E 09:58:34.030 NotebookApp] Uncaught exception GET /notebooks/Untitled.ipynb?kernel_name=python3 (::1) HTTPServerRequest(protocol='http', host='localhost:8888', method='GET', uri='/notebooks/Untitled.ipynb?kernel_name=python3', version='HTTP/1.1', remote_ip='::1', headers={'Host': 'localhost:8888', 'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1', 'Dnt': '1', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Referer': 'http://localhost:8888/tree', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'en-US,en;q=0.9,en-GB;q=0.8', 'Cookie': '_xsrf=2|12adb47b|ce5fc3408dfb4c6ebe2db7346ab98bc7|1531888190; username-localhost-8892="2|1:0|10:1532062480|23:username-localhost-8892|44:NGIzZGQ3NmE4ZjM5NDMwZGIzNDhjODE5YWZmZTVhZmM=|2c000d68aefed941bf2c3bd53b3a927841c76c428a6a1eccd36a44fdaaec6f62"; username-localhost-8891="2|1:0|10:1532092613|23:username-localhost-8891|44:NGY3NDBlMTY3NmI3NDIzMzk0NGViMDA3ODgzOTdlNjM=|39b21d7e732e7717eab69f4ecedcc8365517ef21149a2739b49f977d24a29bb1"; username-localhost-8889="2|1:0|10:1532100753|23:username-localhost-8889|44:ZjYyOWI1ZGU3MTU5NDIyN2E4MmI5NjM2NDYzN2RiMjA=|6c086a8f55ac67abe92024058427b7fee35745cb74f5e7bf4a4926a406ff385f"; username-localhost-8890="2|1:0|10:1532101756|23:username-localhost-8890|44:MGZiZmZiMzZhZTcxNDY3Nzk0ZDFlYWYyZDYzMmIyM2U=|ce0e258c16d103508162befbe45b6279175704d8c04c7b7e00c1b6acdfa3f9de"; username-localhost-8888="2|1:0|10:1532138291|23:username-localhost-8888|44:NzJjMjJmYjk0NDhhNDNiOTkwYjU3YzNiNjNjYmMwMjE=|10c0445e0da773f487bd55e82a12c0207d8e44e08e5ead02075ac3686c431599…
type: Question
type: AnsweredQuestion

http://stackoverflow.com/q/51344368
accepted answer: http://stackoverflow.com/a/51828807
type: Question
upvote count: 2
tagged with: apriori
answer count: 1
tagged with: data-science
has title: "RelationRecord object of apyori module" apriori algorithm python
tagged with: python
favorite count: 0
has body: Excuse me for my english, I'm trying to recognize properties that come up frequently in a set of data to deduce a categorization using the apyori package of python. i'm practicing on a dataframe of 20772 transactions and the largest transaction is 543 items. DataFrame I converted this DataFrame into a list : liste = df.astype(str).values.tolist() I got this list list I used the apriori function of the library apyori to generate the association rules: from apyori import apriori rules = apriori(liste, min_support= 0.01, min_confidence= 0.2) to display the result I converted the rules variable to a list : MB = list(rules) The problem is that instead of showing me the rules but it shows the RelationRecord "RelationRecord object of apyori module". like here result
score: 2
downvote count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51828807

http://stackoverflow.com/q/51400933
score: 0
has comment: http://stackoverflow.com/comment/89773669
tagged with: python
has title: Python Srceenshot with PhantomJS in Kali
answer count: 0
has body: I want to take a screenshot with Selenium PhantomJS, as the Chrome and Firefox --headless options are much slower. Here is my code for it: import selenium from selenium import webdriver driver = webdriver.PhantomJS() driver.get('https://www.google.com') driver.set_window_size(1920, 1080) driver.save_screenshot('screenshot.png') driver.quit() The .png file this creates is 0 bytes, which is thus useless. The following code on the other hand works just fine, although much slower, as the --headless option for Chrome opens and closes the browser. import selenium from selenium import webdriver options = webdriver.ChromeOptions() options.add_argument('--headless') driver = webdriver.Chrome(chrome_options = options, executable_path = r'C:\Users\a\Selenium\chromedriver.exe') driver.get('https://www.google.com') driver.set_window_size(1920, 1080) driver.save_screenshot('screenshot.png')
type: UnansweredQuestion
tagged with: webpage-screenshot
type: Question
tagged with: phantomjs
has comment: http://stackoverflow.com/comment/89772430

http://stackoverflow.com/comment/89712812
type: Comment
has text: Nvm, that error was my fault. I accidentally named a list 'list' earlier in my script which reassigned the predefined variable.
comment on: http://stackoverflow.com/a/51369198
score: 0
type: AnswerComment

http://stackoverflow.com/q/51440934
score: 0
has body: I'm developing a package and would like to test it locally. I found pip install -e ./ and it has been working well. However, I'm trying to set up console_scripts entry points with my setup.py and they are not working. The Windows CMD gives a standar message: 'script' is not recognized as an internal or external command, operable program or batch file. To - my - knowledge, those console scripts should register themselves as pure command line tools. Even on Windows an .exe file should be created. I made a minimal case with a script.py with a setup.py. After running pip install -e ./ the module was installed correctly, but again the function I registered was not there. Is there anything I'm missing? Edit: files # setup.py import setuptools setuptools.setup( name='script', entry_points={ 'console_scipts': [ 'test_entry = script:func' ] } ) # script.py def func(): print('Hello World :(') # And command line call: test_entry Edit II: Running python setup.py develop doesn't work. Neither does pip install ./... I'm beginning to get confused.
tagged with: python
has answer: http://stackoverflow.com/a/51445311
type: AnsweredQuestion
tagged with: setuptools
has title: Console script entry point not accessible with pip -e and windows
type: Question
answer count: 1
accepted answer: http://stackoverflow.com/a/51445311

http://stackoverflow.com/comment/89862805
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51445874
has text: Your code does not run. It says: os.utime(rows, (modTime, modTime)) FileNotFoundError: [Errno 2] No such file or directory. Does this code run for you?
score: 0

http://stackoverflow.com/comment/89717922
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51373030
type: AnswerComment
has text: OK I've implemented what you wrote up (thank you!). It executes without issue. I'm not clear on why I need negative texts as well (texts that are not abuse related). I'm attempting to label texts with a classification of what kind of abuse they are but not if they are abuse related or not. If the text has phishing related or malware related they should be labeled differently. Examples would be ['Malicious Code/Traffic__Aaeh', 'Malicious Code/Traffic__Phishing', 'Vulnerabilities__Software Version', ...]

http://stackoverflow.com/q/51473643
has answer: http://stackoverflow.com/a/51473729
tagged with: python-3.x
tagged with: protocol-buffers
type: Question
has comment: http://stackoverflow.com/comment/89915658
tagged with: python
answer count: 1
score: 0
has body: I started to learn Tensorflow from a tutorial and this is the first time I deal with Google's Protobuf. I'am stuck at protobuf compilation step. I've downloaded Tensorflow models and protoc-3.4.0-win32 Now I have to run compilation command from a terminal however an error occurs: 1) cd C:\TensorFlow\models\research 2) “C:\protoc-3.4.0-win32\bin\protoc.exe” object_detection/protos/*.proto --python_out=. As a result I have an error: "The filename, directory name, or volume label syntax is incorrect" I have no idea why this error occurs and how to fix it. May be I missed something or I should set some special enviroment configs, i.d.k. I use Win7 x64, Python 3.6.6 Any advice will be appreciated!
tagged with: tensorflow
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89916165
has title: Compile protobuf for python on Win7 issue

http://stackoverflow.com/q/51468677
has body: import datetime as dt import matplotlib.pyplot as plt from matplotlib import style import pandas as pd import pandas_datareader.data as web start = dt.datetime (2000,1,1) end = dt.datetime (2018,1,1) df=web.DataReader('TSLA', 'morningstar', start, end) print(df.head()) Trying to use the above code, but I get the error: File "/anaconda3/lib/python3.6/site-packages/pandas_datareader/compat/__init__.py", line 8, in &lt;module&gt; import pandas.io.common as com AttributeError: module 'pandas.io' has no attribute 'common'
tagged with: pandas
downvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 1
has title: AttributeError: module 'pandas.io' has no attribute 'common'
has answer: http://stackoverflow.com/a/51469429
tagged with: pandas-datareader
upvote count: 1
type: Question

http://stackoverflow.com/comment/89762592
has text: What is the Python version?
comment on: http://stackoverflow.com/q/51395590
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51414856
has body: In a Google Colab notebook, I am running a block of code which will take several hours to complete, and at the end a file will be uploaded to my Google drive. The issue is that sometimes my credentials will expire before the code can upload the file. I have looked around and may have found some code that can perhaps refresh my credentials but I am not 100% familiar with the how Pydrive works and what exactly this code is doing. Here is the code I am using so far to set my notebook up to access my Google Drive. !pip install -U -q PyDrive from google.colab import files from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from google.colab import auth from oauth2client.client import GoogleCredentials auth.authenticate_user() gauth = GoogleAuth() gauth.credentials = GoogleCredentials.get_application_default() drive = GoogleDrive(gauth) And this the code I use to upload the file uploadModel = drive.CreateFile() uploadModel.SetContentFile('filename.file') uploadModel.Upload() This is the code I found which may solve my issue (found here PyDrive guath.Refresh() and Refresh Token Issues ) if gauth.credentials is None: # Authenticate if they're not there gauth.LocalWebserverAuth() elif gauth.access_token_expired: # Refresh them if expired print "Google Drive Token Expired, Refreshing" gauth.Refresh() else: # Initialize the saved creds gauth.Authorize() # Save the current credentials to a file gauth.SaveCredentialsFile("GoogleDriveCredentials.txt") So I am guessing the gauth.Refresh() line prevents my credentials from expiring?
has answer: http://stackoverflow.com/a/51416760
answer count: 1
downvote count: 0
has title: Pydrive: Preventing Google Drive Authorization from expiring.
favorite count: 0
tagged with: pydrive
tagged with: python
linked to: http://stackoverflow.com/q/32863213
upvote count: 6
tagged with: google-drive-api
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51416760
score: 6
type: Question
tagged with: google-oauth

http://stackoverflow.com/q/51464415
type: Question
has comment: http://stackoverflow.com/comment/89897640
downvote count: 0
has comment: http://stackoverflow.com/comment/89897695
has comment: http://stackoverflow.com/comment/89897714
has title: Mutation attempt of immutable types in for loop doesn't raise SyntaxError?
linked to: http://stackoverflow.com/q/44864393
favorite count: 0
has comment: http://stackoverflow.com/comment/89897657
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89897619
has body: Consider the following code. a = [1, 2, 3] for i in a: i *= 2 a #[1, 2, 3] As I understand it, inplace operators like *= attempt to mutate the element via __iadd()__. Assuming type(i) == &lt;class 'int'&gt; as it goes through the loop, shouldn't the for loop in this example then raise a SyntaxError? (for trying to mutate immutable integers from the list?) Why doesn't it neither change the list elements nor raise an error?
duplicate of: http://stackoverflow.com/q/44864393
upvote count: 1
tagged with: python
tagged with: list
answer count: 0
score: 1

http://stackoverflow.com/a/51374781
answers question: http://stackoverflow.com/q/51374539
score: 6
upvote count: 7
downvote count: 1
has body: Matplotlib's pyplot is the library that Pandas use in their plot function. Pandas' plot is only a convenient shortcut. For the bar chart question: I would suggest using Seaborn's barplot, using the desired category as hue. If you wish to only use Pandas, then maybe something like: df = pd.DataFrame(np.random.rand(10, 1), columns=['col_name']) df['category'] = df.col_name&gt;0.5 print(df) col_name category 0 0.053908 False 1 0.136295 False 2 0.325790 False 3 0.362942 False 4 0.919924 True 5 0.406884 False 6 0.433959 False 7 0.725699 True 8 0.582537 True 9 0.608040 True df.groupby('category').count().plot(kind='bar', legend=False)
type: Answer

http://stackoverflow.com/a/51389726
score: 0
answers question: http://stackoverflow.com/q/51388952
type: Answer
has comment: http://stackoverflow.com/comment/89788982
has comment: http://stackoverflow.com/comment/89784209
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51388952
has body: I am not sure how to do this with gspread, but you can modify you code very easily and use pygsheets and it allows to update a column all at once. Also, I am not sure what your data looks like so the below may need to be altered or you may need to alter your data set a little. Hope this helps. import pygsheets gc = pygsheets.authorize(service_file = 'client_secret2.json') # Open spreadsheet and select worksheet sh = gc.open('Api_Test') wks = sh.sheet1 #update Column notes = [1,2,3,4] #this is the dataset to getupdated in the column wks.update_col(4, notes, 1)# 4 is the number of column, notes is the dataset to update, 1 skips the first row (I used a header)

http://stackoverflow.com/comment/89757700
score: 0
type: AnswerComment
type: Comment
has text: Please post this as a new question since it is hard to read your code in comments.
comment on: http://stackoverflow.com/a/51392683

http://stackoverflow.com/comment/89758387
type: Comment
type: QuestionComment
has text: I copy the first 5 observations of the county dataset (which is large) to another dataframe for test. When I add .copy(), I don't see the error any more. However, I have a new error: geopy.exc.GeocoderTimedOut: Service timed out. Do you know the reason?
comment on: http://stackoverflow.com/q/51393049
score: 0

http://stackoverflow.com/comment/89939336
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51484409
has text: I'm afraid that I lack the proper syntax in my Python dictionary if I may phraze it that way. I'm overthinking the problem, making it impossible in my head, while in reality it probably is as simple as it can be. Would you mind pointing me in the right direction? For example, if the method I chose, with lists, is right for this task? Or is the `del pplList[::i]` the only one you would change? EDIT: oh, I posted after your second comment
score: 0

http://stackoverflow.com/q/51388373
answer count: 0
type: Question
has body: I am struggling with a situation regarding retrieving dataframe column. Say I have a DataFrame with one Column only. df_Returns = pd.DataFrame(data = monthly_returns_array, columns = ['spx index']) Now lets say, col = df_Returns.columns temp1 = df_Returns[col] temp2 = df_Returns['spx index'] In my example above temp1 is being retrieved as DataFrame while temp2 is a series. Why is there this inconstancy? My situation is that columns name in an original dataframe could be anything, so i would like to retrieves columns from another dataframe (with same column names as original) based on a loop on a variable rather than direct text. I can convert the retrieved column from DataFrame to then Series, but I am just puzzled at this behavior. Truly appreciate your help.
has comment: http://stackoverflow.com/comment/89748759
tagged with: dataframe
score: 0
has comment: http://stackoverflow.com/comment/89749773
has comment: http://stackoverflow.com/comment/89748814
has title: Extracting Python DataFrame Column - Series vs DataFrame Retrieval
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/56444721
answers question: http://stackoverflow.com/q/51468533
has body: In my case issue was related with missing dll in the os, related with multimedia part of windows server essentials, as per https://jakubmertl.com/blog/python-import-cv2-error
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/89707675
comment on: http://stackoverflow.com/a/51367646
has text: @C4W not sure, but at least you definitely know you're converting the values they give you correctly!
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51398549
upvote count: 0
has title: read.index( ) appears to be reading the wrong index?
type: Question
type: AnsweredQuestion
score: -1
has body: So I've spent a couple of days on this and I can't figure out the answer. But I've stripped the problem down to the simplest form (I think). I'm trying to find two different strings in a file, and read the section of the file between them. Right now I have a tester file with literally just 1 2 3 4 5 6 7 8 9, etc in it. I'm running this code: with open('Testing.txt', 'r') as file: read = file.read() if "4" in read: begin = read.index("4") print begin if "8" in read: end = read.index("8") file.seek(begin) print "The location to begin reading is", file.tell() data= file.read()[begin:end] print "data =", data If I start at 1, the code works properly. If I start somewhere above 2, it pulls numbers way farther down the list than it should. I'm sort of at a loss for why this is happening. I hope I'm making sense!
answer count: 1
downvote count: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51398664
accepted answer: http://stackoverflow.com/a/51398664

http://stackoverflow.com/comment/89677307
score: 0
type: AnswerComment
has text: Do you check what is being passed into that field when the post is being processed?
type: Comment
comment on: http://stackoverflow.com/a/51342742

http://stackoverflow.com/a/51395706
accepted answer of: http://stackoverflow.com/q/51395324
has comment: http://stackoverflow.com/comment/89763994
type: Answer
answers question: http://stackoverflow.com/q/51395324
has body: In order to have only one function you could use this: def folder_diff(): folder1 = os.listdir(PATH1) # folder containing your files folder2 = os.listdir(PATH2) # the other folder for item1 in folder1: for item2 in folder2: if(item1==item2): res = filecmp.cmp(PATH1+item1, PATH2+item2) if __name__ == "__main__": import os import filecmp PATH1 = '' PATH2 = '' data = folder_diff() print(data)
has comment: http://stackoverflow.com/comment/89763318
upvote count: 2
has comment: http://stackoverflow.com/comment/89763964
score: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89763933

http://stackoverflow.com/q/51405932
has answer: http://stackoverflow.com/a/51406307
has title: What is "AttributeError: 'str' object has no attribute 'native_events_enabled" error? it appears when using selenium with python
type: Question
tagged with: python-2.7
answer count: 2
tagged with: firefox
has body: Here my requirement is, have to log in one web page using the below-mentioned block of code. using 2.7.13, selenium 2.45.0, Windows 10. class WebJIRA: driverpath = "path\to\geckodriver.exe" driver = webdriver.Firefox(driverpath) ConfigRead.defaultvalues() def login_page(self,username): WebJIRA.webdriver.get(jirausername) main = WebJIRA() main.login_jira() but it throws below error. File "C:\Python27\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 46, in __init__ self.NATIVE_EVENTS_ALLOWED and self.profile.native_events_enabled) AttributeError: 'str' object has no attribute 'native_events_enabled' Can anyone please help me to get through this one. I'm new to python. this question explains how to deal with firefoxprofile when it has been passing as 'str', in my case I have to pass a variable(which contains geckodriver path) but both errors are same.
has comment: http://stackoverflow.com/comment/89783038
score: 0
tagged with: geckodriver
linked to: http://stackoverflow.com/q/48307531
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51410504
tagged with: selenium

http://stackoverflow.com/q/51328575
has title: Simple classification in TensorFlow
has answer: http://stackoverflow.com/a/51329255
has body: I have the following problem: I have a raspberry pi robot which uses four sensors (left, front, right, back). The robot can do the following moves: Run forward, turn left, turn right, move back. Based on the sensor data, i will "train" the robot to do the moves. So a basic input to train the robot will look like: if sensor data = [2, 1, 0, 1] => move left if sensor data = [4, 0, 1,1] => move left if sensor data = [0, 2, 0, 0] => move forward if sensor data = [0, 0, 0, 1] => move backward .. feed more data here .. Now after the training the robot should be possible to predict the next move like: if sensor data = [3, 3, 2, 1] => do predicted move. My first idea was to use TensorFlow to solve this problem, but I couldn't find out what the best way would be to implement this (kind of simple) prediction algorhitm since most of the tutorials are about image and speech recognition. It would be really great if someone could show me a short example in Python on how this could be done using TensorFlow. So the main question is: How can I implement a algorithm which takes a list of arrays with four values as input and then predicts the given output (one variable which can have four states). Solution: I managed to find a solution (it uses Python 3 with TensorFlow and Pandas): import tensorflow as tf import pandas as pd # Path to the directory where model data should be saved. MODEL_PATH = "model" # Path to the training data file. TRAIN_DATA_PATH = "movement_training_data.csv" # The csv column names CSV_COLUMN_NAMES = ['Front', 'Back', 'Left', 'Right', 'Move'] # The moves (results) of the estimation MOVES = ['Forward', 'Back', 'Left', 'Right'] # Defines the batch size of data taken for each training step. batch_size = 100 # Defines how many training steps should be done. # Weights and biases wll be adjusted after each step. train_steps = 1000 def main(argv): # Reads the csv data and assigns column names. The first line is the header line. train_data = pd.read_csv(TRAIN_DATA_PATH,…
score: 1
accepted answer: http://stackoverflow.com/a/51329255
upvote count: 1
tagged with: machine-learning
tagged with: tensorflow
type: AnsweredQuestion
tagged with: algorithm
tagged with: math
has comment: http://stackoverflow.com/comment/89632949
type: Question
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89633035
favorite count: 0
tagged with: python

http://stackoverflow.com/q/51439271
has title: Convert 1d array to lower triangular matrix
favorite count: 0
tagged with: python-3.x
tagged with: python
has body: I would like to convert a 1 dimensional array into a lower, zero diagonal matrix while keeping all the digits. I am aware of numpy.tril function, but it replaces some of the elements with zeros. I need to expand the matrix to contain all the original digits. For example: [10,20,40,46,33,14,12,46,52,30,59,18,11,22,30,2,11,58,22,72,12] Should be 0 10 0 20 40 0 46 33 14 0 12 46 52 30 0 59 18 11 22 30 0 2 11 58 22 72 12 0
accepted answer: http://stackoverflow.com/a/51439529
upvote count: 13
type: AnsweredQuestion
score: 13
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/46041811
has answer: http://stackoverflow.com/a/51442965
possible better answer: http://stackoverflow.com/a/51439629
has answer: http://stackoverflow.com/a/51439529
answer count: 3
has answer: http://stackoverflow.com/a/51439629
downvote count: 0

http://stackoverflow.com/comment/89883356
score: 2
has text: I am not sure what you mean?
type: AnswerComment
comment on: http://stackoverflow.com/a/51456827
type: Comment

http://stackoverflow.com/a/51402389
answers question: http://stackoverflow.com/q/51392167
has comment: http://stackoverflow.com/comment/89781343
accepted answer of: http://stackoverflow.com/q/51392167
score: 1
has comment: http://stackoverflow.com/comment/89776622
upvote count: 1
has comment: http://stackoverflow.com/comment/89779936
type: AcceptedAnswer
downvote count: 0
has body: When you add the item to the scene, Qt takes ownership of it, so you don't need to keep an explicit reference to it on the Python side. This means that when the scene is deleted, the C++ part of the item will be deleted as well - and if there are no other references held to the Python part, it will also be garbage-collected (so there will be nothing left). When you remove the item from the scene, ownership passes back to the caller, who now has full responsiblity for deleting it. If QGraphicsRectItem inherited QObject, you could call deleteLater() to delete the C++ part - but this would still leave you with the empty Python wrapper, so it wouldn't really make much difference. The way to delete a PyQt wrapper is the same as for any other python object - i.e. use del, or simply let it go out of scope and allow it to be garbage-collected in the normal way. There is no special PyQt way to delete such objects, because nothing special is needed. In your example, you never actually make any attempt to delete the item, so the information reported by sip is entirely as expected. Finally, note that it is always possible to delete the C++ part independently of the PyQt wrapper. If you do this, and then attempt to access the item's methods, you will get a RuntimeError: &gt;&gt;&gt; scene = QGraphicsScene() &gt;&gt;&gt; node = QGraphicsRectItem() &gt;&gt;&gt; scene.addItem(node) &gt;&gt;&gt; del scene &gt;&gt;&gt; node.rect() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; RuntimeError: wrapped C/C++ object of type QGraphicsRectItem has been deleted UPDATE: Below is a demo that shows how the item is garbage-collected when it is removed from the scene and allowed to go out of scope. Of course, if there are any references held to the item elsewhere (i.e. if ref-count > 1), the item will not be deleted. import sip, gc from PyQt5 import QtCore, QtWidgets app = QtWidgets.QApplication(['test']) scene = QtWidgets.QGraphicsScene() def test(): node = Qt…
type: Answer

http://stackoverflow.com/a/51432092
answers question: http://stackoverflow.com/q/51431974
score: -1
downvote count: 1
has comment: http://stackoverflow.com/comment/89864796
has body: data = [x for x in json_data if not x['ACTION'] == 'REMOVE'] another way to get a new list with only the desired items.
type: Answer
has comment: http://stackoverflow.com/comment/89857919
upvote count: 0

http://stackoverflow.com/a/51383869
downvote count: 0
type: Answer
has body: I believe I found an approach that will work using the chunksize argument of pd.read_csv. for batch in pd.read_csv('training_data.csv', chunksize=50): # transform/reshape batch #model.train_on_batch(batch, y) next This reads 1,000 batches of size 50 in about 3.86 seconds, and allows me to use the train_on_batch method. I still need to find a better way to read the y data, but I think I may look into storing both X and y in a single csv and using chunksize.
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51369763
score: 1
answers question: http://stackoverflow.com/q/51369763
type: AcceptedAnswer

http://stackoverflow.com/a/51346076
accepted answer of: http://stackoverflow.com/q/51345910
has body: As said by PRMoureu in the comments above, I needed to run wb.save('my.xlsx') after I made my changes to the file
type: Answer
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/51345910
type: AcceptedAnswer

http://stackoverflow.com/comment/89719395
type: AnswerComment
comment on: http://stackoverflow.com/a/51373925
has text: Working. Using .loc is prefereable when filtering rows?
type: Comment
score: 1

http://stackoverflow.com/comment/89867209
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51448289
has text: Place gives you complete control. You can put them anywhere you want. Just do a little math on the coordinates.
score: 0

http://stackoverflow.com/q/51408552
linked to: http://stackoverflow.com/q/5963269
answer count: 2
tagged with: equation
has body: I'm trying to compute a recursive equation on the rows of dataframe with some arguments provided by different other datframes. The equation is provided below and should be performed for each columns of the matrix. It looks like an exponential moving average, except the decay is not constant and given from another dataframe. Given: a matrix Alpha of the same size as the output a matrix P of the same size as the output a vector M0 of the same width as the output I did a first try with a double loop (with .iloc): import pandas as pd import numpy as np """ Assuming inputs: - Matrix P of size 1000x4 - Matrix alpha of size 1000x4 - Vector M0 of size 1X4 """ # input variables height = 1000 width = 4 np.random.seed(1) P = pd.DataFrame(np.random.normal(loc=170, scale=12, size=(height, width)), index=range(height), columns=range(width)) np.random.seed(1) alpha = pd.DataFrame(np.random.normal(loc=0.04, scale=0.04, size=(height, width)), index=range(height), columns=range(width)) np.random.seed(1) M0 = pd.DataFrame(np.random.normal(loc=170, scale=12, size=(height, width)), columns=range(width)) # Output table MA = P.copy()*0 MA.iloc[0] = M0 # Recursive equation for x in range(width): for y in range(1, height): MA.iloc[y][x] = alpha.iloc[y][x]*P.iloc[y][x] + (1-alpha.iloc)* MA.iloc[y-1][x] and a second try with vectorization by expanding the probleme into a cumulative prod (see equation below) but failed to retrieve the values expected (code will be updated later): I could rework my math. However I was wondering if there was any more efficient/simple way to do it as it takes a while. Thank you for any help ! Update 1: Few comments: My original dataframe is a price matrix for different assets (columns) and rows are days ascending downards (past at the top, present at the bottom) From there, my intital moving average day depends on a function depending on the asset returning me the initial window. Thus, the algorithm is not column-symetric -My strategy is to loop over the columns,…
has comment: http://stackoverflow.com/comment/89829360
has comment: http://stackoverflow.com/comment/89791305
tagged with: recursion
has comment: http://stackoverflow.com/comment/89788652
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51411196
score: 2
has comment: http://stackoverflow.com/comment/89827932
downvote count: 0
has answer: http://stackoverflow.com/a/51412800
has title: Python - sequential loop with dataframe
favorite count: 0
tagged with: sequential
has comment: http://stackoverflow.com/comment/89790209
tagged with: moving-average
type: Question
tagged with: python
upvote count: 2

http://stackoverflow.com/q/51456343
score: 2
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/89900490
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/89921420
has comment: http://stackoverflow.com/comment/89957737
has comment: http://stackoverflow.com/comment/89938803
downvote count: 0
has comment: http://stackoverflow.com/comment/89883152
favorite count: 0
tagged with: cx-freeze
has title: Convert .py to .exe including matplotlib code
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/89902326
tagged with: pyinstaller
type: UnansweredQuestion
tagged with: python
has body: I am trying to convert this code: import pandas as pd import matplotlib.pyplot as plt import readTrc path = 'C:/filepath/data.trc' datX, datY, m = readTrc.readTrc(path) srx, sry = pd.Series(datX * 1000), pd.Series(datY * 1000) df = pd.concat([srx, sry], axis = 1) df.set_index(0, inplace = True) df.plot(grid = 1, linewidth = 0.5, figsize = (9,5), legend = False, xlim = (df.index[0] , df.index[-1]), xticks = [-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9]) plt.xlabel('Zeit in ms') plt.ylabel('Spannung in mV') plt.savefig('test.png', dpi = 600) into an executable with cx_Freeze. Setup.py : import cx_Freeze import sys import matplotlib base = None if sys.platform == "win32": base = "Win32GUI" executables = [ cx_Freeze.Executable("read_trc.py", base = base), ] build_exe_options = {"includes":["matplotlib.backends.backend_tkagg"], "include_files":[(matplotlib.get_data_path(), "mpl-data"), ('C:/filepath', 'data.trc')], "excludes":[], } cx_Freeze.setup( name = "script", options = {"build_exe": build_exe_options}, version = "0.0", description = "A basic example", executables = executables) The conversion works but when I try to run the .exe I get this error: Is there a way to make this work? I am using Python 3.6 on Windows 10. I have already tried the fixes found on Stackoverflow regarding Numpy import errors but it does not seem to help. Edit: Thanks to comments I solved the Error. Unfortunately now I get another Error when I try to execute the converted file: Edit2: I tried to include tkinter in my code but it doesn't work. I have a standard python 3.6 distribution installed which should include tkinter. tkinter.test() works. I assume that there is something wrong with the tkinter.ddls import. How would I do that correctly? import cx_Freeze import sys import os import matplotlib os.environ['TCL_LIBRARY'] = r"C:\Users\Artur\AppData\Local\Programs\Python\Python36\DLLs\tcl86t.dll" os.environ['TK_LIBRARY'] = r"C:\Users\Artur\AppData\Local\Programs\Python\Python36\DLLs\tk86t.…

http://stackoverflow.com/comment/89864343
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51446568
has text: @pault, attached output from both runs above

http://stackoverflow.com/q/51348028
tagged with: flask
has body: I'm fairly new to Python and indeed I will have to invest more time in learning it. As for now I'm creating a portfolio using Python, Jinja2, Flask and SASS. Generally, I'm following CS50 tutorial at the moment and am modifying their code to suit my needs. I don't fully understand their syntax, but my familiarity with functions plus reading of a documentation helped me in creating first, cool function: it takes my local time and depending on an hour it greets you appropriately (insertion into html via jinja2). I want now to create an unordered list by applying via jinja2 elements of an array. Here is a complete code of my .py: from flask import Flask, render_template, flash, redirect, request, url_for from datetime import datetime app = Flask(__name__) @app.route("/") def index(): time = datetime.now().time() if time.hour > (0) and time.hour < (12): headline1 = "Good morning, !" return render_template("index.html", headline1=headline1) elif time.hour >= (12) and time.hour < (18): headline2 = "Good afternoon, !" return render_template("index.html", headline2=headline2) else: headline3 = "Good evening, !" return render_template("index.html", headline3=headline3) def nav(): names = ["Home", "About me", "Projects", "Hobby"] return render_template("index.html", names=names) And HTML with Jinja2: {% if headline1 %} {{ headline1 }} {% elif headline2 %} {{ headline2 }} {% else %} {{ headline3 }} {% endif %} {% for name in names %} {{ name }} {% endfor %} Whichever function is first, it is the only working function. Whichever I'm putting as the second, it gets discarded. Sorry if this is a noob's question, but what I'm doing wrong? Both functions are legit, but it seems that there is a problem of one function canceling out the other one. I know I have much to learn, but your answer will help me greatly in the process. Thanks in advance!
accepted answer: http://stackoverflow.com/a/51348257
favorite count: 0
has title: One python function canceling out other
downvote count: 2
tagged with: python
tagged with: jinja2
type: AnsweredQuestion
score: -2
type: Question
has answer: http://stackoverflow.com/a/51348257
upvote count: 0
answer count: 1

http://stackoverflow.com/comment/89656473
type: Comment
has text: Thank you, I removed the commas highlighted and it has worked
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51341051

http://stackoverflow.com/q/51343713
has comment: http://stackoverflow.com/comment/89672503
type: Question
tagged with: automation
tagged with: cloud
has comment: http://stackoverflow.com/comment/89668075
has body: Like if the script I uploaded to AWS has pyautogui.moveTo(0,0) Can it move the mouse of multiple computers at the same time or no? Thanks!
tagged with: amazon-web-services
has answer: http://stackoverflow.com/a/51411719
tagged with: user-interface
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89661401
upvote count: 2
type: UnansweredQuestion
has title: If I plan to run a python script that uses pyautogui can it do multiple computers at once or only one?
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/89662284

http://stackoverflow.com/a/51342586
has body: You can use !setup.py install to do that. Colab is just like a Jupyter notebook. Therefore, we can use the ! operator here to install any package in Colab. What ! actually does is, it tells the notebook cell that this line is not a Python code, its a command line script. So, to run any command line script in Colab, just add a ! preceding the line. For example: !pip install tensorflow. This will treat that line (here pip install tensorflow) as a command prompt line and not some Python code. However, if you do this without adding the ! preceding the line, it'll throw up an error saying "invalid syntax". But keep in mind that you'll have to upload the setup.py file to your drive before doing this (preferably into the same folder where your notebook is).
upvote count: 172
downvote count: 7
answers question: http://stackoverflow.com/q/51342408
score: 165
has comment: http://stackoverflow.com/comment/116987052
type: Answer
has comment: http://stackoverflow.com/comment/103583381
has comment: http://stackoverflow.com/comment/140244238
has comment: http://stackoverflow.com/comment/100568347
has comment: http://stackoverflow.com/comment/116887392
has comment: http://stackoverflow.com/comment/98523063

http://stackoverflow.com/comment/89683462
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51355407
type: Comment
has text: @user3483203 right, I'm fixing it asap, sorry. If possible, would you explain me how this can become a wiki? I never wrote one. Also, this was thought as an answer comparison, helpful to discern which of the answers was best.

http://stackoverflow.com/a/51410717
has comment: http://stackoverflow.com/comment/89793325
answers question: http://stackoverflow.com/q/51410594
has comment: http://stackoverflow.com/comment/89792924
score: 0
has comment: http://stackoverflow.com/comment/89793471
has comment: http://stackoverflow.com/comment/89793403
has body: On raspbian you have to be careful when using external drives. Have you edited the file /etc/fstab? This is necessary to mount the drive also correctly after restarts and when the file is temporarily disconnected and then connected again. If you did this correctly, then the drive will have the permissions you gave it when mounting and Django should be able to access it/write to it. BR
type: Answer

http://stackoverflow.com/q/51467973
has comment: http://stackoverflow.com/comment/90058034
answer count: 0
type: UnansweredQuestion
tagged with: python
tagged with: nosql
tagged with: performance
downvote count: 0
score: 1
type: Question
has comment: http://stackoverflow.com/comment/90074720
has title: Fastest way to get the results in a big DB using python API - Elasticsearch
has body: I am trying to read around 1 million documents. I am using the Scan API, but it takes around 30 seconds which is too slow for me. Is there a faster way? The query I am using is a standard match_all query. In addition, the max result window is 1000000.
upvote count: 1
has comment: http://stackoverflow.com/comment/89981541
tagged with: elasticsearch
favorite count: 0

http://stackoverflow.com/a/63287928
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51436498
downvote count: 0
score: 1
has body: With some inspiration from this answer, you could do this if you just need to go two pages back: return HttpResponse(' ') Keep in mind that this won't reload the page.

http://stackoverflow.com/comment/89783649
comment on: http://stackoverflow.com/q/51406294
score: 1
type: QuestionComment
type: Comment
has text: haha: `cmd =('GET ' + user_url + ' HTTP/1.0\n\n').encode()`

http://stackoverflow.com/q/51417267
tagged with: python-3.x
upvote count: 1
tagged with: python
tagged with: virtualbox
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51418725
has body: I'm trying to make objects from the Angryball class randomly spawn from the right border and move from right to left outside the screen. The idea is that these ogjects must spawn on random y coordinates from the window's right border (better if i can make them seem like if they were coming from outside the border, but that's another point i will check later) and then move at speed 5 until the reach the opposite border. Once one object gets out, another one is spawned again. I don't have any error when i run this but it doesn't work as expected :) Can you help me figuring this out? import pygame import os import random size = width, height = 750, 422 screen = pygame.display.set_mode(size) img_path = os.path.join(os.getcwd()) background_image = pygame.image.load('background.jpg').convert() bg_image_rect = background_image.get_rect() pygame.mixer.pre_init(44100, 16, 2, 4096) pygame.display.set_caption("BallGame") class Ball(object): def __init__(self): self.image = pygame.image.load("ball.png") self.image_rect = self.image.get_rect() self.image_rect.x self.image_rect.y self.facing = 'LEFT' def handle_keys(self): key = pygame.key.get_pressed() dist = 5 if key[pygame.K_DOWN] and self.image_rect.y &lt; 321: self.facing = 'DOWN' self.image_rect.y += dist elif key[pygame.K_UP] and self.image_rect.y &gt; 0: self.facing = 'UP' self.image_rect.y -= dist if key[pygame.K_RIGHT] and self.image_rect.x &lt; 649: self.facing = 'RIGHT' self.image_rect.x += dist elif key[pygame.K_LEFT] and self.image_rect.x &gt; 0: self.facing = 'LEFT' self.image_rect.x -= dist def draw(self, surface): if self.facing == "RIGHT": surface.blit(pygame.transform.flip(self.image, True, False),(self.image_rect.x,self.image_rect.y)) elif self.facing == "DOWN": surface.blit(pygame.image.load("ball_down.png"),(self.image_rect.x,self.image_rect.y)) if self.facing == "UP": surface.blit(pygame.image.load("ball_up.png"),(self.image_rect.x,self.image_rect.y)) elif self.facing == "LEFT": surface.blit(self.image,(sel…
accepted answer: http://stackoverflow.com/a/51418725
has title: Spawn moving objects from border
tagged with: ubuntu-18.04
score: 1
type: Question
answer count: 1
downvote count: 0
favorite count: 0
tagged with: pygame

http://stackoverflow.com/q/51423280
has comment: http://stackoverflow.com/comment/89824547
has comment: http://stackoverflow.com/comment/89825105
type: Question
accepted answer: http://stackoverflow.com/a/51427321
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
score: 2
type: AnsweredQuestion
has body: I am trying to make a simple programme that can help make army lists for a popular tabletop wargame. More as an excercise for my own experience as there are plenty of pre made software packages that do this, but the idea behind it seems fairly straightforward The programme reads the data for all the units available in an army from a spreadsheet and creates various classes for each unit. The main bit I am looking at now is the options/ upgrades. In the file I want a straightforward syntax for the option field for each unit. i.e. the following options string itemA, itemB/itemC-3, 2*itemD, itemE/itemF/itemG, itemH/itemI+itemJ would mean 1. you may take itemA (X pts per model) 2. for every 3 models, you may exchange itemB with a) itemC (net X pts per model) 3. each model may take 2 of itemD (X pts per model) 4. each model may take one of either a)itemE (X pts per model) b)itemF (X pts per model) c)itemG (X pts per model 5. each model may take either a)itemH (X points per model) b)itemI and itemJ (X points per model) At the moment I am processing the string using lots of splits and if statements, that make it very hard to keep track of and assign correctly once the user input their choice. for index, option in enumerate(self.options): output = "{}.".format(index+1) if '-' in option: sub_option, no_models = option.split('-') no_models = int(no_models) print(sub_option) print(no_models) output += "For every {} models ".format(no_models) if '/' in sub_option: temp_str, temp_options, points_list = exchange_option(sub_option) else: temp_str, temp_options, points_list = standard_option(sub_option) index_points.append(points_list) temp_options.append(no_models) index_options.append(temp_options) else: if '/' in option: temp_str, temp_options, points_list = exchange_option(option) else: temp_str, temp_options, points_list = standard_option(option) index_points.append(points_list) index_options.append(temp_options) output += temp_str the *_option() functions are additional helper…
has answer: http://stackoverflow.com/a/51427321
has title: Processing Strings from data file containing punctuation coding in python
upvote count: 2

http://stackoverflow.com/comment/89717357
score: 0
type: QuestionComment
type: Comment
has text: You donot have to use for loop to check seat availability, just use index row and col/.
comment on: http://stackoverflow.com/q/51372775

http://stackoverflow.com/q/51359783
has answer: http://stackoverflow.com/a/57674402
score: 47
has body: I am trying to convert JSON to CSV file, that I can use for further analysis. Issue with my structure is that I have quite some nested dict/lists when I convert my JSON file. I tried to use pandas json_normalize(), but it only flattens first level. import json import pandas as pd from pandas.io.json import json_normalize from cs import CloudStack api_key = xxxx secret = xxxx endpoint = xxxx cs = CloudStack(endpoint=endpoint, key=api_key, secret=secret) virtual_machines = cs.virtMach() test = json_normalize(virtual_machines["virtualmachine"]) test.to_csv("test.csv", sep="|", index=False) Any idea how to flatter whole JSON file, so I can create single line input to CSV file for single (in this case virtual machine) entry? I have tried couple of solutions posted here, but my result was always only first level was flattened. This is sample JSON (in this case, I still get "securitygroup" and "nic" output as JSON format: { "count": 13, "virtualmachine": [ { "id": "1082e2ed-ff66-40b1-a41b-26061afd4a0b", "name": "test-2", "displayname": "test-2", "securitygroup": [ { "id": "9e649fbc-3e64-4395-9629-5e1215b34e58", "name": "test", "tags": [] } ], "nic": [ { "id": "79568b14-b377-4d4f-b024-87dc22492b8e", "networkid": "05c0e278-7ab4-4a6d-aa9c-3158620b6471" }, { "id": "3d7f2818-1f19-46e7-aa98-956526c5b1ad", "networkid": "b4648cfd-0795-43fc-9e50-6ee9ddefc5bd", "traffictype": "Guest" } ], "hypervisor": "KVM", "affinitygroup": [], "isdynamicallyscalable": false } ] }
possible better answer: http://stackoverflow.com/a/62186294
tagged with: pandas
has answer: http://stackoverflow.com/a/51379007
has answer: http://stackoverflow.com/a/62186294
accepted answer: http://stackoverflow.com/a/51379007
has answer: http://stackoverflow.com/a/57793454
has answer: http://stackoverflow.com/a/60052517
favorite count: 0
answer count: 10
tagged with: python
upvote count: 47
has answer: http://stackoverflow.com/a/76014388
has answer: http://stackoverflow.com/a/61049446
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89696369
linked to: http://stackoverflow.com/q/6027558
has answer: http://stackoverflow.com/a/66601730
downvote count: 0
has answer: http://stackoverflow.com/a/73115562
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/109982490
has comment: http://stackoverflow.com/comment/89695949
has comment: http://stackoverflow.com/comment/89693667
type: Question
has comment: http://stackoverflow.com/comment/89699941
has answer: http://stackoverflow.com/a/58211293
has comment: http://stackoverflow.com/comment/89698858
has title: How to flatten multilevel/nested JSON?

http://stackoverflow.com/comment/89885559
type: Comment
comment on: http://stackoverflow.com/a/51457957
has text: @JAponte ohh if that is the case we can easily put NAME in first line instead of w+
type: AnswerComment
score: 0

http://stackoverflow.com/q/51444626
tagged with: django
has comment: http://stackoverflow.com/comment/89859678
type: Question
has comment: http://stackoverflow.com/comment/89864497
has comment: http://stackoverflow.com/comment/89859875
has comment: http://stackoverflow.com/comment/89859479
has body: I have Django a model that has a different meaning between a null value and a blank value. When I create a choicefield with the following CHOICES: CHOICES = [ (None, 'Null'), ('', 'Blank'), ('foo', 'Foo'), ('bar', 'Bar') ] The admin form generates this: Null Blank Foo Bar So that when you submit the form with "blank" selected, the database saves the null value. Is there a way to make Django distinguish within the admin form blank from null? Edit: for more context here is the existing code I am working with simplified some: class CustomChoiceField(models.CharField): FIELD_SETTINGS = { 'null': True, 'blank': True, 'max_length': 5, 'choices': [ (None, 'Null'), ('', 'Blank'), ('foo', 'Foo'), ('bar', 'Bar') ] } class MyModel(BaseModel): my_field = CustomChoiceField('label')
downvote count: 0
has title: Choicefield empty string and null
has comment: http://stackoverflow.com/comment/89864424
tagged with: http://stackoverflow.com/tag/html
tagged with: python
favorite count: 0
score: 2
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/89860015
type: UnansweredQuestion

http://stackoverflow.com/comment/89783585
comment on: http://stackoverflow.com/a/51402161
has text: I am familiar with the list, but not that advanced in it..would it look something like a[ ]=int(line) ?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89844814
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51436955
has text: Updated snippet
score: 0

http://stackoverflow.com/a/71880555
upvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/129149214
has body: Just wanted to add a little bit to above answer. Even if you copy paste the pickle file manually to different directory where you want to load the model, we end up with that error. If you want to move that file use cut paste.
downvote count: 2
score: -2
answers question: http://stackoverflow.com/q/51397611

http://stackoverflow.com/q/51332842
has title: remove big object from a picture in open cv
has answer: http://stackoverflow.com/a/51332989
linked to: http://stackoverflow.com/q/42798659
type: Question
tagged with: opencv
has body: Hi im trying to remove big object from a picture in openCV in python I found a way to do it remove small and it worked perfectly. How could I tweak the code to only keep object from a specific range of size. Here How to remove small connected objects using OpenCV But when I do it for big object I get this: error:OpenCV(3.4.1) Error: Assertion failed (iDepth == 0 || iDepth == 1) in cv::connectedComponents_sub1, file C:\projects\opencv-python\opencv\modules\imgproc\src\connectedcomponents.cpp, line 3941 Traceback (most recent call last):
upvote count: 1
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51332989
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1

http://stackoverflow.com/a/51331237
type: Answer
answers question: http://stackoverflow.com/q/51331053
upvote count: 2
has comment: http://stackoverflow.com/comment/89638224
accepted answer of: http://stackoverflow.com/q/51331053
has body: It's not actually the PCA that is problematic, but just the renaming of your columns: the digits dataset has 64 columns, and you are trying to name the columns according to the column names for the 4 columns in the iris dataset. Because of the nature of the digits dataset (pixels), there isn't really an appropriate naming scheme for the columns. So just don't rename them. digits = datasets.load_digits() x = pd.DataFrame(digits.data) pca = decomposition.PCA(n_components=2) pca.fit(x) x = pca.transform(x) # Here is the result of your PCA (2 components) &gt;&gt;&gt; x array([[ -1.25946636, 21.27488332], [ 7.95761139, -20.76869904], [ 6.99192268, -9.9559863 ], ..., [ 10.80128366, -6.96025224], [ -4.87210049, 12.42395326], [ -0.34438966, 6.36554934]]) Then you can plot the first pc against the second, if that's what you're going for (what I gathered from your code) plt.scatter(x[:,0], x[:,1], s=40) plt.show()
score: 2
has comment: http://stackoverflow.com/comment/89638665
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89639274
downvote count: 0

http://stackoverflow.com/q/51468652
has body: So I am making an application in Python where you fill out your information and then pay for the product on the kiosk. Sometimes these kiosks lose internet connection (due to the poor internet in the buildings) I need to figure out a way to temporarily store that data (customer information(i.e: first name, last name, shipping address, etc)) and (payment method) if the internet goes offline. I'm sending the customer info to ShipStation using the ShipStation API, and the payment via Stripe, any clue if I could securely store the data temporarily?
score: 0
has title: How would I store a form of information temporarily if internet connection is down
tagged with: python
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/89905902
has comment: http://stackoverflow.com/comment/89907586
tagged with: stripe-payments

http://stackoverflow.com/a/51351887
upvote count: 18
accepted answer of: http://stackoverflow.com/q/51351728
type: AcceptedAnswer
score: 18
has body: You can use # pylint: disable=fixme, line-too-long. See this StackOverflow answer.
answers question: http://stackoverflow.com/q/51351728
downvote count: 0
type: Answer

http://stackoverflow.com/comment/89788654
type: Comment
has text: @Mohit I doubt it. Another question mark only example: 1. How many are you ok? 2. How many? Are you ok?
comment on: http://stackoverflow.com/q/51356244
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90013732
type: Comment
has text: This works. Is there a way to call in the _label of that entity and add that as an additional column?
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51521071

http://stackoverflow.com/a/51349523
has comment: http://stackoverflow.com/comment/89673110
has body: is that what you need? my_list = my_string.split() #my_list == [item0, item1, ...] for idx,item in enumerate(my_list): print(idx,my_list[idx]) #output: 0 item0 ; 1 item1 ; ...
score: 0
answers question: http://stackoverflow.com/q/51348463
type: Answer

http://stackoverflow.com/comment/89738584
has text: I haven't had any issue with that? When one is running, the other isnt being used anyways. Blocking calls between the two haven't been an issue.
type: QuestionComment
comment on: http://stackoverflow.com/q/51382376
score: 0
type: Comment

http://stackoverflow.com/q/51451992
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: Why does my code return 0 for the minimum no matter what the actual minimum is?
has answer: http://stackoverflow.com/a/51452050
downvote count: 3
has body: I am writing a piece of code for an assignment for class that is supposed to find the minimum and maximum when given a string. This is the code I have written so far: def find_min_and_max(values): '''(string) -&gt; None ''' mmin = 0 mmax = 0 if values == '': print('There is no min or max') return None for value in values: if len(values) == 1: mmax = value mmin = value if value &gt; str(mmax): mmax = value if value &lt; str(mmin): mmin = value print('The minimum value is ' + str(mmin)) print('The maximum value is ' + str(mmax)) return None When I run it on the shell, this is the answer I receive: ">>> find_min_and_max('132475689') "The minimum value is 0" "The maximum value is 9"" Why am I getting minimum 0? This happens for whatever string of numbers for the parameter, I enter. Thanks.
has answer: http://stackoverflow.com/a/51452028
has comment: http://stackoverflow.com/comment/89874159
type: Question
has comment: http://stackoverflow.com/comment/89874077
answer count: 2
score: -2
has comment: http://stackoverflow.com/comment/89874091

http://stackoverflow.com/a/51387169
downvote count: 0
has comment: http://stackoverflow.com/comment/89749519
type: Answer
accepted answer of: http://stackoverflow.com/q/51386778
has comment: http://stackoverflow.com/comment/89771836
score: 3
has comment: http://stackoverflow.com/comment/89775171
has body: The first problem is that n isn't a number or index, it is a string containing the path name. To get the index, you can use enumerate, which gives index, value pairs. Second, unlike in MATLAB you can't assign to indexes that don't exist. You need to pre-allocate your image array or, better yet, append to it. Third, it is better not to use the variable file since in python 2 it is a built-in data type so it can confuse people. So with preallocating, this should work: images = [None]*len(sub_f) for n, cursub in enumerate(sub_f): path_now = os.path.join(path, cursub, '*.pgm') images[n] = [cv2.imread(fname) for fname in glob.glob(path_now)] Using append, this should work: for cursub in sub_f path_now = os.path.join(path, cursub, '*.pgm') images.append([cv2.imread(fname) for fname in glob.glob(path_now)]) That being said, there is an easier way to do this. You can use the pathlib module to simplify this. So something like this should work: from pathlib import Path mypath = Path('/home/university/Matlab/att_faces') images = [] for subdir in mypath.iterdir(): images.append([cv2.imread(str(curfile)) for curfile in subdir.glob('*.pgm')]) This loops over the subdirectories, then globs each one. This can even be done in a nested list comprehension: images = [[cv2.imread(str(curfile)) for curfile in subdir.glob('*.pgm')] for subdir in mypath.iterdir()]
has comment: http://stackoverflow.com/comment/89771057
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89746400
upvote count: 3
has comment: http://stackoverflow.com/comment/89749066
answers question: http://stackoverflow.com/q/51386778

http://stackoverflow.com/q/51426767
type: Question
downvote count: 0
tagged with: flask
tagged with: python
has title: Flask + Mongo Multi-tenant app
favorite count: 0
answer count: 0
type: UnansweredQuestion
upvote count: 1
score: 1
tagged with: flask-mongoengine
has body: I am trying to build an app with multiple database for each client. With flask-mongoengine you can register multiple database connection and use the alias to connect to the database at the time of query ORM models. I am using @before_request hook to set the tenant. app.config["MONGODB_SETTINGS"] = { 'db': 'default', 'host': 'mongodb://localhost/default', 'alias': 'default' }, { 'db': 'client1', 'host': 'mongodb://localhost/client1', 'alias': 'client1' } from models.import Purchase def get_data(): with switch_db(Purchase, g.context['tenant']) as Data: record = Data.objects(pk=&lt;id&gt;).first() return record I am able to switch the database successfully with this approach. I want to switch the context of the database globally or at the time of user chooses client. So that I don't have to change it for each method and every time I have to query.

http://stackoverflow.com/a/51404896
has comment: http://stackoverflow.com/comment/89782209
type: Answer
has comment: http://stackoverflow.com/comment/89782457
has body: I don't know why but it seems that "" is missing from your sys.path variable, and that prevents from importing modules from current directory all right! I can somehow reproduce your issue (eatcpu.py is in my current dir): $ python.exe Python 2.7.8 (default, Jun 30 2014, 16:08:48) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.path ['', 'C:\\Windows\\system32\\python27.zip', 'D:\\AppX64\\Python27\\DLLs', ... etc...] &gt;&gt;&gt; import eatcpu works. Now in another python session: $ python.exe Python 2.7.8 (default, Jun 30 2014, 16:08:48) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.path.remove("") &gt;&gt;&gt; import eatcpu Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named eatcpu &gt;&gt;&gt; So the quickfix for you is to do: import sys sys.path.append("")
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/51403126

http://stackoverflow.com/comment/89739951
type: Comment
type: QuestionComment
has text: The expected output is just a hand-written example. I am trying to demonstrate I would like the Y.max() and X.max() for each time interval e.g. for the interval 00:00:10.700 00:00:11.180. Hope it is clear.
comment on: http://stackoverflow.com/q/51382499
score: 0

http://stackoverflow.com/a/51375390
has comment: http://stackoverflow.com/comment/89760370
has comment: http://stackoverflow.com/comment/89760612
has comment: http://stackoverflow.com/comment/89722390
type: Answer
has comment: http://stackoverflow.com/comment/89722865
has comment: http://stackoverflow.com/comment/89724799
upvote count: 3
has comment: http://stackoverflow.com/comment/89760777
has body: I think need cumcount with set_index and unstack first for reshape data: a = df.set_index(['a',df.groupby('a').cumcount()])['b'].unstack() print (a) 0 1 2 a 1 5896 4000 89647 2 54 3568 48761 3 5896 2800 5894 a.plot.bar()
score: 3
has comment: http://stackoverflow.com/comment/89759741
has comment: http://stackoverflow.com/comment/89724631
has comment: http://stackoverflow.com/comment/89724752
has comment: http://stackoverflow.com/comment/89759697
answers question: http://stackoverflow.com/q/51375255
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89761132
has comment: http://stackoverflow.com/comment/89760432
accepted answer of: http://stackoverflow.com/q/51375255

css-selectors
tags question: http://stackoverflow.com/q/51442191
tags question: http://stackoverflow.com/q/51375642
tags question: http://stackoverflow.com/q/51415674
tags question: http://stackoverflow.com/q/51371495
tags question: http://stackoverflow.com/q/51449271
tags question: http://stackoverflow.com/q/51402601
tags question: http://stackoverflow.com/q/51340868
tags question: http://stackoverflow.com/q/51326388
tag name: css-selectors
type: Tag

http://stackoverflow.com/a/51475423
type: Answer
score: 0
has body: Use the pattern ([^,]*) to match everything upto a comma &gt;&gt;&gt; re.findall(r'\sante mí:\s+([^,]*)', mensaje) ['DANIEL ROLANDO CORNEJO GALLARDO']
accepted answer of: http://stackoverflow.com/q/51475299
answers question: http://stackoverflow.com/q/51475299
type: AcceptedAnswer

http://stackoverflow.com/a/51445894
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/51445839
score: 0
type: Answer
has body: Your file variable has a list of elements from re.findall Try: import re file = re.findall(r'\[(.*?)\]', file) m = [re.split(r'\ +', i) for i in file] print(m) Output: [['2018-07-10', '15:04:11'], ['2018-07-10', '15:04:12'], ['2018-07-10', '15:04:42'], ['2018-07-10', '15:04:42']]

http://stackoverflow.com/q/51329121
has answer: http://stackoverflow.com/a/51329284
has comment: http://stackoverflow.com/comment/89634069
has body: I have this code : M=np.zeros((N,N),dtype=complex) M=sparse.bsr_matrix(M) M[0][0]=complex(1,1) print(M) I am trying to create an NxN sparse matrix of zeros that I can then add numbers into. Could someone please tell me why it is giving me an error? Thanks!
downvote count: 2
tagged with: python
possible better answer: http://stackoverflow.com/a/51329337
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51329337
accepted answer: http://stackoverflow.com/a/51329284
has title: Sparse matrix of zeros
type: Question
answer count: 2
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/89633796
favorite count: 0
has comment: http://stackoverflow.com/comment/89635000

http://stackoverflow.com/comment/89811416
type: Comment
type: AnswerComment
has text: Thanks. The static function is much faster. I think, though not compelling in this example, it will be helpful in my real application.
score: 0
comment on: http://stackoverflow.com/a/51419667

http://stackoverflow.com/a/51371217
upvote count: 1
score: 1
downvote count: 0
has body: itertools.cycle seems appropriate in this case. Here's another version for future readers: import itertools column_names = ["a", "b", "c"] values = [1, 2, 3, 4, 5, 6, 7, 8, 9] L = zip(itertools.cycle(column_names), values) for g, v in itertools.groupby(sorted(L), lambda x: x[0]): print("{} = {}".format(g, [i[1] for i in v])) gives: a = [1, 4, 7] b = [2, 5, 8] c = [3, 6, 9]
answers question: http://stackoverflow.com/q/51370753
type: Answer

http://stackoverflow.com/comment/89743343
comment on: http://stackoverflow.com/a/51385642
score: 0
type: AnswerComment
has text: This is good. What is the performance impact of using isin vs merge? Would you use the same approach over millions of rows?
type: Comment

http://stackoverflow.com/q/51350115
answer count: 1
linked to: http://stackoverflow.com/q/15889131
has answer: http://stackoverflow.com/a/51350133
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/15889131
tagged with: python
accepted answer: http://stackoverflow.com/a/51350133
has body: I have a list that contain days count in each month: month = [31,28,31,30,31,30,31,31,30,31,30,31] I want to transform list above. Each element of the new list is equal to the sum of all elements in a particular position. For example, first element should be the same (31), second = 28+31, third = 31+28+31 and so on. Desired output: month = [31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365] How to do it? I tried variations with a for loop and append method, but I did not succeed.
type: AnsweredQuestion
has title: How to replace each element of the list with the sum of the elements of the list up to the position of the element inclusive
tagged with: sum
type: Question
score: 0
tagged with: for-loop

http://stackoverflow.com/comment/89746140
type: Comment
has text: I flagged as a duplicate but i didn't know it is not good practice to bring out the best answer from another thread. I stand corrected and will delete this
comment on: http://stackoverflow.com/a/51386913
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89746138
comment on: http://stackoverflow.com/q/51386698
has text: DevOps, CI/CD, Docker, Kubernetes.. are mainly used to automate deployment on servers (web apps). so it's probably not what you're looking for.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51442492
has body: Problem There seems no easy way to one-hot-encode data that has no order. My question is, what is the best way to one-hot-encode values that have no particular order? And if there is no standardised way to do this, why should one-hot-encoded features be ordered? Example I am trying to one-hot-encode a set of features where the values are custom objects. My object looks like this: class MyObject(object) def __init__(self, identity): self.identity = identity def __hash__(self): return self.identity def __eq__(self, other): return self.identity == other.identity In this setting each instance of MyObject can be compared on equality. Suppose we have the following list of objects: objects = [MyObject(0), MyObject(1), MyObject(0)] The function set(objects) yields a set of 2 objects, namely MyObject(0) and MyObject(1). This is indeed the behaviour that I expect. Therefore, when I try to one-hot-encode this data, I would expect something in the form of: index MyObject_0, MyObject_1 0 1 0 1 0 1 2 1 0 However, all solutions that I tried require data to be one-hot-encoded to have some sort of order, whereas that is undefined in my case. I think it should still be possible to have a one-hot-encoding if the order is undefined as in that case it does not matter which one-hot-encoded feature is before the other. Attempted solutions Pandas dataframe My first attempted solution was using pandas' get_dummies() function. import pandas as pd objects = [MyObject(0), MyObject(1), MyObject(0)] dataframe = pd.DataFrame({'MyObjectFeature': objects}) dummies = pd.get_dummies(dataframe) However, this example gives a TypeError: TypeError: 'values' is not ordered, please explicitly specify the categories order by passing in a categories argument. Scikit-learn LabelEncoder &amp; OneHotEncoder My second attempt was using Scikit-learn's LabelEncoder to encode the values before putting them into a OneHotEncoder object. However, in the LabelEncoder the same problem as using Pandas dataframes arises. …
tagged with: python
type: UnansweredQuestion
upvote count: 1
score: 1
has title: How to one hot encode unordered discrete data in python?
type: Question
answer count: 1
downvote count: 0
favorite count: 0
tagged with: one-hot-encoding
has answer: http://stackoverflow.com/a/51442593
tagged with: pandas

http://stackoverflow.com/a/51477540
answers question: http://stackoverflow.com/q/51477478
has comment: http://stackoverflow.com/comment/89928574
has comment: http://stackoverflow.com/comment/89924198
has comment: http://stackoverflow.com/comment/89928160
downvote count: 0
has comment: http://stackoverflow.com/comment/89923475
has body: You are probably on python 3.x, where print statements need brackets try print(play_scraper.collection( collection='COMMUNICATION', category='TOP COMMUNICATION APPS', results=5, page=1)) For your second issue try running pip3 install play-scraper -U To make sure you have the latest requirements. Note pip -&gt; python2.x, pip3 -&gt; python3.X
has comment: http://stackoverflow.com/comment/89923420
type: Answer
has comment: http://stackoverflow.com/comment/89928480
has comment: http://stackoverflow.com/comment/89936111
upvote count: 1
has comment: http://stackoverflow.com/comment/89923774
score: 1

http://stackoverflow.com/a/51368232
type: Answer
score: 4
has body: import numpy as np im = np.array([[[255, 194, 7],[224, 255, 8],[230, 230, 230],[11, 102, 255]]]) Like this? Make a mask and use it to change the values. &gt;&gt;&gt; mask = im == 230 &gt;&gt;&gt; im[mask] = 255 &gt;&gt;&gt; im[np.logical_not(mask)] = 0 &gt;&gt;&gt; im =&gt; array([[[ 0, 0, 0], [ 0, 0, 0], [255, 255, 255], [ 0, 0, 0]]]) Or using numpy.where &gt;&gt;&gt; np.where(im==230, 255, 0) =&gt; array([[[ 0, 0, 0], [ 0, 0, 0], [255, 255, 255], [ 0, 0, 0]]])
accepted answer of: http://stackoverflow.com/q/51367545
upvote count: 4
answers question: http://stackoverflow.com/q/51367545
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89637711
type: AnswerComment
comment on: http://stackoverflow.com/a/51330691
has text: But question still remains... `print(re.search(r'\\$', 'hellothere\'))` should not work but `print(re.search(r'\$', r'hellothere\'))` should work with raw string... because backslash is just a backslash but not part of escape sequence
type: Comment
score: 0

http://stackoverflow.com/a/51407003
type: AcceptedAnswer
has body: There was some confusion in the comments, because projectile_list actually isn't a list but a pygame.sprite.Group. If you want to remove all sprites from a group, you can call the empty method: projectile_list.empty(). Note that empty will remove the sprites only from this specific group. If you want to remove the same sprites from all groups, you can iterate over the sprites and call their kill method.
type: Answer
answers question: http://stackoverflow.com/q/51405186
has comment: http://stackoverflow.com/comment/89785234
accepted answer of: http://stackoverflow.com/q/51405186
score: 0

http://stackoverflow.com/comment/89858398
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51444121
has text: Does all your rows in csv have 2 columns?

http://stackoverflow.com/a/57896662
accepted answer of: http://stackoverflow.com/q/51386478
downvote count: 0
upvote count: 11
type: AcceptedAnswer
type: Answer
score: 11
has body: More up to date answer - yes, you can use python 3.6 now with kivy-ios. I have created and published apps on the app store using python 3.6 and kivy! Here is an example: https://apps.apple.com/us/app/100-days-of-fitness/id1468049372 100% Python and Kivy :)
answers question: http://stackoverflow.com/q/51386478
has comment: http://stackoverflow.com/comment/110818485

onchange
tags question: http://stackoverflow.com/q/51369835
tag name: onchange
type: Tag

http://stackoverflow.com/a/51350849
answers question: http://stackoverflow.com/q/51350775
has body: You can use true/false, or numbers (to provide another way). def color_change(which): #can be integer or boolean if which == 1: #can be changed to true color_label.configure(fg='red') elif which == 2: #can be changed to false color_label.configure(fg='blue') red_button = Button(root, text="Red", fg = "red", font="Arial, 20", command = lambda: color_change(1)) blue_button = Button(root, text="Blue", fg = "blue", font="Arial, 20", command = lambda: color_change(2)) Though using integers is better because you can support many more colors (not just 2, with true/false)
score: 0
type: Answer

http://stackoverflow.com/comment/89783482
comment on: http://stackoverflow.com/a/51406030
score: 2
type: AnswerComment
has text: The problem is that I am developing BOTH the library AND the application at the same time. I'm not working with the typical scenario (a completed library which I am now writing an application against). So during development, I will shift focus back and forth a lot. Today, I might be working on adding some functions to the application, and just put some stubs in the library so it can work without crashing; tomorrow, I'll add some code to the library, but then have to make a change to the application to support it. (This happens when you're the sole developer)
type: Comment

http://stackoverflow.com/a/51450359
has body: You're talking about inheritance vs. composition. This of this as either an "is-a" relationship or a "has-a" relationship. If PowerControl inherits from PowerControlA, then PowerControl "is-a" PowerControlA. That's inheritance. class PowerControl(PowerControlA): # stuff If PowerControl instantiates self.A = PowerControlA(), then PowerControl "has-a" PowerControlA. That's composition. class PowerControl(object): def __init__(*args, **kwargs): self.A = PowerControlA(*args, **kwargs) # maybe # stuff Which one you actually want to use is impossible to say without the problem being better specified.
answers question: http://stackoverflow.com/q/51450298
score: 0
has comment: http://stackoverflow.com/comment/89871140
type: Answer

http://stackoverflow.com/q/51482379
tagged with: indentation
has answer: http://stackoverflow.com/a/51485482
answer count: 1
has title: Intuition behind knowing how to use indentation in python
has comment: http://stackoverflow.com/comment/89933772
favorite count: 0
has comment: http://stackoverflow.com/comment/89933694
has body: I am completely new to programming and have decided to begin my journey by learning Python. Along the way I have been having some issues with knowing how code is behaving with respect to indentation. I will give an example: Problem: Given an array of integers, return the number of 9's in the array. My first attempt did this: def array_count9(nums): list_of_9 = [] for num in nums: if num == 9: list_of_9.append(1) return sum(list_of_9) This was wrong, and I discovered later (after trial and error) that the reason was because I hadn't properly indented my last line of code. The correct answer should: def array_count9(nums): list_of_9 = [] for num in nums: if num == 9: list_of_9.append(1) return sum(list_of_9) This is a problem I have run into repeatedly, and I think it's because I don't really understand how Python deals with indentation. I understand now that the correct answer is correct because with my first attempt, I am telling Python to return the sum of the objects inside the list immediately after testing whether or not the first integer is 9. In the correct example, Python will run through all the numbers, and only when it is done, go back out to the previous indentation and return the list. I don't know, I guess I am wondering if someone can provide a "walk-through" of what is happening in each line of good or direct me to a resource that discusses this further. I have looked for such a resource online but have been unable to find one. Any help would be appreciated!
tagged with: python
accepted answer: http://stackoverflow.com/a/51485482
upvote count: 2
score: 0
downvote count: 2
type: Question
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/89934033
has comment: http://stackoverflow.com/comment/89933823
has comment: http://stackoverflow.com/comment/89933693

http://stackoverflow.com/comment/89679674
type: QuestionComment
comment on: http://stackoverflow.com/q/51353519
score: 0
has text: @njzk2 obviously, that is the point of confusion, and it is a quite common one since many introductory programming materials gloss over the distinction between printing to a buffer (a side effect) and returning from a function.
type: Comment

http://stackoverflow.com/comment/89926083
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51477961
has text: I recently read [this](https://stackoverflow.com/questions/5022066/how-to-serialize-sqlalchemy-result-to-json/51469201#51469201) answer to another similar question. I haven’t used the library but thought I’d bring it to your attention as sounds like it might help.
type: Comment

http://stackoverflow.com/a/52107704
answers question: http://stackoverflow.com/q/51439810
has comment: http://stackoverflow.com/comment/125318171
score: 9
has body: I recently discovered a much more efficient way of retrieving the Drive API 'File ID' of any given file/folder located within your Google Drive File Stream file system. Although I found this functionality on a Windows system, there may be similar functionality on Mac OS X. I do not know exactly what mechanism allows for the functionality described below, but it is nearly identical in function to the way NTFS alternate data streams work. The thing is, the properties of Drive File Stream's virtual drive show it as being partitioned as FAT32 which do not support alternate data streams. Perhaps Google's file system driver is simply emulating the behavior of NTFS alternate data streams. Regardless, the Drive File Stream driver adds a mechanism for reading special metadata attached to file/folder's located within its file system. This metadata can be accessed by calling 'ReadFile' on any file/folder path that is suffixed with a colon followed by a special identifier describing the metadata one wants to retrieve. These are the identifiers I've discovered so far (including descriptions for some of them): user.drive.id - Drive API 'File ID' of the file/folder user.drive.team_drive_id - Drive API 'Team Drive ID' of the file/folder (empty if not in a Team Drive) user.drive.gdoc - Returns '1' if the file is a 'Google Docs' document or '0' if it is not user.drive.email - As far as I can tell, this simply returns the email address of the Google account that Drive File Stream is signed into (I tried calling this on a file that is owned by another Google account, but it still returned my email address) user.drive.itemprotostr - Provides nearly all of the metadata attached to the file, including the output of nearly all of these other identifiers user.drive.md5 - The MD5 checksum of the file com.apple.FinderInfo - Not sure if this actually a valid identifier (as it does not work on Windows), but since I found it in close proximity to the others, and it may be relevant to your platfo…
downvote count: 0
has comment: http://stackoverflow.com/comment/111830754
type: Answer
has comment: http://stackoverflow.com/comment/110504780
has comment: http://stackoverflow.com/comment/103695861
upvote count: 9

http://stackoverflow.com/comment/89959216
comment on: http://stackoverflow.com/a/51469761
type: Comment
has text: The data has already been fitted with numerical approaches. Want I want to achieve now is really to fit the data with a machine learning code, so that I can compare to the performance of numerical fits (like the one that you present). Among others, I have to check if there is maybe some hidden small structure in the data, that deviates from the completely smooth curve. Therefore, can you give me some suitable recurrent neural network template?
score: 1
type: AnswerComment

http://stackoverflow.com/comment/89693753
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51360493
has text: You have to override the View, and start using the new view for the logins. Changing django built in login API is not a good idea.

http://stackoverflow.com/comment/89857965
comment on: http://stackoverflow.com/q/51431380
has text: Yes @lampShadesDrifter there's the possibility that it will look like this: `[['abc', 2], ['def', 2], ['ghi', 2]] `
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89938807
comment on: http://stackoverflow.com/a/51484409
score: 0
type: Comment
type: AnswerComment
has text: Hi, thanks for reply. What do you mean by 1.? Should it be 'del pplList[:i]' or something else? How about the changing index of numbers when the first iteration ends? How could I change the condition right there? I don't know if this is clear what I say.

http://stackoverflow.com/comment/89722564
type: Comment
has text: Empty string instead of newline seems to be sufficient and allows more uniform further processing.
type: AnswerComment
comment on: http://stackoverflow.com/a/51375476
score: 0

http://stackoverflow.com/a/51414303
accepted answer of: http://stackoverflow.com/q/51414271
type: Answer
has body: Use split() and remove() In [11]: s = '30121,long,Mehtab,10,20,,30' In [14]: l = s.split(',') In [15]: l.remove('') In [16]: l Out[16]: ['30121', 'long', 'Mehtab', '10', '20', '30']
answers question: http://stackoverflow.com/q/51414271
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/89890600
has text: Thank you for your comment. I added the code for the front_end. Hope it will help. Thank you.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51459736
score: 0

http://stackoverflow.com/q/51481431
answer count: 2
has comment: http://stackoverflow.com/comment/89932110
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89932491
has comment: http://stackoverflow.com/comment/89931824
favorite count: 0
score: 0
tagged with: python
has body: I have a txt file which has text in this manner: [2018-07-11 20:57:08] SYSTEM RESPONSE: "hello" [2018-07-11 20:57:19] USER INPUT (xvp_dev-0): "hi! how is it going?" [2018-07-11 20:57:19] SYSTEM RESPONSE: "It's going pretty good. How about you?" [2018-07-11 14:05:20] USER INPUT (xvp_dev-0): I've been doing good too! Thank you. [2018-07-12 14:05:20] SYSTEM RESPONSE: "Hello!" How is your day going today? [2018-07-12 14:05:34] USER INPUT (xvp_dev-0): "Great! Can't complain" [2018-07-12 14:05:34] SYSTEM RESPONSE: "Okay. That's good" Now, I want all the lines from the first occurrence of [2018-07-11] to the last, and all the line in between. Currently, I am just finding all the lines that start with [2018-07-11.. and displaying them, but if you notice, there are few lines which are in between them too which are getting lost. for line in file: if b in line: #b = system input of date x = x + "//" + line[11:] else: x=x Sample output would be something like: For the date 2018-11-17: 20:57:08] SYSTEM RESPONSE: "hello" 20:57:19] USER INPUT (xvp_dev-0): "hi! how is it going?" 20:57:19] SYSTEM RESPONSE: "It's going pretty good. How about you?" 14:05:20] USER INPUT (xvp_dev-0): I've been doing good too! Thank you. for the date: 2018-07-12: 14:05:20] SYSTEM RESPONSE: "Hello!" How is your day going today? 14:05:34] USER INPUT (xvp_dev-0): "Great! Can't complain" 14:05:34] SYSTEM RESPONSE: "Okay. That's good" Any idea on how I would be able to get the lines in between too? Since it all depends on dates- there is no way an occurrence of a that can happen later on in the text.
has answer: http://stackoverflow.com/a/51481874
type: Question
has comment: http://stackoverflow.com/comment/89931757
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51481874
has title: Include all lines in between the first and last occurrence
has comment: http://stackoverflow.com/comment/89931731
has answer: http://stackoverflow.com/a/51481753
accepted answer: http://stackoverflow.com/a/51481753
tagged with: python-2.7

concurrency
tag name: concurrency
tags question: http://stackoverflow.com/q/51420758
tags question: http://stackoverflow.com/q/51466456
tags question: http://stackoverflow.com/q/51371837
type: Tag

http://stackoverflow.com/q/51411809
score: 4
answer count: 1
downvote count: 1
favorite count: 0
tagged with: python-3.x
upvote count: 5
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/51412330
type: Question
has body: Im working on a project where I have to take excel file make changes to the data and save it from pandas import ExcelWriter import pandas as pd dfs = pd.read_excel("infile.xlsx") #manuplate data writer = ExcelWriter('outfile.xlsx') dfs.to_excel(writer,'Sheet5') writer.save() The problem I have is the newly saved excel file does not have the same format(cell widht, bold borders) as the input file. What can I do to solve this issue?
has title: keeping the same file format when saving .xlsx file using python

http://stackoverflow.com/comment/89915343
comment on: http://stackoverflow.com/q/51473572
type: Comment
type: QuestionComment
score: 2
has text: `text = input("Please give your text:") text = list(text) print(text)`

http://stackoverflow.com/a/55168094
score: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/134649210
has body: I encounter the same issue. It is a issue correlated to the installation of dramatiq. Infact, in my case, the script would to execute "dramatiq" file in /usr/lib when was in /usr/local/lib. So i found a solution: create a virtual environment.
type: Answer
has comment: http://stackoverflow.com/comment/97075819
upvote count: 3
has comment: http://stackoverflow.com/comment/101070128
accepted answer of: http://stackoverflow.com/q/51326147
answers question: http://stackoverflow.com/q/51326147

http://stackoverflow.com/q/51404567
score: 3
has answer: http://stackoverflow.com/a/51405003
downvote count: 0
type: Question
has title: Django - Posting jQuery dictionary via Ajax prints None in views.py
has comment: http://stackoverflow.com/comment/89780511
upvote count: 3
answer count: 2
possible better answer: http://stackoverflow.com/a/51405170
favorite count: 0
accepted answer: http://stackoverflow.com/a/51405003
has answer: http://stackoverflow.com/a/51405170
tagged with: django
tagged with: python
has body: I have an Ajax function in my Django project resembling the following... $('#btn-submit').click(function(e){ e.preventDefault(); var btn = $(this); var dataUrl = btn.attr('data-href'); var title = $('#title').val(); var dict = {}; $('.choice-m2m-check').each(function(i){ k = $(this).val(); v = $(this).attr('data-value'); dict[k] = v; }); $.ajax({ url:dataUrl, method:'POST', data:{ 'title':title, 'dict':dict, }, success:function(data){ if (data.saved){ ... } }, error:function(error){ ... } }); }); So I have a {key: value, ...} dictionary which assigns a 'true' or 'false' boolean flag to each item. This is then posted to the URL represented by 'dataUrl' where Python does some checks on the data. So firstly, in the jQuery after the key value pairs have been assigned, I console log the value of dict using console.log(dict) which gives me something like the following {item-885564895: "true", item-0385245877: "false"} in the console. The problem is that in my Django view where I print the posted value of request.POST.get('dict') then it prints None. Note that when I print the 'title' field which is a regular string then printing it returns the value of the title. What am I doing wrong?
type: AnsweredQuestion

http://stackoverflow.com/a/51402888
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89776666
answers question: http://stackoverflow.com/q/51401350
upvote count: 2
has body: I have tried following code on my PC and it's working for me import requests url = 'http://localhost/dx/index.php' file_path_json = {"1": "/Users/bob/Documents/python_stuff/venv/json_output.json"} resp = requests.post(url, file_path_json) print(resp) hope this helps

http://stackoverflow.com/q/51445631
possible better answer: http://stackoverflow.com/a/51445715
has answer: http://stackoverflow.com/a/51445715
has body: Consider the following: d = {'a': 0.0, 'b': 1.0, 'c': 2.0} e = pd.Series(d, index = ['a', 'b', 'c']) df = pd.DataFrame({ 'A' : 1.,'B' : e,'C' :pd.Timestamp('20130102')}). When i try to access the first row of column B in the following way: &gt;&gt;&gt; df.B[0] 0.0 I get the correct result. However, after reading KeyError: 0 when accessing value in pandas series, I was under the assumption that, since I have specified the index as 'a', 'b' and 'c', the correct way to access the first row of column B (using positional arguments) is: df.B.iloc[0] , and df.B[0] should raise a Key Error. I dont know what am I missing. Can someone clarify in which case do I get a Key Error ?
has answer: http://stackoverflow.com/a/51445694
answer count: 3
score: 4
favorite count: 0
has title: Pandas indexing and Key error
tagged with: pandas
tagged with: python
upvote count: 4
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/46153647
has answer: http://stackoverflow.com/a/51446997
accepted answer: http://stackoverflow.com/a/51446997
linked to: http://stackoverflow.com/q/48035493
has comment: http://stackoverflow.com/comment/89861770
type: Question
tagged with: indexing

http://stackoverflow.com/q/51406583
has comment: http://stackoverflow.com/comment/89787630
has comment: http://stackoverflow.com/comment/89791491
tagged with: dataframe
has title: How can I do multithreading on a dataframe?
score: 0
has body: I'm trying to do multithreading on dataframe with python like this blog: http://blog.adeel.io/2016/11/06/parallelize-pandas-map-or-apply/ but I get this error: ValueError: No JSON object could be decoded which happens when executing this line df = pd.concat(pool.map(func, df_split)) Could you please tell me what might be wrong? Are there other ways to work on huge dataset using multithreading?
has comment: http://stackoverflow.com/comment/89785837
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: multithreading
type: Question

http://stackoverflow.com/comment/89842438
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51431160
has text: With `dtype=None` it should create a structured array, 1d, but with as many fields as your `usecols` specifies. Your description of `one column of data...` is unclear. Be more explicit.

http://stackoverflow.com/q/51419201
score: 0
tagged with: user-interface
answer count: 1
has answer: http://stackoverflow.com/a/51419695
accepted answer: http://stackoverflow.com/a/51419695
tagged with: windows
tagged with: python
tagged with: build
type: AnsweredQuestion
has title: Application for windows and mac using python
type: Question
tagged with: desktop-application
has body: I'm in a dilemma. I've got a python code that works for each of the yellow squares shown below but I want to make an application that looks like below and uses the information from the first text box and the second drag and drop box. Then depending on what the user clicked on, the code for that would run. I'm not sure how to approach this. Any help would be greatly appreciated!

http://stackoverflow.com/a/62876618
downvote count: 0
has comment: http://stackoverflow.com/comment/120605561
answers question: http://stackoverflow.com/q/51450134
type: Answer
upvote count: 13
score: 13
has comment: http://stackoverflow.com/comment/137318048
has body: pyvips supports SVG load. It's free, fast, needs little memory, and works on macOS, Windows and Linux. You can use it like this: import pyvips image = pyvips.Image.new_from_file("something.svg", dpi=300) image.write_to_file("x.png") The default DPI is 72, which might be a little low, but you can set any DPI you like. You can write to JPG instead in the obvious way. You can also load by the pixel dimensions you want like this: import pyvips image = pyvips.Image.thumbnail("something.svg", 200, height=300) image.write_to_file("x.png") That will render the SVG to fit within a 200 x 300 pixel box. The docs introduce all the options. The pyvips SVG loader has some nice properties: It uses librsvg for the actual rendering, so the PNG will have high-quality anti-aliased edges. It's much faster than systems like ImageMagick, which simply shell out to inkscape for rendering. It supports progressive rendering. Large images (more than a few thousand pixels a side) are rendered in sections, keeping memory use under control, even for very large images. It supports streaming, so you can render an SVG directly to a huge Deep Zoom pyramid (for example) without needing any intermediate storage. It supports input from memory areas, strings and pipes as well as files. Rendering from strings can be handy, eg.: import pyvips x = pyvips.Image.svgload_buffer(b""" <circle r="100" cx="100" cy="100" fill="#900"/> """) x.write_to_file("x.png")
has comment: http://stackoverflow.com/comment/120620651
has comment: http://stackoverflow.com/comment/120612064
has comment: http://stackoverflow.com/comment/120605757
has comment: http://stackoverflow.com/comment/120612042

http://stackoverflow.com/q/51376326
tagged with: python
has answer: http://stackoverflow.com/a/51376380
has comment: http://stackoverflow.com/comment/89724229
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/89727912
has title: Python: What does parenthesis () after a variable name mean?
has comment: http://stackoverflow.com/comment/89724309
type: Question
has comment: http://stackoverflow.com/comment/89724371
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/89725220
downvote count: 1
has answer: http://stackoverflow.com/a/51376381
has comment: http://stackoverflow.com/comment/89724439
accepted answer: http://stackoverflow.com/a/51376380
favorite count: 0
has body: Towards the bottom at the main loop, I'm seeing this line result = result() But I have no idea what it does and I can't even Google it. What is this? The code below imports from task.py and project.py. But both files do not have anything related to result() hence I'm not including them here. #!/usr/bin/env python3 from task import Task from project import Project main_menu = { 'title': 'MAIN MENU', 'items': ['1. Create a project', '2. Load a project', '3. Quit'], 'actions': { '3': exit, } } project_menu = { 'title': 'PROJECT MENU', 'items': ['1. Add a task', '2. Add task dependency', '3. Set task progress', '4. Show project', '5. Back to Main Menu'], 'actions': { '5': main_menu, } } def select_menu(menu): while True: print() print(menu['title']) #MAIN MENU print('\n'.join(menu['items'])) #1. create project, 2. load project .. selection = input('Select &gt; ') next_action = menu['actions'].get(selection) #print(selection, menu['actions']) if next_action: return next_action else: print('\nPlease select from the menu') def create_project(): global cur_project global project_menu project_name = input('Enter the project name: ') cur_project = Project(project_name) return project_menu main_menu['actions']['1'] = create_project cur_menu = main_menu cur_project = None while True: result = select_menu(cur_menu) while callable(result): result = result() cur_menu = result
has comment: http://stackoverflow.com/comment/89724261
has comment: http://stackoverflow.com/comment/89725532
possible better answer: http://stackoverflow.com/a/51376381

http://stackoverflow.com/q/51468593
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51468726
type: Question
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/51468653
tagged with: arrays
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/51468653
has title: Mapping rows of a Pandas dataframe to numpy array
tagged with: pandas
tagged with: python
favorite count: 0
has body: Sorry, I know there are so many questions relating to indexing, and it's probably starring me in the face, but I'm having a little trouble with this. I am familiar with .loc, .iloc, and .index methods and slicing in general. The method .reset_index may not have been (and may not be able to be) called on our dataframe and therefore index lables may not be in order. The dataframe and numpy array(s) are actually different length subsets of the dataframe, but for this example I'll keep them the same size (I can handle offsetting once I have an example). Here is a picture that show's what I'm looking for: I can pull cols of rows from the dataframe based on some search criteria. idxlbls = df.index[df['timestamp'] == dt] stuff = df.loc[idxlbls, 'col3':'col5'] But how do I map that to row number (array indices, not label indices) to be used as an array index in numpy (assuming same row length)? stuffprime = array[?, ?] The reason I need it is because the dataframe is much larger and more complete and contains the column searching criteria, but the numpy arrays are subsets that have been extracted and modified prior in the pipeline (and do not have the same searching criteria in them). I need to search the dataframe and pull the equivalent data from the numpy arrays. Basically I need to correlate specific rows from a dataframe to the corresponding rows of a numpy array.
upvote count: 1
has answer: http://stackoverflow.com/a/51468726

http://stackoverflow.com/comment/89826117
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51390649
score: 0
has text: then 2. the probability X1 <x < X2 (i.e. x lies between X1 and X2 = integral[X2, X21] f(x) dx, which is taking the value of f(x) at X1 + f(x) at X1 + infinitesimally small delta... up to X2

http://stackoverflow.com/comment/89862715
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51445773
has text: @dfundako I did not create a virtual environment, Since I will only have one django flavor and one django project, I do not need a virtual environment. Also, I have installed Django on my personal system using the same process and without creating virtual environment and it had worked then.
score: 0

http://stackoverflow.com/comment/89785779
score: 0
type: Comment
has text: Nice switch to `object` dtype. Gives access to some string operations that `np.char` doesn't provide.
comment on: http://stackoverflow.com/a/51403826
type: AnswerComment

http://stackoverflow.com/comment/89793573
comment on: http://stackoverflow.com/q/51410961
type: Comment
type: QuestionComment
score: 0
has text: do you always get only two values printed in the `if` condition?

http://stackoverflow.com/comment/89714816
has text: What information do you want the new signal to return to you if you press the n-th row?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51371122
type: Comment

http://stackoverflow.com/q/51430726
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/1463306
accepted answer: http://stackoverflow.com/a/51430766
upvote count: 1
downvote count: 1
type: Question
tagged with: sympy
has body: I am trying to include an exec in a function which creates a variable in order to solve an equation using a simple symbol. However, since the solution is created inside an exec, it creates the error: UnboundLocalError: local variable 'sol' referenced before assignment import sympy as sym import sympy.parsing.latex as sym_tex # requires sympy 1.2 def symbolic_solver(equation, unknown, some_symbol='x'): expr = equation.replace(unknown, some_symbol) eqn = sym_tex.parse_latex(expr) exec('%s = sym.Symbol("%s")'%(some_symbol, some_symbol)) try: # Sometimes Sympy throws a notimplemented error when it can not solve exec('sol = sym.solve(eqn, %s)'%(some_symbol)) except NotImplementedError: print('SymPy could not solve the equation.') print('Set the solution manually.') return sol equation = 'm\\cdot g\\cdot h_A + \\frac{1}{2}\\cdot m\\cdot {v_A}^2 = m\\cdot g\\cdot h_B + \\frac{1}{2}\\cdot m\\cdot {v_B}^2' unknown = 'v_B' sol = symbolic_solver(equation, unknown) The reason I have to replace the unknown variable in an equation is because SymPy solver can not handle variables which may have subscript, e.g. v_B. In any case, when I don't use a function, simply run it as a script it produces the following solution: Solution symbolic: [-sqrt(2*g*h_A - 2*g*h_B + v_A**2), sqrt(2*g*h_A - 2*g*h_B + v_A**2)]
score: 0
answer count: 1
has title: Handling exec inside functions for symbolic computations
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51430766

http://stackoverflow.com/q/51372002
has body: I am pretty capable of coding in python but want to start using C for some of my functions. Using ctypes I can open a DLL and use the functions quite easily. Searching for a simple C example of this equivalent seems impossible. I always find 2 page C++ examples full of boiler-plate code and can't really tell what is happening. Or worse, .Net and visual studio examples that import all sorts of dependencies. Below is the python code that works fine including the API documentation of a function of the DLL. from the API Doc: Mcp2210_GetLibraryVersion int Mcp2210_GetLibraryVersion(wchar_t *version) Description: Provides the library version as NULL terminated UNICODE string. Parameters: Inputs: - none Outputs: - wchar_t *version - Pointer to buffer string of 64 bytes (MPC2210_LIBRARY_VERSION_SIZE) in size (So it can accommodate max 30 wide characters.) The version string, including the NULL terminator is copied in this buffer. Cannot be NULL. Returns: - positive value: version string size (bytes) including the null character - negative value: E_ERR_NULL (-10) if *version is NULL from ctypes import windll, c_wchar, byref # bring in some ctypes objects version = (c_wchar * 64)() # declare 64 index array to put unicode characters into mcp2210_dll = windll.LoadLibrary("mcp2210_dll_um_x86.dll") # get a handle to the dll ret_code = mcp2210_dll.Mcp2210_GetLibraryVersion(byref(version)) # call the function print(ret_code, version.value) # display results outputs -&gt; (12, u'2.1.0') below is my failed attempt at using this dll in code::blocks #include &lt;windows.h&gt; #include &lt;stdio.h&gt; #include "mcp2210_dll_um.h" int main() { HINSTANCE hinstDLL; hinstDLL = LoadLibrary("mcp2210_dll_um_x86.dll"); if (hinstDLL != 0){ printf("DLL loaded ok"); char *version; int VersionFunction; VersionFunction = GetProcAddress(hinstDLL, "Mcp2210_GetLibraryVersion"); VersionFunction(*version); printf(version); } else{ return -1; } FreeLibrary(hinstDLL); return 0; } It seems to build and load t…
answer count: 1
downvote count: 0
has title: C dll equivalent to python ctypes
accepted answer: http://stackoverflow.com/a/51372508
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51372508
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
tagged with: ctypes
tagged with: dll
has comment: http://stackoverflow.com/comment/89716589
tagged with: http://stackoverflow.com/tag/c

http://stackoverflow.com/q/51332873
linked to: http://stackoverflow.com/q/231767
answer count: 0
has body: I am working with a Pandas dataframe and iterating over the rows to find relevant data, in this case, colors. For the most part, the 'Color' column's cell will be filled out, in which case I do not need to search other cells in the row for colors and can continue to the next row. However, if no 'Color' column is present, Pandas will raise a KeyError and I will need to create the column and add values to it. Here is a snippet of my code: class Reader(object): def __init__(self, dataframe): """Grabs column headers, converts dataframe from unicode string objects to Python string objects, sets dataValues class variable equal to a numpy array of the sheet""" self.headers = dataframe.columns.values self.dataFrame = dataframe.applymap(str) self.dataValues = self.dataFrame[:].values class Extractor(object): """Extracts relevant spec information from a sku (row)""" def getColor(self, colorRef): """Looks in Model Name and Description for color information. Uses pre-existing color database (colorRef). Returns dataFrame column 'Color' """ index = 0 newColorArray = [] #this will not be returned, its sole purpose is to keep track of colors for sku in myData.dataValues: try: if myData.dataFrame.iloc[index, myData.dataFrame.columns.get_loc('Color') != ('' or ' '): continue #color exists, move to next row except KeyError: newColorArray = ['']*myData.dataFrame.shape[0] #Remaining code searches for colors When I try to execute that block of code, I get a SyntaxError. I have read e-satis's comment but, if I understand yield correctly, this will terminate the function and not this iteration of the loop. Is what I am trying to do even possible in Python? I do not have a lot of practice using objects and classes, so if you'd like to give me feedback there as well, please do.
type: Question
tagged with: try-catch
has comment: http://stackoverflow.com/comment/89641206
tagged with: continue
score: 0
tagged with: pandas
has title: Using continue in try/except statement
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89641293
tagged with: python

http://stackoverflow.com/comment/129257751
type: Comment
comment on: http://stackoverflow.com/a/72335602
has text: the total time complexity of this solution will still be `O(N^2)` since you have the nested for loop. The space complexity of this solution will also be `O(N^2)`
score: 0
type: AnswerComment

http://stackoverflow.com/a/51350214
upvote count: 6
type: Answer
has body: Python has a different order of operations than you think here. It seems you should change your definition to bar = (lambda x: x + 1) if foo else (lambda x: x + 2) What you were actually getting with your definition was bar = lambda x: (x + 1 if foo else lambda x: x + 2) In other words, you were returning a function, and if foo is true the function returns the value of x+1 but if it is false it returns the function lambda x: x + 2. What you really wanted was to return one of two functions, which the modified definition does. The moral of this story: use plenty of parentheses to make your intentions clear. A comment to your question suggests another possibility: bar = lambda x: x + 1 if foo else x + 2 which is equivalent to bar = lambda x: (x + 1 if foo else x + 2) This is not the same as my suggestion. My suggestion, when executed, returns one of two functions. One function always adds one, the other always adds 2, and which function is returned depends on the value of foo when the definition line is executed. The alternative here returns just one function, and this function adds one or two depending on the value of foo when the function is evaluated. Do you see the difference? The alternative changes more frequently. Only you can say which of these meets your needs.
accepted answer of: http://stackoverflow.com/q/51350179
downvote count: 0
answers question: http://stackoverflow.com/q/51350179
score: 6
type: AcceptedAnswer

http://stackoverflow.com/comment/89691517
type: QuestionComment
has text: Did you have a look at the linked webpage? It would be good to see the code. From the description it is very hard to say what you did and what you are trying to achieve.
comment on: http://stackoverflow.com/q/51359475
score: 0
type: Comment

http://stackoverflow.com/q/51421916
has comment: http://stackoverflow.com/comment/89816422
answer count: 1
favorite count: 0
type: UnansweredQuestion
score: -4
has answer: http://stackoverflow.com/a/51422379
tagged with: python
tagged with: dictionary
has title: Insert a value in date format dd-mm-yyyy in dictionary in python
has comment: http://stackoverflow.com/comment/89814684
has comment: http://stackoverflow.com/comment/89814889
type: Question
has comment: http://stackoverflow.com/comment/89815157
upvote count: 0
has body: I am creating a dictionary having some values including a date of birth of a person. But when I run my code, it is giving an error "datetime.datetime has no attribute datetime" . Here is my code: import re from datetime import date import datetime from datetime import datetime userDetails=[] dateOfBith='9-9-1992' #datetimeparse = datetime.strptime(dateOfBith,'%dd-%mm-%yyyy') datetimeparse = datetime.datetime.strptime(dateOfBith, '%Y-%m-%d').strftime('%d/%m/%y') dateparse = datetime(datetimeparse) accountDetails= {"FirstName": "ajay", "LastName": "kumar","Account Number":"4242342345234","Balance Currency":"Rs","Balance Amount":"5000"} accountDetails["DateOfBirth"] = dateparse
downvote count: 4

http://stackoverflow.com/q/51341440
tagged with: python
has comment: http://stackoverflow.com/comment/89663502
has comment: http://stackoverflow.com/comment/89663461
tagged with: mysql-connector-python
tagged with: python-3.x
upvote count: 2
tagged with: mysql
has answer: http://stackoverflow.com/a/51341556
answer count: 1
has comment: http://stackoverflow.com/comment/89656519
score: 2
has comment: http://stackoverflow.com/comment/89656469
downvote count: 0
type: UnansweredQuestion
has body: I'm inserting millions of rows in MySQL using Python3 but I found the memory usage keeps growing and finally reached 64GB. I tried to diagnose the problem and here is a reproduction of the problem: say I have 100 CSV files. Each file contains 50000 rows and I want to insert them into the database. Here is a sample code: import mysql.connector insert_sql = ("INSERT INTO table (Value) VALUES (%s)") for i in range(100): cnx = mysql.connector.connect(user='root', password='password', host='127.0.0.1', database='database') cursor = cnx.cursor() # Insert 50000 rows here for j in range(50000): cursor.execute(insert_sql, (j,)) cnx.commit() cursor.close() cnx.close() print('Finished processing one file') print('All done') The database contains only 1 table with 2 columns: CREATE TABLE `table` ( `Id` int(11) NOT NULL AUTO_INCREMENT, `Value` int(11) NOT NULL, PRIMARY KEY (`Id`) ) Environment: Mac OS Sierra; Python 3.6.x; MySQL 8.0.1; mysql-connector-python 8.0.11 I understand the memory should grow before committing because the changes are buffered. But I supposed it will decrease after the committing. However, it doesn't. Since in my real application I have thousands of files with 100MB each, my memory will blow up. Did I do anything wrong here? (I'm new to database) How can I keep the memory usage under control? Any suggestion will be appreciated! Edit: I also tried the following code according to the comments and answers but it still doesn't work: import mysql.connector insert_sql = ("INSERT INTO table (Value) VALUES (%s)") for i in range(100): cnx = mysql.connector.connect(user='root', password='password', host='127.0.0.1', database='database') cursor = cnx.cursor() params = [(j,) for j in range(50000)] # If I don't excute the following insertion, the memory is stable. cnx.executemany(insert_sql, params) cnx.commit() cursor.close() del cursor cnx.close() del cnx print('Finished processing one file') print('All done')
favorite count: 0
has title: Python mysql memory leak in insertion
type: Question
tagged with: memory-leaks

http://stackoverflow.com/comment/89649046
has text: `flatten` is indeed called recursively, though. Maybe a bug because called inside list comprehension?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51337082
score: 0

http://stackoverflow.com/a/51460157
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89889597
has body: If the player guess is correct on the first try, your while loop will not execute. As your print statement is nested within the while loop, it will only be executed if the first guess is incorrect (in which case it will then be executed irrespective of whether the users guess is correct or not. Dedent your print and it should work fine.
upvote count: 1
has comment: http://stackoverflow.com/comment/89889574
answers question: http://stackoverflow.com/q/51460138
type: Answer

http://stackoverflow.com/a/51345522
has body: Yep! It's possible! Your Python function will have to change though, as there is an implicit return of value None when printing to the console. Your Python function should look like this: def do_greet(self,line): return "Welcome to the interactive prompt user\n" In Bash (and CMD), commands are run from Python like so: python -c "import filename; print(do_greet(argument1, argument2))" Filename is just the name of the file, without the .py extension. Make sure you're in the right directory and Python3 is in your environment variables. To run this as a for loop in Bash, it'll look like this: $ for i in {1..5}; do python -c "import filename; print(filename.do_greet(arg1, arg2))"; done If you're using Python2, it should look the same, except the print statement won't have parentheses: $ for i in {1..5}; do python -c "import filename; print filename.do_greet(arg1, arg2)"; done
has comment: http://stackoverflow.com/comment/89666347
has comment: http://stackoverflow.com/comment/89664817
answers question: http://stackoverflow.com/q/51345198
score: 0
has comment: http://stackoverflow.com/comment/89664942
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89664969
accepted answer of: http://stackoverflow.com/q/51345198
has comment: http://stackoverflow.com/comment/89664767
type: Answer
has comment: http://stackoverflow.com/comment/89664913

http://stackoverflow.com/comment/89674596
comment on: http://stackoverflow.com/a/51350886
has text: i have anaconda for python 3 installed and it works without any installation. you can you that or refer the link which i gave.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51471636
score: 3
has comment: http://stackoverflow.com/comment/89914088
has body: considering id is the index, df['new']=np.where(df.iloc[:,1:].eq(0).all(1),0,-1)
upvote count: 3
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51471573
downvote count: 0
answers question: http://stackoverflow.com/q/51471573

http://stackoverflow.com/comment/89703777
type: AnswerComment
score: 0
type: Comment
has text: Correct; that's "solution weight". Once we've accounted for each item, the problem reduces to items earlier in the list, with that remaining weight.
comment on: http://stackoverflow.com/a/51331295

http://stackoverflow.com/q/51479418
has body: I want to know web link in jira issue, in the same section of jira issue. I try this , but I get an error jira.add_simple_link(issue_edit, { "object": { "url":"http://www.mycompany.com/support?id=1", "title":"Crazy customer support issue" } }) jira.utils.JIRAError: JiraError HTTP 400 text: 'URL' is required., 'Link Text' is required Thanks
answer count: 1
tagged with: python
type: UnansweredQuestion
tagged with: jira
type: Question
has title: Add web link in jira issue
tagged with: hyperlink
has answer: http://stackoverflow.com/a/51669593
score: 0

http://stackoverflow.com/comment/89897324
comment on: http://stackoverflow.com/a/51463945
type: AnswerComment
score: 0
type: Comment
has text: Replace round with ceil and it will work since your code only uses .5's when there are decimals

http://stackoverflow.com/comment/89653244
has text: Works for me on Linux python3.7, pip installed certifi-2018.4.16 chardet-3.0.4 gevent-1.3.4 greenlet-0.4.13 grequests-0.3.0 idna-2.7 requests-2.19.1 urllib3-1.23. Given that 3.7 is very new I'd be suspicious that it might be related. Segfault sounds more like a library/ABI issue than memory, but I'm not an expert on low-level stuff. That's all I've got I'm afraid.
comment on: http://stackoverflow.com/q/51338756
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/51431308
answer count: 2
has comment: http://stackoverflow.com/comment/89833673
downvote count: 1
has answer: http://stackoverflow.com/a/51431482
linked to: http://stackoverflow.com/q/23337471
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/20274987
upvote count: 4
has comment: http://stackoverflow.com/comment/89835207
tagged with: assert
has answer: http://stackoverflow.com/a/51431350
score: 3
has title: what is the properly assert to fail test when exception occur?
has comment: http://stackoverflow.com/comment/89834890
favorite count: 0
has comment: http://stackoverflow.com/comment/89833621
type: Question
has comment: http://stackoverflow.com/comment/89833762
has comment: http://stackoverflow.com/comment/89833708
tagged with: python
tagged with: pytest
has body: I would like testcase pass when no particular exception raise and make testcase only failed when ValueError occurs. get some information from another post feel like maybe there is a better way than try/except How to properly assert that an exception gets raised in pytest? def test_exception(): try: call some function: except ValueError: assert False

http://stackoverflow.com/comment/89780773
type: AnswerComment
comment on: http://stackoverflow.com/a/51371737
score: 0
type: Comment
has text: You need to install Jython. That is the only way

datetime
tags question: http://stackoverflow.com/q/51326314
tags question: http://stackoverflow.com/q/51474263
tags question: http://stackoverflow.com/q/51444121
tags question: http://stackoverflow.com/q/51392909
tags question: http://stackoverflow.com/q/51338543
tags question: http://stackoverflow.com/q/51395590
tags question: http://stackoverflow.com/q/51361732
tags question: http://stackoverflow.com/q/51461337
tags question: http://stackoverflow.com/q/51382266
tags question: http://stackoverflow.com/q/51431527
tags question: http://stackoverflow.com/q/51411362
tags question: http://stackoverflow.com/q/51476061
tags question: http://stackoverflow.com/q/51420042
tags question: http://stackoverflow.com/q/51411971
tags question: http://stackoverflow.com/q/51415742
tags question: http://stackoverflow.com/q/51343370
tags question: http://stackoverflow.com/q/51327498
tags question: http://stackoverflow.com/q/51407293
tags question: http://stackoverflow.com/q/51482381
tags question: http://stackoverflow.com/q/51351718
tags question: http://stackoverflow.com/q/51447695
tags question: http://stackoverflow.com/q/51434887
tags question: http://stackoverflow.com/q/51331959
tags question: http://stackoverflow.com/q/51474924
tag name: datetime
tags question: http://stackoverflow.com/q/51340219
tags question: http://stackoverflow.com/q/51387213
tags question: http://stackoverflow.com/q/51380386
tags question: http://stackoverflow.com/q/51330040
tags question: http://stackoverflow.com/q/51356927
type: Tag
tags question: http://stackoverflow.com/q/51326863
tags question: http://stackoverflow.com/q/51382298
tags question: http://stackoverflow.com/q/51454343
tags question: http://stackoverflow.com/q/51468057
tags question: http://stackoverflow.com/q/51459205
tags question: http://stackoverflow.com/q/51375564
tags question: http://stackoverflow.com/q/51463903
tags question: http://stackoverflow.com/q/51415222
tags question: http://stackoverflow.com/q/51437491
tags question: http://stackoverflow.com/q/51392012
tags question: http://stackoverflow.com/q/51388783
tags question: http://stackoverflow.com/q/51345286
tags question: http://stackoverflow.com/q/51457944

http://stackoverflow.com/q/51369750
accepted answer: http://stackoverflow.com/a/51369878
tagged with: pandas
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51369878
tagged with: python
has body: Trying to Decode the following Hex Code to Ascii j =['[binary]'] hex_to_ascii = bytes.fromhex(j) the following is throwing an error - ValueError: non-hexadecimal number found in fromhex() arg at position 1 if any one can help with issue.
tagged with: hex
type: AnsweredQuestion
upvote count: 2
score: 1
has title: Python ValueError: non-hexadecimal number found in fromhex() arg at position 1
downvote count: 1
type: Question

http://stackoverflow.com/comment/89876586
type: QuestionComment
has text: Can you post the stack trace?
score: 0
comment on: http://stackoverflow.com/q/51453073
type: Comment

http://stackoverflow.com/comment/89640132
type: Comment
comment on: http://stackoverflow.com/q/51331764
has text: Do you already have a generator for such curves? If so, could you add it to the question? It could come in handy to those that attempt to answer.
score: 0
type: QuestionComment

http://stackoverflow.com/a/51393890
type: Answer
score: 2
downvote count: 0
has body: I think you can use groupby with SeriesGroupBy.value_counts: s = df.groupby(['ID','group'])['categories'].value_counts() print (s) ID group categories 1 0 blue 2 red 1 2 1 blue 1 red 1 3 0 red 1 1 green 1 4 0 red 1 1 green 1 red 1 Name: categories, dtype: int64 out = s[s &gt; 1].reset_index(name='count') print (out) ID group categories count 0 1 0 blue 2 Another solution is get duplicates first by filtering with duplicated and then count: df = df[df.duplicated(['ID','group','categories'], keep=False)] print (df) ID group categories 4 1 0 blue 5 1 0 blue df1 = df.groupby(['ID','group'])['categories'].value_counts().reset_index(name='count') print (df1) ID group categories count 0 1 0 blue 2 EDIT: For count categories (all rows) per ID use GroupBy.size: df1 = df.groupby('ID').size().reset_index(name='count') print (df1) ID count 0 1 3 1 2 2 2 3 2 3 4 3
answers question: http://stackoverflow.com/q/51393610
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51393610
type: AcceptedAnswer

http://stackoverflow.com/a/51328145
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/51327792
has body: Here's a more general solution that doesn't require the lists being sliceable, so you can use it on other iterables, like generators. We keep a deque the size of the start sequence until we come across it. Then we add those values to a list, and keep iterating over the sequence. As we do, we keep a deque the size of the end sequence, until we see it, also adding the elements to the list we're keeping. If we come across the end sequence, we yield that list and set the deque up to scan for the next start sequence. from collections import deque def gen(l, start, stop): start_deque = deque(start) end_deque = deque(stop) curr_deque = deque(maxlen=len(start)) it = iter(l) for c in it: curr_deque.append(c) if curr_deque == start_deque: potential = list(curr_deque) curr_deque = deque(maxlen=len(stop)) for c in it: potential.append(c) curr_deque.append(c) if curr_deque == end_deque: yield potential curr_deque = deque(maxlen=len(start)) break print(list(gen([99, 99, 1, 2, 3, 99, 99, 99, 4, 5, 6, 99, 99, 1, 2, 3, 99, 4, 5, 6, 99], [1,2,3], [4,5,6]))) # [[1, 2, 3, 99, 99, 99, 4, 5, 6], [1, 2, 3, 99, 4, 5, 6]]
has comment: http://stackoverflow.com/comment/89631852
downvote count: 0
type: Answer

http://stackoverflow.com/comment/89884972
score: 0
type: Comment
type: QuestionComment
has text: @darthbith That unfortunately didn't work. I read through the whole thread you linked trying all the proposed solutions (of which there were only about 2 or 3, and the rest of the posts were people complaining) and didn't find anything that worked. Given the longevity of this issue of the incompatibility of Anaconda and graphviz, I have decided that I'm just going to uninstall Anaconda and use a different distribution...
comment on: http://stackoverflow.com/q/51447235

http://stackoverflow.com/q/51413877
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89820243
has body: for codes like in a some.py: if __name__ == '__main__': parser = argparse.ArgumentParser() # ... args = parser.parse_args() foo() I'm using nosetests --with-coverage to collect results. but the 'main' codes are not covered, how to test codes here, or omit nose coverage?
has comment: http://stackoverflow.com/comment/89799282
type: Question
has comment: http://stackoverflow.com/comment/89802551
has title: how to test python's "__main__" codes with nose
score: 0
tagged with: nose
answer count: 0
tagged with: code-coverage

http://stackoverflow.com/comment/89851078
score: 0
type: Comment
type: QuestionComment
has text: The problem is that I don't want to include the password in the form but if I don't include it, the user can't update the information, so I thought of hard-coding the html
comment on: http://stackoverflow.com/q/51440311

http://stackoverflow.com/q/51416685
has body: I have a large image from which I need to extract some information. I am using Python opencv library for image enhancement. Using opencv methods I extracted a part of the image that interests me. It is given below. Tesseract is not able to distinguish between 0 and O. It is giving output as all zeroes. I tried with --psm options 6 and others, but to no avail. I am using the latest stable release of tesseract (v3) on windows. I am continuing to work on this problem. Any help would be appreciated. Thanks. EDIT: I found a solution for this. Used box output from tesseract. Need to give makebox as an argument to tesseract command. The box output contains the X and Y coordinates of a 'box' around each character read. I derived the ratio of width to height and with some input images trained a Logistic Regression Model to predict the output a 0 or O. Then I used this trained model for test images and it worked like a charm.
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/100873907
downvote count: 0
has comment: http://stackoverflow.com/comment/124692219
has comment: http://stackoverflow.com/comment/89807996
favorite count: 0
has title: Tesseract not able to distinguish between zero and O
has comment: http://stackoverflow.com/comment/89816842
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89805276
tagged with: tesseract
has comment: http://stackoverflow.com/comment/89805420
score: 2

http://stackoverflow.com/a/51355597
answers question: http://stackoverflow.com/q/51355425
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: Try this: lines = [line.rstrip('\n') for line in open('text.txt')] output = open('a.txt', 'w') for line in lines: line = line.split() # subtract 10 from all of the components in the first column line[0] = int(line[0]) - 10 # subtract 1 from all of the components in the rest of the columns line[1:] = [int(n) - 1 for n in line[1:]] output.write('Values({},{},{},{},{});\n'.format(*line)) output.close()
type: Answer
accepted answer of: http://stackoverflow.com/q/51355425

http://stackoverflow.com/a/51354501
has comment: http://stackoverflow.com/comment/89681450
has comment: http://stackoverflow.com/comment/89681446
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51354466
has body: The np.argsort function gives you the indices of the array in sorted order -- use the indices -- &gt;&gt;&gt; ages = np.random.randint(low=20, high=60, size=10) &gt;&gt;&gt; heights = np.random.randint(low=150, high=200, size=10) &gt;&gt;&gt; ages array([44, 35, 37, 39, 48, 24, 22, 25, 22, 59]) &gt;&gt;&gt; heights array([179, 195, 158, 189, 183, 185, 186, 187, 161, 175]) &gt;&gt;&gt; ia = np.argsort(ages) &gt;&gt;&gt; ages[ia] array([22, 22, 24, 25, 35, 37, 39, 44, 48, 59]) &gt;&gt;&gt; heights[ia] array([186, 161, 185, 187, 195, 158, 189, 179, 183, 175]) Note, in this case, you might consider a structured array: &gt;&gt;&gt; mytype = np.dtype([('age',int), ('height', int)]) &gt;&gt;&gt; data = np.array(list(zip(ages, heights)), dtype=mytype) &gt;&gt;&gt; data array([(44, 179), (35, 195), (37, 158), (39, 189), (48, 183), (24, 185), (22, 186), (25, 187), (22, 161), (59, 175)], dtype=[('age', '&lt;i8'), ('height', '&lt;i8')]) And now you can pass the "order" argument to .sort: &gt;&gt;&gt; data.sort(order='age') &gt;&gt;&gt; data array([(22, 161), (22, 186), (24, 185), (25, 187), (35, 195), (37, 158), (39, 189), (44, 179), (48, 183), (59, 175)], dtype=[('age', '&lt;i8'), ('height', '&lt;i8')]) However, this isn't exactly equivalent as above, since it uses the height to break ties, so note, (22, 161) comes before (22, 186) here.

http://stackoverflow.com/a/51344686
type: Answer
has body: Yes, the two apps I know of are py2exe and PyInstaller. I'm pretty sure both support Python 3 and can store dependencies, libraries, etc. I recommend this link for more info: Making a Stand Alone Executable from a Python Script using PyInstaller
has comment: http://stackoverflow.com/comment/89667204
answers question: http://stackoverflow.com/q/51344299
score: 0

http://stackoverflow.com/a/51406030
has comment: http://stackoverflow.com/comment/89783667
has comment: http://stackoverflow.com/comment/89783482
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/89783543
downvote count: 0
has comment: http://stackoverflow.com/comment/89783788
answers question: http://stackoverflow.com/q/51391328
has comment: http://stackoverflow.com/comment/89784330
has body: I think you’re overcomplicating things. Your end goal is that the library and application are both distributed separately, to be installed by pip. To make that work, they just need to be separate packages that have their own separate setup.py, and the application has the library in its ‘requirements.txt`. And, once you do that, it solves your development issue as well. Create a virtual environment, and just pip install the library into that env while working on the app. There’s no need to manually symlink or copy anything anywhere. Or to write your tests in such a way that they can work with both an installed library and a relative-pathed library. Or anything else. And no messing with sys.path; the library is in the venv’s site-packages, which is already in sys.path. Making all of this just work is the whole point of virtual environments. You don’t even need anything complicated in the readme. People just installing the app with pip (whether systemwide or in a venv) will get the library automatically. People working in the app can treat the library the same way they treat any other dependency. (They should already know how to create a venv and install requirements.txt into it.) The only real issue would be people working on the library who aren’t interested in the app but are using it as test code for the library—but you can just make that unnecessary by including sufficient test code with the library itself (which you probably want to do anyway). If there’s a reason this won’t work for you, you can look at building a versioned subpackage out of the independent library package, the way requests does with urllib3 or bs4 does with unicodedamnit. But from your description, I don’t see any indication that you need that. I think your problem may be that you think pip can only install distributed packages off PyPI or another pip repo. In fact, it's a lot more flexible than that. As the User Guide says: pip supports installing from PyPI, version control, local projects, an…
type: Answer
has comment: http://stackoverflow.com/comment/89784102

http://stackoverflow.com/comment/89827932
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51408552
has text: Two things to be noted: Firstly, what you are doing is not recursive but sequential in nature. Secondly, calculations in your columns are independent for columns irrespective of where you initiate the moving average. Also, a query regarding your post: if i understand your requirement correctly: you need a simple way to obtain the same result from your expansion of the original equation, right ??

http://stackoverflow.com/a/51355821
has comment: http://stackoverflow.com/comment/89689302
has comment: http://stackoverflow.com/comment/89688572
accepted answer of: http://stackoverflow.com/q/51354714
answers question: http://stackoverflow.com/q/51354714
has comment: http://stackoverflow.com/comment/89689537
has comment: http://stackoverflow.com/comment/89689423
has body: This would do the job of what you trying to get from the code i.e trying to get the names as could be infered from the code from requests import get from bs4 import BeautifulSoup # variables count = 1 # lists to store data names = [] gp = [] arenaRank = [] url = 'https://swgoh.gg/g/21284/gid-1-800-druidia/' response = get(url) soup = BeautifulSoup(response.content, 'html.parser') for users in soup.findAll('strong'): if users.text.strip().encode("utf-8")!= '': names.append(users.text.strip().encode("utf-8")) print(names)
score: 0
has comment: http://stackoverflow.com/comment/89689135
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89689131
type: Answer
has comment: http://stackoverflow.com/comment/89688837

http://stackoverflow.com/q/51446299
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/89862936
has comment: http://stackoverflow.com/comment/89862895
tagged with: list
has comment: http://stackoverflow.com/comment/89862960
score: 1
has body: For Example: books = [{'name':'pearson', 'price':60, 'author':'Jesse Pinkman'},{'name':'ah publications', 'price':80, 'author':'Gus Fring'},{'name':'euclidean', 'price':120, 'author':'Skyler White'},{'name':'Nanjial', 'price':260, 'author':'Saul Goodman'}] I need to insert each dictionary into already created table by just taking 'author','price' I have like 100k records to be inserted into table. Right now what I am doing is to loop through the list of dictionaries and take the required key/value pair and insert one by one def insert_books(self, val): cur = self.con.cursor() sql = """insert into testtable values {}""".format(val) cur.execute(sql) self.con.commit() cur.close() for i in books: result = i['author'],i['price'] db_g.insert_books(result) #db_g is class - connection properties So is there a faster and easier way to bulk insert the data like 10k at a time?
has title: Bulk Insert Data from List of Dictionaries into Postgresql database [Faster Way]?
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89863738
has answer: http://stackoverflow.com/a/51446967
has comment: http://stackoverflow.com/comment/89862986
linked to: http://stackoverflow.com/q/44041143
linked to: http://stackoverflow.com/q/37058984
downvote count: 0
answer count: 1

http://stackoverflow.com/q/51389086
has answer: http://stackoverflow.com/a/51389168
has comment: http://stackoverflow.com/comment/89750305
tagged with: pandas
tagged with: python
score: -2
has body: I have two dataframes: lang_df = pd.DataFrame(data = {'Content ID': [1, 1, 2, 2, 3, 3], 'User ID': [10, 11, 10, 11, 10, 11], 'Language': ['A', 'A', 'B', 'B', 'C', 'C']}) pred_df = pd.DataFrame(data = {'Content ID': [4, 7, 14, 6, 6, 6], 'User ID': [10, 11, 10, 11, 10, 11], 'Language': ['A', 'D', 'Z', 'B', 'B', 'A']}) I want to filter out the rows in the second dataframe so that users only get content IDs in languages they have previously watched. Result for this example would look like: result_df = pd.DataFrame(data = {'Content ID': [4, 6, 6, 6], 'User ID': [10, 11, 10, 11], 'Language': ['A', 'B', 'B', 'A']}) I know how to do it using a for loop, but this seems highly inefficient. Not sure how to make the DFs appear in the question for better clarity.
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51389177
has comment: http://stackoverflow.com/comment/89750326
upvote count: 1
accepted answer: http://stackoverflow.com/a/51389177
type: AnsweredQuestion
has title: Filter Model Prediction DataFrame
downvote count: 3
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89750276
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/51389168
has comment: http://stackoverflow.com/comment/89750228

http://stackoverflow.com/a/51398390
answers question: http://stackoverflow.com/q/51397109
has comment: http://stackoverflow.com/comment/119509890
has body: Using ncfirth's link, I was able to modify the code there so that it fits to my problem: from sklearn.tree._tree import TREE_LEAF def is_leaf(inner_tree, index): # Check whether node is leaf node return (inner_tree.children_left[index] == TREE_LEAF and inner_tree.children_right[index] == TREE_LEAF) def prune_index(inner_tree, decisions, index=0): # Start pruning from the bottom - if we start from the top, we might miss # nodes that become leaves during pruning. # Do not use this directly - use prune_duplicate_leaves instead. if not is_leaf(inner_tree, inner_tree.children_left[index]): prune_index(inner_tree, decisions, inner_tree.children_left[index]) if not is_leaf(inner_tree, inner_tree.children_right[index]): prune_index(inner_tree, decisions, inner_tree.children_right[index]) # Prune children if both children are leaves now and make the same decision: if (is_leaf(inner_tree, inner_tree.children_left[index]) and is_leaf(inner_tree, inner_tree.children_right[index]) and (decisions[index] == decisions[inner_tree.children_left[index]]) and (decisions[index] == decisions[inner_tree.children_right[index]])): # turn node into a leaf by "unlinking" its children inner_tree.children_left[index] = TREE_LEAF inner_tree.children_right[index] = TREE_LEAF ##print("Pruned {}".format(index)) def prune_duplicate_leaves(mdl): # Remove leaves if both decisions = mdl.tree_.value.argmax(axis=2).flatten().tolist() # Decision for each node prune_index(mdl.tree_, decisions) Using this on a DecisionTreeClassifier clf: prune_duplicate_leaves(clf) Edit: Fixed a bug for more complex trees
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/94747114
has comment: http://stackoverflow.com/comment/119546085
upvote count: 18
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51397109
score: 18

http://stackoverflow.com/a/51420004
upvote count: 2
has body: The table is rendered using Javascript, thus it doesn't show up in the initial HTML that is loaded by urllib. You could either find the API the page is using and get the data from there or use a headless browser to get the full Javascript rendered HTML.
type: Answer
answers question: http://stackoverflow.com/q/51419743
has comment: http://stackoverflow.com/comment/89814724
downvote count: 0
score: 2

http://stackoverflow.com/a/51460999
type: AcceptedAnswer
has body: You have missing data in your column, represented by NaNs (which are of float type). Don't use map/apply, etc for things like finding the length, just do this with str.len: df['address'].str.len() Items for which len() is not applicable automatically show in the result as NaN. You can fillna(-1) those out to indicate the result is invalid there.
answers question: http://stackoverflow.com/q/51460881
upvote count: 10
type: Answer
downvote count: 0
score: 10
has comment: http://stackoverflow.com/comment/89902792
accepted answer of: http://stackoverflow.com/q/51460881

http://stackoverflow.com/a/51430049
score: 3
type: Answer
upvote count: 3
has comment: http://stackoverflow.com/comment/89831127
has body: Calculate the max cost, then use a list comprehension: from operator import itemgetter max_cost = max(map(itemgetter('cost'), fruits)) # or max_cost = max(i['cost'] for i in fruits) res = [i for i in fruits if i['cost'] == max_cost] print(res) [{'nama': 'oranges', 'id': 9635, 'cost': 23}, {'nama': 'oranges', 'id': 989, 'cost': 23}]
accepted answer of: http://stackoverflow.com/q/51429969
answers question: http://stackoverflow.com/q/51429969
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/51441743
answers question: http://stackoverflow.com/q/51441050
type: Answer
score: 0
has body: in python 3.x you have to add bytes(your bytes).encode rather than the previous 2.x format. it becomes test = fmt.unpack_from(bytes(''.join('\0' for i in range(fmt.size)).encode()))

http://stackoverflow.com/a/51464064
type: Answer
has body: The problem you have it's in the views. Django template has to be rendered by a view, from this view is where you get the data to be rendered in the template. It doesn't matter which url you want to use and which template you are using in the views. What this means is that you can have different urls pointing to the same template (www.example.com/blog/ or www.example.com/programming/) and both render the same template. If i understood you right, all you have to do is change this : url(r'^$', views.post_list, name='post_list'), url(r'^programowanie/$', views.programowanie, name='programowanie'), To this: url(r'^$', views.post_list, name='post_list'), url(r'^programowanie/$', views.post_list, name='programowanie'), You can refer to the official Django website in order to get more information about this : https://docs.djangoproject.com/en/2.0/intro/tutorial03/
answers question: http://stackoverflow.com/q/51463999
accepted answer of: http://stackoverflow.com/q/51463999
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89897057

http://stackoverflow.com/q/51404540
has comment: http://stackoverflow.com/comment/89780081
has answer: http://stackoverflow.com/a/51404692
has comment: http://stackoverflow.com/comment/89780260
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51404678
linked to: http://stackoverflow.com/q/15491894
type: Question
has title: Isolating parts of strings that are in a date format
possible better answer: http://stackoverflow.com/a/51404647
has body: I'm getting information from a website that has no API or anything. I've got the login and retrieve HTML part working and I've got a system that finds the right that will contain the information I need. But I need to remove all the information that isn't in the format "DD/MM/YYYY". So I need to remove all the parts of this string that aren't in that format. Here's an example of the returned : Week 29-16/07/2018 Week 30-23/07/2018 The parts that will change each week are the id="YYYY_WW" and Week WW-DD/MM/YYYY. So from the above example, I'm after two dates: 16/07/2018 and 23/07/2018. Please bear in mind that there could be between 1 and 4 dates within this so it won't always be two weeks that I need to extract. I would also ideally have each date retrieved printed on a new line. Any ideas how I'd go about this? Thanks in advance for any replies :)
tagged with: python-2.7
score: 0
answer count: 3
accepted answer: http://stackoverflow.com/a/51404678
tagged with: python
has answer: http://stackoverflow.com/a/51404647

http://stackoverflow.com/q/51409043
tagged with: python
score: 2
upvote count: 2
type: UnansweredQuestion
has title: Python PrettyTable with multiple header/ title
type: Question
has body: I am able to create a python PrettyTable with a title and table fields. But, I want to create multiple sections in a single table i.e have multiple header (or html rowspan/ colspan to merge cells inorder to create sections). Any pointers for that? Currently, I am able to create a table using: table_fields = ['No','Name', 'Age'] from prettytable import PrettyTable pt = PrettyTable(table_fields) pt.padding_width = 1 pt.title = 'Customer Info' pt.add_row(['1','abc','26']) pt.add_row(['2','xyz','52']) Output: +------------------------------+ | Customer Info | +------------------------------+ | No | Name | Age | +------------------------------+ | 1 | abc | 26 | | 2 | xyz | 52 | +------------------------------+ Desired Output: +------------------------------+ | Customer Info | +------------------------------+ | No | Name | Age | +------------------------------+ | DEPARTMENT 1 | +------------------------------+ | 1 | abc | 26 | | 2 | xyz | 52 | +------------------------------+ | DEPARTMENT 2 | +------------------------------+ | 1 | pqr | 44 | | 2 | def | 31 | +------------------------------+ Looking for a way to add Department 1 and Department 2 rows in the table.
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/57893843
tagged with: prettytable

http://stackoverflow.com/a/51444325
type: Answer
score: 2
downvote count: 0
has body: You could create a dict as intermediate result and then convert this dict back to a list. You also need to convert your integers to strings first. l1 = [100023,100069,222236,22258,41415258,41413265,1214568] l2 = [] l2dict = {} for i in l1: prefix = str(i)[0:4] if prefix in l2dict.keys(): l2dict[prefix].append(i) else: l2dict[prefix] = [i] for item in l2dict.values(): l2.append(item) print(l2)
answers question: http://stackoverflow.com/q/51444111
upvote count: 2
has comment: http://stackoverflow.com/comment/89858771

http://stackoverflow.com/a/51362086
downvote count: 0
answers question: http://stackoverflow.com/q/51361402
has body: Your implementation will work for binary classes , for multi class it will just be -y_true * tf.log(tf.sigmoid(y_pred)) and use inbuilt tensorflow method for calculating categorical entropy as it avoids overflow for y_pred&lt;0 you can view this answer Unbalanced data and weighted cross entropy ,it explains weighted categorical cross entropy implementation. The only change for categorical_crossentropy would be def weighted_loss(y_true, y_pred): def weighted_categorical_cross_entropy(y_true, y_pred): w = tf.reduce_sum(y_true)/tf_cast(tf_size(y_true), tf_float32) loss = w * tf.nn.softmax_cross_entropy_with_logits(onehot_labels, logits) return loss return weighted_categorical_cross_entropy extracting prediction for individual class def loss(y_true, y_pred): s = tf.shape(y_true) # if number of output classes is at last number_classses = s[-1] # this will give you one hot code for your prediction clf_pred = tf.one_hot(tf.argmax(y_pred, axis=-1), depth=number_classses, axis=-1) # extract the values of y_pred where y_pred is max among the classes prediction = tf.where(tf.equal(clf_pred, 1), y_pred, tf.zeros_like(y_pred)) # if one hotcode == 1 then class1_prediction == y_pred else class1_prediction ==0 class1_prediction = prediction[:, :, :, 0:1] # you can compute your loss here on individual class and return the loss ,just for simplicity i am returning the class1_prediction return class1_prediction output from model y_pred = [[[[0.5, 0.3, 0.7], [0.6, 0.3, 0.2]] , [[0.7, 0.9, 0.6], [0.3 ,0.9, 0.3]]]] corresponding ground truth y_true = [[[[0, 1, 0], [1 ,0, 0]] , [[1,0 , 0], [0,1, 0]]]] prediction for class 1 prediction = loss(y_true, y_pred) # prediction = [[[[0. ],[0.6]],[0. ],[0. ]]]]
has comment: http://stackoverflow.com/comment/89696418
has comment: http://stackoverflow.com/comment/89697315
upvote count: 2
has comment: http://stackoverflow.com/comment/89697022
has comment: http://stackoverflow.com/comment/89696487
type: Answer
has comment: http://stackoverflow.com/comment/89716652
has comment: http://stackoverflow.com/comment/89696659
score: 2

http://stackoverflow.com/a/75590161
answers question: http://stackoverflow.com/q/51481200
score: 1
upvote count: 1
has body: Just summing up to save the next guy some time: import requests, pdf2image pdf = requests.get('https://example.com/xyz.pdf', stream=True) images = pdf2image.convert_from_bytes(pdf.content)
type: Answer
downvote count: 0

http://stackoverflow.com/comment/89653154
type: Comment
type: QuestionComment
has text: Using bulk request to insert?
comment on: http://stackoverflow.com/q/51338710
score: 0

http://stackoverflow.com/q/51458555
has title: Why does mypy complain about Any as return annotation and how should I annotate a return value that can be anything?
has comment: http://stackoverflow.com/comment/89886586
tagged with: types
downvote count: 0
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/51475351
has answer: http://stackoverflow.com/a/51475351
tagged with: python
score: 4
has body: I have a class that is essentially a wrapper around a dictionary: class Wrapper(dict): ... def __getitem__(self, item: Hashable) -&gt; Any: return self.wrapped[item] When checking the annotations with mypy, it yields an Explicit "Any" is not allowed when checking this code. My guess is that this stems from the concept that Any is the ancestor and successor of all other types. How should I annotate such function where I want to allow anything to be returned?
has answer: http://stackoverflow.com/a/51458717
has comment: http://stackoverflow.com/comment/89886603
answer count: 3
tagged with: mypy
has answer: http://stackoverflow.com/a/51458614
accepted answer: http://stackoverflow.com/a/51458614
upvote count: 4
type: AnsweredQuestion

http://stackoverflow.com/q/51350935
tagged with: dictionary
score: 2
has comment: http://stackoverflow.com/comment/89686741
upvote count: 2
tagged with: openpyxl
possible better answer: http://stackoverflow.com/a/51351042
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51357573
accepted answer: http://stackoverflow.com/a/51357573
type: Question
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89674423
has answer: http://stackoverflow.com/a/51351042
favorite count: 0
has body: Trying to build a dictionary in Python created by looping through an Excel file using Openpyxl, where the key is the Name of a person, and the value is a list of dictionary items where each key is the Location, and the value is an array of Start and End. Here is the Excel file: And here is what I want: people = { 'John':[{20:[[2,4],[3,5]]}, {21:[[2,4]]}], 'Jane':[{20:[[9,10]]},{21:[[2,4]]}] } Here is my current script: my_file = openpyxl.load_workbook('Book2.xlsx', read_only=True) ws = my_file.active people = {} for row in ws.iter_rows(row_offset=1): a = row[0] # Name b = row[1] # Date c = row[2] # Start d = row[3] # End if a.value: # Only operate on rows that contain data if a.value in people.keys(): # If name already in dict for k, v in people.items(): for item in v: #print(item) for x in item: if x == int(b.value): print(people[k]) people[k][0][x].append([c.value,d.value]) else: #people[k].append([c.value,d.value]) # Creates inf loop else: people[a.value] = [{b.value:c.value,d.value}] Which successfully creates this: {'John': [{20: [[2, 4], [9, 10]]}], 'Jane': [{20: [[9, 10]]}]} But when I uncomment the line after the else: block to try to add a new Location dictionary to the initial list, it creates an infinite loop. if x == int(b.value): people[k][0][x].append([c.value,d.value]) else: #people[k].append([c.value,d.value]) # Creates inf loop I am sure there's a more Pythonic way of doing this, but pretty stuck here and looking for a nudge in the right direction. The outcome here is to analyze all of the dict items for overlapping Start/Ends per person and per location. So John's Start of 3.00 - 5.00 at location 20 overlaps with his Start/End at the same location of 2.00 - 4.00
has comment: http://stackoverflow.com/comment/89674400
has title: Creating nested dictionaries in Python using Openpyxl
tagged with: python

http://stackoverflow.com/a/51359437
has comment: http://stackoverflow.com/comment/89692051
type: Answer
has comment: http://stackoverflow.com/comment/89691901
answers question: http://stackoverflow.com/q/51359122
has comment: http://stackoverflow.com/comment/89691394
has comment: http://stackoverflow.com/comment/89691362
has comment: http://stackoverflow.com/comment/89691719
has comment: http://stackoverflow.com/comment/89691308
has body: The function to_numeric converts argument to a numeric type. The error which you get len() of unsized object is only when calculating something like len() of an int value. So the only explanation to your error is whatever data structure you have stored the column in, either some or all of it is already stored in the form of float as pandas is trying to find its length and getting the above error.
score: 0
has comment: http://stackoverflow.com/comment/89691214
has comment: http://stackoverflow.com/comment/89691006
has comment: http://stackoverflow.com/comment/89691451

http://stackoverflow.com/comment/89951732
type: AnswerComment
type: Comment
has text: `names_line` is a number of row that contains columns labels. If you inspect `list_of_lines` you will see the parsed table content, row by row.
comment on: http://stackoverflow.com/a/51466451
score: 0

http://stackoverflow.com/comment/89820091
has text: Actually that error usually means your identation is wrong. Is that all the error? The statement should be longer
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51424304
score: 0

http://stackoverflow.com/q/51392058
answer count: 1
has comment: http://stackoverflow.com/comment/89756034
has comment: http://stackoverflow.com/comment/89756143
favorite count: 0
has comment: http://stackoverflow.com/comment/89756097
has body: So just getting started learning python. as practice i decided to build a program that would handle my attacks for my D&amp;D character and i can't quite seem to get this to iterate properly. from random import randint def roll_dice(): type = raw_input("Initiative (i) or Attack (a): ") #variable that is passed through the function roll = randint(1,20) if roll == 1: print "Natural 1" elif roll == 20: print "Natural 20" else: crit = "n" if type == 'i': result = roll + 5 print "Initiative = %d" % result return elif type == 'a': """ most of the rest of the program is after here but that all works fine so there is no reason to take up space with that""" roll_dice() for type in roll_dice(): if type == 'a' or type == 'i': continue program will loop once and then gives me: TypeError: 'NoneType' object is not iterable I know this means that the second time it goes to iterate it is passing nothing through but i can't quite figure out how to fix it. any help and/or explanations would be greatly appreciated Edit: I know it does not run as posted. The whole thing is over 100 lines and I did not want to swamp people with that. Once I get home I will post with the whole thing. For clarification: With the whole program it will run once through loop back to the start and then return the error after a completed second run through the program. So the first time through the loop works it is after the completed second run and attempting to start a third.
has title: can't get program to iterate properly (TypeError: 'NoneType' object is not iterable)
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89756130
score: -3
downvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/89756133
has answer: http://stackoverflow.com/a/51392143
has comment: http://stackoverflow.com/comment/89756086
has comment: http://stackoverflow.com/comment/89756099
upvote count: 0

http://stackoverflow.com/comment/120970141
score: 1
has text: being nit-picky but you should really rename the variable 'dict' to something else as 'dict()' is already the name of a built-in constructor
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/54344757

http://stackoverflow.com/comment/89685504
comment on: http://stackoverflow.com/q/51356651
score: 0
type: Comment
type: QuestionComment
has text: document.getElementById('myVideo').addEventListener('ended',myHandler,false);

http://stackoverflow.com/a/51395348
has comment: http://stackoverflow.com/comment/89794937
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89800500
downvote count: 0
has comment: http://stackoverflow.com/comment/89802357
accepted answer of: http://stackoverflow.com/q/51391618
has comment: http://stackoverflow.com/comment/89778053
type: Answer
has body: You are dealing with this problem due to the fact that you were using the wrong link to get the article links. So I didn't quite a few changes and came up with this code (Do note that I removed the bs4 module as it is not needed anymore): import requests search = "edith cowan" headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'} json = {"scholarly_search":{"from":0,"size":"10","_source":{"excludes":["referenced_by_patent_hash","referenced_by_patent","reference"]},"query":{"bool":{"must":[{"query_string":{"query":f"\"{search}\"","fields":["title","abstract","default"],"default_operator":"and"}}],"must_not":[{"terms":{"publication_type":["unknown"]}}],"filter":[]}},"highlight":{"pre_tags":["&lt;span class=\"highlight\"&gt;"],"post_tags":["&lt;/span&gt;"],"fields":{"title":{}},"number_of_fragments":0},"sort":[{"referenced_by_patent_count":{"order":"desc"}}]},"view":"scholar"} req = requests.post("https://www.lens.org/lens/api/multi/search?request_cache=true", headers = headers, json = json).json() links = [] for x in req["query_result"]["hits"]["hits"]: links.append("https://www.lens.org/lens/scholar/article/{}/main".format(x["_source"]["record_lens_id"])) The search variable is equal to the term that you are searching for (in your case "edith cowan"). The links are stored in the links variable. Edit: How I did it So the main question might be where did I get the link from and how did I know what to include in the json variable. For this, I used a simple HTML intercepter (in my case burp suite community edition). This tool showed me that when you visit this URL (the one that you used in your question to send the req to) your browser sends a post request to https://www.lens.org/lens/api/multi/search?request_cache=true which then retrieves all the info of the current page. What concerns the json variable burp suite also shows you what packets are sent, so I copy-pasted them into t…
has comment: http://stackoverflow.com/comment/89773562
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89774876
answers question: http://stackoverflow.com/q/51391618

http://stackoverflow.com/comment/89814709
type: Comment
has text: Google offers plenty of example code for popular languages. There is also documentation for the API as implemented in the client library - search for it with the additional term "pydoc"
score: 0
comment on: http://stackoverflow.com/q/51411985
type: QuestionComment

http://stackoverflow.com/a/51442782
has comment: http://stackoverflow.com/comment/89897682
upvote count: 3
answers question: http://stackoverflow.com/q/51442148
has body: I found how to fix it. My Python packages are manage by Yaourt so I did this: $ yaourt -Qs | grep python- | cut -d ' ' -f 1 | cut -d '/' -f 2 &gt; ~/pythonpackage arr=($(cat ~/pythonpackage)) for i in ${arr[@]};do yaourt -Rddsn $i done and then arr=($(cat ~/pythonpackage)) for i in ${arr[@]};do yaourt -S $i done I am not sure if this is a correct answer, but my broken applications work again now.
score: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51442148
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/95587701

http://stackoverflow.com/a/51394524
has comment: http://stackoverflow.com/comment/89891030
has comment: http://stackoverflow.com/comment/89761592
has comment: http://stackoverflow.com/comment/89763934
type: AcceptedAnswer
has body: it looks like you might be able to 3x the speed by reducing (two for loops, 1 all which is also a for loop) to 1 for loop with some clever placement of the if statements. by zipping the target, datalist. assuming that self.target, self.negative, self.datalist, and self.step are all the same length. for i, (t, d) in enumerate(zip(self.target, self.datalist)): t = float(t) if (t != d) and (t &gt; d) and (self.setTarget == 1): self.target.append(getShadowInfo(x)) self.datalist = d + (t - d) * .1 elif (t != d) and (t &lt;= d) and (self.setTarget == 1): self.target.append(getShadowInfo(x)) self.datalist = d - (d - t) * .1 else: self.setCustomParameter(i) if self.setTarget == 1 self.setTarget = 0 self.setTodaysDate(self.year, self.month, self.day, self.hour, self.min) if you were able to figure out how to reduce to 1 for loop, you could then multiprocess it by replacing the for loop entirely by returning the index and data from a multiprocessing.pool.Pool: # replacing ... self.datalist = d - (d - t) * .1 # with ... return i, d - (d - t) * .1 results = mp.Pool(4).starmap(return_data, zip(self.target, self.datalist)) for i, d in results: self.datalist[i] = d note: the trick is going to be figuring out how to process what needs updating without mutating self.target in the for loop
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51392915
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51392915

http://stackoverflow.com/a/51362016
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/51360932
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51360932
upvote count: 2
has body: You need to add generic.View Instead of generic.NameView, like this from django.views import generic class NameView(generic.View) # you code ...

http://stackoverflow.com/a/51418275
has comment: http://stackoverflow.com/comment/89807807
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/89807621
score: 2
has body: I think your first solution is clear, and that's the most important thing in python. Alternatively, how about a generator instead of a comprehension? def try_div_itr(itr): for elem in itr: try: yield 1 / elem except ZeroDivisionError: pass result = list(try_div_itr([-2, -1, 0, 1, 2])) You could even generalise this def try_itr(func, itr, *exceptions, **kwargs): for elem in itr: try: yield func(elem, **kwargs) except exceptions: pass x = [random.choice([0, 1]) for _ in range(100_000)] %timeit [i for i in (try_div(i) for i in x) if i is not None] 42.6 ms ± 109 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) %timeit [i for i in [try_div(i) for i in x] if i is not None] 36.3 ms ± 154 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) %timeit list(try_div_itr(x)) 25.3 ms ± 85.1 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) %timeit list(try_itr(lambda i: 1/i, x, ZeroDivisionError)) 34.7 ms ± 113 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) # but expect generic method to be slower anyway %timeit list(try_itr((1).__truediv__, x, ZeroDivisionError)) 28.7 ms ± 118 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) # remove lambda abstraction for speed
accepted answer of: http://stackoverflow.com/q/51418142
answers question: http://stackoverflow.com/q/51418142
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51392673
has comment: http://stackoverflow.com/comment/89775667
has title: Any idea to optimise this algorithm?
has comment: http://stackoverflow.com/comment/89775656
type: Question
tagged with: algorithm
tagged with: matrix
tagged with: time-complexity
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89757363
has comment: http://stackoverflow.com/comment/89757261
favorite count: 0
tagged with: binary
has answer: http://stackoverflow.com/a/51392898
has comment: http://stackoverflow.com/comment/89758178
score: 6
tagged with: python
has comment: http://stackoverflow.com/comment/89757341
has comment: http://stackoverflow.com/comment/89775663
upvote count: 6
has body: Let's imagine I have a binary 40*40 matrix. In this matrix, values can be either ones or zeros. I need to parse the whole matrix, for any value == 1, apply the following : If the following condition is met, keep the value = 1, else modify the value back to 0: Condition: in a square of N*N (centered on the currently evaluated value), I can count at least M values == 1. N and M are parameters that can be set for the algorithms, naturally N&lt;20 (in this case) and M&lt;(N*N - 1). The obvious algorithm is to iterate over the whole image and then each time a value == 1. Perform another search around this value. It would make an O^3 complex algorithm. Any idea to make this more efficient? Edit: Some code to make this more easy to understand. Let's create a randomly initialized 40*40 matrix of 1s and 0s. 5% (arbitrarily chosen) of the values are 1s, 95% are 0s. import matplotlib.pyplot as plt import numpy as np %matplotlib inline def display_array(image): image_display_ready = image * 255 print(image_display_ready) plt.imshow(image_display_ready, cmap='gray') plt.show() image = np.zeros([40,40]) for _ in range(80): # 5% of the pixels are == 1 i, j = np.random.randint(40, size=2) image[i, j] = 1 # Image displayed on left below before preprocessing display_array(image) def cleaning_algorithm_v1(src_image, FAT, LR, FLAG, verbose=False): """ FAT = 4 # False Alarm Threshold (number of surrounding 1s pixel values) LR = 8 # Lookup Range +/- i/j value FLAG = 2 # 1s pixels kept as 1s after processing are flag with this value. """ rslt_img = np.copy(src_image) for i in range(rslt_img.shape[0]): for j in range(rslt_img.shape[1]): if rslt_img[i, j] &gt;= 1: surrounding_abnormal_pixels = list() lower_i = max(i - LR, 0) upper_i = min(i + LR + 1, rslt_img.shape[0]) lower_j = max(j - LR, 0) upper_j = min(j + LR + 1, rslt_img.shape[1]) abnormal_pixel_count = 0 for i_k in range(lower_i, upper_i): for j_k in range(lower_j, upper_j): if i_k == i and j_k == j: continue pixel_value = rslt_img[…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89775681
accepted answer: http://stackoverflow.com/a/51392898

http://stackoverflow.com/q/51408022
has body: I have an n-dim array in numpy and I have n column vectors. I need to convert the n-dim array to a 2-D numpy array having rows = size of n-dim array cols = n + 1 to simplify with an example, a = np.random.randint(50, size=(2,2)) r = np.array([0.2,1.9]) c = np.array([4,5]) a =&gt; array([[45, 18], [ 4, 24]]) c =&gt; array([4, 5]) r =&gt; array([ 0.2, 1.9]) I need to convert this to the following, array([[ 45. , 4. , 0.2], [ 18. , 5. , 0.2], [ 4. , 4. , 1.9], [ 24. , 5. , 1.9]]) I wrote it as follows, although my feeling is that it's not the best solution, But it does work and seems fast enough for relatively large values, def get_2d_array( arr, r, c): w = None for i in range(arr.shape[0]): rv = np.full((arr[i].shape[0], 1), r[i]) z = np.concatenate((arr[i].reshape(-1, 1), c.reshape(-1, 1), rv), axis=1) if w is None: w = z else: w = np.concatenate((w, z)) return w Is there any other way of doing this in numpy without a loop? Also, to generalize this, I actually have a 4-D array which I need to reduce to 2D array with similar construct as above. I couldn't get a recursive function to work and ended up have to reduce both 4th and 3rd dims explicitly as follows, def reduce_3d(self, arr3, row, col, third_dim_array): x = None for i in range(arr3.shape[0]): x1 = self.reduce_2d(arr3[i], row, col) third_array = np.full((x1.shape[0], 1), third_dim_array[i]) x1 = np.concatenate((x1, third_array), axis=1) if x is None: x = x1 else: x = np.concatenate((x, x1)) return x def reduce_4d(air_temp ,row, col, third, second): w = None for j in range(air_temp.shape[0]): w1 = self.reduce_3d(air_temp[j], row, col, third) second_arr = np.full((w1.shape[0], 1), second[j]) w1 = np.concatenate((w1, second_arr), axis=1) if w is None: w = w1 else: w = np.concatenate((w, w1)) return w Output of a 4-D example is as follows, a = np.random.randint(100, size=(2,3,2,2)) array([[[[ 8, 38], [89, 95]], [[63, 82], [24, 27]], [[22, 18], [25, 30]]], [[[94, 21], [83, 9]], [[25, 98], [84, 57]], [[89, 20], [40,…
type: AnsweredQuestion
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/51411796
type: Question
has answer: http://stackoverflow.com/a/51411595
tagged with: numpy
answer count: 2
has title: n-dimensional array reduction to 2-d array with additional columns
downvote count: 0
possible better answer: http://stackoverflow.com/a/51411595
favorite count: 0
has answer: http://stackoverflow.com/a/51411796
tagged with: python

http://stackoverflow.com/a/51446778
has comment: http://stackoverflow.com/comment/89863741
has body: Because this is so much clearer... sum(((i, a, b) for i, (a,b) in enumerate(zip(val1, val2))), ()) example: val1 = 'hello' val2 = range(5) sum(((i, a, b) for i, (a,b) in enumerate(zip(val1, val2))), ()) # -&gt; (0, 'h', 0, 1, 'e', 1, 2, 'l', 2, 3, 'l', 3, 4, 'o', 4)
answers question: http://stackoverflow.com/q/51446661
has comment: http://stackoverflow.com/comment/89863971
type: Answer
downvote count: 2
has comment: http://stackoverflow.com/comment/89863820
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/89863809

http://stackoverflow.com/q/51389000
tagged with: python
has comment: http://stackoverflow.com/comment/89775576
has answer: http://stackoverflow.com/a/51404620
type: Question
has answer: http://stackoverflow.com/a/51394988
has body: I would like to get the location of a given blob storage container. I've instantiated my client: blob_client = BlockBlobService(account_name='account_name', account_key='account_key') and I was hoping I could pull the get_container_properties() method from it, but it doesn't return very much information. properties = blob_client.get_container_properties(container_name='container_name') properties only contains etagm last_modified, lease, and public_access. How do I get the location of the container?
tagged with: azure-blob-storage
has title: Get Azure container location (python)
score: 0
answer count: 2
tagged with: azure
has comment: http://stackoverflow.com/comment/89756295
type: UnansweredQuestion

http://stackoverflow.com/comment/89774510
has text: Are you using Python 3? What OS are you using? And what are you using to read the page up/down key presses? Does it have to be in the terminal, or would it be ok to use a GUI, eg Tkinter, which is now bundled with the standard library?
comment on: http://stackoverflow.com/q/51401438
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89925722
has text: Exact content when I get UnicodeError is "Harmonogram 2018 Łukaszewa 35.pdf"
comment on: http://stackoverflow.com/q/51395752
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51411845
answers question: http://stackoverflow.com/q/51411747
downvote count: 1
type: Answer
upvote count: 0
score: -1
has body: let suppose we take 93/47 outputs 1.9787234042553192 to get formatted output till two decimal you can use eval('{:.2f}'.format(93/47)) the output is 1.98

http://stackoverflow.com/comment/89673566
type: AnswerComment
has text: Or use f-strings, `f'Score_{i}'`.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51349937

http://stackoverflow.com/comment/89869867
type: AnswerComment
has text: do I just need to write a script to manually add brackets to this column? there are about 40k rows so I don't know how efficient that would be
comment on: http://stackoverflow.com/a/51449202
type: Comment
score: 0

http://stackoverflow.com/q/51388985
has comment: http://stackoverflow.com/comment/90733218
answer count: 2
has body: I am fairly new to python and right now, I am currently learning python through Al Sweigart's Automate the boring stuff with Python. Right now, I want to open a Firefox by using webdriver. When I run the code: from selenium import webdriver I get no error. However, after running: browswer=webdriver.Firefox() I get the following error message. Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 76, in start stdin=PIPE) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 709, in __init__ restore_signals, start_new_session) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 1344, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: 'geckodriver': 'geckodriver' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "&lt;pyshell#2&gt;", line 1, in &lt;module&gt; browswer=webdriver.Firefox() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/firefox/webdriver.py", line 160, in __init__ self.service.start() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 83, in start os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH. Now, I have already installed geckodriver and I have been scrolling through google to try to find the solution. So far, I have tried manually adding geckodriver to /usr/local/bin. I have also tried running: brew install geckodriver on terminal. It suggested me to try overwriting geckodriver, so brew installed geckodriver on /usr/local/Cellar/geckodriver/0.21.0/bin/geckodriver. I've ran sudo nano /etc/paths t…
has comment: http://stackoverflow.com/comment/89751458
upvote count: 1
has title: Python can't find geckodriver in my path
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/54449494
tagged with: python
tagged with: macos
tagged with: homebrew
tagged with: selenium
type: Question
has answer: http://stackoverflow.com/a/51449121
score: 1

http://stackoverflow.com/a/77031113
upvote count: 2
has comment: http://stackoverflow.com/comment/136326663
has comment: http://stackoverflow.com/comment/136534444
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/137816391
downvote count: 0
answers question: http://stackoverflow.com/q/51374762
has body: Fix for MacOS 14 - Sonoma After a lot of searching and a difficult time I was able to find a possible answer for any MacOS user. If you are using Sonoma MacOS 14, please check @nickgoodwind's answer on issue NameError: name '_mysql' is not defined after setting change to mysql where the same error happens import _mysql ImportError: dlopen(...)

http://stackoverflow.com/a/51425880
accepted answer of: http://stackoverflow.com/q/51421931
score: 1
has body: Scipy has several options for root finding algorithms: https://docs.scipy.org/doc/scipy-0.13.0/reference/optimize.html#root-finding These algorithms tend to want either bounds for the possible solution or the derivative. In this case, bounds seemed like less work :) edit: After re-reading your question, It sounds like you don't have an estimate for the upper and lower bounds. In that case, I suggest Newton's method (scipy.optim.newton, in which case you'll have to compute the derivative (by hand or with sympy). import matplotlib matplotlib.use('Agg') import numpy as np from scipy.optimize import brentq import matplotlib.pyplot as plt def gamma_func(beta, j, T): return (1-np.exp(-j*T*beta)) / (1-np.exp(-(j+1)*T*beta)) # Subtract gamma from both sides so that we have f(beta,...) = 0. # Also, set beta, the independent variable, to the first # argument for compatibility with solver def f(beta, gamma, j, T): return gamma_func(beta, j, T) - gamma # Parameters gamma = 0.5 j = 2.3 T = 1.5 # Lower and upper bounds for solution beta_low = -3 beta_high = 3 # Error tolerance for solution tol = 1e-4 # True solution beta_star = brentq(f, beta_low, beta_high, args=(gamma, j, T), xtol=tol) # Plot the solution plt.figure() plt.clf() beta_arr = np.linspace(-10, 10, 1001) gamma_arr = gamma_func(beta_arr, j, T) plt.plot(beta_arr, gamma_arr) plt.plot(beta_star, gamma_func(beta_star, j, T), 'o') plt.savefig('gamma_plot.png') # Print the solution print("beta_star = {:.3f}".format(beta_star)) print("gamma(beta_star) = {:.3f}".format(gamma_func(beta_star, j, T))) beta_star = -0.357 gamma(beta_star) = 0.500 See the documentation for the other solvers, including multidimensional solvers. Good luck! Oliver
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51421931

http://stackoverflow.com/comment/89929196
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51479520
has text: Ok due to registry error could not login ;i will have to find a workaround thank you ! i have one query pls help in one page after login i have button called "Excel" when i click the excel will be downloaded ,its html format is Excel how to automate this click and download or read the content and store in array

http://stackoverflow.com/q/51420032
answer count: 2
downvote count: 0
has body: I have a saved logistic regression model which I trained with training data and saved using joblib. I am trying to load this model in a different script, pass it new data and make a prediction based on the new data. I am getting the following error "sklearn.exceptions.NotFittedError: CountVectorizer - Vocabulary wasn't fitted." Do I need to fit the data again ? I would have thought that the point of being able to save the model would be to not have to do this. The code I am using is below excluding the data cleaning section. Any help to get the prediction to work would be appreciated. new_df = pd.DataFrame(latest_tweets,columns=['text']) new_df.to_csv('new_tweet.csv',encoding='utf-8') csv = 'new_tweet.csv' latest_df = pd.read_csv(csv) latest_df.dropna(inplace=True) latest_df.reset_index(drop=True,inplace=True) new_x = latest_df.text loaded_model = joblib.load("finalized_mode.sav") tfidf_transformer = TfidfTransformer() cvec = CountVectorizer() x_val_vec = cvec.transform(new_x) X_val_tfidf = tfidf_transformer.transform(x_val_vec) result = loaded_model.predict(X_val_tfidf) print (result)
has title: using saved sklearn model to make prediction
tagged with: pandas
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/51442566
favorite count: 0
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51420090
accepted answer: http://stackoverflow.com/a/51442566
tagged with: logistic-regression
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/51420090

http://stackoverflow.com/comment/89643566
type: QuestionComment
comment on: http://stackoverflow.com/q/51334116
type: Comment
score: 0
has text: Does your xpath work without those weird parentheses at the end? And without the second set of double `//` – it should only need one.

http://stackoverflow.com/comment/89932461
type: Comment
comment on: http://stackoverflow.com/a/51463688
has text: Could you provide more information? I know that RANSAC can find one best line to fit all point. But how to get 3 different line? Running the algorithms three times?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/110417183
type: AnswerComment
has text: Do you know how to get it programmatically? Like if someone gives you their credentials, can I use their three credentials to pull in the client_customer_id so I can execute the code samples?
comment on: http://stackoverflow.com/a/51419623
type: Comment
score: 0

http://stackoverflow.com/comment/89691929
comment on: http://stackoverflow.com/q/51351918
type: Comment
type: QuestionComment
has text: Yes, I agree that I would need proxies. Coming to the login problem, do you have any idea how to call a spider function from inside a middleware? because I have to make a post request to log in.
score: 0

http://stackoverflow.com/q/51412225
type: AnsweredQuestion
upvote count: 2
score: 1
tagged with: python-requests
downvote count: 1
accepted answer: http://stackoverflow.com/a/51412438
has body: I have a json object which is returned against a post call r = requests.post("url", json=data) I was doing r.json() to get the json object. But as I understand it creates a dict object which is unordered. I need to preserve the order. I saw the solution described here: Items in JSON object are out of order using "json.dumps"? But my challenge is my starting point is a response object. How do I take it and convert to a json with the order preserved? Adding some more details: My API call returns an object of form: [{ "key01": "value01", "key02": "value02", "keyN": "valueN" }, { "key01": "value01", "key02": "value02", "keyN": "valueN" }, { "key01": "value01", "key02": "value02", "keyN": "valueN" } ] I have a table with three columns as key01,key02 and keyN. I need to post this json object after some minor manipulations to a software maintaining that specific order of key01,key02 and keyN. But as soon as I do response.json() it is changing the order. I have tried to use the orderedlist approach as mentioned in the two other threads but so far my object is looking like this: b"OrderedDict([('key01','value01'),('key02','value02'),('keyN','valueN')]) How do I get a json which looks like this instead: {"key01":"value01","key02":"value02","keyN":"valueN"}
type: Question
has comment: http://stackoverflow.com/comment/89796424
has comment: http://stackoverflow.com/comment/89796159
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/89796247
answer count: 2
has comment: http://stackoverflow.com/comment/89796213
possible better answer: http://stackoverflow.com/a/51412439
has title: python response.json preserve order
has answer: http://stackoverflow.com/a/51412439
favorite count: 0
has answer: http://stackoverflow.com/a/51412438
has comment: http://stackoverflow.com/comment/89796144
tagged with: python
linked to: http://stackoverflow.com/q/10844064

file
type: Tag
tags question: http://stackoverflow.com/q/51354671
tags question: http://stackoverflow.com/q/51376555
tags question: http://stackoverflow.com/q/51456650
tags question: http://stackoverflow.com/q/51481747
tags question: http://stackoverflow.com/q/51352901
tags question: http://stackoverflow.com/q/51365308
tags question: http://stackoverflow.com/q/51396342
tag name: file
tags question: http://stackoverflow.com/q/51352443
tags question: http://stackoverflow.com/q/51432562
tags question: http://stackoverflow.com/q/51410284
tags question: http://stackoverflow.com/q/51331075
tags question: http://stackoverflow.com/q/51471728
tags question: http://stackoverflow.com/q/51405683
tags question: http://stackoverflow.com/q/51449704
tags question: http://stackoverflow.com/q/51386421
tags question: http://stackoverflow.com/q/51384894
tags question: http://stackoverflow.com/q/51475870
tags question: http://stackoverflow.com/q/51339946
tags question: http://stackoverflow.com/q/51469818
tags question: http://stackoverflow.com/q/51445282
tags question: http://stackoverflow.com/q/51396867
tags question: http://stackoverflow.com/q/51380949
tags question: http://stackoverflow.com/q/51391271
tags question: http://stackoverflow.com/q/51473437
tags question: http://stackoverflow.com/q/51479759
tags question: http://stackoverflow.com/q/51427543
tags question: http://stackoverflow.com/q/51339840
tags question: http://stackoverflow.com/q/51398847
tags question: http://stackoverflow.com/q/51438810
tags question: http://stackoverflow.com/q/51408455
tags question: http://stackoverflow.com/q/51481307
tags question: http://stackoverflow.com/q/51461968
tags question: http://stackoverflow.com/q/51423460

http://stackoverflow.com/comment/90060298
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51381579
has text: is this question still open ?
type: Comment

annotate
tag name: annotate
type: Tag
tags question: http://stackoverflow.com/q/51341226

http://stackoverflow.com/comment/89883423
score: 0
has text: for which python version are you trying to install the tensorflow?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51456176

http://stackoverflow.com/q/51409519
tagged with: python-2.7
score: 0
answer count: 1
tagged with: python
has body: I did the following Install python (2.7) on windows using official setup file from python.org Created a virtual env using the same interpreter Installed ipython in the virtual env When I run ipython from windows commandline, everything works good. I get the colors and autocomplete. But when I run inside cygwin bash, there are no colors and autocomplete does not work. I also installed pyreadline package in the same virtual env but didn't fix it. Any clues?
has title: ipython in cygwin does not have autocomplete
type: UnansweredQuestion
tagged with: ipython
type: Question
tagged with: cygwin
has answer: http://stackoverflow.com/a/51770564

http://stackoverflow.com/comment/89645284
type: AnswerComment
comment on: http://stackoverflow.com/a/51335015
type: Comment
has text: Remember, gradient descent is only an algorithm to minimize the cost function. If you can see which direction would take your cost function the most "downhill" (the derivative), you can easily minimize it for something as simple as linear regression.
score: 0

http://stackoverflow.com/comment/89710413
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51369075
has text: indexing goes `[start:exclusive end]`, if you index `[1:2]` you are going from `1` to `2` exclusive, so just the element at index `1`, which is b
type: Comment

http://stackoverflow.com/comment/89891897
comment on: http://stackoverflow.com/q/51461262
type: Comment
type: QuestionComment
score: 1
has text: Are you sure it's this line of code that's giving you problems? Because it's inside a `try`, if something wrong happened there, it should go to your `except` statement instead of throwing an error.

http://stackoverflow.com/q/51468287
has answer: http://stackoverflow.com/a/51468504
has answer: http://stackoverflow.com/a/51468345
has comment: http://stackoverflow.com/comment/89942287
has comment: http://stackoverflow.com/comment/89906188
type: Question
tagged with: matrix-multiplication
upvote count: 2
tagged with: numpy
answer count: 2
favorite count: 0
has comment: http://stackoverflow.com/comment/89905085
has body: I am facing a problem where I need to perform matrix multiplication between two large matrix A [400000 x 70000] and B [70000 x 1000]. The two matrices are dense and have no special structure that I can utilize. Currently my implementation is to divide A into multiple chunks of rows, say, sub_A [2000 x 70000] and perfrom sub_A * B. I noticed that there are a lot of time is spent on I/O, i.e. read in the sub_A. Read in the matrix takes about 500 seconds and computation takes about 300 seconds. Will using PyTables here be useful to improve the I/O efficiency? Are there any library that will help in improving the time efficiency? Here is the code: def sim_phe_g(geno, betas, chunk_size): num_indv = geno.row_count num_snps = geno.col_count num_settings = betas.shape[1] phe_g = np.zeros([num_indv, num_settings]) # divide individuals into chunks for i in range(0, num_indv, chunk_size): sub_geno = geno[i : i + chunk_size, :] sub_geno = sub_geno.read().val phe_g[i : i + chunk_size, :] = np.dot(sub_geno, betas) return phe_g geno is of size [400000 x 70000] and betas is of size [70000 x 1000]. geno here is a large matrix that is stored in disk. The statement sub_geno = sub_geno.read().val will load a chunk of the genotype into the memory. And this statement costs a lot of time. Also, I divide the big matrix into chunks because of 32GB memory size limitation.
tagged with: python
score: 2
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89906106
has title: Large scale matrix multiplication using Numpy

http://stackoverflow.com/a/51479415
has body: I think the issue is in: np.savetxt(r'name', df.values, fmt='%d') All txt files are saved under the same filename name, and because of overwriting only the last file will be available on the disk. You could change that to: np.savetxt( name.replace("bytes.bin", ".txt"), df.values, fmt='%d')
score: 1
has comment: http://stackoverflow.com/comment/89928904
accepted answer of: http://stackoverflow.com/q/51479146
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51479146
has comment: http://stackoverflow.com/comment/89930588
upvote count: 1

http://stackoverflow.com/q/51369643
tagged with: unit-testing
has body: I have a script of this form which is called in a program (from another similar function). I need to use unittest module to write tests for this function. It doesn't exactly return anything but changes a lot of globals It takes inputs I can't change it to an OOP code right now I want to test cases where I change a certain global varible and see if ,let's say, TOTFRAC is positive or something. I have read tests for OOP codes where I call each variable as an object parameter, but what do I do if my code isn't Object Oriented. Note: I have removed a lot of lines of code because it is rather long, so things might not exactl make sense import numpy import math def SETUP(LAST): def GOTO999(): print(' ERROR IN GAS INPUT : NGAS=',NGAS,'\n') for J in range(1,6): # print(J) print(' N=',J,' NGAS=',NGASN[J],' FRAC=',FRAC[J]) LAST=1 return # A lot of globals # Initialising variables NBREM=[] EBRTOT=[] for K in range(1,6): NBREM.append(0) EBRTOT.append(0.0) NGAS=int(input('NGAS')) NEVENT=int(input('NEVENT')) IMIP=int(input('IMIP')) NDVEC=int(input('NDVEC')) NSEED=int(input('NSEED')) ESTART=float(input('ESTART')) ETHRM=float(input('ETHRM')) ECUT=float(input('ECUT')) ICOUNT=0 if(IMIP == 1): ICOUNT=1 if(NGAS == 0): LAST=1 return if(ESTART &gt; 3.0*(10**6) and IMIP == 3): print(' SUBROUTINE STOPPED: X-RAY ENERGY=','%.3f' % ESTART,'EV. MAXIMUM ENERGY 3.0MEV') sys.exit() if(IMIP != 1 and NEVENT &gt; 10000): print(' SUBROUTINE STOPPED: NUMBER OF EVENTS =',NEVENT,' LARGER THAN ARRAY LIMIT OF 10000') sys.exit() NGASN=[] for i in range(1,6): NGASN.append(int(input('NGASN'+str(i)))) FRAC=[] for i in range(1,6): FRAC.append(round(float(input('FRAC')),4)) TEMPC=round(float(input('TEMPC')),4) TORR=round(float(input('TORR')),4) # more inputs if(IWRITE != 0): outputfile=open("DEGRAD.OUT","w") EBIG=0.05*ESTART/1000. EFINAL=ESTART*1.0001+760.0*EBIG/TORR*(TEMPC+ABZERO)/293.15*EFIELD if(EFINAL &lt; (1.01*ESTART)): EFINAL=1.01*ESTART # CHECK INPUT TOTFRAC=0.00 if(NGAS == 0 or NGAS &gt; 6): GOTO999() …
type: Question
tagged with: testing
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/56283639
has comment: http://stackoverflow.com/comment/99180810
type: UnansweredQuestion
tagged with: python
tagged with: oop
has comment: http://stackoverflow.com/comment/90562904
tagged with: python-unittest
has title: Running unit tests on a non OOP code without any return value

http://stackoverflow.com/q/51363980
answer count: 1
upvote count: 1
tagged with: upgrade
has answer: http://stackoverflow.com/a/51364566
has comment: http://stackoverflow.com/comment/89700890
has comment: http://stackoverflow.com/comment/89701080
favorite count: 0
has body: I can't upgrade pip (9.0.1) to pip (10.0.1). Running pip install --upgrade pip throws OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/EGG-INFO/PKG-INFO' (this is yet another issue I will need to deal with...) Trying pip install --user pip returns Requirement already satisfied: pip in /Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg and has no effect, i.e. pip list | grep pip returns pip (9.0.1) Running pip install --upgrade --user pip returns Successfully installed pip-10.0.1 but pip list | grep pip still returns pip (9.0.1) I have learned not to use sudo, so please don't suggest this. This answer suggests to install by hand (more or less). But I am worried of messing things up. If you are suggesting to use a virtual environment, I am afraid this is one level of sophistication too many for me as I am still very much a beginner, and if something doesn't work the way it should I will find it even more daunting to figure out what to try. Is there really no alternative than the latter options?
linked to: http://stackoverflow.com/q/36411331
has comment: http://stackoverflow.com/comment/89700400
has title: `pip` doesn't upgrade itself
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89701044
tagged with: pip
tagged with: python
downvote count: 0
score: 1
linked to: http://stackoverflow.com/q/31512422
has comment: http://stackoverflow.com/comment/89700287
type: Question

http://stackoverflow.com/comment/89794781
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51410029
has text: There is still some issue: `[6, 20][1, 10]` gives 14, which is correct while `[1, 10][6, 20]` gives 9... it appears to still be able to select an item from the second list twice.

http://stackoverflow.com/q/51479822
tagged with: python
has comment: http://stackoverflow.com/comment/89928783
tagged with: matplotlib
type: Question
has answer: http://stackoverflow.com/a/51480675
has answer: http://stackoverflow.com/a/51480787
score: 0
answer count: 2
has title: Tkinter scale widget not updating in realtime
has body: I'm trying to use Tkinter.Scale to produce a slider that changes the data within a matplotlib, however I am having issues in getting the plots to update in realtime without having to regenerate the plot window each time. If I run my code as so, then it works well, but it creates a new window each time I move the slider which is hard to focus upon visually. import matplotlib.pyplot as plt import numpy as np import tkinter as tk master = tk.Tk() def update(val): plt.close() global idx idx = np.array(w.get()) t1 = np.arange(0.0, 5.0, 0.1) a1 = np.sin(idx*np.pi *t1) a2 = np.sin((idx/2)*np.pi*t1) a3 = np.sin((idx/4)*np.pi*t1) a4 = np.sin((idx/8)*np.pi*t1) """Plotting of data""" fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, sharey = False) # create figure plt.tight_layout() ax1.plot(t1, a1) ax2.plot(t1, a2) ax3.plot(t1, a3) ax4.plot(t1, a4) w = tk.Scale(master, from_=0, to=10, command = update) w.pack() tk.mainloop() I would like the slider to simply re-plot the data each time, however when I move the commands to create the figure preceding the function, as shown below, it no longer updates the plots when I move the slider, but only when the slider is closed. import matplotlib.pyplot as plt import numpy as np import tkinter as tk fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, sharey = False) # create figure plt.tight_layout() master = tk.Tk() def update(val): ax1.cla() # clears the entire current figure but leaves the window ax2.cla() ax3.cla() ax4.cla() global idx idx = np.array(w.get()) t1 = np.arange(0.0, 5.0, 0.1) a1 = np.sin(idx*np.pi *t1) a2 = np.sin((idx/2)*np.pi*t1) a3 = np.sin((idx/4)*np.pi*t1) a4 = np.sin((idx/8)*np.pi*t1) """Plotting of data""" ax1.plot(t1, a1) ax2.plot(t1, a2) ax3.plot(t1, a3) ax4.plot(t1, a4) w = tk.Scale(master, from_=0, to=10, command = update) w.pack() tk.mainloop() Has anyone got any ideas on how to get the data only, and not the whole window, to update as the slider is moved? Apologies if this has been asked already, but I'm failing to find i…
tagged with: tkinter
linked to: http://stackoverflow.com/q/44416336
type: UnansweredQuestion

http://stackoverflow.com/q/51345136
answer count: 1
has comment: http://stackoverflow.com/comment/89663648
has answer: http://stackoverflow.com/a/51345343
tagged with: python
has comment: http://stackoverflow.com/comment/89663691
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89663666
has comment: http://stackoverflow.com/comment/89663659
has comment: http://stackoverflow.com/comment/89663826
type: Question
accepted answer: http://stackoverflow.com/a/51345343
has title: AttributeError: 'super' object has no attribute 'compare_files'
tagged with: inheritance
linked to: http://stackoverflow.com/q/6075758
score: 0
has body: Sample code with inheritance that works as expected. class Animal: def action(self, value_1, p=None): print ('Parent action %d %d' % (value_1, p)) return value_1 + 1 + p class Dog(Animal): def action(self, value): print ('Dog action in child') return super(Dog, self).action(value, 1) print(Dog().action(10)) Following is another example of inheritance where the following error is thrown. AttributeError: 'super' object has no attribute 'compare_files' class FileCompare: def compare_files(self, actual_filename, ref_filename, field_to_skip=None): return True class MetaFileCompare(FileCompare): def compare_files(self, actual_file, ref_file): return super(FileCompare, self).compare_files(actual_file, ref_file, 0) class WorkerFileCompare(FileCompare): def compare_files(self, actual_file, ref_file): return super(FileCompare, self).compare_files(actual_file, ref_file, 5) print (WorkerFileCompare().compare_files('a', 'b')) Code is almost same except for class name, method name and return type. Sounds like am missing something very silly. There are no typo errors. Can you please provide some pointers?

http://stackoverflow.com/comment/89735553
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51381375
has text: Also see the official Python [Unicode HOWTO](https://docs.python.org/2/howto/unicode.html) and [The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)](https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/) by SO co-founder Joel Spolsky.
type: Comment

http://stackoverflow.com/comment/89731548
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51379445
has text: Your INSERT names 5 columns but your VALUES clauses only specify 2 values.

http://stackoverflow.com/a/51383653
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51382357
accepted answer of: http://stackoverflow.com/q/51382357
has comment: http://stackoverflow.com/comment/89741239
type: Answer
has body: Use lookup: df1['PD'] = df2.lookup(df1.RATING,df1.TENOR.astype(str)) Output: RATING TENOR PD ID 1234 BBB 2.0 0.005100 2345 BB+ 1.5 0.009106 3456 BBB- 1.0 0.002800 Note: I had to use astype because my dtypes didn't match in my df2.columns and df1.TENOR. You'll have to check this you might not need to astype depending on your datatypes.

http://stackoverflow.com/comment/89790106
type: Comment
has text: I used the run_couroutine_threadsafe function as suggested, but it seems like then the couroutine never gets executed. I put these changes in another edit to the post.
comment on: http://stackoverflow.com/q/51371660
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89811528
type: AnswerComment
has text: @JakeWest It's not difficult at all. Just learn about XPath and add expressions you need.
type: Comment
comment on: http://stackoverflow.com/a/51395145
score: 0

http://stackoverflow.com/comment/89905168
has text: What are the contents of the `tweet_file`?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51466850

http://stackoverflow.com/q/51330928
has body: First timer here just beginning to teach myself python on Codecademy. I have a question about an exercise I completed def hotel_cost(days): return 140 * (days - 1) def plane_ride_cost(city): if city == "Charlotte": return 183 elif city == "Tampa": return 220 elif city == "Pittsburgh": return 222 elif city == "Los Angeles": return 475 def rental_car_cost(days): cost = days * 40 if days &gt;= 7: cost -= 50 elif days &gt;= 3: cost -= 20 return cost def trip_cost(city, days, spending_money): return rental_car_cost(days) + hotel_cost(days - 1) + plane_ride_cost(city) + spending_money print trip_cost("Charlotte", 5, 500) The above code about planning a trip works and makes sense to me. What I want to try to figure out for fun before continuing on to the next lesson is how I can add raw_inputs so that instead of inputting the values in print trip_cost on the last line I can have something like this city = raw_input("where are you going? ") days = raw_input("how many days are you staying? ") spending_money = raw_input("how much spending money are you bringing? ") I can't seem to figure out how to integrate that into the code. Any help? I know this is super basic but just getting my feet wet.
upvote count: 1
has answer: http://stackoverflow.com/a/51330979
downvote count: 1
answer count: 1
favorite count: 0
has title: Adding raw_inputs into this lesson on Codecademy
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89637610
tagged with: python
has comment: http://stackoverflow.com/comment/89638670
type: Question
has comment: http://stackoverflow.com/comment/89639372
has comment: http://stackoverflow.com/comment/89639166
has comment: http://stackoverflow.com/comment/89639034
score: 0

http://stackoverflow.com/q/51473607
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51475345
tagged with: python
tagged with: discord
score: 0
has title: How to add/create roles using commands in discord.py
type: Question
tagged with: discord.py
has body: so I'm trying to have a user look at a list of potential "roles", and based on what the user selects, (whether or not the role exists at the moment or not) the bot will either add the role to the user, or create a new role to add to the user. At the moment, I keep getting an error saying name "message" is not defined, but I'm not really sure what to do. Here is my code @client.command(pass_context = True) async def classes(): class_list = ["English", "Math", "Science", "History", "Geography", "French","Technology", "Comp_Sci", "Business", "Music", "Art"] entered_class = message.content role = discord.utils.get(message.server.roles, name=entered_class) roles = ["470082568163950612", "470082563696754708"] if role is None: await client.create_role(name=entered_class, mentionable=True) await client.add_roles(message.author, role) msg = 'Successfully created and added role{0.author.mention}'.format(message) await client.send_message(message.channel, msg) if role is True: await client.add_roles(message.author, role) await client.send_message(message.channel, msg) And heres my imports import discord from discord.utils import get from discord.utils import find from discord.ext import commands from discord.ext.commands import Bot TOKEN = 'NDcwMDYwMDc1MjgxODA5NDEw.DjQyZQ.j-YlOu5mZnDjpeUj32Nbc7wfbbs' client = Bot(command_prefix = "Wood!") Any help would be much appreciated
answer count: 1

http://stackoverflow.com/comment/89827895
has text: Good point, that completely slipped my mind when writing the answer. If they are on a UNIX like system though they shouldn’t have any issues - I use it myself
type: Comment
comment on: http://stackoverflow.com/a/51427781
score: 1
type: AnswerComment

http://stackoverflow.com/q/51371470
answer count: 2
downvote count: 2
has body: I'm missing the ability to print "The median cannot be found" based on there being nothing in the sequence. This is my current code using None, which doesn't work. def print_median(seq): if print_median(sep) = None: print("The median cannot be found.") else: median = (seq[len(seq) // 2 - 1] + seq[len(seq) // 2]) / 2 print("The median of " + str(seq) + " is " + str(median) + ".") Also tried using ((),) and a few random attempts that didn't work either. The expected outcome is &gt;&gt;&gt; print_median(()) The median cannot be found. as well as producing &gt;&gt;&gt; print_median((-12, 0, 3, 9)) The median of (-12, 0, 3, 9) is 1.5. for when there are numbers inputed to the seq.
has comment: http://stackoverflow.com/comment/89715355
favorite count: 0
has comment: http://stackoverflow.com/comment/89717182
tagged with: python
has answer: http://stackoverflow.com/a/51371569
has comment: http://stackoverflow.com/comment/89715067
tagged with: python-3.x
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89715047
score: -2
has title: Debugging: How to show a seq of nothing
has answer: http://stackoverflow.com/a/51371498
type: Question

http://stackoverflow.com/a/51329787
answers question: http://stackoverflow.com/q/51329742
has body: You can use the os library to execute system commands import os os.system("your command") you can add your wanted application to the system path to be able to execute it using system commands
score: 0
type: Answer

influxdb
tags question: http://stackoverflow.com/q/51366465
tag name: influxdb
type: Tag

http://stackoverflow.com/q/51448289
score: -1
has comment: http://stackoverflow.com/comment/89874266
answer count: 1
has comment: http://stackoverflow.com/comment/89867617
favorite count: 0
accepted answer: http://stackoverflow.com/a/51455577
has comment: http://stackoverflow.com/comment/89869311
has comment: http://stackoverflow.com/comment/89867208
tagged with: python
has body: I'm trying to implement a 4-option radiobutton, however, whenever I try to Place the radiobutton inside the window, each option gets placed on top of each other, instead of one below the other: MODES = [ ("First ", "1"), ("Second", "L"), ("Third ", "RGB"), ("Fourth", "CMYK") ] answer = StringVar() answer.set("L") for text, mode in MODES: RB = Radiobutton(root, text=text, variable = answer, value = mode, font = ("Segoe UI", 14), ) RB.place(x=20, y=90) However, when I Pack the radiobutton, and not Place the radiobutton, it seems to place the options one below the other, so is there a way to use the Place function, and still have the options display one below the other? Thanks in advance. Here's a screenshot for reference: As you can see, there's only one option being displayed, and all the others are underneath.
has comment: http://stackoverflow.com/comment/89879406
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89872511
tagged with: tkinter
downvote count: 1
has title: TkInter Radiobuttons placing each option on top of eachother
type: Question
has comment: http://stackoverflow.com/comment/89867209
has comment: http://stackoverflow.com/comment/89867659
has answer: http://stackoverflow.com/a/51455577
upvote count: 0
has comment: http://stackoverflow.com/comment/89867562

http://stackoverflow.com/q/51418416
has title: Variables in input questions
score: 0
accepted answer: http://stackoverflow.com/a/51418532
answer count: 1
has comment: http://stackoverflow.com/comment/89808044
has answer: http://stackoverflow.com/a/51418532
tagged with: input
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89808049
has body: So, I know that if you do: variable1 = 10 variable2 = variable1 then variable2 will be 10. But if you do: variable1 = 10 and then ask for an input: variable2 = input("...") and type variable1 as the input, then variable2 will be 'variable1' instead of 10. How can I change this so that variable2 equals variable1 after inputting the string variable1?
type: Question
tagged with: variables

http://stackoverflow.com/comment/89939955
score: 0
type: QuestionComment
type: Comment
has text: You're correct, they do not use more than one graph. Do you imagine using python control expressions to select which graph to use for each batch? Or do you imagine this being done using tf.cond() and conditional graphs?
comment on: http://stackoverflow.com/q/51470270

http://stackoverflow.com/a/51410231
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89876699
downvote count: 0
answers question: http://stackoverflow.com/q/51410104
has body: You seem to have a misconception here: But sometimes the folder has no log files, so nothing happen. I could add an if statement to check every cycle of the for loop, if the value of logs is not None… That won't do anything. If there are no logs, the glob will return an empty list, and that won't run your loop with logs=None, it just won't run your loop at all: &gt;&gt;&gt; files = [] &gt;&gt;&gt; for file in files: ... if file is None: ... print('None') ... else: ... print(file) This will print nothing at all. If you want to test whether there were any results, the simplest thing to do is just test the results: files = glob.glob('*.log') for file in files: # do something if not files: print('No files') This isn't a fully general solution, if the iterable you're looping over could be an iterator rather than a sequence or other container. A sequence is truthy if and only if it's non-empty, but an iterator is always truthy. Plus, there's no way to check whether an iterator is empty except by iterating it. So, the general solution, that works even with iterators, requires some kind of flag or counter. Sometimes a hacky solution like this is readable enough: file = None for file in glob.glob('*.log'): # do something if file is not None: print('Empty') … but I think in many cases (where the loop isn't so trivial that you can immediately connect the file = None above it to the test after it, or where you can't use None because it's a valid value for the iterable, etc.), you're better off being explicit. Or, if you know that you're getting a sequence, as you do with glob, just do the simple if not seq: test described above.
type: Answer

http://stackoverflow.com/q/51349752
type: AnsweredQuestion
downvote count: 0
favorite count: 0
upvote count: 8
type: Question
tagged with: google-api
has answer: http://stackoverflow.com/a/51356033
tagged with: google-api-python-client
tagged with: python
possible better answer: http://stackoverflow.com/a/51356033
answer count: 2
has answer: http://stackoverflow.com/a/51349957
has body: i want to read an write data from a sheet, reading works fine but writing doesn't. i use all the scopes mentioned in the documentation: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append data_writer(1,1,1) code: from __future__ import print_function from apiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools # Setup the Sheets API SCOPES = 'https://www.googleapis.com/auth/spreadsheets'+"https://www.googleapis.com/auth/drive.file"+"https://www.googleapis.com/auth/drive" store = file.Storage('credentials.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store) service = apiclient.discovery.build('sheets', 'v4', http=creds.authorize(Http())) # Call the Sheets API SPREADSHEET_ID = '1JwVOqtUCWBMm_O6esIb-9J4TgqAmMIdYm9sf5y-A7EM' RANGE_NAME = 'Jokes!A:C' # How the input data should be interpreted. value_input_option = 'USER_ENTERED' # How the input data should be inserted. insert_data_option = 'INSERT_ROWS' def data_reader(): #reading data read = service.spreadsheets().values().get(spreadsheetId=SPREADSHEET_ID,range=RANGE_NAME).execute() #reading values values = read.get('values', []) if not values: print('No data found.') else: for row in values: print(row[2]) continue def data_writer(score,num_comments,mystring): value_range_body = { "score":score, "num_comments":num_comments, "joke":mystring } request = service.spreadsheets().values().append(spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME, valueInputOption=value_input_option, insertDataOption=insert_data_option, body=value_range_body) response = request.execute()
score: 8
tagged with: anaconda
accepted answer: http://stackoverflow.com/a/51349957
has title: google api (sheets) Request had insufficient authentication scopes
tagged with: google-oauth

http://stackoverflow.com/q/51411590
type: Question
has title: Appending onto Raw_input
has answer: http://stackoverflow.com/a/51411698
score: 0
accepted answer: http://stackoverflow.com/a/51411609
has body: In my code, I have the user input a file name. I would like to append .txt to the end of their input, so they don't have to. (filename vs filename.txt) I've tried a couple different methods, but here is my current (not working) version. from twitter_keys import * import requests # Load the UID list filetype = ".txt" filename = raw_input("Copy/Paste the Filename here: "), filetype with open (filename, "r") as myfile: data = myfile.read() print data Looking at my debugger, I see how it's not working, but I can't find a good solution on how I should better go about it. Debugger output: print filename ('StrangeBeacons-20180718-144446-followers', '.txt') I'm sure there's an easy way to do this, but I'm probably not asking the right question when I search for posts or documentation.
answer count: 3
tagged with: file-handling
has answer: http://stackoverflow.com/a/51411609
tagged with: python
possible better answer: http://stackoverflow.com/a/51411698
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51411634

http://stackoverflow.com/q/51448505
tagged with: django-queryset
has title: Django: sorting by datetime field is only accurate to minutes, not seconds?
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89882538
has comment: http://stackoverflow.com/comment/89867786
tagged with: time
tagged with: python
has comment: http://stackoverflow.com/comment/89880367
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: django
has body: Is there a way to make Django consider seconds (and even milliseconds) ordering a queryset by a DateTime field? I want to display a table with the results of my blood tests ordered in reverse chronological order. It works, as long as tests aren't added in the same minute. If they are only separated by seconds, they are listed in chronological order for the duration of that minute. models.py class BloodTest(models.Model): patient = models.ForeignKey(Patient, on_delete=models.CASCADE) name = models.CharField(max_length=20, choices=BLOOD_TEST_CHOICES, default=BILIRUBIN) value = models.PositiveSmallIntegerField(max_length=10) time = models.DateTimeField(default=timezone.now(), validators= [validate_date]) views.py def blood_list(request, blood_id): blood = BloodTest.objects.get(id=blood_id) patient = blood.patient blood_list = BloodTest.objects.filter(name=blood.name).filter(patient=patient.id).order_by('-time') context = {'blood_list': blood_list, 'patient': patient, 'blood': blood} return render(request, 'vitals/blood-list.html', context) blood-list.html template {% for blood in blood_list %} &lt;tr&gt; &lt;td&gt;{{ blood.time }}&lt;/td&gt; &lt;td&gt;&lt;a href="{% url 'blood' blood.id %}"&gt;{{ blood.value }}&lt;/a&gt;&lt;/td&gt; &lt;/tr&gt; {% endfor %}
score: 1
type: Question

http://stackoverflow.com/comment/113659956
type: Comment
has text: Sup buddy. Do'nt forget to choose one poste as "the answer". ;)
type: QuestionComment
comment on: http://stackoverflow.com/q/51351089
score: 0

http://stackoverflow.com/comment/89823907
score: 0
type: AnswerComment
has text: try the code and let me know if you need any further explanation/clarification.
type: Comment
comment on: http://stackoverflow.com/a/51426236

http://stackoverflow.com/a/51470709
type: Answer
score: 6
has comment: http://stackoverflow.com/comment/89909813
upvote count: 6
has body: Maybe usingpd.concat is slightly faster than reindex pd.concat([df]*len([0,1,2])).sort_index().assign(time=[0,1,2]*len(df)) Out[275]: A B time 0 1 12 0 0 1 12 1 0 1 12 2 1 2 23 0 1 2 23 1 1 2 23 2 2 3 34 0 2 3 34 1 2 3 34 2 3 4 45 0 3 4 45 1 3 4 45 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51470602
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51470602

http://stackoverflow.com/a/55685603
score: -2
downvote count: 2
type: Answer
has body: Have you tried to prefix it with dbo. something like: dbo.tablename I was playing around with it today and had the same issue and adding the dbo part worked :-)
answers question: http://stackoverflow.com/q/51423154
upvote count: 0

http://stackoverflow.com/comment/89921691
has text: @Datanovice - It was converted possible non string values to `string`s after removing missing values.
type: Comment
comment on: http://stackoverflow.com/a/51476462
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89836841
type: Comment
comment on: http://stackoverflow.com/a/51433019
score: 0
type: AnswerComment
has text: This works (thanks!) but I'm still slightly confused (however, as you say, this may be a bug), add "ax2.set_visible(False)" before plt.show().... The wrong axis disappears...! Am I going crazy?!

http://stackoverflow.com/q/51347115
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89667497
score: 3
has comment: http://stackoverflow.com/comment/89667477
has comment: http://stackoverflow.com/comment/89667576
has comment: http://stackoverflow.com/comment/89667243
upvote count: 3
tagged with: dataframe
type: Question
has title: Compute a new dataframe following specific set of rules
has comment: http://stackoverflow.com/comment/89667628
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89668528
has comment: http://stackoverflow.com/comment/89667221
tagged with: pandas-groupby
has answer: http://stackoverflow.com/a/51370940
tagged with: pandas
has comment: http://stackoverflow.com/comment/89667521
has body: I have a dataframe with 4 columns Dataframe 1: column_A column_B column_C id 0 1 1 anna 123 1 2 1 anna 7 2 30 2 bob 42 3 20 2 bob 12 4 10 2 charlie 1 5 100 3 charlie 2 Now, I want to compute a new Dataframe (Dataframe 2) with the following properties id_1 id_2 val 0 123 7 1 1 42 12 1 2 42 1 2 3 12 1 2 4 1 2 3 val == 1, if across rows both corresponding values in column_B and column_C match val == 2, if across rows only corresponding value in column_B match val == 3, if across rows only corresponding value in column_C match My current implementation is O(N^2). Considering the dataframe is large, is there some parallelization i can use to speed up the processing. We can also interpret the Question as finding pair of row index in a Pandas Dataframe where value in column_B, column_C is same. example: Row[0] and row[1] have same values in column_B and column_C
has comment: http://stackoverflow.com/comment/89667350
has comment: http://stackoverflow.com/comment/89668548

http://stackoverflow.com/comment/89709124
score: 0
comment on: http://stackoverflow.com/q/51368187
has text: No, it's not a scaling issue. It's that you are plotting strings, which you shouln't. See duplicate.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51330240
upvote count: 1
type: Answer
has body: As stated in other answers, your error comes from calculating the length of your input at the start and then not updating it as you shorten the list. Here's another take at a working solution: with open('toy.txt', 'r') as infile: input_lines = reversed(map(lambda s: s.strip(), infile.readlines())) output = [] for pattern in input_lines: if len(output) == 0 or not output[-1].startswith(pattern): output.append(pattern) print('\n'.join(reversed(output)))
downvote count: 0
answers question: http://stackoverflow.com/q/51327765
score: 1

http://stackoverflow.com/a/51379019
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89729595
type: Answer
accepted answer of: http://stackoverflow.com/q/51378815
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51378815
has comment: http://stackoverflow.com/comment/89729942
has body: Change from radial import rad to from .radial import rad The . allows the file to look locally rather than within the working directory.

http://stackoverflow.com/comment/89646258
has text: Is there a way to do this in `O(n) time and O(1) space`.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51335501
type: Comment

http://stackoverflow.com/q/51408066
tagged with: python
has body: I am using scrapy to scrape this website: https://www.cartrade.com/buy-used-cars/p-10 My code: import scrapy class ShopcluesSpider(scrapy.Spider): name = 'example' allowed_domains = ['www.cartrade.com/buy-used-cars'] start_urls = ['https://www.cartrade.com/buy-used-cars/'] custom_settings = { 'FEED_URI' : 'tmp/data.csv'} def parse(self, response): # Extract product information titles = response.xpath('//div[@class = "carimgblk"]/a/img/@title').extract() URLs = response.xpath('//div[@class = "carimgblk"]/a/meta/@content').extract() prices = response.xpath('//div[@class = "cr_prc"]/text()').extract() for item in zip(titles,prices,URLs): scraped_info = { 'title' : item[0].strip(), 'price' : item[1].strip().replace(',', ''), 'URL': item[2].strip(), } yield scraped_info next_page = response.css('li.next a::attr(href)').extract_first() if next_page: yield scrapy.Request(response.urljoin(next_page),callback=self.parse) The issue is that it's not scraping all pages. I also noticed prices are not totally correct. What am I doing wrong?
type: UnansweredQuestion
has title: Scraping multiple pages using scrapy
tagged with: scrapy
type: Question
has comment: http://stackoverflow.com/comment/89798446
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51413474

http://stackoverflow.com/comment/89842607
type: Comment
has text: it cannot connect with database mysql
comment on: http://stackoverflow.com/a/51436379
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89654644
has text: So check what is the version of python and edit if need `yum` command. And do not use binary from `/tmp`, reinstall is sample and safe
comment on: http://stackoverflow.com/q/51340142
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/51380752
upvote count: 2
has comment: http://stackoverflow.com/comment/89743972
downvote count: 1
favorite count: 0
has body: I have an app that's outputting a JSON through a socket which was working fine in the past, however recently the socket doesn't seem to be establishing and it continuously POST &amp; GET's with the lines: &lt;user_ip&gt;,&lt;client_ip&gt; - - [17/Jul/2018 12:48:17]"GET /socket.io/?EIO=3&amp;transport=polling......HTTP/1.1" 200 221 0.000000 &lt;user_ip&gt;,&lt;client_ip&gt; - - [17/Jul/2018 12:48:17]"POST /socket.io/?EIO=3&amp;transport=polling......HTTP/1.1" 200 243 0.517600 Additionally, when the WebSocket first tries, I can see from Chromes console the message: WebSocket connection to ..... failed: Establishing a tunnel via proxy server failed. I've also had a look through what I think is a similar issue based on socketIO-client but wasn't able to resolve my problem. Can anyone help with overcoming this connection issue? Included a full log on running the app below: Server initialized for eventlet. * Debugger is active! * Debugger PIN: 129-744-633 (7616) wsgi starting up on http://0.0.0.0:6328 (7616) accepted (&lt;client_ip&gt;, 50548) &lt;user_ip&gt;,&lt;client_ip&gt; - - [17/Jul/2018 13:18:23] "GET /&lt;app_url&gt; HTTP/1.1" 200 1664 0.015000 3602c46fa50247eb9d397fda82f3eae8: Sending packet OPEN data {'sid': '3602c46fa50247eb9d397fda82f3eae8', 'upgrades': ['websocket'], 'pingTimeout': 60000, 'pingInterval': 25000} 3602c46fa50247eb9d397fda82f3eae8: Sending packet MESSAGE data 0 &lt;user_ip&gt;,&lt;client_ip&gt; - - [17/Jul/2018 13:18:23] "GET /socket.io/?EIO=3&amp;transport=polling&amp;t=1531829903367-0 HTTP/1.1" 200 381 0.000000 (7616) accepted (&lt;client_ip&gt;, 50560) 3602c46fa50247eb9d397fda82f3eae8: Received packet MESSAGE data 0/testnamespace 3602c46fa50247eb9d397fda82f3eae8: Sending packet MESSAGE data 0/testnamespace &lt;user_ip&gt;,&lt;client_ip&gt; - - [17/Jul/2018 13:18:23] "POST /socket.io/?EIO=3&amp;transport=polling&amp;t=1531829903377-1&amp;sid=3602c46fa50247eb9d397fda82f3eae8 HTTP/1.1" 200 221 0.000000 &lt;user_ip&gt;,&lt;client_ip&gt; - - [17/Ju…
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89744687
answer count: 0
score: 1
tagged with: flask-socketio
has title: Flask-SocketIO socket fails to connect and continuously re-attempts
type: Question
tagged with: flask

http://stackoverflow.com/a/75344194
has body: How about broadening your search space to include VS Code Server as an alternative? It closely resembles the classic Windows (GUI) version, but it has client-server architecture, so your code resides and runs on the server, but the user interface is rendered locally in the browser, so no graphical desktop needs to be installed on the server.
type: Answer
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51465212

http://stackoverflow.com/q/51392184
tagged with: mqtt
tagged with: python
tagged with: kivy
has comment: http://stackoverflow.com/comment/89756636
has body: I'm using kivy 1.11.0 with python 2.7.15. #-*- coding: utf-8 -*- import paho.mqtt.client as mqtt from kivy.app import App from kivy.uix.screenmanager import ScreenManager, Screen from kivy.uix.image import Image from kivy.lang import Builder Builder.load_string(""" &lt;InitScreen&gt;: AnchorLayout: anchor_x:"center" anchor_y:"center" Label: text:"init" &lt;WaitScreen&gt;: Image: id:charactor pos_hint:{'center_x':.5,'y':0 } size_hint:1,1 source:'./wait1.png' """) class Charactor(Image): pass class InitScreen(Screen): pass class WaitScreen(Screen): def __init__(self, **kwargs): super(WaitScreen, self).__init__(**kwargs) class View(App): sm = ScreenManager() cli = mqtt.Client(protocol=mqtt.MQTTv311) def __init__(self, **kwargs): super(View, self).__init__(**kwargs) def build(self): self.sm.add_widget(InitScreen(name='init')) self.sm.current='init' return self.sm def on_start(self): self.cli.on_connect = self.on_connect self.cli.on_message = self.on_message self.cli.connect('localhost', port=1883, keepalive=60) self.cli.loop_start() def on_connect(self,client, userdata, flags, respons_code): print('status {0}'.format(respons_code)) client.subscribe('get/test') def on_message(self,client, userdata, msg): self.changeScreen() def changeScreen(self,**kwargs): self.sm.add_widget(WaitScreen(name='wait')) self.sm.current='wait' if __name__ == '__main__': View().run() if get message(on_message), change screen but error happed Fatal Python error: (pygame parachute) Segmentation Fault i think detected the cause of error have Image. When on_message load Image source, error happened I think paho.mqtt callback(on_message,on_connect） is doubtful because When self.changeScreen() is in def on_start,def build, error not happened below code is error has not happened class View(App): sm = ScreenManager() cli = mqtt.Client(protocol=mqtt.MQTTv311) waitflag = False def __init__(self, **kwargs): super(View, self).__init__(**kwargs) def build(self): self.sm.add_widget(InitScreen(name='init')) …
has comment: http://stackoverflow.com/comment/89756506
has title: Kivy+mqtt-When on_message,Fatal Python error: (pygame parachute) Segmentation Fault
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51398564
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89757823
has comment: http://stackoverflow.com/comment/89756647
has answer: http://stackoverflow.com/a/51406541
score: -1
answer count: 2
upvote count: 0
tagged with: paho
favorite count: 0
tagged with: python-2.7

http://stackoverflow.com/comment/89824863
comment on: http://stackoverflow.com/q/51419256
score: 0
type: QuestionComment
type: Comment
has text: Are you building a source dist or a wheel? What error do you get? If you update your question with error details (or ask a new one and link it here), I will try to help.

http://stackoverflow.com/comment/89697747
type: QuestionComment
comment on: http://stackoverflow.com/q/51362459
has text: We don't need to see your entire program, just the minimal amount required to reproduce the issue. There's a *lot* that can be trimmed out.
score: 0
type: Comment

http://stackoverflow.com/a/51391303
has comment: http://stackoverflow.com/comment/89772275
answers question: http://stackoverflow.com/q/51390819
score: 0
type: Answer
has body: Will the size just increases as we use the field? Yes. It's possible to define a max_length in a TextField(), but according to the docs: "it is not enforced at the model or database level. Use a CharField for that".
has comment: http://stackoverflow.com/comment/89760322

http://stackoverflow.com/a/51460932
type: Answer
has comment: http://stackoverflow.com/comment/89891442
score: 1
upvote count: 1
downvote count: 0
has body: Make sure all your return values are the same type. You need to use arrays but you're using ints when you return zero. Fixed: def change(amount): if amount &lt; 24: return [0] assert(amount &gt;= 24) if amount == 24: return [5, 5, 7, 7] if amount == 25: return [5, 5, 5, 5, 5] if amount == 26: return [5, 7, 7, 7] if amount &gt; 1000: return [0] coins = change(amount - 5) coins.append(5) return coins
answers question: http://stackoverflow.com/q/51460879

http://stackoverflow.com/a/51471213
answers question: http://stackoverflow.com/q/51471188
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51471188
type: AcceptedAnswer
has body: IIUC (I guess first column A in df1 is ['A','B','B'] ) df.groupby(['A','B']).agg({'C':'count','D':lambda x : sum(x=='y')}).reset_index() Out[285]: A B C D 0 A N 2 1 1 B N 1 0 2 B S 2 1
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/q/51336958
has comment: http://stackoverflow.com/comment/89648662
tagged with: class
has comment: http://stackoverflow.com/comment/89648677
score: 0
has body: A question from a beginner: Can someone explain to me please why the method change_pos isn't working and doesn't change the sitting position from True to False (and either the opposite way) in the following code? How do I implement this change_pos method to whole instances (p1, p2) in one line of code? class Person: def __init__(self, name, Personality, isSitting): self.name=name self.Personality = Personality self.isSitting=isSitting def sit_down(self): self.isSitting=True def stand_up(self): self.isSitting=False def change_pos(self): if (self.isSitting==True): self.isSitting==False else: self.isSitting==True p1=Person("Alice", "aggressive", False) p2=Person("Becky", "talkative", True) print (p1.name,'is', p1.isSitting ,'about sitting') print (p2.name,'is', p2.isSitting ,'about sitting') p2.change_pos() print (p1.name,'is', p1.isSitting ,'about sitting') print (p2.name,'is', p2.isSitting ,'about sitting') The output is: Alice is False about sitting Becky is True about sitting Alice is False about sitting Becky is True about sitting
has comment: http://stackoverflow.com/comment/89648594
has comment: http://stackoverflow.com/comment/89648625
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89649351
answer count: 0
has comment: http://stackoverflow.com/comment/89648779
tagged with: methods
linked to: http://stackoverflow.com/q/8381735
has title: Python - operate a method
has comment: http://stackoverflow.com/comment/89648674
type: Question
duplicate of: http://stackoverflow.com/q/8381735

http://stackoverflow.com/a/51346575
type: AcceptedAnswer
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/51346268
score: 1
accepted answer of: http://stackoverflow.com/q/51346268
has body: This summary_name[i] assumes that there already is something that has the name summary_name and that allows access using [i]. Since Python is a dynamic language, this can be anything. All that is necessary to use [i] on an object is to implement object.__getitem__ for reading and object.__setitem__ for writing. How is Python supposed to know which of the many classes that do this you want summary_name to be an instance of? So you first have to define summary_name, for example as an empty list summary_name = ["I", "am", "a", "list"] a tuple summary_name = ("I", "am", "a", "tuple") or a string summary_name = "I am a string." All these allow read access using summary_name[i]. Since you want to use write access, you must define an object that allows summary_name[i] = something. A list with 100 entries, all initialized to None could be created using summary_name = [None] * 100 Only after this can you set entries of this list.
upvote count: 1

http://stackoverflow.com/comment/90029087
score: 0
type: QuestionComment
has text: Thanks for your comment. It's my first time to ask question on stackoverflow, made some stupid mistakes. But the real problem is the resolution of the photo(full.png) which is too large. I reduced the resolution by half and it worked.
type: Comment
comment on: http://stackoverflow.com/q/51372854

http://stackoverflow.com/a/51482088
has comment: http://stackoverflow.com/comment/89947894
accepted answer of: http://stackoverflow.com/q/51481923
has body: The biggest gain is likely to come from calling split only once per line size, path = line.strip().split("\t") # or ...split("\t", 3)[0:2] if there are extra fields to ignore You can at least simplify your code by treating the input file as an iterator and using the csv module. This might give you a speed-up as well, as it eliminates the need for an explicit call to split: with open(filepath, "r") as open_file: reader = csv.reader(open_file, delimiter="\t") writer = csv.writer(streamed_file) for size, path in reader: is_dir = os.path.isdir(path) writer.writerow([is_dir, size, path])
has comment: http://stackoverflow.com/comment/89961894
type: Answer
downvote count: 0
score: 7
has comment: http://stackoverflow.com/comment/89940862
has comment: http://stackoverflow.com/comment/89934090
answers question: http://stackoverflow.com/q/51481923
upvote count: 7
type: AcceptedAnswer

http://stackoverflow.com/a/56815975
upvote count: 0
has body: for Anaconda 2019.03 with Python 3.7 version for CPU create command: conda create -n tensorflow_env tensorflow activate command: conda activate tensorflow_env Import command: (tensorflow_env) C:\WINDOWS\system32>python import tensorflow as tf print(tf.version) for GPU create command: conda create -n tensorflow_gpuenv tensorflow-gpu activate command: conda activate tensorflow_gpuenv Import command: (tensorflow_gpuenv) C:\WINDOWS\system32>python import tensorflow as tf print(tf.version)
answers question: http://stackoverflow.com/q/51402053
score: -1
downvote count: 1
type: Answer

http://stackoverflow.com/q/51342472
favorite count: 0
tagged with: python-3.x
tagged with: tkinter
has comment: http://stackoverflow.com/comment/89658561
has comment: http://stackoverflow.com/comment/89658512
tagged with: python
tagged with: lambda
has comment: http://stackoverflow.com/comment/89658490
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51342493
score: 1
linked to: http://stackoverflow.com/q/3431676
type: Question
has comment: http://stackoverflow.com/comment/89658424
has answer: http://stackoverflow.com/a/51342493
tagged with: for-loop
has comment: http://stackoverflow.com/comment/89658402
has title: How to make python loop remember each value?
upvote count: 2
has body: Whenever I dynamically create buttons in tkinter through a loop, to call a function with a value assigned to them through the loop, like so: from tkinter import * root=Tk() def add(text): print(text) for i in ('a', 'b', 'c'): Button(root, text=i, command=lambda:add(i)).pack() mainloop() I always have the problem that the function is called with the last value in the loop, whatever button I press. In this case, it simply prints c whatever button I press. I do not know if this is a problem with lambda or tkinter, or simply my programming, but I would like to know how to fix it. I have tried using copy.copy, copy.deepcopy (on the lambda function and the string), and [:] and str (on the string).
duplicate of: http://stackoverflow.com/q/3431676
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/89799556
comment on: http://stackoverflow.com/a/51413842
type: AnswerComment
has text: I don't know why this was downvoted. Given that the bug has been fixed upstream (but not released), I think it's probably better to install from the repo than to fix it locally, but I don't see anything wrong with explaining how to fix it locally…
type: Comment
score: 3

http://stackoverflow.com/q/51438158
score: -1
has comment: http://stackoverflow.com/comment/89846629
accepted answer: http://stackoverflow.com/a/51438240
answer count: 2
has comment: http://stackoverflow.com/comment/89846348
has comment: http://stackoverflow.com/comment/89846267
favorite count: 0
has comment: http://stackoverflow.com/comment/89846409
has title: Getting different output while deleting element from list in python3
tagged with: python
has answer: http://stackoverflow.com/a/51438240
tagged with: python-3.x
tagged with: list
downvote count: 2
possible better answer: http://stackoverflow.com/a/51438278
upvote count: 1
has answer: http://stackoverflow.com/a/51438278
linked to: http://stackoverflow.com/q/1207406
has comment: http://stackoverflow.com/comment/89846458
type: Question
type: AnsweredQuestion
has body: I want to check every number with every number in a list without repeating any checks. This code: a = [0,1,2,3,4] b = a for i in a : for j in b: print(i,j) del b[0] It gives the output: 0 0 0 1 0 2 0 3 0 4 2 1 2 2 2 3 2 4 4 2 4 3 4 4 The output I want is: 0 0 0 1 0 2 0 3 0 4 1 1 1 2 1 3 1 4 2 2 2 3 2 4 3 3 3 4 4 4 Why does i skip 1 and 3? It is fixed when I remove the line 'del b[0]' but to my understanding, this line should not have any impact on the value of 'i'
has comment: http://stackoverflow.com/comment/89846319
duplicate of: http://stackoverflow.com/q/1207406

http://stackoverflow.com/comment/89866388
type: QuestionComment
comment on: http://stackoverflow.com/q/51447877
has text: Don't put extraneous spaces in your connection string. For example, use `DRIVER={ODBC...` not `DRIVER = {ODBC...`
score: 0
type: Comment

http://stackoverflow.com/comment/89711543
comment on: http://stackoverflow.com/q/51369303
type: Comment
type: QuestionComment
score: 0
has text: What makes you think that weights are normally distributed? If you don't know the distribution, you should be using Chebyshev's inequality, which gives non-parametric bounds.

http://stackoverflow.com/a/51468856
type: Answer
has comment: http://stackoverflow.com/comment/90137090
has comment: http://stackoverflow.com/comment/90094953
score: 0
answers question: http://stackoverflow.com/q/51448085
has body: No. You must specify the object points. Note that they need not change across the image sequence, since you can interpret the change as due to camera motion relative to the target. Also, you can (should) assume that Z=0 for a planar target like yours. You may specify X,Y up to scale, and thus obtain after calibration translations up to scale. No Clarification: by "need not change across the image sequence" I mean that you can assume the target fixed in the world frame, and interpret the relative motion as due to the camera only. The world frame itself, absent a better prior, can be defined by the pose of the target in any one of the images (say, the first one). Obviously, I do not mean that the pose of the target relative to the camera does not change - in fact, it must change in order to obtain a calibration. If you do have a better prior, you should use if. For example, if the target moves on a turntable, you should solve directly for the parameters of the cylindrical motion, since there is less of them (one constant axis, one constant radius, plus one angle per image, rather than 6 parameters per image).

http://stackoverflow.com/comment/89903972
score: 0
type: Comment
type: QuestionComment
has text: Your code is clearer now, but I am still not following what the error/problem is? As long as your function are defined above stat_frac_sales, they are fair game to be used downstream by your stat_frac_sales function. Also as long as FCF, EBIT, and import_sales returns a int or float then you should be good to go
comment on: http://stackoverflow.com/q/51466241

http://stackoverflow.com/comment/89657255
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51341882
has text: You should grab a working RandomForestClassifier examples from scikit-learn docs/tutorials to build upon - and keep in mind it will want an array of purely-numeric datapoints ('X') and results ('y') for its `fit()` step. Hard to say more there until you've tried more. But you're doing `Doc2Vec` wrong. Don't change the default `alpha` values. Don't call `train()` more than once unless you absolutely need to (and you don't).
type: Comment

http://stackoverflow.com/a/53766441
answers question: http://stackoverflow.com/q/51392779
type: Answer
has body: Because there are two wrong things in your answer. The first one is that you don't write your value for N, you've got to get the user in. Secondly, the math operation is wrong. You need to fix print(i ** 2) as print(i * 2) so you can get the result they want. That's probably why it doesn't accept. My answer to the same question had been as follows. if __name__ == '__main__': n = int(input("")) i = 0 while i &lt; n: r = i * i i += 1 print(r)
score: 0

http://stackoverflow.com/a/51470677
has comment: http://stackoverflow.com/comment/89909728
type: AcceptedAnswer
downvote count: 0
has body: One issue with the original answer in this post is that the transformation converts the integers to objects. This happens after the transpose since now the same column stores integers as well as the index which is textual. Instead, you can sidestep the issue like this: out = df.reset_index(drop=True).T.drop_duplicates().T.set_index(df.index) out var0 var2 s1 0 2 s2 0 4 s1 0 8 s2 0 12 Or, if your actual example is sufficiently different that you can't use the above, there is always casting, i.e. out.astype(int)
type: Answer
score: 3
accepted answer of: http://stackoverflow.com/q/51470552
upvote count: 3
answers question: http://stackoverflow.com/q/51470552

http://stackoverflow.com/a/51500380
type: Answer
has body: Best way now is using the keras module in tensorflow: from tensorflow import keras mnist = tf.keras.datasets.mnist (train_images, train_labels),(test_images, test_labels) = mnist.load_data()
downvote count: 0
score: 6
answers question: http://stackoverflow.com/q/51480927
upvote count: 6

http://stackoverflow.com/comment/89981632
type: Comment
has text: I'm curious, why would using 4 UDFs (albeit built-in) passing data back and forth between dfs and regular types be better than one udf
comment on: http://stackoverflow.com/a/51450431
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89730531
comment on: http://stackoverflow.com/q/51379445
type: Comment
type: QuestionComment
has text: What does`print("## SQL: " + columnInsertSql)` print?
score: 1

http://stackoverflow.com/comment/89910891
type: AnswerComment
type: Comment
has text: https://stackoverflow.com/questions/51471241/python-replacing-scores-with-actual-valuetransposing
comment on: http://stackoverflow.com/a/51435426
score: 0

http://stackoverflow.com/q/51423438
score: 2
tagged with: anaconda
type: Question
tagged with: intellij-idea
tagged with: python-3.6
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/51424024
has body: In my Python project developed in IntellijIDEA, I have the file requirements.txt with the following content: paho-mqtt==1.3.1 scipy=0.19.0 utm==0.4.2 pandas==0.22.0 shapely=1.3.3 pyproj=1.9.5.1 When I build the project, I get the error: Solving environment: ...working... failed PackagesNotFoundError: The following packages are not available from current channels: - paho-mqtt==1.3.1 Current channels: - https://repo.continuum.io/pkgs/main/osx-64 - https://repo.continuum.io/pkgs/main/noarch - https://repo.continuum.io/pkgs/free/osx-64 - https://repo.continuum.io/pkgs/free/noarch - https://repo.continuum.io/pkgs/r/osx-64 - https://repo.continuum.io/pkgs/r/noarch - https://repo.continuum.io/pkgs/pro/osx-64 - https://repo.continuum.io/pkgs/pro/noarch I was able to build this project on another laptop without any problem. I am using Python 3.6 and the Python SDK path is the following: /Users/mimi/anaconda3/bin/python.
favorite count: 0
tagged with: python-3.x
upvote count: 2
has title: Cannot install some libraries from requirements.txt in IntellijIDEA
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/89887593
type: QuestionComment
comment on: http://stackoverflow.com/q/51446751
has text: The typewrite() function doesn't return anything, it just sends keystrokes to whatever window has focus. Also, PyAutoGUI can't detect when the user clicks the mouse or presses a key, it can only send clicks and keystrokes.
score: 0
type: Comment

http://stackoverflow.com/comment/89893668
comment on: http://stackoverflow.com/q/51453681
has text: Why do you think my comments would be helpful? I don't use windows and I don't use Eclipse.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90297702
score: 0
has text: This is just how `numpy` converts `float` types to `str`, it will add a trailing `.0`. Converting a float value using `str()` produces the same result, so this is just the _stringification_ of a `float` type number.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51325032

http://stackoverflow.com/q/51421992
has answer: http://stackoverflow.com/a/51426380
score: 4
type: Question
tagged with: numpy
favorite count: 0
has comment: http://stackoverflow.com/comment/89829156
answer count: 3
possible better answer: http://stackoverflow.com/a/51425759
accepted answer: http://stackoverflow.com/a/51422461
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/89829779
downvote count: 0
has answer: http://stackoverflow.com/a/51422461
has title: How to vectorize a python function that loops over an array of 3D points?
tagged with: numba
has comment: http://stackoverflow.com/comment/89829752
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89820987
has answer: http://stackoverflow.com/a/51425759
has body: Here is the code: import numpy as np from numpy.random import random @profile def point_func(point, points, funct): return np.sum(funct(np.sqrt(((point - points)**2)).sum(1))) @profile def point_afunc(ipoints, epoints, funct): res = np.zeros(len(ipoints)) for idx, point in enumerate(ipoints): res[idx] = point_func(point, epoints, funct) return res @profile def main(): points = random((5000,3)) rpoint = random((1,3)) pres = point_func(rpoint, points, lambda r : r**3) ares = point_afunc(points, points, lambda r : r**3) if __name__=="__main__": main() I have profiled it with kernprof and gotten this: Timer unit: 1e-06 s Total time: 2.25667 s File: point-array-vectorization.py Function: point_func at line 4 Line # Hits Time Per Hit % Time Line Contents ============================================================== 4 @profile 5 def point_func(point, points, funct): 6 5001 2256667.0 451.2 100.0 return np.sum(funct(np.sqrt(((point - points)**2)).sum(1))) Total time: 2.27844 s File: point-array-vectorization.py Function: point_afunc at line 8 Line # Hits Time Per Hit % Time Line Contents ============================================================== 8 @profile 9 def point_afunc(ipoints, epoints, funct): 10 1 5.0 5.0 0.0 res = np.zeros(len(ipoints)) 11 5001 4650.0 0.9 0.2 for idx, point in enumerate(ipoints): 12 5000 2273789.0 454.8 99.8 res[idx] = point_func(point, epoints, funct) 13 1 0.0 0.0 0.0 return res Total time: 2.28239 s File: point-array-vectorization.py Function: main at line 15 Line # Hits Time Per Hit % Time Line Contents ============================================================== 15 @profile 16 def main(): 17 1 145.0 145.0 0.0 points = random((5000,3)) 18 1 2.0 2.0 0.0 rpoint = random((1,3)) 19 20 1 507.0 507.0 0.0 pres = point_func(rpoint, points, lambda r : r**3) 21 22 1 2281731.0 2281731.0 100.0 ares = point_afunc(points, points, lambda r : r**3) So this part is taking most of the time: 11 5001 4650.0 0.9 0.2 for idx, point in enumerate(ipoints): 12 5000…

frozenset
tags question: http://stackoverflow.com/q/51413212
tag name: frozenset
type: Tag

http://stackoverflow.com/comment/89732836
score: 0
type: AnswerComment
has text: @AzatIbrakov, there is a lot wrong with his code, in both if statement logic and variable usage and syntax. But his question was: why aren't the rest of the if- statements after `if n%2 is 0:` not working. I answered because his if statements make no sense, the rest he can figure out on his own. I am not here to finish his homework. Also I think he meant to write `n**(1/3)` but mistakenly wrote `-` instead of `/`.
comment on: http://stackoverflow.com/a/51380562
type: Comment

http://stackoverflow.com/q/51441787
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51442152
has comment: http://stackoverflow.com/comment/89853501
tagged with: matplotlib
type: Question
has body: I have tried to plot the lines on the graph. But I am not understanding how I can place the marker on it. See the following: plt.figure(figsize=(21,7)) plt.plot(datasetTest.closeTarget,label='Price',color='blue') plt.plot(datasetTest.predict_close,label='Predicted',color='red') plt.title('Price vs Predicted') plt.legend(loc='upper left') plt.show() I got the following output correctly: I am willing to have the following markers on both the lines for every point for conditions. See the same image: I have read the documentation: https://matplotlib.org/api/markers_api.html, but do not understand how to use it. Please let me know.
has title: Adding marker to the line to show trend matplotib python
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89853545

http://stackoverflow.com/comment/89646714
has text: worked, btw why is ` apply ` method not applicable here?
comment on: http://stackoverflow.com/a/51335836
type: Comment
score: 0
type: AnswerComment

statsmodels
tags question: http://stackoverflow.com/q/51366666
tags question: http://stackoverflow.com/q/51445332
tags question: http://stackoverflow.com/q/51390649
tags question: http://stackoverflow.com/q/51390196
tags question: http://stackoverflow.com/q/51438022
tags question: http://stackoverflow.com/q/51413822
tags question: http://stackoverflow.com/q/51356330
tags question: http://stackoverflow.com/q/51400402
type: Tag
tag name: statsmodels
tags question: http://stackoverflow.com/q/51394963
tags question: http://stackoverflow.com/q/51481756

http://stackoverflow.com/q/51405913
has comment: http://stackoverflow.com/comment/89782886
has comment: http://stackoverflow.com/comment/89782866
tagged with: python
has answer: http://stackoverflow.com/a/51405959
has answer: http://stackoverflow.com/a/51405952
type: AnsweredQuestion
score: 3
tagged with: list
downvote count: 1
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/51406081
possible better answer: http://stackoverflow.com/a/51405955
has answer: http://stackoverflow.com/a/56359146
has body: In my program I pull a string from another file and assign it to a variable (see below) ex1 = 'John Doe' How would I convert the above string to a different format as seen below? (Note the space after the comma) ex2 = 'Doe, John' Sorry if this question seems trivial but I haven't had much experience with lists and most solutions incorporate lists (so I don't fully understand them). Any help would be greatly appreciated!
has comment: http://stackoverflow.com/comment/89782860
has comment: http://stackoverflow.com/comment/89782899
has answer: http://stackoverflow.com/a/51406019
has answer: http://stackoverflow.com/a/51405955
accepted answer: http://stackoverflow.com/a/51405972
answer count: 7
tagged with: string
has comment: http://stackoverflow.com/comment/89782930
favorite count: 0
has title: Python: Reverse Order Of Words
has answer: http://stackoverflow.com/a/51405972

http://stackoverflow.com/a/51397776
answers question: http://stackoverflow.com/q/51397678
upvote count: 1
score: 1
has body: Here is an example if if/elif/else statement in python3: test = 'mytest' if test == 'not_my_test': print('nope') elif test == 'mytest': print('yay') else: print('something else') You can find more information here : https://docs.python.org/3/tutorial/controlflow.html EDIT: As a general remark, you should not define variable using capital letters (PEP convention: https://www.python.org/dev/peps/pep-0008/?)
downvote count: 0
has comment: http://stackoverflow.com/comment/89874088
type: Answer

http://stackoverflow.com/comment/89689547
type: QuestionComment
comment on: http://stackoverflow.com/q/51358674
has text: So what's the *problem* with the code you've posted? You're currently only checking for one of the three things, so maybe look at `or`.
score: 0
type: Comment

http://stackoverflow.com/a/51349084
type: Answer
has comment: http://stackoverflow.com/comment/89670609
score: 2
has body: Use python's sweet list comprehension, which will return you a list containing all the names that have "e" in them like - middle_name_contains_e = [i for i in middle_names if 'e' in i] and as pointed out in the comment, just replace 'e' with 'E' to match capital letter like so - middle_name_contains_e = [i for i in middle_names if 'E' in i] Or you could manually loop through all the names in the list like so - def middle_name_contains_e(): names = [] for name in middle_names: if "e" in name: names.append(name) return names names = middle_name_contains_e()
answers question: http://stackoverflow.com/q/51349013
downvote count: 0
upvote count: 2

http://stackoverflow.com/q/51367743
tagged with: pyyaml
has body: I am working with a Rails database that contains serialized values in one column. These values should have been regular Hashes, but due to improperly sanitizing the parameters they were stored as HashWithIndifferentAccess or Parameters. For example, one column entry looks like this: --- !ruby/object:ActionController::Parameters parameters: !ruby/hash:ActiveSupport::HashWithIndifferentAccess windowHeight: 946 documentHeight: 3679 scrollTop: 500 permitted: false I want to read this with Python's yaml implementation, but when I try to do so, I get: *** yaml.constructor.ConstructorError: could not determine a constructor for the tag '!ruby/object:ActionController::Parameters' in "&lt;unicode string&gt;", line 1, column 5: --- !ruby/object:ActionController::P ... ^ So, for some reason it expects a constructor. But quite obviously, the value itself is just a regular dictionary. How can I still read it?
upvote count: 1
tagged with: yaml
answer count: 1
linked to: http://stackoverflow.com/q/50538446
favorite count: 0
has title: How do I read a custom serialized YAML object (written by Rails) with Python?
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: ruby-on-rails
type: Question
has answer: http://stackoverflow.com/a/51367744
accepted answer: http://stackoverflow.com/a/51367744

http://stackoverflow.com/q/51448049
tagged with: opencv
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/51411156
accepted answer: http://stackoverflow.com/a/51458447
has title: How to use opencv copyTo() function?
score: 1
tagged with: image-processing
type: Question
has answer: http://stackoverflow.com/a/51458447
has comment: http://stackoverflow.com/comment/89869104
answer count: 1
has comment: http://stackoverflow.com/comment/89870060
upvote count: 1
tagged with: python
favorite count: 0
tagged with: python-3.x
has body: I have read through the documentation for copyTo() but am still confused on how this function would be applied to the following code. This anwer states that we can use the copyTo function instead of 255-x. How would this function be applied in this case? I would appreciate a code snippet. # Compute the gradient map of the image def doLap(image): # YOU SHOULD TUNE THESE VALUES TO SUIT YOUR NEEDS kernel_size = 5 # Size of the laplacian window blur_size = 5 # How big of a kernal to use for the gaussian blur # Generally, keeping these two values the same or very close works well # Also, odd numbers, please... blurred = cv2.GaussianBlur(image, (blur_size,blur_size), 0) return cv2.Laplacian(blurred, cv2.CV_64F, ksize=kernel_size) # # This routine finds the points of best focus in all images and produces a merged result... # def focus_stack(unimages): images = align_images(unimages) print "Computing the laplacian of the blurred images" laps = [] for i in range(len(images)): print "Lap {}".format(i) laps.append(doLap(cv2.cvtColor(images[i],cv2.COLOR_BGR2GRAY))) laps = np.asarray(laps) print "Shape of array of laplacians = {}".format(laps.shape) output = np.zeros(shape=images[0].shape, dtype=images[0].dtype) abs_laps = np.absolute(laps) maxima = abs_laps.max(axis=0) bool_mask = abs_laps == maxima mask = bool_mask.astype(np.uint8) for i in range(0,len(images)): output = cv2.bitwise_not(images[i],output, mask=mask[i]) return 255-output
downvote count: 0
tagged with: computer-vision

http://stackoverflow.com/comment/89861127
comment on: http://stackoverflow.com/q/51445446
type: QuestionComment
type: Comment
score: 2
has text: You can change the stack size (https://stackoverflow.com/questions/3323001/what-is-the-maximum-recursion-depth-in-python-and-how-to-increase-it/18649326) or don't use a recursive solution.

http://stackoverflow.com/comment/89981804
type: AnswerComment
comment on: http://stackoverflow.com/a/51450431
score: 0
has text: @ArnonRotem-Gal-Oz it's important that these are built-ins (not user defined *python* functions) - this means that all of the execution can happen inside the JVM (pyspark is just wrapper afterall). If you want to use a python udf, spark has to serialize the dataframe so that the python code can be executed. **Update**: See [this post](https://stackoverflow.com/a/38297050/5858851) for a more detailed explanation.
type: Comment

http://stackoverflow.com/comment/89756965
comment on: http://stackoverflow.com/a/51392590
score: 0
type: Comment
has text: This doesn't answer the whole question
type: AnswerComment

http://stackoverflow.com/q/51466775
score: 1
has body: I am having trouble using python join statement if the string I am joining is more then one characater var_string = ', '.join('?' * len(field_split)) print(var_string) Gets me back this string if field_split is a list of length 25 Var - ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? What I really want is a string that is made up of 25 '%s' %s, %s, %s, %s, %s, ..... I figured I could change my join to var_string = ', '.join('%s' * len(field_split)) But that returns me %, s, %, s, %, s, %, s, %, s, %, s, %, s, %, s, %, s, %, s, %, s, %, s, %, s, %, s, %, s, %, s, %, s, %, s, %, s, %, s, %, s, %, s, %, s, %, s, %, s Why is the join breaking up my text and returning a comma after each single letter? I thought it had to do with the special characters but even when I changed the question mark to ab it split up the ab. How do I properly take a take a string and repeat it N number of times with a comma after each repeat(except the last)
has comment: http://stackoverflow.com/comment/89901986
type: Question
answer count: 2
has title: Python join not working if the string I am joining is more then 1 character
favorite count: 0
has answer: http://stackoverflow.com/a/51466890
has comment: http://stackoverflow.com/comment/89901950
has answer: http://stackoverflow.com/a/51467396
upvote count: 2
type: UnansweredQuestion
tagged with: python
downvote count: 1

http://stackoverflow.com/a/51365159
has body: Try this: mylist = ['Date,Open,High,Low,Close,Adj Close,Volume', '2015-01-12,159.000000,159.250000,155.759995,156.440002,135.236679,4182800', '2015-01-13,157.259995,159.970001,155.679993,156.809998,135.556564,4377500'] import pandas as pd df = pd.DataFrame([i.split(',') for i in mylist[1:]], columns=list(mylist[0].split(','))) df
type: Answer
answers question: http://stackoverflow.com/q/51364955
score: 0

http://stackoverflow.com/comment/89820178
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51405739
has text: You removed your answer as if you are punishing a naughty child. So who has the bad attitude? Grow up.

http://stackoverflow.com/a/51372541
score: 0
answers question: http://stackoverflow.com/q/51372034
has body: I'm assuming you have 3 lists: a = [1,4,7] b = [2,5,8] c = [3,6,9] for i in range(0, len(a)): print("%d, %d, %d" % (a[i], b[i], c[i])) This returns what you need: 1,2,3 4,5,6 7,8,9
type: Answer

http://stackoverflow.com/q/51378687
has comment: http://stackoverflow.com/comment/89729387
linked to: http://stackoverflow.com/q/3617052
has comment: http://stackoverflow.com/comment/89729311
answer count: 0
type: Question
has body: I want to escape a string in MySQL query because string is creating problems for me. I am using MySQLdb and to escape a string I am using MySQLdb.escape_string("'") but that is giving the error. Can anyone tell me why I am getting this error? Or how should this string be escaped properly? Code import MySQLdb def database(): global db db = MySQLdb.connect(host="host", user="user", passwd="sss",db="database_name") database() cursor = db.cursor() var = "some's name" MySQLdb.escape_string("'") query = "select * from node Where io = '{}' ".format(var) cursor.execute(query) value = cursor.fetchone() cursor.close() Error Traceback (most recent call last): File "C:/Desktop/practise.py", line 30, in &lt;module&gt; MySQLdb.escape_string("'") TypeError: escape_string() argument 1 (impossible bad format char&gt;)
has comment: http://stackoverflow.com/comment/89729448
score: 0
has title: TypeError: escape_string() argument 1 (impossible<bad format char>) in Python
has comment: http://stackoverflow.com/comment/89729218
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/89828214
score: 0
type: Comment
type: QuestionComment
has text: If you have a table, using [datatables](https://datatables.net/) is an easy way have a filterable and searchable table
comment on: http://stackoverflow.com/q/51428322

http://stackoverflow.com/comment/89798903
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51411305
has text: This will be slower than 1x through the list which is possible
type: AnswerComment

data-manipulation
tags question: http://stackoverflow.com/q/51417159
tags question: http://stackoverflow.com/q/51449319
type: Tag
tags question: http://stackoverflow.com/q/51409861
tags question: http://stackoverflow.com/q/51425987
tags question: http://stackoverflow.com/q/51407375
tag name: data-manipulation

http://stackoverflow.com/a/51386034
score: 1
downvote count: 0
has body: You don't need to change anything about your dataframe, just index the dataframe based on your value columns and plot that. cols = [col for col in df.columns if col.startswith('value')] df[cols].plot.bar(stacked=True) plt.show()
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51385880

http://stackoverflow.com/comment/89671005
has text: Can you make this self contained and minimal? This could be a bug in pgf but it’s hard to tell without knowing your underlying data.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51347692
score: 0

http://stackoverflow.com/q/51382903
score: 0
answer count: 1
has body: I keep getting this warning but really do not know what should I change here: C:\Users\3626416\Software\Anaconda\lib\site-packages\pandas\core\indexing.py:543: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy self.obj[item] = s Here is my code: df_pcl.loc[:,['Weight','Pieces','Cons','DeadWeight']] = df_pcl.loc[:,['Weight','Pieces','Cons','DeadWeight']] * pcl2docRtio
has answer: http://stackoverflow.com/a/51384270
has title: Getting SettingWithCopyWarning when applying apply on a DataFrame Pandas
tagged with: dataframe
type: UnansweredQuestion
type: Question
tagged with: pandas
tagged with: python

http://stackoverflow.com/q/51413822
has comment: http://stackoverflow.com/comment/89799467
type: Question
tagged with: statsmodels
tagged with: linear-regression
linked to: http://stackoverflow.com/q/42261976
has answer: http://stackoverflow.com/a/51414088
has title: How to create as scatter plot with regression line based on statsmodel OLS?
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89799068
favorite count: 0
has comment: http://stackoverflow.com/comment/89799513
has comment: http://stackoverflow.com/comment/89799119
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/89799162
has body: I am having difficulty adding a regression line (the one which statsmodel OLS is based on) on to scatter plot. Note that with seaborn's lmplot, I can get a line (see example), but I would like to use the exact one coming from statsmodel OLS for total consistency. How can I adjust code below to add in the regression line into the first scatter plot? import statsmodels.regression.linear_model as sm import seaborn as sns import pandas as pd import numpy as np np.random.seed(0) data = {'Xvalue': range(20, 30), 'Yvalue': np.random.randint(low=10, high=100, size=10)} data = pd.DataFrame(data) X = data'Xvalue' Y = data['Yvalue'] model2 = sm.OLS(Y,sm.add_constant(X), data=data) model_fit = model2.fit() print(model_fit.summary()) #Plot data.plot(kind='scatter', x='Xvalue', y='Yvalue') #Seaborn sns.lmplot(x='Xvalue', y='Yvalue', data=data) Scatter plot (trying to work out how to add in the statsmodel OLS regression line seaborn lmplot with its regression line (trying to mimic this)
upvote count: 2
tagged with: seaborn
type: UnansweredQuestion

http://stackoverflow.com/q/51350288
has comment: http://stackoverflow.com/comment/89673217
upvote count: 1
has comment: http://stackoverflow.com/comment/89673434
type: Question
has comment: http://stackoverflow.com/comment/89673851
has body: I want to delete all the files older than one day except the hidden files I have tried the below code but it seems it also tries to delete hidden files, how can I modify it so that it deletes all the files but not hidden files? import os import time current_time = time.time() for f in os.listdir(): creation_time = os.path.getctime(f) if (current_time - creation_time) // (24 * 3600) &gt;= 1: os.unlink(f) print('{} removed'.format(f)) If it was linux, I could have done, if not f.startswith('.'): I have gone through the links: https://bitbucket.org/aafshar/pida-main/src/tip/pida/services/filemanager/filemanager.py I do not probably understand it. A more simple code would be appreciated.
has comment: http://stackoverflow.com/comment/89673702
has comment: http://stackoverflow.com/comment/89673378
has comment: http://stackoverflow.com/comment/89673251
has title: How can i delete files in a folder and subfolders using python in windows machine?
has comment: http://stackoverflow.com/comment/89673210
linked to: http://stackoverflow.com/q/23864234
tagged with: python-2.7
downvote count: 4
answer count: 1
has comment: http://stackoverflow.com/comment/89673267
has comment: http://stackoverflow.com/comment/89673146
has answer: http://stackoverflow.com/a/51350886
favorite count: 0
type: UnansweredQuestion
tagged with: windows
score: -3
has comment: http://stackoverflow.com/comment/89673345
tagged with: python
has comment: http://stackoverflow.com/comment/89673607

http://stackoverflow.com/q/51348980
has title: Python virtual environment suddenly lost all libraries and modules
tagged with: python-venv
answer count: 1
downvote count: 0
has body: I was running Jupyter Notebook in my Python venv. I made a new venv in a completely unrelated folder, but figured I don't need it. I move back to my original venv folder, ran my notebook files, just to find that it lost Python3 AND ALL the modules and libraries like numpy, matplotlib, beautifulSoup etc. Why and how does this happen? This is the code I use every time to my a virtual environment (provided by professor) mkdir pyvenv cd pyvenv python3 -m venv `pwd` And then to enter the venv, source bin/activate It seems that source bin/activate is causing some trouble, but this article is a bit too hard for me to understand. Plus, I have made separate virtual environments before so I am clueless as to why this time it just decided to get rid of Python3 and all other stuff in my original directory.
has answer: http://stackoverflow.com/a/51350297
tagged with: python
favorite count: 0
tagged with: jupyter-notebook
type: UnansweredQuestion
upvote count: 1
type: Question
score: 1

http://stackoverflow.com/q/51329877
has comment: http://stackoverflow.com/comment/89635515
tagged with: glade
type: Question
tagged with: python
tagged with: gtk
score: 0
has answer: http://stackoverflow.com/a/51360802
answer count: 1
type: UnansweredQuestion
has body: I want the button to open the terminal and run a command when I click on it, with python(glade)
has title: What do you put for handler and user data in the gtkbutton (glade)?
tagged with: user-interface

http://stackoverflow.com/q/51411950
answer count: 1
has comment: http://stackoverflow.com/comment/89795533
accepted answer: http://stackoverflow.com/a/51412025
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/51412025
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89795517
has title: enum34 is not installed correctly - Python 2.7
linked to: http://stackoverflow.com/q/43124775
type: Question
has comment: http://stackoverflow.com/comment/89795536
has comment: http://stackoverflow.com/comment/89795583
tagged with: python-2.7
has body: Running the command pip2.7 show enum34 outputs the version and where is installed correctly: Name: enum34 Version: 1.1.2 Summary: Python 3.4 Enum backported to 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4 Home-page: https://pypi.python.org/pypi/enum34 Author: Ethan Furman Author-email: ethan@stoneleaf.us License: BSD License Location: /usr/lib/python2.7/dist-packages Requires: Required-by: Nevertheless I am having the following error with enum: AttributeError: 'enum' object has no attribute 'IntFlag' This error happens when you dont have enum34 installed in python 2.7, but it is already installed. I can import enum and running enum.__file__ outputs the path: /usr/lib/python2.7/dist-packages/enum/__init__.pyc Why is IntFlag missing in enum if enum34 is installed?

http://stackoverflow.com/comment/89872596
score: 0
type: Comment
type: QuestionComment
has text: I guess I would ask how you know it is non-convex now and if there are other optimizers you recommend I use?
comment on: http://stackoverflow.com/q/51432497

forms
tags question: http://stackoverflow.com/q/51433725
tags question: http://stackoverflow.com/q/51427987
tags question: http://stackoverflow.com/q/51477004
type: Tag
tags question: http://stackoverflow.com/q/51440311
tags question: http://stackoverflow.com/q/51455444
tags question: http://stackoverflow.com/q/51333549
tags question: http://stackoverflow.com/q/51468834
tags question: http://stackoverflow.com/q/51431241
tags question: http://stackoverflow.com/q/51346035
tags question: http://stackoverflow.com/q/51440566
tag name: forms
tags question: http://stackoverflow.com/q/51477628

http://stackoverflow.com/a/51417030
type: Answer
has comment: http://stackoverflow.com/comment/89818165
has body: It's hard for me to figure what do you want to do with this code really. But if you want to: Let user write what he was eating. Check, if in sentence given by user is word dairy (no matter character case), and if so, return True. Then there are you problems. First, if you want your code to let user write something you need to use this: input_test = input('Enter somethings eaten in last 24 hours: ') Input is for letting the user write something for the code. print is for printing something on the screen, so you can't return print. You can return however a string, and then give it to some variable, and then print this variable. def input_eaten(): input_test = input('Enter somethings eaten in last 24 hours: ') return input_test eaten_some = input_eaten() print('dairy' in eaten_some.lower()) I hope I helped you. If not, let me know what exactly do you want your program to do. Keep practice and good luck :)
answers question: http://stackoverflow.com/q/51415740
score: 0
has comment: http://stackoverflow.com/comment/89841869

http://stackoverflow.com/q/51461609
favorite count: 0
possible better answer: http://stackoverflow.com/a/51461676
tagged with: subset
tagged with: python
has comment: http://stackoverflow.com/comment/89892434
type: AnsweredQuestion
score: 3
downvote count: 0
has title: Subset pandas dataframe with lists
type: Question
accepted answer: http://stackoverflow.com/a/51461698
has body: I would like to subset my dataframe based on a couple of lists of variables, that is: list1=[var1,var2,var3] list2=[var4,var5,var6] data_final = data[list1,list2] which produced this error: TypeError: unhashable type: 'list' If I provide a single list, everything works fine: data_final = data[list1] Below is a min-example: dict1 = [{'var0': 0, 'var1': 1, 'var2': 2}, {'var0': 0, 'var1': 2, 'var2': 4}, {'var0': 1, 'var1': 5, 'var2': 8}, {'var0': 1, 'var1': 15, 'var2': 12},] df = pd.DataFrame(dict1, index=['s1', 's2','s3','s4']) list1=['var0'] list2=['var1','var2'] These two commands work fine: df[list1] df[list2] But this one produces the above mentioned error: df[list1,list2]
has answer: http://stackoverflow.com/a/51461755
has answer: http://stackoverflow.com/a/51461698
upvote count: 3
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/89892479
has answer: http://stackoverflow.com/a/51461676

http://stackoverflow.com/comment/89889967
type: QuestionComment
has text: I'm using Python 2.7, and it looks like I can't call `super(CMakeBuild, self)` because `build_ext` (and it's parent `Command`) do not inherit from `object`. What does the `super.run` accomplish that I need? I've gotten very close by adding a `cmake_args = ['-DCMAKE_INSTALL_PREFIX={}'.format(os.path.abspath(os.path.dirname(extdir)))]`. Everything installs just fine now, but now the linux dynamic linker can't find my libmy_project.so.
comment on: http://stackoverflow.com/q/51451124
score: 0
type: Comment

http://stackoverflow.com/comment/89827088
type: AnswerComment
has text: Thank you. Most often I don't and let GC clean it up. If you want to be sure it gets cleaned immediately, use `with open('file.txt') as f` instead, and then `f.readlines()` inside the list comprehension.
type: Comment
comment on: http://stackoverflow.com/a/51427744
score: 0

http://stackoverflow.com/q/51466553
favorite count: 0
tagged with: fft
has comment: http://stackoverflow.com/comment/89906078
has comment: http://stackoverflow.com/comment/89901925
has comment: http://stackoverflow.com/comment/89902147
tagged with: python
has comment: http://stackoverflow.com/comment/89902069
possible better answer: http://stackoverflow.com/a/51482317
type: AnsweredQuestion
score: 3
downvote count: 0
has answer: http://stackoverflow.com/a/51482317
has body: When using np.fft.fft2 on images, the result is of the same size as the input. For real images, the real-to-complex FT has a symmetry where ft[i,j] == ft[-i,-j].conj(), as explained in this answer. For this reason, some frameworks such as PyTorch or scikit-cuda, return a FT of shape (height // 2 +1, width // 2 + 1). Now, given a redundancy-free/one-sided FT, how can I use numpy index magic to map it to the full FT output by numpy? Background: I need this for translating some numpy code.
has comment: http://stackoverflow.com/comment/89907057
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/51621475
accepted answer: http://stackoverflow.com/a/51621475
has title: How do I go from redundancy-free Fourier Transform (e.g. PyTorch) to redundant (full) Fourier Transform?
tagged with: matrix-indexing
has comment: http://stackoverflow.com/comment/89916339
upvote count: 3
answer count: 2
linked to: http://stackoverflow.com/q/43001729
has comment: http://stackoverflow.com/comment/89906149

http://stackoverflow.com/a/51387226
score: 21
answers question: http://stackoverflow.com/q/51386979
upvote count: 21
has comment: http://stackoverflow.com/comment/90454171
has comment: http://stackoverflow.com/comment/90453107
has body: As you can see in the C implementation of Tkinter , _tkinter_tkapp_mainloop_impl, _tkinter_tkapp_mainloop_impl(TkappObject *self, int threshold) n represent the threshold parameter passed to the function. Now, looking at the implementation itself, it is possible to see this loop at the beginning of the function, while (Tk_GetNumMainWindows() &gt; threshold &amp;&amp; !quitMainLoop &amp;&amp; !errorInCmd) Hence, you can see that the code is meant to drop out of the mainloop when the number of root level windows drops to threshold or below. Note that by default the optional parameter will have a value of 0 which logically means it will stay active if any root level windows are opened. Further information I can't comment on why this threshold parameter was added, but the lack of documentation and/or information on this specific parameter most likely comes from the fact that it seems quite rare that someone would pass n explicitly to tkinter.mainloop and change the default behavior.
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90453661
accepted answer of: http://stackoverflow.com/q/51386979

http://stackoverflow.com/q/51466124
possible better answer: http://stackoverflow.com/a/51466340
score: 1
has answer: http://stackoverflow.com/a/51466340
type: Question
has body: I have a python script which runs another python script as a subprocess. The original script communicates with the subprocess using stdin and stdout. I cannot get the subprocess to reply to messages from the original process. As a minimal example, say I have a script asker.py that wants to get an answer from answerer.py. Asker sends a message to stdin of answerer, and answerer has to send a message back, which asker will print. asker.py looks like this: import sys import subprocess as sub answerer = sub.Popen(["python", "answerer.py"], stdin=sub.PIPE, stdout=sub.PIPE) answerer.stdin.write("Are you listening?\n") answerer.stdin.flush() reply = answerer.stdout.readline() print reply answerer.py looks like this: while (True): line = raw_input() print "Yes!" I'm not seeing anything get printed by asker.py. Instead, it just hangs on the readline() call. If I run answerer.py directly from the command line, it replies to input that I type in just fine, so how do I get it to reply to asker?
has title: Python subprocess won't talk to me
has answer: http://stackoverflow.com/a/51466978
accepted answer: http://stackoverflow.com/a/51466978
answer count: 2
upvote count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
tagged with: subprocess
downvote count: 0

http://stackoverflow.com/q/51381122
tagged with: pytesser
type: Question
tagged with: tesseract
has comment: http://stackoverflow.com/comment/89758666
has title: Python pytesseract incorrect text extraction from image
tagged with: python-2.7
downvote count: 0
has body: I'm trying to extract the text from image using pytesseract. But I'm getting incorrect text. suppose when I try to read the following image, A = pytesseract.image_to_string(Image.open('A.png'),config='-psm 6',lang = 'eng') output is: Shooﬁng I mentioned the language 'English' but still getting unknown characters like "ﬁ" Though I mentioned lang= 'eng', it is giving latin characters. "ﬁ" Name : Latin Small Ligature Fi Unicode number U+FB01
has comment: http://stackoverflow.com/comment/89740722
favorite count: 0
has comment: http://stackoverflow.com/comment/89734250
tagged with: python
score: 2
tagged with: python-tesseract
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89758646
has comment: http://stackoverflow.com/comment/109750104

http://stackoverflow.com/a/51386316
type: Answer
answers question: http://stackoverflow.com/q/51384135
has body: As it is said in the error log you provided: ERRORS: ServiceCatalog.HistoricalServer.os_license: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. ServiceCatalog.Server.os_license: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. method product_list * returns flat list of values but not the tuples. It Should look like tuple(tuple(value, human readable name)). So edit this function to return tuple of these tuples. You can achieve this by mapping the flat array and adding some values to it or by taking exactly two values from values_list method. (NOTE: you cannot use flat=True, it is prohibited and not desired). * product_list this method is not working because, you are not passing either intance nor anything else to this method. So Server.account is not the model instance but model class. You should edit this function for example like this. def product_list(self): return CustomerCatalog.objects.filter(account=self.account).values_list('os_license', 'ccname') # or map(lambda x: (x, 'Some human readable string'), ...values_list('ccname'))
score: 0

http://stackoverflow.com/comment/89679585
type: AnswerComment
has text: For which row, do you get the error? This tells me that for some of your data, the Description does not have the Subject as a subtring.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51331384

http://stackoverflow.com/a/51433965
upvote count: 1
score: 1
downvote count: 0
has body: You can use list comprehension and reindex dfs = [df[df['group'] == g] for g in df.group.unique()] df_f = pd.concat([a.set_index('order').reindex(range(a.iloc[0].order, 1)) for a in dfs]) df_f['group'] = df_f.group.ffill() group value order -3 a 0.0 -2 a 3.0 -1 a NaN 0 a NaN -4 b 2.0 -3 b NaN -2 b NaN -1 b NaN 0 b NaN
answers question: http://stackoverflow.com/q/51433910
type: Answer

http://stackoverflow.com/comment/89774190
score: 1
comment on: http://stackoverflow.com/q/51395070
type: Comment
type: QuestionComment
has text: How can your working environment include Python 2.7.13 *and* Python 3.5.3?

http://stackoverflow.com/a/51428261
answers question: http://stackoverflow.com/q/51416482
type: Answer
has body: I kept probing till i landed on this question and this one and they helped clear up the fog for me. After installing sqlacodegen and flask-sqlacodegen using pip install sqlacodegen pip install flask-sqlacodegen All i had to do now is run the following command in my Flask application root sqlacodegen sqlite:///data-dev.sqlite --flask &gt; models.py And the models corresponding to my database were generated and then after i replaced my the bookshelf/data/models.py with the just generated models.py. Then finally changed bookshelf/__init__.py create_app function to look like this def create_app(): app = Flask(__name__) app.config.from_object('config') db.init_app(app) app.register_blueprint(main, url_prefix='/') app.register_blueprint(admin, url_prefix='/admin') return app And now everything seems to be working fine.
score: 0

http://stackoverflow.com/a/51343283
has body: A Stack Overflow answer can only cover one specific answer, not give a complete tutorial. But you probably actually want a complete tutorial. Also, if you're reading this from the distant future, whatever is written below may be as out-of-date as laptops that only do video and sound without smellovision. So, you should read the Python Packaging Authority's tutorial on installing packages. You have (at least) two Python installations: A Python 3.6 that you probably installed with a python.org installer, which lives in /Library/Frameworks/Python.framework/Versions/3.6/. A Python 2.7 that Apple included as part of the OS, which lives in /System/Library/Frameworks/Python.framework/Versions/2.7/. If you just run python, you get the Apple 2.7, not your 3.6. But you installed your packages for your Python 3.6, not your 2.7.1 (Plus, you don't want to run 2.7 anyway.) You're supposed to run python3, as explained in PEP 394—or, better, use a virtual environment—when you have both Python 2.x and Python 3.x on the same system.2 Either will solve your problem. If you're curious why pip installed for 3.6 instead of 2.7… well, it shouldn't work that way. But Apple's Python 2.7 is a bit out of date (I mean, even out of date for 2.7), so it doesn't even include pip. Which means the only pip on your system is the 3.6 one. So, even though python runs python2.7 instead of python3.6, pip runs pip3.6 instead of pip2.7. Which is very confusing, and pretty much unavoidable on current Macs. This is a part of the reason current recommendations suggest never running pip directly; instead, run it like this: python3 -m pip install requests That guarantees that the Python installation you're installing requests into is the same on that you get when you run your script with python3 test5.py. As things currently stand, as long as you don't ever touch Apple's 2.7, you can get away with just using pip3, or even pip. But that could easily change in, say, macOS 10.14, so better to get into the right h…
answers question: http://stackoverflow.com/q/51343217
type: Answer
upvote count: 2
score: 2
downvote count: 0

http://stackoverflow.com/comment/89688626
type: Comment
has text: Do you think `df.groupby(df.columns.tolist()).size().reset_index(name='count')` ?
comment on: http://stackoverflow.com/a/51357379
score: 0
type: AnswerComment

http://stackoverflow.com/a/51468415
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
has body: I think need: #if necessary create DatetimeIndex df = df.set_index('TIME') #get mean per rows s = df.mean(axis=1) #create boolean mask by +/- 100 chained by OR (|) m = (df.gt(s + 100, axis=0) ) | (df.lt(s - 100, axis=0)) #remove column by condition - inverted mask with any for check at least one True df = df.loc[:, ~m.any()] print (df) A B C E TIME 2015-03-01 0.74 -0.70 2.62 3.43 2015-03-02 0.15 -1.28 0.56 0.08 2015-03-03 -0.18 -3.82 0.21 -0.32 2015-03-04 -1.45 -1.26 0.74 -0.09 2015-03-05 -13.01 -12.88 -16.46 -11.67 2015-03-06 -47.73 -57.09 -55.45 -55.15 2015-03-07 -2.31 -3.57 -36.24 2.87 2015-03-08 0.64 0.34 1.76 1.51 Detail: print (m) A B C D E TIME 2015-03-01 False False False False False 2015-03-02 False False False True False 2015-03-03 False False False False False 2015-03-04 False False False False False 2015-03-05 False False False False False 2015-03-06 False False False False False 2015-03-07 False False False False False 2015-03-08 False False False False False Another solution: m = (df.lt(s + 100, axis=0) ) &amp; (df.gt(s - 100, axis=0)) #check all Trues per columns df = df.loc[:, m.all()] print (m) A B C D E TIME 2015-03-01 True True True True True 2015-03-02 True True True False True 2015-03-03 True True True True True 2015-03-04 True True True True True 2015-03-05 True True True True True 2015-03-06 True True True True True 2015-03-07 True True True True True 2015-03-08 True True True True True
accepted answer of: http://stackoverflow.com/q/51468346
type: Answer
answers question: http://stackoverflow.com/q/51468346

http://stackoverflow.com/comment/89680043
comment on: http://stackoverflow.com/a/51353320
has text: @jpp: Most of the third party `OrderedSet`s I've seen are implemented at the Python layer, so they'd be slower (though possibly slightly more memory efficient). The 3.6+ solution (using plain `dict`) is actually more memory efficient than a *plain* `set` based solution; the new `dict` design actually makes equivalent "add only" `dict` use less memory than an equivalent `set`, and while lookups and insertions are a little slower, they're typically within an order of magnitude; no Python implemented function will match `dict` on this.
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/comment/89823174
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51416862
has text: something that i was thinking to simplify the macro approach was to disable search wrap

http://stackoverflow.com/comment/89831621
type: Comment
score: 3
comment on: http://stackoverflow.com/q/51429792
has text: With a Fourier transform, you generally not interested in the real and imaginary parts (unless you actually need phase information). So you should consider the magnitude of the complex values. This is the "energy" at a given frequency, and that will help you to determine which frequencies comtribute most to the signal. The other thing is that the signals have a mean value, so the zero frequency, i.e. constant, is significant and dominates the contribution from the other frequencies. Either subtract of the mean of the signal or use a logarithmic y-scale.
type: QuestionComment

http://stackoverflow.com/a/51447911
has comment: http://stackoverflow.com/comment/89866927
has body: &gt;&gt;&gt; import collections &gt;&gt;&gt; from pprint import pprint &gt;&gt;&gt; df Book-1 Book-2 Similarity Score 0 b1 b2 0.95 1 b1 b3 0.87 2 b2 b3 0.84 &gt;&gt;&gt; &gt;&gt;&gt; d = collections.defaultdict(list) &gt;&gt;&gt; for row in df.itertuples(index=False): a,b,c = row d[a].append((b,c)) d[b].append((a,c)) &gt;&gt;&gt; pprint(d) defaultdict(&lt;class 'list'&gt;, {'b1': [('b2', 0.95), ('b3', 0.87)], 'b2': [('b1', 0.95), ('b3', 0.84)], 'b3': [('b1', 0.87), ('b2', 0.84)]})
has comment: http://stackoverflow.com/comment/89866693
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51434502
accepted answer of: http://stackoverflow.com/q/51434502
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/89831099
comment on: http://stackoverflow.com/q/51429985
score: 0
type: Comment
type: QuestionComment
has text: Hmm, well, I would imagine the instructions do create a 64-bit DLL. I've used http://www.dependencywalker.com/ for debugging this sort of problem - use the 64-bit version to debug 64-bit situations and vice versa.

http://stackoverflow.com/a/51446820
answers question: http://stackoverflow.com/q/51446327
type: Answer
score: 0
has body: we can do this by using grouper function given in itertools documentation page. from itertools import zip_longest def grouper(iterable, n, fillvalue=None): "Collect data into fixed-length chunks or blocks" # grouper('ABCDEFG', 3, 'x') --&gt; ABC DEF Gxx args = [iter(iterable)] * n return zip_longest(fillvalue=fillvalue, *args) def out_iterator(lst): for each in grouper(lst,n): if None in each: yield each[:each.index(None)] else: yield each a=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] n=3 print(list(out_iterator(a))) Output: [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10)]

http://stackoverflow.com/comment/89808856
type: QuestionComment
comment on: http://stackoverflow.com/q/51418913
has text: You could just replace `'%s',%args.input` with `args.input`.
score: 1
type: Comment

http://stackoverflow.com/q/51337695
favorite count: 0
has title: Selecting arbitrary subsets of dates in Pandas
tagged with: python
accepted answer: http://stackoverflow.com/a/51337712
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51337712
type: Question
tagged with: date
tagged with: pandas
upvote count: 1
has body: Is there a way to select arbitrary date subsets in a Pandas dataframe? So that if I have the following: dates = pd.date_range('20130101', periods=6) df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD')) df A B C D 2013-01-01 0.469112 -0.282863 -1.509059 -1.135632 2013-01-02 1.212112 -0.173215 0.119209 -1.044236 2013-01-03 -0.861849 -2.104569 -0.494929 1.071804 2013-01-04 0.721555 -0.706771 -1.039575 0.271860 2013-01-05 -0.424972 0.567020 0.276232 -1.087401 2013-01-06 -0.673690 0.113648 -1.478427 0.524988 I would like to do, for example: my_selection = ['2013-01-01', '2013-01-03', '2013-01-02', '2013-01-02', '2013-01-05']] my_df = df.loc[my_selection] my_df A B C D 2013-01-01 0.469112 -0.282863 -1.509059 -1.135632 2013-01-03 -0.861849 -2.104569 -0.494929 1.071804 2013-01-02 1.212112 -0.173215 0.119209 -1.044236 2013-01-02 1.212112 -0.173215 0.119209 -1.044236 2013-01-05 -0.424972 0.567020 0.276232 -1.087401
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/89930126
score: 0
has text: If you are to use the data, perhaps reduce it to just the UK datapoints to make it run faster.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51418474

http://stackoverflow.com/a/51431227
upvote count: 1
downvote count: 0
has body: Probably you are looking for a generic solution without any third party libraries (i.e. only standard library). Here we go: def filter_by(csv_data, column_name, column_value): indices = [i for i, name in enumerate(data[0]) if name == column_name] if not indices: return index = indices[0] for row in data[1:]: if row[index] == column_value: yield row And this is how you use it: print(list(filter_by(movie_data, "country", "USA"))) This shall output (I formatted it a bit for clarity): [ ['Avatar', 'James Cameron', 'Color', '178', 'CCH Pounder', 'English', 'USA', '2009'], ["Pirates of the Caribbean: At World's End", 'Gore Verbinski', 'Color', '169', 'Johnny Depp', 'English', 'USA', '2007'] ]
answers question: http://stackoverflow.com/q/51430857
type: Answer
score: 1

http://stackoverflow.com/q/51429878
has comment: http://stackoverflow.com/comment/89830797
has comment: http://stackoverflow.com/comment/89830755
type: Question
has title: How do I add elements in python list?
score: 0
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/51430036
downvote count: 1
has body: weight = [10, 3, 7, 9, 6, 5, 2] def listsum(numlist): sum = 0 for i in numlist: sum = sum + i return sum listsum(weight) I have this simple function to add the values of weight together and am expecting a total of 42 however when I run the function, I don't get any errors or anything. I am not sure what's going on and have been trying to search various answers for the past 20 mins to no avail. Can someone point me in the right direction here? Thank you
favorite count: 0
has comment: http://stackoverflow.com/comment/89830812
has comment: http://stackoverflow.com/comment/89830780
has comment: http://stackoverflow.com/comment/89830801
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51429939
has answer: http://stackoverflow.com/a/51429909
tagged with: python

http://stackoverflow.com/comment/89702673
has text: @pjs Yes you are right, it is not normal distributed. It is perhaps more exponential distributed. How can I find the index of the tail for such a distribution?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51358512

http://stackoverflow.com/comment/89761953
comment on: http://stackoverflow.com/q/51395250
has text: Please don't post images of code/output, instead copy and paste the output and paste in a quotation block or code block.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89779353
comment on: http://stackoverflow.com/a/51403077
has text: @laland as @Parfait warns, using query parameterization for the custom values is the best way to avoid sql injections. For the `field` part, on the other hand, it is still dangerous, and yes, you should validate the input given by the user not to contain special characters (single quotes, double quotes, commas, semicolon, spaces etc). In general, you should eliminate characters that are not allowed in a column name.
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/comment/89884843
comment on: http://stackoverflow.com/q/51457418
score: 0
type: QuestionComment
has text: Show the conversion code
type: Comment

http://stackoverflow.com/comment/89788697
has text: as suggested by @Bayko in comments. I opened anaconda as admin and that did the job.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51407205
type: AnswerComment

http://stackoverflow.com/a/51418581
answers question: http://stackoverflow.com/q/51417159
has comment: http://stackoverflow.com/comment/89815652
downvote count: 0
has comment: http://stackoverflow.com/comment/89815794
has body: If need count unique catagories per id first split, create MultiIndex Series by stack and last use SeriesGroupBy.nunique with map for new column of original DataFrame: s = (df.set_index('id')['richtingen'] .str.split(', ',expand=True) .stack() .groupby(level=0) .nunique()) print (s) id 220 1 1110 3 3300 1 dtype: int64 df['freq'] = df['id'].map(s) print (df) richtingen id freq 0 Marketing, Sales 1110 3 1 Marketing, Sales 1110 3 2 Finance 220 1 3 Marketing, Engineering 1110 3 4 IT 3300 1 Detail: print (df.set_index('id')['richtingen'].str.split(', ',expand=True).stack()) id 1110 0 Marketing 1 Sales 0 Marketing 1 Sales 220 0 Finance 1110 0 Marketing 1 Engineering 3300 0 IT dtype: object
type: Answer
has comment: http://stackoverflow.com/comment/89815943
score: 3
upvote count: 3

http://stackoverflow.com/a/51385153
answers question: http://stackoverflow.com/q/51384137
has body: It's an interesting format the data is coming so I needed to do some transforming first. d = ['countries','user','visit'] e = ['usa','aaa',50] f= ['uk','bbb',20] g = ['germany','ccc',9] h = ['india','ddd',30] i = ['russia','eee',58] df1 = pd.DataFrame({0:d,1:e,2:f,3:g,4:h,5:i}) 0 1 2 3 4 5 0 countries usa uk germany india russia 1 user aaa bbb ccc ddd eee 2 visit 50 20 9 30 58 Above resembles your starting format. In the next steps, I replace the columns with the country names, drop the first row (originally country names), and set the index to the first column. df1.columns = df1.iloc[0].values df1.drop(0, inplace=True) df1.set_index('countries', inplace=True) df1 usa uk germany india russia countries user aaa bbb ccc ddd eee visit 50 20 9 30 58 Unstack is where it starts to resemble the dataframes we're used to. Unstacking twice gives us record format. Reset_index gives something to pivot on, and pivot gets us the format. I then turn the dataframe into a sparse dataframe. df1 = df1.unstack().unstack() df1.reset_index(inplace=True) df1 = df1.pivot(index = 'index',columns = 'user', values = 'visit') dfs = df1.to_sparse(fill_value = 0) dfs user aaa bbb ccc ddd eee index germany 0 0 9 0 0 india 0 0 0 30 0 russia 0 0 0 0 58 uk 0 20 0 0 0 usa 50 0 0 0 0 dfs.density 0.2
type: AcceptedAnswer
score: 0
accepted answer of: http://stackoverflow.com/q/51384137
type: Answer

http://stackoverflow.com/comment/89675588
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51351532
has text: I have a very big BitVector.
score: 0

http://stackoverflow.com/comment/89934476
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51478165
has text: well, I had one integer column and I wanted to write that as integers but when I use `np.nan` I can't keep the column as integer. Thats why I am trying different precision format for different columns. Also if I use `round()` then some prints in scientific `e` notation I also don't want that. So, my best shot would be using `round()` without introducing `e` notation.

http://stackoverflow.com/comment/89801086
has text: download this :https://bootstrap.pypa.io/get-pip.py run python get-pip.py It will upgrade pip
comment on: http://stackoverflow.com/q/51414407
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/79401111
score: 0
has body: My approach is to create a function which split the value. If there are more than 2 values, or less than 1, throw a ValueError so argparse can complain in my behalf. I also use a name space to name the stamp and tolerance, making it easy for the caller. #!/usr/bin/env python3 import argparse def stamp_and_tolerance(value=None): if value is None: return argparse.Namespace(stamp=None, tolerance=None) tokens = value.split(",") if len(tokens) == 1: return argparse.Namespace(stamp=tokens[0], tolerance=None) elif len(tokens) == 2: return argparse.Namespace(stamp=tokens[0], tolerance=tokens[1]) raise ValueError() parser = argparse.ArgumentParser() parser.add_argument( "-t", "--timestamp", type=stamp_and_tolerance, default=stamp_and_tolerance(), metavar="stamp[,tolerance]", help="Timestamp and optional tolerance", ) args = parser.parse_args() print(f"Stamp: {args.timestamp.stamp}") print(f"Tolerance: {args.timestamp.tolerance}") Sample runs ./my.py -h usage: my.py [-h] [-t stamp[,tolerance]] options: -h, --help show this help message and exit -t stamp[,tolerance], --timestamp stamp[,tolerance] Timestamp and optional tolerance ./my.py Stamp: None Tolerance: None ./my.py -t mystamp Stamp: mystamp Tolerance: None ./my.py -t mystamp,mytolerance Stamp: mystamp Tolerance: mytolerance Notes I use comma as the separator, it can be almost anything The metavar correctly communicates what the argument looks like I set the default so that I don't have to bother with if args.timestamp != None I use SimpleNamespace so the arguments are named, making it nicer to access
type: Answer
answers question: http://stackoverflow.com/q/51389736

http://stackoverflow.com/comment/89866809
has text: This is the output from the code I provided in my comment: `[('Mark', '10 points'), ('Ashley', '10 points'), ('Ron', '20 points')]`. You probably ran it inside a loop.
comment on: http://stackoverflow.com/q/51447982
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89852850
score: 0
comment on: http://stackoverflow.com/a/51426322
type: Comment
type: AnswerComment
has text: Great, thanks a lot! I'm actually indexing with a full date, but I guess I can handle this myself from now on. Cheers!

http://stackoverflow.com/q/51329367
has body: I can effectively export to PDF from a google sheet using this code from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive gDriveCreds="mycreds.txt" gauth = GoogleAuth() GoogleAuth.DEFAULT_SETTINGS['client_config_file'] = "client_secrets.json" gauth.LoadCredentialsFile(gDriveCreds) if gauth.credentials is None: gauth.LocalWebserverAuth() elif gauth.access_token_expired: gauth.Refresh() else: gauth.Authorize() gauth.SaveCredentialsFile(gDriveCreds) drive = GoogleDrive(gauth) file_obj = drive.CreateFile({'id': 'sfkldjlfsdkjfgdklj'}) file_obj.GetContentFile('temp.pdf', mimetype='application/pdf') But I can't figure out a way to create the pdf with 0" margins like I want. I have the google sheet set up with 0" margins, but the python export just defaults to some typical margin.
has title: Python Google Sheets api export to pdf with 0" margin
type: Question
has comment: http://stackoverflow.com/comment/89837710
linked to: http://stackoverflow.com/q/46088042
upvote count: 1
tagged with: http://stackoverflow.com/tag/pdf
favorite count: 0
tagged with: google-drive-api
tagged with: pydrive
type: UnansweredQuestion
tagged with: google-api
tagged with: python
answer count: 0
downvote count: 0
score: 1

http://stackoverflow.com/q/51451482
downvote count: 1
has comment: http://stackoverflow.com/comment/89873182
has answer: http://stackoverflow.com/a/51451514
has comment: http://stackoverflow.com/comment/89873218
type: Question
has answer: http://stackoverflow.com/a/51451510
answer count: 2
has title: What is a float, have I got the right idea?
has body: I was programming a calculator and I came across float. I was told to use floats then my calculator would be able to calculate calculations including numbers like 16.4 and 4.5 and not just whole numbers. Now, I sort of got thinking and wondered if someone could just verify I'm on the right tracks. I understand an int is a solid number, a double is basically 2 numbers with a dot in the middle, a decimal? And now comes the tricky one, the float data type. I just need somebody to verify I'm on the right track. I think a float is a data type that can either be a whole number (this is what I'm not sure about) and a double/decimal. I feel like float is the safe data type kinda thing, where you're not sure and want to accept whole and decimal numbers, am I right? Is it for accepting both whole and decimals? For anyone that struggles to understand, heres the code to my calculator, it might help. while True: calculation = input("Calculation: ") if (calculation.__contains__("+")): print(float(calculation[0] ) + float(calculation[2])) elif (calculation.__contains__("-")): print(float(calculation[0] ) - float(calculation[2])) elif (calculation.__contains__("*")): print(float(calculation[0] ) * float(calculation[2])) elif (calculation.__contains__("/")): print(float(calculation[0] ) / float(calculation[2]))
has comment: http://stackoverflow.com/comment/89873222
has comment: http://stackoverflow.com/comment/89873201
has comment: http://stackoverflow.com/comment/89873198
favorite count: 0
has comment: http://stackoverflow.com/comment/89873709
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 1
has comment: http://stackoverflow.com/comment/89873241
tagged with: floating-point

http://stackoverflow.com/q/51345814
tagged with: python-itertools
linked to: http://stackoverflow.com/q/855191
accepted answer: http://stackoverflow.com/a/51345918
duplicate of: http://stackoverflow.com/q/855191
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/89664945
favorite count: 0
score: -1
type: Question
tagged with: python
has body: I have a Matrix that is consisted out of 80 cells. My objective is to test each of the possible combinations there are where each combination is 8 cells long. For instance one of the possible combinations is [0, 1, 2, 3, 4, 5, 6, 7] I was trying to use the following code to print each of these combinations and all I got was a MemoryError: comb = combinations(range(80), 8) for i in list(comb): print(i) My purpose is to actually take i (each combination) and set it in my device and verify it is functional. The print(i) was just intended to verify that I am doing it right and to see some of the combinations. Is there a more memory efficient way to do this kind of task ? By the way, I am aware that there are 2.898753715E+10 combinations that I am planning to test.
answer count: 1
downvote count: 1
has title: Printing the combinations list results in MemoryError
has comment: http://stackoverflow.com/comment/89664822
has answer: http://stackoverflow.com/a/51345918

http://stackoverflow.com/a/51392845
has body: n=int(input()) for i in range(0,n): print(i*i)
has comment: http://stackoverflow.com/comment/89757536
score: 1
has comment: http://stackoverflow.com/comment/89757542
has comment: http://stackoverflow.com/comment/89757517
downvote count: 0
answers question: http://stackoverflow.com/q/51392779
has comment: http://stackoverflow.com/comment/89757488
type: Answer
upvote count: 1

http://stackoverflow.com/a/64927461
upvote count: 4
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/51333374
type: Answer
has body: TLDR For non distributed systems, work with numbers internally (like 225204568) and encode them to short alphanumeric IDs (like "F2AXP8") in the UI or other external interfaces. Use the amazing sqid library or the following Python3, JavaScript, PowerShell & VBA functions that work like this: >>> int32_to_id(225204568) 'F2AXP8' >>> id_to_int32('F2AXP8') 225204568 For distributed systems use ULIDs: https://github.com/mdipierro/ulid (They are a lot longer but unique across different machines.) For non distributed systems How short are the IDs? Half a billion IDs can fit in 6 characters. So it's as compact as possible while still using only non-ambiguous digits and letters. What if I want even shorter IDs? You can have them. Just expand the character set by changing the line chars="..." in the function. If, for example, you allow all lower and upper case letters you can have 56 billion IDs within 6 characters. Adding a few symbols (like ~!@#$%^&*()_+-=) gives you 208 billion IDs. And why didn't you chose to have the shortest possible IDs? I prefer a bit longer IDs that are still easy to copy-paste (no symbols so double clicking selects the whole ID), easy to read without mistakes (no look-alike characters like 2 and Z) and rather easy to communicate verbally (no lower case letters). Sticking to numeric digits only is your best option for verbal communication but they are not compact. I'm convinced: show me the code For most languages use the sqids library. I'm leaving my implementations for those that were not supported by sqids at the time of this post. My versions have fewer features (for example they don't filter out known profanity words) PowerShell function int32ToId { param ( [int]$n ) $chars = "0123456789ACEFHJKLMNPRTUVWXY" $length = $chars.Length $result = "" if ($n -eq 0) { return "0" } while ($n -gt 0) { $pos = $n % $length $n = [math]::Floor($n / $length) $result = $chars[$pos] + $result } return $result } function idToInt32 { param ( [string]$id ) $chars = "…

http://stackoverflow.com/q/51408860
type: Question
answer count: 2
has title: How to make string from a text file in Python 3?
has body: path = "C:\\Users\\user\\Downloads\\wordlist.txt" word_list = open(path, 'r') list = [x for x in word_list.split(" ")] How can I open a file, so that I can make it into a string and eventually turn that string into a list? I've tried with split(), but it seems that text files can't just be split, although they are read.
favorite count: 0
has answer: http://stackoverflow.com/a/51408897
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/89789155
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51408918
has answer: http://stackoverflow.com/a/51408918
downvote count: 3
score: -1
accepted answer: http://stackoverflow.com/a/51408897

http://stackoverflow.com/q/51436042
has comment: http://stackoverflow.com/comment/89842288
has comment: http://stackoverflow.com/comment/89842267
has comment: http://stackoverflow.com/comment/89842953
has title: how to make a list of objects without losing reference
type: UnansweredQuestion
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/89842112
has comment: http://stackoverflow.com/comment/89843012
has comment: http://stackoverflow.com/comment/89843115
has answer: http://stackoverflow.com/a/51437380
has comment: http://stackoverflow.com/comment/89843238
has comment: http://stackoverflow.com/comment/89842378
upvote count: 0
has comment: http://stackoverflow.com/comment/89843049
type: Question
has comment: http://stackoverflow.com/comment/89842189
has comment: http://stackoverflow.com/comment/89842336
tagged with: class
has answer: http://stackoverflow.com/a/51436278
answer count: 2
downvote count: 3
has body: --------------------------------EDITED---------------------------------------- here is the whole code, sorry i forgot to add the @classmethod decorator from abc import ABC, abstractmethod class Player(ABC): player_list = [] @classmethod def __init__(self, name): self.name = name self.score = 0 Player.player_list.append(self) @abstractmethod def getname(self): pass class generic(Player): def getname(self): return self.name p1 = generic('bob') p2 = generic('tim') p1.name = 'steve' for player in Player.player_list: print(player.name) this doesn't return steve, tim instead returns tim, tim also print(Player.player_list) returns [&lt;class '__main__.generic'&gt;, &lt;class '__main__.generic'&gt;]
tagged with: function
favorite count: 0
has comment: http://stackoverflow.com/comment/89843071
has comment: http://stackoverflow.com/comment/89842863
has comment: http://stackoverflow.com/comment/89842198

http://stackoverflow.com/q/51387915
has comment: http://stackoverflow.com/comment/89771755
has comment: http://stackoverflow.com/comment/89771107
has title: Error with RandomGridSearchCV in Sklearn MLPRegressor
has comment: http://stackoverflow.com/comment/89767654
has body: I found similar issues around the internet but with slight differences and none of the solutions worked for me. I have a set of explanatory variables X (2085,12) and an explained variable y (2085,1) which I have to do some stuff on, including the use of these sklearn classes (as title). In order to get the right hyperparameters I have arranged the code as follows: #solver: sgd mlpsgd = MLPRegressor(max_iter = 1000, solver='sgd') alpha = [float(x) for x in np.logspace(start = -6, stop = 3, num = 100)] hidden_layer_sizes = [(int(x),int(y),int(z)) for x in np.logspace(start = 0, stop = 2.2, num = 8) for y in np.logspace(start = 0, stop = 2.2, num = 8) for z in np.logspace(start = 0, stop = 2.2, num = 8)] hidden_layer_sizes.extend((int(x),int(y)) for x in np.logspace(start = 0, stop = 2, num = 25) for y in np.logspace(start = 0, stop = 2, num = 25)) hidden_layer_sizes.extend((int(x),) for x in np.logspace(start = 1, stop = 2, num = 1000)) activation = ['logistic', 'tanh', 'relu'] learning_rate = ['constant', 'invscaling','adaptive'] learning_rate_init = [float(x) for x in np.logspace(start = -5, stop = 0, num = 20)] random_grid3 = {'learning_rate': learning_rate,'activation': activation,'learning_rate_init': learning_rate_init, 'hidden_layer_sizes': hidden_layer_sizes, 'alpha': alpha} mlp_random3 = RandomizedSearchCV(estimator = mlpsgd, param_distributions = random_grid3, n_iter = 350, n_jobs=-1) mlp_random3.fit(X, y) Now I know that the whole random grid is insanely huge, but I tried even with a very small one and this is not the issue (and this way it is more of a match for the type of research I am supposed to do), and I should mention that I use windows and the program starts with if __name__ == '__main__': as I understood (hopefully correctly) it is needed for the multiprocessing I am asking in the second to last line of the firs part of code I attached. Well the thing is that when I run the code some of the 350 iteration are processed correctly, but then it stops …
has comment: http://stackoverflow.com/comment/89776714
has comment: http://stackoverflow.com/comment/89771351
tagged with: python
tagged with: joblib
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89771413
accepted answer: http://stackoverflow.com/a/51402483
upvote count: 1
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89774244
score: 1
has comment: http://stackoverflow.com/comment/89774318
has comment: http://stackoverflow.com/comment/89771382
tagged with: numpy
has comment: http://stackoverflow.com/comment/89769567
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51402483
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/89770957
has comment: http://stackoverflow.com/comment/89772435
favorite count: 0

http://stackoverflow.com/q/51397843
tagged with: python
accepted answer: http://stackoverflow.com/a/51399662
possible better answer: http://stackoverflow.com/a/51398595
tagged with: opencv
type: AnsweredQuestion
has body: i'm trying to build a simple image detection algorithm in which will classify different objects such as plastic cups, bottles, cell phones, etc. What is the best way to implement this using openCV and python? Thanks
has title: OpenCV Multiple Image Detection
tagged with: image-processing
has answer: http://stackoverflow.com/a/51399662
type: Question
has answer: http://stackoverflow.com/a/51398595
score: 0
answer count: 2

http://stackoverflow.com/comment/129507660
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51410283
has text: The [library d3graph](https://erdogant.github.io/d3graph) may be use. You can specify directed edges. It is a force-directed d3-graph. More information is posted here: https://stackoverflow.com/questions/8840255/django-and-interactive-graph-network-visualization/62520707#62520707

http://stackoverflow.com/q/51457805
type: Question
has answer: http://stackoverflow.com/a/51459688
has comment: http://stackoverflow.com/comment/89885478
has comment: http://stackoverflow.com/comment/89885599
has comment: http://stackoverflow.com/comment/89885586
has body: So recently I was working with matplotlib here is my code import matplotlib.pyplot as plt plt.plot([1,2,3] ,[2,4,6], label="line") plt.xlabel("x") plt.ylabel("y") plt.title("Interesting graph") plt.legend() plt.show() Now as I have to write this plt. every single time which I feel is redundant So my question is there any way that only once I have to write plt and I can call all the methods on it by just writing the method name Here is an example of what I wanted which I am writing using with in python with plt : plot([1,2,3] ,[2,4,6], label="line") xlabel("x") ylabel("y") title("Interesting graph") legend() plt.show() If something like this is not present in python can I suggest this in python idea mailing list
answer count: 2
downvote count: 4
has comment: http://stackoverflow.com/comment/89884970
upvote count: 0
has comment: http://stackoverflow.com/comment/89885548
has comment: http://stackoverflow.com/comment/89885014
has title: Calling all attributes of an object just by writting the object name once in python
has answer: http://stackoverflow.com/a/51464430
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/89885542
type: UnansweredQuestion
score: -4
has comment: http://stackoverflow.com/comment/89885010
has comment: http://stackoverflow.com/comment/89885629

http://stackoverflow.com/comment/89712793
has text: @user3483203 I get an error on repl python2 (that's probably OP's issue)
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51370265
score: 0

http://stackoverflow.com/comment/89913496
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51472668
has text: Change lineIDSpace6Num < 4 to lineIDSpace6Num < 3.
score: 1

http://stackoverflow.com/q/51380631
tagged with: web-scraping
has body: Friends I was trying to scrape Category and sub category from following link using BeautifulSoup in Pyhton. But I am not able to scrape it gave me blank list all times I tried following method: first I tried to scrape only one category from following method but it give e blank output soup.find('h3',{"class":"m-t-40"}) I tried to scrape all category but still it give me blank output soup.find_All('h3',{"class":"m-t-40"}) Can anyone tell me how to scrape from this link? Thanks in Advance
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51380992
accepted answer: http://stackoverflow.com/a/51380992
type: Question
answer count: 1
score: 0
upvote count: 1
has title: How to scrape Job categories and its sub categories from Upwork website?
downvote count: 1
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/89733561

http://stackoverflow.com/comment/89699544
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51363368
has text: Edit your original post, include a working snippet, and provide a stack trace. It's pretty hard to try to imagine all the situation without any of these.

http://stackoverflow.com/comment/89926093
type: AnswerComment
type: Comment
score: 1
has text: For whitespace separators, `delim_whitespace=True`' is recommended
comment on: http://stackoverflow.com/a/51478900

http://stackoverflow.com/comment/89926624
comment on: http://stackoverflow.com/a/51475163
score: 0
type: Comment
has text: Hi Anton, I'm using Windows 10 (python 3.6.5). In step (2) I get the following fatal error 'Microsoft is not a valid short file name', so I'm unable to install a new version. Any idea why this happens?
type: AnswerComment

http://stackoverflow.com/q/51379723
answer count: 1
has answer: http://stackoverflow.com/a/51379949
favorite count: 0
linked to: http://stackoverflow.com/q/51462317
tagged with: django
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89880297
has comment: http://stackoverflow.com/comment/89730873
downvote count: 0
score: 1
has title: django modelAdmin displayed title
has comment: http://stackoverflow.com/comment/89730839
type: Question
tagged with: django-admin
has comment: http://stackoverflow.com/comment/89880405
has body: I am new to django. I have the following codes: model: class MyUser(AbstractUser): profile = models.OneToOneField(Profile, null=True, on_delete=models.PROTECT) My profile model contains only some personal fields like full_name, gender, birthdate, etc. admin: class MyUserInline(admin.StackedInline): model = MyUser exclude = ('first_name', 'last_name', 'username', 'plan', 'password') fieldsets = ( (_('Personal info'), {'fields': ('email',)}), (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) class MyUserChangeForm(UserChangeForm): class Meta(UserChangeForm.Meta): model = MyUser def clean_password(self): return "" class ProfileAdmin(admin.ModelAdmin): inlines = (MyUserInline,) change_user_password_template = None form = MyUserChangeForm change_password_form = AdminPasswordChangeForm ordering = ('myuser__email',) def save_model(self, request, obj, form, change): obj.myuser.username = obj.myuser.email obj.save() list_display = ('full_name', 'myuser_email', 'myuser_is_staff', 'myuser_is_superuser', 'myuser_is_active') def user_change_password(self, request, id, form_url=''): if not self.has_change_permission(request): raise PermissionDenied user = self.get_object(request, unquote(id)) if user is None: raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % { 'name': force_text(self.model._meta.verbose_name), 'key': escape(id), }) if request.method == 'POST': form = self.change_password_form(user, request.POST) if form.is_valid(): form.save() # rest of method # other minor methods The problems are: In recent actions or after editing a user, I see Profile Object instead of username or email. enter image description here see here: my other problem In profile edit page, the permission part contains only a box containing a list of all possible permissions, however there must be another box containing user current permissions list Wha…
accepted answer: http://stackoverflow.com/a/51379949
upvote count: 1

http://stackoverflow.com/a/51391569
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/51391083
downvote count: 0
has body: Use the summary to confirm the following (trust me, there will be an answer :D ): After the second conv you've got a shape like (None, 358,718,32) The Pooling then gives you something very near (None, 120, 240, 32) And the Flatten layer gave you (None, 120*240*32) which is (None, 921600)!!!! This is the reason of so many parameters! The dense layer will have 2 weights for each input, plus 2 biases, totaling 1843202 parameters just for the Dense layer. You need more Convs + Poolings to gradually reduce the size before throwing that huge amount into a Dense layer.
type: Answer

http://stackoverflow.com/comment/89826866
type: QuestionComment
has text: Side note: Don't use built-in names like `object` for your variables.
score: 2
comment on: http://stackoverflow.com/q/51426583
type: Comment

paginator
tags question: http://stackoverflow.com/q/51471699
type: Tag
tag name: paginator

http://stackoverflow.com/q/51417633
favorite count: 0
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90759362
tagged with: tesseract
tagged with: python-tesseract
score: 1
has body: I'm using pytesseract for images that include both English and Hebrew. On some of them it works fine but on others the following error occurs: Traceback (most recent call last): File "C:\Users\User\Desktop\ocr.py", line 47, in text = pytesseract.image_to_string(Image.open(filename), lang="heb+eng") File "C:\Python27\lib\site-packages\pytesseract\pytesseract.py", line 286, in image_to_string return run_and_get_output(image, 'txt', lang, config, nice) File "C:\Python27\lib\site-packages\pytesseract\pytesseract.py", line 194, in run_and_get_output run_tesseract(**kwargs) File "C:\Python27\lib\site-packages\pytesseract\pytesseract.py", line 170, in run_tesseract raise TesseractError(status_code, get_errors(error_string)) pytesseract.pytesseract.TesseractError: (-1073741819, u'') I have installed heb.traineddata, so I'm not sure what may be the problem. On those images that produce this error, using "eng" only doesn't make the code fail, however ends up returning wrong results, ignoring the Hebrew text, obviously. Why would pytesseract work on some files and on others won't? Thank you
type: Question
has title: TesseractError: (-1073741819, u'') when using pytesseract
downvote count: 0
tagged with: hebrew
tagged with: ocr

http://stackoverflow.com/comment/89712337
comment on: http://stackoverflow.com/a/51368300
has text: yes but if i only have one sample having class 1, cant it be made to predict 1?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/51482706
has comment: http://stackoverflow.com/comment/89940912
type: Answer
accepted answer of: http://stackoverflow.com/q/51481066
has body: You can do the task even without lambdas, relying solely on the regex capabilities (although the regex is more complicated). The regex needed is: (?:(32|64)|\d+)(?=\D|$). Details: (?: - Start of the non-capturing group, needed as a container for alternatives. (32|64) - The first alternative (and capturing group), either 32 or 64. | - Or. \d+ - The second alternative, a sequence of digits. ) - End of the non-capturing group. (?=\D|$) - The (common) ending part (after both alternatives) - positive lookup for either a non-digit char or end of string. The first alternative (and capturing group) matches either 32 or 64 and the second alternative (without capturing group) matches any other number. The replacement expression is \1 (replace the match with the content of the first capturing group). So, if the second alternative matched, the first group matched nothing, hence nothing is put as the replacement for the current match. To demonstrate how it works, run the example program: import re src = ['abc123 def3464', 'hello32 goodbye64', 'some numbers 1254324'] print(src) result = [re.sub(r"(?:(32|64)|\d+)(?=\D|$)", r"\1", i) for i in src] print(result) If you are unhappy with the trailing space in the last output string, add .strip() after re.sub(...).
downvote count: 1
has comment: http://stackoverflow.com/comment/90032016
score: 3
has comment: http://stackoverflow.com/comment/89938822
upvote count: 4
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51481066

http://stackoverflow.com/comment/89638014
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51330725
has text: You have to provide the relationship. show your models then only one can help

http://stackoverflow.com/a/51649564
has body: Here what i would do (Django 1.11 and celery 4.2), you have a problem in your celery config and you try to re-declare the Celery instance : tasks.py from myapp.celery import app # would contain what you need :) from celery.utils.log import get_task_logger logger = get_task_logger(__name__) @app.task(name='news.tasks.update_news_status') def update_news_status(news_id): # (I pass the news id and return it, nothing complicated about it) return news_id celery.py from __future__ import absolute_import, unicode_literals from celery import Celery from django.conf import settings import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings") app = Celery('myapp', backend='rpc://', broker=BROKER_URL) # your config here app.config_from_object('django.myapp:settings', namespace='CELERY') # change here app.autodiscover_tasks() models.py from django.db import models class News(models.model): (...) def save(self, *args, **kwargs): super(News, self).save(*args, **kwargs) from news.tasks import update_news_status update_news_status.delay(self.id) # change here And launch it with celery -A myapp worker --loglevel=info because your app is defined in myapp.celery so -A parameter need to be the app where the conf is declared
answers question: http://stackoverflow.com/q/51426895
score: 0
type: Answer

http://stackoverflow.com/a/70066328
score: 0
answers question: http://stackoverflow.com/q/51458881
has body: A more succint version: def squirrel_play(temp, is_summer): return temp in range(60, 101 if is_summer else 91)
type: Answer

http://stackoverflow.com/q/51479608
has comment: http://stackoverflow.com/comment/89931958
duplicate of: http://stackoverflow.com/q/15340582
score: 0
has title: Why is this lookbehind failing and what does this exception mean?
has comment: http://stackoverflow.com/comment/89928642
has comment: http://stackoverflow.com/comment/89927593
has comment: http://stackoverflow.com/comment/89931207
tagged with: lookbehind
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89929615
has body: I'm trying get all ID numbers preceded by some specific text, but it returns nothing followed by an exception ("Exception AttributeError: "'NoneType' object has no attribute 'path'" in &lt;function _remove at 0x01F68530&gt; ignored") f = open('log.txt') s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) a = re.compile('(?&lt;=Activating user record[\s\S]{98})[\w]{15}') ids = re.findall(a, s) print ids The pattern works when I test it. If I remove the lookbehind assertion or use another pattern, it's finding matches e.g. re.compile('[\w]{15}'). What am I missing? I'm trying to snag the 15 character ID from something like this: https://regex101.com/r/1JKo6O/2
has comment: http://stackoverflow.com/comment/89928158
tagged with: regex-lookarounds
has comment: http://stackoverflow.com/comment/89929498
answer count: 0
has comment: http://stackoverflow.com/comment/89928133
has comment: http://stackoverflow.com/comment/89929667
has comment: http://stackoverflow.com/comment/89928211
has comment: http://stackoverflow.com/comment/89930266
has comment: http://stackoverflow.com/comment/89927746
type: Question
linked to: http://stackoverflow.com/q/15340582
has comment: http://stackoverflow.com/comment/89928576
has comment: http://stackoverflow.com/comment/89930546
has comment: http://stackoverflow.com/comment/89930297
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/89929332

http://stackoverflow.com/q/51480426
upvote count: 1
accepted answer: http://stackoverflow.com/a/51590327
answer count: 1
has comment: http://stackoverflow.com/comment/123059963
favorite count: 0
tagged with: shader
has answer: http://stackoverflow.com/a/51590327
tagged with: python
has comment: http://stackoverflow.com/comment/89934207
has comment: http://stackoverflow.com/comment/89992309
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/89936887
score: 1
tagged with: pyopengl
type: Question
has body: I am just trying to run exactly this sample code to test the installation: https://gist.github.com/ousttrue/c4ae334fc1505cdf4cd7 It fails on glCreateProgram() eventhough i have instaled PyOpenGL, PyOpenGL-accelerate and freeglut using the whl files from here: https://www.lfd.uci.edu/~gohlke/pythonlibs/ Error: File "C:\Program Files (x86)\Python\Python35\lib\site- packages\OpenGL\platform\baseplatform.py", line 410, in __call__ self.__name__, self.__name__, OpenGL.error.NullFunctionError: Attempt to call an undefined function glCreateProgram, check for bool(glCreateProgram) before calling The Code from this tutorial which does not include a shader works just fine: https://noobtuts.com/python/opengl-introduction So it is just glCreateProgram() that fails. I have also copied the DLL files into SystenWOW64 and System32, as well as the folder my Script runs in. Has anyone an idea where to search for the error. I run Windows 10 64 Bit with 64 bit Python 3.5 via Remote Desktop
has title: PyOpenGL: glCreateProgram() causes NullFunctionError

http://stackoverflow.com/comment/89854109
type: AnswerComment
has text: I get "AttributeError: 'DataFrame' object has no attribute 'value' ". Should have specified it was a df maybe ? Added it in my post.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51441958

http://stackoverflow.com/a/51673106
has comment: http://stackoverflow.com/comment/90366721
has body: I ran into the same problem and ended up using Facebook python wrapper for FastText instead of gensim's implementation. import fastText model = fastText.load(path_to_french_bin) Then you can get word vectors for out-of-vocabulary words like so: oov_vector = model.get_word_vector(oov_word) As for why gensim's load_fasttext_format works for the English model and not the French one I don't know!
answers question: http://stackoverflow.com/q/51481553
upvote count: 5
score: 5
downvote count: 0
type: Answer

http://stackoverflow.com/comment/89679218
has text: Just for reference: https://docs.python.org/3.6/library/itertools.html#itertools-recipes
type: Comment
comment on: http://stackoverflow.com/a/51353296
score: 0
type: AnswerComment

http://stackoverflow.com/q/51329505
tagged with: odoo
has body: I'm sending email from module @override create method here is my method @api.model def create(self, values): res = super(licenses, self).create(values) template = self.env.ref('licenses.license_create_email_template', False) # Send out the e-mail template to the user self.env['mail.template'].browse(template.id).send_mail(res, force_send=True) return res here is my template <?xml version="1.0" encoding="utf-8"?> License Create ${user.email|safe} License Create ${object.x_partner_id.email} ${object.x_partner_id.lang} The License of ${object.x_partner_id.name} has been created. When i preview template from setting it rendering correctly but when i render email template from code it gives render error here is render error picture (Picture)Email template render problem error
accepted answer: http://stackoverflow.com/a/51334526
score: 0
tagged with: odoo-10
answer count: 1
has title: Odoo Email template render error
tagged with: python
has answer: http://stackoverflow.com/a/51334526
type: AnsweredQuestion
type: Question

scipy
tags question: http://stackoverflow.com/q/51390649
tags question: http://stackoverflow.com/q/51474792
tags question: http://stackoverflow.com/q/51479809
tags question: http://stackoverflow.com/q/51450708
tags question: http://stackoverflow.com/q/51392040
tags question: http://stackoverflow.com/q/51476588
tags question: http://stackoverflow.com/q/51472141
tags question: http://stackoverflow.com/q/51436766
tags question: http://stackoverflow.com/q/51470343
tags question: http://stackoverflow.com/q/51424647
tags question: http://stackoverflow.com/q/51399515
type: Tag
tags question: http://stackoverflow.com/q/51422840
tags question: http://stackoverflow.com/q/51385138
tags question: http://stackoverflow.com/q/51408435
tags question: http://stackoverflow.com/q/51407237
tags question: http://stackoverflow.com/q/51338448
tags question: http://stackoverflow.com/q/51357265
tags question: http://stackoverflow.com/q/51413068
tag name: scipy
tags question: http://stackoverflow.com/q/51467937
tags question: http://stackoverflow.com/q/51429596
tags question: http://stackoverflow.com/q/51343403
tags question: http://stackoverflow.com/q/51427764
tags question: http://stackoverflow.com/q/51405574
tags question: http://stackoverflow.com/q/51352538
tags question: http://stackoverflow.com/q/51470186
tags question: http://stackoverflow.com/q/51369303
tags question: http://stackoverflow.com/q/51369663
tags question: http://stackoverflow.com/q/51462834
tags question: http://stackoverflow.com/q/51358964
tags question: http://stackoverflow.com/q/51465708
tags question: http://stackoverflow.com/q/51377812
tags question: http://stackoverflow.com/q/51412955
tags question: http://stackoverflow.com/q/51458456
tags question: http://stackoverflow.com/q/51394973
tags question: http://stackoverflow.com/q/51410155
tags question: http://stackoverflow.com/q/51362331
tags question: http://stackoverflow.com/q/51459467
tags question: http://stackoverflow.com/q/51359476
tags question: http://stackoverflow.com/q/51331053
tags question: http://stackoverflow.com/q/51371902
tags question: http://stackoverflow.com/q/51386399
tags question: http://stackoverflow.com/q/51328872
tags question: http://stackoverflow.com/q/51451046
tags question: http://stackoverflow.com/q/51386947
tags question: http://stackoverflow.com/q/51414971
tags question: http://stackoverflow.com/q/51380580
tags question: http://stackoverflow.com/q/51334170
tags question: http://stackoverflow.com/q/51406199
tags question: http://stackoverflow.com/q/51429792
tags question: http://stackoverflow.com/q/51420923
tags question: http://stackoverflow.com/q/51365408
tags question: http://stackoverflow.com/q/51346630
tags question: http://stackoverflow.com/q/51470473
tags question: http://stackoverflow.com/q/51445332
tags question: http://stackoverflow.com/q/51352353

http://stackoverflow.com/a/51453606
answers question: http://stackoverflow.com/q/51449769
has comment: http://stackoverflow.com/comment/89887916
has body: You can try to do it using a scripted upsert, like this: actions = [ { '_op_type': 'update', "_index": index, "_type": "users", "_id": s['id_user'], "script": { "source": "ctx._source.purchases = ctx._source.purchases ?: params.purchases", "params": { "purchases": [] } }, "scripted_upsert": true, "upsert": {} } for i, s in users.iterrows() ] success, failure = self.db.bulk(actions, stats_only=True) The purchases array will only get assigned with the array in params if not already defined in the source.
accepted answer of: http://stackoverflow.com/q/51449769
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/89899253
type: QuestionComment
comment on: http://stackoverflow.com/q/51464939
has text: You don't tell us what the problem is with your code. Does it give an error? Does it not do anything at all?
score: 0
type: Comment

http://stackoverflow.com/q/51425552
tagged with: python
has comment: http://stackoverflow.com/comment/89822185
duplicate of: http://stackoverflow.com/q/6473679
has comment: http://stackoverflow.com/comment/89822139
has comment: http://stackoverflow.com/comment/89822348
has body: I need to reshape data sets from array of arrays to table like original: table_data = [ ['header_1', 12, 23, 34, 45, 56, 99, 100], ['header_2', 1, 2, 3, 4, 5, 6, 10], ['header_3', 999, 888, 777, 666, 555, 444, 333], ] expected: table_data = [ ['header_1', 'header_2', 'header_3'], [12, 1, 999], [23, 2, 888], [34, 3, 777], [45, 4, 666], [56, 5, 555], [99, 6, 444], [100, 10, 333], ]
type: Question
tagged with: numpy
has title: Reshape data from arrays to table like
score: 0
has comment: http://stackoverflow.com/comment/89822308
tagged with: pandas
has comment: http://stackoverflow.com/comment/89822143
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/6473679

http://stackoverflow.com/comment/89672500
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51349851
type: Comment
has text: Voted to close. @Nickiel please don't be discouraged by SO and this isn't personal, the question doesn't fit SO's format as it is a "help me debug my code" problem. That said, off the top of my head, perhaps a plugin running inside the spreadsheet software would work better, otherwise most applications lock the file to prevent something like this happening to avoid concurrent users corrupting the file.

http://stackoverflow.com/comment/89877313
score: 1
comment on: http://stackoverflow.com/q/51453844
type: Comment
type: QuestionComment
has text: You **have** to iterate

http://stackoverflow.com/comment/89908288
type: QuestionComment
comment on: http://stackoverflow.com/q/51467592
score: 0
has text: Nope, that's not it. The scripts it's about to convert into an exe is just a simple for loop that generates random numbers like lottery ticket numbers. Should be straight forward.. According to the image it says it cannot find module 'encodings' - So my guess is that pyinstaller do not work with Python 3.70 as it clearly are missing some modules. It generates perfectly, but it cannot be run. Nothing in the spec files calls for external things, only path is the script .py file used to generate the exe.
type: Comment

http://stackoverflow.com/comment/89664530
comment on: http://stackoverflow.com/a/51345641
has text: You should probably explain a little bit.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89916888
score: 0
has text: I didn't downvote your answer (yet!) - But it's pretty obvious, why it got downvoted - You do not answer the question! And what's even worse, that you knew that yourself, when posting the "answer" already.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51445170

http://stackoverflow.com/q/51450737
has comment: http://stackoverflow.com/comment/89872818
has comment: http://stackoverflow.com/comment/89874282
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51451580
has body: I have some data that was given to me in a format that I'm trying to get into a flat file for a customer. It is hierarchical data but it doesn't have all the data filled in and you can't just do an easy fill because of so many different sub levels involved. The numbers are always 4 digits and signify something specific. This is a report that can go out to dozens of subgroups with thousands of rows of data. Here is a sample in R: L1 &lt;- c("Main1", rep(NA, 21), "Main2", "Main3") L2 &lt;- c(NA, "Sub2_1", rep(NA, 22)) L3 &lt;- c(NA, NA, "Sub3_1", rep(NA, 17), "Sub3_2", rep(NA, 3)) L4 &lt;- c(rep(NA, 3), "Sub4_1", rep(NA, 9), "Sub4_2", rep(NA, 7), "0015", rep(NA, 2)) L5 &lt;- c(rep(NA, 4), "Sub5_1", NA, NA, "Sub5_2", NA, "Sub5_3", rep(NA, 4), "Sub5_5", rep(NA, 9)) L6 &lt;- c(rep(NA, 5), "1111", "2885", NA, "0001", NA, "Sub6_1", rep(NA, 4), "Sub6_2", rep(NA, 8)) L7 &lt;- c(rep(NA, 11), "Sub7_1", rep(NA, 4), "Sub7_2", rep(NA, 7)) L8 &lt;- c(rep(NA, 12), "0011", rep(NA, 4), "9494", "Sub8_1", rep(NA, 5)) L9 &lt;- c(rep(NA, 19), "8479", rep(NA, 4)) df &lt;- data.frame(L1, L2, L3, L4, L5, L6, L7, L8, L9) And I want an output like this since the four digit "code" is what we really need to look up: code_f &lt;- c("1111", "2885", "0001", "0011", "9494", "8479", "0015", NA, NA) L1_f &lt;- c(rep("Main1", 7), "Main2", "Main3") L2_f &lt;- c(rep("Sub2_1", 7), NA, NA) L3_f &lt;- c(rep("Sub3_1", 6), "Sub3_2", NA, NA) L4_f &lt;- c(rep("Sub4_1", 4), rep("Sub4_2", 2), rep(NA, 3)) L5_f &lt;- c(rep("Sub5_1", 2), "Sub5_2", "Sub5_3", rep("Sub5_5", 2), rep(NA, 3)) L6_f &lt;- c(rep(NA, 3), "Sub6_1", rep("Sub6_3", 2), rep(NA, 3)) L7_f &lt;- c(rep(NA, 3), "Sub7_1", rep("Sub7_2", 2), rep(NA, 3)) L8_f &lt;- c(rep(NA, 5), "Sub8_1", rep(NA, 3)) df_f &lt;- data.frame(code_f, L1_f, L2_f, L3_f, L4_f, L5_f, L6_f, L7_f, L8_f)
has title: Hierarchical Data List Data Wrangling in R or Python
type: Question
has comment: http://stackoverflow.com/comment/89874337
accepted answer: http://stackoverflow.com/a/51451576
tagged with: hierarchical-data
tagged with: http://stackoverflow.com/tag/r
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51451580
has answer: http://stackoverflow.com/a/51451576
has comment: http://stackoverflow.com/comment/89871867
tagged with: hierarchy

http://stackoverflow.com/a/51395687
has body: A1,A2: It looks like you want V to be a list of lists, where the outer list has n lists of m values, where each value is f(i,j). For this, you don't need to pre-initialize the list, you can just use the append method. While iterating, the enumerate method will give you the index of the current element in G, so you can access the current list in V. The following will build your list of lists: V = [] for outerListIndex, i in enumerate(G): V.append([]) for j in I: V[outerListIndex].append(f(i,j))
type: Answer
has comment: http://stackoverflow.com/comment/89763359
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51395116
answers question: http://stackoverflow.com/q/51395116

http://stackoverflow.com/a/51334954
has body: Your derivative definition doesn't have a base condition to stop the recursion calls (also mentioned by @Miket25 in the comments), and seems a bit awkward too: Per Wolfram, the derivative closed form w. r. t. x is: You could change dsigmoid to: def dsigmoid(x): enegx = np.exp(-x) return enegx / (1 + enegx) ** 2
answers question: http://stackoverflow.com/q/51334924
upvote count: 1
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/89801907
type: QuestionComment
has text: "based on the type of $(CURTARGET)" shouldn't that be "based on the value of $(CURTARGET)" ?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51415259

http://stackoverflow.com/comment/89850043
comment on: http://stackoverflow.com/a/51439879
score: 0
type: AnswerComment
type: Comment
has text: i'm doing this,to escape from 1st time entering url on browser

pythonpath
tags question: http://stackoverflow.com/q/51403479
tags question: http://stackoverflow.com/q/51401774
type: Tag
tags question: http://stackoverflow.com/q/51452760
tag name: pythonpath

http://stackoverflow.com/comment/89874383
has text: Wish I had more time to edit down and make a nice tree diagram showing this with much less words, but gotta sign off for now! Hope this "ELI5" version is helpful for someone.
type: AnswerComment
comment on: http://stackoverflow.com/a/51452163
type: Comment
score: 1

http://stackoverflow.com/a/51359077
upvote count: 2
answers question: http://stackoverflow.com/q/51359010
type: Answer
score: 2
has body: you can replace " after read_csv and save that file again using df_csv.to_csv('fname') df_csv.apply(lambda x:x.str.replace('"', ""))
downvote count: 0

http://stackoverflow.com/comment/89861607
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51439245
has text: What is that `metadata` on a line by itself? I would start by `pdb` to see why the ValueError is being raised. You may try explicitly applying `df.astype(df._meta.dtypes)` before writing.

http://stackoverflow.com/comment/89924911
has text: are you getting any error? If yes then what is the error message?
comment on: http://stackoverflow.com/a/51472515
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51344709
type: UnansweredQuestion
type: Question
tagged with: runtime
has body: I am currently having an issue with a rather extensive Python program I have written. The program is a tactical calculator for a game and is shown below. # Tactical Calculator budget = int(input("budget per round:")) amount = int(input("ingots per round:")) rounds = int(input("rounds:")) infantry_budget = {'assault': 80, 'light': 90, 'motorized': 100, 'commando': 150} engine_budget = {'armored': 135, 'tank': 180, 'heavy tank': 240, 'super tank': None} artillery_budget = {'battalion': 120, 'field': 200, 'rocket': 220} amount1 = [int((budget * rounds) / infantry_budget["light"]), int((budget * rounds) / infantry_budget["assault"]), int((budget * rounds) / infantry_budget["motorized"]), int((budget * rounds) / infantry_budget["commando"])] print(amount1) amount2 = [int((budget * rounds) / engine_budget['armored']), int((budget * rounds) / engine_budget(['tank'])), int((budget * rounds) / engine_budget['heavy tank'])] print(amount2) infantry_ingots = {'assault': 10, 'motorized': 30, 'commando': 45} engine_ingots = {'armored': 60, 'tank': 90, 'heavy tank': 145, 'super tank': None} artillery_ingots = {'battalion': 50, 'field': 80, 'rocket': 100} The issue I have is that after amount1 is printed, the Python shell prints a runtime error, stating that " 'dict' object is not callable". I would please like to know why it is printing this error and how to fix it. Thank you very much for any assistance you can offer concerning this program.
has title: Python runtime error in tactical game: dict object not callable
score: 0
has comment: http://stackoverflow.com/comment/89662735
tagged with: python
has comment: http://stackoverflow.com/comment/89662695
tagged with: dictionary
answer count: 0

http://stackoverflow.com/comment/89703804
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51364002
has text: Thank you for answer, I edited my question for explain myself better. I'll glad if you look at again
type: AnswerComment

http://stackoverflow.com/q/51397717
type: Question
has comment: http://stackoverflow.com/comment/89807354
tagged with: geopy
linked to: http://stackoverflow.com/q/51393049
has title: loop dataframe column to covert county to coordinates
has comment: http://stackoverflow.com/comment/89845774
score: 0
has body: I want to convert county state name to coordinates. county: fips state_fips county_fips state county 1000 1 0 Alabama Alabama 1005 1 5 Alabama Barbour County 1007 1 7 Alabama Bibb County 1009 1 9 Alabama Blount County 1011 1 11 Alabama Bullock County 6085 6 85 California Santa Clara County 6089 6 89 California Shasta County 6091 6 91 California Sierra County 32021 32 21 Nevada Mineral County 32023 32 23 Nevada Nye County 32027 32 27 Nevada Pershing County 32029 32 29 Nevada Storey County I want to use python geopy package. from geopy.geocoders import Nominatim import pandas as pd import numpy as np import time geolocator = Nominatim(timeout=None) fobj_out = open('county_coordinate.txt', 'a') i=0 for row in county.itertuples(index=True, name='Pandas'): location = geolocator.geocode(getattr(row, "county")) #print(location.address) #print((location.latitude, location.longitude)) cty=getattr(row, "county") #lat = location.latitude #long = location.longitude fobj_out.write(str(i)) i=i+1 fobj_out.write(",") fobj_out.write(cty) fobj_out.write(",") fobj_out.write(str(location.latitude)) fobj_out.write(",") fobj_out.write(str(location.longitude)) fobj_out.write("\n") time.sleep(0.5) # delay 5 milli-seconds between each request fobj_out.close() I got the error: TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond urllib.error.URLError: &lt;urlopen error [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond&gt; geopy.exc.GeocoderServiceError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond First, I hope the time.sleep could he…
tagged with: python
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/89891587
type: Comment
comment on: http://stackoverflow.com/q/51460227
type: QuestionComment
has text: [Have you checked how many raw SQL queries are occurring?](https://docs.djangoproject.com/en/2.0/faq/models/#how-can-i-see-the-raw-sql-queries-django-is-running). If not, follow the link and let me know how many are happening. Edit: I will do my best to help.
score: 1

http://stackoverflow.com/a/51403405
has comment: http://stackoverflow.com/comment/89777737
has comment: http://stackoverflow.com/comment/89778004
has body: df.loc[mask].Values.values gives you an array of the values; df.loc[mask].Values.values[0] (or whatever index) will give you just the value.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51403325

http://stackoverflow.com/q/51430560
tagged with: lda
score: 3
has answer: http://stackoverflow.com/a/51450733
answer count: 1
tagged with: text-mining
has title: gensim lda permission denied when I try to save my model
favorite count: 0
upvote count: 3
has body: I've been getting some irregular behavior from an LDA topic model program and right now, it seems like my file won't save the lda model it creates... I'm really not sure why. Here's a code snippet, albeit it's going to take me more time before I could write code that's reproducible since I'm really just trying to load certain files I created beforehand. def naive_LDA_implementation(name_of_lda, create_dict=False, remove_low_freq=False): LDA_MODEL_PATH = "lda_dir/" + str(name_of_lda) +"/model_dir/" # for some reason this location doesn't work entirely... and yes, I have made a directory in a the folder of this name. # This ends up saving the .state, .id2word, and .expEblogbeta.npy files... But normally when saving an lda model actually works, a fourth file is included that's to my understanding the model itself. # LDA_MODEL_PATH = "models/" # This is what I originally had as the location for LDA_MODEL_PATH. I was using a directory called models for multiple lda models. This no longer works. doc_df = getCorpus(name_of_lda, cleaned=True) # returns a dataframe containing a row for each text record and an extra column that contains the tokenized version of the text's post/string of words. dict_path = "lda_dir/" + str(name_of_lda) + "/dict_of_tokens.dict" docs_of_tokens = convert_cleaned_tokens_entries(doc_df['cleaned_tokens']) if create_dict != False: doc_dict = corpora.Dictionary(docs_of_tokens) : if remove_low_freq==True: doc_dict.filter_extremes(no_below=5, no_above=0.6) doc_dict.save(dict_path) print("Finished saving") else: doc_dict = corpora.Dictionary.load(dict_path) doc_term_matrix = [doc_dict.doc2bow(doc) for doc in docs_of_tokens] # gives a unique id for each word in corpus_arr Lda = gensim.models.ldamodel.LdaModel ldamodel = Lda(doc_term_matrix, num_topics=15, id2word = doc_dict, passes=20, chunksize=10000) ldamodel.save(LDA_MODEL_PATH) To put it sraightforwardly... I have no clue why permission is being denied when I try to save my lda model to a particular l…
tagged with: python
tagged with: gensim
linked to: http://stackoverflow.com/q/3718657
downvote count: 0
type: UnansweredQuestion
type: Question

http://stackoverflow.com/q/51371835
tagged with: pandas
has title: Replace None with NaN and ignore NoneType in Pandas
has answer: http://stackoverflow.com/a/51372046
tagged with: python
has answer: http://stackoverflow.com/a/51372004
type: AnsweredQuestion
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/51372004
type: Question
tagged with: numpy
answer count: 2
upvote count: 1
has body: I'm attempting to create a raw string variable from a pandas dataframe, which will eventually be written to a .cfg file, by firstly joining two columns together as shown below and avoiding None: Section of df: command value ... 439 sensitivity "0.9" 440 cl_teamid_overhead_always 1 441 host_writeconfig None ... code: ... df = df['value'].replace('None', np.nan, inplace=True) print df df = df['command'].astype(str)+' '+df['value'].astype(str) print df cfg_output = '\n'.join(df.tolist()) print cfg_output I've attempted to replace all the None values with NaN firstly so that no lines in cfg_output contain "None" as part of of the string. However, by doing so I seem to get a few undesired results. I made use of print statements to see what is going on. It seems that df = df['value'].replace('None', np.nan, inplace=True), simply outputs None. It seems that df = df['command'].astype(str)+' '+df['value'].astype(str) and cfg_output = '\n'.join(df.tolist()), cause the following error: TypeError: 'NoneType' object has no attribute '__getitem__' Therefore, I was thinking that by ignoring any occurrences of NaN, the code may run smoothly, although I'm unsure about how to do so using Pandas Ultimately, my desired output would be as followed: sensitivity "0.9" cl_teamid_overhead_always 1 host_writeconfig
downvote count: 1
favorite count: 0
score: 0
accepted answer: http://stackoverflow.com/a/51372046

http://stackoverflow.com/comment/89791192
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51409756
score: 0
has text: The lists will never be more than 2 times longer than the other, but there is no bound on whether list1 is the bigger list or if list2 is the bigger list

http://stackoverflow.com/q/51466153
tagged with: python
type: UnansweredQuestion
downvote count: 2
has title: How to save extracted pitch values in a csv file?
type: Question
tagged with: audio
score: -2
tagged with: feature-extraction
tagged with: signal-processing
answer count: 2
tagged with: feature-selection
upvote count: 0
has answer: http://stackoverflow.com/a/51466504
has body: Well I think I should mention it that it's the very first time I'm trying Audio signal processing in Python. I have an audio data set and I am extracting pitch features using Aubio library, and MFCC feature using the python_speech_features library in Python. The thing is, for a single audio file, I am getting around 84 valued vector for the pitch and 12 valued feature vector for MFCC. Image of extracted pitch feature vector So how do I save all these so many values in a single csv file? I have around 700 audio files separated in different directories wrt to emotions. Should I take the mean of all of these values and save them wrt the audio file in a csv? Like this: Also, how would I used these values for classification then? Any help would be much appreciated, Thanks.
favorite count: 0
has answer: http://stackoverflow.com/a/51466273

http://stackoverflow.com/a/51468575
has comment: http://stackoverflow.com/comment/89905997
accepted answer of: http://stackoverflow.com/q/51468432
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89905797
type: Answer
has comment: http://stackoverflow.com/comment/89915231
has body: setuptools comes with a pkg_resources framework for handling cases like this. There's a lot to read there, and I don't know of any good tutorials, but the basic idea is this: You specify executableFile as a file resource. setuptools figures out where to stick that at install (or wheel-building) time. At runtime, you call resource_filename to get the path to executableFile, and you subprocess.call that path. You probably also want to atexit the cleanup_resources function. Under the covers, pkg_resources will figure out all the details. With --inplace it will be a file in your source tree; with an exploded install, it will be a file somewhere in your site-packages; with an egg install, or even as part of a site-packages zipped up by py2exe or the like, it will be a file extracted on demand to a cache directory. But you don't have to worry about that; you just get a path and it works. Meanwhile: I think this happens because the subprocess.call(...) searches the executableFile in the main.py folder instead of the package folder. It searches the current working directory. That may be the same as the directory main.py is in, but only if your user ran your program by changing to that directory and running ./main.py or python main.py or similar. I've tried to use os.path.dirname(os.path.abspath('executableFile')) That isn't going to work, because abspath is searching the current working directory too, so it's just a more complicated way of getting the same incorrect path. And then you dirname that, and get back the working directory, which is useless. If you knew the relative path from package.classA.py to executableFile, you could find it this way: packagedir = os.path.dirname(os.path.abspath(__file__)) execdir = os.path.join(packagedir, '&lt;that relative path&gt;') execpath = os.path.join(execdir, 'executableFile') Or, if you knew the relative path from main.py, you could do the same thing inside main.py and store the path somewhere to be used later (e.g., pass it into t…
answers question: http://stackoverflow.com/q/51468432

http://stackoverflow.com/comment/89881185
type: AnswerComment
has text: Thanks, this did the problem, I think I was missing the `fill=BOTH` part!
type: Comment
comment on: http://stackoverflow.com/a/51455577
score: 0

numba
tags question: http://stackoverflow.com/q/51459701
tags question: http://stackoverflow.com/q/51384157
tags question: http://stackoverflow.com/q/51347988
tags question: http://stackoverflow.com/q/51421992
tag name: numba
tags question: http://stackoverflow.com/q/51419608
tags question: http://stackoverflow.com/q/51412619
tags question: http://stackoverflow.com/q/51369663
tags question: http://stackoverflow.com/q/51324539
type: Tag
tags question: http://stackoverflow.com/q/51423566

http://stackoverflow.com/comment/89776096
score: 1
comment on: http://stackoverflow.com/q/51402593
has text: Welcome to [Stack Overflow!](https://stackoverflow.com) Please take the [tour](https://stackoverflow.com/tour), have a look around, and read [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask). Also like @SreeramTP said, you should share what you have tried.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/65659315
answers question: http://stackoverflow.com/q/51392889
score: 15
has body: You might also receive this if you set a breakpoint, but didn't use the -s flag with pytest.
type: Answer
upvote count: 15
downvote count: 0
has comment: http://stackoverflow.com/comment/130958402

http://stackoverflow.com/comment/90523049
type: Comment
comment on: http://stackoverflow.com/a/51487322
type: AnswerComment
score: 0
has text: Thanks - I added my code. I think the problem could be because i'm using flask_restful...?

http://stackoverflow.com/q/51471188
score: -1
has comment: http://stackoverflow.com/comment/89910689
tagged with: pandas
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51471213
tagged with: python
type: AnsweredQuestion
has body: I have raw data looks like df, how can I made df to df1? df = pd.DataFrame({"A":["A","A","B","B","B"], "B":["N","N","N","S","S"], "C":["E","E","NE","NE","NE"], "D":["y","n","n","y","n"]}) df1 = pd.DataFrame({"A":["A","N","E"], "B":["N","N","S"], "C":[2,1,2], "D":[1,0,1]})
has title: Pandas Counts with different level
downvote count: 1
has comment: http://stackoverflow.com/comment/89910690
type: Question
accepted answer: http://stackoverflow.com/a/51471213
upvote count: 0

http://stackoverflow.com/comment/90101571
type: Comment
comment on: http://stackoverflow.com/a/51452885
score: 0
type: AnswerComment
has text: A few other dumps: https://pastebin.com/Jw3gTn0Z Please compare these with yours.

http://stackoverflow.com/q/51480971
has answer: http://stackoverflow.com/a/51481156
has comment: http://stackoverflow.com/comment/89930794
answer count: 2
linked to: http://stackoverflow.com/q/14132789
has comment: http://stackoverflow.com/comment/89931361
downvote count: 0
has answer: http://stackoverflow.com/a/51481339
accepted answer: http://stackoverflow.com/a/51481339
favorite count: 0
tagged with: package
tagged with: python
has title: Execute a python file from different directory
possible better answer: http://stackoverflow.com/a/51481156
score: 2
type: AnsweredQuestion
upvote count: 2
has body: I try to understand how to split up python files belonging to the same project in different directories. If I understood it right I need to use packages as described here in the documentation. So my structure looks like this: . ├── A │ ├── fileA.py │ └── __init__.py ├── B │ ├── fileB.py │ └── __init__.py └── __init__.py with empty __init__.py files and $ cat A/fileA.py def funA(): print("hello from A") $ cat B/fileB.py from A.fileA import funA if __name__ == "__main__": funA() Now I expect that when I execute B/fileB.py I get "Hello from A", but instead I get the following error: ModuleNotFoundError: No module named 'A' What am I doing wrong?
tagged with: directory-structure
type: Question
linked to: http://stackoverflow.com/q/43728431
has comment: http://stackoverflow.com/comment/89930977

http://stackoverflow.com/a/51345191
type: AcceptedAnswer
has body: Use QVector2D: from PyQt5 import QtCore, QtGui A = QtCore.QPoint(200,200) B = QtCore.QPoint(400,400) res = QtGui.QVector2D(B-A).normalized() print(res) Output: PyQt5.QtGui.QVector2D(0.7071067690849304, 0.7071067690849304)
answers question: http://stackoverflow.com/q/51345105
type: Answer
accepted answer of: http://stackoverflow.com/q/51345105
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/51373900
upvote count: 5
tagged with: database
has body: I'm looking to select rows where state contains the word Traded and trading _book does not start with letters 'E','L','N' Test_Data = [('originating_system_id', ['RBCL', 'RBCL', 'RBCL','RBCL']), ('rbc_security_type1', ['CORP', 'CORP','CORP','CORP']), ('state', ['Traded', 'Traded Away','Traded','Traded Away']), ('trading_book', ['LCAAAAA','NUBBBBB','EDFGSFG','PDFEFGR']) ] dfTest_Data = pd.DataFrame.from_items(Test_Data) display(dfTest_Data) originating_system_id rbc_security_type1 state trading_book RBCL CORP Traded LCAAAAA RBCL CORP Traded Away NUBBBBB RBCL CORP Traded EDFGSFG RBCL CORP Traded Away PDFEFGR Desired output: originating_system_id rbc_security_type1 state trading_book RBCL CORP Traded Away PDFEFGR I though this would do the trick: prefixes = ['E','L','N'] df_Traded_Away_User = dfTest_Data[ dfTest_Data[~dfTest_Data['trading_book'].str.startswith(tuple(prefixes))] &amp; (dfTest_Data['state'].str.contains('Traded')) ]'originating_system_id','rbc_security_type1','state','trading_book' display(df_Traded_Away_User) but I'm getting: ValueError: Must pass DataFrame with boolean values only
type: Question
score: 5
downvote count: 0
accepted answer: http://stackoverflow.com/a/51373925
favorite count: 0
tagged with: pandas
answer count: 1
tagged with: python
has title: Pandas dataframe - Select rows where one column's values contains a string and another column's values starts with specific strings
has answer: http://stackoverflow.com/a/51373925
type: AnsweredQuestion

http://stackoverflow.com/a/51377617
score: 4
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/89727219
answers question: http://stackoverflow.com/q/51377543
type: Answer
has body: Assignment such as num //= 10 is a statement and cannot be part of an expression. Why is this so in python? Recently it was decided that assignment should be allowed in expressions in certain situations and this caused a huge controversy, see this article for more.
has comment: http://stackoverflow.com/comment/89726877

http://stackoverflow.com/a/51338292
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/89651260
has comment: http://stackoverflow.com/comment/89651051
score: 4
has body: You can always try it in interpreter to see which error gets raised: &gt;&gt;&gt; int('a') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: invalid literal for int() with base 10: 'a' Now that you know that it is ValueError, just change your code: while True: try: i = int(input('Enter an INTEGER: ')) except ValueError: print("You must enter an INTEGER, not any other format of data") else: break # to exit the while loop
answers question: http://stackoverflow.com/q/51338230
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51338230
type: Answer

http://stackoverflow.com/a/51428033
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51427829
score: 1
upvote count: 1
has body: Several things: if statements require a : at the end of them sad, unmotivated, etc. are interpreted as variables. I'm assuming you meant if 'sad' in userInput This wasn't actually breaking your code, but will clean it up - instead of nesting more if statements inside an else, use elif Improvement - your code currently assumes that any answers not including "sad", "unmotivated", or "angry" must be happy. Why not handle "happy" explicitly and add an extra case that let's the user know you don't understand? import secrets myLst = ["Cheer up. Although life may not be easy now, in the end it’s all worth it. Everything will get better in time. So SMILE!", "the sun will rise and we will try again", "No one is in control of your happiness but you; therefore, you have the power to change anything about yourself or your life that you want to change."] myLst2 = ["We Generate Fears While We Sit. We Overcome Them By Action", "You Are Never Too Old To Set Another Goal Or To Dream A New Dream", "Of course motivation is not permanent. But then, neither is bathing; but it is something you should do on a regular basis."] myLst3 = ["Speak when you are angry and you will make the best speech you will ever regret", "If you spend your time hoping someone will suffer the consequences for what they did to your heart, then you're allowing them to hurt you a second time in your mind", "When angry, count four. When very angry, swear"] myLst4 = ["Let us be grateful to people who make us happy", "I have only two kinds of days: happy and hysterically happy", "Be happy. It’s one way of being wise"] def motivationalQuote(): userInput = input ("What is your mood? Sad, unmotivated, angry or happy?") if 'sad' in userInput: print(secrets.choice(myLst)) elif 'unmotivated' in userInput: print(secrets.choice(myLst2)) elif 'angry' in userInput: print(secrets.choice(myLst3)) elif 'happy' in userInput print(secrets.choice(myLst4)) else: print('I cannot tell how you are feeling!')

http://stackoverflow.com/a/51470229
answers question: http://stackoverflow.com/q/51465663
has body: The adjacency matrix returned by NetworkX is sparse. First, convert it to a dense matrix: dense = nx.adjacency_matrix(G).todense() Create a dataframe whose content is the adjacency matrix and rows and columns represent all nodes: adj_df = pd.DataFrame(dense, index=G.nodes(), columns=G.nodes()) Finally, take the subset of the dataframe, as defined by df: adj_df.loc[df.Name, df.Name] # Jack Anna Emilie Frank John #Jack 0 0 1 0 0 #Anna 0 0 0 0 0 #Emilie 1 0 0 0 0 #Frank 0 0 0 0 1 #John 0 0 0 1 0
downvote count: 0
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/comment/90121607
comment on: http://stackoverflow.com/q/51405945
type: Comment
type: QuestionComment
has text: This doesn't look like Python syntax. You probably should start there.
score: 0

http://stackoverflow.com/comment/89815860
type: AnswerComment
comment on: http://stackoverflow.com/a/51422144
type: Comment
has text: Added some explanation
score: 0

http://stackoverflow.com/comment/89821076
score: 0
has text: Thanks, putting it into a set really sped things up a ton! My problem is now solved, but I'm just curious, what do you mean by a mapper function in the second part?
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51412519

http://stackoverflow.com/q/51347747
has comment: http://stackoverflow.com/comment/89668242
answer count: 0
score: 1
upvote count: 1
has body: I am using DefaultDict to create a dictionary and for some reason, it seems to be switching the key and pair and I am not sure why. recurring_suppliers[supplier_name] = ( float(transaction_amount)) print(supplier_name) print(transaction_amount) print(recurring_suppliers) The output is the following: defaultdict(&lt;class 'str'&gt;, {}) תמרי-וקסר אחזקות בע"מ 2340.0 defaultdict(&lt;class 'str'&gt;, {'תמרי-וקסר אחזקות בע"מ': 2340.0}) Here is the DefaultDict declaration as well: recurring_suppliers = defaultdict(str) Any idea why the formatting is printed this way? I've never experienced this after using DefaultDict often. I am also confused by the single quotes at the start of the number and after the colon. Any insight is appreciated, thanks in advance!
type: Question
has title: DefaultDict Switching Key-Pairs
downvote count: 0
tagged with: defaultdict
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89668579
tagged with: python
has comment: http://stackoverflow.com/comment/89668394

http://stackoverflow.com/a/51410222
upvote count: 1
answers question: http://stackoverflow.com/q/51410168
downvote count: 0
type: Answer
has body: You can use re.findall after using join on your list: &gt;&gt;&gt; re.findall(r'(\[.*?\]|\(.*?\))', ''.join(a)) ['[Test]', '(Link)', '[Test2]', '(link2)', '[test3]', '(link3)'] Regex Explanation: ( # Matching group 1 \[.*?\] # Matches non-greedily in between brackets | # OR \(.*?\) # Matches non-greedily between parenthesis ) # End of matching group
score: 1

http://stackoverflow.com/q/51368859
answer count: 1
has title: Python logging calling module from multiple places
has comment: http://stackoverflow.com/comment/89710156
score: 0
has answer: http://stackoverflow.com/a/51369231
linked to: http://stackoverflow.com/q/51125808
favorite count: 0
has comment: http://stackoverflow.com/comment/89710140
type: UnansweredQuestion
has body: I would like to set up a logging hierarchy for my project using python's logging module and the dot '.' name structure described here: https://docs.python.org/2/library/logging.html#logging.getLogger For a given module (bar.py), I would like to set up the logger something like: log = logging.getLogger('x.bar') Where I can then use log.(debug/info/warning/etc...) throughout the bar.py module. I know that bar.py will never be run directly, but functions within it could possibly be called from several other modules - so I don't know advance what to set 'x' to in the code snippet. I want bar.py to inherit the logging handlers and formatters from it's caller (x).
upvote count: 1
tagged with: python
tagged with: logging
downvote count: 1
type: Question

http://stackoverflow.com/q/51473501
accepted answer: http://stackoverflow.com/a/51473779
tagged with: numpy
type: AnsweredQuestion
has title: How to repeat rows based on value of a column in Python
has body: I have the following df that comprises of code/product &amp; weeks columns. code. Product . weeks 123 . product1 . 1;2 123 . product1 . 3 321 . product2 . 4;5;6 321 . product2 . 7 For those rows that have more than 1 week (eg 1;2 or 4;5;6), I want to repeat these rows. My Desirsed output is as follows: code. Product . weeks 123 . product1 . 1 123 . product1 . 2 123 . product1 . 3 321 . product2 . 4 321 . product2 . 5 321 . product2 . 6 321 . product2 . 7 What is the best approach to take using pandas or numpy?
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: pandas
has comment: http://stackoverflow.com/comment/89915633
linked to: http://stackoverflow.com/q/32468402
tagged with: python
has answer: http://stackoverflow.com/a/51473779
answer count: 2
possible better answer: http://stackoverflow.com/a/51473789
upvote count: 1
has answer: http://stackoverflow.com/a/51473789

awk
tag name: awk
type: Tag
tags question: http://stackoverflow.com/q/51414103

http://stackoverflow.com/comment/113323054
has text: `E: Unable to locate package python-matplotlib-qt5 ` on ubuntu20.04
comment on: http://stackoverflow.com/a/51444612
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51444151
type: Question
tagged with: canopy
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51451280
type: UnansweredQuestion
has title: Enthought Canopy - working directory changes when code is run
tagged with: python
has body: I am trying to run a Python script in Enthought Canopy (which I use regularly). The script reads in a number of files, so I use the Canopy editor to set the working directory. However, every time the code runs, the working directory changes (without my asking it to) and the code doesn't run properly. The script itself is stored in a third directory, which is neither the working directory I want nor the directory Canopy switches to. I haven't seen this before, so would appreciate some advice.

http://stackoverflow.com/q/51476922
linked to: http://stackoverflow.com/q/10861784
upvote count: 9
has comment: http://stackoverflow.com/comment/89927667
has answer: http://stackoverflow.com/a/60764856
score: 9
tagged with: django-sessions
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89923119
has comment: http://stackoverflow.com/comment/89926713
tagged with: python
has body: This is my current sessionId cookie attributes: Set-Cookie: sessionid=3jdpjxgepk49vrnhbabdvju3r80ci581; expires=Mon, 06-Aug-2018 12:40:14 GMT; HttpOnly; Max-Age=1209600; Path=/ I want sessionId to be secure with the secure attribute: Set-Cookie: sessionid=3jdpjxgepk49vrnhbabdvju3r80ci581; expires=Mon, 06-Aug-2018 12:40:14 GMT; HttpOnly,secure; Max-Age=1209600; Path=/ I have tried adding the following attribute in settings.py: SESSION_COOKIE_SECURE = True However, I am still not getting the secure attribute in sessionId. Any alternative solution for this?
type: UnansweredQuestion
tagged with: django
type: Question
has title: How to make Django sessionId cookie as secure

http://stackoverflow.com/a/51473986
has body: I would attempt to isolate the linked ads first, then get 10 random out of them using order by a generated random column. I am not sure how this would be effective out of generated sql. To be sure, i would prefer to create a stored procedure exactly on the task since this is clear a data mining operation that ends up on random samples.
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51460227
score: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51460227

http://stackoverflow.com/q/51340386
has comment: http://stackoverflow.com/comment/89654355
type: Question
has comment: http://stackoverflow.com/comment/89654440
has comment: http://stackoverflow.com/comment/111883571
has title: how to translate word with google translator?
has answer: http://stackoverflow.com/a/51340484
has comment: http://stackoverflow.com/comment/89654340
has answer: http://stackoverflow.com/a/68949360
downvote count: 3
has body: I'm making simple script that will translate words from English to Russian language using requests and BeatifulSoup, the problem is that the result box is empty where should be translated word/ I'm not sure if i should use GET or POST method. This is what I've tried with open('File.csv', 'r') as file: csv_reader = csv.reader(file) for line in csv_reader: if line[1] == '': url = 'https://translate.google.com/#en/ru/{}'.format(line[0]) r = requests.get(url, timeout=5) soup = BeautifulSoup(r.content, 'html.parser') translate = soup.find('span', id='result_box') for word in translate: print(word.find('span', class_=''))
possible better answer: http://stackoverflow.com/a/63271805
upvote count: 4
accepted answer: http://stackoverflow.com/a/51340484
has answer: http://stackoverflow.com/a/63271805
score: 1
favorite count: 0
tagged with: beautifulsoup
tagged with: python
linked to: http://stackoverflow.com/q/22587001
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/72197989
linked to: http://stackoverflow.com/q/3867860

http://stackoverflow.com/a/62325781
score: 0
type: Answer
has body: I was trying to do the same thing and I was getting error like this. So I tried install vtk package with conda. You need conda to install vtk of course so: !wget -c https://repo.anaconda.com/miniconda/Miniconda3-4.5.4-Linux-x86_64.sh !chmod +x Miniconda3-4.5.4-Linux-x86_64.sh !bash ./Miniconda3-4.5.4-Linux-x86_64.sh -b -f -p /usr/local !conda install -q -y --prefix /usr/local python=3.6 ujson import sys sys.path.append('/usr/local/lib/python3.6/site-packages') import ujson print(ujson.dumps({1:2})) !conda --version Then set up vtk package with conda as: !apt-get install vtk6 !conda install -c anaconda vtk I was trying to install mayavi for mne package so: !conda activate mne !conda install gxx_linux-64=7.3 !pip install https://api.github.com/repos/enthought/mayavi/zipball/226189a6ad3dc3c01d031ef21d0d0cde554ac851 Be careful because you need to mne package to activate so before installing mayavi (I was trying to install mne as I said before): !pip install mne
answers question: http://stackoverflow.com/q/51393710

http://stackoverflow.com/comment/89741711
type: QuestionComment
type: Comment
has text: I'm already using a logger for each module (`LOG = logging.getLogger(__name__)` ) but they all depend on the root logger, which is the one I configured with 2 handlers and I want to keep this mechanism to know which module is logging.
score: 0
comment on: http://stackoverflow.com/q/51383097

http://stackoverflow.com/comment/89635495
score: 0
comment on: http://stackoverflow.com/q/51329757
type: QuestionComment
has text: "user [pid]" is a value
type: Comment

http://stackoverflow.com/comment/89911776
has text: if test_package is a python script then you might not need to type the extension. By the way, what is the test part you are trying to print? Also, make sure they are in the same directory.
comment on: http://stackoverflow.com/q/51471734
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51405882
accepted answer of: http://stackoverflow.com/q/51405256
type: Answer
has body: make_private was added in the 1.10 version of the Storage client library. Check which version are you using with pip list, as you must be using a different version, and upgrade if possible. Nonetheless, if you can't upgrade (let's say that your development environment is 'tied' to this version of the library), I tested this with a different version that I have in one development environment (version 1.8.0) , and if you follow the source code for make_private and do those two lines in the code, it works. So, like this: #blob.make_private() is basically: blob.acl.all().revoke_read() blob.acl.save(client=blob.client)
answers question: http://stackoverflow.com/q/51405256
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/89783771
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51344717
has body: I have a shell that executes on boot via init.d, to run a python script upon boot: #!/bin/bash ### BEGIN INIT INFO # Provides: start.sh # Required-Start: $all # Required-Stop: # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Prepare device ### END INIT INFO PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/bin . /lib/init/vars.sh . /lib/lsb/init-functions sudo /usr/bin/python /dir/script.py &amp; exit Part of the scripts pulls data from a database: cmd = "mysql -h 127.0.0.1 -upi -pXXXX -e 'some SQL code" Messages = subprocess.check_output(cmd, shell = True ) The python script correctly initializes on boot and runs end-to-end when executed from the console. However, when executed during the boot process, it looks like mysql service isn't fully functional yet: ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111 "Connection refused") How can I make sure the shell doesn't run until the mysql service is up?
has comment: http://stackoverflow.com/comment/89663872
type: UnansweredQuestion
has title: Shell script running on boot can't run mysql
upvote count: 0
score: -1
has comment: http://stackoverflow.com/comment/89662756
type: Question
has answer: http://stackoverflow.com/a/51344741
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/89662746
has comment: http://stackoverflow.com/comment/89662738
tagged with: linux
has comment: http://stackoverflow.com/comment/89662720
answer count: 1
downvote count: 1
tagged with: python
favorite count: 0

http://stackoverflow.com/q/51359439
has title: filterset lookups for annotated fields
tagged with: python
tagged with: django-rest-framework-filters
downvote count: 0
score: 1
has body: i have a problem to create a filterset for one of my ModelViewSets to provide filter functionality (incl. all allowed lookups e.g. in, gt, lt, ...) for annotated fields in my api. My Code looks as following: import rest_framework_filters as filters from django_filters.rest_framework import DjangoFilterBackend from rest_framework.viewsets import ModelViewSet class MyViewSet(ModelViewSet): class MyFilterSet(filters.FilterSet): """ internal FilterSet """ min_value = filters.AllLookupsFilter() class Meta: model = MyModel fields = { 'id': '__all__', 'name': '__all__', 'type': '__all__', 'managed_by': '__all__', 'created_by': '__all__', } filter_backends = (DjangoFilterBackend,) filter_class = MyFilterSet def get_queryset(self): return super().get_queryset().annotate(min_value=Min('field')).order_by('id') When i try to start my app the following exception occurs: TypeError: 'Meta.fields' contains fields that are not defined on this FilterSet: min_value Any idea whats wrong with my code? I found out that my "djangorestframework-filters" module was outdated. I made the update to the recent version (0.10.2) and now the error changed to: File "C:\Dev\Python\Python36\lib\site-packages\rest_framework_filters\filterset.py", line 44, in __new__ opts.fields = {f.name: f.lookups or []} AttributeError: 'AllLookupsFilter' object has no attribute 'name' I already updated all dependent modules. Any ideas whats the problem here?
type: Question
tagged with: django-filter
upvote count: 1
answer count: 1
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/90083830
favorite count: 0
has answer: http://stackoverflow.com/a/51558887
type: UnansweredQuestion

http://stackoverflow.com/q/51480423
type: Question
has answer: http://stackoverflow.com/a/51482556
tagged with: byte-order-mark
tagged with: text-processing
has body: Note: The possible duplicate concerns an older version of Python and this question has already generated unique answers. I have been working on a script to process Project Gutenberg Texts texts into an internal file format for an application I am developing. In the script I process chapter headings with the re module. This works very well except in one case: the first line. My regex will always fail on the first Chapter marker at the first line if it includes the ^ caret to require the regex match to be at the beginning of the line because the BOM is consumed as the first character. (Example regex: ^Chapter). What I've discovered is that if I do not include the caret, it won't fail on the first line, and then <feff> is included in the heading after I've processed it. An example: <feff>Chapter I The advice according to this SO question (from which I learned of the BOM) is to fix your script to not consume/corrupt the BOM. Other SO questions talk about decoding the file with a codec but discuss errors I never encounter and do not discuss the syntax for opening a file with the template decoder. To be clear: I generally use pipelines of the following format: cat -s <filename> | <other scripts> | python <scriptname> [options] > <outfile> And I am opening the file with the following syntax: import sys fin = sys.stdin if '-i' in sys.argv: # For command line option "-i <infile>" fin = open(sys.argv[sys.argv.index('-i') + 1], 'rt') for line in fin: ...Processing here... My question is what is the proper way to handle this? Do I remove the BOM before processing the text? If so, how? Or do I use a decoder on the file before processing it (I am reading from stdin, so how would I accomplish this?) The files are stored in UTF-8 encoding with DOS endings (\r\n). I convert them in vim to UNIX file format before processing using set ff=unix (I have to do several manual pre-processing tasks before running the script).
has comment: http://stackoverflow.com/comment/89930050
possible better answer: http://stackoverflow.com/a/51482556
has comment: http://stackoverflow.com/comment/89933938
has answer: http://stackoverflow.com/a/70421149
has title: How am I suppposed to handle the BOM while text processing using sys.stdin in Python 3?
has comment: http://stackoverflow.com/comment/89934431
has comment: http://stackoverflow.com/comment/89933917
linked to: http://stackoverflow.com/q/8898294
accepted answer: http://stackoverflow.com/a/51483180
score: 3
downvote count: 0
has answer: http://stackoverflow.com/a/51492057
favorite count: 0
linked to: http://stackoverflow.com/q/45240387
tagged with: python
tagged with: utf-8
has comment: http://stackoverflow.com/comment/89933578
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89933703
linked to: http://stackoverflow.com/q/1972362
upvote count: 3
has comment: http://stackoverflow.com/comment/89933222
has comment: http://stackoverflow.com/comment/89934283
has comment: http://stackoverflow.com/comment/89933843
has answer: http://stackoverflow.com/a/51483180
linked to: http://stackoverflow.com/q/2456380
has comment: http://stackoverflow.com/comment/89934167

http://stackoverflow.com/comment/89917317
type: Comment
comment on: http://stackoverflow.com/a/51474340
type: AnswerComment
has text: How about setter? Can you also provide?
score: 0

http://stackoverflow.com/a/51392143
has body: It doesn't seem like your roll_dice() function returns anything, causing the TypeError. The reason it "seems" like the program loops once is because of the line right before the for loop, which calls the function. What it seems like you are trying to do is extract the type variable from inside your function, which can be done by returning the type with return type instead of just return and using the if statement alone. To loop until type isn't a or i, a while loop may be more useful, like so: while True: type = roll_dice() if type != 'a' and type != 'i': break
downvote count: 0
answers question: http://stackoverflow.com/q/51392058
score: 1
upvote count: 1
type: Answer

http://stackoverflow.com/comment/89805523
type: QuestionComment
has text: File "<stdin>", line 1 C:\Python34\edX\function\M1_RCA.py ^ SyntaxError: unexpected character after line continuation character //// it's all of error message
score: 0
comment on: http://stackoverflow.com/q/51415740
type: Comment

http://stackoverflow.com/comment/89769659
type: AnswerComment
score: 0
type: Comment
has text: Excellent. It worked. I have worked it on a V(9 lists ,1000 values) and I (1000 values). It just worked and rightly identified the maximum value and index number. If you don't mind. I have one more last question. That is, how to plot V (9 lists, 1000 values) and I (1000 values) on one figure. So, finally, I end up having nine plots in same xy figure. Please, help me.
comment on: http://stackoverflow.com/a/51398371

http://stackoverflow.com/q/51392238
tagged with: python
has body: The python time module offers five clocks: time, monotonic, perf_counter, process_time, and thread_time (and the deprecated clock). What these clocks do is well explained in the documentation. You can get system-depended information about these clocks with the time.get_clock_info(&lt;clock_name&gt;) function. This in particular returns the resolution of this clock, which is in my understanding the minimal difference between to consecutive calls to that clock, that is not zero. To test this, I created the following code: import time names = ['time', 'monotonic', 'perf_counter', 'process_time', 'thread_time'] for n in names: info = time.get_clock_info(n) f = getattr(time, n) print(n, info) l = [] for _ in range(1000000): l.append(f()) deltas = [l[i] - l[i - 1] for i in range(1, len(l)) if l[i] - l[i - 1] != 0] print(min(deltas, default=0)) This code prints the following for me: time 0.015625 0.00650477409362793 monotonic 0.015625 0.015000000013969839 perf_counter 3.77580764525532e-07 3.7699999988483057e-07 process_time 1e-07 0.015625 thread_time 1e-07 0.015625 This is quiet surprising, because the actual minimal delta of time is 2.4x smaller than promised and the actual minimal delta of process_time and thread_time are both 150.000 times bigger than promised. Why is that? Is that implementation depending and python doesn't know the actual resolution? If it is that way, why does it pretend to know? Or am I misunderstanding something? System Information: Windows 10 64bit Python3.7 64bit
has answer: http://stackoverflow.com/a/51392436
score: 4
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89756537
tagged with: time
has comment: http://stackoverflow.com/comment/89756444
answer count: 1
has title: Meaning of time.get_clock_info().resolution
accepted answer: http://stackoverflow.com/a/51392436
upvote count: 4
type: AnsweredQuestion
downvote count: 0
favorite count: 0
tagged with: python-3.7
type: Question

http://stackoverflow.com/q/51420925
has answer: http://stackoverflow.com/a/51423729
answer count: 1
downvote count: 0
score: 1
favorite count: 0
tagged with: python
has title: How to create a Dynamic Sequence based on another field?
accepted answer: http://stackoverflow.com/a/51423729
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
has body: I want to create a dynamic sequence for products based on the field category_id. I've added a category_code in product.category. But once I call it inside the create function, it returns False: class ProductProduct(models.Model): _inherit = 'product.product' @api.model def create(self, vals): if 'default_code' not in vals or vals['default_code'] == '/': sequence = self.env.ref('product_sequence.seq_product_auto') record=super(ProductProduct, self).create(vals) print self.categ_id.category_code vals['default_code'] =self.categ_id.category_code + sequence.next_by_id() return record
upvote count: 1
type: Question
tagged with: odoo

http://stackoverflow.com/a/51473608
answers question: http://stackoverflow.com/q/51473387
type: Answer
score: 1
upvote count: 1
has body: Your array is currently "not really 2D", in that ['kim' '0'] will be evaluated to ['kim0'] (to check this, access myList[0]). Also, you initialize your numbers as strings ('0' instead of simply 0). If you do the initialization correctly, you'd get something like this: myList = np.array([['kim', 0], ['jong', 0], ['un', 0], ['is', 0], ['here', 1]]) Then your operation is already (almost correct). Now simply look at the column that contains the words for your where condition: selector = np.where(myList[:,0] == "is") # look for the word only in the first column And then finally change the value: myList[selector, 1] = 1 # access the "value column" Should you want to increase the value, simply do +=1 instead of = 1, or you could even stick to your string-formatted values (care with the initialization, though; you still need the commas), and then assign '1' instead.
downvote count: 0

http://stackoverflow.com/q/51479444
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/51479495
has body: I have two Python scripts which produces a GUI and runs code off some of the buttons. When run from Python, I run mainImpactTool.py which then runs impactTool.py to produce the GUI. mainImpactTool.py impactTool.py I followed the guidance here: https://pythonhosted.org/PyInstaller/usage.html#what-to-bundle-where-to-search So I could create a single executable for running on Windows. If I had one script I would normally run: Pyinstaller --onefile mainImpactTool.py However, to use two scripts, I did this: Pyinstaller --onefile mainImpactTool.py impactTool.py Pyinstaller works, but when I run the .exe file I get the error: ImportError ... Failed to execute script mainImpactTool Any suggestions on what I am doing wrong? Thank you
answer count: 1
has title: Pyinstaller - multiple python scripts
score: 4
downvote count: 0
accepted answer: http://stackoverflow.com/a/51479495
favorite count: 0
tagged with: pyinstaller
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/94028611

http://stackoverflow.com/a/51468633
answers question: http://stackoverflow.com/q/51468615
type: Answer
upvote count: 4
score: 3
has comment: http://stackoverflow.com/comment/89905730
has body: Can be done by list comprehension, like so - [i for i in my_list if len(set(i)) == len(i)] What we are doing here is we are checking how many unique elements are the in a list of list, by using set(i), if after set, it still contains 3 elements, that means all the elements are unique and we need that list. If we look at the code and the list - my_list = [[5,5,5],[5,10,5],[5,10,15],[5,10,10],[5,10,20]] # [i for i in my_list] will get us [5,5,5], [5,10,5] ... # applying set(i) on, for example first i will give us set([5]) # and len(set([5])) is not equal to len(i) # therefore O/P will be O/P = [i for i in my_list if len(set(i)) == len(i)] #[[5, 10, 15], [5, 10, 20]]
downvote count: 1

http://stackoverflow.com/comment/89878105
has text: But whe we try this, generates some errors in the code!
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51454026

http://stackoverflow.com/comment/89698462
comment on: http://stackoverflow.com/q/51363043
has text: (Also, I remember the exact same question from some time ago, but can't find it now... not easy to search for this kind of question)
score: 0
type: QuestionComment
type: Comment

split
tags question: http://stackoverflow.com/q/51456204
tags question: http://stackoverflow.com/q/51352883
tag name: split
tags question: http://stackoverflow.com/q/51455196
tags question: http://stackoverflow.com/q/51468317
tags question: http://stackoverflow.com/q/51458202
tags question: http://stackoverflow.com/q/51331274
tags question: http://stackoverflow.com/q/51329118
tags question: http://stackoverflow.com/q/51470805
tags question: http://stackoverflow.com/q/51343919
tags question: http://stackoverflow.com/q/51417020
tags question: http://stackoverflow.com/q/51410798
tags question: http://stackoverflow.com/q/51414133
tags question: http://stackoverflow.com/q/51452208
tags question: http://stackoverflow.com/q/51476964
tags question: http://stackoverflow.com/q/51332316
type: Tag
tags question: http://stackoverflow.com/q/51455199
tags question: http://stackoverflow.com/q/51451892

http://stackoverflow.com/comment/89896219
type: Comment
type: QuestionComment
score: 1
has text: I think you haven't set `is_staff = True` is making problem, I have posted a answer give a try to it
comment on: http://stackoverflow.com/q/51462947

http://stackoverflow.com/comment/89877032
score: 0
type: AnswerComment
has text: Moreover you can try something like this also : `driver.find_element_by_xpath("//*[@id='make-this-my-store'][1]").click()`
type: Comment
comment on: http://stackoverflow.com/a/51427209

http://stackoverflow.com/a/51366507
upvote count: 3
has body: You can use a dictionary comprehension with groupby: res = {k: v.drop('country', 1) for k, v in df.groupby('country')} print(res) {'ES': amount city revenue 0 8 Barcelona 1 1 7 Madrid 2, 'FR': amount city revenue 7 1 Paris 8, 'IT': amount city revenue 2 6 Rome 3 3 5 Torino 4, 'UK': amount city revenue 4 4 London 5 5 3 Liverpool 6 6 2 Manchester 7}
accepted answer of: http://stackoverflow.com/q/51366343
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51366343
downvote count: 0
score: 3
type: Answer

http://stackoverflow.com/a/51458327
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89886114
has body: strip() is easiest method in this case, but if you want to do any advanced text processing in the future, it isn't bad idea to learn regular expressions: import re from pprint import pprint l = [['\n1\nWie was de Nederlandse scheepvaarder die de Spaanse zilvervloot veroverde?\n', '\nA. Michiel de Ruyter\nB. Piet Heijn\nC. De zilvervloot is nooit door de Nederlandersonderschept\n', '\nB\n', '\nAntwoord B De Nederlandse vlootvoogd werd hierdoor bekend.\n'], ['\n2\nIn welk land ligt Upernavik?\n', '\nA. Antartica\nB. Canada\nC. Rusland\nD.Groenland\nE. Amerika\n', '\nD\n', '\nAntwoord D Het is een dorp in Groenland met 1224inwoners.\n']] l = [[re.sub(r'^([\s]*)|([\s]*)$', '', j)] for i in l for j in i] pprint(l, width=120) Output: [['1\nWie was de Nederlandse scheepvaarder die de Spaanse zilvervloot veroverde?'], ['A. Michiel de Ruyter\nB. Piet Heijn\nC. De zilvervloot is nooit door de Nederlandersonderschept'], ['B'], ['Antwoord B De Nederlandse vlootvoogd werd hierdoor bekend.'], ['2\nIn welk land ligt Upernavik?'], ['A. Antartica\nB. Canada\nC. Rusland\nD.Groenland\nE. Amerika'], ['D'], ['Antwoord D Het is een dorp in Groenland met 1224inwoners.']]
downvote count: 0
has comment: http://stackoverflow.com/comment/89886078
type: Answer
answers question: http://stackoverflow.com/q/51458202

http://stackoverflow.com/q/51477186
has comment: http://stackoverflow.com/comment/89930635
has title: Dataframe transformation of a excel file representing a tree view scheme in Pandas
tagged with: dataframe
type: Question
has body: I have an excel file representing a tree view : df = pd.DataFrame({"id": [921,922,923,9211,9212,9213,9221,55,56,9231,9232], "broader": [920,920,920,921,921,9211,922,9221,9221,923,923], "narrower": [[922, 923],[921, 923],[921, 922],[9212],[9211],[0],[0],[56],[55],[9232],[9231]], "related": [[9211, 9212],[9221],[0],[9213],[0],[0],[55, 56],[0],[0],[0],[0]] }) where the "id"'s are the nodes, "broader" the parent, "narrower" the nodes on the same level and "related" the children. I would like to make an excel sheet where each line is a tree branch in order to know how many entries i have got depending on the level, i.e.: df = pd.DataFrame({"base": [920,920,'...'], "level 1": [921,921,'...'], "level2": [9211,9212,'...'], "level3": [9213,0,'...'] }) Does anyone have an idea about the way to do it?
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/89922973
has comment: http://stackoverflow.com/comment/89923229
has comment: http://stackoverflow.com/comment/89922752
answer count: 0
type: UnansweredQuestion
tagged with: treeview
has comment: http://stackoverflow.com/comment/89954729
tagged with: python
has comment: http://stackoverflow.com/comment/89955209

http://stackoverflow.com/comment/89930568
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51480869
has text: what should `from A import x` do?

http://stackoverflow.com/comment/89827608
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51426647
has text: The more information you can give about the environment you run this in ("my machine") the higher the chances, someone can help here.
score: 0

http://stackoverflow.com/comment/89841744
has text: haha, beat you by 2 seconds @AndrasDeak ;)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51435816

css
tags question: http://stackoverflow.com/q/51465035
tags question: http://stackoverflow.com/q/51376820
tags question: http://stackoverflow.com/q/51470308
tags question: http://stackoverflow.com/q/51395008
tags question: http://stackoverflow.com/q/51347871
type: Tag
tags question: http://stackoverflow.com/q/51345112
tags question: http://stackoverflow.com/q/51333107
tags question: http://stackoverflow.com/q/51327859
tag name: css
tags question: http://stackoverflow.com/q/51460002
tags question: http://stackoverflow.com/q/51383352
tags question: http://stackoverflow.com/q/51442769

http://stackoverflow.com/comment/89679320
score: 0
comment on: http://stackoverflow.com/q/51353201
type: QuestionComment
type: Comment
has text: I changed my indents but there is still nothing being printed.

http://stackoverflow.com/comment/89763476
type: QuestionComment
has text: Do you mean a console-like behaviour of your tkinter application? If so, you can redirect inputs/outputs to/from `stdin`/`stdout` streams.
score: 0
comment on: http://stackoverflow.com/q/51394482
type: Comment

http://stackoverflow.com/comment/89780474
comment on: http://stackoverflow.com/q/51404539
score: 0
type: Comment
type: QuestionComment
has text: do you know the number or is there only one `exampleN` directory?

date
tags question: http://stackoverflow.com/q/51404436
tags question: http://stackoverflow.com/q/51457944
tag name: date
tags question: http://stackoverflow.com/q/51384426
tags question: http://stackoverflow.com/q/51476762
tags question: http://stackoverflow.com/q/51442158
tags question: http://stackoverflow.com/q/51343638
tags question: http://stackoverflow.com/q/51337695
tags question: http://stackoverflow.com/q/51387255
type: Tag
tags question: http://stackoverflow.com/q/51458798
tags question: http://stackoverflow.com/q/51474924
tags question: http://stackoverflow.com/q/51331775
tags question: http://stackoverflow.com/q/51465148
tags question: http://stackoverflow.com/q/51470668
tags question: http://stackoverflow.com/q/51345286

http://stackoverflow.com/comment/89703546
has text: The version of Python 2.7 that Apple pre-installs doesn’t quite follow the recommendations for distros. It includes the optional `python2.7` alias, but doesn’t include the required `python2` alias. So, either you make your own symlink or bash alias or whatever, or you use `python2.7` to run it.
score: 0
comment on: http://stackoverflow.com/q/51365270
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89692423
type: QuestionComment
comment on: http://stackoverflow.com/q/51360098
score: 3
has text: See https://stackoverflow.com/questions/22468401/can-you-set-a-dictionary-value-dependant-on-another-dictionary-entry for a similar problem.
type: Comment

http://stackoverflow.com/q/51443807
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51444262
score: 1
type: Question
has title: How can I fix "UnicodeDecodeError: 'utf-8' codec can't decode bytes..." in python?
accepted answer: http://stackoverflow.com/a/51444256
possible better answer: http://stackoverflow.com/a/51444262
answer count: 2
has answer: http://stackoverflow.com/a/51444256
upvote count: 1
has body: I need to read specified rows and columns of csv file and write into txt file.But I got an unicode decode error. import csv with open('output.csv', 'r', encoding='utf-8') as f: reader = csv.reader(f) your_list = list(reader) print(your_list)
downvote count: 0
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/a/51370746
answers question: http://stackoverflow.com/q/51370602
has comment: http://stackoverflow.com/comment/89713723
has comment: http://stackoverflow.com/comment/89713715
has comment: http://stackoverflow.com/comment/89713833
has comment: http://stackoverflow.com/comment/89713887
has body: Python 3.3+'s str is quite a complicated structure, and can end up storing the underlying data in up to three different ways, depending on which APIs have been used with the string and the code points represented by the string. The most common alternate representation case is a cached UTF-8 representation, but that only applies to non-ASCII strings so it doesn't apply here. In this case, I suspect the single character string (which, as an implementation detail, is a singleton) was used in a way that triggered the creation of the legacy wchar_t* representation (extensions using the legacy Py_UNICODE APIs can cause this), and your Python build uses a four byte wchar_t, leading to the string being eight bytes bigger than it otherwise would be (four for the a itself, four more for the NUL terminator). The fact that it's a singleton means that even though you may never have triggered such a legacy API call, any extension which retrieved a reference to the singleton would affect the observed size for everyone by using it with the legacy API. Personally, I don't reproduce at all on my Linux 3.6.5 install (the sizes increase smoothly), indicating no wchar_t representation was created, and on my Windows 3.6.3 install, 'a' is only 54 bytes, not 58 (which matched Windows' native two byte wchar_t). In both cases I'm running with ipython; it's possible different ipython dependencies with different versions are responsible for your (and my) inconsistent observations. To be clear, this extra cost is fairly immaterial; since the single character string is a singleton, the incremental cost of use is really just 4-8 bytes (depending on pointer width). You're not going to break the bank on memory if a handful of strings ended up used with the legacy APIs.
has comment: http://stackoverflow.com/comment/89713972
has comment: http://stackoverflow.com/comment/89715551
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/89713934
has comment: http://stackoverflow.com/comment/89713700
upvote count: 4
has comment: http://stackoverflow.com/comment/89713788
has comment: http://stackoverflow.com/comment/89713741
score: 4

http://stackoverflow.com/q/51421122
answer count: 1
accepted answer: http://stackoverflow.com/a/51421247
has title: Scrapy Spider following urls, but wont export the data
tagged with: python
type: AnsweredQuestion
has body: I am trying to grab details from a real estate listing page. I can grab all the data, I just can't seem to export it.. Perhaps a problem with the way I use the yield keyword. The code work for the most part: Visits page 1, example.com/kittens Goes to page 2, example.com/puppers. Here are 10 apartments listed in blocks. I can get data from each block, but I need additional info from inside the hyperlink. Visits the hyperlink, say, example.com/puppers/apartment1. It grabs some info from here as well, but I can't seem to return this data to include it in my HousingItem() class. import scrapy from urllib.parse import urljoin class HousingItem(scrapy.Item): street = scrapy.Field() postal = scrapy.Field() city = scrapy.Field() url = scrapy.Field() buildY = scrapy.Field() on_m = scrapy.Field() off_m = scrapy.Field() class FAppSpider(scrapy.Spider): name = 'f_app' allowed_domains = ['example.com'] start_urls = ['https://www.example.com/kittens'] def parse(self, response): yield scrapy.Request(url="https://www.example.com/puppers", callback=self.parse_puppers) def parse_inside_pupper(self, response): item = HousingItem() item['buildY'] = response.xpath('').extract_first().strip() item['on_m'] = response.xpath('').extract_first().strip() item['off_m'] = response.xpath('').extract_first().strip() def parse_puppers(self, response): base_url = 'https://www.example.com/' for block in response.css('div.search-result-main'): item = HousingItem() item['street'] = block.css(''), item['postcode'] = block.css(''), item['city'] = block.css('') item['url'] = urljoin(base_url, block.css('div.search-result-header &gt; a::attr(href)')[0].extract()) # Problem area from here.. yield response.follow(url=item['url'],callback=self.parse_inside_pupper) # yield scrapy.request(url=item['url'],callback=self.parse_inside_pupper)? yield item FEED_EXPORT_FIELDS is adjusted in my SETTINGS.py. The 4 items from parse_puppers() get exported correctly, parse_inside_puppers() data is correct in the console, …
tagged with: web-scraping
tagged with: scrapy
type: Question
has answer: http://stackoverflow.com/a/51421247
score: 0

http://stackoverflow.com/comment/89724537
comment on: http://stackoverflow.com/q/51357265
has text: LSMulator is my own code ,the code link https://github.com/asross/cs265/blob/master/simulations/lsmulator.py
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51452090
has answer: http://stackoverflow.com/a/51484314
tagged with: elasticsearch-query
type: AnsweredQuestion
tagged with: elasticsearch-dsl-py
type: Question
tagged with: elasticsearch-dsl
has answer: http://stackoverflow.com/a/51457311
score: 0
answer count: 2
has body: I have a list whose size is not fixed and can contain any no. of items. Based on the number of items in the list, I have to generate an elastic search AND query to find the exact match of values. For eg: If my list contains 2 items : ['a', 'b'], my elastic search query should look like this : Q('term', field='a') &amp; Q('term', field='b') Similary, if my list contains 4 items : ['a', 'b','c','d'] ;my query will look like this : Q('term', field='a') &amp; Q('term', field='b') &amp; Q('term', field='c') &amp; Q('term', field='d') What's the right approach to generate this kind of query based upon list size? PS : I am using elasticsearch_dsl module's Q library to generate elastic search queries. https://elasticsearch-dsl.readthedocs.io/en/latest/search_dsl.html
has title: Generate elastic search AND query based upon list size i.e no. of AND's in the query will be based on no. of items in the list
possible better answer: http://stackoverflow.com/a/51484314
tagged with: elasticsearch
accepted answer: http://stackoverflow.com/a/51457311
tagged with: python

database
tags question: http://stackoverflow.com/q/51433569
tags question: http://stackoverflow.com/q/51445481
tags question: http://stackoverflow.com/q/51340840
type: Tag
tags question: http://stackoverflow.com/q/51460873
tags question: http://stackoverflow.com/q/51361250
tags question: http://stackoverflow.com/q/51358289
tags question: http://stackoverflow.com/q/51400332
tags question: http://stackoverflow.com/q/51403364
tags question: http://stackoverflow.com/q/51401288
tags question: http://stackoverflow.com/q/51377970
tags question: http://stackoverflow.com/q/51373900
tags question: http://stackoverflow.com/q/51402221
tags question: http://stackoverflow.com/q/51335298
tags question: http://stackoverflow.com/q/51388592
tags question: http://stackoverflow.com/q/51408463
tag name: database
tags question: http://stackoverflow.com/q/51416693
tags question: http://stackoverflow.com/q/51466265
tags question: http://stackoverflow.com/q/51418952
tags question: http://stackoverflow.com/q/51430390
tags question: http://stackoverflow.com/q/51412969
tags question: http://stackoverflow.com/q/51396787
tags question: http://stackoverflow.com/q/51426289
tags question: http://stackoverflow.com/q/51373404
tags question: http://stackoverflow.com/q/51376210

http://stackoverflow.com/a/51351733
accepted answer of: http://stackoverflow.com/q/51351653
type: Answer
answers question: http://stackoverflow.com/q/51351653
score: 1
has comment: http://stackoverflow.com/comment/89676586
upvote count: 1
has comment: http://stackoverflow.com/comment/89676197
has body: Actually, while the assignments for t and g are indeed creating new instances, you are passing the same instance of the original wrapped function, spam. After being decorated, spam is no longer a function, instead it is an instance of tracer. That is how Python is design to handle the wrapping of class around an object: the object's name becomes an instance of the wrapping object. Anytime tracer(spam) is created, the attribute func in tracer is an instance of the original wrapped function spam. Thus, when calling the wrapped value, self.func(*args) is called in tracer.__call__, triggering func.__call__, which increments calls. The instances of tracer, t and g, are all being passed the same instance of tracer, spam, which is being assigned to the attribute func. Thus, t.func and g.func are all instances and thus reference spam, and all of its attributes. Therefore, when you call t.func and g.func, you are triggering spam.__call__, thus incrementing calls in spam: class tracer: def __init__(self, _func): self.func = _func self.calls = 0 def __repr__(self): return f"{self.__class__.__name__}(storing {self.func.__name__})" def __call__(self, *args): self.calls += 1 print(f"__call__ executed in {repr(self)}") return self.func(*args) @tracer def spam(a,b,c): print (a+b+c) &gt;&gt;&gt;spam(1, 2, 3) __call__ executed in tracer(storing spam) t= tracer(spam) &gt;&gt;&gt;t.func(1, 2, 3) __call__ executed in tracer(storing spam) g=tracer(spam) &gt;&gt;&gt;g.func(1, 2, 3) __call__ executed in tracer(storing spam)
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89644364
has text: @Richard wait 2 hours is a short time to think that nobody will respond, on the other hand publish an answer is always good, but it is also better to point out the limitations so the one who wants to use your solution will know what can fail. If my answer helps you, do not forget to mark it as correct :)
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51334495
score: 1

http://stackoverflow.com/q/51450366
accepted answer: http://stackoverflow.com/a/51451373
tagged with: pandas
has body: I am reading a .csv file from amazon s3 bucket by using pandas 'read_csv'. Below is the statement which I issued: xyz = pd.read_csv(io.BytesIO(obj['Body'].read()), dtype={'col1': str ,'col2':int,'col3':int ,'col4':int} ,encoding='latin-1') Now herein lies my problem; col2 contains some special characters such as " `" and col3 contains " : ". So is there a way in python wherein I can redirect these bad rows in a temp list by scanning all records from the .csv file on S3 bucket? I want to keep a log of bad data and insert the corrected one's only. I would really appreciate the help.
tagged with: python
has title: Python pandas read_csv issue with bad data when dtype is specified
has answer: http://stackoverflow.com/a/51451373
type: AnsweredQuestion
tagged with: amazon-s3
score: 0
type: Question
answer count: 1

http://stackoverflow.com/comment/89627712
type: QuestionComment
has text: yes, use range(begin, end) where end is not included. Thus `range(-k, k+1)` if you want all integers from -k to k included
score: 1
comment on: http://stackoverflow.com/q/51325979
type: Comment

http://stackoverflow.com/q/51414491
has answer: http://stackoverflow.com/a/51414912
has comment: http://stackoverflow.com/comment/89800636
tagged with: oauth-2.0
type: Question
has comment: http://stackoverflow.com/comment/89800376
answer count: 2
tagged with: flask
has comment: http://stackoverflow.com/comment/89835364
possible better answer: http://stackoverflow.com/a/51414893
downvote count: 0
has comment: http://stackoverflow.com/comment/89800246
favorite count: 0
has title: How to access parameters in a redirect URI in Flask?
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89800493
upvote count: 2
accepted answer: http://stackoverflow.com/a/51414912
tagged with: python
has body: I'm working in Flask on creating a JMML ("Join my mailing list") widget that submits data to an email marketing platform, and the platform follows an OAuth2 flow. The basic flow is: I create access URL using a the base API URL, an API key, and a redirect URI The program accesses this URL, and the user of the program is redirected to the marketing platform to log in and grant access. The marketing platform performs another redirect back to the redirect URI that I provided. The URI is appended with the access token that I need to provide with app POST requests of my JMML. Here's an example of what the returned URI looks like: http://localhost:5000/redirect_url#access_token=2C1zxo3O0J1yo5Odolypuo9DSmcI Here's the problem I'm having: I have no idea how, programmatically, to use that final redirect url/uri as a variable in Python.I could make the user copy/paste it into a field, but there's gotta be a better way. I honestly don't even know the terminology for a redirected-redirect like this. It's pathetic, and I'm lost, but here's what I have so far: @app.route('/redirect_url') def redirect_url(): # I have no idea how to actaully get the parameter out of the redirect url. pass I've checked the API documentation for the email marketing company's API, but they only provide code tips for handling Oauth2 in Ruby and PHP. Help!
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/11774265
has comment: http://stackoverflow.com/comment/89800893
has answer: http://stackoverflow.com/a/51414893

http://stackoverflow.com/q/51402714
score: 0
has comment: http://stackoverflow.com/comment/89776912
type: Question
has comment: http://stackoverflow.com/comment/89778566
has comment: http://stackoverflow.com/comment/89778117
tagged with: pandas
has comment: http://stackoverflow.com/comment/89777259
has title: Python error - bound method Series.map of
type: UnansweredQuestion
tagged with: python
has body: I have two Dataframes that store some employee details as below: DF1 has employee's personal details whereas DF2 store which team they belong to. DF1: emp_id,name 1,Tom 2,Scott DF2: emp_id,team_name 1,Finance 2,IT I am trying to merge both these Dataframes using the below function by adding a new column called 'team_name' in DF1: DF1['team_name'] = DF1['emp_id'].map(DF2.set_index('emp_id')['team_name']) I however get the below error on executing the above code. &lt;bound method Series.map of 0 ... this has all emp_ids listed Could anyone help me figure how to overcome this error. Thanks Update: This is the complete sequence that I am doing: DF2_updated = DF2.reset_index() DF1['team_name'] = DF1['emp_id'].map(DF2.set_index('emp_id')['team_name']) Final_DF = DF1[DF1['emp_id'].notnull() == True].reset_index(drop=True) This throws this message and I am not sure how to get past this.
has comment: http://stackoverflow.com/comment/89777749
answer count: 0

http://stackoverflow.com/q/51393710
type: Question
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/93217991
has comment: http://stackoverflow.com/comment/93035198
has title: How to install mayavi on google Colab?
tagged with: google-colaboratory
linked to: http://stackoverflow.com/q/15383666
has body: I tried installing mayavi on Colab using pip: !pip install mayavi This threw the following error: Running setup.py bdist_wheel for mayavi ... error The rest of the error output is available at the Colab document. Solution: Work in Progress Following the response from @Bob-Smith, I found that his solution needed a slight change for installing the dependencies: !apt-get install vtk6 !apt-get install libvtk6-dev python-vtk6 Problems Faced and Workaround Found (PFWF) PFWF-001 !apt-get install python-vtk throws the following error: Package 'python-vtk' has no installation candidate I found a command-reference for this: !apt-get install libvtk5-dev python-vtk However, this command also did not work. The package name had changed from libvtk5-dev to libvtk6-dev and the python binding for VTK has changed from python-vtk to python-vtk6. Clearly this kind of change will continue to happen in future and you may need to check the package name and the python binding for VTK before running the following statement: !apt-get install libvtk6-dev python-vtk6 Note: If you are here looking to solve VTK installation problems for python and this does not solve that you may want to look here: installing-vtk-for-python Installing mayavi still throws error: Although the two steps above install the dependencies, the last line: !pip install mayavi spits out the following error: Could not connect to any X display. The latest progress on Mayavi installation can be found here. https://colab.research.google.com/drive/1K_VIP9izNLKalD_IgBSiTowyNkU7aWcW
tagged with: mayavi
favorite count: 0
tagged with: vtk
downvote count: 0
has answer: http://stackoverflow.com/a/62325781
has comment: http://stackoverflow.com/comment/93218221
type: UnansweredQuestion
tagged with: pip
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/51435316

hocr
type: Tag
tags question: http://stackoverflow.com/q/51421283
tag name: hocr

http://stackoverflow.com/q/51349254
has comment: http://stackoverflow.com/comment/89671383
score: 0
has title: Matplotlib: Cyclic Contour Plot
tagged with: matplotlib
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89677446
has comment: http://stackoverflow.com/comment/89724787
tagged with: contour
answer count: 0
linked to: http://stackoverflow.com/q/51188648
has body: I already asked a question here: Contour plot on the surface of a 3D cylinder But I didn't get an answer so I am trying another approach. I would like to plot a contour plot with data across the radius. I think I almost did it but there is one problem. First my code and how the plot looks like now: Contour Plot import numpy as np import matplotlib.pyplot as plt xlist = np.linspace(-40, 40) ylist = np.linspace(-40, 40) X, Y = np.meshgrid(xlist, ylist) Z = np.sqrt(X ** 2 + Y ** 2 ) plt.figure() #These are my values for a certain radius levels = [15, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 34, 36, 37] contour = plt.contourf(X, Y, Z, levels) contour_filled = plt.contourf(X, Y, Z, levels) plt.colorbar(contour_filled) plt.show() My problem is the radius. I would like to visualize a certain value (e.g. 15) on the radius of 150 as a certain color (e.g. blue).In my plot the value 15 represents the radius 15. I hope you guys know what I mean... Maybe the function contour is the wrong approach?? But is there a possibility to get a similar plot (with all the nice filled colors) with another function? Best regards
type: Question
has comment: http://stackoverflow.com/comment/89674115
tagged with: python

http://stackoverflow.com/q/51431517
has comment: http://stackoverflow.com/comment/89834732
tagged with: python-3.x
has body: Views.py def time_consuming_task_caller(time_to_sleep, j): print ('start', task_id) # time.sleep(time_to_sleep) # print('finished', task_id) def time_consuming_task_caller(time_to_sleep, j): Process(target=time_consuming_task, args=(time_to_sleep, task_id)).start() print ('processing...', task_id) return {'one': 'two'} def get_task(request): if request.method == 'GET': response = time_consuming_task_caller(5,1) # 5 is like time to sleep, 1 is task id. print(response) return HttpResponse(json.dumps(response), content_type="application/json") This causes error at return HttpResponse(json.dumps(response), content_type="application/json") because it prints all three print statements (except the commented one) Even with time.sleep() commented it causes the error. Ultimate goal is to make it work for processes that may take longer to execute. EDIT urls.py urlpatterns = [ path('api/', get_task ,name='run') ] Error Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "c:\users\user\appdata\local\programs\python\python36\Lib\multiprocessing\spawn.py", line 105, in spawn_main exitcode = _main(fd) File "c:\users\user\appdata\local\programs\python\python36\Lib\multiprocessing\spawn.py", line 115, in _main self = reduction.pickle.load(from_parent) File "D:\Programming\django_project\webapp - Dev\server 3\manager\utils.py", line 1, in &lt;module&gt; from .models import Task File "D:\Programming\django_project\webapp - Dev\server 3\manager\models.py", line 2, in &lt;module&gt; from accounts.models import CustomUser File "D:\Programming\django_project\webapp - Dev\server 3\accounts\models.py", line 2, in &lt;module&gt; from django.contrib.auth.models import AbstractUser File "D:\Programming\django_project\env_django\lib\site-packages\django\contrib\auth\models.py", line 2, in &lt;module&gt; from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "D:\Programming\django_project\env_django\lib\site-packages\django\contrib\au…
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/51432644
has comment: http://stackoverflow.com/comment/89834333
has comment: http://stackoverflow.com/comment/89834999
has comment: http://stackoverflow.com/comment/89834611
tagged with: python-multiprocessing
tagged with: multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/89834267
answer count: 1
has title: multiprocessing.Process.start() raises exception django.core.exceptions.AppRegistryNotReady
score: 0
has comment: http://stackoverflow.com/comment/89835053

http://stackoverflow.com/q/51475555
answer count: 1
type: UnansweredQuestion
has title: How to extract text from merged pdf files?
has body: I wrote some code to merge a bunch of pdf files that were located in a directory and extract text, however, the code doesn't work. #Merge all pdf files in the parent directory. merger = PyPDF2.PdfFileMerger() for file in [a for a in os.listdir() if a.endswith(".pdf")]: merger.append(open(file, 'rb')) #Now extract text from the merged object. pdf_reader = PyPDF2.PdfFileReader(merger) for page in pdf_reader.pages: #For each page, get corpus of text. for line in page.extractText().splitlines(): corpus += line The following error occurs AttributeError: 'PdfFileMerger' object has no attribute 'seek' I do not wish to output the merged file and then process it - that would be slow and error-prone. How do I use the merged object directly into PdfFileReader?
type: Question
has answer: http://stackoverflow.com/a/51475765
tagged with: python
tagged with: pypdf
score: 0

http://stackoverflow.com/q/51468973
has answer: http://stackoverflow.com/a/51485711
tagged with: uuid
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
has title: peewee ArrayField of UUIDS
accepted answer: http://stackoverflow.com/a/51485711
type: Question
tagged with: peewee
downvote count: 0
tagged with: postgresql
has body: I am trying to manipulate, using peewee, a table which has a column containing an array of uuids. The model is the following: class test_db(BaseModel): arr = playhouse.postgres_ext.ArrayField( peewee.UUIDField, index_type=False ) I would like to insert an entry into this table and I am using the following code: arr = [uuid.UUID('d167169e-a017-4c17-8f3a-1dee98c1e563')] x = test_db(arr=arr) x.save() But I received peewee.ProgrammingError: can't adapt type 'UUID' I also tried this one arr = ['d167169e-a017-4c17-8f3a-1dee98c1e563'] x = test_db(arr=arr) x.save() But I received the following error: peewee.ProgrammingError: column "arr" is of type uuid[] but expression is of type text[] LINE 1: INSERT INTO "test_db" ("arr") VALUES (ARRAY['d167169e-a017-4... ^ HINT: You will need to rewrite or cast the expression. Could you please provide some help for this issue? Thank you very much!
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/89889575
type: Comment
has text: PPM is definitely the easiest, as you can see above. It's late here, so I may try and do code to read PPM images tomorrow.
comment on: http://stackoverflow.com/a/51459622
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89875645
type: QuestionComment
comment on: http://stackoverflow.com/q/51451400
has text: **@fireball**, I think writing a reusable code for inline insertion of sequence of same numbers would be a great fit (instead of dividing a list into sub lists and using **+** operator again and again) which can do using **unpacking** feature of lists. Please have a look at my answer. I think you will like it.
score: 0
type: Comment

http://stackoverflow.com/comment/89740528
has text: I'm working with MySQL now, but Django still forces me to use the `max_length` parameter since its a CharField (If I change back to TextField it results in the same error), so what is the difference in using MySQL or SQLite3 on this point?
type: AnswerComment
comment on: http://stackoverflow.com/a/51373087
type: Comment
score: 0

http://stackoverflow.com/q/51348075
score: 7
tagged with: http://stackoverflow.com/tag/json
has title: Convert list of byte objects to dict
tagged with: python-requests
tagged with: http
upvote count: 8
type: Question
has body: I'm consuming an API that returns a list a of objects in a JSON. But when I get its content with Requests lib, the content is a byte array of objects like this : b'[{"id":44,"id_string":"a2BPQDsGLfLiwo4r5U4JCY","title":"ED_1803_ITAIPAVA_RJ","description":"ED_1803_ITAIPAVA_RJ","url":"https://kobocat.docker.kobo.techo.org/api/v1/data/44"},{"id":57,"id_string":"a3pb3ALiGuQAHD6XzdHAip","title":"ED_v2018_1801_Taba\xc3\xa7u-SP","description":"ED_v2018_1801_Taba\xc3\xa7u-SP","url":"https://kobocat.docker.kobo.techo.org/api/v1/data/57"},{"id":68,"id_string":"a4Gz2dSwRuyQCsjBwNhf3D","title":"ECS_1804_SONHO REAL-BA","description":"ECS_1804_SONHO REAL-BA","url":"https://kobocat.docker.kobo.techo.org/api/v1/data/68"},{"id":2,"id_string":"a4KjYoy8ieCRNykiYb7nGP","title":"ECS_1708_Vila Esperan\xc3\xa7a-SP","description":"ECS_1708_Vila Esperan\xc3\xa7a-SP","url":"https://kobocat.docker.kobo.techo.org/api/v1/data/2"},{"id":38,"id_string":"a7GQQ7xEu4K6HXWYu9SaSC","title":"ECo_1711_Terra Nossa-UF","description":"ECo_1711_Terra Nossa-UF","url":"https://kobocat.docker.kobo.techo.org/api/v1/data/38"},{"id":78,"id_string":"a7NnnbdhBUSsGoxVWBiGFb","title":"ECoSP_1805_Vila Nova Esperan\xc3\xa7a-SP","description":"ECoSP_1805_Vila Nova Esperan\xc3\xa7a-SP","url":"https://kobocat.docker.kobo.techo.org/api/v1/data/78"}] How can I make it a normal list of dictionares? I tried iterating through the byte array with for in range() , but all I can return are numbers.
answer count: 2
has answer: http://stackoverflow.com/a/51348094
accepted answer: http://stackoverflow.com/a/51348094
possible better answer: http://stackoverflow.com/a/65381624
has answer: http://stackoverflow.com/a/65381624
has comment: http://stackoverflow.com/comment/89668754
downvote count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89668804

http://stackoverflow.com/q/51382573
downvote count: 1
has comment: http://stackoverflow.com/comment/89737215
has comment: http://stackoverflow.com/comment/89737414
type: Question
has body: Is there anyway to modify the brightness of a an image in a non-homogeneous way? I mean that every pixel of an image is modified with different magnitude.I am using python's function pillow. I dont mind doing it with Opencv if there is a way.
has comment: http://stackoverflow.com/comment/89738028
has comment: http://stackoverflow.com/comment/89737739
upvote count: 0
has comment: http://stackoverflow.com/comment/89739439
has comment: http://stackoverflow.com/comment/89737879
has comment: http://stackoverflow.com/comment/89742940
has comment: http://stackoverflow.com/comment/89739110
score: -1
has title: modify the brightness of a an image in a non-homogeneous
has comment: http://stackoverflow.com/comment/89737243
accepted answer: http://stackoverflow.com/a/51384039
has comment: http://stackoverflow.com/comment/89737665
answer count: 1
favorite count: 0
tagged with: python
tagged with: opencv
type: AnsweredQuestion
tagged with: python-imaging-library
tagged with: pixel
has comment: http://stackoverflow.com/comment/89737929
has answer: http://stackoverflow.com/a/51384039
tagged with: image-processing

http://stackoverflow.com/comment/89836315
type: Comment
type: QuestionComment
has text: @dawg Yes I've tried `locals()`, but it is not clear how to access enclosing variables from inside `scope()`. Also it works for functions, and less so for classes per [the docs](https://docs.python.org/3/library/functions.html#locals)
comment on: http://stackoverflow.com/q/51432553
score: 0

http://stackoverflow.com/a/65595319
downvote count: 0
score: 4
type: Answer
answers question: http://stackoverflow.com/q/51349736
has body: In my case I accidentally pasted in Meta class of my custom user the attribute abstract = True. So it raises this error.
upvote count: 4

http://stackoverflow.com/comment/89886384
type: QuestionComment
has text: I would have stored the user id in the ModInfo Document as a StringField, and later dereferenced it by using bson.ObjectID("someID") but it seems as though your method is working about the same. Sorry I don't think I can offer a more convienient solution.
comment on: http://stackoverflow.com/q/51445481
score: 0
type: Comment

subprocess
tags question: http://stackoverflow.com/q/51371880
tag name: subprocess
tags question: http://stackoverflow.com/q/51433645
tags question: http://stackoverflow.com/q/51442945
tags question: http://stackoverflow.com/q/51452010
tags question: http://stackoverflow.com/q/51424025
tags question: http://stackoverflow.com/q/51460923
tags question: http://stackoverflow.com/q/51408678
tags question: http://stackoverflow.com/q/51372151
tags question: http://stackoverflow.com/q/51468432
tags question: http://stackoverflow.com/q/51442279
tags question: http://stackoverflow.com/q/51395017
type: Tag
tags question: http://stackoverflow.com/q/51325685
tags question: http://stackoverflow.com/q/51325187
tags question: http://stackoverflow.com/q/51415626
tags question: http://stackoverflow.com/q/51466124
tags question: http://stackoverflow.com/q/51444775
tags question: http://stackoverflow.com/q/51424854
tags question: http://stackoverflow.com/q/51423255
tags question: http://stackoverflow.com/q/51405501
tags question: http://stackoverflow.com/q/51426618
tags question: http://stackoverflow.com/q/51469341
tags question: http://stackoverflow.com/q/51426929

http://stackoverflow.com/comment/89966189
comment on: http://stackoverflow.com/a/51332942
has text: OK thanks very much. 3 bars was too cluttered. Reduced to 2 & set dodge values to 0.2 & 0.65, with widths 0.4 & 0.45, plus x_range.range_padding to 0.027 Result exactly what I wanted!
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89898381
has text: Thank you, Ajay. I'm just starting to work with dataframes and this is some advice I will definitely implement in the future, maybe even later in this project!
type: AnswerComment
comment on: http://stackoverflow.com/a/51462143
score: 0
type: Comment

http://stackoverflow.com/comment/89724590
comment on: http://stackoverflow.com/q/51375642
score: 0
type: Comment
type: QuestionComment
has text: exampl wwwww，the 'xxxxx' is random.

http://stackoverflow.com/a/51388865
type: AcceptedAnswer
downvote count: 0
has body: Using the string method str.rjust: >>> num = int(input("Enter the number of rows: ")) >>> for i in range(1, num + 1): ... print(" ".join("*" * i).rjust(num * 2 - 1)) Enter the number of rows: 5 * * * * * * * * * * * * * * *
accepted answer of: http://stackoverflow.com/q/51388808
has comment: http://stackoverflow.com/comment/89750033
type: Answer
answers question: http://stackoverflow.com/q/51388808
upvote count: 6
score: 6

pickle
tags question: http://stackoverflow.com/q/51328195
tags question: http://stackoverflow.com/q/51416302
tags question: http://stackoverflow.com/q/51461051
tags question: http://stackoverflow.com/q/51433041
tags question: http://stackoverflow.com/q/51351508
type: Tag
tags question: http://stackoverflow.com/q/51364122
tags question: http://stackoverflow.com/q/51432379
tag name: pickle

http://stackoverflow.com/comment/89848639
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51439343
score: 3
has text: The whole module is imported (if it hasn't been already), and then `do_something` from that module is bound to `do` in the current namespace.

http://stackoverflow.com/q/51451400
downvote count: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/89875645
tagged with: arrays
has body: I have a fortran array of the type DATA ELEV \1.2,3.2,2*0.0,3.9,3*0.0\ which in python would be ELEV = [1.2, 3.2, 0.0, 0.0, 3.9, 0.0, 0.0, 0.0] Notice how 2*0.0 was not 0.0 but instead 2 elements with value 0.0. Is there some way to use numpy or other python methods(or libraries) to write it similarly in python3 ? I essentially have array in the fortran format which I want to use in my python code instead of mere representation.
has answer: http://stackoverflow.com/a/51452937
has answer: http://stackoverflow.com/a/51451814
has answer: http://stackoverflow.com/a/51451455
favorite count: 0
tagged with: python-3.x
has title: How to declare array in format where continuous zeros can be written as n*0 like in fortran?
upvote count: 2
has answer: http://stackoverflow.com/a/51452660
tagged with: python
possible better answer: http://stackoverflow.com/a/51451455
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89873490
score: 1
accepted answer: http://stackoverflow.com/a/51451814

http://stackoverflow.com/comment/89883856
has text: That's the way "Run in Python console" works. If you want to view the values of variables, you can set a breakpoint and run with the debugger instead.
comment on: http://stackoverflow.com/q/51447530
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/66506739
score: -1
answers question: http://stackoverflow.com/q/51461210
upvote count: 0
type: Answer
downvote count: 1
has body: Although I realize this is an old question, I think the main issue of inheritance from instance over class merits attention. I'm not sure if the previous answers fully understood your example of the importance of inheritance from an instance, where features cannot be detailed in advance, which by definition is required with classes. In another issue I found an answer describing the module Acquisition which did exactly this, inheriting from an instance. It might be worth a look: Inheriting from instance in Python

http://stackoverflow.com/q/51430390
has comment: http://stackoverflow.com/comment/90046792
answer count: 0
has title: SQLAlchemy: questions on constructing a tree?
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/89831797
type: Question
has body: I'm attempting to make my first app with flask. This is my node class as of now: class TreePage(db.Model): __tablename__ = 'tree' id = db.Column(db.Integer, primary_key= True) name = db.Column(db.String(100), nullable= False) content = db.Column(db.String) parent_id = db.create_all(db.Integer, db.ForeignKey('id')) children = db.relationship('TreeNode', cascade = "all", backref = db.backref("parent", remote_side='TreeNode.id'), collection_class = db.attribute_mapped_collection('name') ) Being new to SQLAlchemy and databases in general, lots of the information I'm reading here and on the SQLAlchemy documentation is kind of hard to grasp. My goal right now is to be able to access a tree and its content, and then if that tree has children to be able to pick which child to study from; this is basically a visual representation of what I want to make. My guess is this should be a one to many relationship, so I won't have to deal with local/remote sides right? Both of which confuse me at the moment. Next, do I need to worry at all about the cascade parameter, or can I leave it be for now? Lastly, I want to solidify how self referential relationships work. With two different classes it's easy for me to grasp: the 'one' relationship creates a relationship object, and then the 'many' object creates a foreign key that references the primary key of its owner. But in the case of a self referential relationship, is the 'owner' the object that holds id and parent_id being the id of whatever parent object comes before? thanks and I apologize if this is at all confusing.
tagged with: database
score: 0
tagged with: relational-database
linked to: http://stackoverflow.com/q/36352271
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51456266
tagged with: decoding
type: UnansweredQuestion
tagged with: prefix
has comment: http://stackoverflow.com/comment/89904551
upvote count: 1
tagged with: python
tagged with: performance
answer count: 0
score: 1
type: Question
linked to: http://stackoverflow.com/q/33089660
downvote count: 0
has comment: http://stackoverflow.com/comment/89882926
has comment: http://stackoverflow.com/comment/89882448
tagged with: huffman-code
favorite count: 0
has title: How to decode prefix codes efficiently with Python?
has body: I am trying to decode a Huffman encoded string, with the following script: def decode(input_string, lookup_table): codes = lookup_table.keys() result = bytearray() i = 0 while len(input_string[i:]) != 0: for code in codes: if input_string[i:].startswith(code): result.append(lookup_table[code]) i += len(code) break return ''.join((chr(x) for x in result)) lookup_table = {'10': 108, '00': 111, '0111': 114, '010': 119, '0110': 72, '1111': 33, '1110': 32, '1100': 100, '1101': 101} input_string = '0110110110100011100100001111011001111' print decode(input_string, lookup_table) This script gives as output: 'Hello world!' The script works for this small string, but decoding an encoded version of Hamlet takes 110 seconds. Is there a more efficient and faster way to do this?

http://stackoverflow.com/q/51401681
score: 2
type: AnsweredQuestion
downvote count: 0
type: Question
upvote count: 2
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51401808
accepted answer: http://stackoverflow.com/a/51401808
has body: From python 3.4 to 3.5 the error handling in Json module has changed. in 3.5 decoding raises JSONDecodeError in 3.4 decoding raises ValueError My actual way to write a compatible script is: try: from json import JSONDecodeError except ImportError: JSONDecodeError = ValueError What is the best practice to do it?
tagged with: python
has title: Python 3.4 and 3.5 - JsonDecodeError compatibility

http://stackoverflow.com/comment/120589785
has text: Welcome to Stack Overflow! Code-only answers are not particularly helpful. Please add some descriptions of how this code solves the problem.
comment on: http://stackoverflow.com/a/68230740
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/q/51344293
has comment: http://stackoverflow.com/comment/89661890
has comment: http://stackoverflow.com/comment/89662631
has comment: http://stackoverflow.com/comment/89718198
favorite count: 0
has answer: http://stackoverflow.com/a/51344385
type: Question
has comment: http://stackoverflow.com/comment/89661895
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/89661876
upvote count: 1
has body: So I am trying to make automation solution for one of my project and I am using Python/Django as it is web app. I am trying to find an English word in list of strings and for particular, in bitcoin addresses. The project is about vanity address so I am trying to find whether a bitcoin address has english word in it or not. I know it sounds crazy but I am curious to know if it is possible or not. So for example, 1GOOGLEzZDwTGhXJwPSapWtViWJf2NJYyt 1vsDRvApplemzFVj8ALj6mfBsbifRoD4mi 1NmD9HtNHYjtkncsT1bXW1j84jg9MV8VzD 1mFAceBookzFVj8ALj6mfBsbifRoD4miY3 1mzFVj8ALj6mfBsbifRoYaHOOeD4miY36v 1NmzD3YLFsMpPQEsCVCjanAiN1trk3tURL So first address contains Google, second contains Apple, third contains nothing, fourth contains Facebook in it and fifth contains Yahoo in it and sixth contains URL which i don't consider english word but like Google and Facebook it is one of a kind word. So it it possible to check what kind of words are in one bitcoin address using python? An address can have zero or multiple possible words in it and I would like to know which words if possible. If this is possible, can anyone tell me which library I can use? I am working with Python3 and Django 2. P.S. I am not specifically looking for Google, Facebook, Apple, yahoo in it! It was just an example. I want to check if an address contains english word or not which means it can have monkey or donkey or any english word. Thanks.
answer count: 1
downvote count: 1
type: UnansweredQuestion
has title: Is it possible to check if string contains English word using python?

http://stackoverflow.com/q/51413483
score: 0
has answer: http://stackoverflow.com/a/51530732
has body: How do I implement "tooltips" for the hover tool in Bokeh 0.12.11 (and possibly other versions)? Searching for "Bokeh hover tooltips" gives a bunch of documentation results such as: https://docs.bokeh.org/en/latest/docs/user_guide/tools.html But when I try to implement the "tooltips" on Bokeh 0.12.11 from an example such as: https://docs.bokeh.org/en/latest/docs/gallery/elements.html I get the following error: AttributeError: unexpected attribute 'tooltips' to Figure, possible attributes are above, aspect_scale, etc.
has title: Python Bokeh Hover Tool giving: AttributeError: unexpected attribute 'tooltips' to Figure
answer count: 1
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89798470
linked to: http://stackoverflow.com/q/45855928
tagged with: python
has comment: http://stackoverflow.com/comment/89935149
has comment: http://stackoverflow.com/comment/89800180
has comment: http://stackoverflow.com/comment/89798754
has comment: http://stackoverflow.com/comment/89800720
has comment: http://stackoverflow.com/comment/89798529
tagged with: bokeh
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89798765

http://stackoverflow.com/q/51379974
accepted answer: http://stackoverflow.com/a/51380557
has answer: http://stackoverflow.com/a/51380413
tagged with: python
tagged with: python-os
score: 2
type: AnsweredQuestion
upvote count: 3
downvote count: 1
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/89731665
possible better answer: http://stackoverflow.com/a/51380413
has title: Try block catches wrong exception
has body: I'm trying to create a folder, handling the different errors (FileExistsError if the folder already exists and OSError if the folder's name contains illegal characters), but Python seems to always choose the first except block when catching an error no matter which one it is and the order they are. Is there anything I didn't understand? import os from pathlib import Path def generateSetup(name) : dir_path = os.path.dirname(os.path.realpath(__file__)) if not Path(dir_path + '/setups').exists() : os.mkdir(dir_path + '/setups') try : os.mkdir(dir_path + '/setups/' + name) except FileExistsError : print('The file already exists') except OSError : print('The name contains illegal characters') stp_name = input('Enter your setup\'s name :') generateSetup(stp_name)
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51380557

http://stackoverflow.com/q/51358956
has body: I would like to parse all link extensions in the below text using re.findall to store my result in an array. my_text = Comparer Comparer Comparer I'm trying to get this result : ["link_extension_1.php","link_extension_2.php","link_extension_3.php"] I tried that : re.findall(r'\ <div', my_text) but got that error : SyntaxError: unexpected EOF while parsing Thanks Max
tagged with: python
tagged with: regex
tagged with: parsing
score: 0
has title: parsing with re.findall regex between html tags leads to eof error
has answer: http://stackoverflow.com/a/51359145
type: Question
type: AnsweredQuestion
answer count: 1
accepted answer: http://stackoverflow.com/a/51359145

http://stackoverflow.com/q/51405646
answer count: 2
possible better answer: http://stackoverflow.com/a/51443322
has body: I'm trying to achieve sans-serif axes labels and ticks in matplotlib with pgf. I want to control that by rcParams so I have it working for all subsequent plots. Currently, I'm using "pgf.rcfonts":False, "pgf.texsystem": "pdflatex", "text.usetex": True, "font.family": "sans-serif", which I adapted from the mpl docs. It does set all my text in the figure to sans-serif. However, the numbers are kept with a serif font. I want them to be sans-serif. As soon as i force the formatter, its sans-serif. Any way to get it to do that automatically? MinEx follows... import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import FormatStrFormatter #define style style = { "pgf.rcfonts":False, "pgf.texsystem": "pdflatex", "text.usetex": True, "font.family": "sans-serif" } #set mpl.rcParams.update(style) #get data data = np.random.random(100) #set up plot f,ax = plt.subplots() ax.plot(data) #label something ax.set_xlabel('Runner') The label is sans now. The ticks are not! But when calling ax.xaxis.set_major_formatter(FormatStrFormatter('%d')) they are.
favorite count: 0
upvote count: 3
has comment: http://stackoverflow.com/comment/89783726
has title: Matplotlib ticks sans-serif for all plots
has comment: http://stackoverflow.com/comment/89785113
accepted answer: http://stackoverflow.com/a/51409039
tagged with: python
downvote count: 0
has answer: http://stackoverflow.com/a/51409039
has answer: http://stackoverflow.com/a/51443322
type: AnsweredQuestion
score: 3
tagged with: matplotlib
tagged with: formatting
linked to: http://stackoverflow.com/q/41453109
type: Question

http://stackoverflow.com/comment/90452000
type: Comment
comment on: http://stackoverflow.com/a/51442593
type: AnswerComment
has text: I agree with everything but the last sentence. You can pick _any_ assignment but there has to be one chosen. It is arbitrary which assignment you are going to pick. It does not matter. But the fact that there has to be one picked is non-disputable. Also, it is easiest to pick the one that is somewhat "natural" but it is not a must to pick this one.
score: 0

http://stackoverflow.com/q/51355035
favorite count: 0
has comment: http://stackoverflow.com/comment/89682575
has answer: http://stackoverflow.com/a/51355105
has answer: http://stackoverflow.com/a/51355097
has comment: http://stackoverflow.com/comment/89682553
has comment: http://stackoverflow.com/comment/89682510
tagged with: python
has answer: http://stackoverflow.com/a/51355118
score: 14
has comment: http://stackoverflow.com/comment/89682563
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89682530
tagged with: performance
upvote count: 14
has title: Find different pair in a list by python
possible better answer: http://stackoverflow.com/a/51355118
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/51355115
has answer: http://stackoverflow.com/a/51355407
downvote count: 0
has answer: http://stackoverflow.com/a/51355569
answer count: 6
has comment: http://stackoverflow.com/comment/89695487
has comment: http://stackoverflow.com/comment/89701689
has comment: http://stackoverflow.com/comment/89682491
has body: I have a list and I want to find different pair in list. I implement a function --> different() import numpy as np def different(array): res = [] for (x1, y1), (x2, y2) in array: if (x1, y1) != (x2, y2): res.append([(x1, y1), (x2, y2)]) return res a = np.array([[[1, 2], [3, 4]], [[1, 2], [1, 2]], [[7, 9], [6, 3]], [[3, 3], [3, 3]]]) out = different(a) # get [[(1, 2), (3, 4)], # [(7, 9), (6, 3)]] Is there any other better way to do it? I want to improve my function different. List size may be greater than 100,000.
accepted answer: http://stackoverflow.com/a/51355115
has comment: http://stackoverflow.com/comment/89682523
has comment: http://stackoverflow.com/comment/89682514

http://stackoverflow.com/q/51442589
has comment: http://stackoverflow.com/comment/89855296
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/89855086
favorite count: 0
has comment: http://stackoverflow.com/comment/89855265
has comment: http://stackoverflow.com/comment/89856236
has body: As an example, I have the following dataframe: Date Balance 2013-04-01 03:50:00 A 2013-04-01 04:00:00 A 2013-04-01 04:15:00 B 2013-04-01 04:15:00 B 2013-04-01 04:25:00 A 2013-04-01 04:25:00 A 2013-04-01 04:35:00 B 2013-04-01 04:40:00 B 2013-04-02 04:55:00 B 2013-04-02 04:56:00 A 2013-04-02 04:57:00 A 2013-04-03 10:30:00 A 2013-04-03 16:35:00 A 2013-04-03 20:40:00 A My goal is to add one column 'Counter' that basically shows a balance of the number of A's and B's. So, every time an A appears, the counter column increases one value. Every time B appears, the counter column decreases one value. If two A's appear at the same time (same Date) in two consecutive rows, the balance should increase by two on both of the rows (the same reasoning applies for consecutive B's or for A's and B's at the same time). Therefore, the dataframe would look like this in the end: Date Balance Counter 2013-04-01 03:50:00 A 1 2013-04-01 04:00:00 A 2 2013-04-01 04:15:00 B 0 2013-04-01 04:15:00 B 0 2013-04-01 04:25:00 A 2 2013-04-01 04:25:00 A 2 2013-04-01 04:35:00 B 1 2013-04-01 04:40:00 B 0 2013-04-02 04:55:00 B -1 2013-04-02 04:56:00 A 0 2013-04-02 04:57:00 A 1 2013-04-03 10:30:00 A 2 2013-04-03 16:35:00 A 3 2013-04-03 20:40:00 A 4 The major problem is that the dataframe has more than 2 millions rows, therefore it is really time consuming to perform a loop. Is there any way to implement a vectorized approach to this problem? Edit (I was able to compile a solution that works well if the dates are not the same on consecutive rows). Anyone could help me to figure out the rest? d = {'Date': ['2013-04-01 03:50:00', '2013-04-01 04:00:00','2013-04-01 04:15:00','2013-04-01 04:15:00','2013-04-01 04:25:00', '2013-04-01 04:25:00','2013-04-01 04:35:00','2013-04-01 04:40:00','2013-04- 02 04:55:00','2013-04-02 04:56:00', '2013-04-02 04:57:00','2013-04-03 10:30:00','2013-04-03 16:35:00','2013-04- 03 20:40:00'], 'Balance': ['A','A','B','B','A','A','B','B','B', 'A','A','A','A','A',]} df = pd.DataFrame(data…
type: Question
score: 5
has answer: http://stackoverflow.com/a/51444015
tagged with: python
tagged with: vectorization
accepted answer: http://stackoverflow.com/a/51444015
has comment: http://stackoverflow.com/comment/89856277
has comment: http://stackoverflow.com/comment/89855240
has comment: http://stackoverflow.com/comment/89855239
has comment: http://stackoverflow.com/comment/89855211
answer count: 1
has title: Python - Counter in 2 million row table
has comment: http://stackoverflow.com/comment/89855317
upvote count: 5
tagged with: counter

http://stackoverflow.com/q/51448936
score: 0
has comment: http://stackoverflow.com/comment/89871674
answer count: 1
tagged with: keras
has body: I am practicing using Keras to build a Convolution Neural Network. I decided to follow along this tutorial: http://adventuresinmachinelearning.com/keras-tutorial-cnn-11-lines/ However when attempting to convolve my model I run into the following error: AttributeError: 'module' object has no attribute '_TensorLike' The following is my code to look at. from __future__ import print_function import keras from keras.datasets import mnist from keras.layers import Dense, Flatten from keras.layers import Conv2D, MaxPooling2D from keras.models import Sequential import matplotlib.pylab as plt batch_size = 128 num_classes = 10 epochs = 10 # input image dimensions img_x, img_y = 28, 28 # load the MNIST data set, which already splits into train and test sets for us (x_train, y_train), (x_test, y_test) = mnist.load_data() # reshape the data into a 4D tensor - (sample_number, x_img_size, y_img_size, num_channels) # because the MNIST is greyscale, we only have a single channel - RGB colour images would have 3 x_train = x_train.reshape(x_train.shape[0], img_x, img_y, 1) x_test = x_test.reshape(x_test.shape[0], img_x, img_y, 1) input_shape = (img_x, img_y, 1) # convert the data to the right type 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 - this is for use in the # categorical_crossentropy loss below y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) model = Sequential() model.add(Conv2D(32, kernel_size=(5, 5), strides=(1, 1), activation='relu', input_shape=input_shape)) model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2))) model.add(Conv2D(64, (5, 5), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(1000, activation='relu')) model.add(Dense(num_cl…
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/64605844
has title: Keras AttributeError: 'module' object has no attribute '_TensorLike'
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/89868506
has comment: http://stackoverflow.com/comment/89875852

http://stackoverflow.com/q/51439167
downvote count: 2
type: Question
score: -2
has answer: http://stackoverflow.com/a/51439630
has body: In Python I have created a dataframe that has four columns, related to a list of shares listed on various exchanges around the world. The columns are: Stock ticker, Country of listing, Industry Sector, PE multiple I want to create a matrix, that collates the data so that along the X axis I see the various countries, and along the Y axis I see the various sectors. Within each cell I'd like to get the median PE multiple of all the companies that are in each combination of country and sector - e.g. banks in USA and Engineering in UK.
upvote count: 0
tagged with: matrix
answer count: 1
has comment: http://stackoverflow.com/comment/89848478
favorite count: 0
accepted answer: http://stackoverflow.com/a/51439630
tagged with: python
has title: How do I create a matrix from a dataframe with 3 columns in Python
type: AnsweredQuestion

http://stackoverflow.com/comment/89908868
score: 1
has text: I know that train_test_split() under sklearn library splits the dataset into training and test data based on test_size argument. If test_size is 0.2, it splits the dataset in the ratio 80:20. But if I want to split every 10th row of the dataset as train data and the remaining as test, how can I do that?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51470179

http://stackoverflow.com/a/51438243
has comment: http://stackoverflow.com/comment/89859621
score: 0
has comment: http://stackoverflow.com/comment/89858804
has comment: http://stackoverflow.com/comment/89856588
type: Answer
has comment: http://stackoverflow.com/comment/89856472
accepted answer of: http://stackoverflow.com/q/51437917
answers question: http://stackoverflow.com/q/51437917
has comment: http://stackoverflow.com/comment/89856101
has body: Modify your code in this way: file = open('student.txt') l=[] for line in file: fields = line.strip().split() print(fields) l.append(fields) Now l is a list of list, and you can do so: sub = [] for i in l: sub.append(i[2]) sub = list(set(sub)) for i in sub: print i for index, j in enumerate(l): if i in l[index][2]: print '\t' + ' '.join(j) Output: Science Rubeena 18 Science Kareen 18 Science Robotics Riggu 18 Robotics Art Jullu 18 Art sean 25 Art Geology Rene 18 Geology Babu 18 Geology
has comment: http://stackoverflow.com/comment/89860206
has comment: http://stackoverflow.com/comment/89856520
has comment: http://stackoverflow.com/comment/89856645
has comment: http://stackoverflow.com/comment/89858954
has comment: http://stackoverflow.com/comment/89856310
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89859891

rpc
tag name: rpc
tags question: http://stackoverflow.com/q/51446540
type: Tag

flask-sqlalchemy
tags question: http://stackoverflow.com/q/51474661
tags question: http://stackoverflow.com/q/51446322
type: Tag
tags question: http://stackoverflow.com/q/51476697
tags question: http://stackoverflow.com/q/51373771
tags question: http://stackoverflow.com/q/51416482
tags question: http://stackoverflow.com/q/51391771
tags question: http://stackoverflow.com/q/51479279
tags question: http://stackoverflow.com/q/51360696
tags question: http://stackoverflow.com/q/51336349
tags question: http://stackoverflow.com/q/51391867
tags question: http://stackoverflow.com/q/51386742
tag name: flask-sqlalchemy
tags question: http://stackoverflow.com/q/51451768
tags question: http://stackoverflow.com/q/51419417
tags question: http://stackoverflow.com/q/51448741
tags question: http://stackoverflow.com/q/51391039

http://stackoverflow.com/q/51447318
type: Question
has comment: http://stackoverflow.com/comment/89864963
has title: If the condition of <if> statement is False, doesn't we have to just skip it?
has body: mysum=0 for i in range(5,11,2): mysum += i if mysum ==5: break mysum += 1 print(mysum) // always prints: 5 I don't understand why the result is just '5'. I think if the condition of if statement is False, then it would skip the code block. Let me explain how I understand this code. (When mysum is 5): The if statement is going to be true. So, it goes into the code block, and there is break statement, so it exits the code block. In that case, the result of print(mysum) is 5. (When mysum is 7 or 9): The if statement is going to be false. So, it skips past the code block, and prints of the result of print(mysum), which is 7 or 9. But there is only 5 in result. Thanks in advance.
has comment: http://stackoverflow.com/comment/89864960
answer count: 3
accepted answer: http://stackoverflow.com/a/51447424
tagged with: python
has comment: http://stackoverflow.com/comment/89865040
has answer: http://stackoverflow.com/a/51447454
favorite count: 0
score: -4
upvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89864928
possible better answer: http://stackoverflow.com/a/51447441
downvote count: 5
has answer: http://stackoverflow.com/a/51447424
has answer: http://stackoverflow.com/a/51447441

http://stackoverflow.com/a/51329552
answers question: http://stackoverflow.com/q/51329510
score: 0
has comment: http://stackoverflow.com/comment/89635573
has comment: http://stackoverflow.com/comment/89635020
has comment: http://stackoverflow.com/comment/89635386
type: Answer
has body: You say they get out of order, but that is because python dicts didn't have order (except most recent versions). You could use OrderedDict instead and they will keep the original order: from collections import OrderedDict data = json.loads(my_json, object_pairs_hook=OrderedDict)

http://stackoverflow.com/a/65797984
score: 0
type: Answer
has body: Never put custom user model and additional models containing links to user model in one models.py file in one app. This can be a matter of that error. Bad idea leading to that error: # customUserModel/models.py from django.contrib.auth.models import AbstractUser from django.conf import settings class User(AbstractUser): pass class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) some_field = models.CharField(max_length=25) This is a good idea: # customUserModel/models.py from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass # additionalUserProfile/models.py from django.conf import settings class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) some_field = models.CharField(max_length=25) #settings.py AUTH_USER_MODEL = 'customUserModel.User'
answers question: http://stackoverflow.com/q/51349736
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/51351434
tagged with: python-2.7
tagged with: pandas
favorite count: 0
upvote count: 2
has body: I'm attempting to filter a pandas dataframe DF for rows who's value in column 'X' are in a particular list. DF_filtered = DF[DF['X'].isin(list.of.interest)] DF is typically millions of rows long. The following lines of code completes in a fraction of a second: DF_filtered = DF[0:1000000][DF[0:1000000]['X'].isin(list.of.interest)] DF_filtered = DF[500000:1500000][DF[500000:1500000]['X'].isin(list.of.interest)] This line, however, takes upwards of 15 minutes: DF_filtered = DF[0:1000001][DF[0:1000001]['X'].isin(list.of.interest)] Is this just a weird quirk of pandas/python? I know that it would be simple to wrap this in a batching function, but I really don't know why this is going on.
type: UnansweredQuestion
has title: Pandas is.in dataframe subsetting is slow, but only for million+1 rows
tagged with: python
score: 2
answer count: 0
tagged with: dataframe
type: Question
downvote count: 0

http://stackoverflow.com/q/51391545
has answer: http://stackoverflow.com/a/51391664
favorite count: 0
accepted answer: http://stackoverflow.com/a/51391664
linked to: http://stackoverflow.com/q/427102
has title: django url without pk
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 3
downvote count: 0
type: Question
has body: I have been trying for too long now to get my urls working with my simple models and view. There is something I am definitely not understanding. I wish to create a url similar to: .../department/team, where I do not use the PK of department object but the name instead. My model looks like: class Department(models.Model): name = models.CharField(max_length=50, blank=True, null=True) def __str__(self): return 'Department: ' + self.name class Hold(models.Model): name = models.CharField(max_length=50, blank=True, null=True) department = models.ForeignKey(Department, on_delete=models.CASCADE) my view looks like (UPDATED): class IndexView(generic.ListView): template_name = 'index.html' context_object_name = 'departments_list' def get_queryset(self): return Department.objects.all() class DepartmentView(generic.DetailView): model = Department template_name="depdetail.html" slug_field = "name" slug_url_kwarg = "name" my url looks the following: UPDATED urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<name>', views.DepartmentView.as_view(), name='depdetail') ] and finally my html: Hello there {{ object.name }} student Choose your team: however i keep getting page not found or must be slug or pk.. I hope someone can help me out so I can wrap my head around this. UPDATED It works now :) Thank you for the replies.
upvote count: 3
answer count: 1
tagged with: url

http://stackoverflow.com/q/51446327
linked to: http://stackoverflow.com/q/434287
has answer: http://stackoverflow.com/a/51446519
has answer: http://stackoverflow.com/a/51446512
has answer: http://stackoverflow.com/a/51598549
has answer: http://stackoverflow.com/a/51446820
has answer: http://stackoverflow.com/a/51458645
linked to: http://stackoverflow.com/q/312443
accepted answer: http://stackoverflow.com/a/51446512
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89863157
has comment: http://stackoverflow.com/comment/89863788
has comment: http://stackoverflow.com/comment/89863556
tagged with: python
score: 11
linked to: http://stackoverflow.com/q/8991506
tagged with: generator
has comment: http://stackoverflow.com/comment/89865154
type: AnsweredQuestion
has title: Python 3 generator comprehension to generate chunks including last
has answer: http://stackoverflow.com/a/51446651
downvote count: 1
type: Question
has body: If you have a list in Python 3.7: &gt;&gt;&gt; li [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] You can turn that into a list of chunks each of length n with one of two common Python idioms: &gt;&gt;&gt; n=3 &gt;&gt;&gt; list(zip(*[iter(li)]*n)) [(0, 1, 2), (3, 4, 5), (6, 7, 8)] Which drops the last incomplete tuple since (9,10) is not length n You can also do: &gt;&gt;&gt; [li[i:i+n] for i in range(0,len(li),n)] [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10]] if you want the last sub list even if it has less than n elements. Suppose now I have a generator, gen, unknown length or termination (so calling list(gen)) or sum(1 for _ in gen) would not be wise) where I want every chunk. The best generator expression that I have been able to come up with is something along these lines: from itertools import zip_longest sentinel=object() # for use in filtering out ending chunks gen=(e for e in range(22)) # fill in for the actual gen g3=(t if sentinel not in t else tuple(filter(lambda x: x != sentinel, t)) for t in zip_longest(*[iter(gen)]*n,fillvalue=sentinel)) That works for the intended purpose: &gt;&gt;&gt; next(g3) (0, 1, 2) &gt;&gt;&gt; next(g3) (3, 4, 5) &gt;&gt;&gt; list(g3) [(6, 7, 8), (9, 10)] It just seems -- clumsy. I tried: using islice but the lack of length seems hard to surmount; using a sentinel in iter but the sentinel version of iter requires a callable, not an iterable. Is there a more idiomatic Python 3 technique for a generator of chunks of length n including the last chuck that might be less than n? I am open to a generator function as well. I am looking for something idiomatic and mostly more readable. Update: DSM's method in his deleted answer is very good I think: &gt;&gt;&gt; g3=(iter(lambda it=iter(gen): tuple(islice(it, n)), ())) &gt;&gt;&gt; next(g3) (0, 1, 2) &gt;&gt;&gt; list(g3) [(3, 4, 5), (6, 7, 8), (9, 10)] I am open to this question being a dup but the linked question is almost 10 years old and focused on a list. There is no new method in Python 3 with g…
answer count: 8
has answer: http://stackoverflow.com/a/51446752
upvote count: 12
possible better answer: http://stackoverflow.com/a/51446651
has answer: http://stackoverflow.com/a/51446721

http://stackoverflow.com/q/51404618
has comment: http://stackoverflow.com/comment/89780391
type: AnsweredQuestion
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51405409
type: Question
upvote count: 2
answer count: 2
has body: Me and my acquaintance are working on creating a loading bar that takes forever to load for the fun of it. However, when making this loading bar, it seems to crash within the first second or two. Here's the code: import pygame import time import random pygame.init() progress = 0 black = [0, 0, 0] white = [255, 255, 255] green = [0, 255, 0] screenWidth = 600 screenHeigth = 800 size = [screenWidth, screenHeigth] font = pygame.font.SysFont("Comic Sans MS", 25) clock = pygame.time.Clock() screen = pygame.display.set_mode(size) pygame.display.set_caption('Loading...') def textObjecte(text, color, size): if size == "small": textsuraface = font.render(text, True, color) return textsuraface, textsuraface.get_rect() def loading(progress): if progress &lt; 100: text = font.render("loading: " + str(int(progress)) + "%", True, green) screen.blit(text, (300, 100)) def message_to_screen(msg, color, y_displace, size="small"): textSurf, textRect = textObjecte(msg, color, size) textRect.center = (screenWidth/2), (screenHeigth/2) + y_displace screen.blit(textSurf, textRect) while progress/2 &lt; 100: timeCount = random.randint(15, 30) increase = random.randint(1, 7) progress += increase screen.fill(black) pygame.draw.rect(screen, white, [300, 50, 200, 50]) pygame.draw.rect(screen, black, [301, 51, 198, 48]) if (progress/2) &gt; 100: pygame.draw.rect(screen, white, [302, 52, 196, 46]) else: pygame.draw.rect(screen, white, [302, 52, progress, 46]) loading(progress/2) pygame.display.flip() time.sleep(timeCount) Any help with the code would be greatly appreciated.
has comment: http://stackoverflow.com/comment/89781153
has answer: http://stackoverflow.com/a/51405329
has comment: http://stackoverflow.com/comment/89780635
has title: Crashing Loading Bar in Python
possible better answer: http://stackoverflow.com/a/51405329
tagged with: python
tagged with: pygame
favorite count: 0
linked to: http://stackoverflow.com/q/30720665
accepted answer: http://stackoverflow.com/a/51405409

http://stackoverflow.com/comment/89857996
comment on: http://stackoverflow.com/q/51443848
score: 0
type: Comment
type: QuestionComment
has text: I tried some options and I have not gotten any result, I even had to set the path permanently but I still did not get a positive result

http://stackoverflow.com/q/51437045
has comment: http://stackoverflow.com/comment/89844502
tagged with: pandas
has comment: http://stackoverflow.com/comment/89844485
has comment: http://stackoverflow.com/comment/89844633
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89844449
favorite count: 0
has comment: http://stackoverflow.com/comment/89844086
tagged with: python
has answer: http://stackoverflow.com/a/51437650
tagged with: dictionary
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/20109391
score: 1
has comment: http://stackoverflow.com/comment/89844436
upvote count: 1
has body: I have a dictionary with as values a list of dictionaries and these lists are of variable length. I have tried a lot, but can't get the data properly transformed to a Pandas dataframe. The data looks like this: {key1: [{'column5': 40, 'column1': 1, 'column2': 6, 'column3': 170, 'column4': 300}], key2: [{'column5': 6, 'column1': 33, 'column2': 5, 'column3': 76, 'column4': 13}], key3: [{'column5': 7, 'column1': 44, 'column2': 2, 'column3': 67, 'column4': 13}, {'column5': 45, 'column1': 400, 'column2': 100, 'column3': 12, 'column4': 145}]} I want to get a frame like this: column1 column2 column3 .. key1 1 6 170 key2 33 5 76 key3 33 2 67 key3 400 100 12 . . I either get errors like 'Arrays must all be of same length' when using pd.DataFrame.from_records and when using orient=index, the data is still as a dictionary placed in the dataframe. Some of the things I've tried: df = pd.DataFrame.from_dict(a, orient='index') df.transpose() //Data is not properly placed in the dataframe df = pd.DataFrame.from_records(dataset, orient='index') //Data is not properly placed in the dataframe df = pd.DataFrame.from_records(dataset) //Gives error about length of arrays df = pd.DataFrame.from_dict(dataset).T //Gives error about length of arrays How should I go about this? Thanks a lot!
type: Question
has title: Convert dict with variable length list of dicts to pandas dataframe
accepted answer: http://stackoverflow.com/a/51437650
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89844829

http://stackoverflow.com/comment/89657536
type: Comment
type: QuestionComment
has text: oh i get it , create first, and then slug?
comment on: http://stackoverflow.com/q/51342063
score: 1

http://stackoverflow.com/comment/89852947
score: 0
type: Comment
has text: can you try and check if it still works after unfreezing some layers and do some transfer learning/fine tuning?
comment on: http://stackoverflow.com/a/51438271
type: AnswerComment

http://stackoverflow.com/q/51370211
type: Question
has comment: http://stackoverflow.com/comment/89712859
tagged with: python
has body: I work with Pandas and I am trying to create a vector where the value is increased and especially reset by condition. Due to a big amount of data I need an alternative to loops. I couldn't find any case where the 'count'-value is reset and starts to count again by condition without using a loop. Input data: Out[73]: Time Force 0 1 -10 1 2 -8 2 3 -12 3 4 -30 4 5 12 5 6 16 6 7 -8 7 8 -10 8 9 -40 9 10 -50 10 11 -60 11 12 -70 12 13 -50 13 14 -10 I want to create a new vector 'count' where the value is increased when the 'Force'-value is between -5 and -15. When it's outside this threshold the 'Count'-value is reset to 0 and starts again to Count() when it's inside the threshold. What I would like to have: Time Force Count 0 1 -10 1 1 2 -8 2 2 3 -12 3 3 4 -30 0 4 5 12 0 5 6 16 0 6 7 -8 1 7 8 -10 2 8 9 -40 0 9 10 -50 0 10 11 -60 0 11 12 -70 0 12 13 -50 0 13 14 -10 1
has comment: http://stackoverflow.com/comment/89712690
possible better answer: http://stackoverflow.com/a/51370736
score: 0
answer count: 2
tagged with: bigdata
has answer: http://stackoverflow.com/a/51370604
upvote count: 1
has answer: http://stackoverflow.com/a/51370736
downvote count: 1
has title: Pandas Dataframe - Row Iteration with Resetting Count-Value by Condition without loop
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51370604
type: AnsweredQuestion
favorite count: 0

http://stackoverflow.com/comment/89672601
has text: Both CSVs have the same amount of columns? Are all the names of the columns the same in each? I see you have join = “inner” which would cause unmatched columns to disappear. Default value is “outer”
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51349064

http://stackoverflow.com/a/51332691
has comment: http://stackoverflow.com/comment/113639931
downvote count: 0
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51332639
has body: You can use numpy.where, which you can wrap in a simple function to meet your requirements: def max_by_index(idx, arr): return np.where(arr[idx] == np.max(arr[idx])) In action: &gt;&gt;&gt; max_by_index(0, a) (array([1], dtype=int64), array([2], dtype=int64)) You can index your array with this result to access the maximum value: &gt;&gt;&gt; a[0][max_by_index(0, a)] array([0.7]) This will return all locations of the maximum value, if you only want a single occurrence, you may replace np.max with np.argmax.

http://stackoverflow.com/a/51330514
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89637204
type: Answer
has comment: http://stackoverflow.com/comment/89638575
has body: When you use the form [sos,g] = zp2sos(z,p,k); g is the same as k. For example, &gt; [sos, g] = zp2sos([-1 0.5 0.6], [-0.5 0.1+0.25j 0.1-0.25j 0.9], 3); &gt; g g = 3
has comment: http://stackoverflow.com/comment/89638648
upvote count: 1
has comment: http://stackoverflow.com/comment/89637718
answers question: http://stackoverflow.com/q/51328872
score: 1
accepted answer of: http://stackoverflow.com/q/51328872

http://stackoverflow.com/q/51435635
tagged with: positional-argument
tagged with: function-signature
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/89841244
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89841600
has comment: http://stackoverflow.com/comment/89841273
tagged with: python
has answer: http://stackoverflow.com/a/51435919
accepted answer: http://stackoverflow.com/a/51435919
type: AnsweredQuestion
has title: Is *args guaranteed to preserve order?
has body: In Python3 i can use * to accept any number of positional arguments. A sample demonstrating this: def a(*args): for argument in args: print(argument) a(1,2,3,4) Would thus print: 1 2 3 4 What I'm uncertain is, if the order of positional arguments stored in args is actually guaranteed to be preserved? Can I trust that if I call a(1,2,3,4) then args is always (1,2,3,4) or is this just a side effect of an implementation detail? While trying to look into this, I saw that order in **kwargs is preserved since Python 3.6 and this is specified in PEP-468 how ever I didn't find any mention of *args in this regard.
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89841363
score: 0

http://stackoverflow.com/q/51480680
tagged with: python
type: Question
has title: python 2.7 getting below error while running the script
has comment: http://stackoverflow.com/comment/89930079
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89930176
has body: I have the following code in Python 2.7 and am receiving the following error. import os,subprocess,re f = open("/var/tmp/disks_out", "w") proc = subprocess.Popen( ["df", "-h"], stdout=subprocess.PIPE, stderr=subprocess.PIPE ) out, err = proc.communicate() for line in out: f.write(line) f.close() f1 = open("/var/tmp/disks_out","r") disks = [] for line in f1: m = re.search(r"(c\dt\d.{19})",line) if m: disk = m.group[1] disks.append(disk) print(disks) Error: disk = m.group[1] TypeError: 'builtin_function_or_method' object is unsubscriptable Does anyone know why this is happening?
has answer: http://stackoverflow.com/a/51480865
type: UnansweredQuestion

http://stackoverflow.com/q/51442279
has title: Appending Datetime into an Array (Python)
tagged with: arrays
tagged with: python-2.7
downvote count: 0
has body: Scope: to produce a script that fetches the task list from windows cmd, stores it as an array, appends an identical timestamp to each task, and then appends it to a text file as a comma-delimited table so an analyst can load it into excel later. Trouble: The question here is how to create an additional column in the array, and then populate it with the timestamp. The standard numpy functions (append) don't seem to quite do what I need, and accessing specific columns in an array and referencing them in a loop is still unclear to me. I'm new enough to arrays that I might be missing a key piece of logic Code so far: import os, sys, subprocess, numpy, csv, datetime # Set the output location to a user provided location, where a txt simply named with the date will be stored for that day. date_ = datetime.datetime.now() date = date_.strftime('%Y%m%d') timestamp = date_.strftime('%x %X') output_ = raw_input("Please enter the directory where you would like the task list to be compiled:") location = output_ +'\\tasklist_' + str(date) +'.txt' # Create the array from tasklist subprocess.check_output('tasklist /fo csv > %userprofile%\desktop\processes.csv') arrays = [numpy.array(map(str, line.split(',')))for line in open('C:\Users\[USER]\Desktop\processes.csv')] # Iterate over the array, and append the timestamp: rows = len(x) count = 0 for task in arrays: if count <= rows: count =+ 1 ## ADD TIMESTAMP # Check for output txt. If it exists, append to it. if it doesnt, write over it. if os.path.isfile(location) == True: numpy.delete(arrays,(0),axis=0) with open(location, "a+") as save: save.write(arrays) else: with open(location, "a+") as save: save.write(arrays) Helpful mentions: This question here helped me set up the Task List procedure. Thanks for viewing!
favorite count: 0
answer count: 0
type: UnansweredQuestion
tagged with: python
score: 3
tagged with: subprocess
linked to: http://stackoverflow.com/q/13525882
upvote count: 3
tagged with: tasklist
type: Question

http://stackoverflow.com/comment/89795902
comment on: http://stackoverflow.com/q/51411971
score: 0
type: Comment
type: QuestionComment
has text: Could you iterate through something like: `range(0, df['Time (sec)'].max(), 200)`?

http://stackoverflow.com/comment/89676354
score: 0
type: Comment
has text: If you are shure that you want to use Git(hub) you can use the API https://developer.github.com/v3/git/ or git itself.
type: QuestionComment
comment on: http://stackoverflow.com/q/51351804

string-search
tags question: http://stackoverflow.com/q/51389795
type: Tag
tag name: string-search

http://stackoverflow.com/a/51410888
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/51410794
answers question: http://stackoverflow.com/q/51410794
has body: The reason why entering 20.5 gives you an error is because in the amt variable, it is looking for an integer to be inputted. In python, any number with a decimal is considered a float. The code for the amt variable is currently amt = int(input("Withdraw amount: ")) For the amt variable to have a number with a decimal as acceptable input, the amt variable should be this: amt = float(input("Withdraw amount: "))

google-app-engine-python
type: Tag
tag name: google-app-engine-python
tags question: http://stackoverflow.com/q/51386090

http://stackoverflow.com/a/51434535
has body: Use a regular expression with Series.str.extract, where your first capturing group is everything up to the last digit, and then the next capturing group is all of the letters remaining. I've added optional capturing groups so that it works if your string has all numbers or all letters. s = pd.Series(['12345678ABC', '12345678ABCDEF', '12345A6789AB', '12A3456ABC', '1234123', 'ABCDERED']) s.str.extract('(?:(.*\d))?(?:([a-zA-Z]+))?') Output: 0 1 0 12345678 ABC 1 12345678 ABCDEF 2 12345A6789 AB 3 12A3456 ABC 4 1234123 NaN 5 NaN ABCDERED
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/89839458
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51434481
accepted answer of: http://stackoverflow.com/q/51434481
type: Answer

http://stackoverflow.com/a/55840400
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51390551
type: Answer
score: 11
answers question: http://stackoverflow.com/q/51390551
upvote count: 11
has body: The NTP client sends a packet with its local time orig_time, which the NTP server receives at the server time recv_time. The server then replies at server time tx_time and the client receives that reply at local time dest_time. The round trip delay is calculated as recv_time - orig_time + dest_time - tx_time, and the offset between the clocks is offset = (recv_time - orig_time + tx_time - dest_time) / 2. Assuming the two NTP packets take consistent paths, the correct adjusted time is simply dest_time + offset, which is equivalent to tx_time + delay/2.
type: AcceptedAnswer

http://stackoverflow.com/comment/89762269
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51395245
type: Comment
has text: inserting value in idboard in view.py like punjab Board and Sindh Board

http://stackoverflow.com/q/51373533
tagged with: python
tagged with: computer-vision
type: AnsweredQuestion
tagged with: python-tesseract
has title: Extracting Hebrew text from image in python
linked to: http://stackoverflow.com/q/11489824
score: 7
upvote count: 7
has body: I want to extract Hebrew text from an image. I've tried using pytesseract, but it gets some letters confused (for example ' instead of י or נ instead of כ) I tried doing some manipulations on the image (such as resizing, removing noise and binarization) which helped a little but still got many mistakes. I've spent hours searching for better text extraction tools but couldn't find. So here's my question: A) Is there a tool I can use that I might have missed? B) If not, what are the steps to creating my own? Thanks in advance, Amichai
type: Question
accepted answer: http://stackoverflow.com/a/51374015
possible better answer: http://stackoverflow.com/a/72169730
answer count: 2
has answer: http://stackoverflow.com/a/51374015
downvote count: 0
tagged with: ocr
favorite count: 0
tagged with: hebrew
has answer: http://stackoverflow.com/a/72169730

http://stackoverflow.com/a/51398766
has body: If you want the result to be 'Nice', result = 'Nice' If there's extra condition that 'Nice' must be in your expression, add an if statement if 'mama' in text1: result = 'Nice';
answers question: http://stackoverflow.com/q/51398626
type: Answer
score: 0

http://stackoverflow.com/comment/89674542
score: 1
has text: @Parfait see the highest-upvoted answer on the dupe link, which does not use regex
comment on: http://stackoverflow.com/q/51348996
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51362012
has answer: http://stackoverflow.com/a/51362154
favorite count: 0
type: UnansweredQuestion
tagged with: python
duplicate of: http://stackoverflow.com/q/35639588
has body: I have a pandas column with values ranging from 0.0 to 1.0. I want to convert this column to a binary column (0 or 1) based on a threshold, i.e. if the value is &lt;= threshold it will become 0 and 1 otherwise.
type: Question
linked to: http://stackoverflow.com/q/35639588
has answer: http://stackoverflow.com/a/51362173
has title: Convert a pandas dataframe column based on condition
score: 4
upvote count: 4
answer count: 3
has answer: http://stackoverflow.com/a/51362055
tagged with: pandas
downvote count: 0

http://stackoverflow.com/comment/89739669
comment on: http://stackoverflow.com/q/51383415
score: 0
type: QuestionComment
has text: The Dense layer accepts ints not a sequence. For example try `Dense(5)`
type: Comment

http://stackoverflow.com/comment/89725410
type: AnswerComment
has text: It's slowly making sense now. I just never saw anything been done like (not to mention there was no explanation or comment from my professor). So basically since the variable `result` holds onto the function, I can just use that execute the function inside the variable right? So in other sense, it's kind of like I'm having a variable `result` and a function declared as `def result() ` right?
type: Comment
comment on: http://stackoverflow.com/a/51376380
score: 0

http://stackoverflow.com/comment/89718144
comment on: http://stackoverflow.com/q/51373165
score: 0
type: Comment
type: QuestionComment
has text: `d['persons']['id']` would yield an error, not sure is a path?

http://stackoverflow.com/q/51360363
tagged with: axis
has comment: http://stackoverflow.com/comment/89695058
favorite count: 0
has title: matplotlib logarithmic y axis format
type: UnansweredQuestion
tagged with: python
answer count: 0
has body: I have an issue with the output format of a semilogy plot in python: import matplotlib.pyplot as plt import numpy as np x = np.arange(3, 10, 1) y = x**2 fig, ax = plt.subplots(nrows=1, ncols=1) ax.plot(x, y) ax.set_yscale('log') ax.set_ylim(8, 80) ax.set_yticks([10, 20, 30, 40, 50, 60, 70, 80]) ax.set_yticklabels(['10', '20', '30', '50', '60', '70', '80']) plt.show() my output is this it seems the log scale is creating new tick labels which remain when I create the ones I want. I tried to solve it by adding ax.set_yticks([]) ax.set_yticklabels([]) right before the ticks definition, but unfortunately it didn't work. Everything is fine in linear scale. Any help is appreciated.
has comment: http://stackoverflow.com/comment/89698811
upvote count: 1
downvote count: 1
tagged with: plot
duplicate of: http://stackoverflow.com/q/48468463
type: Question
tagged with: matplotlib
linked to: http://stackoverflow.com/q/48468463
score: 0

http://stackoverflow.com/comment/89752506
comment on: http://stackoverflow.com/a/51390120
score: 0
type: Comment
has text: Thank you very much! One additional question:How to return it in format of numpy array? e.g. [['15', '17'], ['24'], ['6']]
type: AnswerComment

http://stackoverflow.com/comment/89755060
score: 1
type: Comment
comment on: http://stackoverflow.com/q/51390918
type: QuestionComment
has text: @smci: I've rolled the edit back because I think the question is about keeping track of the created objects, not about the randomness.

http://stackoverflow.com/q/51456603
tagged with: pytest-html
tagged with: pytest
has answer: http://stackoverflow.com/a/51456653
upvote count: 1
type: Question
has title: Could not find a version that satisfies the requirement py.xml (from versions: ) No matching distribution found for py.xml
has comment: http://stackoverflow.com/comment/89883279
answer count: 1
downvote count: 0
score: 1
has body: I want to modify the columns of the result table of pytest report using the following code: from datetime import datetime from py.xml import html import pytest @pytest.mark.optionalhook def pytest_html_results_table_header(cells): cells.insert(2, html.th('Description')) cells.insert(1, html.th('Time', class_='sortable time', col='time')) cells.pop() @pytest.mark.optionalhook def pytest_html_results_table_row(report, cells): cells.insert(2, html.td(report.description)) cells.insert(1, html.td(datetime.utcnow(), class_='col-time')) cells.pop() @pytest.mark.hookwrapper def pytest_runtest_makereport(item, call): outcome = yield report = outcome.get_result() report.description = str(item.function.__doc__) To use the above code, I am trying to install py.xml. While using pip install py.xml. , I am getting the below error messgae: Could not find a version that satisfies the requirement py.xml (from versions: ) No matching distribution found for py.xml Please let me know how to resolve this issue
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/89688523
score: 0
comment on: http://stackoverflow.com/a/51358024
type: AnswerComment
type: Comment
has text: Yes. okay. I have to concatenate the URL starting part with the key for each image. How do I do that inside {{ }} in HTML?

http://stackoverflow.com/comment/89765015
comment on: http://stackoverflow.com/q/51393049
has text: My real dataset county has several thousands of observations, how should I do it?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/51462204
answers question: http://stackoverflow.com/q/51462146
has comment: http://stackoverflow.com/comment/89904447
has comment: http://stackoverflow.com/comment/89906772
score: 3
has body: You and do it this way. Using reindex to get back those missing id values. df1 = df.replace('None',np.nan).set_index('id1') df1.stack().reset_index(level=1, drop=True).reindex(df1.index) Output: id1 123 NaN 124 Plane 125 Boat dtype: object
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89905995
type: Answer
has comment: http://stackoverflow.com/comment/89902313
has comment: http://stackoverflow.com/comment/89905692
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51462146

http://stackoverflow.com/q/51329122
accepted answer: http://stackoverflow.com/a/51329615
score: 0
has comment: http://stackoverflow.com/comment/89633894
tagged with: pandas
answer count: 1
tagged with: python
has body: I build a dictionary app, where I use a 3 column df1 DataFrame (English - German - Spanish). I need to iterate every column where a user given a value in English, and he should post the equivalent word in Spanish and German. I started the code like that: for w in df1.index: e = df1.loc[w]['English'] print("Translate: " + e + "in German") d = input('') print("Now try Spanish\n") s = input('') How to iterate RANDOMLY to check if the supplied input matches the values in a particular row? Update: Data Sample | Deutsch | Englisch | Español | |--------------------|-----------------|----------------| | bei meinen eltern | with my paernts | con mis padres | | zu Hause | at home | en casa | | stammen aus | come from | viene de | | ist in ... geboren | was born in | nació en |
has answer: http://stackoverflow.com/a/51329615
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89634669
has title: iterating rows in Pandas to match values in columns
type: Question

http://stackoverflow.com/q/51369718
has comment: http://stackoverflow.com/comment/89711804
score: 7
type: Question
tagged with: arrays
has comment: http://stackoverflow.com/comment/89711775
possible better answer: http://stackoverflow.com/a/51369803
accepted answer: http://stackoverflow.com/a/51369778
has answer: http://stackoverflow.com/a/51369824
upvote count: 7
has answer: http://stackoverflow.com/a/51369768
tagged with: python
answer count: 4
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51369778
has title: Python - How can I find if an item exists in multidimensional array?
has body: I've tried a few approaches, none of which seem to work for me. board = [[0,0,0,0],[0,0,0,0]] if not 0 in board: # the board is "full" I then tried: if not 0 in board[0] or not 0 in board[1]: # the board is "full" None of these approaches worked, though the second one generally let the array fill up more. (I wrote code to fill up the array randomly).
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51369803
tagged with: list
downvote count: 0

http://stackoverflow.com/q/51402770
tagged with: python
type: UnansweredQuestion
type: Question
has body: Using python pandas, I am trying to write a condition in pandas which will match two columns from two different excel file having the same column name and different numerical values in them. For each column there are 2000 rows to match. The condition: if final value = ( if File1(column1value) - File2(column1value) = 0 then update the value with 1; if File1(column1value) - File2(column1value) is less than or equ al to 0.2 then keep File1Column1Value; if (File1Column1) - File2(column1value) greater than 0.2 the. update the value with 0. https://i.sstatic.net/Nx3WA.jpg
has answer: http://stackoverflow.com/a/51403062
answer count: 1
has title: Two different excel file to match their rows having same name
score: 0
tagged with: pandas

http://stackoverflow.com/comment/89808318
has text: what exactly is your desired output for this example?
comment on: http://stackoverflow.com/q/51418579
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89801874
type: QuestionComment
comment on: http://stackoverflow.com/q/51414814
has text: @oberron how shall i write the lambda function in this situation?
score: 0
type: Comment

http://stackoverflow.com/a/51330436
has body: To print everything in one output you could try import sqlite3 from tabulate import tabulate conn = sqlite3.connect("Table.db") c = conn.cursor() def order_by_day(): with conn: data = c.execute("SELECT * FROM Table_name ORDER BY Day_column") print(tabulate(data, headers="keys", tablefmt="grid", stralign='center', numalign='center')) An additional syntax I found from this question import sqlite3 from tabulate import tabulate conn = sqlite3.connect("Table.db") c = conn.cursor() def order_by_day(): with conn: data = c.execute("""SELECT * FROM Table_name ORDER BY Day_column CASE WHEN Day_column='Monday' THEN 1 WHEN Day_column='Tuesday' THEN 2 WHEN Day_column='Wednesday' THEN 3 WHEN Day_column='Thursday' THEN 4 WHEN Day_column='Friday' THEN 5 WHEN Day_column='Saturday' THEN 6 WHEN Day_column='Sunday' THEN 7 END""") print(tabulate(data.fetchall(), headers="keys", tablefmt="grid", stralign='center', numalign='center'))
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/51330180
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51330180
type: Answer
has comment: http://stackoverflow.com/comment/89638574

http://stackoverflow.com/a/57196817
has body: you want to get data form user we use scanf('%d %d', %name, %value) name, value=input(), input() Another solution is that: name, value=input().split() use split method
type: Answer
answers question: http://stackoverflow.com/q/51374688
score: 0

http://stackoverflow.com/comment/89756560
type: QuestionComment
comment on: http://stackoverflow.com/q/51391867
has text: Size = 2 Is the variable used to control how big something like a flask search bar is. This is still here because I wanted to set a minimum size for the choice options, however, I don't believe it works. Removing it does not resolve the issue
score: 0
type: Comment

http://stackoverflow.com/q/51420923
possible better answer: http://stackoverflow.com/a/58142000
accepted answer: http://stackoverflow.com/a/52702937
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/58142000
has title: Resampling a signal with scipy.signal.resample
tagged with: scipy
type: Question
score: 9
answer count: 2
upvote count: 9
downvote count: 0
has body: I was trying to resample a generated signal from 256 samples to 20 samples using this code: import scipy.signal import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10, 256, endpoint=False) y = np.cos(-x**2/6.0) yre = signal.resample(y,20) xre = np.linspace(0, 10, len(yre), endpoint=False) plt.plot(x,y,'b', xre,yre,'or-') plt.show() Which returns this plot (apparently correct): However, as can be noticed, the first sample is badly approximated. I believe that resample computes the average of the samples that belongs to equidistant groups of samples and, in this case, it seems that the first subgroup of samples is padded with zeros in the beggining in order to estimate the first output sample. Thus, I consider that the first sample can be successfully estimated by telling resample function that I do not want to pad with zeroes the first subgroup. Can somebody help me in order to achieve a correct resampling of this signal? Thanks in advance.
has answer: http://stackoverflow.com/a/52702937
tagged with: python
favorite count: 0
tagged with: python-3.x

caesar-cipher
tags question: http://stackoverflow.com/q/51437514
type: Tag
tag name: caesar-cipher

multidimensional-array
tags question: http://stackoverflow.com/q/51383405
tags question: http://stackoverflow.com/q/51395078
tags question: http://stackoverflow.com/q/51326320
tags question: http://stackoverflow.com/q/51394842
type: Tag
tags question: http://stackoverflow.com/q/51361765
tags question: http://stackoverflow.com/q/51412320
tags question: http://stackoverflow.com/q/51431380
tags question: http://stackoverflow.com/q/51474401
tags question: http://stackoverflow.com/q/51410742
tags question: http://stackoverflow.com/q/51330475
tags question: http://stackoverflow.com/q/51375389
tags question: http://stackoverflow.com/q/51326534
tags question: http://stackoverflow.com/q/51410509
tags question: http://stackoverflow.com/q/51372775
tags question: http://stackoverflow.com/q/51336934
tag name: multidimensional-array

http://stackoverflow.com/comment/89790313
comment on: http://stackoverflow.com/q/51408162
type: Comment
score: 0
has text: @DanielMöller let me check that right now
type: QuestionComment

http://stackoverflow.com/comment/89768751
comment on: http://stackoverflow.com/a/51390796
has text: Thanks I corrected my answer, I think it's more accurate now.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89701822
has text: Thank you so much for your answer. I have one last question: Where does the memory of the previous 3 pixels come from? Does each pixel have an lstm cell, or is one row-lstm contained in a single lstm cell? Also, do we do row-lstm for each pixel in the image?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51364384

http://stackoverflow.com/comment/89752262
score: 0
comment on: http://stackoverflow.com/q/51389961
type: Comment
has text: since you are not performing iteration I don't understand what your issue is or what you are trying to accomplish
type: QuestionComment

http://stackoverflow.com/q/51366666
tagged with: statsmodels
type: Question
has comment: http://stackoverflow.com/comment/89706768
has title: Ecommerce item sales forecasting with pandas and statsmodels
has answer: http://stackoverflow.com/a/51377554
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/89707414
answer count: 1
has body: I want to forecast item sales (number of sales for each product) with pandas and statsmodel for an ecommerce business. Because item sales is a count dependent variable I'm assuming a Poisson modeling would work best. In an ideal world the model will be used to decide on which products to use in ads (increasing product views) and also to decide on deciding price points (changing prices) to result in best performance/profitability. So far so good, however when I try: ... import statsmodels.formula.api as smf ... result = smf.poisson(formula="Item_Sales ~ Product_Detail_Views + Variant_Price + C(Product_Type)", data=df).fit() I get: RuntimeWarning: invalid value encountered in multiply return -np.dot(L*X.T, X) RuntimeWarning: invalid value encountered in greater_equal return mu &gt;= 0 RuntimeWarning: invalid value encountered in greater oldparams) &gt; tol)) And a table full of NaNs If I use OLS with the same dataset: result = smf.ols(formula="Item_Sales ~ Product_Detail_Views + Variant_Price + C(Product_Type)", data=df).fit() I get an R-squared of 0.809 so data is good. The model isn't as usable though as I get negative predictions which are obviously not possible (you cannot have negative sales of items). How can I make the Poisson model work?
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51403577
tagged with: keras
has body: I defined a recurrent network with return_state set to True: import numpy as np from tensorflow.python import keras data, targets = np.ones((4, 2, 3)), np.zeros((4, 2, 3)) input_shape = data.shape input_1 = keras.layers.Input(batch_shape=(None,)+input_shape[1:]) recurrent_1, _, state = keras.layers.LSTM(units=input_shape[-1], input_shape=input_shape[1:], return_sequences=True, return_state=True)(input_1) model = keras.models.Model(inputs=[input_1], outputs=[recurrent_1]) model.compile(loss='mean_squared_error', optimizer='RMSprop', metrics=['accuracy']) tensorboard_callback = keras.callbacks.TensorBoard(log_dir='/', histogram_freq=1, write_graph=True, write_grads=True, write_images=False) model.fit(data, targets, validation_split=0.25, callbacks=[tensorboard_callback]) The fit() call failed with this error: Traceback (most recent call last): File "/home/joshuaf/PycharmProjects/skyline/catkin_ws/src/learning/src/functional_recurrent_tensorboard.py", line 23, in &lt;module&gt; model.fit(data, targets, validation_split=0.25, callbacks=[tensorboard_callback]) File "/home/joshuaf/PycharmProjects/skyline/venv/local/lib/python2.7/site-packages/tensorflow/python/keras/engine/training.py", line 1348, in fit validation_steps=validation_steps) File "/home/joshuaf/PycharmProjects/skyline/venv/local/lib/python2.7/site-packages/tensorflow/python/keras/engine/training_arrays.py", line 157, in fit_loop callbacks.set_model(callback_model) File "/home/joshuaf/PycharmProjects/skyline/venv/local/lib/python2.7/site-packages/tensorflow/python/keras/callbacks.py", line 70, in set_model callback.set_model(model) File "/home/joshuaf/PycharmProjects/skyline/venv/local/lib/python2.7/site-packages/tensorflow/python/keras/callbacks.py", line 762, in set_model tf_summary.histogram('{}_out'.format(layer.name), layer.output) File "/home/joshuaf/PycharmProjects/skyline/venv/local/lib/python2.7/site-packages/tensorflow/python/summary/summary.py", line 187, in histogram tag=tag, values=values, name=s…
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 0
upvote count: 2
has title: (Keras) Does the TensorBoard callback work for a recurrent network with return_state on?
tagged with: tensorflow
type: Question
downvote count: 0

http://stackoverflow.com/a/51426758
downvote count: 0
answers question: http://stackoverflow.com/q/51421283
has comment: http://stackoverflow.com/comment/89833909
score: 4
has body: hOCR appears to be a dialect of XML, so you should be able to use the xml.etree module from the stdlib to parse the hOCR code into a Python-navigable tree. Then navigate that tree to compose an object or nested dict, and then finally using the stdlib's json module to convert that dict to JSON.
type: Answer
upvote count: 4

http://stackoverflow.com/comment/89792638
type: AnswerComment
has text: You give statements that makes no sense. You didn't give a row of code and how you're using pyinstaller but expect help!? This platform is not for complaining!
type: Comment
comment on: http://stackoverflow.com/a/51406763
score: 0

http://stackoverflow.com/comment/89814433
comment on: http://stackoverflow.com/a/51388550
has text: Let me ask you something, you are not nothing django model user? you doing your entire authentication and user classes ouside the django or outside User auth from django?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89776273
type: Comment
has text: Weird because a `node` (that inherits from `QObject` and so has `deleteLater`) is well deleted. Even if python still has a reference. What's the implementation behind `deleteLater` ?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51402353

http://stackoverflow.com/a/51435444
has comment: http://stackoverflow.com/comment/89840995
has comment: http://stackoverflow.com/comment/89841278
has comment: http://stackoverflow.com/comment/89840921
type: AcceptedAnswer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89841173
has comment: http://stackoverflow.com/comment/89840944
has comment: http://stackoverflow.com/comment/89841048
type: Answer
accepted answer of: http://stackoverflow.com/q/51435407
has comment: http://stackoverflow.com/comment/89840874
answers question: http://stackoverflow.com/q/51435407
has comment: http://stackoverflow.com/comment/89841264
has body: You can, by using ** to unpack a dict in the arguments, which sets them to be keyword arguments. timedelta(**{unit_of_measurement: quantity_of_units}) The reason why it works is because that unpacks to: timedelta(&lt;unit_of_measurement&gt;=quantity_of_units) Where &lt;unit_of_measurement&gt; is minutes, seconds, days... So you can replace your if... elif... else... statements with: end = (now + timedelta(**{unit_of_measurement: quantity_of_units})).strftime('%Y-%m-%d')
upvote count: 1

http://stackoverflow.com/a/51344385
has comment: http://stackoverflow.com/comment/89662029
type: Answer
answers question: http://stackoverflow.com/q/51344293
downvote count: 0
has body: You'll need a list of all English words you care to detect. There are a number of places to get these. I'd suggest looking at the dictionary files for a spellchecker, like aspell, since you don't care about the definitions. Aspell has a command to dump wordlists. aspell -d en dump master | aspell -l en expand &gt; words.en.txt Next, get an iterable of the words. You'll probably want to filter out trivially short words like a and I, and any words with special characters that can't appear in an address. Format the word list into a regex with alternations, i.e. '|'.join(wordlist). Since Python's backtracking regex engine doesn't handle alternations efficiently, you'll want a faster engine. Try pip install rure, which uses Rust's regex engine, and use that to compile the regex instead. (See Rust's regex optimization guide.) If you care about which word it found, you can wrap the whole regex in () to make it a capturing group. Then just run the compiled regex (maybe case-insensitive) against each address in turn. If it matches, you'll get the word.
score: 5
upvote count: 5

http://stackoverflow.com/comment/89798516
comment on: http://stackoverflow.com/a/51413418
score: 1
has text: But even if there are more matches in the rest of `bigDictB`, you are still going to add the same `bigDictAkey` to the `setOfMatches` set, which already has the current `bigDictAkey`, and that's why you should `break` as soon as you find a match.
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51416691
has body: Remove anything in angle brackets and square brackets as well as commas. import re data = '''2014 Estimate 1,968 185 845 439 107 2,735 1,312 1,285[4] ''' print(re.sub(r'<.*?>|\[.*?\]|,', '', data, flags=re.DOTALL)) This outputs: 2014 Estimate 1968 185 845 439 107 2735 1312 1285
has comment: http://stackoverflow.com/comment/89804954
score: 0
has comment: http://stackoverflow.com/comment/89804829
answers question: http://stackoverflow.com/q/51416599
type: Answer

http://stackoverflow.com/comment/89699571
score: 1
has text: Yes, but cloud vision only response one label for all objects, Example one label of car.
comment on: http://stackoverflow.com/q/51354969
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51417597
score: 2
downvote count: 0
upvote count: 2
has body: You have to instantiate fresh new md5 encoder every time because you would just append some string to the old string and get hash from their concatenation: import hashlib while True: OString = input("Input some text here &gt;") encoder = hashlib.md5() encoder.update(OString.encode()) hashedString = encoder.hexdigest() print(hashedString) Ostring = None hashedString = None
answers question: http://stackoverflow.com/q/51417506
type: Answer

http://stackoverflow.com/q/51473617
has comment: http://stackoverflow.com/comment/89954874
has title: django orm : connecting 2 models using one base model
type: UnansweredQuestion
has body: I have 3 models auth-user as my base model and other 2 models have the foreign key of auth-user. Now I want to combine all three tables and create an object which fetches all data from 3 tables combined. class AuthUser(models.Model): password = models.CharField(max_length=128) last_login = models.DateTimeField(blank=True, null=True) is_superuser = models.IntegerField() username = models.CharField(unique=True, max_length=150) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=150) email = models.CharField(max_length=254) is_staff = models.IntegerField() is_active = models.IntegerField() date_joined = models.DateTimeField() class Meta: managed = False db_table = 'auth_user' class employees(models.Model): employee_name = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True, to_field='username') department = models.CharField(max_length=100) dob = models.DateField() doj = models.DateField() blood_grp = models.CharField(max_length=100, null=True) father_name = models.CharField(max_length=100, null=True) add1 = models.CharField(max_length=100, null=True) add2 = models.CharField(max_length=100, null=True) # doj = models.ImageField(upload_to='profile_pics', blank=True) con_relation = models.CharField(max_length=100) # email_id = models.EmailField(max_length=254, blank=True, null=True) webmail_id = models.CharField(max_length=100, blank=True, null=True) emergency_mob = models.CharField(max_length=100) contact_person = models.CharField(max_length=100, blank=True, null=True) biometric = models.CharField(max_length=100, blank=True, null=True) biometric_id = models.CharField(max_length=100, blank=True, null=True) offer_letter = models.CharField(max_length=100, blank=True, null=True) team_leader = models.CharField(max_length=100) manager = models.CharField(max_length=100, blank=True, null=True) employment_status = models.CharField(max_length=100, blank=True, null=True) company_id = models.CharField(max_length=100) adhar_id = …
tagged with: python
has comment: http://stackoverflow.com/comment/89917827
has comment: http://stackoverflow.com/comment/89954663
answer count: 0
has comment: http://stackoverflow.com/comment/89915525
tagged with: orm
has comment: http://stackoverflow.com/comment/89954458
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/89917482
score: 0

http://stackoverflow.com/q/51334876
favorite count: 0
type: UnansweredQuestion
has title: I would like to make a veto map list in order to choose a map for scrimming?
tagged with: python
score: 1
type: Question
has answer: http://stackoverflow.com/a/51335160
downvote count: 0
upvote count: 1
answer count: 1
has body: Im new i guess and havent done python in like 6 months. I want a list of game maps (from overwatch), and then ask the user to remove a map from the list and then ask again until only 5 maps remain. Here is what I have and i honestly have no idea what im doing. Hanamura = 1 Horizon_Lunar_Colony = 2 Temple_of_Anubis = 3 Volskaya_Industries = 4 Dorado = 5 Junkertown = 6 Rialto = 7 Route_66 = 8 Gibraltar = 9 Blizzard_World = 10 Eichenwalde = 11 Hollywood = 12 Kings_row = 13 Numbani = 14 Ilios = 15 Lijiang = 16 Nepal = 17 Oasis = 18 # (Hanamura, Horizon_Luner_Colony, Temple_of_Anubis, Volskaya_Industries, Dorado, Junkertown, Rialto, Route_66, Gibraltar, Blizzard_World, Eichenwalde, Hollywood, Kings_row, Numbani, Ilios, Lijiang, Nepal, Oasis) # (Hanamura = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,15, 16, 17, 18) print ('Hanamura0 \nHorizon_Lunar_Colony1 \nTemple_of_Anubis2 \nVolskaya_Industries3 \nDorado4 \nJunkertown5 \nRialto6 \nRoute_66_7 \nGibraltar8 \nBlizzard_World9 \nEichenwalde10 \nHollywood11 \nKings_row12 \nNumbani13 \nIlios14 \nLijiang15 \nNepal16 \nOasis 17\n') p = 1 numbofitems = 18 if numbofitems &gt;= 5: x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18] x.remove(input()) print(x) numbofitems - p

http://stackoverflow.com/a/51468653
has comment: http://stackoverflow.com/comment/89905899
has comment: http://stackoverflow.com/comment/89905932
has comment: http://stackoverflow.com/comment/89905946
has body: I believe need get_indexer for positions by filtered columns names, for index is possible use same way or numpy.where for positions by boolean mask: df = pd.DataFrame({'timestamp':list('abadef'), 'B':[4,5,4,5,5,4], 'C':[7,8,9,4,2,3], 'D':[1,3,5,7,1,0], 'E':[5,3,6,9,2,4]}, index=list('ABCDEF')) print (df) timestamp B C D E A a 4 7 1 5 B b 5 8 3 3 C a 4 9 5 6 D d 5 4 7 9 E e 5 2 1 2 F f 4 3 0 4 idxlbls = df.index[df['timestamp'] == 'a'] stuff = df.loc[idxlbls, 'C':'E'] print (stuff) C D E A 7 1 5 C 9 5 6 a = df.index.get_indexer(stuff.index) Or get positions by boolean mask: a = np.where(df['timestamp'] == 'a')[0] print (a) [0 2] b = df.columns.get_indexer(stuff.columns) print (b) [2 3 4]
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89905885
score: 0
has comment: http://stackoverflow.com/comment/89905862
has comment: http://stackoverflow.com/comment/89905843
type: Answer
accepted answer of: http://stackoverflow.com/q/51468593
has comment: http://stackoverflow.com/comment/89905919
answers question: http://stackoverflow.com/q/51468593

http://stackoverflow.com/a/76293378
has body: In the /usr/local/lib/python3.10/dist-packages/keras_vggface/models.py in &lt;module&gt; file... Change this: keras.engine.topology import get_source_inputs To: keras.utils.layer_utils import get_source_inputs Reason: If you use the old module, you may encounter an error like module 'keras.engine' has no attribute 'Layer'
answers question: http://stackoverflow.com/q/51337558
type: Answer
score: 1
upvote count: 1
downvote count: 0

http://stackoverflow.com/q/51433272
has title: How to manage large size file?
upvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89837799
tagged with: linux
has comment: http://stackoverflow.com/comment/89837427
tagged with: memory-mapped-files
has comment: http://stackoverflow.com/comment/89837216
has comment: http://stackoverflow.com/comment/89837659
score: -1
has comment: http://stackoverflow.com/comment/89837291
type: UnansweredQuestion
has body: Disk file size of 600+ MB continuously appended by multiple agents. Below code open and reads this large size file, def alert_entries(): with open('large_size_file') as f: .... .... for entry in entry_re.findall(f.read()): yield entry Machine goes slow after opening this file. How to manage opening and reading large size file, memory efficiently?
tagged with: mmap
tagged with: python
has comment: http://stackoverflow.com/comment/89837410
has comment: http://stackoverflow.com/comment/89837746
downvote count: 1
has answer: http://stackoverflow.com/a/51433425
linked to: http://stackoverflow.com/q/519633
has comment: http://stackoverflow.com/comment/89837379
has comment: http://stackoverflow.com/comment/89837236
has comment: http://stackoverflow.com/comment/89837312
type: Question

http://stackoverflow.com/q/51444413
has comment: http://stackoverflow.com/comment/89859234
upvote count: 5
answer count: 5
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/67634946
downvote count: 0
has answer: http://stackoverflow.com/a/55253962
has answer: http://stackoverflow.com/a/71965549
type: Question
tagged with: matplotlib
has answer: http://stackoverflow.com/a/51897676
score: 5
has body: I have written a Python 3.6 program that reads a .txt file of UTM coordinates, sorts them into counterclockwise order, displays the coordinates on a graph using matplotlib, and then writes the coordinates to a .txt file on the desktop. It works fine when I run it in spyder, which is the IDE that I have been using, but when I convert it to an exe using cx_Freeze (by building my python file) and try to run it, I get the following error: ModuleNotFoundError: No module named 'matplotlib.backends.backend_qt5agg' I have tried installing the Qt5 backend by doing: pip install PyQt5 As well as updating cx_Freeze. Any help would be much appreciated. I am still a beginner with Python as well as programming in general so I apologize if I was not clear enough in my explantion. Below is my code for my main Python script import matplotlib matplotlib.use('Qt5Agg') import matplotlib.pyplot as plt import math as math import tkinter as tk from tkinter.filedialog import askopenfilename import time def findFilename(): root = tk.Tk() #root.withdraw() filename = askopenfilename() root.destroy() return(filename) def findSize(cnt, filename): #number of lines in file with open(filename) as f: for line in f: cnt = cnt+1; return cnt; def findChar(filename): file = open(filename, "r") char = "" lines = file.read() if(lines.find(" ") == -1): char = "," else: char = " " return(char) def inputArr(cnt, arrX, arrY, arrZ, filename, char): file = open(filename, "r") num1 = 0 num2 = 0 num3 = 0 place1 = 0 place2 = 0 place3 = 0 for i in range(0, cnt): num = file.readline() place1 = num.find(char) num1 = num[:place1] num = num[place1 + 1:] place2 = num.find(char) num2 = num[:place2] num = num[place2+1:] place3 = num.find(char) num3 = num[:place3] arrX.append(float(num1)) arrY.append(float(num2)) arrZ.append(float(num3)) return(arrX, arrY, arrZ) def drawPath(arrX, arrY, label, cnt): plt.plot(arrX, arrY, '-ok', color = 'red') plt.xlabel("X coordinates") plt.ylabel("Y coordinates") plt.title("Loop path") plt…
has answer: http://stackoverflow.com/a/51444612
has title: Matplotlib Qt5Agg backend not found
favorite count: 0
tagged with: cx-freeze
tagged with: python-3.x

http://stackoverflow.com/a/51466415
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89901348
accepted answer of: http://stackoverflow.com/q/51466325
answers question: http://stackoverflow.com/q/51466325
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89901573
type: Answer
has body: Using the data of your example, I would do the following: import matplotlib.pyplot as plt l_ext = [ [0.3, 2.18327756], [0.8, 0.78647796], [1.3, 1.0077252 ], [1.8, 2.40453182], [2.3, 2.18328295], [2.8, 0.7864866 ], [3.3, 1.00775437], [3.8, 2.40455773], [4.3, 2.18328834], [4.8, 0.78649524], [5.3, 1.00778353], [5.8, 2.40458364], [6.3, 2.18329373], [6.8, 0.78650388], [7.3, 1.00781269], [7.8, 2.40460955], [8.3, 2.18329912], [8.8, 0.78651252], [9.3, 1.00784186]] r_ext = [ [0.7, 1.00769604], [1.2, 0.78646933], [1.7, 2.18327218], [2.2, 2.40448 ], [2.7, 1.00766689], [3.2, 0.78646069], [3.7, 2.18326679], [4.2, 2.40445409], [4.7, 1.00763773], [5.2, 0.78645206], [5.7, 2.18326141], [6.2, 2.40442819], [6.7, 1.00760858], [7.2, 0.78644343], [7.7, 2.18325603], [8.2, 2.40440228], [8.7, 1.00757942], [9.2, 0.7864348 ], [9.7, 2.18325065]] for left, right in zip(l_ext, r_ext): print left, right plt.plot( [left[0],right[0]], [left[1],right[1]], 'k') plt.show() which produces the following plot:

http://stackoverflow.com/comment/89932330
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51481747
has text: Why do you need to delete the line? Can't you just loop on the lines and use them one after the others until EOF?

http://stackoverflow.com/q/51424392
downvote count: 2
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/89819887
favorite count: 0
has comment: http://stackoverflow.com/comment/89819948
tagged with: python
has comment: http://stackoverflow.com/comment/89821022
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51424517
accepted answer: http://stackoverflow.com/a/51424517
has body: I have to classes like below. class Reports() _name = 'reports' def fetch_transaction_invoice(): #any logic here class Bar(): _name = 'bar' def test_method(): # here i want to access fetch_transaction_invoice of Reports class. but when i try like following class Bar(): _name = 'bar' def test_method(): Reports.fetch_transaction_invoice () it gives me error which is following. TypeError: unbound method fetch_transaction_invoice() must be called with Reports instance as first argument (got nothing instead)
has title: Create instance of class inside other class
has comment: http://stackoverflow.com/comment/89820232
type: Question
has comment: http://stackoverflow.com/comment/89820834
score: -1
has comment: http://stackoverflow.com/comment/89819863

http://stackoverflow.com/comment/89684844
score: 0
type: Comment
type: QuestionComment
has text: You risk downvotes for saying "C/C++" without a very good explanation why both languages are relevant for your question. (I did not downvote by the way.)
comment on: http://stackoverflow.com/q/51356315

http://stackoverflow.com/a/51447226
accepted answer of: http://stackoverflow.com/q/51447147
has body: You don't have any kind of for loop in your template, so naturally it will only show one user. You need to iterate over the users collection that you passed from the view. {% for user in users %} {{ user.userprofile.jersey_number }} {{ user.get_full_name }} {{ user.userprofile.position }} {{ user.userprofile.grade }} {% endfor %}
answers question: http://stackoverflow.com/q/51447147
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/89864900
upvote count: 1
score: 1

http://stackoverflow.com/a/51351988
accepted answer of: http://stackoverflow.com/q/51351936
type: Answer
has body: You should set the input as the variable, and send that variable to the functions. Like: x = input('please enter a selection') and then define your function def s(x): print('you selected: ' + x)
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51351936
has comment: http://stackoverflow.com/comment/89676777
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89684641
type: QuestionComment
has text: Can you show us what you have tried?
comment on: http://stackoverflow.com/q/51356244
score: 0
type: Comment

http://stackoverflow.com/q/51419763
tagged with: python
has title: Python grpcio best programming practice
type: Question
score: 0
has comment: http://stackoverflow.com/comment/90137497
has body: There is a topic talking about best practic https://github.com/grpc/grpc-go/issues/682 But I am not sure at last, How to use grpcio in my program. I am using tensorflow-serving which is base on GRPC. My client is based on python sdk grpcio-1.8.3. The client program is a Flask server with many APIs each of them holds identical channel and stub. When the tensorflow-serving(the GRPC server) restart, the client program will failed into "Endpoint read failed" and would not recover any more. But when I upgrade the grpcio to newer version, The bug seems fixed, so that the client can reconnect automatically. And if the grpcio client, namely the Flask server holds one channel and stub globally, the error seems never appears. But I am still not sure what is the best way to program with grpc client SDK like grpcio, stable and high performance. Because there are even no exception testings on those examples, not to mention about how to use multiple channels and stubs in one process.
has comment: http://stackoverflow.com/comment/90141746
has comment: http://stackoverflow.com/comment/90018680
answer count: 0
type: UnansweredQuestion
tagged with: grpc-python

apscheduler
tags question: http://stackoverflow.com/q/51459386
tag name: apscheduler
tags question: http://stackoverflow.com/q/51369857
type: Tag

http://stackoverflow.com/comment/89848055
comment on: http://stackoverflow.com/a/51437932
type: AnswerComment
score: 0
type: Comment
has text: I have changed it. I copied the python2 example! oops!

http://stackoverflow.com/comment/89770222
score: 0
comment on: http://stackoverflow.com/q/51397212
type: Comment
type: QuestionComment
has text: Not sure what the problem is. You can draw a contour plot with `plt.contour`. In how far does that no work?

http://stackoverflow.com/comment/89778088
type: AnswerComment
score: 0
type: Comment
has text: Maybe something like this? In checkbox "onclick" i'm passing the necessary variables through function? and then myCuteFunction automatically generates url? but inside function? Or should i pass full url?
comment on: http://stackoverflow.com/a/51403226

http://stackoverflow.com/q/51470200
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51470365
downvote count: 1
tagged with: sqlalchemy
type: Question
score: -1
has body: I am doing CS50 project and the current task is to create a register page. User fills in the form and presses button. So it has to be insert into my PostgreSQL database. But when I fill the form and press 'Register' I got this error: StatementError: (sqlalchemy.exc.InvalidRequestError) A value is required for bind parameter u'surname' [SQL: u'INSERT INTO users (name, surrname, nickname, password) VALUES (%(name)s, %(surname)s,%(nickname)s, %(password)s'] [parameters: [{':password': u'', ':name': u'John', ':surname': u'Young', ':nickname': u'yolojohny1'}]] (Background on this error at: http://sqlalche.me/e/cd3x) books.py import os from flask import Flask, session, render_template, request from flask_session import Session from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker app = Flask(__name__) # Check for environment variable if not os.getenv("DATABASE_URL"): raise RuntimeError("DATABASE_URL is not set") # Configure session to use filesystem app.config["SESSION_PERMANENT"] = False app.config["SESSION_TYPE"] = "filesystem" Session(app) # Set up database engine = create_engine(os.getenv("DATABASE_URL")) db = scoped_session(sessionmaker(bind=engine)) @app.route("/") def index(): return render_template("register.html") @app.route('/register', methods=["POST"]) def register(): "REGISTRATION PROCESS" # Get form information name = request.form.get("name") surname = request.form.get("surname") nickname = request.form.get("nickname") password = request.form.get("password") db.execute("INSERT INTO users (name, surrname, nickname, password) VALUES (:name, :surname," ":nickname, :password", {":name": name, ":surname": surname, ":nickname": nickname, ":password": password}) db.commit() return render_template("success.html") register.html: {% extends "layout.html" %} {% block title %} New User {% endblock %} {% block body %} Register new account Create account! {% endblock %} database: CREATE TABLE "users" ( id SERIAL PRIMARY KEY, name VAR…
tagged with: flask
accepted answer: http://stackoverflow.com/a/51470365
upvote count: 0
answer count: 1
has title: Cannot insert row using Flask and SQLAlchemy
favorite count: 0
tagged with: postgresql
tagged with: python

http://stackoverflow.com/comment/89692458
type: QuestionComment
has text: What should be the desired behaviour in case the value of `prefix` changes?
comment on: http://stackoverflow.com/q/51360098
score: 1
type: Comment

http://stackoverflow.com/a/51458614
upvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51458555
type: Answer
has body: This happens when the disallow_any_explicit is set to True for that module in the configuration file. Just remove that option for the default False.
downvote count: 1
has comment: http://stackoverflow.com/comment/125905166
score: -1
has comment: http://stackoverflow.com/comment/130022003
answers question: http://stackoverflow.com/q/51458555

http://stackoverflow.com/comment/89749555
score: 0
has text: What is the constraint on number of points?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51380580

http://stackoverflow.com/a/51482306
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51482178
accepted answer of: http://stackoverflow.com/q/51482178
type: AcceptedAnswer
downvote count: 0
has body: Since you know the starting index of where you want to move from and move to, we can use np.zeros_like and numpy indexing: h = w = 3 sub = image[0:0+w,4:4+h] out = np.zeros_like(image) Then assign: out[2:2+w, 2:2+h] = sub Output: array([[0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ], [0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ], [0. , 0. , 0.1, 0.3, 0.5, 0. , 0. , 0. ], [0. , 0. , 0.4, 0.4, 0.6, 0. , 0. , 0. ], [0. , 0. , 0.3, 0.3, 0.7, 0. , 0. , 0. ], [0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ]])

http://stackoverflow.com/comment/89630939
has text: Do the proteins always start the same or they may overlap elsewhere? Is your file sorted? These assumptions could lead to a more efficient solution if they are true
comment on: http://stackoverflow.com/q/51327765
type: Comment
type: QuestionComment
score: 3

qpushbutton
type: Tag
tags question: http://stackoverflow.com/q/51443198
tags question: http://stackoverflow.com/q/51389423
tag name: qpushbutton

http://stackoverflow.com/comment/89628863
has text: If I'm not mistaken, `ctypes.c_byte(0)` just returns a single-byte value initialized to zero ? Which would explain while using it as a buffer doesn't work.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51325695
score: 0

http://stackoverflow.com/a/51403830
upvote count: 1
has body: The count method of the list object only takes 1 argument. The easiest to achieve what you are looking for is to use a simple addition: Numbers = [1, 2, 3, 4] print(Numbers.count(1) + Numbers.count(2)) # outputs 2
type: AcceptedAnswer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89816149
type: Answer
accepted answer of: http://stackoverflow.com/q/51403730
answers question: http://stackoverflow.com/q/51403730

http://stackoverflow.com/q/51327207
answer count: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/57693323
accepted answer: http://stackoverflow.com/a/51328346
possible better answer: http://stackoverflow.com/a/57693323
score: 4
linked to: http://stackoverflow.com/q/50863397
tagged with: python
tagged with: kalman-filter
tagged with: opencv
type: AnsweredQuestion
has body: The following code use to scan image from bottom to top. However, the prediction of Kalman filter always show 0,0 in first time. So that, it will draw line from bottom to 0,0. How to make path(Kalman filter) more similar to actual path? The following code and image was updated. import cv2 import matplotlib.pyplot as plt import numpy as np img = cv2.imread('IMG_4614.jpg',1) img = cv2.resize(img, (600, 800)) hsv_image = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) low_yellow = np.array([18, 94, 140]) up_yellow = np.array([48, 255, 255]) hsv_mask = cv2.inRange(hsv_image, low_yellow, up_yellow) hls_image = cv2.cvtColor(img, cv2.COLOR_BGR2HLS) low_yellow = np.array([0, 170, 24]) up_yellow = np.array([54, 255, 255]) hls_mask = cv2.inRange(hls_image, low_yellow, up_yellow) mask = np.logical_or(hsv_mask,hls_mask) offset = 100 height, width, _ = img.shape previousPos = h currentPos = h - offset finalImg = img.copy() is_first = True initState = np.array([[np.float32(int(width/2))], [np.float32(h)]], np.float32) last_measurement = current_measurement = initState last_prediction = current_prediction = np.array((2, 1), np.float32) kalman = cv2.KalmanFilter(4, 2) kalman.measurementMatrix = np.array([[1, 0, 0, 0], [0, 1, 0, 0]], np.float32) kalman.transitionMatrix = np.array([[1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0], [0, 0, 0, 1]], np.float32) while currentPos &gt;= 0: histogram = np.sum(mask[currentPos:previousPos,:], axis=0) areas = np.where(histogram &gt; 40) if areas[0].size &gt;= 2: bottomLeft = areas[0][0] topRight = areas[0][-1] x = int((topRight-bottomLeft) / 2 + bottomLeft) y = int((previousPos - currentPos) / 2 + currentPos) last_prediction = current_prediction last_measurement = current_measurement current_measurement = np.array([[np.float32(x)], [np.float32(y)]], np.float32) lmx, lmy = last_measurement[0], last_measurement[1] cmx, cmy = current_measurement[0], current_measurement[1] cv2.rectangle(finalImg, (bottomLeft,previousPos), (topRight,currentPos), (0,255,0), 5) cv2.circ…
tagged with: opencv3.0
has answer: http://stackoverflow.com/a/51328346
has title: KalmanFilter always predict 0,0 in first time
type: Question
upvote count: 4

http://stackoverflow.com/comment/89870356
type: Comment
has text: Thank you. This was exactly what I was trying to accomplish. I had seem some examples with def __unicode__ but not __str__. Thanks again.
comment on: http://stackoverflow.com/a/51448484
score: 1
type: AnswerComment

http://stackoverflow.com/q/51363116
answer count: 1
tagged with: unit-testing
has answer: http://stackoverflow.com/a/51390409
has body: I am trying to unit test some code using Mock. I would like to raise an exception, and test that the exception is caught and another function is called before it is re-raised except exception as e: car.create_log(car_details) raise e The unit test: car = Car() car.registrations.update = Mock() car.registrations.update.side_effect = RegistrationError() car.create_log = Mock() car.register_car('123123') car.create_log.assert_called_once() self.assertRaises(RegistrationError) I can confirm the method throws an error but cannot test that the method create_log is called before the error is re-raised.
has title: Mock assert function called before exception is thrown
tagged with: mocking
downvote count: 0
type: UnansweredQuestion
score: 1
type: Question
tagged with: python
favorite count: 0
upvote count: 1

http://stackoverflow.com/a/51402297
answers question: http://stackoverflow.com/q/51400919
type: Answer
downvote count: 1
has body: download pymongo files and run setup.py
upvote count: 0
score: -1

http://stackoverflow.com/q/51477961
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/51487322
has title: Flask + SQLAlchemy result to JSON
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/89926083
linked to: http://stackoverflow.com/q/5022066
tagged with: flask
has comment: http://stackoverflow.com/comment/89926143
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51487322
favorite count: 0
has comment: http://stackoverflow.com/comment/89937661
tagged with: python
type: AnsweredQuestion
has body: I'm new to Flask and SQLAlchemy and I have spent so much time trying to get my database query to present as JSON using a Flask url (not flask_restful). I thought I had it working by using n0nSmoker/SQLAlchemy-serializer. It worked using a simple query using this syntax selecting my Trade SQLAlchemy class: trades = Trade.query.all() I was able to return trades.to_dict() with no problem. However because I need to do a group_by, I need to use the more flexible syntax of db.session.query(Trade, Trade.exchange, Trade.trader....... etc this method stopped working. I have looked at other options like the inspection system but it seems a bit beyond my skill level. Plus it seems like some of the methods like _asdict() aren't available at the row level. I'm a bit lost and not sure how to proceed. Any help would be hugely appreciated. Edit: More code requested: top of app.py from flask import Flask from flask_restful import Resource, Api from models import * from flask_sqlalchemy import SQLAlchemy from sqlathanor import FlaskBaseModel, initialize_flask_sqlathanor app = Flask(__name__) app.config.from_pyfile('config.py') db = SQLAlchemy(model_class = FlaskBaseModel) db = initialize_flask_sqlathanor(db) class Trades(Resource): def get(self): return AllTrades() api.add_resource(Trades,'/') if __name__ == '__main__': app.run(host="0.0.0.0") from models.py from app import db class Trade(db.Model): id = db.Column(db.Integer, primary_key=True) exchange = db.Column(db.String(255)) trader = db.Column(db.String(255)) symbol = db.Column(db.String(255)) coin = db.Column(db.String(255)) order_id = db.Column(db.String(255)) price = db.Column(db.String(255)) qty = db.Column(db.String(255)) fee = db.Column(db.String(255)) fee_currency = db.Column(db.String(255)) order_time = db.Column(db.DateTime(timezone=False)) side = db.Column(db.String(255)) maker_taker = db.Column(db.String(255)) def AllTrades(): #t = Trade # trades = db.session.query( # t, # t.exchange, # t.trader, # t.symbol, # t.coin,…
score: 2
upvote count: 2

http://stackoverflow.com/comment/89931623
type: AnswerComment
comment on: http://stackoverflow.com/a/51481210
type: Comment
has text: Works, thank you ! COuld you just pls take a look at the 2 extras that I add to the question ?
score: 0

http://stackoverflow.com/a/51432191
answers question: http://stackoverflow.com/q/51432164
type: Answer
has comment: http://stackoverflow.com/comment/89835760
score: 1
upvote count: 1
has body: You can't convert it to ASCII because 'Â' is not part of the ASCII table. You need to decode it using the proper enconding. In this case, you should use latin1: foo = b'\xc2' bar = foo.decode('latin1')
downvote count: 0

http://stackoverflow.com/comment/89921547
comment on: http://stackoverflow.com/a/51476462
score: 0
type: Comment
has text: yep I got : TypeError: ('sequence item 0: expected str instance, Timestamp found', 'occurred at index 0') would I also need to subset my columns into a new df to apply this?
type: AnswerComment

http://stackoverflow.com/a/51447312
score: 3
has comment: http://stackoverflow.com/comment/89865537
answers question: http://stackoverflow.com/q/51447199
has body: As someone who transitioned from MATLAB to Python just over a year ago, you're not alone in going through the syntax learning curve. Once you've worked through a few examples, you start to get the hang of it. As @abarnert mentioned in the comments, simply instantiate your arrays as you have done: import numpy as np A = np.array([0, 0, 0, 0]) B = 1 C = 2 D = np.array([3, 4]) Then you can construct your output matrix as follows: E = np.matrix([A, [B, C, *D]]) Which gives: [[0 0 0 0] [1 2 3 4]]
has comment: http://stackoverflow.com/comment/89866248
downvote count: 0
has comment: http://stackoverflow.com/comment/89865608
type: Answer
upvote count: 3

http://stackoverflow.com/q/51358307
type: Question
upvote count: 2
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
downvote count: 1
has title: compare the next row value and change the current row value using pandas python
has body: any way of comparing a row value with the next row value and change the current row value using pandas? Basically in the the first Data frame DF1, in the value column, one of the value is '999', so the values of the next rows for that 'user-id' is less than the value '999'. so in this case i want to add '1000' which is 10^(len(999)) to the all successive values of that 'user-id'. I tried using shift, but I found that it skips one of the row value by giving a 'Null'. And I am also not sure how to do it without creating a new value. For example, if this is the data set I have, DF1 user-id serial-number value day 1 2 10 1 1 2 20 2 1 2 30 3 1 2 40 4 1 2 50 5 1 2 60 6 1 2 70 7 1 2 80 8 1 2 90 9 1 2 100 10 1 2 999 11 1 2 300 12 1 2 400 13 2 3 11 1 2 3 12 2 2 3 13 3 2 3 14 4 2 3 99 5 2 3 16 6 2 3 17 7 2 3 18 8 I need the resultant data frame to be DF1: user-id serial-number value day 1 2 10 1 1 2 20 1 1 2 30 1 1 2 40 1 1 2 50 1 1 2 60 1 1 2 70 1 1 2 80 1 1 2 90 1 1 2 100 1 1 2 999 1 1 2 1300 1 1 2 1400 1 . . 2 3 11 1 2 3 12 1 2 3 13 1 2 3 14 1 2 3 99 1 2 3 116 1 2 3 117 1 2 3 118 1 I think I've explained the question properly. similarly i want to do it for all the values in the "value" column for each user ID. Any suggestions?
favorite count: 0
has answer: http://stackoverflow.com/a/51361858
tagged with: python
type: UnansweredQuestion
score: 1

http://stackoverflow.com/comment/89854503
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51442354
type: AnswerComment
has text: No guarantee that the index is numeric, let alone integer. better off using `np.arange(len(df)) // 3 + 1`

http://stackoverflow.com/comment/89796424
type: QuestionComment
type: Comment
has text: Hi @BaileyParker thanks for your response. I have an internal process which takes a json object and maps it to a database table. The order of rows in the . table must match the exact sequence in the json. Unfortunately I cannot change the intermediate logic (it's a vendor product). The sequence of elements returned from the API is same as in the table. The response.json() method is changing it.
comment on: http://stackoverflow.com/q/51412225
score: 0

http://stackoverflow.com/a/65306276
type: Answer
score: 3
has body: First, remember to add the line pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files/Tesseract-OCR/tesseract.exe' where C:/Program Files/Tesseract-OCR/tesseract.exe is the location where your tesseract is installed. You have indicated that the image file is a string, which is ok, but you did not add an extension of the image! For example, you would have written image_file = 'location.png'. The extension jpeg, or any other format your image is holding. Then, instead of writing text = pyt.image_to_string(image_file), write text = pyt.image_to_string(img) because its an image you are parsing and not a string. The rest of the code is ok. Note: You may need to specify the exact location of the image; for example 'C:/Users/Dismas/Desktop/opencv-python/image_text.png' But if you still get the same problem, you can use the link How to install tesseract OCR. I followed the steps therein as they are. I had a similar problem like yours, but now I am sorted. The image below may be a good source of better understanding screenshot
upvote count: 3
answers question: http://stackoverflow.com/q/51364353
downvote count: 0

http://stackoverflow.com/q/51407524
has title: Pandas .loc[] method only returns only DataType not Series despite calling single index
favorite count: 0
has comment: http://stackoverflow.com/comment/89786890
downvote count: 0
has comment: http://stackoverflow.com/comment/89787693
type: AnsweredQuestion
has body: TL;DR: .loc[] returns DataFrame type all the time. Even when specifying single index. I've tried everything. This is driving me insane. I can't seem to reproduce it anywhere else. I've checked every Type of data that's beeing passed. Everything is as it should be. But no matter what I pass into the .loc[] it will return a DataFrame not series. import numpy as np import pandas as pd import datetime index_list = 'A B C D E F G H'.split() df = pd.DataFrame(data=None,index=index_list) k = 0 while k &lt;= 2: now = datetime.datetime.now().strftime('%H:%M:%S') df.loc[:,now] = 1 for i in index_list: print(df.loc[i]) print(type(df.loc[i])) k += 1 The code above will run with 0 errors and return Series Type of data. This is distilled code but it's exactly the same as the real one. Same flow, exaclty the same Type of data is beeing passed. 'now' is set as a column name and all the new values for every index is now 1. Next the script iterates trough the index_list and prints the type. The problem is that in the real script .loc will only return DataFrame type not Series. And I have no idea why. I even tried to manually enter the .loc index name to check if I'm not passing the wrong type of data. Still returned DataFrame. I'm 100% out of ideas of what I could be doing wrong. Maybe some of you have ideas? EDIT removed The original code. I found that if I call print(df.loc[i].iloc[0]) It will return the Series data for the column. print(type(df.loc[i].iloc[0])) Will print: 20:48:48 1 Name: (A,), dtype: int64 &lt;class 'pandas.core.series.Series'&gt; Why is the name (A,) a tuple?
score: 1
type: Question
has comment: http://stackoverflow.com/comment/89786452
answer count: 1
has answer: http://stackoverflow.com/a/51408310
accepted answer: http://stackoverflow.com/a/51408310
has comment: http://stackoverflow.com/comment/89786704
tagged with: pandas
upvote count: 1
has comment: http://stackoverflow.com/comment/89786475
tagged with: python

http://stackoverflow.com/q/51354191
tagged with: properties
has comment: http://stackoverflow.com/comment/89680973
type: Question
score: 2
has answer: http://stackoverflow.com/a/51354757
has answer: http://stackoverflow.com/a/51376599
has comment: http://stackoverflow.com/comment/89681611
has comment: http://stackoverflow.com/comment/89681052
has comment: http://stackoverflow.com/comment/89681064
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89681417
tagged with: python-3.6
favorite count: 0
linked to: http://stackoverflow.com/q/10149344
has title: Create python properties from an array, sharing getters and setters?
has comment: http://stackoverflow.com/comment/89681070
has body: I've been working on a python script where every time certain values are changed, a parallel value should be modified as well. For example: self.empire.gold = 345 self.empire.update_times.gold = time.time() Doing this every time was becoming a pain, so I've been researching how to make this happen automatically. This is what I came up with: import time class boring_object: pass class Object: def __init__(self, gold): self._gold = gold self._updates = boring_object() @property def gold(self): return self._gold @gold.setter def gold(self, value): self._gold = value self._updates.gold = time.time() Using this, I can automatically update the time. However, I want to apply similar setters to a bunch of other resources as well. I could duplicate this code five times to cover gold, grain, potatoes, etc., but I just want to pass in an array of the resource names to a constructor and have them share generic getters and setters. Is that possible? Before implementing any of this I'm using something closer to the boring_object(): class Object: def __init__(self, array): for each in array: setattr(self, each, 0) Besides for lacking the property functionality, this doesn't print() nicely. Bonus points for a solution that both allows for generic getters and setters and prints nicely without too much extra code. Once I wrote this up, I found this question about getters and setters. One answer suggested using __getattr__ and __setattr__, which would get me closer to my goal, but I don't want to store update times for and mutate all the attributes which I ultimately set on this object - just the ones named when I initialize it. Other attributes should behave as if there was no custom getter/setter logic.
has comment: http://stackoverflow.com/comment/89681736
has comment: http://stackoverflow.com/comment/89681082
tagged with: python
has comment: http://stackoverflow.com/comment/89681327
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/89680414
type: QuestionComment
comment on: http://stackoverflow.com/q/51353893
has text: This is too broad for the site. Please check out the [help/on-topic] to see which types of questions are appropriate for stack overflow.
type: Comment
score: 0

http://stackoverflow.com/q/51436746
answer count: 1
has body: I have built a network to predict 4 time series simultaneously, say [respiration, blood-pressure, pulse, spo2], using TimeDistributed layer in Keras. Before feeding into the network I normalize the series using sklearn.preprocessing.StandardScaler function. Here is a snapshot of original data and normalized data: Original: Normalized: resp sysbp pulse spo2 resp sysbp pulse spo2 18 111.5 71 97 -0.322154 -0.007753 -0.865683 0.051831 18 109.5 71 97 -0.322154 -0.067897 -0.865683 0.051831 19 122 70 97 -0.151163 0.308004 -0.922641 0.051831 18 128 72 98 -0.322154 0.488436 -0.808725 0.292901 18 125 71 96 -0.322154 0.39822 -0.865683 -0.189238 20 113 71 96 0.019828 0.037355 -0.865683 -0.189238 16 121 71 96 -0.664136 0.277932 -0.865683 -0.189238 20 119 71 97 0.019828 0.217788 -0.865683 0.051831 18 119 71.5 97 -0.322154 0.217788 -0.837204 0.051831 19 119 88 97 -0.151163 0.217788 0.102603 0.051831 16 119 88 97 -0.664136 0.217788 0.102603 0.051831 14 119 87 97 -1.006117 0.217788 0.045645 0.051831 19 119 88 98 -0.151163 0.217788 0.102603 0.292901 29 119 92 96 1.558744 0.217788 0.330435 -0.189238 The ranges before &amp; after normalization respectively are as follows: resp=[0,99] &amp; [-3.4,13.5], sysbp=[0,269] &amp; [-3.3,4.7], pulse=[0,204] &amp; [-4.9,6.7], spo2=[0,100] &amp; [-23.3,0.77] I have structured the data in timesteps of length 200, mentioned batch size as 100 and the number of dimensions, as we have seen above, is 4. Hence, the structure of my neural network looks like: batch_size=100 x = Input(batch_shape=(batch_size,200,4) , name='input') mask = Masking(mask_value=0., name='input_masked')(x) lstm1 = Bidirectional(LSTM(4, name="lstm1", dropout=0.25, recurrent_dropout=0.1, return_sequences=True, stateful=True))(mask) output1 = TimeDistributed(Dense(4, activation='relu'), name='output1')(lstm1) model = Model(inputs=x, outputs=output1) optimizer = Adam(lr=0.001) model.compile(optimizer=optimizer, loss='mean_absolute_error', metrics=['accuracy']) history = model.fit(X_t…
favorite count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 1
tagged with: tensorflow
has answer: http://stackoverflow.com/a/51440451
type: Question
upvote count: 0
has title: Which activation function to use for sequence prediction in a lstm network in Keras?
tagged with: neural-network
score: -1
tagged with: keras
tagged with: lstm

http://stackoverflow.com/comment/89872280
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51450883
has text: I have edited the question to make it easier to see the problem

http://stackoverflow.com/a/51428998
upvote count: 0
downvote count: 1
has body: What if you want to say "Hello, Adam. How are you?", You need to use print(my_function(name = 'Adam')) since using, print(my_function('Hello', 'Adam')) would be redundant. IMO, the second one is better, in case the parameter name ever changes. In this specific case it is. But in general I wouldn't say better, but rather different.
score: -1
answers question: http://stackoverflow.com/q/51428918
type: Answer

http://stackoverflow.com/a/51367068
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51366452
has comment: http://stackoverflow.com/comment/132999838
answers question: http://stackoverflow.com/q/51366452
has comment: http://stackoverflow.com/comment/92237671
type: Answer
has comment: http://stackoverflow.com/comment/89707654
has comment: http://stackoverflow.com/comment/137394073
has comment: http://stackoverflow.com/comment/92229300
has body: The with_suffix method will return a new path with a different extension, either changing an existing extension or adding a new one. Examples from the docs: &gt;&gt;&gt; p = PureWindowsPath('c:/Downloads/pathlib.tar.gz') &gt;&gt;&gt; p.with_suffix('.bz2') PureWindowsPath('c:/Downloads/pathlib.tar.bz2') &gt;&gt;&gt; p = PureWindowsPath('README') &gt;&gt;&gt; p.with_suffix('.txt') PureWindowsPath('README.txt') In your case, p.with_suffix(ext) would do the job. For cases where you need to add a suffix after any existing suffixes instead of removing existing suffixes, you can use p.with_suffix(p.suffix+ext). This is kind of clunky, though, and I don't know whether I would prefer it over Path(str(p)+ext).
has comment: http://stackoverflow.com/comment/92230582
upvote count: 137
score: 137

http://stackoverflow.com/comment/89880116
comment on: http://stackoverflow.com/a/51454865
score: 0
type: AnswerComment
has text: that is actually a really good idea. I didn't think about adding. Thank you!
type: Comment

http://stackoverflow.com/a/51460464
has comment: http://stackoverflow.com/comment/89908190
has body: If you kick out those vicious signs &lt;!--,--&gt; from the html elements, you can easily access the content. This is how you can go: import requests from bs4 import BeautifulSoup url = "https://www.baseball-reference.com/boxes/ANA/ANA201806180.shtml" res = requests.get(url) content = res.text.replace("&lt;!--","").replace("--&gt;","") soup = BeautifulSoup(content,"lxml") umpire, gametime, attendance, weather = soup.find_all(class_="section_content")[2]("strong") print(f'{umpire.next_sibling}\n{gametime.next_sibling}\n{attendance.next_sibling}\n{weather.next_sibling}\n') Output: HP - Greg Gibson, 1B - Jerry Layne, 2B - Jordan Baker, 3B - Vic Carapazza. 3:21. 33,809. 70° F, Wind 6mph out to Centerfield, Night, No Precipitation.
has comment: http://stackoverflow.com/comment/89906324
type: Answer
has comment: http://stackoverflow.com/comment/89908149
has comment: http://stackoverflow.com/comment/89905246
has comment: http://stackoverflow.com/comment/89906628
answers question: http://stackoverflow.com/q/51460053
score: 0
has comment: http://stackoverflow.com/comment/89908464

http://stackoverflow.com/comment/89860491
has text: are you able to see for example ' Conversion of loft to habitable room with hip to gable roof alterations, rear dormer and 3 front rooflights. Certificate of Lawful Development (proposed). 77 Furzehill Road Borehamwood Hertfordshire WD6 2DL Ref. No: 18/1443/CLP | Received: Thu 19 Jul 2018 | Validated: Thu 19 Jul 2018 | Status: Awaiting decision ' when you run the shell
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51442071
type: Comment

http://stackoverflow.com/q/51415626
tagged with: subprocess
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89802615
type: Question
has comment: http://stackoverflow.com/comment/89802498
has answer: http://stackoverflow.com/a/51416074
has comment: http://stackoverflow.com/comment/89802464
has title: how to run a command in python, supplying input, then reading the output
answer count: 1
has body: I want to use Popen from subprocess to execute the command: 'python3 test.py' # The following is test.py code: string = input('Enter Something') if string == 'mypassword': print('Success') else: print('Fail') In my program, I want to execute 'python3 test.py' multiple times, each time supplying input, and reading the output ('Success' or 'Fail') and storing it in a variable. My program that is suppose to execute 'python3 test.py' is as follows: from subprocess import Popen, PIPE # Runs test.py command = Popen(['python3', 'test.py'], stdin=PIPE) # After this, it prompts me to type in the input, # but I want to supply it from a variable # I want to do something like my_input = 'testpassword' command.supplyInput(my_input) result = command.getOutput() # result will have the string value of 'Success' or 'Fail'
score: 0
has comment: http://stackoverflow.com/comment/89802725
tagged with: python
has comment: http://stackoverflow.com/comment/89802694
tagged with: python-3.x

http://stackoverflow.com/a/51455331
upvote count: 1
has comment: http://stackoverflow.com/comment/89880123
has body: One approach would be the following: In [28]: df.groupby(df.complete.cumsum()).sum()[1:].num.values Out[28]: array([ 6.83, 1.24])
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51455280

http://stackoverflow.com/comment/89795656
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51411420
has text: Thank you! Do you know how they work as I have tried numerous times to get both working. The closest I got was masking a single time step but then I wasn’t sure how to concatenate all of the resulting DataArrays together. Plus it would have taken an age to run!
score: 0

http://stackoverflow.com/a/73514504
has body: Well, i was also facing the same issue. I was continuously getting server errors but then I figured out it was a simple error. go to the urls.py file from django.urls import path from . import views urlpatterns = [ path('', views.index, name = index), #the path for our index view ] I just had to remove name = index and the server worked with 0 errors. enter image description here
type: Answer
answers question: http://stackoverflow.com/q/51327457
score: 0

http://stackoverflow.com/comment/89744050
score: 0
type: Comment
type: QuestionComment
has text: How does the quantity available affect the solution you need?
comment on: http://stackoverflow.com/q/51386017

opencv
type: Tag
tags question: http://stackoverflow.com/q/51353893
tags question: http://stackoverflow.com/q/51335390
tags question: http://stackoverflow.com/q/51411210
tags question: http://stackoverflow.com/q/51421007
tags question: http://stackoverflow.com/q/51383462
tags question: http://stackoverflow.com/q/51470948
tags question: http://stackoverflow.com/q/51454896
tags question: http://stackoverflow.com/q/51365126
tags question: http://stackoverflow.com/q/51457194
tags question: http://stackoverflow.com/q/51329643
tags question: http://stackoverflow.com/q/51397843
tags question: http://stackoverflow.com/q/51401380
tags question: http://stackoverflow.com/q/51351315
tags question: http://stackoverflow.com/q/51410961
tags question: http://stackoverflow.com/q/51358325
tags question: http://stackoverflow.com/q/51468533
tags question: http://stackoverflow.com/q/51382471
tags question: http://stackoverflow.com/q/51343573
tags question: http://stackoverflow.com/q/51342774
tags question: http://stackoverflow.com/q/51475343
tags question: http://stackoverflow.com/q/51449589
tags question: http://stackoverflow.com/q/51362250
tags question: http://stackoverflow.com/q/51354637
tags question: http://stackoverflow.com/q/51462548
tags question: http://stackoverflow.com/q/51327207
tags question: http://stackoverflow.com/q/51440895
tags question: http://stackoverflow.com/q/51381661
tags question: http://stackoverflow.com/q/51393461
tags question: http://stackoverflow.com/q/51399274
tags question: http://stackoverflow.com/q/51372912
tags question: http://stackoverflow.com/q/51450028
tags question: http://stackoverflow.com/q/51448085
tags question: http://stackoverflow.com/q/51455805
tags question: http://stackoverflow.com/q/51329903
tag name: opencv
tags question: http://stackoverflow.com/q/51379376
tags question: http://stackoverflow.com/q/51386778
tags question: http://stackoverflow.com/q/51457734
tags question: http://stackoverflow.com/q/51390533
tags question: http://stackoverflow.com/q/51474421
tags question: http://stackoverflow.com/q/51380692
tags question: http://stackoverflow.com/q/51395070
tags question: http://stackoverflow.com/q/51349895
tags question: http://stackoverflow.com/q/51401475
tags question: http://stackoverflow.com/q/51424523
tags question: http://stackoverflow.com/q/51335082
tags question: http://stackoverflow.com/q/51474976
tags question: http://stackoverflow.com/q/51479523
tags question: http://stackoverflow.com/q/51413096
tags question: http://stackoverflow.com/q/51462910
tags question: http://stackoverflow.com/q/51418002
tags question: http://stackoverflow.com/q/51436675
tags question: http://stackoverflow.com/q/51448049
tags question: http://stackoverflow.com/q/51325461
tags question: http://stackoverflow.com/q/51411156
tags question: http://stackoverflow.com/q/51402207
tags question: http://stackoverflow.com/q/51329338
tags question: http://stackoverflow.com/q/51371421
tags question: http://stackoverflow.com/q/51433863
tags question: http://stackoverflow.com/q/51481991
tags question: http://stackoverflow.com/q/51465794
tags question: http://stackoverflow.com/q/51388043
tags question: http://stackoverflow.com/q/51352550
tags question: http://stackoverflow.com/q/51454239
tags question: http://stackoverflow.com/q/51332842
tags question: http://stackoverflow.com/q/51382573
tags question: http://stackoverflow.com/q/51481544
tags question: http://stackoverflow.com/q/51379912
tags question: http://stackoverflow.com/q/51395132
tags question: http://stackoverflow.com/q/51465037
tags question: http://stackoverflow.com/q/51437992
tags question: http://stackoverflow.com/q/51372922
tags question: http://stackoverflow.com/q/51465351
tags question: http://stackoverflow.com/q/51439435
tags question: http://stackoverflow.com/q/51460264
tags question: http://stackoverflow.com/q/51455622
tags question: http://stackoverflow.com/q/51408179
tags question: http://stackoverflow.com/q/51347194
tags question: http://stackoverflow.com/q/51409007

http://stackoverflow.com/comment/89648648
score: 1
has text: The error traceback doesn't lie - the `decrypt` function is being called in line 140, and the error is inside it
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51336785

arima
tags question: http://stackoverflow.com/q/51370531
tag name: arima
type: Tag
tags question: http://stackoverflow.com/q/51400402

http://stackoverflow.com/a/51465830
has body: You are doing binary classification. result has shape [batch_size,1]. So if you are doing argmax() you will always get 0. &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; result = np.random.rand(5,1) &gt;&gt;&gt; result array([[ 0.54719484], [ 0.31675804], [ 0.55151251], [ 0.25014937], [ 0.00724972]]) &gt;&gt;&gt; result.argmax(axis=-1) array([0, 0, 0, 0, 0]) &gt;&gt;&gt; (result &gt; 0.5).astype(int) array([[1], [0], [1], [0], [0]]) &gt;&gt;&gt;
answers question: http://stackoverflow.com/q/51465526
type: Answer
has comment: http://stackoverflow.com/comment/89900303
score: 9
upvote count: 9
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51465526

http://stackoverflow.com/q/51463139
has comment: http://stackoverflow.com/comment/89895159
favorite count: 0
has comment: http://stackoverflow.com/comment/89895331
tagged with: python-3.x
tagged with: tkinter
has comment: http://stackoverflow.com/comment/89895571
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/89895517
type: Question
upvote count: 2
has body: I'm currently reading the book "Python GUI Programming Cookbook" and i programmed this code. import tkinter #1 from tkinter import scrolledtext #2 win=tkinter.Tk() #3 src=scrolledtext.ScrolledText(win,width=30,height=4,wrap=tkinter.CHAR) #4 scr.grid(column=0, columnspan=3) #5 win.mainloop() #6 but the problem is when comment out second line and replace line 4 with: #from tkinter import scrolledtext src=tkinter.scrolledtext.ScrolledText(win,width=30,height=4,wrap=tkinter.CHAR) python gives me error: AttributeError: module 'tkinter' has no attribute 'scrolledtext' aren't this tow line have the same meaning
has title: why "tkinter.scrolledtext.ScrolledText() doesn't work and i have to explecitly import it first like "from tkinter import scrolledtext"

http://stackoverflow.com/comment/89863507
has text: Possible duplicate of [Text File Parsing with Python](https://stackoverflow.com/questions/11936967/text-file-parsing-with-python)
score: 0
comment on: http://stackoverflow.com/q/51446622
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89757261
has text: Actually, the complexity of the algorithm you suggest is O((M^2)*(N^2)). You parse through a matrix of M^2 places and, whenever a value of 1 is found, you parse through another matrix of N^2 places. Worst case, you can find M^2 ones (MxM matrix is all ones).
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51392673
type: QuestionComment

http://stackoverflow.com/comment/89955891
has text: I know what the property is, but by writing "User.id" e.g., I can get id of each user model for which the update is going to be executed.
type: Comment
comment on: http://stackoverflow.com/a/51485849
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89790622
type: QuestionComment
has text: Missing parenthesis on `print(bool("")`.
score: 0
comment on: http://stackoverflow.com/q/51409601
type: Comment

http://stackoverflow.com/a/51371949
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51371771
answers question: http://stackoverflow.com/q/51371771
has body: Before getting into any of this: As chepner pointed out in a comment, this input looks like, and therefore is probably intended to be, JSON. Which means you shouldn't be parsing it with regular expressions; just parse it as JSON: &gt;&gt;&gt; s = ''' {"text": "Love this series!\ufeff", "time": "Hace 11 horas", "author": "HasRah", "cid": "UgyvXmvSiMjuDrOQn-l4AaABAg"}''' &gt;&gt;&gt; obj = json.loads(s) &gt;&gt;&gt; obj['author'] 'HasRah' Actually, it's not clear whether your input is a JSON file (a file containing one JSON text), or a JSONlines file (a file containing a bunch of lines, each of which is a JSON text with no embedded newlines).1 For the former, you want to parse it like this: obj = json.load(st) For the latter, you want to loop over the lines, and parse each one like this: for line in st: obj = json.loads(line) … or, alternatively, you can get a JSONlines library off PyPI. But meanwhile, if you want to understand what's wrong with your code: The error message is telling you the problem, although maybe not in the user-friendliest way: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.7/re.py", line 148, in search return _compile(pattern, flags).search(string) TypeError: expected string or bytes-like object See the docs for search make clear: re.search(pattern, string, flags=0) Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding MatchObject instance… You haven't passed it a string, you've passed it a list of strings. That's the whole point of readlines, after all. There are two obvious fixes here. First, you could read the whole file into a single string, instead of reading it into a list of strings: s = st.read() u = re.search('%s(.*)%s' % (start, end), s).group(1) Alternatively, you could loop over the lines, trying to match each one. And, if you do this, you still don't need readlines(), because a file is already an i…
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51369722
has answer: http://stackoverflow.com/a/51370078
tagged with: python
tagged with: kivy
tagged with: python-3.x
has body: Very simple question I might just not be comprehending life, self.ids.UpdateCustomer1.add_widget(TextInput(text='123',id=str('AddUserTextBox'))) Here is my code, I just want to set the id of a dynamic text box that pops up when a button is pressed. that all works fine, but whenever I reference AddUserTextBox.text it tells me its non-existent. or more specifically " NameError: name 'AddUserTextBox' is not defined" Now I have tried setting id='AddUserTextBox' and also as id=AddUserTextBox and I have had no luck. all help would be greatly appreciated
score: 0
type: UnansweredQuestion
type: Question
has title: How to set ID of dynamic TextInput in Kivy
has answer: http://stackoverflow.com/a/51370359
answer count: 2

http://stackoverflow.com/comment/89836987
type: Comment
type: QuestionComment
has text: maybe `df.groupby(['Year', 'Month']).temp.mean()` ?
score: 1
comment on: http://stackoverflow.com/q/51433040

http://stackoverflow.com/a/51457945
accepted answer of: http://stackoverflow.com/q/51457803
upvote count: 8
answers question: http://stackoverflow.com/q/51457803
has body: Using pivot_table df.pivot_table(index=['First','Last'],columns='Group',values='Measure',fill_value=0) Out[247]: Group A B First Last Jane Doe 0 11 John Smith 2 0 Mary Johnson 1 0
type: AcceptedAnswer
score: 8
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/89885268
has comment: http://stackoverflow.com/comment/89885217

http://stackoverflow.com/comment/89910425
score: 2
comment on: http://stackoverflow.com/q/51471020
has text: The relevant phrase is "chained comparison"; there are lots of Q/A pairs already on the site, but it's hard to know what phrase to google first.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51476569
has comment: http://stackoverflow.com/comment/89921696
has body: You can use a list comprehension with str.join: bad_vals = {'', 'Nan'} df['C_Memo'] = [', '.join([i for i in row if i not in bad_vals]) for row in df.values] print(df) ID role subject C_Memo 0 123 Teacher Eng 123, Teacher, Eng 1 444 Math 444, Math 2 NaN Dr Science Dr, Science This is not necessarily worse than pd.DataFrame.apply, which has overheads associated with iterating over pd.Series objects for each row.
downvote count: 0
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51476150

http://stackoverflow.com/a/51445041
upvote count: 4
has comment: http://stackoverflow.com/comment/89920478
answers question: http://stackoverflow.com/q/51438232
downvote count: 0
has body: It turns out this is possible. We need a pointer do the data, which needs some additional capabilities: class Holder(PointerHolderBase): def __init__(self, tensor): super().__init__() self.tensor = tensor self.gpudata = tensor.data_ptr() def get_pointer(self): return self.tensor.data_ptr() def __int__(self): return self.__index__() # without an __index__ method, arithmetic calls to the GPUArray backed by this pointer fail # not sure why, this needs to return some integer, apparently def __index__(self): return self.gpudata We can then use this class to instantiate GPUArrays. The code uses Reikna arrays which are a subclass but should work with pycuda arrays as well. def tensor_to_gpuarray(tensor, context=pycuda.autoinit.context): '''Convert a :class:`torch.Tensor` to a :class:`pycuda.gpuarray.GPUArray`. The underlying storage will be shared, so that modifications to the array will reflect in the tensor object. Parameters ---------- tensor : torch.Tensor Returns ------- pycuda.gpuarray.GPUArray Raises ------ ValueError If the ``tensor`` does not live on the gpu ''' if not tensor.is_cuda: raise ValueError('Cannot convert CPU tensor to GPUArray (call `cuda()` on it)') else: thread = cuda.cuda_api().Thread(context) return reikna.cluda.cuda.Array(thread, tensor.shape, dtype=torch_dtype_to_numpy(tensor.dtype), base_data=Holder(tensor)) We can go back with this code. I have not found a way to do this without copying the data. def gpuarray_to_tensor(gpuarray, context=pycuda.autoinit.context): '''Convert a :class:`pycuda.gpuarray.GPUArray` to a :class:`torch.Tensor`. The underlying storage will NOT be shared, since a new copy must be allocated. Parameters ---------- gpuarray : pycuda.gpuarray.GPUArray Returns ------- torch.Tensor ''' shape = gpuarray.shape dtype = gpuarray.dtype out_dtype = numpy_dtype_to_torch(dtype) out = torch.zeros(shape, dtype=out_dtype).cuda() gpuarray_copy = tensor_to_gpuarray(out, context=context) byte_size = gpuarray.itemsize * gpuarray.size pycuda.…
type: AcceptedAnswer
score: 4
accepted answer of: http://stackoverflow.com/q/51438232
type: Answer
has comment: http://stackoverflow.com/comment/89916863

http://stackoverflow.com/a/51371428
type: Answer
upvote count: 4
has body: First, have a look at the data that your classifiers are seeing. Measure the correlation between features and the class (Pearson correlation is fine) and check if you have irrelavant features. For example, the word patient is not usually considered a stopword, but in a medical database, it will most likely be one. Also consider using more complex features, like bigrams or trigrams, or even adding word embeddings (e.g., take a pretrained model such as word2vec or GloVe, and then take the average text vector). N.B.: These days text classification is mostly done with neural networks and word embeddings. That said, your dataset isn't very big, so it may not be worth it to change methods (or maybe you don't want to, for some reason).
accepted answer of: http://stackoverflow.com/q/51371356
answers question: http://stackoverflow.com/q/51371356
score: 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51425300
has body: I want to speed up the cosine distance calculation scipy.spatial.distance.cosine as much as possible so I tried to use numpy def alt_cosine(x,y): return 1 - np.inner(x,y)/np.sqrt(np.dot(x,x)*np.dot(y,y)) I tried cython from libc.math cimport sqrt def alt_cosine_2(x,y): return 1 - np.inner(x,y)/sqrt(np.dot(x,x)*np.dot(y,y)) and get improvements gradually (test on numpy arrays with length 50) &gt;&gt;&gt; cosine() # ... make some timings 5.27526156300155e-05 # mean calculation time for one loop &gt;&gt;&gt; alt_cosine() 9.913400815003115e-06 &gt;&gt;&gt; alt_cosine_2() 7.0269494536660205e-06 What is the fastest way to do this? Unfortunately, I was not able to specify variable types to alt_cosine_2, I will use this function with numpy arrays with type np.float32
answer count: 2
has answer: http://stackoverflow.com/a/51431661
tagged with: trigonometry
has answer: http://stackoverflow.com/a/51426811
downvote count: 0
linked to: http://stackoverflow.com/q/49058949
has comment: http://stackoverflow.com/comment/89822653
favorite count: 0
has title: Python fast cosine distance with cython
possible better answer: http://stackoverflow.com/a/51426811
tagged with: python
accepted answer: http://stackoverflow.com/a/51431661
type: AnsweredQuestion
tagged with: cython
type: Question
tagged with: numpy
score: 4
upvote count: 4

http://stackoverflow.com/q/51374926
score: 0
answer count: 1
has body: I am writing the Automated script to work with angular and non-angular applications - in fact, once browser is opened, it will have a few re-directions before it gets to needed page with an angular app. I can handle it by timeouts and selenium, but i cannot find ng-model elements. I am trying now: Code Updated 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.keys import Keys from pytractor.webdriver import Ie wd = Ie(base_url='http://localhost:8080/base_url', script_timeout=50) #timeout does not work here by some reason wd.ignoreSynchronization = True wd.get('link') time.sleep(40) Also, due to synchronization page does not load further And in the end i am receiving: AngularNotFoundException: Message: Angular could not be found on page: link : retries looking for angular exceeded Any advice? Thank you in advance. The structure of the web-part i am trying to attend is (in stars ***********): WBSE Number WBSE Description Project Profile Line Item - Material Code Details Time of Supply Material Sales Text / Line Item Text Quantity Display Quantity? Material Code Type Additional Information Line Item Category Tax Condition Type Amount Are you contractually obligated to bill reimbursable expenses as services revenue? (This is not common) Amount of expenses to bill as fees Condition Type 2 -- None -- A6WG1001 -- None -- Consulting Outsourcing -- None -- 000010 - S00600 - Services 000020 - S06600 - Reimbursable Expenses Yes No -- None -- Fees Expenses ** ** ***************** ******************** -- None -- Yes No -- None -- A6WG1001 -- None -- Consulting Outsourcing -- None -- 000010 - S00600 - Services 000020 - S06600 - Reimbursable Expenses Yes No -- None -- Fees Expenses ****************** ***************** -- None -- Yes No
has comment: http://stackoverflow.com/comment/89732492
has comment: http://stackoverflow.com/comment/89732105
tagged with: python
has comment: http://stackoverflow.com/comment/89736981
has answer: http://stackoverflow.com/a/51382775
tagged with: angularjs
has comment: http://stackoverflow.com/comment/89731905
type: UnansweredQuestion
tagged with: selenium
has title: Pytractor throwing find_element_by_model() missing 1 required positional argument: 'descriptor'
tagged with: protractor
has comment: http://stackoverflow.com/comment/89730533
tagged with: selenium-iedriver
type: Question

http://stackoverflow.com/q/51392880
type: Question
answer count: 1
has body: As shown in the below picture,there's an excel sheet and about 2,000 URLs of cover images in the F column. What I want to do is that downloading the pictures with the URLs and replace the URL with the image correspondingly. Download,Insert the pictures into F column and remove the URLs automatically. How to complement it with Python ? Any suggestion or code is welcomed.Thanks.
favorite count: 0
tagged with: python
linked to: http://stackoverflow.com/q/30229231
tagged with: download
type: UnansweredQuestion
downvote count: 2
upvote count: 1
linked to: http://stackoverflow.com/q/16476924
has title: Python: How to download images with the URLs in the excel and replace the URLs with the pictures?
tagged with: excel
has comment: http://stackoverflow.com/comment/89757844
has answer: http://stackoverflow.com/a/51393002
score: -1
tagged with: image

http://stackoverflow.com/q/51423101
has title: How to create a Whoosh custom weight function?
score: 2
type: Question
answer count: 1
downvote count: 0
tagged with: whoosh
has body: I want to create a function that combines two approaches for ranking results. The first is based on the position and the second is BM25F. In whoosh documentation, I found out that I can pass scoring.FunctionWeighting(custom_function) as a keyword argument to my searcher. My custom function is : def position_weight(searcher, fieldname, text, matcher): poses = matcher.value_as("positions") w1 = 1.0 / (poses[0] + 1) # w2 = BM25F(matcher) ? This is what I don't know how to do. return 0.25 * w1 + 0.75 * w2 I got this function from documentation, so I don't understand the arguments of this function.
favorite count: 0
has answer: http://stackoverflow.com/a/69841302
upvote count: 2
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/89859073
comment on: http://stackoverflow.com/q/51443725
score: 1
has text: @Lxndr your problem has been asked plenty of times actually (the interval problem). Definetly dont need a loop to do this. Will get very slow as your data frame size increases
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89789223
comment on: http://stackoverflow.com/q/51408105
score: 0
has text: No luck unfortunately
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51460605
has comment: http://stackoverflow.com/comment/89900421
upvote count: 3
answers question: http://stackoverflow.com/q/51439968
has comment: http://stackoverflow.com/comment/101122546
type: AcceptedAnswer
type: Answer
score: 3
downvote count: 0
has body: Try to change your code in the following way: video = rnn.predict(input_fn = lambda:misc.input_fn_eval(1)) The problem is that you have to call input_fn_eval from input_fn. Then all the tensors created by that function belong to the graph created by Estimator You could find similar issues here and here
accepted answer of: http://stackoverflow.com/q/51439968

http://stackoverflow.com/a/79110143
score: 0
has comment: http://stackoverflow.com/comment/139497330
type: Answer
answers question: http://stackoverflow.com/q/51423139
has body: Right answer has link, which is not working. May be, such outside link, can be used for hacking, at a later point of time, by manipulating contents in that link.

http://stackoverflow.com/comment/89925956
type: Comment
comment on: http://stackoverflow.com/a/51478666
type: AnswerComment
has text: i got new error with new command. @FiveStarBot.command(pass_context=True) @commands.check(user_is_me) async def message(cxt, member: discord.Member, *, text : str): print('\n[Лог использования команды !message]') print('Отправитель: ', cxt.message.author, ' Получатель: ', member, ' Текст: ', text) await FiveStarBot.send_message(member, text) Error: AttributeError: 'Command' object has no attribute 'check'
score: 0

http://stackoverflow.com/comment/89927828
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51477226
type: Comment
has text: I deleted tensorflow and keras with pip. then i tried a pip install --upgrade tensorflow-gpu, and then it worked ! Now my training is taking 2 mins/epoch instead of 23 mins. I still didn't really understand why it worked but nevermind. Thank you for Help !

http://stackoverflow.com/a/51456856
downvote count: 1
has body: I just had a similar problem with Navigator. I typed anaconda-navigator on the command line and it opened fine. This doesn't explain why it won't open from the icon but does offer a work-around.
score: 0
answers question: http://stackoverflow.com/q/51435579
type: Answer
upvote count: 1

http://stackoverflow.com/a/51469641
type: Answer
has comment: http://stackoverflow.com/comment/89944982
has comment: http://stackoverflow.com/comment/89910335
has comment: http://stackoverflow.com/comment/89908271
score: 3
has comment: http://stackoverflow.com/comment/89907850
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51469622
has body: You can use a nested dictionary comprehension: List1 = [{"Value": "Value1", "Start": 7.11, "End": 8}, {"Value": "Value2", "Start": 16.45, "End": 20}] List2 = [{"From":7.11, "To": 8, "Result": 0}, {"From":16.45, "To": 20, "Result": 1} ] new_list = [{**a, **{'Result':b['Result']}} for a, b in zip(List1, List2)] Output: [{'Value': 'Value1', 'Start': 7.11, 'End': 8, 'Result': 0}, {'Value': 'Value2', 'Start': 16.45, 'End': 20, 'Result': 1}] Since, dictionary unpacking (**) is a feature in Python3 only, you can use dict.items in Python2: new_list = [dict(a.items()+[('Result', b['Result'])]) for a, b in zip(List1, List2)] Output: [{'Start': 7.11, 'End': 8, 'Result': 0, 'Value': 'Value1'}, {'Start': 16.45, 'End': 20, 'Result': 1, 'Value': 'Value2'}]
answers question: http://stackoverflow.com/q/51469622

http://stackoverflow.com/comment/89643263
comment on: http://stackoverflow.com/q/51333966
has text: Whatever happened to `for i in range(len(foo)): foo[i].sort()`?
type: Comment
type: QuestionComment
score: 3

http://stackoverflow.com/a/51417578
type: Answer
upvote count: 1
score: 1
has body: Update: newer Scapy versions have support for on-the-flow netflow v9 parsing (use the GitHub master version). # Live / on-the-flow / other: use NetflowSession &gt;&gt;&gt; sniff(session=NetflowSession, prn=[...]) Original post: Netflow v9 is a poor format, because each packet needs some previous packets to be dissected. Scapy does not support this functionality on-the-go, but it instead provides a function callable on a packet list. You need to collect a list of the netflowV9 packets then call netflowv9_defragment(thelist) See https://github.com/secdev/scapy/blob/master/scapy/layers/netflow.py#L11 This only means you can’t use prn with NetflowV9
has comment: http://stackoverflow.com/comment/98343049
has comment: http://stackoverflow.com/comment/89845949
has comment: http://stackoverflow.com/comment/89845899
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51413829
has comment: http://stackoverflow.com/comment/89838498
answers question: http://stackoverflow.com/q/51413829

http://stackoverflow.com/q/51356244
type: UnansweredQuestion
tagged with: punctuation
tagged with: python
has comment: http://stackoverflow.com/comment/89723072
tagged with: text
has comment: http://stackoverflow.com/comment/89684923
has title: Python program to put proper punctuations in a given string
upvote count: 3
has comment: http://stackoverflow.com/comment/89686192
type: Question
has comment: http://stackoverflow.com/comment/89684804
has comment: http://stackoverflow.com/comment/89684906
tagged with: nltk
score: -2
has comment: http://stackoverflow.com/comment/89684679
has answer: http://stackoverflow.com/a/63624563
has comment: http://stackoverflow.com/comment/89684641
downvote count: 5
tagged with: text-mining
has comment: http://stackoverflow.com/comment/89685015
has comment: http://stackoverflow.com/comment/89788654
answer count: 2
has body: I want to put proper punctuation marks in a given paragraph having many punctuationless sentences. E.g: input: hey how are you can you come today output: hey, how are you? can you come today? I just want to split the sentences to isolate the question part and the statement part. Basically, I need to put only &quot;.&quot; and &quot;?&quot; at appropriate places. Is there any protocol to do the same. Any suggestion will be appreciated.
has answer: http://stackoverflow.com/a/51356457
favorite count: 0

http://stackoverflow.com/q/51407770
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51408174
type: Question
has comment: http://stackoverflow.com/comment/89787465
has title: Regex - excluding words but with wildcards
score: -1
has answer: http://stackoverflow.com/a/51408174
downvote count: 2
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/89786762
has body: May not be possible with one expression but here goes. txt = 'check from HERE and i need RED but not BLUE' For the above text I need an expression that will match if 'RED' appears anywhere after 'HERE' but 'BLUE' does not appear anywhere after HERE.
has comment: http://stackoverflow.com/comment/89787494
favorite count: 0
tagged with: python
tagged with: regex

model
tags question: http://stackoverflow.com/q/51356650
tags question: http://stackoverflow.com/q/51332961
tag name: model
type: Tag
tags question: http://stackoverflow.com/q/51346035
tags question: http://stackoverflow.com/q/51327922

http://stackoverflow.com/q/51395501
type: Question
score: 3
has body: This is the data in time column: {'Thursday': {'0:00': 1, '23:00': 1, '21:00': 1}, 'Saturday': {'2:00': 1}, 'Monday': {'1:00': 1}} But this code is giving me syntax error : checkin_df['time_clean'] = map(lambda (x, y): map(lambda (k, v): map(lambda(i, value): [k, value, v.values()[i]], enumerate(v)), y.iteritems()), checkin_df['time'].iteritems()) I am getting the following error : checkin_df['time_clean'] = map(lambda (x, y): map(lambda (k, v): map(lambda(i, value): [k, value, v.values()[i]], enumerate(v)), y.iteritems()), checkin_df['time'].iteritems()) ^ SyntaxError: invalid syntax Which part am I missing ? Could you please help ?
upvote count: 3
has title: SyntaxError: invalid syntax inside map(lambda (x, y)
tagged with: functional-programming
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
tagged with: lambda
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/51395531
accepted answer: http://stackoverflow.com/a/51395531

http://stackoverflow.com/q/51360522
tagged with: beautifulsoup
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has body: I am looking to return the text from the "value" class but my problem is, in the table there are multiple td tags with the class "value" and text containing "Module Time: ". So how do you return a result/text when the class name is the same throughout the table, the only difference being the result itself. HTML: Module Time: 1.4165606 For example, a few lines of code below the snippet above is this: Module Time: 0.100279 So I just want to return the result from the first HTML snippet.
type: Question
has answer: http://stackoverflow.com/a/51361080
score: 0
has title: Return text from a specific td using Python & beautifulsoup4
answer count: 1

linux-mint
type: Tag
tags question: http://stackoverflow.com/q/51329742
tag name: linux-mint

http://stackoverflow.com/comment/89867277
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51448385
has text: https://docs.djangoproject.com/en/2.0/ref/models/querysets/

http://stackoverflow.com/a/51468829
has body: The message in message.server is the message command, which doesn't have a server. (That's what the error is telling you) You should pass the invocation context into the command with pass_context=True @FiveStarBot.command(pass_context=True) async def message(ctx, member: discord.Member, *, text : str): await FiveStarBot.send_message(member, text) This takes advantage of a discord.py converter to do the name lookup for you
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51465704

doc2vec
tags question: http://stackoverflow.com/q/51341882
tag name: doc2vec
type: Tag

http://stackoverflow.com/comment/89769828
type: QuestionComment
has text: try suitable encoding type instead of utf-8
comment on: http://stackoverflow.com/q/51399208
score: 0
type: Comment

http://stackoverflow.com/q/51350978
type: Question
duplicate of: http://stackoverflow.com/q/45552766
downvote count: 0
has title: Getting a list of dependencies from the optimizer backwards in tensorflow
favorite count: 0
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/45552766
has body: I'd like to generate a list of all dependencies from the optimizer backwards in tensorflow. My goal is to validate some assign operations were picked up correctly. Is there a straightforward way to generate such a graph?
answer count: 0
score: 1
upvote count: 1
tagged with: tensorflow

web-services
type: Tag
tags question: http://stackoverflow.com/q/51420063
tag name: web-services

http://stackoverflow.com/q/51344906
has title: In python,how to use decorator compatible with normal function and coroutine function simply?
type: UnansweredQuestion
score: 6
tagged with: python
upvote count: 6
type: Question
has answer: http://stackoverflow.com/a/51347508
has body: Here is my way,but I feel it is not very simple, any better way? import asyncio import time def timer_all(f): if asyncio.iscoroutinefunction(f): async def wrapper(*args, **kwargs): now = time.time() result = await f(*args, **kwargs) print('used {}'.format(time.time() - now)) return result else: def wrapper(*args, **kwargs): now = time.time() result = f(*args, **kwargs) print('used {}'.format(time.time() - now)) return result return wrapper there is a lot of decorator, retry, add log etc,all will write this way,a bit ugly,right?
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/a/51464390
type: Answer
downvote count: 13
has body: I think this error is for out of memory. Your RAM or GPU memory was full and could not process new data. you can do two works: 1. Decrease your batch size. 2. Save your model in for example 60th epoch and close current program and run new program and restore saved model and train model from 61 epoch to 120 epoch and save that and close program and repeat this work for your interested epoch
upvote count: 1
score: -12
answers question: http://stackoverflow.com/q/51463383

http://stackoverflow.com/comment/89906772
has text: Running value_counts on Id shows no duplicates. It is possible that one observation has more than one category, it's a large dataset, Roughly 2000 observations. If theres more than 1 category, I would want both records.
comment on: http://stackoverflow.com/a/51462204
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89899965
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51465526
has text: did you happen to have very very unbalanced samples? Like 99% of one class and 1% of another class?
score: 4

http://stackoverflow.com/q/51388707
type: AnsweredQuestion
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/52216299
tagged with: gensim
score: 0
tagged with: seaborn
has body: We have Anaconda 4.3.1 installed on our hosts and recently we have installed several packages for data science use. All the imports were fine except for gensim. I am getting "Intel MKL FATAL ERROR: Cannot load libmkl_avx2.so or libmkl_def.so." and getting out of python shell. It sounds like a duplicate but the weird part is, when I import tensorflow or seaborn before importing gensim, I am not getting that error and gensim is being imported. I would also like to know if there is any dependency between these packages. And I do have the latest version of numpy which is 1.14.5. I have looked at various solutions proposed about installing few packages and uninstalling few. I would like to know the reason why we should be doing it before actually doing it.
answer count: 1
tagged with: tensorflow
tagged with: anaconda
accepted answer: http://stackoverflow.com/a/52216299
has title: Intel MKL FATAL ERROR: while trying to import gensim package

http://stackoverflow.com/comment/89928969
type: Comment
comment on: http://stackoverflow.com/q/51480152
score: 0
has text: One simple, though strictly more expensive than necessary, approach would be to see if the intersection `np.intersect1d(a, b)` is empty or not.
type: QuestionComment

http://stackoverflow.com/q/51478441
has comment: http://stackoverflow.com/comment/89925903
has comment: http://stackoverflow.com/comment/89925974
has comment: http://stackoverflow.com/comment/89925689
score: 0
has comment: http://stackoverflow.com/comment/89925799
tagged with: data-analysis
has comment: http://stackoverflow.com/comment/89925347
type: UnansweredQuestion
tagged with: python
has body: I want to make a colorbar that would have its tick pointing inward. However, when I set the direction of ticks to 'in', the ticks are draw beneath the colorbar and are almost invisible. What should I do to make them drawn on top of the colorbar? from matplotlib import pyplot as plt from matplotlib import cm norm = plt.Normalize(0, 100) sm = plt.cm.ScalarMappable(cmap="Purples", norm=norm) sm.set_array([]) fig, ax = plt.subplots(figsize=(10,10)) cbar = ax.figure.colorbar(sm) cbar.outline.set_visible(False) cbar.ax.yaxis.set_ticks_position('both') cbar.ax.tick_params(labelsize=20, color='k') gives (outer ticks visible): from matplotlib import pyplot as plt from matplotlib import cm norm = plt.Normalize(0, 100) sm = plt.cm.ScalarMappable(cmap="Purples", norm=norm) sm.set_array([]) fig, ax = plt.subplots(figsize=(10,10)) cbar = ax.figure.colorbar(sm) cbar.outline.set_visible(False) cbar.ax.yaxis.set_ticks_position('both') cbar.ax.tick_params(labelsize=20, color='k', direction='in') gives (inner ticks invisible):
tagged with: colorbar
has comment: http://stackoverflow.com/comment/89925393
answer count: 0
tagged with: plot
type: Question
has comment: http://stackoverflow.com/comment/89926272
has title: How to make matplotlib colorbar inner ticks visible?
tagged with: matplotlib

http://stackoverflow.com/comment/89645035
score: 0
comment on: http://stackoverflow.com/q/51334847
type: Comment
type: QuestionComment
has text: Then I believe the best you can do is make an testing module, and within that module import sys, append to the path, import your scripts, and then place that module in the tests directory and import that.

http://stackoverflow.com/q/51442363
has title: How can I fetch Intercom users using Python API with a particular filter?
type: Question
tagged with: intercom
has body: How to fetch users from Intercom Python API using the tag last seen less than 2 days ago or else creating the segment in UI for the same will it be possible to fetch all users in Segment which I have created with filter 'last seen less than 2 days ago'?
tagged with: api
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51877576
tagged with: django
tagged with: python
score: 1
upvote count: 1

http://stackoverflow.com/a/51343810
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/89679377
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51325640
accepted answer of: http://stackoverflow.com/q/51325640
upvote count: 2
has body: Your output looks like you are using the HTML display in the Jupyter notebook, so you will need to set pre for the white-space style, because HTML collapses multiple whitespace, and use a monospace font, e.g.: styles = { 'font-family': 'monospace', 'white-space': 'pre' } x_style = x.style.set_properties(**styles) Now to format the float, a simple right justified with $ could look like: x_style.format('${:&gt;10,.0f}') This isn't quite right because you want to convert the negative number to (2), and you can do this with nested formats, separating out the number formatting from justification so you can add () if negative, e.g.: x_style.format(lambda f: '${:&gt;10}'.format(('({:,.0f})' if f &lt; 0 else '{:,.0f}').format(f))) Note: this is fragile in the sense it assumes 10 is sufficient width, vs. excel which dynamically left justifies $ to the maximum width of all the values in that column. An alternative way to do this would be to extend string.StringFormatter to implement the accounting format logic.

http://stackoverflow.com/q/51372910
tagged with: collision-detection
tagged with: python-2.7
score: 0
tagged with: for-loop
answer count: 1
has answer: http://stackoverflow.com/a/51373282
tagged with: python
tagged with: pygame
has body: I'm sorry if this isn't a super general question, but it's such a specific thing that I just know should work, and it just doesn't. Why doesn't the collision detection from the green player hitting the yellow box work? I'm sorry for all of the other clutter, but I couldn't find anything to delete to make the code smaller whilst still remaining the core game. Right now it's mostly barebones. ' import pygame, sys, time pygame.init() isRunning = True windowWidth = 1280 windowHeight = 720 playerHeight = 64 playerWidth = 64 playerX = (windowWidth / 2) - (playerWidth / 2) + 100 playerY = (windowHeight / 2) - (playerHeight / 2) playerXLate = playerX playerYLate = playerY playerSpeed = 4 blockHeight = 64 blockWidth = 64 blockX = 0 blockY = 0 number = 3 playerMovingForewards = False playerMovingLeft = False playerMovingBackwards = False playerMovingRight = False playerColor = (0, 255, 0) blockColor = (255, 255, 0) backgroundColor = (0, 0, 255) window = pygame.display.set_mode((windowWidth, windowHeight)) while isRunning == True: Map = open('Map', 'r') mapY = Map.readlines() mapX = mapY[0].split() for y in range(len(mapY)): mapX = mapY[y] for x in range(len(mapX)): if mapX[x] == "1": if playerX + playerWidth &gt;= (x * 64) and playerX &lt;= (x * 64) + blockWidth and playerY + playerHeight &gt;= (y * 64) and playerY &lt;= (y * 64) + blockHeight: playerX = playerXLate playerY = playerYLate pygame.draw.rect (window, (blockColor), ((x / 2) * 64, y * 64, blockWidth, blockHeight)) Map.close() playerXLate = playerX playerYLate = playerY for event in pygame.event.get(): if (event.type == pygame.QUIT): isRunning = False pygame.quit() sys.exit() if(event.type == pygame.KEYDOWN): if (event.key == pygame.K_w): playerMovingForewards = True if (event.key == pygame.K_a): playerMovingLeft = True if (event.key == pygame.K_s): playerMovingBackwards = True if (event.key == pygame.K_d): playerMovingRight = True if(event.type == pygame.KEYUP): if (event.key == pygame.K_w): playerMovingForewards =…
type: UnansweredQuestion
has title: In Pygame for loops collision-detection isn't working
type: Question

http://stackoverflow.com/q/51412941
tagged with: bash
answer count: 1
has body: So this is an odd issue. python script.py -a 1234 works /usr/bin/python /tmp/script.py -a 1234 works nc 127.0.0.1 443 -e /bin/bash works nc 127.0.0.1 443 -e /usr/bin/python /tmp/script.py -a 1234 fails with all-A-records NIY nc 127.0.0.1 443 -e "/usr/bin/python /tmp/script.py -a 1234" fails with failed : No such file or directory Am I missing something here? I'm not sure why this isn't working.
favorite count: 0
tagged with: python
has title: NetCat Execute - File Not Found
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/51413112
tagged with: netcat
type: Question
tagged with: parrot-os
has answer: http://stackoverflow.com/a/51413112
downvote count: 0
upvote count: 3

http://stackoverflow.com/q/51329934
upvote count: 2
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/89635532
has comment: http://stackoverflow.com/comment/89635793
has title: Is there a way to create a single column pandas DataFrame from list without copying the list?
answer count: 3
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/89635504
favorite count: 0
has body: Suppose I have this code: import pandas as pd mylist = [item for item in range(100000)] df = pd.DataFrame() df["col1"] = mylist Is the data in mylist copied when it is assigned to df["col1"] ? If so, is there a way to avoid this copy? Edit: My list in this case is a list of strings. One things I am getting from these answers is if I instead create a numpy array of these strings, no data duplication will occur I call df["col1"] = mynparray?
has answer: http://stackoverflow.com/a/51330018
has answer: http://stackoverflow.com/a/70765227
has comment: http://stackoverflow.com/comment/89635535
linked to: http://stackoverflow.com/q/993984
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/89635578
has answer: http://stackoverflow.com/a/78809620
tagged with: list

http://stackoverflow.com/comment/89703688
comment on: http://stackoverflow.com/q/51365661
score: 0
type: QuestionComment
has text: your question is way too broad; longer training can routinely lead to overfitting & worse behavior, that's why techniques like early stopping are (routinely...) employed in practice...
type: Comment

http://stackoverflow.com/q/51439359
has title: Default arguments in lambda function
answer count: 0
has comment: http://stackoverflow.com/comment/89848851
upvote count: 1
downvote count: 1
type: Question
tagged with: function
score: 0
has comment: http://stackoverflow.com/comment/89869907
tagged with: default
has comment: http://stackoverflow.com/comment/89870112
has body: import time from functools import partial (lambda fun:fun())(partial(time.sleep,2)) #runs, sleeps 2 seconds partial(lambda fun:fun(),partial(time.sleep,2))() #runs, sleeps 2 seconds partial was used to give default argument 2 to sleep, which runs as fun(), and was given as an argument to lambda function, which was run by (). But how to give default argument to lambda function without partial, so that () also could run it like (lambda fun:fun(),defaultargument)()? (I passed a function as a default argument.)
favorite count: 0
type: UnansweredQuestion
tagged with: anonymous
tagged with: python
tagged with: lambda

http://stackoverflow.com/a/51345413
type: AcceptedAnswer
downvote count: 0
upvote count: 85
has body: When training a machine learning model, one of the main things that you want to avoid would be overfitting. This is when your model fits the training data well, but it isn't able to generalize and make accurate predictions for data it hasn't seen before. To find out if their model is overfitting, data scientists use a technique called cross-validation, where they split their data into two parts - the training set, and the validation set. The training set is used to train the model, while the validation set is only used to evaluate the model's performance. Metrics on the training set let you see how your model is progressing in terms of its training, but it's metrics on the validation set that let you get a measure of the quality of your model - how well it's able to make new predictions based on data it hasn't seen before. With this in mind, loss and acc are measures of loss and accuracy on the training set, while val_loss and val_acc are measures of loss and accuracy on the validation set. At the moment your model has an accuracy of ~86% on the training set and ~84% on the validation set. This means that you can expect your model to perform with ~84% accuracy on new data. I notice that as your epochs goes from 23 to 25, your acc metric increases, while your val_acc metric decreases. This means that your model is fitting the training set better, but is losing its ability to predict on new data, indicating that your model is starting to fit on noise and is beginning to overfit. So that is a quick explanation on validation metrics and how to interpret them.
type: Answer
score: 85
accepted answer of: http://stackoverflow.com/q/51344839
answers question: http://stackoverflow.com/q/51344839
has comment: http://stackoverflow.com/comment/89671588
has comment: http://stackoverflow.com/comment/131415322

header
type: Tag
tags question: http://stackoverflow.com/q/51478739
tag name: header

http://stackoverflow.com/a/51326643
has body: Clean data is runs before the is_valid, because clean is one of many methods that django runs to validate your form since you cleaning just one field, use clean to this field class BokningForm(ModelForm) ... def clean_pumpstart(self): data = self.cleaned_data['pumpStart'] data = datetime.strptime(data , "%Y-%m-%d %H:%M") return data in your views maybe this can workout if form.is_valid(): bokning= form.save(commit=False) ... # Change your value bokning.save() EDIT: Got some good info in other post... try use clean method inside the model, looks like this runs first class Bokning(models.Model): def clean(self): ... Source: Django: Model clean method called before form clean
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51326314
type: Answer
has comment: http://stackoverflow.com/comment/89628690
downvote count: 0
has comment: http://stackoverflow.com/comment/89628497

http://stackoverflow.com/comment/89756149
type: AnswerComment
type: Comment
has text: I actually thought OP needed the number of times `text_2_compared` appeared in `text_1`, but on reading the question again, it seems OP just wants an indicator variable. Thus `in` is sufficient
comment on: http://stackoverflow.com/a/51391852
score: 0

http://stackoverflow.com/q/51439724
tagged with: anaconda
has answer: http://stackoverflow.com/a/51439766
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/51439774
tagged with: nltk
downvote count: 0
has answer: http://stackoverflow.com/a/51439774
accepted answer: http://stackoverflow.com/a/51439766
has body: I need some NLTK data packages in my code. I tried installing it from below command, but It installs all the packages that I do not need conda install -c conda-forge nltk_data How can I install specific NLTK data packages like stopwords, punkt, etc.
favorite count: 0
score: 8
has title: How to install NLTK data in windows (Anaconda)
upvote count: 8
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/51471937
favorite count: 0
tagged with: python
tagged with: pygame
tagged with: collision
score: 2
type: AnsweredQuestion
downvote count: 0
type: Question
possible better answer: http://stackoverflow.com/a/51472042
has title: Collision detection for sprites in the current room
upvote count: 2
has answer: http://stackoverflow.com/a/51472042
answer count: 2
has body: I asked a similar question not long ago regarding collision detection on rocks. I have multiple rooms with a group of rocks in each. The collision detection for these rocks is in the player class. My question here is how do I set it so that the collision detection works for the rocks in these rooms? When i run the script and try to move my character it gives this error: line 34, in move_single_axis for rock in current_room.rock_list: NameError: name 'current_room' is not defined Here is the code which is broken up into multiple files. PLAYER CLASS FILE import pygame BLACK = (0, 0, 0) WHITE = (255, 255, 255) class Player(pygame.sprite.Sprite): def __init__(self, filename, x, y): super().__init__() self.image = pygame.image.load(filename).convert() self.image.set_colorkey(BLACK) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y def changespeed(self, x, y): if x != 0: self.move_single_axis(x, 0) if y != 0: self.move_single_axis(0, y) def move_single_axis(self, x, y): self.rect.x += x self.rect.y += y for rock in current_room.rock_list: if self.rect.colliderect(rock.rect): if x &gt; 0: self.rect.right = rock.rect.left if x &lt; 0: self.rect.left = rock.rect.right if y &gt; 0: self.rect.bottom = rock.rect.top if y &lt; 0: self.rect.top = rock.rect.bottom ROOMS CLASS FILE import Player import pygame from Rock import * BLACK = (0, 0, 0) WHITE = (255, 255, 255) class Room(object): rock_list = None def __init__(self): self.rock_list = pygame.sprite.Group() class Room0(Room): def __init__(self): super().__init__() rock = Rock("Rock.png", 200, 200) self.rock_list.add(rock) self.background_position = [0, 0] self.background_image = pygame.image.load("Floor.png").convert() ROCK CLASS FILE import pygame BLACK = (0, 0, 0) WHITE = (255, 255, 255) class Rock(pygame.sprite.Sprite): def __init__(self, filename, x, y): super().__init__() self.image = pygame.image.load(filename).convert() self.image.set_colorkey(BLACK) self.rect = self.image.get_rect().inflate(1, 1) self.…
has answer: http://stackoverflow.com/a/51509018
accepted answer: http://stackoverflow.com/a/51509018

http://stackoverflow.com/comment/89845708
comment on: http://stackoverflow.com/q/51437779
has text: Show us your directories structure? And btw, are you sure your application has read permission on these css files?
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89700351
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51358969
has text: Thank you! I used fileConfig in my main.py to set up an output to console, file1 with level debug and file2 with level info. However, I got a ValueError in my main.py. This is not logged to file1 nor file2. I can only see it in the colsole. How can I catch such error without knowing that it could occur? [link_to_config](https://pastebin.com/TgQZHq05)
type: AnswerComment

http://stackoverflow.com/a/51338715
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51338696
has body: @aran-fey is right import logging def log(func): """ Log what function is called """ def wrap_log(*args, **kwargs): name = func.__name__ logger = logging.getLogger(name) logger.setLevel(logging.INFO) # add file handler fh = logging.FileHandler("%s.log" % name) fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' formatter = logging.Formatter(fmt) fh.setFormatter(formatter) logger.addHandler(fh) logger.info("Running function: %s" % name) result = func(*args, **kwargs) logger.info("Result: %s" % result) return result # Your error was you returned the function, not the result return wrap_log @log def double_function(a): """ Double the input parameter """ return a*2 if __name__=="__main__": value = double_function(2) print(value)
answers question: http://stackoverflow.com/q/51338696
type: Answer
score: 2
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/89870660
has text: Thx. But one crucial difference here is that previous element of b is raised to the power of 0.8, not a multiple of 0.8.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51449260

http://stackoverflow.com/q/51338230
has title: Is a there exception if you ask for a integer and do not get an integer?
possible better answer: http://stackoverflow.com/a/51338271
accepted answer: http://stackoverflow.com/a/51338292
has answer: http://stackoverflow.com/a/51338271
tagged with: python
has body: I am trying to make a program where you enter an integer, but if you do not enter an integer, handle it with an exception. However I can not find any exceptions for integers on the internet. ### TECH SUPPORT ### while True: try: i = int(input('Enter an INTEGER: ')) except [INT EXCEPTION HERE]: print("You must enter an INTEGER, not any other format of data") - Does anyone know an exception if you ask for an integer input and do not get an integer?
type: AnsweredQuestion
tagged with: python-3.x
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89650929
has answer: http://stackoverflow.com/a/51338303
tagged with: int
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/51338292
score: 1
favorite count: 0

http://stackoverflow.com/comment/89817874
comment on: http://stackoverflow.com/a/51423297
type: Comment
has text: `pt` doesn't have keys, it's a list, iterating it will give the objects, which is what's wanted
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89633690
has text: Even with that restriction there will still be a ridiculous number of results.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51328929

http://stackoverflow.com/a/51343368
answers question: http://stackoverflow.com/q/51342354
accepted answer of: http://stackoverflow.com/q/51342354
type: Answer
has body: Several things are conspiring here. I assume that you want the shape of trainY to be (50,), but since you add the noise only after reshaping, broadcasting causes trainX + np.random.rand(trainX.shape[0]) to have shape (50, 50). If you change the initial part of the code to bias = np.ones(50) trainX = np.arange(0, 10, 0.2) trainY = (3 * trainX + np.random.rand(trainX.shape[0]) * 20 - 10) + 10 trainX = np.vstack([bias, trainX]).T and ensure that the shapes are set up properly through sess.run(train_op, feed_dict={X: x.reshape((1, 2)), Y: y}) then your code will run. However, since you are only dealing with the inner product of 2-dimensional vectors, you can avoid the reshaping altogether by instead simply using tf.tensordot: X = tf.placeholder("float", shape=(2,)) Y = tf.placeholder("float") w = tf.Variable([0.0, 0.0], name="weights") model = tf.tensordot(X, w, 1) Finally, note that while the approach of splitting up the sample before passing it to the optimizer (in what is typically referred to as batching) works well for large datasets, in your case you could just as well pass the entire sample at once; that is, something that would amount to X = tf.placeholder("float", shape=(50, 2)) Y = tf.placeholder("float", shape=(50, 1)) w = tf.Variable(tf.zeros([2, 1], "float"), name="weights") model = tf.matmul(X, w) cost = tf.reduce_sum(tf.pow((Y - model), 2)) init = tf.global_variables_initializer() train_op = tf.train.GradientDescentOptimizer(0.0001).minimize(cost) with tf.Session() as sess: sess.run(init) for i in range(10000): sess.run(train_op, feed_dict={X: trainX, Y: trainY.reshape((50, 1))})
score: 1
has comment: http://stackoverflow.com/comment/89678335
upvote count: 1
has comment: http://stackoverflow.com/comment/89709763
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/51398758
has comment: http://stackoverflow.com/comment/89769007
has comment: http://stackoverflow.com/comment/89768697
has comment: http://stackoverflow.com/comment/89768567
upvote count: 1
has comment: http://stackoverflow.com/comment/89768626
type: Answer
has comment: http://stackoverflow.com/comment/89768817
accepted answer of: http://stackoverflow.com/q/51398626
answers question: http://stackoverflow.com/q/51398626
has comment: http://stackoverflow.com/comment/89768952
downvote count: 0
has body: You can wrap the the regex string in wildcards. result = re.sub(r".*\bmama\b.*",'Nice', text1) . stands for any character and * stands for 0+ amount of the character to the left of it.
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/89784373
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51406585
has text: Yes, for each unique combination of `[Zona, Region, COM, PROV]` this will count the occurences of each unique value found in `Type of Housing`
score: 0

http://stackoverflow.com/a/75237132
answers question: http://stackoverflow.com/q/51412969
has body: blockchain-parser only supports plyvel 1.2.0 plyvel 1.2.0 only support Python 3.8 Please check your python version is correct. https://plyvel.readthedocs.io/en/latest/news.html brew install leveldb pip install plyvel==1.2.0 pip install blockchain-parser
score: 0
type: Answer

http://stackoverflow.com/a/51509853
score: 0
answers question: http://stackoverflow.com/q/51428359
type: Answer
has body: If you can handle a different output format, you can also you set intersection. &gt;&gt;&gt; L = set([ (1,2), (3,5), (6,10), (7,8) ]) &gt;&gt;&gt; M = set([ (1,3), (8,9), (12,13) ]) &gt;&gt;&gt; N = set([ (6,10), (3,4), (5,6), (10,11), (12,13) ]) &gt;&gt;&gt; T = set([ (6,10) , (1,4) ]) &gt;&gt;&gt; [T &amp; x for x in (L,M,N)] [{(6, 10)}, set(), {(6, 10)}] This will give you a list of sets of tuples which appear in both sets each. This should be faster than using nested loops.

http://stackoverflow.com/a/51366300
accepted answer of: http://stackoverflow.com/q/51366283
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51366283
has body: You're specifying in your try-except block that you're expecting a NameError, but you're getting an IOError. By using try: .... except NameError: .... you're handling only exceptions of type NameError. All other exceptions (in your case IOError) that are thrown up are not handled anywhere, thus crashing your code. Remove the NameError after the expect or add additional expected errors in the following manner try: .... expect NameError, IOError: ....
upvote count: 1
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/89637557
comment on: http://stackoverflow.com/a/51330889
type: AnswerComment
score: 0
type: Comment
has text: (the actual class name is MonitoredComponent, and it's in a django app called Monitor, that's why it's Monitor_monitoredcomponent)

http://stackoverflow.com/comment/89899704
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51465183
has text: Explain "not working". It is clear that it is not doing what you want it to do – else you would not have to ask – but *what* is not working? How does this fail? Do you get an error? Wrong images?
score: 0

http://stackoverflow.com/q/51387726
type: Question
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51387804
favorite count: 0
has body: In PyCharm, I have a class like this: class Car: def __init__(self): self.speed = 0 def say_state(self): print("I'm going {} kph!".format(self.speed)) def increase_speed(self, increase): self.speed += increase situated in a sub folder called Classes. I have driver python file, which simply contains: if __name__ == '__main__': my_car = Car() my_car.say_state() my_car.increase_speed(2) my_car.say_state() Unfortunately the class Car is not recognized. What do I have to do for the class Car to be recognized in the driver file? I guess this is a simple one. Apologies my background is strongly type languages - C#. PS: Even if I put my class Car in the same folder as the Driver it is not automatically recognized. I have to include: from Car import Car So if I have a class that uses 10 classes, which is not unlikely in complex applications, do I really have to include 10 import statements? I would expect that a good IDE recognizes classes ion the same project without having to import them explicitly. Am I missing something or is this just like this with Python as it is interpreted?
upvote count: 2
type: UnansweredQuestion
has title: recognize classes in sub folder in PyCharm
tagged with: python
has comment: http://stackoverflow.com/comment/89783836
has comment: http://stackoverflow.com/comment/89747370
score: 2
tagged with: pycharm
has answer: http://stackoverflow.com/a/51406782

http://stackoverflow.com/comment/89782608
type: QuestionComment
comment on: http://stackoverflow.com/q/51405791
score: 0
type: Comment
has text: How was the virtualenv *created*? Was it created on this same machine, or somewhere else with a different OS/architecture?

http://stackoverflow.com/comment/89724309
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51376326
score: 0
has text: @PM2Ring It's from my class.

http://stackoverflow.com/comment/89749793
type: Comment
has text: I am trying to achieve the -5 hours however. I;m not sure why this is happening on my end.
comment on: http://stackoverflow.com/a/51388829
type: AnswerComment
score: 0

http://stackoverflow.com/q/51449252
has answer: http://stackoverflow.com/a/51449540
upvote count: 2
answer count: 2
tagged with: selenium
has body: I'm using Selenium Webdriver to check the text of this particular paragraph (the one highlighted in blue here): But how do I 'query' that paragraph? This is what I'm trying (not working): def test_intro_text(self): """Test that intro text is expected text""" container = self.browser.find_element_by_id('visual-17') hed_dek_wrapper = container.find_element_by_class_name('hed-dek-wrapper') intro_text = hed_dek_wrapper.findElement('p:nth-of-type(2)') self.assertIn( 'Over the past 20 years, we have seen an evolution.', intro_text.text ) I'm getting this error: AttributeError: 'WebElement' object has no attribute 'findElement'
accepted answer: http://stackoverflow.com/a/51449540
has title: How to get an 'nth-of-type' in Selenium
type: AnsweredQuestion
tagged with: automated-tests
score: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/51449532
favorite count: 0
has answer: http://stackoverflow.com/a/51449532
type: Question
tagged with: python

http://stackoverflow.com/a/51481366
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51477977
answers question: http://stackoverflow.com/q/51477977
has comment: http://stackoverflow.com/comment/89965572
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89992358
downvote count: 0
has comment: http://stackoverflow.com/comment/89992029
has comment: http://stackoverflow.com/comment/89956209
type: Answer
has body: Here is a version with Attention (not Hierarchical) but you should be able to figure out how to make it work with hierarchy too - if not I can help out too. The trick is to define 2 models and use 1 for the training (model) and the other one to extract attention values (model_with_attention_output): # Tensorflow 1.9; Keras 2.2.0 (latest versions) # should be backwards compatible upto Keras 2.0.9 and tf 1.5 from keras.models import Model from keras.layers import * import numpy as np dictionary_size=1000 def create_models(): #Get a sequence of indexes of words as input: # Keras supports dynamic input lengths if you provide (None,) as the # input shape inp = Input((None,)) #Embed words into vectors of size 10 each: # Output shape is (None,10) embs = Embedding(dictionary_size, 10)(inp) # Run LSTM on these vectors and return output on each timestep # Output shape is (None,5) lstm = LSTM(5, return_sequences=True)(embs) ##Attention Block #Transform each timestep into 1 value (attention_value) # Output shape is (None,1) attention = TimeDistributed(Dense(1))(lstm) #By running softmax on axis 1 we force attention_values # to sum up to 1. We are effectively assigning a "weight" to each timestep # Output shape is still (None,1) but each value changes attention_vals = Softmax(axis=1)(attention) # Multiply the encoded timestep by the respective weight # I.e. we are scaling each timestep based on its weight # Output shape is (None,5): (None,5)*(None,1)=(None,5) scaled_vecs = Multiply()([lstm,attention_vals]) # Sum up all scaled timesteps into 1 vector # i.e. obtain a weighted sum of timesteps # Output shape is (5,) : Observe the time dimension got collapsed context_vector = Lambda(lambda x: K.sum(x,axis=1))(scaled_vecs) ##Attention Block over # Get the output out out = Dense(1,activation='sigmoid')(context_vector) model = Model(inp, out) model_with_attention_output = Model(inp, [out, attention_vals]) model.compile(optimizer='adam',loss='binary_crossentropy') return model, model_wi…
has comment: http://stackoverflow.com/comment/89964984
has comment: http://stackoverflow.com/comment/89955299
has comment: http://stackoverflow.com/comment/89965480

http://stackoverflow.com/q/51326320
tagged with: pandas
upvote count: 1
answer count: 1
has body: I have a multi header dataframe and it looks like that: SPY ARKW Open High Open High Bid Ask Bid Ask Bid Ask Bid Ask Date 2018-07-03 272.86 272.87 272.97 272.98 56.00 56.35 56.24 56.63 2018-07-02 269.49 269.51 272.04 272.05 54.87 55.21 56.04 56.09 2018-06-29 272.09 272.12 273.66 273.67 55.58 55.95 55.95 56.07 I want to iterate over all top level columns so in that case SPY and ARKW so I tried: for column in df: print(column) but it iterates also over lower level columns: ('SPY', 'Open', 'Bid') ('SPY', 'Open', 'Ask') ('SPY', 'High', 'Bid') ('SPY', 'High', 'Ask') ('ARKW', 'Open', 'Bid') ('ARKW', 'Open', 'Ask') ('ARKW', 'High', 'Bid') ('ARKW', 'High', 'Ask') How can I iterate over top level columns and then for each select Open Bid column?
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51326399
accepted answer: http://stackoverflow.com/a/51326399
tagged with: multidimensional-array
tagged with: python
has title: How to select top level columns in multi header pandas dataframe
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
tagged with: dataframe

http://stackoverflow.com/q/51363208
has title: How to deal with multiple keyword arguments?
tagged with: arguments
favorite count: 0
has answer: http://stackoverflow.com/a/51363396
has body: I've got some trouble dealing with defining a user friendly function interface when passing two keyworded arguments with the same key. Question What is the best way to make it possible to call a function where two keyworded arguments have the same key and the second keyworded argument has precedence? If this problem occurs, the first keyworded argument always stems from an unzipped database in a dict, while the second keyworded argument is always passed by giving it "directly" as a keyworded argument. The database dictionary values must not be overwritten in the outer scopy of the functions, since they may be used multiple times. edit: To keep up the usability of the function for the user, a backend-implementation is preferred. This means that the user can simply pass arguments to the function without the use of additional modules, while the function itself does all the magic. Problem I've got a function, called fun_one here, which receives a multitude of arguments defined directly by the user of my program. This may be length and width of a heat exchanger for example. To ease the use of the function and make the calling code as short as possible, the use of databases is encouraged. These databases contain the data in a dict (or in a pandas Series), in this case called inputs. To pass the database-dict inputs to the function, it is unzipped with **inputs and thus passed as keyworded arguments. Now if the user wants to overwrite a specific argument of the database, my understanding of a user-friendly approach would be to just let him pass the preceded argument again, for example with length=23.7, and internally overwrite the argument from the database. But of course (see example code) this raises the error before I can even enter the function where I could try/except: TypeError: fun_one() got multiple values for keyword argument 'length' Code example reproducing the error def fun_one(*args, **kwargs): # short example function print(kwargs) inputs = {'length': 15.8, '…
has answer: http://stackoverflow.com/a/76240401
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/51364236
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51363396
possible better answer: http://stackoverflow.com/a/51364236
type: Question
tagged with: function
downvote count: 0
score: 4
has answer: http://stackoverflow.com/a/76240414
upvote count: 4

http://stackoverflow.com/q/51480725
has title: Correct way to write JSON data returned from a SPARQL query in Python
has body: I'm using python3 to make SPARQL queries. I need to read a Virtuoso database and output triples. Some of the data in the triples contains special characters like linefeeds and such. Anyway, I can get the data out like this: queryString = "some query" sparql.setQuery(queryString) sparql.setReturnFormat(JSON) try: jsonData = sparql.query() for result in jsonData: print('Result: ***') f.write(str(result) + '\n') except: print("Oops:", sys.exc_info()[0], file=sys.stderr) When I do this, I get the following output in the file: b'{\n' b' "head" : {\n' b' "vars" : [\n' b' "subject",\n' b' "predicate",\n' b' "object"\n' b' ]\n' b' },\n' b' "results" : {\n' b' "bindings" : [\n' b' {\n' b' "predicate" : {\n' b' "type" : "uri",\n' b' "value" : "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"\n' b' },\n' b' "subject" : {\n' b' "type" : "uri",\n' b' "value" : "http://www.ontologyrepository.com/CommonCoreOntologies/delimits"\n' b' },\n' b' "object" : {\n' b' "type" : "uri",\n' b' "value" : "http://www.w3.org/2002/07/owl#InverseFunctionalProperty"\n' b' }\n' b' },\n' and so on. I'm not sure what the b prefix does on these lines. Anyway, I'm having trouble reading this in with the JSON libraries. So I would prefer to write it with JSON. I would like to replace the for loop with a simple thing like json.dump(jsonData, f) or json.dumps(jsonData, f) When I do that I get the error message Oops: &lt;class 'TypeError'&gt;. I notice that the type of jsonData is &lt;class 'SPARQLWrapper.Wrapper.QueryResult'&gt;. Is the SPARQL query not returning JSON? Is there some other transformation I have to make?
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89936499
linked to: http://stackoverflow.com/q/22824539
favorite count: 0
has answer: http://stackoverflow.com/a/51486695
tagged with: python
tagged with: sparql
has comment: http://stackoverflow.com/comment/89936753
accepted answer: http://stackoverflow.com/a/51486695
score: 2
type: AnsweredQuestion
tagged with: sparqlwrapper
upvote count: 2
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/89940844
type: Question

http://stackoverflow.com/a/51416294
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51416203
type: Answer
has body: &gt;&gt;&gt; l = [{'lat': 57.161597, 'lng': -1.0962736}, {'lat': 32.3794617, 'lng': -0.08347689999999999}] &gt;&gt;&gt; [set(d.values()) for d in l] [{57.161597, -1.0962736}, {32.3794617, -0.08347689999999999}] &gt;&gt;&gt;
has comment: http://stackoverflow.com/comment/89804257
downvote count: 0
has comment: http://stackoverflow.com/comment/89803914

http://stackoverflow.com/q/51330275
answer count: 1
has body: I have a set of lines in a file like below. mov 66 (56.9%) 5406720 (56.9%) I want to identify these lines in a set of files and extract the first (mov) and fifth field (5406720 in the above case) and write this to a separate single file. Thanks &amp; regard, santosh
favorite count: 0
tagged with: extract
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/51330613
tagged with: regex
score: -1
downvote count: 1
has title: Extract a particular word at a particular position in a line using Python
type: UnansweredQuestion
upvote count: 0

http://stackoverflow.com/q/51337937
type: AnsweredQuestion
has body: I'm working on a Raspberry Pi 3, and at the moment, I'm trying to create a GUI in PyQt5 for some nmap commands. More or less, I take input from a list, edit the subent, and from that, using various commands, it doesn't work. I am using subprocess for this to happen, due to the fact that I only require the output from the terminal. Some commands from the nmap library work pretty well with no problems, and I manage to fetch the result, but with others the result is ongoing. I try to print the result from this command: sudo nmap -p 80,443 192.168.1.1/24 -oG - And, the method that I'm using: def nmapHttScan(self): subnet = str(self.leNmap.text()) result = ' ' res= subprocess.Popen(['sudo','nmap','-p 80,443',''+subnet,'-oG -'],stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True,encoding = 'utf-8') while True: output=res.stdout.readline() if output =='' and res.poll() is not None: break; if output: print('output',output.strip()) rc=res.poll() print(str(rc)) Every time I press the button in my GUI, so that I could see a result, my shell restarts and I don't really know what to do. I think I may be using the process.poll() method wrong, but I've been working on this problem for about 4-5 days, and I have been searching everywhere. So, please, if you have any idea I'm willing to try anything. Thank you, and have a nice day!
has answer: http://stackoverflow.com/a/51340078
type: Question
accepted answer: http://stackoverflow.com/a/51340078
answer count: 1
has title: Shell keeps restarting while using a more complicated nmap command in subprocess in a PYQT5 GUI
score: 0
tagged with: python
tagged with: python-3.x
tagged with: nmap

http://stackoverflow.com/q/51420358
answer count: 1
accepted answer: http://stackoverflow.com/a/52491243
has body: I wanted to set up a communication between a Raspberry PI (slave) and my PC (Master) through Modbus protocol. Currently, I'm using modbus-tk (python) to set up the communication protocol. The issue is that the Master was not able to read the register from the slave. May I know what is wrong with my code? I'm very confused. The error that I obtained from Slave was: Handle request failed: Invalid CRC in request or Request length is invalid The error that I obtained from Master was: ModbusInvalidResponseError Note: the purpose is to use the Master to read the data from the slave. Here is the code for the slave: import modbus_tk import modbus_tk.defines as cst from modbus_tk import modbus_rtu import serial import time modbusServ = modbus_rtu.RtuServer(serial.Serial('/dev/ttyUSB0'),baudrate= 19200, bytesize=8, parity='N', stopbits=1, xonxoff=0) print("start") modbusServ.start() slave_1 = modbus_tk.modbus.Slave(1) slave_1.add_block ( "1", modbus_tk.defines.HOLDING_REGISTERS, 1, 5) aa= (1,2,3,4,5) # data in the register while True: slave_1.set_values ("1", 1, aa) time.sleep(0.5) Here is the code for the Master: import sys import serial #add logging capability import logging import modbus_tk.modbus import modbus_tk.defines as cst import modbus_tk.modbus_rtu as modbus_rtu logger = modbus_tk.utils.create_logger("console") while True: master = modbus_rtu.RtuMaster(serial.Serial('COM3', baudrate= 19200, bytesize=8, parity='N', stopbits=1)) master.open master.set_timeout(3) master.set_verbose(True) logger.info("connected") logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 1, 5)) Here is the datasheet and a picture of the USB-to-rs485 device that I am using to connect my Raspberry Pi and my PC: https://www.enika.cz/data/files/produkty/komponenty/mereni-a-regulace/UT-890A%20User%20manual.pdf https://c.76.my/Malaysia/ut-890-usb-to-rs485-converter-belco-1605-07-belco@2569.jpg Thank you very very much for the help.
upvote count: 4
type: AnsweredQuestion
downvote count: 0
favorite count: 0
tagged with: modbus
tagged with: modbus-tk
type: Question
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/52491243
has title: How to set up simple slave and master with modbus-tk RTU (Python)

http://stackoverflow.com/comment/89807193
score: 0
has text: Thanks for updating. This isn't a common use case, so it's unlikely to be baked into a library which is for validation purposes. If you know that all the properties will be at the root properties object level, you can extract them easily enough. If there are many nested and referenced objects, that becomes a harder problem. - In answer to your question... no. The validators that provide verbose details on validation results only do so on error.
type: QuestionComment
comment on: http://stackoverflow.com/q/51392796
type: Comment

http://stackoverflow.com/comment/89753210
type: AnswerComment
type: Comment
score: 1
has text: This is incorrect. 'Deprecated' in software means that further use is "discouraged." As I understand it, this generally means that *there is no guarantee that this feature will be supported, or even will exist, in future releases.* However, while this is the pattern, this is still rather nebulous, so I'm looking for people more familiar with the pandas project to understand their intent with this word.
comment on: http://stackoverflow.com/a/51390517

http://stackoverflow.com/comment/89871311
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51450397
has text: `where` is a reserved keyword in NumPy.

http://stackoverflow.com/q/51392915
has body: I really want to ask this, because even if I read the documentation and have seen some examples cannot really get the point of how to use this. I have a Raspberry pi 3 model B, and I cross compiled QT 5.6 and the lastest SIP and PyQt5 versions to develop Python GUIs and use the linux frame buffer, everything was a success, until I ran this part of my code def refresh_data(self): if self.setTarget == 1: for x in range(0, self.targetnum): self.target.append(getShadowInfo(x)) if float(self.target[x]) != self.datalist[x]: if float(self.target[x]) &gt; self.datalist[x]: self.step.append(float(self.target[x]) - self.datalist[x]) self.negative.append(0) else: self.step.append(self.datalist[x] - float(self.target[x])) self.negative.append(1) else: self.step.append(0) self.negative.append(0) self.step[x] *= 0.1 self.setTarget = 0 self.setTodaysDate(self.year, self.month, self.day, self.hour, self.min) self.stopv += 10 for x in range(0, self.targetnum): if self.step[x] != 0: if self.negative[x] == 0: self.datalist[x] += self.step[x] else: self.datalist[x] -= self.step[x] self.setCustomParameter(x) if all(i == 0 for i in self.step): self.timer.stop() if self.stopv &gt;= 100: self.timer.stop() Which reads data from an external file and set it as a target, then it increase or decrease the actual value to update it on the python GUI, that way it looks smooth, but meanwhile that happens, the performance gets poor and it even execute the code slowly than it should (is ran by an 50ms Qtimer). With htop, I notice that when running this part of the code, my RPi only use one core of its four, can somebody help me to to multiprocess the two for loops?, or maybe better, the refresh_data function?. EDIT! setCustomParameter function def setCustomParameter(self, intparameter): if intparameter == 1: #RPMMeter self.hygrometer.setProperty("gaugeValue", round(self.datalist[1], 2)) self.label_5.setText(QCoreApplication.translate("MainWindow", "Engine Speed: " + str(round(self.datalist[1], 2)) + …
tagged with: raspberry-pi3
tagged with: qt5
has comment: http://stackoverflow.com/comment/89758170
score: 0
upvote count: 1
answer count: 1
downvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89758333
favorite count: 0
has comment: http://stackoverflow.com/comment/89758135
tagged with: python-3.x
has title: Python3 multiprocessing a 'for' loop
tagged with: pyqt5
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51394524
accepted answer: http://stackoverflow.com/a/51394524
has comment: http://stackoverflow.com/comment/89758260
type: Question

http://stackoverflow.com/q/51391634
favorite count: 0
downvote count: 0
has answer: http://stackoverflow.com/a/54357001
tagged with: cluster-computing
tagged with: parallel-processing
type: AnsweredQuestion
has body: I want to do some parallel computing for the first time and I don't know exactly where should I start from. The problem is that I have a huge file list (around 7000 csv files) that I want to process and get a single file from the data. For this task I would like to use the campus' cluster which works with Torque PBS. The closest question to what I want to achive that I've found in SO so far is this one. With the main difference that I should use Torque (do I really?). So, to leave it short, my question would be: How could I implement the solution of the cited question using Torque PBS?
score: 1
has title: Torque PBS - running several serial Python processes
type: Question
has comment: http://stackoverflow.com/comment/89779480
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/90466706
tagged with: pbs
linked to: http://stackoverflow.com/q/31864503
accepted answer: http://stackoverflow.com/a/54357001
tagged with: python
tagged with: torque

http://stackoverflow.com/comment/89818229
has text: Have you any idea how Windows XP drops packets sent from RAW socket and not from classic socket?
type: AnswerComment
comment on: http://stackoverflow.com/a/51422927
score: 0
type: Comment

http://stackoverflow.com/comment/89831733
has text: I think this will do the work... Will check and mark it as the answer.. Thanks BTW
type: Comment
comment on: http://stackoverflow.com/a/51430268
score: 0
type: AnswerComment

http://stackoverflow.com/q/51335131
answer count: 1
tagged with: django
tagged with: python
has title: Add input-tags to an article and create new tag records if it's non-existence in database
type: AnsweredQuestion
has body: I have Tag and Article data models of many-to-many relationships, class Tag(models.Model): owner = models.ForeignKey(User,on_delete=models.CASCADE) name = models.CharField(max_length=100) def __str__(self): return self.name class Meta: ordering = ("id",) class Article(models.Model): tags = models.ManyToManyField(Tag, blank=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) ... When receiving tags inputted from the form, I first check if the tags existing to determine whether or not to create a new one in the database, and then append all input-tags to an article. #save the new article in database if article_form.is_valid(): article = article_form.save(commit=False) article.owner = self.request.user article.save() create tags which not found in records #compare tags input_tags = self.request.POST["tags"] input_tags = tags.split(",") query_tags = Tag.objects.all() #get name list of tab objects query_tags = [tag.name for tag in query_tags] #create new tabs in TabTable for tag in input_tags: if tag not in query_tags: Tag.objects.create(name=tag, owner=self.request.user) retrieve input tag objects tag_objs = [] for input_tag in input_tags: try: qualified_tab = Tab.object.filter(name=input_tag)[0] tag_objs.append(qualified_tab) append tags to article article.tags.add(*tag_objs) This is a routine task, but the solution is cumbersome. How to complete such a task elegantly?
type: Question
has comment: http://stackoverflow.com/comment/89799145
has answer: http://stackoverflow.com/a/51335543
accepted answer: http://stackoverflow.com/a/51335543
score: 0
has comment: http://stackoverflow.com/comment/90352095

http://stackoverflow.com/a/51445093
has body: You need to use pandas.read_csv() with parameters header and names to specify that csv has no column headers and then specify the column names of your own. Then perfom multiplication and create a new column. In order to get top 5 trades you have to groupby and then sort in decreasing order of count before picking top 5. df = pd.read_csv("foo.csv", header=None, names=['instrument','qty', 'price']) df['amt'] = df['qty'] * df['price'] g = df.groupby('instrument').agg({ 'instrument':'count', 'qty':'sum', 'amt':'sum' }).rename(columns={'instrument':'count'}).sort_values(by=['count'], ascending=False).head(5) for msg in (pd.Series(g['instrument'].map(str) + ": " + g['count'].map(str) + " trade(s) total of " + g['qty'].map(str) + " shares, $ " + round(g['amt'],2).map(str)).values): print(msg) Output: GOOG: 4 trade(s) total of 400 shares, $ 360302.5 AAPL: 3 trade(s) total of 850 shares, $ 129409.5 IBM: 2 trade(s) total of 15 shares, $ 2278.85 INTC: 1 trade(s) total of 200 shares, $ 7248.0 MSFT: 1 trade(s) total of 50 shares, $ 3449.5
score: 0
has comment: http://stackoverflow.com/comment/89910754
has comment: http://stackoverflow.com/comment/89893469
type: Answer
answers question: http://stackoverflow.com/q/51444913

http://stackoverflow.com/comment/89777303
score: 4
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51400486
has text: I found it, I called a os.chdir in a test and it caused the coverage to be send elsewhere. Thx for your help stx101

http://stackoverflow.com/a/51393804
answers question: http://stackoverflow.com/q/51393759
type: Answer
accepted answer of: http://stackoverflow.com/q/51393759
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89759842
has comment: http://stackoverflow.com/comment/89761208
upvote count: 1
has body: As far as I know, python scripts are not executed in Ionic. By writing python code we can though, access services which are written in Python by writing the API call from 'providers' in ionic.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89763456

http://stackoverflow.com/a/51359265
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89694673
has comment: http://stackoverflow.com/comment/89691073
downvote count: 0
has body: I checked both urls using my browser, and it looks like in second one there is no span with id priceblock_ourprice. So of course driver.find_element_by_xpath can't find apropriate span. However I can find this span: $62.26 Perhaps the content of the page server by amazon is different when you use your browser and different when running selenium (because of cookies for example). Please double check source of page you got in selenium.
has comment: http://stackoverflow.com/comment/89691898
type: Answer
answers question: http://stackoverflow.com/q/51359029

http://stackoverflow.com/comment/89695146
score: 1
type: Comment
comment on: http://stackoverflow.com/a/51344433
has text: and,your answer is what I want to do.
type: AnswerComment

http://stackoverflow.com/comment/89746977
type: QuestionComment
comment on: http://stackoverflow.com/q/51370752
score: 0
type: Comment
has text: You are not using the ORM. Those are so called Core constructs: "The SQLAlchemy Expression Language presents a system of representing relational database structures and expressions using Python constructs. These constructs are modeled to resemble those of the underlying database as closely as possible, while providing a modicum of abstraction of the various implementation differences between database backends." Iow you're in a way already writing SQL yourself.

http://stackoverflow.com/q/51392868
has answer: http://stackoverflow.com/a/51392901
has body: Based on user input I need to pass custom arguments into Django filter. Something along the lines of the following: q = Question.objects.all() a = q.filter(O_Stat__icontains = "Active", Ll_Name__icontains = "fruit") I tried setting the arguments to string: f = 'Operating_Status__icontains = "Active", Legal_Name__icontains = "fruit"' a = q.filter(f) Get a stack trace error. Is there a better solution then to pass every possible field into the filter ? #Like This a = q.filter(O_Stat__icontains = UserIn1, Ll_Name__icontains = UserIn2) Regards.
type: Question
answer count: 1
accepted answer: http://stackoverflow.com/a/51392901
score: 0
tagged with: sql
tagged with: django
tagged with: python
type: AnsweredQuestion
has title: Passing multiple arguments into Django's filter()

infinite-loop
tags question: http://stackoverflow.com/q/51433663
type: Tag
tag name: infinite-loop

http://stackoverflow.com/comment/89884413
type: Comment
has text: Very nice work. You made sure that the normal functionality of a class doesn't break, and added the functionality i asked for. Very nice!
comment on: http://stackoverflow.com/a/51448192
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89854555
has text: Bolivia: - salt pans Peru: Chile: same as layout as outlined in post
comment on: http://stackoverflow.com/q/51442309
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51405261
score: 1
upvote count: 1
has body: Rather than using the input function, you could user tkinter's askstring command. This will bring up a small dialog box with the question asked and return the user's entry to the script. import tkinter as tk import tkinter.simpledialog as sd def getUserInput(): userInput = sd.askstring('User Input','Enter your name') print(f'You said {userInput}') root = tk.Tk() btn = tk.Button(root,text="Get Input", command=getUserInput) btn.grid() root.mainloop() If you wish to ask for numerical values, tkinter also has askfloat and askinteger functions. These allow you to specify minimum and maximum values. import tkinter as tk import tkinter.simpledialog as sd def getUserInput(): userInput = sd.askstring('User Input','Enter your name') print(f'You said {userInput}') def getUserFloatInput(): options = {'minvalue':3.0,'maxvalue':4.0} userInput = sd.askfloat('User Input','Enter an approximation of Pi',**options) print(f'You said pi is {userInput}') def getUserIntegerInput(): options = {'minvalue':4,'maxvalue':120} userInput = sd.askinteger('User Input','How old are you?',**options) print(f'You said you are {userInput}') root = tk.Tk() btn1 = tk.Button(root,text="Get String Input", command=getUserInput) btn1.grid() btn2 = tk.Button(root,text="Get Float Input", command=getUserFloatInput) btn2.grid() btn3 = tk.Button(root,text="Get Integer Input", command=getUserIntegerInput) btn3.grid() root.mainloop()
downvote count: 0
answers question: http://stackoverflow.com/q/51394482
type: Answer

http://stackoverflow.com/comment/89724686
score: 3
type: QuestionComment
type: Comment
has text: If you open the file outside of python, does it contain data?
comment on: http://stackoverflow.com/q/51376555

http://stackoverflow.com/q/51362595
tagged with: python
has comment: http://stackoverflow.com/comment/89697727
tagged with: generator
has body: I'm still new to generators in python. I was trying out one on my own and tried to something really simple: def fib(a): ... if a==0 or a==1:return 1 ... yield fib(a-1)+fib(a-2) print(list(fib(5)) This code gave me this error: TypeError: unsupported operand type(s) for +: 'generator' and 'generator' Can't generators be used in this manner?
linked to: http://stackoverflow.com/q/231767
score: 1
has title: Generator error in python
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89697808
tagged with: fibonacci
has answer: http://stackoverflow.com/a/51363114
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/51362822
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51362809
type: UnansweredQuestion

http://stackoverflow.com/comment/89887632
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51459007
has text: have the objective intuition, instead of the list intuition.

http://stackoverflow.com/comment/89874456
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51416599
score: 0
has text: What do you mean by cleaning up the entire column? Does it mean not only removing tags but replacing them with whitespaces, or just aligning the data to "Estimate" column?

http://stackoverflow.com/comment/89741761
type: Comment
type: QuestionComment
has text: Added an answer.
comment on: http://stackoverflow.com/q/51384841
score: 0

http://stackoverflow.com/a/51445144
has body: Solver convention differences could be at play, or slight variances in the tolerance values. To test this, do you get the same result if you use the Pyomo model with a GAMS solver? SolverFactory('gams').solve(model, tee=True, solver=???)
has comment: http://stackoverflow.com/comment/89917839
score: 0
answers question: http://stackoverflow.com/q/51438892
has comment: http://stackoverflow.com/comment/91080524
type: Answer

http://stackoverflow.com/q/51449912
accepted answer: http://stackoverflow.com/a/51450324
has comment: http://stackoverflow.com/comment/89870397
tagged with: pycharm
has comment: http://stackoverflow.com/comment/89870413
has comment: http://stackoverflow.com/comment/89870481
has comment: http://stackoverflow.com/comment/89870613
has comment: http://stackoverflow.com/comment/89871010
upvote count: 1
downvote count: 1
has body: I am using pycharm , i am having this error by adding any package , Click Here i have tried lot of methods , but didn't succeed yet. Info : python 3.6.2 pip 10.0.1 VirtualEnv
type: Question
has comment: http://stackoverflow.com/comment/89870697
has comment: http://stackoverflow.com/comment/89870352
has comment: http://stackoverflow.com/comment/89870774
has comment: http://stackoverflow.com/comment/89870560
score: 0
has answer: http://stackoverflow.com/a/51450324
answer count: 1
favorite count: 0
has title: use correct version of 'pip' installed for your Python interpreter
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/89871000
linked to: http://stackoverflow.com/q/22640640
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89870439

http://stackoverflow.com/comment/89850424
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51437134
score: 1
has text: The space which is used for the plots is defined by the `rect` kwarg of `tight_layout()`. The four numbers are the corners of the rectangle which is used for that. Increase x2 (i.e. 0.85) and the gap between the plots and the legend will shrink, decrease it and it will grow. The same with the value y2 (0.9) with regards to the title.

http://stackoverflow.com/comment/89656092
score: 0
type: QuestionComment
type: Comment
has text: Does your `if` in `readresponse()` in `except`?
comment on: http://stackoverflow.com/q/51341314

http://stackoverflow.com/comment/139109428
type: AnswerComment
score: 0
type: Comment
has text: So, we can not send mesage to user by integer id? Does we always need profile entity?
comment on: http://stackoverflow.com/a/54516321

http://stackoverflow.com/q/51404194
tagged with: tkinter
score: 0
has comment: http://stackoverflow.com/comment/89779390
type: AnsweredQuestion
has body: I am currently developing a calculator app in Python where when you click a button, it enters the symbol on that button into the entry box displayed at the top of the window. However, when I click a number button - let's say I click the button with "4" on it, and then I click the button with "6" on it, the entry box shows the number 64, and not the number 46. Here is the code for inserting the number 1 into the entry box (named user_output) when the "1" button is clicked: def insert_one(): user_output.insert(0, "1") Here is what you'd get if you were to type in 563 into the calculator: http://prntscr.com/k7zugb Does anybody know how to fix this? EDIT: A user called Bryan Oakley asked for an illustration to show some of the code. Here is the demonstration so you can see how the code works when numbers are entered into user_output: try: from Tkinter import * except ImportError: from tkinter import * window = Tk() window.title("Demo") window.geometry("323x75") def insert_one(): user_output.insert(0, "1") def insert_two(): user_output.insert(0, "2") def insert_three(): user_output.insert(0, "3") user_output = Entry(width=53, justify=LEFT) one = Button(text="1", height=3, width=2, justify=LEFT, command=insert_one) two = Button(text="2", height=3, width=2, justify=LEFT, command=insert_two) three = Button(text="3", height=3, width=2, justify=LEFT, command=insert_three) user_output.grid(row=0, columnspan=3) one.grid(row=1, column=0, sticky=N+S+E+W) two.grid(row=1, column=1, sticky=N+S+E+W) three.grid(row=1, column=2, sticky=N+S+E+W) window.mainloop()
has comment: http://stackoverflow.com/comment/89779919
has comment: http://stackoverflow.com/comment/89779528
has answer: http://stackoverflow.com/a/51404646
type: Question
has title: How do I put numbers the right way around in Entry box using <entry_box_name>.insert
has comment: http://stackoverflow.com/comment/89780043
has comment: http://stackoverflow.com/comment/89780014
answer count: 1
accepted answer: http://stackoverflow.com/a/51404646
tagged with: python
tagged with: calculator

http://stackoverflow.com/a/51420632
type: AcceptedAnswer
has body: Try this - re.sub(u'[()]', '', re.search(u"[(]\d{4}[)]", "this car(chevelon) is manufactured in China(2012)").group(0)) Will O/P - 2014 Reason for this pattern is - [(]\d{4}[)] We need to make sure our four digits are between the parentheses
type: Answer
has comment: http://stackoverflow.com/comment/89826627
accepted answer of: http://stackoverflow.com/q/51420402
answers question: http://stackoverflow.com/q/51420402
score: 0

http://stackoverflow.com/a/51473054
type: Answer
has comment: http://stackoverflow.com/comment/131265102
has body: In my opinion in such case it would be better to first parse those arguments using argparse. That way you can get Namespace object, that can be modified and much easier to maintain than hardcodingsys.argv. After that you can modify Namespace any way you want Small example: def parse_args(): parser = argparse.ArgumentParser(description="Description") parser.add_argument('--file_path') parsed_args = parser.parse_args() return parsed_args if __name__ == '__main__': args = parse_args() print(args.file_path) # the argument passed while running script args.another_value = "value" print(args.another_value) # value added within code setattr(args, 'yet_another', 'value') # another way to set attributes
answers question: http://stackoverflow.com/q/51472873
score: 0
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/89859985
comment on: http://stackoverflow.com/q/51362314
has text: This template must be the return of a `view`. You can inject a context to the template, like this: https://docs.djangoproject.com/en/2.0/intro/tutorial03/#write-views-that-actually-do-something
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51430488
has body: A better solution is to use a SortedSet from http://www.grantjenks.com/docs/sortedcontainers/index.html. Before inserting an element you check irange_key all values within +- tolerance. If nothing is there, then add this element. This solution should be at least an order of magnitude faster than the close_set approach already suggested, and an order of magnitude better as well on memory usage. Plus it will work for floats as well as integers if you should need that.
has comment: http://stackoverflow.com/comment/89832432
has comment: http://stackoverflow.com/comment/89832975
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51429844
downvote count: 0
has comment: http://stackoverflow.com/comment/89835776
score: 1

http://stackoverflow.com/comment/89786890
type: QuestionComment
score: 1
has text: No references to external libraries, please. Mock up a simple dataframe which demonstrates your problem. See [mcve].
comment on: http://stackoverflow.com/q/51407524
type: Comment

http://stackoverflow.com/q/51325685
tagged with: python
has title: How to terminate process created by Python Popen
score: 2
has answer: http://stackoverflow.com/a/51326075
tagged with: subprocess
tagged with: terminate
type: Question
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51325747
upvote count: 2
has body: I'm running calc.exe (windows 10, python 3.6) using proc = subprocess.Popen("calc.exe"), then time.sleep(time) and then want to kill process: os.kill(proc.pid, -9) or os.kill(proc.pid, signal.SIGTERM) gives me error "Access Denied". I also tried proc.terminate - it didn't help. And I also noticed that proc.pid gives different PID from PID which is shown in task manager. Any ideas how to kill my process? Thanks!
has comment: http://stackoverflow.com/comment/89627131
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/2868129

http://stackoverflow.com/a/51481543
accepted answer of: http://stackoverflow.com/q/51481373
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51481373
score: 4
has body: Your bytearray is represented as a string. When a string is represented for human eyes the characters are displayed according to the current encoding (ASCII, utf-8, etc.). In your current encoding, the character with the value 0x23 is a hash-symbol (#). Only for the bytes which do not have a character representation (0x00, etc.) the hex representation is displayed (e.g. \x00). So what you see is absolutely correct because you asked (maybe without knowing) for a string representation of your byte array. If you want to see a hex value for each byte, use data1.hex(). This will create a hex representation for each byte and concatenate all of these. The result will be a string containing only hex digits (0-9 and a-f). This is only useful for printing, in most cases it is not useful for further processing. In Python3, consider using bytes([0x00, 0x01, ...]) instead. That will produce a bytes object which is more native to the language (e.g. many functions like write(), send(), etc. will accept it as input). It also has a hex() method as described above.
type: Answer
upvote count: 4
downvote count: 0

http://stackoverflow.com/q/51396841
tagged with: multithreading
type: Question
has body: I have a main thread that gets connections and immediately spawns new threads then inside the thread it receives a name that gets logged, currently my threads are named Thread-n. I would like to change the name of the thread from inside. I found this, but it sadly only works on linux, any similar program to do this on Windows?
has title: How to change a python thread name from inside the thread on Windows?
has answer: http://stackoverflow.com/a/51396977
score: 15
linked to: http://stackoverflow.com/q/34361035
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 15
downvote count: 0

http://stackoverflow.com/comment/89805155
type: Comment
comment on: http://stackoverflow.com/a/51409150
has text: @SaraWasl You are welcome! :)
score: 0
type: AnswerComment

http://stackoverflow.com/q/51345287
favorite count: 0
has body: Banking_Deposits = {'January':[15000,9800,10100], 'Feburary':[2500,1400,14100], 'March': [20000,78366]} total_dep = sum(Banking_Deposits.values()) I would like to get the value sum of the total deposit made in all the 3 months. However I was returned with this error: TypeError: unsupported operand type(s) for +: 'int' and 'list'
answer count: 3
tagged with: python
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51345320
upvote count: 1
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51345317
has title: Getting the sum of all values in a nested list dictionary
type: Question
has answer: http://stackoverflow.com/a/51346068
possible better answer: http://stackoverflow.com/a/51345317
downvote count: 0
has answer: http://stackoverflow.com/a/51345320

http://stackoverflow.com/a/51414253
downvote count: 0
has body: As indicated in scipy issue #609 on github, the signaltonoise function [...] is not useful except for backwards compatibility. The reason is that there's a Matlab signal-to-noise function http://www.mathworks.com/help/signal/ref/snr.html which means something different. This is not good, because scipy clones the Matlab interface of other signal-related functions, and this incompatibility apparently has no offsetting benefit. If you do need this function for backward compatibility, the short implementation can be found in the history of scipy repository as (reproduced here without the documentation comments, license): def signaltonoise(a, axis=0, ddof=0): a = np.asanyarray(a) m = a.mean(axis) sd = a.std(axis=axis, ddof=ddof) return np.where(sd == 0, 0, m/sd)
type: Answer
answers question: http://stackoverflow.com/q/51413068
score: 19
upvote count: 19
accepted answer of: http://stackoverflow.com/q/51413068
type: AcceptedAnswer

http://stackoverflow.com/q/51440046
has answer: http://stackoverflow.com/a/51440230
tagged with: sorting
favorite count: 0
answer count: 1
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: What I have is: models.py: class Address(custom_mixins.SiteAwareAbstractModel): states = State.objects.all() CHOICES = list() for state in states: CHOICES.append((state.code, state.name)) CHOICES = tuple(CHOICES) state_name = models.CharField(max_length=80, choices=CHOICES) Then the State class class State(models.Model): name = models.CharField(max_length=256) code = models.CharField(max_length=2, null=True) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['-id'] def __str__(self): return '{}'.format(self.name) This renders all the states as they're stored in the table. What I want is to display all the states in the alphabetically order. I tried doing: states = State.objects.all().order_by( 'name').values_list( 'code', flat=True) But this threw the error CHOICES.append((state.code, state.name)) AttributeError: 'str' object has no attribute 'code'
score: 2
downvote count: 0
type: Question
upvote count: 2
has title: django: sort the table data according alphabetically

http://stackoverflow.com/q/51409927
type: Question
upvote count: 3
tagged with: pandas
answer count: 1
has title: Python- Selecting pairs of objects from a data frame
favorite count: 0
has comment: http://stackoverflow.com/comment/89791471
tagged with: python
has body: I have a data frame that contains information about the positions of various objects, and a unique index for each object (index in this case is not related to the data frame). Here is some example data: ind pos x y z -1.0 7.0 0.0 21 [-2.76788330078, 217.786453247, 26.6822681427] 0.0 22 [-7.23852539062, 217.274139404, 26.6758270264] 0.0 1.0 152 [-0.868591308594, 2.48404550552, 48.4036369324] 6.0 2.0 427 [-0.304443359375, 182.772140503, 79.4475860596] The actual data frame is quite long. I have written a function that takes two vectors as inputs and outputs the distance between them: def dist(a, b): diff = N.array(a)-N.array(b) d = N.sqrt(N.dot(diff, diff)) return d and a function that, given two arrays, will output all the unique combinations of elements between these arrays: def getPairs(a, b): if N.array_equal(a, b): pairs = [(a[i], b[j]) for i in range(len(a)) for j in range(i+1, len(b))] else: pairs = [(a[i], b[j]) for i in range(len(a)) for j in range(len(b))] return pairs I want to take my data frame and find all the pairs of elements whose distance between them is less than some value, say 30. For the pairs that meet this requirement, I also need to store the distance I calculated in some other data frame. Here is my attempt at solving this, but this turned out to be extremely slow. pairs = [getPairs(list(group.ind), list(boxes.get_group((name[0]+i, name[1]+j, name[2]+k)).ind)) \ for i in [0,1] for j in [0,1] for k in [0,1] if name[0]+i != 34 and name[1]+j != 34 and name[2]+k != 34] pairs = list(itertools.chain(*pairs)) subInfo = pandas.DataFrame() subInfo['pairs'] = pairs subInfo['r'] = subInfo.pairs.apply(lambda x: dist(df_yz.query('ind == @x[0]').pos[0], df_yz.query('ind == @x[1]').pos[0])) Don't worry about what I'm iterating over in this for loop, it works for the system I'm dealing with and isn't where I'm getting slowed down. The step I use .query() is where the major jam happens. The output I am looking for is something like: pair distance (21, 22) 22.…
has answer: http://stackoverflow.com/a/51410781
accepted answer: http://stackoverflow.com/a/51410781
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/89791821
has comment: http://stackoverflow.com/comment/89791256
downvote count: 0

http://stackoverflow.com/a/51443106
has comment: http://stackoverflow.com/comment/89876751
answers question: http://stackoverflow.com/q/51438894
has comment: http://stackoverflow.com/comment/89876223
has body: You can actually add those meds as features, something like this: data=pd.DataFrame({'gender':['m','f','m'],'icds':[['i10'],['i20','i30'],['i40']],'med':[['xanex','isotopin'],['cz3','hicet','t-montair'],['t-montair','xanex']]}) all_med= list(np.unique(flatten(list(data['med'].values)))) for meds in all_med: med_list=[] for i in xrange(len(data)): d= data['med'][i] if meds in d: med_list.append(1) else: med_list.append(0) data[meds]=med_list Output: gender icds med cz3 hicet isotopin \ 0 m [i10] [xanex, isotopin] 0 0 1 1 f [i20, i30] [cz3, hicet, t-montair] 1 1 0 2 m [i40] [t-montair, xanex] 0 0 0 t-montair xanex 0 0 1 1 1 0 2 1 1
type: Answer
has comment: http://stackoverflow.com/comment/89875660
score: 0

http://stackoverflow.com/q/51369215
tagged with: z3
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51370304
upvote count: 1
tagged with: z3py
has answer: http://stackoverflow.com/a/51370305
type: Question
possible better answer: http://stackoverflow.com/a/51370304
has title: Z3 BitVec extraction using symbolic high and low
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/51370305
score: 1
favorite count: 0
tagged with: python
has body: I've been playing around with proving certain SIMD vectorizations using Z3 and I'm running into a problem trying to model SIMD operations that conditionally move around bits or lanes (such as Intel _mm_shuffle_epi8 for example) The problem occurs when I try to use symbolic high and low with Extract which does not seem supported: assert a.sort() == BitVecSort(128) assert b.sort() == BitVecSort(128) Extract( Extract(i+3,i,b)*8+7, Extract(i+3,i,b)*8, a) results in z3.z3types.Z3Exception: Symbolic expressions cannot be cast to concrete Boolean values. The problem appears to be two-fold: Z3 does not appear to support symbolically sized BitVecs &gt;&gt;&gt; a = Int('a') &gt;&gt;&gt; b = BitVec('b', a) ctypes.ArgumentError: argument 2: &lt;class 'TypeError'&gt;: wrong type Would be neat, but alas. As a result, Extract needs to be able to know the precise BitVec sort of its return value, and demands that both high and low are concrete, even though it appears the only real requirement should be that simplify(high - low) results in a concrete value. What's the correct way of doing this?

http://stackoverflow.com/comment/89926032
score: 0
comment on: http://stackoverflow.com/q/51478739
type: QuestionComment
type: Comment
has text: Possible duplicate of [How to extract specific columns from a space separated file in Python?](https://stackoverflow.com/questions/25768230/how-to-extract-specific-columns-from-a-space-separated-file-in-python)

http://stackoverflow.com/comment/89626472
comment on: http://stackoverflow.com/a/51325650
has text: @GvidoKārlisŠķuburs as Chris has pointed out, my solution only accounts for adding points, not removing them, which complicates it a bit more and no longer makes it the optimal way to do it. You may need to recalculate highest scores using one of the other listed ways at the end
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/51430004
has body: I need some help on this problem I'm working on. It needs me to write a function that inputs a list and removes any empty lists inside it. This is what I have so far: a = [] b = [] def listmaking(a): List = [] List = input.append() List = input.split(" ") return List for item in a: if item!=[]: b.append(item) print(b) I don't know where I am going wrong here. Any help would be appertained!
upvote count: 0
score: -1
has answer: http://stackoverflow.com/a/51430325
has answer: http://stackoverflow.com/a/51430102
answer count: 3
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89831055
has answer: http://stackoverflow.com/a/51430041
downvote count: 1
has title: Adding and removing lists
type: Question

http://stackoverflow.com/a/51348150
upvote count: 1
has comment: http://stackoverflow.com/comment/89679239
has body: You can feed your LSTM output into many different layers (or neural functions, in general), which lead to different outputs, and then train your model on each of these outputs concurrently: from keras.models import Model from keras.layers import Input, Dense, LSTM # function definitions lstm_function = LSTM(..args) pitch_function = Dense(num_pitches, activation='softmax') duration_function = Dense(num_durations, activation='softmax') input_features = Input(input_dimensionality) # function applications lstm_output = lstm_function(input_features) pitches = pitch_function(lstm_output) durations = duration_function(lstm_output) # model model = Model(inputs=[input_features], outputs=[pitches, durations]) model.compile(loss=['categorical_crossentropy', 'mse'], optimizer='RMSProp') This may be generalized to arbitrary information flows, with as many layers/outputs as you need. Remember that for each output you need to define a corresponding loss (or None).
has comment: http://stackoverflow.com/comment/89675517
downvote count: 0
type: AcceptedAnswer
score: 1
accepted answer of: http://stackoverflow.com/q/51347933
answers question: http://stackoverflow.com/q/51347933
type: Answer

http://stackoverflow.com/a/51434837
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89866948
accepted answer of: http://stackoverflow.com/q/51433620
has body: You can use scatter so as to make points: import numpy as np import pandas as pd import matplotlib.pyplot as plt shape = (100,2) df = pd.DataFrame(np.random.randn(*shape), columns=['x', 'y']) df.boxplot(return_type='axes') q975 = df.quantile(0.975) q025 = df.quantile(0.025) mean = df.mean() plt.scatter(range(1,shape[1]+1), q975, c='m', label='Q_97.5') plt.scatter(range(1,shape[1]+1), q025, c='r', label='Q_2.5') plt.scatter(range(1,shape[1]+1), mean, c='k', label='Mean') plt.legend() plt.show()
answers question: http://stackoverflow.com/q/51433620
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/89681616
score: 1
type: AnswerComment
has text: gaganso, I need `Failure reason` and `Target system address` for all the rows with Platform IDs of the form CS-Unix-*, in that case what would be the `hostnames`.
comment on: http://stackoverflow.com/a/51354488
type: Comment

http://stackoverflow.com/comment/89935859
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51453595
type: Comment
has text: My bad I messed up in the question. The address is in quotes but it still doesn't work, i'll edit the question.

http://stackoverflow.com/a/51439808
has comment: http://stackoverflow.com/comment/89879139
type: Answer
has comment: http://stackoverflow.com/comment/89878835
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89858516
has comment: http://stackoverflow.com/comment/89857120
has body: No, you don't need a defined function to employ scipy's griddata. We can interpolate any given dataset, e.g., z = x² + y² + 1 with some data points removed: 0 0 1 1 0 2 3 0 10 0 1 2 1 1 3 2 1 6 0 2 5 1 2 6 2 2 9 3 2 14 0 3 10 2 3 14 3 3 19 The following code interpolates a 3D surface from these data points: import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from scipy.interpolate import griddata #read data points from text file, could be also a csv reader arr = np.genfromtxt("test.txt") #extract x, y, z x = arr[:,0] y = arr[:,1] z = arr[:,2] #create figure with a 3D projection axis fig = plt.figure() ax = fig.add_subplot(111, projection="3d") #number of data points per axis n = 20 #upsample evenly along x and y axis x_up = np.linspace(np.min(x), np.max(x), n) y_up = np.linspace(np.min(y), np.max(y), n) #create grid from these updsampled 1D arrays x3d, y3d = np.meshgrid(x_up, y_up) #interpolate z-values for this regular grid #x, y, z are your original data points #methods other than cubic are available z3d = griddata((x, y), z, (x3d, y3d), method = "cubic") #plot surface ax.plot_surface(x3d, y3d, z3d) #plot original data points on top ax.scatter(x, y, z, color = "black", marker = "x", s = 50) ax.set_xlabel("X") ax.set_ylabel("Y") ax.set_zlabel("Z") plt.show() Sample output:
has comment: http://stackoverflow.com/comment/89854719
accepted answer of: http://stackoverflow.com/q/51436766
answers question: http://stackoverflow.com/q/51436766
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/89900252
type: Comment
has text: No, if you do not expect two objects of this class to be compared.
comment on: http://stackoverflow.com/a/51465694
score: 0
type: AnswerComment

http://stackoverflow.com/q/51468969
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51469017
tagged with: dataframe
has body: Here is my first dataframe df1, Open High Low Close Date 2018-07-16 2797.360107 2801.189941 2793.389893 2798.429932 2018-07-17 2789.340088 2814.189941 2789.239990 2809.550049 2018-07-18 2811.350098 2816.760010 2805.889893 2815.620117 2018-07-19 2809.370117 2812.050049 2799.770020 2804.489990 2018-07-20 2804.550049 2809.699951 2800.010010 2801.830078 Now i want to add 21 July which is in another dataframe df2 for eg., Date Prediction 0 2018-07-25 2111.111 Now how should I add 2018-07-21 as df1 index and data corresponding to it should be df2['Prediction'] for Close column else other column can be 0. So final df should be like this, Open High Low Close Date 2018-07-16 2797.360107 2801.189941 2793.389893 2798.429932 2018-07-17 2789.340088 2814.189941 2789.239990 2809.550049 2018-07-18 2811.350098 2816.760010 2805.889893 2815.620117 2018-07-19 2809.370117 2812.050049 2799.770020 2804.489990 2018-07-20 2804.550049 2809.699951 2800.010010 2801.830078 2018-07-21 0 0 0 2111.111
answer count: 2
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/51469054
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Add new Datetime to Datetime Index Pandas dataframe with value
tagged with: datetimeindex

http://stackoverflow.com/comment/89919692
score: 1
comment on: http://stackoverflow.com/a/51473300
type: AnswerComment
has text: @JamesSoh In Python 2.7 you can create a list that is representing your disambiguation of choices, e.g. `X = ['A'] + 6*['B'] + 3*['C']`, and then call `random.choice(X)`
type: Comment

http://stackoverflow.com/q/51406359
score: 1
answer count: 2
possible better answer: http://stackoverflow.com/a/51411012
has comment: http://stackoverflow.com/comment/89784216
downvote count: 0
has comment: http://stackoverflow.com/comment/89784770
has answer: http://stackoverflow.com/a/51411012
has comment: http://stackoverflow.com/comment/89784962
favorite count: 0
accepted answer: http://stackoverflow.com/a/51412638
has body: I know this is a repeat but I've looked through the answers and none of them make sense to why I'm getting ValueError: I/O operation on closed file in this specific python 2.7 function written here. No error when separating this out to a stand alone sciptlet of: import hashlib import sys sha256_hash = hashlib.sha256() filename = 'result.txt' with open(filename,"rb") as f: # Read and update hash string value in blocks of 4K for byte_block in iter(lambda: f.read(4096),b""): sha256_hash.update(byte_block) print(sha256_hash.hexdigest()) f.close() But when I put this into a defined function I get a ValueError on the print function. def sha256hashcheck(): with open( 'goldresult.txt' ,"rb") as f: # Read and update hash string value in blocks of 4K for byte_block in iter(lambda: f.read(4096),b""): sha256_hash.update(byte_block) print(sha256_hash.hexdigest()) f.close() sha256hashcheck() All the other defined functions run the close() method before exiting the function, plus I make a test file on the side that no function calls and use that as the open in the def and I still get the ValueError exception File "parse-o365-ip-addrs.py", line 61, in sha256hashcheck print(sha256_hash.hexdigest()) ValueError: I/O operation on closed file Any pointers or suggestions? TY Here is my entire script .. yes I'm new to python .. :) # Initial code - https://gist.github.com/cdodd/7679fb9c5f2a2e4700c7a9c7a53e2a19 (cdodd) import xmltodict from socket import inet_ntoa from struct import pack import sys import urllib import hashlib # Read from URL data = urllib.urlopen('https://support.content.office.net/en-us/static/O365IPAddresses.xml').read() doc = xmltodict.parse(data) # Read from local file # doc = xmltodict.parse(open('/path/to/file.xml').read()) # set your variables subnettestVar = 'test.txt' subnetresultVar = 'result.txt' subnetgoldVar = 'goldresult.txt' sha256_hash = hashlib.sha256() #define your functions or classes def calcDottedNetmask(mask): bits = 0xffffffff ^ (1 &lt;&lt; 32 - mask…
tagged with: python-2.7
tagged with: file-io
has comment: http://stackoverflow.com/comment/89784235
tagged with: python
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89784135
has title: I/O operation on closed file in Python def
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51412638

static-methods
tags question: http://stackoverflow.com/q/51460601
tag name: static-methods
type: Tag

http://stackoverflow.com/comment/89913184
comment on: http://stackoverflow.com/q/51472439
has text: Next X lines? Do you want to include the line that has ABC to be printed or not?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89651719
type: QuestionComment
has text: Can you tell us a bit more about what `fun` does and what its output is (perhaps even post its code)? The best solution could well depend on the exact nature of `fun` (to what extent its affected by the GIL, how large its output is, that sort of thing).
score: 1
comment on: http://stackoverflow.com/q/51338573
type: Comment

http://stackoverflow.com/comment/89908518
score: 0
type: Comment
type: QuestionComment
has text: Can you post it as an answer so that I get to accept it and close the question?
comment on: http://stackoverflow.com/q/51470075

http://stackoverflow.com/comment/89668470
comment on: http://stackoverflow.com/a/51345989
type: Comment
has text: You are welcome. If you found the answer useful, please accept my answer.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89848326
score: 0
has text: As you can see, `text` only means the inner text of a tag, and it does not "see" `br` tag, it is not correct way to use `text`. Besides, it would just fetch the whole node that contains some text in its inner text, it would not extract any substrings from them. This will extract those nodes since they will match fully: `soup.find_all(text=re.compile(r"^[A-Z0-9#.-]+(?:\s+[-.#A-Z0-9]+)*$"))`
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51439084

http://stackoverflow.com/a/51499602
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51438253
has body: As @Mathieu and @normanius pointed out: It is not possible. Instead vtkFieldData can be used to transfer information through the vtk pipeline.
type: Answer
upvote count: 1
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51438253

http://stackoverflow.com/comment/89737407
has text: @BearBrown, yes, that's the point. He's saying that the code isn't crashing, but he thinks that it should crash.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51382748
score: 0

http://stackoverflow.com/comment/89699853
comment on: http://stackoverflow.com/a/51361583
type: Comment
score: 0
type: AnswerComment
has text: thanks for answering, it works only in sample csv files that i made same as in the picture. When i use csv files that my prof gave me and they both contain 29k records, the program gave me ", line 6, in <module> old_data = dict(csv_old) ValueError: dictionary update sequence element #0 has length 67; 2 is required" error, i wonder if i need to change "dict" to something else to make em work

http://stackoverflow.com/a/51434104
has body: Using list comprehensions and string methods: Given s = """\ a VARCHAR(20), b FLOAT, c FLOAT, d NUMBER(38,0), e NUMBER(38,0) """ Code [z.strip() for y in [x.split(", ") for x in s.split(",\n")] for z in y] # ['a VARCHAR(20)', 'b FLOAT', 'c FLOAT', 'd NUMBER(38,0)', 'e NUMBER(38,0)'] Alternatively [z.strip(",") for y in [x.split(", ") for x in s.splitlines()] for z in y] # ['a VARCHAR(20)', 'b FLOAT', 'c FLOAT', 'd NUMBER(38,0)', 'e NUMBER(38,0)']
type: Answer
answers question: http://stackoverflow.com/q/51433630
score: 0

http://stackoverflow.com/q/51337392
score: 0
has comment: http://stackoverflow.com/comment/89650438
tagged with: python
has comment: http://stackoverflow.com/comment/89649401
answer count: 0
type: UnansweredQuestion
tagged with: pyqtgraph
has title: pyqtgraph: How to color plot axis?
type: Question
has comment: http://stackoverflow.com/comment/132658509
has body: I have tried to color the axis of a pyqtgraph plot in the following line self.PlotWidget.setLabel('bottom', '...') but this just colors the text from the label. So my question is, is there a possibility to color just the black background of the plot? Thanks for your answers!

http://stackoverflow.com/q/51365581
has title: Sympy returns "Key Error" when solving a system of ODEs
answer count: 1
has comment: http://stackoverflow.com/comment/89704986
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/89704278
tagged with: python
has comment: http://stackoverflow.com/comment/89703651
tagged with: differential-equations
tagged with: math
type: Question
tagged with: sympy
has answer: http://stackoverflow.com/a/51366640
has body: I am trying to solve the geodesic equation using the initial values: Where the above is a system of two ODEs. In the code, x1 = T(s) and x2 = P(s) and Γabc = Ga(a,b,c). My code is as shown below: from gravipy import * from sympy import * def distance(t1,p1,t2,p2): init_printing() R = 1737 dimensions = 2 t,p = symbols("t p") x = Coordinates("x",[t,p]) Metric = diag(R**2, R**2*sin(t)**2) g = MetricTensor("g", x, Metric) Ga = Christoffel("Ga", g) T,P = symbols("T P", cls=Function) s = symbols("s") ics = {T(1):t1, T(2):t2, P(1):p1, P(2):p2} system=[] coords = [T(s),P(s)] for a in range(dimensions): eq = coords[a].diff(s,s) for b in range(dimensions): for c in range(dimensions): christ = Ga(a+1,b+1,c+1).replace("t","T(s)") eq += christ * coords[b].diff(s) * coords[c].diff(s) system.append(Eq(eq,0)) print(system) T,P = dsolve(system, [T(s), P(s)], ics=ics) print(T,P) coords=[T(s),P(s)] integral = 0 for mu in range(dimensions): for nu in range(dimensions): integral += g(mu,nu).replace("t","T(s)") * coords[mu].diff(s) * coords[nu].diff(s) print(integrate(sqrt(integral), (s, 1, 2))) distance(1,1,2,2) However, when I run the program, it generates the system of equations: [Eq(-3017169*sin(2*T(s))*Derivative(P(s), s)**2/2 + Derivative(T(s), s, s), 0), Eq(3017169*sin(2*T(s))*Derivative(P(s), s)*Derivative(T(s), s) + Derivative(P(s), s, s), 0)] Or, more readably: but then fails when running dsolve(), with the error: File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\solvers\ode.py", line 584, in dsolve match = classify_sysode(eq, func) File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\sympy\solvers\ode.py", line 1377, in classify_sysode if not order[func]: KeyError: P(s) Where it alternates between P(s) and T(s). It appears that the error occurs when classifying the ODE, so does this mean that sympy is unable to solve the equations?

http://stackoverflow.com/q/51399594
score: 2
tagged with: selenium-chromedriver
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51401932
tagged with: selenium
has comment: http://stackoverflow.com/comment/89774526
type: Question
has body: I'm trying to run chromedriver with this plugin. I downloaded the plugin as .crx and I initialized browser with this extension: from selenium import webdriver from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.add_extension('/path/to/extension.crx') driver = webdriver.Chrome(chrome_options=chrome_options, executable_path='/path/to/chromedriver') The extension is correctly loaded in browser but is not enabled. In order to enable the extension you have to click the extension icon which is outside of DOM. Is there any way to perform this kind of action.
answer count: 2
has comment: http://stackoverflow.com/comment/89774930
has title: start selenium chromedriver with enabled extension
linked to: http://stackoverflow.com/q/18198121
downvote count: 0
has comment: http://stackoverflow.com/comment/89877378
has answer: http://stackoverflow.com/a/51401932
has answer: http://stackoverflow.com/a/54296890
favorite count: 0
has comment: http://stackoverflow.com/comment/89775763
upvote count: 2
possible better answer: http://stackoverflow.com/a/54296890
tagged with: python

http://stackoverflow.com/comment/101843166
score: 0
type: AnswerComment
type: Comment
has text: I seem to be having this same issue. Dropping duplicates might work, but it concerns me that it produces them in the first place. Is there a better solution?
comment on: http://stackoverflow.com/a/51421873

http://stackoverflow.com/a/51378615
score: 1
upvote count: 1
downvote count: 0
has body: You could use numpy import numpy as np x = ['abc', 'def', 'ghi', 'jkl' ] a = np.rot90([list(row) for row in x], 3) result = [''.join(row) for row in a] output: [ 'jgda', 'kheb', 'lifc' ]
type: Answer
answers question: http://stackoverflow.com/q/51378404

http://stackoverflow.com/comment/89648986
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51337082
score: 0
has text: try to assign the result: `a = flatten(wrap_in_lists(1, 2**11))`, the issue is probably when trying to print the result

http://stackoverflow.com/q/51408020
downvote count: 0
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89787611
has body: I'm getting this error when I try to user get_or_create int() argument must be a string, a bytes-like object or a number, not 'tuple' for ubc in Ubc.objects.all(): professional_grade, created = ProfessionalGrade.objects.get_or_create(ubc=ubc) if created: professional_grade.category=0, professional_grade.category_name="BRUTA" professional_grade.experts = 0 professional_grade.coordinators = 0 professional_grade.seniors = 0 professional_grade.researchers = 0 professional_grade.plenos = 0 professional_grade.experience = 0 professional_grade.masters = 0 professional_grade.doctors = 0 professional_grade.save()
favorite count: 0
answer count: 0
has title: django get_or_create int() argument must be a string, a bytes-like object or a number, not 'tuple'
type: UnansweredQuestion
tagged with: django
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89787340

http://stackoverflow.com/comment/89785392
has text: @Chris_Rands I have clarified my questions in a new post https://stackoverflow.com/questions/51406699/python-consolidate-similar-patterns-into-single-consensus-pattern
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51328156

http://stackoverflow.com/comment/89697225
has text: @romainjouin, Ok, I'm leaving this answer up as a sign-post for others who want to test. Unfortunately, I can't test on 0.23 right now. Seems like a problem with the later version.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51362304
type: Comment

http://stackoverflow.com/q/51369440
tagged with: oop
has comment: http://stackoverflow.com/comment/89714966
type: Question
tagged with: function
has answer: http://stackoverflow.com/a/51383959
has body: I Have that code: class Welcome(object): MyHouse='Earth' def say(self, what): print(what, self.MyHouse) welcome = Welcome() Living = ['World', 'Planet', welcome.MyHouse] MyChoice = list(map(lambda choice : setattr(welcome, 'MyHouse', choice), Living)) print(''.join(str(MyChoice) for MyChoice in MyChoice)) getattr(welcome, 'say')('Hello') with this code , I want to use setattr() to change the MyHouse variable according to the strings contained in the Living list, but when I see the results I only get None objects ?, why this and how can I fix it, it would be because setattr does not give output ?. print(MyChoice) Output: [None, None, None]
has comment: http://stackoverflow.com/comment/89711118
score: 0
answer count: 1
has title: Python, map with lambda returns only None Objects on my list()
type: UnansweredQuestion
tagged with: python
tagged with: lambda

http://stackoverflow.com/comment/89858263
score: 0
type: Comment
type: QuestionComment
has text: Use .iloc instead of .loc for location-based indexing
comment on: http://stackoverflow.com/q/51444091

http://stackoverflow.com/comment/89747851
has text: Please present a sample case and your current solution. This should clarify the problem.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51387980

http://stackoverflow.com/q/51377429
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89726642
tagged with: python
answer count: 0
tagged with: tensorflow
type: Question
score: 0
has comment: http://stackoverflow.com/comment/89726469
has body: Using the tf.estimator.LinearClassifier can you run predict on a model with a sub set of features ? Crated a model with 5 features but want to run a prediction with 2 features ? ValueError: Feature capital_gain is not in features dictionary.
has title: Run prediction with subset of features

http://stackoverflow.com/comment/89730839
has text: (1) implement a sensical `__str__` for the mode; (2) you should add a `set_password` function that hashes and stores the password.
comment on: http://stackoverflow.com/q/51379723
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51472136
answer count: 1
has comment: http://stackoverflow.com/comment/89912924
downvote count: 1
has body: I have one central machine and multiple remote machines. Configured passwordless connections to remote machines from central machine. I have to login from central vm to remote vm's and execute script in remote vm's Below is the example, what i am trying Central Machine: #!/bin/sh ssh root@remotemachine1 #run runscript.py in remotemachine1 ssh root@remotemachine2 #run runscript.py in remotemachine2 Remote Machine python runscript.py runscript.py device = ["device1","device2","device3"] for i, x enumerate(device): print "{}. {}".format(i+1, x) select_device = raw_input("Choose Device: ") print "You Selected Device {}".format(device[int(select_device) - 1]) do something .... .... .... .... repeat = raw_input("Do you want to repeat? Y/N:") do something ........ ........ ........ Someone help me how to login and run script in remote1 machine and exit from remote1 machine and run script in remote2 machine.
has comment: http://stackoverflow.com/comment/89928429
linked to: http://stackoverflow.com/q/13928116
has comment: http://stackoverflow.com/comment/89923537
has answer: http://stackoverflow.com/a/51472166
has comment: http://stackoverflow.com/comment/89912714
has comment: http://stackoverflow.com/comment/89913055
duplicate of: http://stackoverflow.com/q/13928116
linked to: http://stackoverflow.com/q/3510673
has title: login to remote machine and run script
type: AnsweredQuestion
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89912676
tagged with: linux
accepted answer: http://stackoverflow.com/a/51472166
tagged with: bash
type: Question
tagged with: ssh
tagged with: python
tagged with: shell
has comment: http://stackoverflow.com/comment/89912926
has comment: http://stackoverflow.com/comment/89912721
upvote count: 2

http://stackoverflow.com/a/51461837
score: 2
accepted answer of: http://stackoverflow.com/q/51461836
has body: This seems to be an issue with Pandas version 0.23.0. In the latest version, 0.23.2, it correctly assigns the labels. import pandas as pd values = [5100,5400,9400,10000,16000,10500,0,0,0,87500,14000,11250] d = {'continuous': values,'label': [0]*6+[1]*6} df = pd.DataFrame(data=d) bins = [-1, 0, 5000000] df['discrete'] = pd.cut(df['continuous'], bins=bins) print(pd.crosstab(df.discrete, df.label)) Gives the desired output label 0 1 discrete (-1, 0] 0 3 (0, 5000000] 6 3
answers question: http://stackoverflow.com/q/51461836
has comment: http://stackoverflow.com/comment/89892743
has comment: http://stackoverflow.com/comment/89892742
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/89892744
has comment: http://stackoverflow.com/comment/89892745

http://stackoverflow.com/q/51414702
has title: Missing parentheses in call to 'print'
upvote count: 2
has comment: http://stackoverflow.com/comment/89801031
has comment: http://stackoverflow.com/comment/89800611
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89802365
has comment: http://stackoverflow.com/comment/89802216
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89800877
downvote count: 6
has body: A small game that guesses numbers, but there are the following errors in pycharm, opening with IDLE is no problem. May I ask what is the reason? #guess number import random #use import function convert random module num = random.randint(0,11) #create random int temp = input ('Please type you guess number: ') #type random str guess = int (temp) #temp convert to int, if the str is decimal could use int(float(temp)) transfer while guess != num: #while loop print ("Sorry! You are wrong.") temp = input ('Please type the number again: ') guess = int (temp) if guess == num: print ('Amazing!') else: if guess &gt; num: print ("The number is high.") else : print ('The number is low.') print ('Congragulation!') D:\Anaconda\python.exe "C:/Users/Sky Talk/PycharmProjects/untitled/Key" File "C:/Users/Sky Talk/PycharmProjects/untitled/Key", line 7 print "dict['name']:",dict['name'] ^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print("dict['name']:",dict['name'])? Process finished with exit code 1 code screenshot error message terminal screenshot
score: -4
type: Question
has answer: http://stackoverflow.com/a/51896235

http://stackoverflow.com/q/51425729
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51425908
accepted answer: http://stackoverflow.com/a/51425908
has body: I have two arrays. Array1 [[-0.23, 0.11], [0.29, -0.37]] Array2 ([5.28, 4.40]) I want to do sum the multiplication of one array by the other Example sum(5.28 *-0.23 + 4.40 * 0.11) = ind1 sum(5.28 *-0.29 + 4.40 * -0.37) = ind2 df -0.7304 -3.1592
tagged with: python
possible better answer: http://stackoverflow.com/a/51425939
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89823064
has answer: http://stackoverflow.com/a/51425939
type: Question
tagged with: numpy
has title: What is the best way to multiply arrays? in Python

http://stackoverflow.com/q/51450334
has answer: http://stackoverflow.com/a/51456421
type: Question
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/89871490
tagged with: sql
has comment: http://stackoverflow.com/comment/89876313
tagged with: sqlite
tagged with: python
has title: sqlite INSERT OR IGNORE doesn't work
has comment: http://stackoverflow.com/comment/89874259
has body: I've been trying for a while but can't find a mistake Here's my table: CREATE TABLE IF NOT EXISTS participants( FirstName TEXT, LastName TEXT, ChatID INTEGER, UNIQUE(ChatID) )" And here's how I try to insert data: INSERT OR IGNORE INTO participants ( FirstName, LastName, ChatID) VALUES (?, ?, ?)", (FirstName ,LastName , ChatID)) I've tried creating using PRIMARY KEY instead of UNIQUE but that didn't work too. I'm using SQLite with Python if that matters. def create_first_table(): cursor = connection.cursor() cursor.execute("CREATE TABLE IF NOT EXISTS participants(FirstName TEXT, LastName TEXT, ChatID INTEGER, UNIQUE(ChatID) )") cursor.close() def dynamic_data_entry(fname, lname, chatid): cursor = connection.cursor() FirstName = fname LastName = lname ChatID = chatid cursor.execute("INSERT OR IGNORE INTO participants (FirstName , LastName , ChatID ) VALUES (?, ?, ?)", (FirstName ,LastName , ChatID )) connection.commit() cursor.close()
has comment: http://stackoverflow.com/comment/89871529
favorite count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 2

http://stackoverflow.com/comment/89893169
comment on: http://stackoverflow.com/q/51462068
type: Comment
type: QuestionComment
score: 0
has text: Because you're yielding an `item_id` of "".

http://stackoverflow.com/comment/89871393
type: Comment
type: QuestionComment
has text: PowercontrolA and PowercontrolB have different method definitions depending on what hardware I am using.
comment on: http://stackoverflow.com/q/51450298
score: 0

http://stackoverflow.com/q/51434996
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51435305
downvote count: 1
has answer: http://stackoverflow.com/a/51435009
accepted answer: http://stackoverflow.com/a/51435009
type: Question
possible better answer: http://stackoverflow.com/a/51435241
has body: I have the following code: #!/usr/bin/python2.7 import json, re, sys x = json.loads('''{"status":{"code":"200","msg":"ok","stackTrace":null},"dbTimeCost":11,"totalTimeCost":12,"hasmore":false,"count":5,"result":[{"_type":"Compute","_oid":"555e262fe4b059c7fbd6af72","label":"lvs3b01c-ea7c.stratus.lvs.ebay.com"},{"_type":"Compute","_oid":"555e27d8e4b059c7fbd6bab9","label":"lvs3b01c-9073.stratus.lvs.ebay.com"},{"_type":"Compute","_oid":"555e27c9e4b059c7fbd6ba7e","label":"lvs3b01c-b14b.stratus.lvs.ebay.com"},{"_type":"Compute","_oid":"555e2798e4b0800601a83b0f","label":"lvs3b01c-6ae2.stratus.lvs.ebay.com"},{"_type":"Compute","_oid":"555e2693e4b087582f108200","label":"lvs3b01c-a228.stratus.lvs.ebay.com"}]}''') print x['result'][4]['label'] sys.exit() The desired result should be all the labels. But, when I run it, it only prints the first label. What am I doing wrong here? And also, before I could figure out that "result" was the key to use, I needed to copy and paste the json data to a site like "jsonlint.com" to reformat it in a readable fashion. Im wondering if there's a better way to do that, preferably without having to copy and paste the json data anywhere. So two questions: How do I get the above code to list all the labels How do I know the key to the field I want, without having to reformat the given ugly one liner json data
score: 0
answer count: 3
upvote count: 1
favorite count: 0
has title: loop through json elements for a list of values
has answer: http://stackoverflow.com/a/51435241

http://stackoverflow.com/q/51445874
has comment: http://stackoverflow.com/comment/89875033
favorite count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 4
has comment: http://stackoverflow.com/comment/89863798
upvote count: 0
has body: i have this code right now: import os import time import datetime import csv year = 2017 month = 12 day = 5 hour = 19 minute = 50 second = 0 date = datetime.datetime(year=year, month=month, day=day, hour=hour, minute=minute, second=second) modTime = time.mktime(date.timetuple()) with open('Book1.csv', newline='') as csvfile: spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in spamreader: rows = ''.join(row) os.utime(rows, (modTime, modTime)) print("done") when i print rows it works fine and prints c:\test for example when i run utime it says it cant find c:\\test which makes sense. in the csv file it just says C:\ how can i solve it so it only makes one backslash.
has comment: http://stackoverflow.com/comment/89874937
score: -4
has comment: http://stackoverflow.com/comment/89862805
has comment: http://stackoverflow.com/comment/89862510
type: Question
has comment: http://stackoverflow.com/comment/89862453
has comment: http://stackoverflow.com/comment/89874974
has title: utime csv file gives double backslash
answer count: 1
has comment: http://stackoverflow.com/comment/89863023
has comment: http://stackoverflow.com/comment/89862846
has answer: http://stackoverflow.com/a/51447074

http://stackoverflow.com/comment/89776829
score: 0
comment on: http://stackoverflow.com/q/51402904
has text: Not wanting to sound mean or an arse but your best bet for this kind of question is too google it ("what is the use of super in python"). Take a good read over https://www.pythonforbeginners.com/super/working-python-super-function, once you have finished reading it; i would recommend leaving it a couple of days then re-read it again. It's a good article.
type: Comment
type: QuestionComment

sphinx-apidoc
tag name: sphinx-apidoc
tags question: http://stackoverflow.com/q/51376785
type: Tag

http://stackoverflow.com/comment/89811481
score: 0
has text: thanks, I didnt realize I can put more than two elements into heap.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51420087

http://stackoverflow.com/comment/89901765
type: Comment
comment on: http://stackoverflow.com/a/51466652
has text: `child.paths()` (plural) is the recursive call to get the paths through the subtree.
score: 0
type: AnswerComment

http://stackoverflow.com/a/51453987
has body: I suppose you would need to clone the full repo: git clone https://github.com/secdev/scapy cd scapy From there, you can have access to the interactive shell: sudo ./run_scapy Welcome to Scapy &gt;&gt;&gt; p = IP(dst="github.com")/ICMP() &gt;&gt;&gt; r = sr1(p) Begin emission: .Finished to send 1 packets. That would include all scapy features, including ipsec: &gt;&gt;&gt; sa = SecurityAssociation(ESP, spi=0xdeadbeef, crypt_algo='AES-CBC', ... crypt_key='sixteenbytes key') &gt;&gt;&gt; p = IP(src='1.1.1.1', dst='2.2.2.2') &gt;&gt;&gt; p /= TCP(sport=45012, dport=80) &gt;&gt;&gt; p /= Raw('testdata') &gt;&gt;&gt; p = IP(raw(p)) &gt;&gt;&gt; p
has comment: http://stackoverflow.com/comment/89894645
type: Answer
answers question: http://stackoverflow.com/q/51453936
score: 0

http://stackoverflow.com/q/51438920
has answer: http://stackoverflow.com/a/51440172
tagged with: dataframe
answer count: 3
possible better answer: http://stackoverflow.com/a/51440172
tagged with: pandas
has answer: http://stackoverflow.com/a/51440785
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/69948688
upvote count: 2
tagged with: python
has body: I have two Multi-indexed DataFrames. One is my reference (about 37000 rows) and the other has fewer rows (e.g., 10). I want to replace the rows of the big one with the values from the second one. Sample df1: lvl1 lvl2 lvl3 Value Value2 A 1 I 0,862877333 0,181795348 1 II 0,787022218 0,292046262 1 III 0,40516176 0,445079108 2 I 0,882167166 0,683954412 2 IV 0,743618024 0,103097267 3 I 0,901062673 0,729188996 3 II 0,529989452 0,715379923 3 IV 0,740272198 0,792457421 B 1 I 0,548587694 0,637462653 1 II 0,201284924 0,084391963 2 I 0,999118031 0,558207224 2 II 0,63353019 0,251377184 2 V 0,694294638 0,685050861 3 V 0,436723389 0,310871641 3 VI 0,630832871 0,869957421 3 VII 0,157874482 0,639308814 Sample df 2: lvl1 lvl2 lvl3 Value Value2 A 1 I 0,8654 1 B 2 II 0,264 2 Resulting df3: lvl1 lvl2 lvl3 Value Value2 A 1 I **0,8654** 0,181795348 1 II 0,787022218 0,292046262 1 III 0,40516176 0,445079108 2 I 0,882167166 0,683954412 2 IV 0,743618024 0,103097267 3 I 0,901062673 0,729188996 3 II 0,529989452 0,715379923 3 IV 0,740272198 0,792457421 1 I 0,548587694 0,637462653 B 1 II 0,201284924 0,08439196 2 I 0,999118031 0,558207224 2 II **0,264** 0,251377184 2 V 0,694294638 0,685050861 3 V 0,436723389 0,310871641 3 VI 0,630832871 0,869957421 3 VII 0,157874482 0,639308814
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/51440785
has title: Multiindex dataframe rows replacement
type: Question

http://stackoverflow.com/a/51346368
has body: You can use re.compile in soup.find_all Ex: from bs4 import BeautifulSoup import re s = """ Tanjong Pagar · ~$20/pax · ~$40/pax""" soup = BeautifulSoup(s, "html.parser") for i in soup.find_all(text=re.compile(r"\~\$\d+\/pax")): print(i.strip()) Output: · ~$20/pax · ~$40/pax
answers question: http://stackoverflow.com/q/51346298
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51346298

http://stackoverflow.com/comment/89745919
type: Comment
comment on: http://stackoverflow.com/q/51371218
has text: These downvoters and closers should be suspended from the ability to give votes and closing, if not a reasonable reason is given..
score: 0
type: QuestionComment

http://stackoverflow.com/q/51410486
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
tagged with: dataframe
answer count: 2
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/51410668
has title: How to condense these nested for loops into list comprehension in python with dataframes?
accepted answer: http://stackoverflow.com/a/51410668
favorite count: 0
tagged with: iteration
has body: I'm trying to take one row at a time from dataframe 1, and check it against all rows of dataframe 2, and according to conditions update another column in dataframe 1. I've got this working with nested for loops but how can this be condensed with list comprehension? Here's a simplified example of what works using nested for loops. It's doing "if every entry i of column c1 in df1 is less than every entry in column d1 of df2, then update column c3 of df1: import pandas as pd import numpy as np df1 = pd.DataFrame([{'c1': 1, 'c3': "0"}, {'c1': 3, 'c3': "0"}, {'c1': 10, 'c3': "0"}]) df2 = pd.DataFrame([{'d1': 3}, {'d1': 7}]) print(df1) print(df2) for i in df1.index: for j in df2.index: if df1.loc[i, "c1"] &lt; df2.loc[j, "d1"]: df1.loc[i, "c3"] = 0 else: df1.loc[i, "c3"] = 1 print(df1) print(df2) I've done similar updates using a solution of type df1.loc[*some condition which specifies the applicable rows of df1* eg df1["c1"] &gt; df2["d1"], c3] = 1 but that will only work when the rows of df1 and df2 are 1:1, and wouldn't compare each row of df1 to all the rows of df2 anyway. Thanks!
has comment: http://stackoverflow.com/comment/89792465
possible better answer: http://stackoverflow.com/a/51410776
has answer: http://stackoverflow.com/a/51410776
tagged with: python

http://stackoverflow.com/comment/89846729
comment on: http://stackoverflow.com/a/51423194
type: AnswerComment
score: 0
has text: You can get rid of the column by using `file.drop(columns=['column_name'], inplace=True)` with `column_name` the name of the column that you want to drop. But this is getting off-topic. I'm afraid, I cannot help you. I just can't think of reason why the `pd.to_numeric` wouldn't do the trick.
type: Comment

http://stackoverflow.com/q/51378773
accepted answer: http://stackoverflow.com/a/51378829
has answer: http://stackoverflow.com/a/51378817
downvote count: 1
tagged with: sqlalchemy
has title: Python slicing tuples from list
type: Question
upvote count: 0
score: -1
has answer: http://stackoverflow.com/a/51378811
answer count: 3
has answer: http://stackoverflow.com/a/51378829
favorite count: 0
has body: I need to extract the values 76212 &amp; 160008 from my result which is below: [(76212, 160008)] For example I want: Result1 = 76212 Result2 = 160008 How do I achieve this? EDIT Should probably add that this result is taken from SQLAlchemy ORM. My code for this is below: query1 = session.query(X.Y,Z.A) \ .filter(cast(X.Y, VARCHAR).like(f'%{jobno}')) \ .all() print(query1)
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51378817

http://stackoverflow.com/a/51483112
downvote count: 0
answers question: http://stackoverflow.com/q/51482381
type: Answer
upvote count: 1
has body: Here is another way using simple indexing, but also using .between for succinctness. It still works even if your Time column is not of dtype datetime (i.e. works with str or O dtypes): df.loc[df.Time.between('09:30:00', '16:00:00')] Time Open High Low Close Volume Date 2018-03-20 09:30:00 93.05 93.32 93.01 93.12 524939 2018-03-20 09:31:00 93.68 93.69 93.53 93.54 77138 2018-03-20 09:32:00 92.82 92.90 92.82 92.88 43388 2018-03-20 15:56:00 93.65 93.71 93.64 93.69 44175 2018-03-20 15:57:00 93.12 93.29 93.00 93.27 166822 2018-03-20 15:58:00 93.28 93.36 93.27 93.33 70954 2018-03-20 15:59:00 93.33 93.43 93.30 93.34 94118 2018-03-20 16:00:00 93.34 93.53 93.34 93.44 75326
score: 1

http://stackoverflow.com/q/51470905
tagged with: unique
has comment: http://stackoverflow.com/comment/89914003
answer count: 0
type: UnansweredQuestion
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/89944970
type: Question
score: 0
linked to: http://stackoverflow.com/q/51487990
has title: How to reshape a tensor based on first index using tensorflow when finding a workaround tf.unique axis=1
tagged with: python
has body: I want help in converting a tensor to a new format based on values at its 1st index. Normally I would do this using a loop in python, but I would like to learn how to do this in Tensorflow. In following code x[0,0] &amp; x[1,0] are 0 so they are grouped in 0th index of the output x=tf.constant([[0, 1],[0, 2],[1, 1],[2, 10],[2, 2]]) #output=[[1,2],[1],[10,2]] #i would like the output in this format I am doing so when trying to pick unique values from a 2D Tensor. y=tf.constant([[1,2],[2,3],[1,2]] #output should be [[1,2],[2,3]]

http://stackoverflow.com/comment/89891530
type: Comment
score: 2
comment on: http://stackoverflow.com/a/51461054
type: AnswerComment
has text: "It probably has an index out of bounds in the negative direction": no, this is [perfectly ordinary Python syntax](https://stackoverflow.com/q/11367902/2564301). It is mentioned in [the official documentation](https://docs.python.org/3/library/stdtypes.html?highlight=negative#common-sequence-operations) under #3.

http://stackoverflow.com/q/51392167
downvote count: 0
possible better answer: http://stackoverflow.com/a/51402353
favorite count: 0
has answer: http://stackoverflow.com/a/51402353
tagged with: python
has answer: http://stackoverflow.com/a/51402389
has comment: http://stackoverflow.com/comment/89771448
type: AnsweredQuestion
score: 2
upvote count: 2
tagged with: pyqt5
has body: It seems that a QGraphicsItem status goes from To be destroyed by: C/C++ to To be destroyed by: Python, while not destroyed and still accessible. Is it an expected behavior ? If so, can someone explain ? Creation part node = QGraphicsRectItem() self.scene.addItem(node) print("Deleted ? ", sip.isdeleted(node)) print("Owned by Python ? ", sip.ispyowned(node)) sip.dump(node) Output Deleted ? False Owned by Python ? False &lt;PyQt5.QtWidgets.QGraphicsRectItem object at 0x7fcdb82371f8&gt; Reference count: 3 Address of wrapped object: 0x214bf80 Created by: Python To be destroyed by: C/C++ Parent wrapper: &lt;PyQt5.QtWidgets.QGraphicsScene object at 0x7fcdb821ea68&gt; Next sibling wrapper: &lt;__main__.Host object at 0x7fcdb8237dc8&gt; Previous sibling wrapper: NULL First child wrapper: NULL Deletion part self.scene.removeItem(node) print("Deleted ? ", sip.isdeleted(node)) print("Owned by Python ? ", sip.ispyowned(node)) sip.dump(node) Output Deleted ? False Owned by Python ? True &lt;PyQt5.QtWidgets.QGraphicsRectItem object at 0x7fcdb82371f8&gt; Reference count: 2 Address of wrapped object: 0x214bf80 Created by: Python To be destroyed by: Python Parent wrapper: NULL Next sibling wrapper: NULL Previous sibling wrapper: NULL First child wrapper: NULL One can see it is now owned by Python after deletion. And it still exists. Why ?
type: Question
has comment: http://stackoverflow.com/comment/89757859
has title: When does QGraphicsItem get destroyed in PyQt?
tagged with: qgraphicsitem
tagged with: destroy
accepted answer: http://stackoverflow.com/a/51402389
answer count: 2
tagged with: pyqt

http://stackoverflow.com/comment/89734488
has text: @pyd - What is your pandas version?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51381324

http://stackoverflow.com/q/51363762
downvote count: 0
has body: I've got a QGraphicsScene in which I added QPushButtons inside QGraphicsProxyWidgets. Is there a way to display tooltips for those buttons? The setToolTip works but nothing appear when I hover on the buttons. Do I need to specify some flag on the QGraphicsScene/View ? A simplified version of the button creation code : class Button(QPushButton): def __init__(self, scene): super(Button, self).__init__() self.proxy = QGraphicsProxyWidget() self.proxy.setWidget(self) scene.addItem(self.proxy) self.setToolTip("tooltip") Thanks in advance !
favorite count: 0
has title: Tooltip for widget inside a QGraphicsProxyWidget
possible better answer: http://stackoverflow.com/a/51364037
tagged with: python
accepted answer: http://stackoverflow.com/a/51365331
tagged with: qt
type: AnsweredQuestion
tagged with: qgraphicsscene
score: 1
tagged with: pyside
upvote count: 1
has answer: http://stackoverflow.com/a/51365331
type: Question
has answer: http://stackoverflow.com/a/51364037
answer count: 2
tagged with: pyqt

http://stackoverflow.com/q/51445332
has body: I'm running linear regressions with statsmodels and because I tend to distrust my results I also ran the same regression with scipy. The underlying dataset has about 80,000 observations. Unofrtunately, I cannot provide the data for you to reproduce the errors. I run two rounds of regressions: first simple OLS, second simple OLS with standardized variables Surprisingly, the results differ a lot. While R² and p-value seem to be the same, coefficients, intercept and standard error are all over the place. Interestingly, after standardizing the results align more. Now, there is only a slight difference in the constant, which I am happy to attribute to rounding issues. The exact numbers can be found in the appended screenshots. Any idea, where these differences come from and why they disappear after standardizing? What did I do wrong? Do I have to be extra worried, since I run most of my regressions with sklearn (only swapped to statsmodels since I needed some p-values) and even more differences may occur? Thanks for your help! If you need any additional information, feel free to ask. Code and Screenshots are povided below. My code in short looks like this: # package import import numpy as np from scipy.stats import linregress from scipy.stats.mstats import zscore import statsmodels.api as sma import statsmodels.formula.api as smf # adding constant train_IV_cons = sma.add_constant(train_IV) # run regression (coefficients, intercept, rvalue, pvalue, stderr) = linregress(train_IV[:,0], train_DV) print(coefficients, intercept, rvalue, pvalue, stderr) est = smf.OLS(train_DV, train_IV_cons[:,[0,1]]) model_results = est.fit() print(model_results.summary()) # normalize variables train_IV_norm = train_IV train_IV_norm[:,0]=np.array(ss.zscore(train_IV_norm[:,0])) train_IV_norm_cons = sma.add_constant(train_IV_norm) # run regressions (coefficients, intercept, rvalue, pvalue, stderr) = linregress(train_IV_norm[:,0], train_DV_norm) print(coefficients, intercept, rvalue, pvalue, stder…
score: 3
downvote count: 0
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89861931
answer count: 0
upvote count: 3
has comment: http://stackoverflow.com/comment/89872105
type: UnansweredQuestion
tagged with: regression
tagged with: scipy
type: Question
has title: Linear Regression in Python: Scipy vs. Statsmodels - same R², different coefficients
tagged with: statsmodels
has comment: http://stackoverflow.com/comment/89862097
tagged with: statistics

http://stackoverflow.com/a/51359837
type: Answer
score: 1
upvote count: 1
downvote count: 0
has body: You can try following $map aggregation db.collection.aggregate([ { $project: { dump: { $map: { input: "$dump", as: "dp", in: { "severity": "$$dp.severity", "problemReportId": "$$dp.problemReportId", "groupInCharge": "$$dp.groupInCharge", "feature": "$$dp.feature", "_id": "$$dp._id", "duplicate": "0" } } } } } ])
answers question: http://stackoverflow.com/q/51358494

http://stackoverflow.com/a/51455628
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/89880684
has comment: http://stackoverflow.com/comment/89880672
score: 1
has body: Make sure you have pip installed numpy, also check on the paths at environment variables at My Computer or Control Panel.
downvote count: 0
answers question: http://stackoverflow.com/q/51455571
has comment: http://stackoverflow.com/comment/89880708

http://stackoverflow.com/q/51465183
has title: Python static gallery generator code thumbnails directory
has comment: http://stackoverflow.com/comment/89899704
type: Question
has answer: http://stackoverflow.com/a/51465211
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/89898905
favorite count: 0
has body: I have code: class Gallery(): def __init__(self, directory = '.'): self.imgnames = [] self.directory = directory def get_files(self): self.filenames = os.listdir(self.directory) logging.debug("Directory files: %s" % self.filenames) def generate_thumbnails(self): counter = 0 for name in self.filenames: logging.debug("Trying to open %s" % name) counter+= 1 if name == "loading.gif": continue try: im = Image.open(name) self.imgnames.append(name) im.thumbnail( (300,300) ) logging.debug("Saving thumb-%s" % name) im.save("thumb-%s" % name) sys.stdout.write("\r%f%%" % (counter*100.0/len(self.filenames))) sys.stdout.flush() except IOError: logging.debug("File %s cannot be parsed by PIL, ignoring" % name) def integrate_bootstrap(self): logging.info("Generating index.html") head = open("./gallery_files/index.html.head", 'r').read() tail = open("./gallery_files/index.html.tail", 'r').read() final = open("index.html", 'w') and i would like change image thumbnails directory to save to ./gallery_files/thumbs/ when i change im.save("thumb-%s" % name) to im.save("./gallery_files/thumbs/thumb-%s" % name) not working. Any ideas? Thank you
has comment: http://stackoverflow.com/comment/89898910
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89900548
accepted answer: http://stackoverflow.com/a/51465211
downvote count: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/89685772
type: Comment
has text: a little far fetched duplicate. Related, yes, exact duplicate, well no since it requires some more work to make that work.
comment on: http://stackoverflow.com/q/51356556
score: 0
type: QuestionComment

http://stackoverflow.com/q/51469825
tagged with: set
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/51469908
has comment: http://stackoverflow.com/comment/89907998
type: UnansweredQuestion
tagged with: duplicates
has comment: http://stackoverflow.com/comment/89908002
downvote count: 0
has comment: http://stackoverflow.com/comment/89907999
has title: Python fast duplicate detection, can I store only the hash but not the value
score: 1
tagged with: sparse-matrix
favorite count: 0
has comment: http://stackoverflow.com/comment/89907981
tagged with: hash
type: Question
tagged with: python
has body: I have a method for creating an image "hash" which is useful for duplicate frame detection. (Doesn't really matter for the question) Currently I put each frame of a video in a set, and can do things like find videos that contain intersections by comparing the sets. (I have billions of hashes) Since I have my own "hash" I don't need the values of the set, only the ability to detect duplicate items. This would reduce my memory footprint by like half (since I would only have the hashes). I know internally a set is actually hash,value pairs. There must be a way to make a "SparseSet" or a "hashonly" set. Something like 2 in sparset(1,2,3) True but where for s in sparset(1,2,3) would return nothing, or hashes not values.

http://stackoverflow.com/comment/89766416
comment on: http://stackoverflow.com/q/51397678
score: 1
type: Comment
type: QuestionComment
has text: If you post your code with the elifs in and tell us what error you get, someone might be able to help you.

http://stackoverflow.com/comment/89926800
type: AnswerComment
has text: Thank you so much for this explanation!!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51464429

http://stackoverflow.com/a/54398189
answers question: http://stackoverflow.com/q/51379376
type: Answer
score: 1
has body: You can get bytes directly from frame, like below: bytes(frame) So final result will be: s3.Bucket(BUCKET_NAME).put_object(Key = 'rpi_img/img{}.jpg', Body = bytes(frame))
upvote count: 1
downvote count: 0

http://stackoverflow.com/q/51337666
has comment: http://stackoverflow.com/comment/89649890
has comment: http://stackoverflow.com/comment/89650002
has title: Updating Label Multiple Time in One Function
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89650615
has comment: http://stackoverflow.com/comment/89649968
answer count: 0
has comment: http://stackoverflow.com/comment/89656757
type: Question
tagged with: python
tagged with: kivy
tagged with: kivy-language
has body: I have a kivy windows, and I have to change a label which shows reading dataset progress. When reading dataset is being executed, I want show the progress as a text in kivy window, but it seems kivy just finished a logic first and then update the label. Here is my code: Function to run kivy: class loadingView(App): def build(self): container = Container() Clock.schedule_once(container.run, 1) return container and this is a class contains a function to run a logic: class Container(GridLayout, object): procTxt = ObjectProperty() procProgbar = ObjectProperty() def run(self, *args): self.procTxt.text = "Reading first dataset" self.procProgbar.value += 10 # I read first dataset here self.procTxt.text = "Reading second dataset" self.procProgbar.value += 10 # I read second dataset here self.procTxt.text = "Reading third dataset" self.procProgbar.value += 10 # I read third dataset here # Read dataset done self.procTxt.text = "DONE" But when I run the code, the kivy window showed up, delayed for some time, and immediately update the Label into "DONE". There is a pause in every reading progress. But it seems the label isn't updating. Is there anyway to update a label everytime the app read the dataset?
score: 0
has comment: http://stackoverflow.com/comment/89650572

http://stackoverflow.com/a/51343659
has body: Setup df = pd.DataFrame({'hour': [1,7,13,18,25,31]}) Use pd.to_datetime with the unit flag, and set the origin flag to the beginning of your desired year. pd.to_datetime(df.hour, unit='h', origin='1979-01-01') 0 1979-01-01 01:00:00 1 1979-01-01 07:00:00 2 1979-01-01 13:00:00 3 1979-01-01 18:00:00 4 1979-01-02 01:00:00 5 1979-01-02 07:00:00 Name: hour, dtype: datetime64[ns]
type: Answer
score: 4
answers question: http://stackoverflow.com/q/51343638
upvote count: 4
has comment: http://stackoverflow.com/comment/89660732
downvote count: 0

http://stackoverflow.com/q/51389851
downvote count: 0
has comment: http://stackoverflow.com/comment/89753825
has comment: http://stackoverflow.com/comment/89751952
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/89752160
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89751796
tagged with: python
answer count: 0
has title: python convert long function into class
score: 1
has body: Im looking to convert this python script into a class which accepts an object. The goal is to better structure the program as there will be additional functions/classes. Any help in the right direction would be great. Thanks in advance. import serial import time vin_number = '' def connect(): ser=serial.Serial('/dev/rfcomm0', 115200) ser.write(b'ATL1\r\n') ser.write(b'ATH1\r\n') ser.write(b'ATS1\r\n') ser.write(b'ATSP0\r\n') ser.write(b'0902\r\n') time.sleep(5) resp = ser.read(ser.in_waiting) return resp def parse_vin(rcv): result = rcv.split(' ') row1 = " ".join(result[6:9]) row2 = " ".join(result[11:18]) row3 = " ".join(result[20:27]) vin_hex = row1 + row2 + row3 return vin_hex def decode_vin(vin_hex): vin = str(bytearray.fromhex(vin_hex).decode()) return vin try: rcv = "7E8 10 14 49 02 01 4C 46 56 7E8 21 33 42 32 38 52 38 41 7E8 22 33 30 32 35 33 31 30" #rcv = connect() vin_hex = parse_vin(rcv) vin_number = decode_vin(vin_hex) print(vin_number) except Exception as e: print(e)
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89751830

http://stackoverflow.com/a/51349800
type: Answer
answers question: http://stackoverflow.com/q/51340712
has body: Assigning Input1=0 Input2=0 Solves the problem. I could fix the issue. Thanks anyway
has comment: http://stackoverflow.com/comment/89672295
score: 0

code-generation
tag name: code-generation
tags question: http://stackoverflow.com/q/51414920
tags question: http://stackoverflow.com/q/51463872
type: Tag

http://stackoverflow.com/comment/89702349
has text: Also, is `MyController` supposed to be a class or a module? You seem to assume it's a class, judging from your variable names, but the error says its a module. Probably you first have to create an instance of some class from that module before you can use the method.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51364913

http://stackoverflow.com/q/51366354
tagged with: python-3.6
has title: pyodbc exec stored proc with params / output param - update not working
score: 0
linked to: http://stackoverflow.com/q/48061304
has comment: http://stackoverflow.com/comment/89705256
has comment: http://stackoverflow.com/comment/89706380
type: UnansweredQuestion
tagged with: python
has body: Trying to use the method detailed here to call a stored proc and perform an update using pyodbc in python3.6. I have one method that handles starting the instance and one that wraps things up. Starting the instance works perfectly: def start_instance(self, count): params = [1, count] sql = """ DECLARE @out as int; EXEC [dbo].[my_sproc] @id = ?, @count = ?, @instance_id = NULL, @output = @out OUTPUT; SELECT @out as op; """ val = self.dbObj.query(sql, params).fetchval() self.instance = val Ending it produces an error: def end_instance(self): params = [1, self.instance] sql = """ DECLARE @out as int; EXEC [dbo].[my_sproc] @id = ?, @instance_id = ?, @output = @out OUTPUT; SELECT @out as op; """ val = self.dbObj.query(sql, params).fetchval() print(val) The error is pyodbc.ProgrammingError: No results. Previous SQL was not a query. My Stored Proc: ALTER PROCEDURE [dbo].[my_sproc] @id int, @count int = NULL, @instance_id int = NULL, @output int OUTPUT AS IF(@instance_id IS NULL) BEGIN DECLARE @OutputTbl TABLE (ID INT) INSERT INTO [dbo].[my_table]([id], [record_count]) OUTPUT INSERTED.id VALUES(@id, COALESCE(@count, 0)); END IF(@instance_id IS NOT NULL) BEGIN UPDATE [dbo].[my_table] SET [instance_end] = GETDATE(), [records_processed] = COALESCE(@count, 0) WHERE [id] = @id AND [instance_id] = @instance_id; SET @output = 1 END I can run the below sql in SSMS and it will work fine: DECLARE @out as int; EXEC [dbo].[my_sproc] @id = 1, @count = NULL, @instance_id = 12, @output = @out OUTPUT; SELECT @out as op UPDATE: Got it working initially thanks to Gord Thompson's hint regarding SET NOCOUNT ON. However, I ultimately want end_instance() to run atexit. I'm currently doing this: atexit.register(self.clean_up_on_exit) and then: def clean_up_on_exit(self): self.check_in_records() self.end_instance() self.dbObj.close_conn() If I just call end_instance() at the end of start_instance() just for testing purposes, I get the expected result. However, adding it to my clean_up_on_exit() me…
tagged with: pyodbc
has comment: http://stackoverflow.com/comment/89706154
answer count: 0
has comment: http://stackoverflow.com/comment/89714266
type: Question

http://stackoverflow.com/a/51434213
has comment: http://stackoverflow.com/comment/89839072
score: 0
has comment: http://stackoverflow.com/comment/89841842
type: AcceptedAnswer
type: Answer
has body: Python has a map function, this takes a function and an iterable. There is also the sum function, which returns the sum of an iterable. You can use this: sum(map(int(trip_list)) Note that the map function does not return a list, it returns a generator. To convert it to a list, use list(sum(map(int, trip_list))) (this may take a while as it requires iterating over the entire list, and yours is quite long). The error with your code is converting your list to a string, that is, &gt;&gt;&gt; my_list = ["5", "6"] &gt;&gt;&gt; my_list_str = str(my_list) &gt;&gt;&gt; my_list_str "['5', '6']" &gt;&gt;&gt; type(my_list_str) &lt;class 'str'&gt; &gt;&gt;&gt; type(my_list) &lt;class 'list'&gt; So when you try to iterate over the string, the first x is [ which is not a number (thus the exception). As a sidenote, using list(map(int, a_list)) is faster than [int(i) for i in a_list] &gt;&gt;&gt; c1 = "list(map(int, a_list))" &gt;&gt;&gt; c2 = "[int(i) for i in a_list]" &gt;&gt;&gt; s = "a_list = [str(i) for i in range(1000)]" &gt;&gt;&gt; import timeit &gt;&gt;&gt; timeit.timeit(c1, setup=s, number=10000) 1.9165708439999918 &gt;&gt;&gt; &gt;&gt;&gt; timeit.timeit(c2, setup=s, number=10000) 2.470973639999997
answers question: http://stackoverflow.com/q/51434149
accepted answer of: http://stackoverflow.com/q/51434149

http://stackoverflow.com/q/51480760
accepted answer: http://stackoverflow.com/a/51481061
tagged with: python
has title: Dynamic DEPTH_LIMIT as parameter in Scrapy, passed from Scrapyd
type: AnsweredQuestion
tagged with: scrapyd
upvote count: 1
tagged with: scrapy
type: Question
score: 1
has answer: http://stackoverflow.com/a/51481061
has body: I am currently using Scrapyd to start a crawling spider and the DEPTH_LIMIT setting is set in the Scrapy App settings. I was wondering how to pass the depth_limit as a parameter in Scrapyd, allowing me to set it "dynamically" as requested by the user for every different crawling. I believe I can only act on the spiders and pipelines of Scrapy. EDIT Thanks to @John Smith response, I found out it's possible to pass settings to the schedule method of scrapyd settings = { 'unique_id': unique_id, # unique ID for database instance 'USER_AGENT': 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)', 'DEPTH_LIMIT': 1 } # Schedule a new crawling task from scrapyd task_id = scrapyd.schedule('default', "spider-name", settings=settings, url=url, domain=domain)
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/89914648
comment on: http://stackoverflow.com/q/51473138
has text: @rahultyagi No it doesnt.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89776422
comment on: http://stackoverflow.com/a/51388550
type: AnswerComment
has text: just add your Auth0 backend at your settings and use your auth token to process it
score: 0
type: Comment

http://stackoverflow.com/a/51382249
type: Answer
answers question: http://stackoverflow.com/q/51382162
score: 5
upvote count: 5
downvote count: 0
has body: With popups and other data that only appears dynamically via javascript, you can't just scrape the data using something like urllib. You could use a browser controller like splinter or selenium which will allow you to automatically hover over or click things to bring up the popup and then extract its data. After you get the popup html, you can use BS4 to clean it up. Ex: from splinter import Browser browser = Browser() browser.visit("http://google.com") button = browser.find_by_name('button1') button.click()

http://stackoverflow.com/a/51432456
accepted answer of: http://stackoverflow.com/q/51431945
answers question: http://stackoverflow.com/q/51431945
type: Answer
has body: You can use a list comprehension to obtain the keys the same number of times as the values: [x for x,y in zip(ca.keys(),ca.values()) for i in y] ['currency', 'Country', 'Country', 'Country', 'Country', 'Country', 'Languages', 'Languages', 'Languages', 'Languages', 'Languages']
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/51381763
score: 1
has comment: http://stackoverflow.com/comment/89745853
upvote count: 1
tagged with: pynput
type: Question
has body: I wanted to detect keyboard with pynput, so I copied and pasted a demo from their site. Here it is: from pynput import keyboard def on_press(key): try: print('alphanumeric key {0} pressed'.format( key.char)) except AttributeError: print('special key {0} pressed'.format( key)) def on_release(key): print('{0} released'.format( key)) if key == keyboard.Key.esc: # Stop listener return False # Collect events until released with keyboard.Listener( on_press=on_press, on_release=on_release) as listener: listener.join() But I get this error, the file is named differently than the module: Traceback (most recent call last): File "C:\Users\Andrey\Documents\Python\123.py", line 1, in &lt;module&gt; from pynput import keyboardFile "C:\Users\Andrey\AppData\Local\Programs\Python\Python36-32\pynput.py", line 10, in &lt;module&gt; with keyboard.Listener(NameError: name 'keyboard' is not defined
has answer: http://stackoverflow.com/a/51397155
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89745880
has comment: http://stackoverflow.com/comment/89745828
favorite count: 0
tagged with: python-3.x
tagged with: importerror
has comment: http://stackoverflow.com/comment/89735280
type: UnansweredQuestion
has title: python 3.6 pynput NameError: name 'keyboard' is not defined
tagged with: python
has comment: http://stackoverflow.com/comment/89762903

http://stackoverflow.com/q/51442884
type: Question
possible better answer: http://stackoverflow.com/a/51443435
has title: Remove Duplicate List Dictionary based on the Designations
has comment: http://stackoverflow.com/comment/89855672
has answer: http://stackoverflow.com/a/51443435
has body: Below list dict, if we have duplicate names then need to get the dict which is having the designation.If its single name then need to get the dict which does'nt have designation lst = [{'desig': '', 'name': 'William'}, {'desig': 'Chairman of the Board', 'name': 'William'}, {'desig': '', 'name': 'English'}, {'desig': 'Director', 'name': 'English'}, {'desig': '', 'name': 'Charles '}] My output should be like below. lst = [{'desig': 'Chairman of the Board', 'name': 'William'}, {'desig': 'Director', 'name': 'English'}, {'desig': '', 'name': 'Charles '}]
has comment: http://stackoverflow.com/comment/89856561
answer count: 3
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89856048
tagged with: python
accepted answer: http://stackoverflow.com/a/51443427
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51443442
downvote count: 5
score: -4
has answer: http://stackoverflow.com/a/51443427
has comment: http://stackoverflow.com/comment/89856031

http://stackoverflow.com/comment/89896478
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51463586
type: Comment
has text: Looks like it was 'utf-16-le', but you and snakecharmerb got me on the right track. Thanks!

http://stackoverflow.com/q/51428864
favorite count: 0
tagged with: python-3.x
has body: My goal is to have a random name of a fruit stored as fruit_name. Using this I would like to remove all fruits with the same first three letters in its value. For example: fruit_name = 'apple II' dictionary = {'grape' : 'abc.asrtyui', 'apple' : 'xyz7.qwertyui', 'apple I' : 'xyz.rghhyui', 'grape II' : 'zxs2.qwertyui', 'apple II' : 'xyz.qwvnyyui', 'orange' : 'bnm1.qrthnrui'} My thought process is: STEP 1: find the key with fruit_name (in this case 'apple II') STEP 2: look at first three letters for its value STEP 3: remove the all the keys and its values with those same three letters. So for my example above, after this process happens the dictionary would contain: dictionary = {'grape' : 'abc.asrtyui', 'grape II' : 'zxs2.qwertyui', 'orange' : 'bnm1.qrthnrui'} Here is my snippet, not sure if I am going in the right direction as I am completely confused. ALSO, id like to do this with the standard library. Thanks in advance! for k1, v1 in dictionary.items(): for k2, v2 in dictionary.items(): if k1 == k2: continue if v1[:3] == v2[:3]:
possible better answer: http://stackoverflow.com/a/51428990
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51428990
type: AnsweredQuestion
has title: Using the key, remove all keys with similar values
score: 1
type: Question
has answer: http://stackoverflow.com/a/51428980
has comment: http://stackoverflow.com/comment/89829020
has answer: http://stackoverflow.com/a/51429172
tagged with: list-comprehension
answer count: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/51428980

http://stackoverflow.com/comment/89755463
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51391515
has text: This works! Thank you! And the data I'm working with is in an unorthodox format because I was trying to extract information from text data and sum the results. This was a follow up to a question I asked yesterday (https://stackoverflow.com/questions/51362588/counting-the-occurrences-of-a-substring-from-one-column-within-another-column/51362726?noredirect=1#comment89720274_51362726), which is how I ended up with such strange formatting. Regardless, this was the final step in the frustrating process of figuring this out so I thank you so much!
type: Comment

http://stackoverflow.com/comment/89634069
type: QuestionComment
has text: I believe sparse matrices have a unique representation that do not allow you to directly set the values. I'm not certain but maybe try setting the values you want and then converting it to a sparse matrix.
score: 0
comment on: http://stackoverflow.com/q/51329121
type: Comment

http://stackoverflow.com/a/51413359
has body: That is because after the loop for line in op: is over, the file was read to the end and there is nothing more to read. There are several alternatives: Option 1 (worse): re-open the file: with open('words.txt') as op: print(avoids('e')) with open('words.txt') as op: print(avoids('a')) Option 2 (better): read all lines and pass them to avoids(): def avoids(forbidden, lines): """counts the number of words in Enlgish which do not contain any character found in forbidden str""" number=0 for line in lines: count=0 for letter in line.strip(): if forbidden.count(letter)==0: count=count+1 if count==len(line.strip()): number=number+1 return number with open('words.txt') as op: lines = op.readlines() print(avoids('e', lines)) print(avoids('a', lines)) However, this requires keeping all lines in memory which is OK for smaller files but may be a problem for very large files. Option 3a (better for very large files): This is the same as option 1 but has open() placed inside the function. def avoids(forbidden, filename): """counts the number of words in Enlgish which do not contain any character found in forbidden str""" number=0 with open(filename) as op: for line in op: count=0 for letter in line.strip(): if forbidden.count(letter)==0: count=count+1 if count==len(line.strip()): number=number+1 return number print(avoids('e', 'words.txt')) print(avoids('a', 'words.txt')) Option 3b (also good for very large files but I do not like it): Add op.seek(0) before return number. Alternatively (and likely better), as mentioned by @kindall in the comments, op.seek(0) can be placed at the beginning of the function to make sure we are at the beginning of the file before we start reading lines. This will "rewind" the file to the beginning and allows you to open the file only once outside the function. Essentially, this will make your old function work as expected by you.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51413332
has comment: http://stackoverflow.com/comment/89799664
type: Answer
has comment: http://stackoverflow.com/comment/89798393
has comment: http://stackoverflow.com/comment/89798685
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/51413332

http://stackoverflow.com/comment/89933772
type: QuestionComment
type: Comment
has text: @ytu I guess I'm wondering how to avoid this mistake. I'm also wondering why the code doesn't work when return is indented the same as "for num in nums." Also, I am wondering if anybody knows of an additional resource where I can better understand how this works.
comment on: http://stackoverflow.com/q/51482379
score: 0

http://stackoverflow.com/q/51398004
tagged with: memory
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/91037997
tagged with: arrays
has answer: http://stackoverflow.com/a/51399815
score: 6
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/51406625
has title: Concatenate Numpy arrays with least memory
has body: Not I have 50GB dataset saved as h5py, which is a dictionary inside. The dictionary contains keys from 0 to n, and the values are numpy ndarray(3 dimension) which have the same shape. For example: dictionary[0] = np.array([[[...],[...]]...]) I want to concat all these np arrays, code like sample = np.concatenate(list(dictionary.values)) this operation waste 100GB memory! If I use del dictionary It will decrease to 50GB memory. But I want to control the memory usage as 50GB during loading data. Another way I tried like this sample = np.concatenate(sample,dictionary[key]) It is still using 100GB memory. I think all the cases above, the right side will create a new memory block to save, and then assigned to the left side, which will double the memory during calculations. Thus, the third way I tried like this sample = np.empty(shape) with h5py.File(...) as dictionary: for key in dictionary.keys(): sample[key] = dictionary[key] I think this code has an advantage. The value dictionary[key] assigned to some row of sample, then the memory of dictionary[key] will clear. However, I test it and find that the memory usage is also 100GB. Why? Are there any good methods to limit the memory usage as 50GB?
accepted answer: http://stackoverflow.com/a/51399815
linked to: http://stackoverflow.com/q/7869095
upvote count: 7
possible better answer: http://stackoverflow.com/a/51406625
downvote count: 1
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/95838104
type: AnswerComment
comment on: http://stackoverflow.com/a/51434048
has text: Note that this might not work if there are multiple processes pushing into the queue. it would be difficult to figure out which one of the producers must push in None. In such cases, @user2357112 's answer, though uglier, is easier to implement
type: Comment
score: 0

http://stackoverflow.com/comment/89836352
comment on: http://stackoverflow.com/q/51430484
has text: I don't think I have enough information to appropriately answer this question then. If you subclass `CountVectorizer`, wouldn't you only need to initalize the subclass, and then have full access to everything you would otherwise need in `CountVectorizer` in your subclass `StemmedCountVectorizer`?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/51417282
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/51417939
favorite count: 0
has answer: http://stackoverflow.com/a/57629691
type: UnansweredQuestion
has title: ValueError: ndarray is not contiguous
has comment: http://stackoverflow.com/comment/89807067
tagged with: python
has comment: http://stackoverflow.com/comment/89806820
has comment: http://stackoverflow.com/comment/101822383
downvote count: 0
score: 1
type: Question
tagged with: numpy
has body: when I build a matrix using the last row of my dataframe: x = w.iloc[-1, :] a = np.mat(x).T it goes: ValueError: ndarray is not contiguous `print the x shows(I have 61 columns in my dataframe): print(x) cdl2crows 0.000000 cdl3blackcrows 0.000000 cdl3inside 0.000000 cdl3linestrike 0.000000 cdl3outside 0.191465 cdl3starsinsouth 0.000000 cdl3whitesoldiers_x 0.000000 cdl3whitesoldiers_y 0.000000 cdladvanceblock 0.000000 cdlhighwave 0.233690 cdlhikkake 0.218209 cdlhikkakemod 0.000000 ... cdlidentical3crows 0.000000 cdlinneck 0.000000 cdlinvertedhammer 0.351235 cdlkicking 0.000000 cdlkickingbylength 0.000000 cdlladderbottom 0.002259 cdllongleggeddoji 0.629053 cdllongline 0.588480 cdlmarubozu 0.065362 cdlmatchinglow 0.032838 cdlmathold 0.000000 cdlmorningdojistar 0.000000 cdlmorningstar 0.327749 cdlonneck 0.000000 cdlpiercing 0.251690 cdlrickshawman 0.471466 cdlrisefall3methods 0.000000 Name: 2010-01-04, Length: 61, dtype: float64 how to solve it? so many thanks
answer count: 2

http://stackoverflow.com/a/51375344
upvote count: 1
answers question: http://stackoverflow.com/q/51375115
downvote count: 0
has body: All parameters in a function have to be separated by commas (,). As already mentioned in the comments, there is a , missing to separate your parameters in your __init__() method. Your __init__() method should look like this: def __init__(self, filename, pagesize=letter, bottomup=1, pageCompression=0, encoding=rl_config.defaultEncoding, verbosity=0, encrypt=None): As you can see: Now, there is comma between verbosity and encrypt. More from the Python docs: parameter_list ::= defparameter ("," defparameter)* ["," [parameter_list_starargs]] | parameter_list_starargs Here you can see, that a "," (comma) is needed to separate parameters.
type: Answer
score: 1

http://stackoverflow.com/comment/89805394
type: Comment
type: QuestionComment
score: 1
has text: openpyxl does not remove sorts. Please include the code you're using.
comment on: http://stackoverflow.com/q/51411315

violin-plot
tags question: http://stackoverflow.com/q/51480276
tag name: violin-plot
type: Tag

http://stackoverflow.com/q/51334312
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has title: Is gevent pool wait_available thread safe
tagged with: python
has body: So I have a function lets say test and gevent pool of size 10. pool.Pool(size=10) def test(): pool.wait_available(timeout=0.5) pool.spawn(something) If the function test is called by different threads, will it cause any issue. I mean wait_availableshould be thread safe but the pool.spawn will it have thread safety/race condition issue. I mean lets say there are already 9 greenlets running and there a couple of requests calling the test function. Both of them will read pool.wait_available which should not block But the pool.spawn right after that will make one of them block. I just want to make sure that the pool.spawn doesn't block for more than the specified timeout period. How can I accomplish this?
score: 1
upvote count: 1
tagged with: gevent
type: Question
has answer: http://stackoverflow.com/a/51334482
tagged with: pool
tagged with: green-threads

http://stackoverflow.com/a/51459177
type: Answer
has body: you don't have to test against True or False. you can just check with if or if not def squirrel_play(temp, is_summer): low_temp = 60 hi_temp = 91 if is_summer: # implicit check for True hi_temp = 101 if temp in range(low_temp, hi_temp): return True return False
accepted answer of: http://stackoverflow.com/q/51458881
upvote count: 1
answers question: http://stackoverflow.com/q/51458881
downvote count: 1
type: AcceptedAnswer
score: 0

http://stackoverflow.com/comment/89913168
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51471699
has text: Hello, Thank you very much. I've added USER_LIST instance and used your method,however, I can use the function -- pager_num_range.

http://stackoverflow.com/comment/89671018
score: 0
has text: To answer your question though, I usually just use PDF and the rasterize kwarg for image data.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51347692

http://stackoverflow.com/comment/89649189
type: Comment
type: QuestionComment
has text: Cannot repro in any of python 3.4.0, 3.6.4, or 3.7.0 (all 32 bit on Windows). I get a RecursionError as expected.
comment on: http://stackoverflow.com/q/51337082
score: 0

http://stackoverflow.com/q/51361695
tagged with: python
type: AnsweredQuestion
type: Question
tagged with: testing
accepted answer: http://stackoverflow.com/a/51361855
tagged with: tornado
tagged with: mongodb
score: 0
tagged with: mocking
answer count: 1
has body: I am trying to write a mock test for an api that someone else coded, and my duty is to test a module's post method. The module is written to do a job of a handler and it uses BaseHandler as super class. What do i need is how/what to mock while writing the mock test for a http post method. Should I mimic a post request? Or make a real one? Or what else? I am not allowed to share any codes, but the code uses tornado to make connection to localhost, mongodb for database read-write and is written using Python 3.6. Any ideas are welcome. Thanks from now.
has answer: http://stackoverflow.com/a/51361855
has title: Mock testing an api for post method

http://stackoverflow.com/comment/131162731
has text: Check instance of `pd` before `class pd`. Here is documentation about how you can [extend pandas](https://pandas.pydata.org/docs/development/extending.html).
score: 0
comment on: http://stackoverflow.com/q/51417411
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51329797
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Create a button to control background music on and off in pygame
score: 3
has answer: http://stackoverflow.com/a/51329901
has answer: http://stackoverflow.com/a/51330269
upvote count: 3
type: Question
tagged with: button
downvote count: 0
tagged with: game-development
has answer: http://stackoverflow.com/a/66220976
answer count: 3
has body: I want to create a button in my game that can control the background music on and off. The first click will stop the background music, and the second click can bring back the music. Now my button can control the music on and off, but I need to click multiple times to make it work, it seems that the click event is not captured everytime, here is my code: for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: if 20 + 50 &gt; mouse_position[0] &gt; 20 and 20 + 20 &gt; mouse_position[1] &gt; 20: play_music = not play_music if play_music: pygame.mixer.music.unpause() else: pygame.mixer.music.pause() pygame.display.flip() clock = pygame.time.Clock() clock.tick(15)
tagged with: pygame

http://stackoverflow.com/comment/89685844
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51350931
type: Comment
has text: Thanks for the in depth answer, I really appreciate that you added reasoning to each route.

http://stackoverflow.com/comment/89768651
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51397556
has text: Thank you so much! I just changed this return redirect('lessons:index', kwargs=dict(reference=form.instance.reference)) to this return redirect('lessons:index', reference=form.instance.reference). And it works! My url looks like that path('<reference>', lessons.lessons_view, name='index'),

http://stackoverflow.com/q/51326086
score: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
has body: I'm having trouble installing the package 'geomeppy' for editing IDFs. When running pip install geomeppy, it gives me the following error: FileNotFoundError: [Errno 2] No such file or directory: 'requirements.in' Has anyone come across this before?
has answer: http://stackoverflow.com/a/51326136
tagged with: python
accepted answer: http://stackoverflow.com/a/51326136
linked to: http://stackoverflow.com/q/19742406
has title: Trouble installing geomeppy
upvote count: 1
downvote count: 1
type: AnsweredQuestion
type: Question

http://stackoverflow.com/comment/89907158
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51469336
score: 0
has text: Import your array to another df, dataframes have methods to transpose and save to csv ...

http://stackoverflow.com/q/51439483
accepted answer: http://stackoverflow.com/a/51439795
has body: Hi I've been scratching my head over past few days to figure out how to manipulate dj-money fields. Here are my two model fields: client_cost = MoneyField( _('client cost'), max_digits=10, decimal_places=2, default_currency='AUD', null=True, ) camera_operator_cost = MoneyField( _('camera operator cost'), max_digits=10, decimal_places=2, default_currency='AUD', null=True, ) They can have completely different currencies (default being 'AUD'). I need to be able to: extract currency from these fields. (Need the exact statement). add these two fields which could have amounts in any currency. reformat the total in whatever currency I want. Let's say total in AU$ is 250 and now i want the same value in US$ which will be ~184US$ Please help. PS: I'm using this: https://github.com/django-money/django-money
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51439795
tagged with: django
upvote count: 1
type: Question
has title: Django Money - Add two MoneyFields in different currencies and generate output in given currency
score: 1

http://stackoverflow.com/comment/89763318
type: Comment
score: 0
has text: Thanks for `os.listdir`. I just have 1 question for this. I have `file1.txt` and `file2.txt`. I want to compare `file1.txt` of folder1 with `file1.txt` of folder2 and same for file2. Will it results in this `folder1 = ['file1.txt', 'file2.txt']` & `folder2 = ['file1.txt', 'file2.txt']` always and not `folder1 = ['file1.txt', 'file2.txt']` & `folder2 = ['file2.txt', 'file1.txt']` so that I dont compare file1 with file2
type: AnswerComment
comment on: http://stackoverflow.com/a/51395706

http://stackoverflow.com/a/51449587
has comment: http://stackoverflow.com/comment/89869926
has comment: http://stackoverflow.com/comment/89871325
has comment: http://stackoverflow.com/comment/90023000
downvote count: 0
type: Answer
has body: You could use tcpdump (which is implemented in C) to capture the UDP traffic, since it's faster than python: #!/bin/bash iface=$1 # interface, 1st arg port=$2 # port, 2nd arg tcpdump -i $iface -G acq_time_in_seconds -n udp port $port -w traffic.pcap And then you can use e.g. scapy to process that traffic #!/usr/bin/env python from scapy.all import * scapy_cap = rdpcap('traffic.pcap') for packet in scapy_cap: # process packets...
answers question: http://stackoverflow.com/q/51448972
has comment: http://stackoverflow.com/comment/89870081
upvote count: 3
score: 3

http://stackoverflow.com/a/51431667
answers question: http://stackoverflow.com/q/51431408
score: 0
has body: code = ("1 2 3 4") list(code)
type: Answer

http://stackoverflow.com/comment/89904722
comment on: http://stackoverflow.com/a/51463928
has text: Sorry. I meant, you didn't the question I posed in my comment.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89833159
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51430995
has text: use `test.done(function(response){...do stuff with response...})`

http://stackoverflow.com/a/77720647
answers question: http://stackoverflow.com/q/51434897
type: Answer
score: 2
has body: First install ffmpeg from ffmpeg download page https://ffmpeg.org/download.html , then extract the zip file and rename it ffmpeg, then move the renamed ffmpeg folder in the C drive. Then go to control panel -> environment variables -> path -> edit -> new -> C:\ffmpeg\bin , then click ok Then do pip install ffmpeg from pydub import utils, AudioSegment from pydub.effects import speedup def get_prober_name(): return "C://ffmpeg/bin/ffprobe.exe" AudioSegment.converter = "C://ffmpeg/bin/ffmpeg.exe" utils.get_prober_name = get_prober_name sound = AudioSegment.from_file("output.mp3",format="mp3") final = speedup(sound, playback_speed=1.5) # speeds up the audio track by scale of 1.5 final.export("final.mp3",format="mp3")
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/89703904
has text: thanks for your reply. But what is your definition of "middle character"? If there odd numbers of characters it is clear, but if it is even?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51356332
type: AnswerComment

http://stackoverflow.com/a/51386416
has comment: http://stackoverflow.com/comment/89744737
upvote count: 1
score: 1
has body: In your elif statement, you're using a bitwise "and" operator rather than the logical and operator. Everywhere that you have "&amp;" replace it with "and"
downvote count: 0
answers question: http://stackoverflow.com/q/51386324
type: Answer

http://stackoverflow.com/q/51353117
downvote count: 1
type: Question
has title: How to preserve quotes of string during .format
has answer: http://stackoverflow.com/a/51353124
accepted answer: http://stackoverflow.com/a/51353124
score: 0
answer count: 1
tagged with: string
favorite count: 0
tagged with: python
has body: I'm writing a multi-line file, lines like: workspace -fr "fluidCache" "cache/nCache/fluid"; On some of the lines I need to use a variable containing a file path, when I use the following: render_output = os.path.join(project_root, r'common\render_output') ws_file.write("""workspace -fr "images" {0};""".format(render_output)) result: workspace -fr "images" I:\..\common\render_output; The result I need is render_output with quotes: workspace -fr "images" "I:\..\common\render_output"; How might I format the render_output so that the quotations of its string value are maintained in the triple quoted write argument?
type: AnsweredQuestion
upvote count: 1

http://stackoverflow.com/q/51368293
answer count: 2
tagged with: elasticsearch
has answer: http://stackoverflow.com/a/51508603
tagged with: pypy
favorite count: 0
has answer: http://stackoverflow.com/a/51597965
type: UnansweredQuestion
tagged with: python
score: 2
downvote count: 0
has body: I have some code that saves data to Elasticsearch. It runs fine in Python 3.5.2 (cpython), but raises an exception when running on pypi3 6.0.0 (Python 3.5.3). Any ideas why? File "/opt/venvs/parsedmarc/site-packages/parsedmarc/elastic.py", line 366, in save_forensic_report_to_elasticsearch forensic_doc.save() File "/opt/venvs/parsedmarc/site-packages/elasticsearch_dsl/document.py", line 394, in save index=self._get_index(index), File "/opt/venvs/parsedmarc/site-packages/elasticsearch_dsl/document.py", line 138, in _get_index raise ValidationException('You cannot write to a wildcard index.') elasticsearch_dsl.exceptions.ValidationException: You cannot write to a wildcard index
type: Question
upvote count: 2
has title: Why does elasticsearch raise elasticsearch_dsl.exceptions.ValidationException: You cannot write to a wildcard index.on pypy but not cpython?

http://stackoverflow.com/comment/89859832
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51444888
has text: Does QNX put all loaded symbols into a shared pool?

http://stackoverflow.com/a/51338247
type: AcceptedAnswer
downvote count: 0
has body: Looks like a task for the indirect parametrizaton to me. Prepare parameters First things first: pytest.mark.parametrize expects parameters to be passed as a list of tuples, with data ordered by arg names, for example: @pytest.mark.parametrize('spam,eggs', [(1, 2), (3, 4), (5, 6)]) will generate three tests: spam=1, eggs=2, spam=3, eggs=4, spam=5, eggs=6. So you have to transform the PARAMS dict into list of tuples with one number per dict key. There are lots of ways to do that, one solution being: PARAMS = {'pic1': [1, 2, 3], 'pic2': [14, 15], 'pic3': [100, 200, 300]} test_pic_params = [(key, el) for key, nums in PARAMS.items() for el in nums] @pytest.mark.parametrize('file,num', test_pic_params) def test_pic(file, num): assert True Check whether the tests are generated correctly: $ pytest --collect-only --quiet test_spam.py test_spam.py::test_pic[pic1-1] test_spam.py::test_pic[pic1-2] test_spam.py::test_pic[pic1-3] test_spam.py::test_pic[pic2-14] test_spam.py::test_pic[pic2-15] test_spam.py::test_pic[pic3-100] test_spam.py::test_pic[pic3-200] test_spam.py::test_pic[pic3-300] no tests ran in 0.07 seconds Indirect parametrization Now you want to process the file parameter before the test, so the test gets the downloaded file for pic1 instead of pic1. This can be done with indirect parametrization. What you need to do is: implement a fixture named file (it is important that the fixture has the same name as the test parameter, or pytest won't recognize and apply it); add indirect=['file'] to parametrization marker. This way, pic1 is first passed to file() fixture and the result of the fixture is then passed to the test. Extended example: import pathlib import pytest PARAMS = {'pic1': [1, 2, 3], 'pic2': [14, 15], 'pic3': [100, 200, 300]} test_pic_params = [(key, el) for key, nums in PARAMS.items() for el in nums] @pytest.fixture def file(request): pic = request.param # this will just create an empty file named 'pic1' etc; # replace it with file download logic filename =…
has comment: http://stackoverflow.com/comment/89655614
accepted answer of: http://stackoverflow.com/q/51337165
answers question: http://stackoverflow.com/q/51337165
type: Answer
upvote count: 6
score: 6
has comment: http://stackoverflow.com/comment/89684575
has comment: http://stackoverflow.com/comment/89685046
has comment: http://stackoverflow.com/comment/89668286

http://stackoverflow.com/comment/89718626
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51373500
score: 1
has text: Is that turtle or pygame?

http://stackoverflow.com/a/61856603
has body: The real fix that worked for me was to install the module that was causing the error, that is the PySide module. Do not install PySide (pip install PySide) unless you are using Python 3.4 or less. If you are running Python 3.4 and up (up to 3.7), you need to install PySide2 (pip install PySide2). None of the other answers worked for me at all because the error was the same all over again.
score: 0
answers question: http://stackoverflow.com/q/51435579
type: Answer

http://stackoverflow.com/q/51381456
downvote count: 4
answer count: 1
favorite count: 0
has title: How to run multiple functions in parallel using python script
tagged with: python
has comment: http://stackoverflow.com/comment/89734634
type: UnansweredQuestion
tagged with: multithreading
upvote count: 1
has body: We have 7 functions which we have to run parallel using python script ,we have tried using multiprocessor and Process api of python but still the functions are running one by one ,I have created one method and with multiple functional block and i tried with multiple method but that also didnt work..
score: -3
type: Question
has answer: http://stackoverflow.com/a/51381595

http://stackoverflow.com/comment/89641105
type: QuestionComment
comment on: http://stackoverflow.com/q/51332803
has text: Well it is sorting, just that since they are strings it's alphabetical. Why not keep the `'Day'` as a `datetime64` with `pd.to_datetime()` and then if you ever need to figure out what day of the week it is you can just use the `datetime` attribute `.dt.weekday`
score: 0
type: Comment

http://stackoverflow.com/comment/89669062
has text: Can you [edit] your post to include that in a codeblock - it's not particularly readable in comments...
comment on: http://stackoverflow.com/q/51348192
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89799153
type: QuestionComment
has text: Ok, thanks I will try
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51413687

http://stackoverflow.com/comment/90003756
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51472515
type: AnswerComment
has text: You have anaconda installed. Can you try "conda install -c cogsci pygame" on your command prompt?

http://stackoverflow.com/q/51363200
has answer: http://stackoverflow.com/a/51363474
type: Question
tagged with: javascript
has title: How can I extract text from another website using python and JavaScript?
score: 0
answer count: 1
has body: I would like to link some text that is under directors from for example from IMDb. I can see JavaScript is used in the inspect element, is it possible to list the movie names as a list in the output of python? Making the code read just that part of the JavaScript from the website and then being able to use it without the need of writing the titles down. In addition, can it only note "movie titles" in years 2015 - 2015. I am a beginner but this is a project to help reduce time when writing something.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89698721
tagged with: python

http://stackoverflow.com/q/51429465
favorite count: 0
accepted answer: http://stackoverflow.com/a/51455486
score: 6
tagged with: python
upvote count: 6
type: AnsweredQuestion
tagged with: matplotlib
tagged with: python-unittest
tagged with: unit-testing
type: Question
has body: I want to assert that matplotlib.pyplot.show was called in one of my class's methods, but I don't want the method to actually call show() and plot on an external window during the unit test. No matter how I try to mock matplotlib, it doesn't seem to work. I'll list the important parts of my code below: #In Model Test Class: import Model import matplotlib import unittest from unittest.mock import patch class Model_Test(unittest.TestCase): @patch('matplotlib.pyplot') def test_plot_data(self, mock_pyplot): model = Model() model.plot_data() mock_pyplot.show.assert_called_once() #In Model Class: import matplotlib.pyplot as plt import pandas as pd class Model(object): ... # (__init__ and other methods) def plot_data(self): self.dataframe.plot(y=self.dataframe.columns, subplots=False, figsize=(15, 8), fontsize=12) plt.title('Data for Model Version: ' + self.version, fontsize=20) plt.xlabel('timestamp', fontsize=12) plt.ylabel('value', fontsize=12) plt.show() I also tried setting a return value for mock_plot.show. When I use the debugger, matplotlib within the Model class is not propagated with a Mock object, so I am unsure how to mock the matplotlib module or its member functions. Is it possible to mock matplotlib? Any ideas for how to properly mock matplotlib in unit tests (mainly to prevent displaying plots)? EDIT: I was able to get it to work by changing the patch decoration to @patch('matplotlib.pyplot.show'), but I'm still unsure why this worked and my previous attempt didn't.
tagged with: mocking
has title: How to mock pyplot.show in python (to prevent showing plots)
has answer: http://stackoverflow.com/a/51455486
downvote count: 0
answer count: 1

http://stackoverflow.com/q/51349381
has comment: http://stackoverflow.com/comment/89671646
has comment: http://stackoverflow.com/comment/89671335
score: 0
answer count: 2
tagged with: string
has answer: http://stackoverflow.com/a/51349444
duplicate of: http://stackoverflow.com/q/1059559
tagged with: python
has comment: http://stackoverflow.com/comment/89671618
linked to: http://stackoverflow.com/q/4998629
tagged with: delimiter
has comment: http://stackoverflow.com/comment/89671360
has comment: http://stackoverflow.com/comment/89671693
linked to: http://stackoverflow.com/q/1059559
accepted answer: http://stackoverflow.com/a/51349444
possible better answer: http://stackoverflow.com/a/51349451
has body: I want to split a string by remove everything expect alphabetical characters. By default, split only splits by whitespace between words. But I want to split by everything expect alphabetical characters. How can I add multiple delimiter to split? For example: word1 = input().lower().split() # if you input " has 15 science@and^engineering--departments, affiliated centers, Bandar Abbas&amp;&amp;and Mahshahr." #the result will be ['has', '15', 'science@and^engineering--departments,', 'affiliated', 'centers,', 'bandar', 'abbas&amp;&amp;and', 'mahshahr.'] But I am looking for this kind of result: ['has', '15', 'science', 'and', 'engineering', 'departments', 'affiliated', 'centers', 'bandar', 'abbas', 'and', 'mahshahr']
has comment: http://stackoverflow.com/comment/89671308
has answer: http://stackoverflow.com/a/51349451
type: Question
type: AnsweredQuestion
has title: How to split a string with many delimiter in python?

wolfram-mathematica
tags question: http://stackoverflow.com/q/51415823
tag name: wolfram-mathematica
type: Tag
tags question: http://stackoverflow.com/q/51392040

http://stackoverflow.com/a/51460194
has comment: http://stackoverflow.com/comment/89889930
has body: My first suggestion would be to start off with a 2D list: MT = "X", 1, 2, 3, 4, 5, 6, 7, 8, 9 ,10 rather than what you have. Start a new empty list right before the inner while loop. You can initialize it with the first value new_row = [repeat]. Inside that loop append to the new_row rather than MT After that while loop is done, you can append the new_row to MT MT.append(new_row) That should get you started with the 2d list. However, while I have you here... If you need to repeat and keep track of how many times you've repeated, then use a for loop rather than a while loop. For example, if you want a loop that goes from 2 to 12 you'd use: for repeat in range(2, 13): print(repeat) Also, never overwrite built-in keywords as that can lead to unexpected behavior. So name list something else but I don't think that variable is really needed since it is similar to repeat.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51460055
type: Answer
answers question: http://stackoverflow.com/q/51460055
score: 0

http://stackoverflow.com/q/51344674
has comment: http://stackoverflow.com/comment/89662645
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89662937
upvote count: 2
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89662811
has comment: http://stackoverflow.com/comment/89662942
has answer: http://stackoverflow.com/a/51344949
has comment: http://stackoverflow.com/comment/89662676
score: 2
type: Question
has body: I have two tables / pandas DataFrames. table1 that needs to be classified, i.e. filling the column class, based on the data in a to c ... a b c class1 class2 class3 0 2 3 4 ??? ??? ??? 1 3 5 0 ??? ??? ??? 2 9 8 2 ??? ??? ??? ... and table2 that provides the classification rules. a a b b c c min max min max min max class1 0 9 0 9 0 9 class2 1 3 4 5 0 1 class3 1 5 3 9 1 3 So the goal is to complement the classifications for each row in table1 by comparing if columns a to c all fall between min and max of table2. The result would look like this: a b c class1 class2 class3 0 2 3 4 True False False 1 3 5 0 True True False 2 9 8 2 True False False In row 0 that means: class1: 0 &lt;= a &lt;= 9 and 0 &lt;= b &lt;= 9 and 0 &lt;= c &lt;= 9 is True class2: 1 &lt;= a &lt;= 3 and 4 &lt;= b &lt;= 5 and 0 &lt;= c &lt;= 1 is False class3: 1 &lt;= a &lt;= 5 and 3 &lt;= b &lt;= 9 and 1 &lt;= c &lt;= 3 is False As an additional difficulty, the number of columns is arbitrary. So the solution should work for different table sizes. I could simply loop through both tables and test by line and classification, but that would be very inefficient. Is there a more elegant pandas-like solution?
has title: Classifying a pandas DataFrame using another DataFrame
tagged with: dataframe
tagged with: comparison
tagged with: pandas

http://stackoverflow.com/comment/89894804
type: QuestionComment
score: 2
has text: don't use python keyword `list` to name a variable
type: Comment
comment on: http://stackoverflow.com/q/51462948

http://stackoverflow.com/q/51420002
has answer: http://stackoverflow.com/a/55417457
linked to: http://stackoverflow.com/q/42073357
tagged with: gitlab-ci-runner
upvote count: 29
has comment: http://stackoverflow.com/comment/89811210
has answer: http://stackoverflow.com/a/70721129
has answer: http://stackoverflow.com/a/68657068
has comment: http://stackoverflow.com/comment/96478300
has answer: http://stackoverflow.com/a/65345673
tagged with: gitlab-ci
favorite count: 0
tagged with: linux
answer count: 5
type: UnansweredQuestion
tagged with: python
tagged with: gitlab
has title: How to solve the "remote: You are not allowed to upload code." error on GitLab CI/CD job?
has body: I am currently trying to use GitLab to run a CI/CD job that runs a Python file that makes changes to a particular repository and then commits and pushes those changes to master. I also have a role of Master in the repository. It appears that all git functions run fine except for the git push, which leads to fatal: You are not currently on a branch. and with using git push origin HEAD:master --force, that leads to fatal: unable to access 'https://gitlab-ci-token:xxx@xxx/project.git/': The requested URL returned error: 403. I've been looking over solutions online, one being this one, and another being unprotecting it, and couldn't quite find what I was looking for just yet. This is also a sub-project within the GitLab repository. Right now, this is pretty much what my .gitlab-ci.yml looks like. before_script: - apt-get update -y - apt-get install git -y - apt-get install python -y - apt-get python-pip -y main: script: - git config --global user.email "xxx@xxx" - git config --global user.name "xxx xxx" - git config --global push.default simple - python main.py My main.py file essentially has a function that creates a new file within an internal directory provided that it doesn't already exist. It has a looks similar to the following: import os import json def createFile(strings): print "&gt;&gt;&gt; Pushing to repo..."; if not os.path.exists('files'): os.system('mkdir files'); for s in strings: title = ("files/"+str(s['title'])+".json").encode('utf-8').strip(); with open(title, 'w') as filedata: json.dump(s, filedata, indent=4); os.system('git add files/'); os.system('git commit -m "Added a directory with a JSON file in it..."'); os.system('git push origin HEAD:master --force'); createFile([{"title":"A"}, {"title":"B"}]); I'm not entirely sure why this keeps happening, but I have even tried to modify the repository settings to change from protected pull and push access, but when I hit Save, it doesn't actually save. Nonetheless, this is my overall output. I would reall…
downvote count: 0
score: 29
has answer: http://stackoverflow.com/a/65578500
type: Question

http://stackoverflow.com/a/53190791
has comment: http://stackoverflow.com/comment/96234979
type: Answer
answers question: http://stackoverflow.com/q/51374273
has body: Hi my solution was using linux in the following way Windows Subsystem for Linux - see then install from store ubunto then need to pip3 install --upgrade "tensorflow=1.7*" then if you try to run toco it would not be recognized. the solution is go to folder ~/.local/bin/ there you would find toco, this is a python file. run python3 ~/.local/bin/toco you would get the "exe" of toco. to convert you can run the command explained in https://codelabs.developers.google.com/codelabs/tensorflow-for-poets-2-tflite/#2 just change the -graph_def_file=tf_files/retrained_graph.pb to --input_file=tf_files/retrained_graph.pb Hope this helps someone Note: if you are missing pip3, you would need to install it
upvote count: 1
score: 1
downvote count: 0

http://stackoverflow.com/a/51358453
has body: ix = abs(df.corr()).sort_values('A', ascending=False).index This was so much easier than expected.
type: Answer
accepted answer of: http://stackoverflow.com/q/51358289
answers question: http://stackoverflow.com/q/51358289
downvote count: 1
score: 3
upvote count: 4
type: AcceptedAnswer

http://stackoverflow.com/comment/89860315
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51444844
has text: if you change `environments` in first script, try to get one more time the env, i update my answer
type: AnswerComment

http://stackoverflow.com/comment/89930310
comment on: http://stackoverflow.com/q/51475082
has text: @DanielMöller i'll edit with a screenshot
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/73289119
has comment: http://stackoverflow.com/comment/129484163
answers question: http://stackoverflow.com/q/51392779
downvote count: 2
type: Answer
upvote count: 0
score: -2
has body: if __name__ == '__main__': n = int(input()) for i in range(0,n): (i*i) and 1 &lt;=n &lt;=20 print(i*i)

http://stackoverflow.com/q/51338338
upvote count: 1
has comment: http://stackoverflow.com/comment/89651158
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89651218
score: 0
answer count: 1
has body: my score label or chances count is not configured when i run the function. can anyone help on this? the question label changes perfectly but the score label does not change and i am unable to understand why is that so. def checkans(self): chances = 0 score = 0 count = 0 while chances == 3: break else: operations=['+', '-', '*'] a = random.randint(1,15) b = random.randint(1,15) random.shuffle(operations) op = operations[0] self.label.configure(text=(a,op,b)) if op == '+': ans = a + b if op == '-': ans = a - b if op == '*': ans = a * b self.e.focus_set() if self.e.get() == ans: score += 1 self.scorelabel.configure(text=('score', score)) else: chances += 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89651169
has answer: http://stackoverflow.com/a/51341892
type: UnansweredQuestion
tagged with: python
has title: why label is not being configured in function?
tagged with: tkinter

http://stackoverflow.com/q/51478288
type: Question
has body: I have 2 queries that you can find print results as below. &lt;QuerySet [{'swtype': 1}, {'swtype': 2}]&gt; &lt;QuerySet ['201;203;205', '207;208']&gt; I looked some commands at stackoverflow for pairing these lists as per below. pair = itertools.zip_longest(swtype, p_list) But the output is not as I was seeking. It's like 1:201 2:203 none:205 none:207 none:208 What I am after is to have: 1:201 none:203 none:205 2:207 none:208 Is that possible by zipping or should I create 2 seperate loops. If I create 2 seperate loops than I am having other problems.
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89925270
has comment: http://stackoverflow.com/comment/89925235
has answer: http://stackoverflow.com/a/51478540
favorite count: 0
has title: django zip unequal lists
tagged with: http://stackoverflow.com/tag/zip
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89924992
type: AnsweredQuestion
tagged with: list
score: 1
accepted answer: http://stackoverflow.com/a/51478540

http://stackoverflow.com/q/51380270
type: Question
upvote count: 5
tagged with: duplicates
possible better answer: http://stackoverflow.com/a/51380416
has answer: http://stackoverflow.com/a/51380416
score: 5
has body: My question is similar to this, but instead of removing full duplicates I'd like to remove consecutive partial "duplicates" from a list in python. For my particular use case, I want to remove words from a list that start consecutive with the same character, and I want to be able to define that character. For this example it's #, so ['#python', 'is', '#great', 'for', 'handling', 'text', '#python', '#text', '#nonsense', '#morenonsense', '.'] should become ['#python', 'is', '#great', 'for', 'handling', 'text', '.']
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/51380444
favorite count: 0
tagged with: python
has title: Removing elements that have consecutive partial duplicates in Python
has answer: http://stackoverflow.com/a/51381052
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/51380444
linked to: http://stackoverflow.com/q/5738901

http://stackoverflow.com/a/51448740
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/51448587
downvote count: 0
has comment: http://stackoverflow.com/comment/89868045
accepted answer of: http://stackoverflow.com/q/51448587
has body: The following should do the trick: train_file = "training_data_ez.csv" train_features = pd.read_csv(train_file, usecols=['var', 'sq', 'sin']) The pd.DataFrame.sample method let's you randomly sample from your pd.DataFrame. By default this is without replacement, i.e. we don't sample the same row twice. df_950 = train_features.sample(950) The remaining 50 we can just get by dropping the 950 rows from our original DataFrame. df_50 = train_features.drop(df_950.index) The train_test_split function from scikit-learn is an alternative, if you need to preserve class-balance in your random samples.
has comment: http://stackoverflow.com/comment/89868535
score: 4
type: AcceptedAnswer

http://stackoverflow.com/q/51481069
type: Question
answer count: 2
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/79085535
has answer: http://stackoverflow.com/a/79085535
tagged with: python
tagged with: php
has answer: http://stackoverflow.com/a/51481340
linked to: http://stackoverflow.com/q/37264368
linked to: http://stackoverflow.com/q/31811253
has title: PHP Execute Python Script on button click
upvote count: 1
linked to: http://stackoverflow.com/q/3446216
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89930894
score: 1
accepted answer: http://stackoverflow.com/a/51481340
has body: I am using php to have a button refresh a python script. The goal of this is to when a certain input is present and a button is pressed, to run the python script. If there is no user input, there is a default value for $input_val, just incase. The way I have been trying to test this is in my python file, I have a line that should output to var/tmp/my_logfile.log, but no logs are being returned when run through the php page. Like every other stack article I've seen it works in the command prompt. The code I use to try this has been the following: PHP: if (isset($_POST['update'])) { exec('/usr/bin/python3 /var/www/python_test.py ".$input_val."'); } HTML: &lt;form name="update" method="post" &gt; &lt;button name = "update" type="submit"&gt; Update charts &lt;/button&gt; &lt;/form&gt; Some of the references I have used, but to no luck: Execute Python script from Php HTML form button to run PHP to execute Python script https://www.raspberrypi.org/forums/viewtopic.php?t=105932 https://serverfault.com/questions/679198/executing-a-python-script-through-php-button
has comment: http://stackoverflow.com/comment/89931583

http://stackoverflow.com/a/51525414
has body: Here's an example of searching for an anchor element with a specific URL in BS: from bs4 import BeautifulSoup document = ''' google Unatama Don Don ''' soup = BeautifulSoup(document, "lxml") url = "/f/oDhilr3O" for x in soup.find_all("a", {"href" : url}): print(x.text) Output: Unatama Don
score: 0
answers question: http://stackoverflow.com/q/51450243
type: Answer

http://stackoverflow.com/comment/89719611
type: AnswerComment
type: Comment
has text: can you provide a link to website?
comment on: http://stackoverflow.com/a/51373703
score: 0

http://stackoverflow.com/a/51432784
has body: It looks like you have a dataset iterator that has not been initialized. A dataset iterator is not a variable, hence does not get initialized with tf.global_variables_intializer(). You have to initialize it explicitly by calling sess.run(iterator.initializer) on whatever dataset iterator you created (e.g. with iterator = dataset.make_initializable_iterator(). Additionally, note that each dataset iteration (running the GetNext node) yields a complete element of the dataset, even if you only care about a subset of the element. If data_dict is the output of an iteration (created with data_dict = iterator.get_next()), doing print(sess.run(i[1])), while only giving you one of the k,v pairs in the dictionary, actually yields the whole data_dict. I expect that this pipeline would not give you the output you expect unless you reinitialize the iterator within the for loop. To make what I'm saying more concrete, if you had a dataset created as follows, you would expect the following iteration outputs: ## dataset: [{'a':0, 'b':10}, {'a':1, 'b':11}, {'a':2, 'b':12}, ...] dataset = tf.data.Dataset.range(10).map(lambda x: {'a': x, 'b': x + 10}) iterator = dataset.make_initializable_iterator() next_elem = iterator.get_next() with tf.Session() as sess: sess.run(iterator.initializer) print(sess.run(next_elem['a'])) # 0 print(sess.run(next_elem['a'])) # 1 print(sess.run(next_elem['b'])) # 12
answers question: http://stackoverflow.com/q/51419237
upvote count: 5
score: 5
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/89838805
has comment: http://stackoverflow.com/comment/89938397

http://stackoverflow.com/comment/89710650
type: QuestionComment
has text: (almost) a duplicate of https://stackoverflow.com/questions/2407398/how-to-merge-lists-into-a-list-of-tuples
type: Comment
comment on: http://stackoverflow.com/q/51369187
score: 0

http://stackoverflow.com/comment/89860141
has text: Yes max this is also true
type: QuestionComment
comment on: http://stackoverflow.com/q/51444958
type: Comment
score: 0

http://stackoverflow.com/q/51480428
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89985043
tagged with: anaconda
answer count: 0
type: Question
tagged with: jupyter-irkernel
has title: I cannot open Anaconda and Jupyter has 0 active kernels
has body: Firstly, I re-installed Anaconda, but I cannot open Anaconda. When I click it, it has no response. When I am trying to open Anaconda at the command line using the following: anaconda-navigator I got an error as follows: from PySide import __version__ as PYSIDE_VERSION # analysis:ignore ModuleNotFoundError: No module named 'PySide' But I actually have piped pyqt5. I do not know how to solve it, I cannot open Anaconda. Secondly，as I am not able to open Anaconda, I am trying to open Jupyter at the command line using jupyter notebook, but I got error as 0 active kernels. When I get into the Jupyter notebook, I can't do anything. I cannot build a new file as follows: when I click the new button, no response. I've tried to re-install Python and Anaconda many times, but I still get the error. Can anyone help me to figure out what's wrong with it?
downvote count: 0
tagged with: jupyter
score: 1
tagged with: jupyter-notebook
favorite count: 0

http://stackoverflow.com/comment/89727219
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51377617
type: AnswerComment
has text: Thank you for the link to this very interesting article!

http://stackoverflow.com/q/51446817
tagged with: ms-access
favorite count: 0
accepted answer: http://stackoverflow.com/a/51446992
tagged with: python
type: AnsweredQuestion
has title: AttributeError: 'NoneType' object has no attribute 'DoCmd'
has comment: http://stackoverflow.com/comment/89864466
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89863882
has body: Having trouble figuring out what I'm doing wrong. Here is the code: import smtplib import win32api,time import pypyodbc from win32com.client import Dispatch DbName = 'C:/Users/billybob643/Documents/Database1.accb' Access = Dispatch("Access.Application") Access.OpenCurrentDatabase(DbName) DbAccess = Access.CurrentDb() DbAccess.DoCmd.RunMacro("00") Any help would be greatly appreciated. Thanks!
type: Question
has answer: http://stackoverflow.com/a/51446992
answer count: 1
downvote count: 0

http://stackoverflow.com/a/51346855
score: 3
answers question: http://stackoverflow.com/q/51346710
upvote count: 3
has body: You could check for duplicates. In [200]: dfs = {i: n for i, n in df.groupby( df.duplicated(subset=['column_B', 'column_C'], keep=False))} In [201]: dfs[True] Out[201]: column_A column_B column_C id 0 1 1 anna 123 1 2 1 anna 7 2 30 2 bob 42 2 20 2 bob 12 In [202]: dfs[False] Out[202]: column_A column_B column_C id 3 10 3 charlie 1 4 100 3 david 2
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51346710

http://stackoverflow.com/comment/89837654
type: Comment
has text: @gahooa I fixed that, thank you.
type: QuestionComment
comment on: http://stackoverflow.com/q/51433070
score: 0

http://stackoverflow.com/comment/89871622
has text: @abarnert I'm looking at the Python 3.5 source code, since I'm dealing with it
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51448030
type: QuestionComment

http://stackoverflow.com/comment/89761530
type: Comment
type: QuestionComment
has text: five questions in one question?
comment on: http://stackoverflow.com/q/51395116
score: 0

http://stackoverflow.com/q/51465708
score: 1
has answer: http://stackoverflow.com/a/51466322
upvote count: 1
tagged with: scipy
type: Question
tagged with: numpy
tagged with: sympy
accepted answer: http://stackoverflow.com/a/51466322
answer count: 1
downvote count: 0
favorite count: 0
has title: Find a transformation to a random variable X from Uniform(0, 1) with SymPy
has body: Is it possible to find the transformation expression to X from U(0, 1) in SymPy? import sympy.stats as stat import sympy as sp x = sp.Symbol('x') p = sp.Piecewise( (x + 1, (-1. &lt;= x) &amp; (x &lt;= 0)), (1 - x, (x &gt;= 0) &amp; (x &lt;=1 )), (0, True) ) X = stat.ContinuousRV(x, p, Interval(-1, 1)) cdf = stat.cdf(X)(x) # Where to go from here? stat.sample(X) # TypeError: object of type 'ConditionSet' has no len() sample in sympy/stats/crv.py def sample(self): 172 """ A random realization from the distribution """ --&gt; 173 icdf = self._inverse_cdf_expression() 174 return icdf(random.uniform(0, 1)) How can I find the inverse cdf expression from the custom piecewise? By hand I get: 1 - sqrt(2-2u) Is it possible with another library?
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/89695149
score: 0
type: Comment
type: QuestionComment
has text: @Adelin Sorry it was a typo. Actually i want to use Login Function from __init__.py into my login_test.py loginModel import was by mistake
comment on: http://stackoverflow.com/q/51361412

http://stackoverflow.com/a/51346456
score: 0
type: AcceptedAnswer
has body: The energy dataset is just a single column table with one cell being one energy value per second of a few days. You will not be able to apply supervised learning for this dataset as you do not have labels for your dataset (there is no known state given an energy value). This means that models like SVM, decision trees, etc. are not feasible given your dataset. What you have is a timeseries with a single variable output. As I understand it, your goal is to determine whether or not there are different energy states, and what the average value is for those state(s). I think it would be incredibly helpful to plot the timeseries using something like matplotlib or seaborn. After plotting the data, you can have a better feel for whether your hypothesis is reasonable and how you might further want to approach the problem. You may be able to solve your problem by just plotting the timeseries and observing that there are, say, four distinct energy states (e.g. idle, standby, working, etc.), avoiding any complex statistical techniques, machine learning, etc. To answer your question, you can in principle use k-means for one dimensional data. However, this is probably not recommended as these techniques are usually used on multidimensional data. I would recommend that you look into Jenks natural breaks optimization or kernel density optimization. Similar questions to yours can be found here and here, and should help you get started.
type: Answer
answers question: http://stackoverflow.com/q/51342369
accepted answer of: http://stackoverflow.com/q/51342369

http://stackoverflow.com/comment/89633287
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51328252
has text: That worked, but i needed to replace `csvRow.append(cell.text.encode('ascii', 'replace')` to `csvRow.append(cell.getText())`
score: 0

http://stackoverflow.com/q/51447977
downvote count: 0
has title: Python- How to apply dot product between elements of a data frame
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/51448168
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51448129
type: Question
accepted answer: http://stackoverflow.com/a/51448168
has body: I have two data frames. Both have one column of numpy arrays with 3 elements per entry, like so: 0 [0.552347, 0.762896, 0.336009] 1 [0.530716, 0.808313, 0.254895] 2 [0.528786, 0.734991, 0.424469] 3 [0.202799, 0.669395, -0.714691] 4 [0.791936, -0.100072, -0.602347] 6 [0.428896, -0.122712, 0.89498] How do I take the dot product of each row of one data frame with the corresponding row of the other data frame? Meaning, I want to calculate the dot product of the first element of df1 with the first element of df2, then the second element of df1 with the second element of df2, then third, and so on.
has answer: http://stackoverflow.com/a/51448044
answer count: 3
tagged with: pandas
possible better answer: http://stackoverflow.com/a/51448044

http://stackoverflow.com/a/51439098
score: 0
answers question: http://stackoverflow.com/q/51425713
type: Answer
has body: The right way to answer the question - is to use reset_index() function. After using grouby() function we need to reset MultiIndex to index. In code it wiil be: result.reset_index().merge(array1, on=['Project'])

http://stackoverflow.com/q/51429266
type: Question
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89830425
has comment: http://stackoverflow.com/comment/89852017
tagged with: tkinter
has body: def browse_button(): ## Store the path as a global variable global folder_path filename = filedialog.askdirectory() folder_path.set(filename) print(filename) return folder_path def outputfile(): global out_path filepath = filedialog.asksaveasfilename(filetypes = (("CSV","*.csv"),("all files","*.*"))) out_path.set(filepath) print (filepath) return out_path ## Instantiating root widget root = Tk() # StringVar and IntVar are a type of control variable. #These store values needed later folder_path= StringVar() out_path = StringVar() h20_yr = IntVar() wy_lbl= Label(root, text = "Water Year: ") wy_lbl.grid( row = 0, column = 1) wy_entry = Entry(root) wy_entry.grid(row = 0, column = 2) lbl1 = Label(root, textvariable = folder_path) lbl1.grid(row = 1, column=1) browse = Button(text="Input Folder", command=browse_button) browse.grid(row=1, column=2) lbl2 = Label(root, textvariable= out_path) lbl2.grid(row =2, column = 1) save_as = Button(text = 'Save Output', command = outputfile) save_as.grid(row = 2, column = 2) print( folder_path.get(), out_path.get(), h20_yr.get()) Novice python user here. The labels populate and file paths to the chosen folder and output file are printed no problemo through the function call as the button command. Why are these then not stored globally? I need to pass these values to existing code that runs the program. Thanks in advance.
answer count: 0
type: UnansweredQuestion
has title: Unable to pass tkinter callback values to functions

http://stackoverflow.com/comment/89759162
has text: Only know one way - [query()](https://pandas.pydata.org/pandas-docs/stable/indexing.html#the-query-method). Interested to see a comparative analysis of efficiencies of alternatives though.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51390164
type: QuestionComment

http://stackoverflow.com/comment/89741500
score: 1
has text: What exactly do you mean by alternating tests? On the other hand, if your tests are implemented in a way that they fail when run with other tests but pass when they are run individually, there seems to be an issues with dependencies between your tests. I would rather fix this by implementing fixtures
type: Comment
comment on: http://stackoverflow.com/q/51384360
type: QuestionComment

http://stackoverflow.com/comment/89778382
has text: I tried that, but it doesn't work. I get the error "ValueError: Could not find root within given tolerance (6.21975346313850940634e-12 > 2.16840434497100886801e-19). Try another starting point or tweak arguments." The other thing about NSolve in Python is that I can't specify that the solution be positive
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51392040
score: 0

getmethod
tag name: getmethod
type: Tag
tags question: http://stackoverflow.com/q/51362902

peewee
tag name: peewee
type: Tag
tags question: http://stackoverflow.com/q/51427625
tags question: http://stackoverflow.com/q/51473354
tags question: http://stackoverflow.com/q/51468973
tags question: http://stackoverflow.com/q/51461102
tags question: http://stackoverflow.com/q/51478412

http://stackoverflow.com/comment/89849242
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51439435
type: Comment
has text: you can check the extensions of the file and then decide

http://stackoverflow.com/q/51391065
type: Question
downvote count: 0
has title: Editing JSON file with HTTP request to Flask server from other computers
tagged with: flask
linked to: http://stackoverflow.com/q/32815451
favorite count: 0
tagged with: python-3.x
answer count: 0
duplicate of: http://stackoverflow.com/q/32815451
type: UnansweredQuestion
has body: I couldn't think of a good title that really described what I'm looking for so I did my best. Basically I have a Flask server that has several endpoints. It holds data in a JSON file on my system. I have an endpoint called "/update_json" which I can pass a paramater like http://127.0.0.1:5000/update_json?json_key=json_value and it will update the json file with the key and value passed. So if I'm not mistaken it might not work on other system's since they won't have the json file correct? The specific code looks like this @app.route("/update_json") def update_json(): args = request.args args = jsonify(args) with open("static/data.json") as f: data = json.load(f) for key in args.json: data["test"][key] = args.json[key] data = json.dumps(data, indent=4) with open("static/data.json", "w") as f: f.write(data) if request.args: return "Succesfully updated the JSON" else: return "Please include some keys and values to update the JSON if this won't work on other systems what's a possible solution. Thanks in advance
upvote count: 1
tagged with: python
duplicate of: http://stackoverflow.com/q/489861
score: 1

http://stackoverflow.com/q/51388201
linked to: http://stackoverflow.com/q/19913659
tagged with: python
has answer: http://stackoverflow.com/a/51388828
has comment: http://stackoverflow.com/comment/90100305
tagged with: cython
has body: In a Pandas DataFrame, I want to create a new column conditionally based on the value of another column. In my application, the DataFrame typically has a few million lines, and the number of unique conditional values is small, on the order of unity. Performance is extremely important: what is the fastest way to generate the new column? I created an example case below, and tried and compared different methods already. In the example, the conditional filling is represented by a dictionary lookup based on the value of the column label (here: one of 1, 2, 3). lookup_dict = { 1: 100, # arbitrary 2: 200, # arbitrary 3: 300, # arbitrary } I then expect my DataFrame to be filled as: label output 0 3 300 1 2 200 2 3 300 3 3 300 4 2 200 5 2 200 6 1 100 7 1 100 Below are 6 different methods tested on 10M lines (parameter Nlines in the test code): method 1: pandas.groupby().apply() method 2: pandas.groupby().indices.items() method 3: pandas.Series.map method 4: for loop on labels method 5: numpy.select method 6: numba The full code is available at the end of the answer, with the runtimes of all methods. The output of every method is asserted to be equal before performances are compared. method 1: pandas.groupby().apply() I use pandas.groupby() on the label, then fills each block with the same value using apply(). def fill_output(r): ''' called by groupby().apply(): all r.label values are the same ''' r.loc[:, 'output'] = lookup_dict[r.iloc[0]['label']] return r df = df.groupby('label').apply(fill_output) I get &gt;&gt;&gt; method_1_groupby ran in 2.29s (average over 3 iterations) Note that groupby().apply() is ran twice on the first group to determine which code path to use (see Pandas #2936). This can slow things down for a small number of groups. I tricked the Method 1 can adding a first dummy group, but I didn't get much improvement. method 2: pandas.groupby().indices.items() Second is a variant: instead of using apply I access the indices directy with groupby().indices.item…
has title: Fastest way to create a pandas column conditionally
answer count: 1
upvote count: 17
tagged with: performance
accepted answer: http://stackoverflow.com/a/51388828
tagged with: numpy
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/89753786
score: 17
favorite count: 0
type: Question

http://stackoverflow.com/q/51423911
score: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51424784
tagged with: python
has title: pandas pct_change unrealistic values
has comment: http://stackoverflow.com/comment/89819720
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89819343
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/51424784
has body: i execute the following python code: data_extracted = data_extracted.interpolate(method='linear', axis=0).ffill().bfill() data_extracted = data_extracted.replace([np.inf, -np.inf], np.nan).fillna(0) data_pct_change = data_extracted.pct_change(axis=0).replace([np.inf, -np.inf], np.nan) data_pct_change = data_pct_change.fillna(0) print(data_pct_change) This is the input(data_extracted, example): ARTICLE_NUMBER 400115897090 500109158982 DATE 2016-01-18 NaN NaN 2016-02-01 5914.0 8776.0 2016-02-15 NaN NaN 2016-02-29 NaN 4402.0 2016-03-14 6214.0 6880.0 2016-04-04 6766.0 7942.0 2016-04-11 6454.0 7528.0 2016-04-25 6070.0 7534.0 2016-05-16 6778.0 7066.0 2016-05-30 6856.0 NaN 2016-06-20 7132.0 7138.0 2016-06-27 7384.0 7426.0 2016-07-18 8830.0 8614.0 2016-08-01 9448.0 9166.0 2016-08-15 8824.0 9676.0 2016-08-22 8500.0 8974.0 2016-09-12 6226.0 6868.0 2016-10-03 6754.0 7426.0 2016-11-07 NaN 8296.0 2016-11-14 7858.0 8116.0 2016-11-21 8212.0 9070.0 2016-12-05 NaN NaN 2016-12-19 9428.0 8284.0 Then the code above is executed and i get the follwoing result: ARTICLE_NUMBER 400115897090 500109158982 DATE 2016-01-18 0.000000 0.000000 2016-02-01 0.000000 0.000000 2016-02-15 0.000000 0.000000 2016-02-29 0.000000 0.000000 2016-03-14 0.000000 0.000000 2016-04-04 0.000000 0.000000 2016-04-11 0.000000 0.000000 2016-04-25 0.000000 0.000000 2016-05-16 0.000000 0.000000 2016-05-30 0.000000 0.000000 2016-06-20 0.000000 0.000000 2016-06-27 0.000000 0.000000 2016-07-18 0.000000 0.000000 2016-08-01 0.000000 0.000000 2016-08-15 0.000000 0.000000 2016-08-22 13.384615 252.600000 2016-09-12 -0.221925 0.807571 2016-10-03 0.407216 0.172339 2016-11-07 -0.104396 -0.109044 2016-11-14 0.053170 0.299499 2016-11-21 -0.029773 -0.020572 2016-12-05 0.111074 -0.798490 2016-12-19 0.099970 4.998371 Why do i get such wrong results? I know about floating point precision, but that here is really weird. For example: 2016-08-22: An increase of 252% from 9676 to 8974. That is definitvely wrong as well as the 0.000000's Can …

http://stackoverflow.com/q/51349064
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89672601
answer count: 0
score: 1
upvote count: 1
type: Question
tagged with: pandas
downvote count: 0
has title: Columns gone missing after using pandas pd.concat
favorite count: 0
has body: I try to combine two data frames using the following code: df1=pd.read_csv('NBA_2010_new.csv',encoding='ISO-8859-1') df2=pd.read_csv('NBA_2011.csv',encoding='ISO-8859-1') frames = [df1,df2] combine = pd.concat(frames,axis=0,ignore_index=True,join='inner') df=combine.reset_index(drop = True) df.index += 1 The CSV files originally contains 26 columns..but the when i try to view df using df.info()...it only says 22 columns, some columns are missing....
has comment: http://stackoverflow.com/comment/89715980

http://stackoverflow.com/q/51405551
has answer: http://stackoverflow.com/a/51445984
has body: I have a function which adds a text widget to the frame dynamically when a user clicks a button. And then different text is inserted into each of the text widget. These text widgets have been stored in a list because I want to scroll all the text box by calling the .see method. I have a function defined which auto-scrolls all the text widget to a specific position which is obtained using the text.search() method. the text.search() methods returns the index for the search-term from the text widget no. 1 of the frame, and then it auto-scrolls all the text widget. Question How to search for a specific term individually in all text_widgets and obtain their indexes and use their indexes to scroll their respective text boxes? Similar code #Initializing an array at the top of your code: widgets = [] #Next, add each text widget to the array: for i in range(10): text1 = tk.Text(...) widgets.append(text1) #Next, define a function that calls the see method on all of the widgets: def autoscroll(pos): for widget in widgets: widget.see(pos) #Finally, adjust your binding to call this new method: pos_start = text1.search(anyword, '1.0', "end") text1.tag_bind(tag, '&lt;Button-1&gt;', lambda e, index=pos_start: autoscroll(index))
has comment: http://stackoverflow.com/comment/89782851
answer count: 1
has comment: http://stackoverflow.com/comment/89808917
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: Tkinter search: Need to search for every text widget
tagged with: tkinter
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/comment/89807354
comment on: http://stackoverflow.com/q/51397717
type: Comment
has text: Isn't this a duplicate of your own question? https://stackoverflow.com/questions/51393049/convert-county-state-names-to-coordinates If so, consider deleting this one and editing the first one instead.
type: QuestionComment
score: 1

http://stackoverflow.com/comment/89860780
type: QuestionComment
has text: The question is how to put the pyFMU output in the form suitable for optuimization
comment on: http://stackoverflow.com/q/51444291
score: 0
type: Comment

http://stackoverflow.com/q/51401118
tagged with: python
has comment: http://stackoverflow.com/comment/89785517
answer count: 0
has body: Given the set of matrix,supposedly the transpose of conjugate IV will obtain the UB: IV_transpose*UB(IV)=UB However, I get the different output. Please see the code; angle=60 UB = np.array([ [1,0,0,0], [0,math.cos(4*math.radians(angle)),math.sin(4*math.radians(angle)),0], [0, math.sin(4 * math.radians(angle)), -math.cos(4 *math.radians(angle)),0],[0,0,0,-1]]) IV = [[1.0],[1.0],[0.0],[0.0]] IVT=np.conj(IV).T UBIV=np.matmul(UB,IV) output=np.matmul(IVT,UBIV) print (output) print (UB) This is my output: IV_transpose*UB(IV)=[[ 0.5]] UB= [[ 1. 0. 0. 0. ] [ 0. -0.5 -0.8660254 0. ] [ 0. -0.8660254 0.5 0. ] [ 0. 0. 0. -1. ]] My question is why IV_transpose*UB(IV)!=UB. How to make it equal? Thank you.
upvote count: 1
downvote count: 1
type: Question
has title: How to write unitary transformation of matrix in Python
tagged with: numpy
tagged with: transformation
score: 0
tagged with: matrix
has comment: http://stackoverflow.com/comment/89797775
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/51466170
upvote count: 1
has body: Can also use np.isin df1[np.isin(df1.Name1, df.Name) &amp; np.isin(df1.Name2, df.Name)]
downvote count: 0
answers question: http://stackoverflow.com/q/51466042
type: Answer
score: 1

http://stackoverflow.com/a/51327452
downvote count: 0
has comment: http://stackoverflow.com/comment/89630533
has body: You may use the following regular expression: (https?.*?\.com\/)(\s+[\w-]*\s+)(https?.*?\.com\/[\w\.]+) (https?.*?\.com\/) First capture group. Capture http or https, anything up to .com and forward slash /. (\s+[\w-]*\s+) Second capture group. Capture whitespace, alphanumerical characters and hypens, and whitespace. You can add more characters to the character set if needed. (https?.*?\.com\/[\w\.]+) Third capture group. Capture http or https, anything up to .com, forward slash /, alphanumerical characters and full stop . for the extension. Again you can add more characters to the character set in this capture group if you are expecting other characters. You can test the regex live here. Alternatively, if you are expecting variable urls and domains you may use: (\w*\:.*?\.\w*\/)(\s+[\w-]*\s+)(\w*\:?.*?\.\w*\/[\w\.]+) Where first and third capture groups now do match any alphanumerical characters followed by colon :, and anything up to a ., alphanumerical characters \w and forward slash. You can test this here. You may replace captured groups with: \1\2 Where \1, \2, and \3 are backreferences to captured groups one, two and three respectively. Python snippet: >>import re >>str = "La-la-la https://example.com/ la-la-la https://example.com/example.PNG" >>out = re.sub(r'(https?.*?\.com\/)(\s+[\w-]*\s+)(https?.*?\.com\/[\w\.]+)', r'\1\2 ', str) >>print(out) La-la-la https://example.com/ la-la-la
score: 1
answers question: http://stackoverflow.com/q/51327209
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/89630662

http://stackoverflow.com/comment/89688311
score: 0
has text: Brings up "AttributeError: 'NoneType' object has no attribute 'a'" when this happens. I realized I didn't need the count variable but I seemed to have it working in a better state with it.
type: Comment
comment on: http://stackoverflow.com/a/51354846
type: AnswerComment

http://stackoverflow.com/a/51427885
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51427313
upvote count: 2
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/51427313
has body: For web servers, you probably don't want something that runs in-process: An in-process scheduler for periodic jobs [...] https://github.com/Tivix/django-cron has proven a working solution. There's also the heavyweight champion Celery and Celerybeat.

http://stackoverflow.com/a/51376890
has body: You should check if quotechar is enabled and set in your export. https://doc.scrapy.org/en/latest/topics/spiders.html?highlight=CSV_DELIMITER#csvfeedspider-example Usually text should be enquoted with " so it's no issue that the delimiter is in the text.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/51376353

http://stackoverflow.com/comment/89878974
type: QuestionComment
comment on: http://stackoverflow.com/q/51453792
has text: FYI I am not using two monitors, just 2 desktops in windows 10.
score: 0
type: Comment

http://stackoverflow.com/comment/89792330
type: Comment
type: QuestionComment
has text: "When my python interpreter path in .py is changed to i.e #!/usr/bin it works well." I doubt it.... please review those comments, add "python" and see what happens
score: 0
comment on: http://stackoverflow.com/q/51410089

http://stackoverflow.com/q/51393471
tagged with: cplex
has comment: http://stackoverflow.com/comment/89781045
has body: Statement cplexProblem.solution.basis.get_row_basis() gives the following error TypeError: 'NoneType' object is not subscriptable Checked the code a bit and in _procedural.py , there seems to be a bug in the getbase_r . Please check the last line return LAU.array_to_list(cstat, numrows) , should it not be return LAU.array_to_list(rstat, numrows) _procedural.py def getbase_c(env, lp): numcols = CR.CPXXgetnumcols(env, lp) cstat = _safeIntArray(numcols) rstat = LAU.int_list_to_array([]) status = CR.CPXXgetbase(env, lp, cstat, rstat) check_status(env, status) return LAU.array_to_list(cstat, numcols) def getbase_r(env, lp): numrows = CR.CPXXgetnumrows(env, lp) cstat = LAU.int_list_to_array([]) rstat = _safeIntArray(numrows) status = CR.CPXXgetbase(env, lp, cstat, rstat) check_status(env, status) return LAU.array_to_list(cstat, numrows) Has anyone seen this problem? Thanks.
answer count: 1
score: 0
has title: Cplex Python Error Getting Error in Basis Row Status
tagged with: python
tagged with: linear-programming
has answer: http://stackoverflow.com/a/51405268
type: UnansweredQuestion
type: Question

http://stackoverflow.com/comment/89771545
comment on: http://stackoverflow.com/q/51400404
has text: @WiktorStribiżew What do you mean, actual string? I didn't alter the string after saving the link. The actual string is on the link I posted.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89810591
has text: Thank you so much! Such a simple solution, don't know why I didn't do this sooner!
type: AnswerComment
comment on: http://stackoverflow.com/a/51419686
score: 0
type: Comment

http://stackoverflow.com/q/51472097
answer count: 1
tagged with: scikit-learn
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/51472142
has title: zip argument #1 must support iteration on class object list
type: AnsweredQuestion
downvote count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/89912391
type: Question
has comment: http://stackoverflow.com/comment/89912339
has comment: http://stackoverflow.com/comment/89912363
has body: I have a point class in python (Python36-32) class point: def __init__(self , xPoint ,yPoint): self.x = xPoint self.y = yPoint def makeMeStr(self): return "("+str(self.x)+","+str(self.y)+")" def __repr__(self): return self.makeMeStr() def __str__(self): return self.makeMeStr() when i create a list of these points and when I do left, right = zip(*myListOfPoint) i get TypeError: zip argument #1 must support iteration Any suggestion please
score: -2
has comment: http://stackoverflow.com/comment/89912373
has answer: http://stackoverflow.com/a/51472142
has comment: http://stackoverflow.com/comment/89912638
has comment: http://stackoverflow.com/comment/89912408

http://stackoverflow.com/a/51356357
answers question: http://stackoverflow.com/q/51355762
downvote count: 0
has comment: http://stackoverflow.com/comment/89689460
type: Answer
has comment: http://stackoverflow.com/comment/89689439
upvote count: 1
score: 1
has body: QAction has a method setCheckable to enable the behaviour you want. The method setChecked can be used to toggle the check state. You can set the QIcon of a QAction when adding it to a QMenu using addAction. You can then change the QIcon using the setIcon method of the QAction. Note that this is not exactly the same as what the Windows menu does in the screenshot. But it it a usable way to achieve the same result.

http://stackoverflow.com/comment/89786145
score: 0
has text: @rahlf23 I printed out table and it is empty, but on the site there are 6 rows in the table.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51407233

http://stackoverflow.com/q/51426766
has title: an error in python plot
accepted answer: http://stackoverflow.com/a/51426870
tagged with: python
possible better answer: http://stackoverflow.com/a/51427023
has answer: http://stackoverflow.com/a/51427023
has body: import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn.linear_model import LinearRegression a = np.zeros((1000,3)) fig=plt.figure() ax=fig.gca(projection='3d') line1,=ax.plot(a[:,0], a[:,1], a[:,2], 'k') ax.set_xlabel('$x_1_t$');ax.set_ylabel('$x_1_t-tau$');ax.set_zlabel('$x_1_t-2tau$') plt.title('hello') plt.show() I use python2.x. The error message is the following. Anyone knows how to fix it? Traceback (most recent call last): File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/backends/backend_macosx.py", line 83, in _draw self.figure.draw(renderer) File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/artist.py", line 55, in draw_wrapper return draw(artist, renderer, *args, **kwargs) File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/figure.py", line 1475, in draw renderer, self, artists, self.suppressComposite) File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/image.py", line 141, in _draw_list_compositing_images a.draw(renderer) File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mpl_toolkits/mplot3d/axes3d.py", line 298, in draw ax.draw(renderer) File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mpl_toolkits/mplot3d/axis3d.py", line 306, in draw self.label.draw(renderer) File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/artist.py", line 55, in draw_wrapper return draw(artist, renderer, *args, **kwargs) File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/text.py", line 706, in draw bbox, info, descent = textob…
type: AnsweredQuestion
tagged with: matplotlib
tagged with: figure
type: Question
upvote count: 4
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51426870
score: 4
favorite count: 0

http://stackoverflow.com/q/51429288
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51449939
favorite count: 0
has title: save subplots after .imshow()
has answer: http://stackoverflow.com/a/51449939
tagged with: python
tagged with: savefig
has body: Here are my visualization codes: f, ax = plt.subplots(1, 2) for i, img in enumerate([img1, img2]): grads = # my visualization codes # visualize grads as heatmap ax[i].imshow(grads, cmap='jet') How could I save whatever was shown using imshow here? Any advice is greatly appreciated!
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/89869016
upvote count: 3
tagged with: matplotlib
linked to: http://stackoverflow.com/q/10041627
has comment: http://stackoverflow.com/comment/89869619
type: Question
tagged with: subplot
tagged with: visualization

http://stackoverflow.com/comment/89841569
has text: I thought the linked docs would be detailed enough. If not there are many other sources on the internet.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51435684

http://stackoverflow.com/q/51436711
has comment: http://stackoverflow.com/comment/89844479
favorite count: 0
has comment: http://stackoverflow.com/comment/89843545
tagged with: pandas
tagged with: python
has title: Extracting JSON in pandas column to separate columns while handling rows with None
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89844402
has comment: http://stackoverflow.com/comment/89844577
has answer: http://stackoverflow.com/a/51436955
upvote count: 1
type: Question
type: AnsweredQuestion
has body: I have a pandas dataframe called df that contains twitter tweets created by taking the twitter json and loading it into the dataframe. I am trying to extract the interesting information. The coordinates column is mostly None, but sometimes it contains GeoJSON in this format: {'coordinates': [21.425775, 8.906141], 'type': 'Point'} Here 21.425775 refers to the longitude and 8.906141 refers to the latitude. I would like to extract the latitude and longitude into separate columns. Unfortunately my pandas skills are more towards the beginner level, so I am not sure how to do find and substring; also there seems to be better ways as suggested in this question which I don't fully understand. An example of the dataframe is: coordinates 0 None 1 {'coordinates': [21.425775, 8.906141], 'type': 'Point'} How can I extract the information in the nested JSON column into separate pandas columns while gracefully handling the None values in the other rows?
score: 1
tagged with: http://stackoverflow.com/tag/json
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/51436955
linked to: http://stackoverflow.com/q/47113449
answer count: 1
downvote count: 0

http://stackoverflow.com/a/51337845
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51336897
downvote count: 0
has body: So after reading plenty of posts and solutions, I decided to just reduce my file size by getting rid of useless data. Maybe you will find this useful. By the way, I read somewhere that you need at least 25x more memory than your JSON file has, so in my case, I needed more than 8GB. with open('data.json', 'r') as data_file: data = json.load(data_file) print(data.keys()) del data['author'] with open('datav2.json', 'w') as data_file: data = json.dump(data, data_file)
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51336897

http://stackoverflow.com/q/51352094
favorite count: 0
answer count: 5
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
tagged with: list
has answer: http://stackoverflow.com/a/51352597
has answer: http://stackoverflow.com/a/51352279
has comment: http://stackoverflow.com/comment/89676928
type: Question
has answer: http://stackoverflow.com/a/51352241
has title: How to update dictionary and its list contents?
score: 1
has answer: http://stackoverflow.com/a/51352174
has body: I've created two dictionaries that I wish to combine like this: dict1 = {'temp1':[1,2,3,4]} dict2 = {'temp1': [3,4,5],'temp2':[15,16,17]} dict1.update(dict2) I was hoping to get this: dict1 = {'temp1': [1, 2, 3, 4, 5], 'temp2': [15, 16, 17]} But instead I get this: dict1 = {'temp1': [3, 4, 5], 'temp2': [15, 16, 17]} How do I update and filter out duplicates in the lists in the dictionary?
has comment: http://stackoverflow.com/comment/89676771
upvote count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51352141

cryptography
tags question: http://stackoverflow.com/q/51336785
tag name: cryptography
type: Tag
tags question: http://stackoverflow.com/q/51446016
tags question: http://stackoverflow.com/q/51456397

http://stackoverflow.com/a/51370134
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89713276
type: Answer
has body: Regarding your code, you are trying to do the same thing twice. You are using open to open and read the file and also np.loadtxt to read it. The error is from the np.loadtxt. For np.loadtxt you need to supply the file types if they aren't all the same: There is an example in the docs: np.loadtxt(d, dtype={'names': ('gender', 'age', 'weight'), 'formats': ('S1', 'i4', 'f4')}) For yours, it'd look like data = np.loadtxt('text.txt', dtype={ 'names' : ('color', 'a', 'b', 'c', 'd'), 'formats' : ('U50', 'f', 'f','f', 'f') }) And then you can use https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html to locate your string. You can store everything in one file. You just need to read in the file in the correct manner. Doing it the other way with open would look like: with open('text.txt') as f: for line in f: my_arr = line.split() my_str = my_arr.pop(0) # Create a list of all the items and then pop the string off the list my_arr = list(map(float, my_arr)) if my_str == "blue1": print(my_arr, type(my_arr[0])) The floats are now in a list so we can print all of them and show that their type is float Output: ([0.0, 1.0, 2.0, 3.0], &lt;type 'float'&gt;)
answers question: http://stackoverflow.com/q/51369853
accepted answer of: http://stackoverflow.com/q/51369853
has comment: http://stackoverflow.com/comment/89713550
score: 0

http://stackoverflow.com/q/51370082
answer count: 1
has title: NameError: name '' is not defined - Passing function return as input to another function
score: -1
has answer: http://stackoverflow.com/a/51370189
tagged with: nameerror
has body: I am trying to figure out how to pass the results of a Function to the other function in the same script. I have tested the CreateDict function and it works. I am unable to use the results as the input for CreateHumanUsrNameDict The Error I receive with the below is CreateHumanUsrNameDict(UsrDict) NameError: name 'UsrDict' is not defined import csv def CreateDict(filename): UsrDict = {} with open(filename) as csvfile: readCSV = csv.reader(csvfile, delimiter=':') for row in readCSV: UsrDict[row[0]]=row[1] return UsrDict def CreateHumanUsrNameDict(UsrDict): HumanUsrDict={} for k, v in HumanUsrDict.items(): if v == len(4): HumanUsrDict[k:v] print(HumanUsrDict) if __name__=='__main__': CreateDict('Book1.csv') CreateHumanUsrNameDict(UsrDict)
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89712462
tagged with: python
tagged with: parameter-passing
accepted answer: http://stackoverflow.com/a/51370189
has comment: http://stackoverflow.com/comment/89712590
downvote count: 1
type: AnsweredQuestion
type: Question
tagged with: function
upvote count: 0

user-interface
tags question: http://stackoverflow.com/q/51481114
tags question: http://stackoverflow.com/q/51343002
tags question: http://stackoverflow.com/q/51389968
tags question: http://stackoverflow.com/q/51469559
tags question: http://stackoverflow.com/q/51430427
type: Tag
tags question: http://stackoverflow.com/q/51425354
tags question: http://stackoverflow.com/q/51364849
tags question: http://stackoverflow.com/q/51393587
tags question: http://stackoverflow.com/q/51419201
tags question: http://stackoverflow.com/q/51447614
tags question: http://stackoverflow.com/q/51369080
tags question: http://stackoverflow.com/q/51346955
tags question: http://stackoverflow.com/q/51350812
tags question: http://stackoverflow.com/q/51329877
tags question: http://stackoverflow.com/q/51449293
tag name: user-interface
tags question: http://stackoverflow.com/q/51343713
tags question: http://stackoverflow.com/q/51476517
tags question: http://stackoverflow.com/q/51389835
tags question: http://stackoverflow.com/q/51461696

http://stackoverflow.com/comment/89841256
has text: try removing these packages, and see if it works then. I doubt that other conda packages caused the problem, but it might still be worth a shot.
comment on: http://stackoverflow.com/q/51435579
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89677163
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51352328
has text: on exception, the `try` never completes so `port` is never set. Then when you do get a valid value, it exists within the context of your recursive function call, which is a different scope
type: Comment

http://stackoverflow.com/a/51363268
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51363196
has comment: http://stackoverflow.com/comment/89699206
answers question: http://stackoverflow.com/q/51363196
type: Answer
has body: You need to combine all the elements you want included in the row into a single list: import csv with open('test.csv', 'w') as file: output = csv.writer(file) out = ['Date'] for i in range(0,len(c)): out.append(lst[i]) output.writerow(out)

http://stackoverflow.com/comment/89813493
type: Comment
score: 1
has text: Also `filter(lambda word: len(word) == length, sentence.split())`
type: AnswerComment
comment on: http://stackoverflow.com/a/51420851

http://stackoverflow.com/q/51391847
tagged with: python
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89763986
has title: How to set queue limit for response object of multiprocessing pool
type: Question
score: 0
has comment: http://stackoverflow.com/comment/89761848
has body: z() is a really fast generator, faster than do() can process them. is there a way to queue the 'results' object? what attributes of this object? this is what I did, i setup a queue internally to queue the 'results', is there a better way??? from multiprocessing.dummy import Pool as ThreadPool import Queue,time,random from datetime import datetime class rob: def __init__(self,maxq): self.count = 0 self.q = Queue.Queue(maxq) self.maxq = maxq def add(self,x=1): self.count += x def z(self): while True: #s = random.choice(range(1,6)) #time.sleep(.1) t = datetime.now().strftime("%I:%M:%S.%f") self.add() t = t+'---'+str(self.count) #print 'z:',t if self.q.full(): print 'waiting' self.q.put(t) yield t def do(self,t): secs = random.choice(range(1,10)) #could take max of 10 seconds per do() time.sleep(secs) d = self.q.get() return t #print e.message, e.args #patch_send() mt = 100 b = rob(mt*3) pool = ThreadPool(mt) #because u can results = pool.imap_unordered( b.do, b.z() ) #pool.close() for r in results: print r
has comment: http://stackoverflow.com/comment/89764123

jinja2
tags question: http://stackoverflow.com/q/51383352
tags question: http://stackoverflow.com/q/51351469
tags question: http://stackoverflow.com/q/51404129
tags question: http://stackoverflow.com/q/51348028
tags question: http://stackoverflow.com/q/51454964
tags question: http://stackoverflow.com/q/51404188
tags question: http://stackoverflow.com/q/51468834
tags question: http://stackoverflow.com/q/51359325
type: Tag
tags question: http://stackoverflow.com/q/51353549
tags question: http://stackoverflow.com/q/51332848
tags question: http://stackoverflow.com/q/51375866
tags question: http://stackoverflow.com/q/51435649
tags question: http://stackoverflow.com/q/51441100
tag name: jinja2
tags question: http://stackoverflow.com/q/51351359

http://stackoverflow.com/comment/89748780
type: QuestionComment
comment on: http://stackoverflow.com/q/51387969
has text: But i used pip install in the conda shell and it says it installed, but when I went into the Anaconda Navigator, it still has not updated to the newer version.
score: 0
type: Comment

http://stackoverflow.com/comment/89978899
type: AnswerComment
type: Comment
has text: @scharette Thanks for sharing. I would be hesitant to draw any conclusions from a test with only 20 lines in a file, but I agree it's probably true that there's not a huge difference.
score: 1
comment on: http://stackoverflow.com/a/51480083

http://stackoverflow.com/a/51395419
has comment: http://stackoverflow.com/comment/89762287
upvote count: 1
has comment: http://stackoverflow.com/comment/89762441
has body: The easiest way would probably just be this: print("{0:b}".format(width)) However, if you want to code the conversion yourself and store the bytes in an array, you could do it like that: import PIL import numpy as np from PIL import Image im = Image.open('youngerlrf005.jpg') a1 = [] width, height = im.size while width &gt; 0: a1.append(width &amp; 1) width = width &gt;&gt; 1 a1.reverse() print(a1) Just keep in mind, that the variable width will equal to zero after you do that, so if you need the width anywhere else, you'd have to redefine it width = im.size[0]
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51394993
accepted answer of: http://stackoverflow.com/q/51394993
type: Answer
has comment: http://stackoverflow.com/comment/89762232
score: 1

http://stackoverflow.com/comment/89879080
type: Comment
has text: that's what `count` is. it matches your expected output, which you have labeled as `num_prescriber`. is there some other variable you need?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51452332

http://stackoverflow.com/a/51335015
downvote count: 0
has body: The b_gradient and m_gradient are the partial derivatives of the cost/error function with respect to b/m. That's why there is a -2/N as 1/N is part of the cost/error function, and it is multiplied by 2 after computing the derivative. If you don't know calculus, you will just have to take that in for now. If you do, then it is pretty easy to derive.
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51334970
upvote count: 2
has comment: http://stackoverflow.com/comment/89645284
has comment: http://stackoverflow.com/comment/89645244

http://stackoverflow.com/q/51399274
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89780111
has title: More efficient method to save 10 frames per second from a video between given timecode - Python
has answer: http://stackoverflow.com/a/51405917
has body: Ive got a set of videos, and a CSV file that with heading(start, end, category, season, episode) with the task to save 10 images per second between the start and end points in each row of the file. The method I devised (see below) first reads the CSV file and creates a list of integers (every 100 ms between the start and end points). Then using cv2 I load the video, go to the frame given in the list and progressively save each one. My question in wether there is a quicker way to do this, whilst I havent done any speed tests or anything like that, the method just seems a bit slow and clunky. Any help appreciated. import csv import cv2 def readCSV(): times = [] reader = csv.DictReader(open("timecode.csv")) for i in reader: l = range( ((int(str(i["start"])[0:2]))*60000) + ((int(str(i["start"])[2:4]))*1000), ((int(str(i["end"])[0:2]))*60000) + ((int(str(i["end"])[2:4]))*1000) ) for j in l[::100]: times.append([i["season"], i["episode"], j, i["interaction"]]) return times def vid_to_frame(season, episode, timecode, category): vid = cv2.VideoCapture("s{}_e{}.mp4".format(str(season).zfill(2), str(episode).zfill(2))) vid.set(cv2.CAP_PROP_POS_MSEC, float(timecode)) success, image = vid.read() if success: cv2.imwrite("E:/Hammond/readingVideos/imageSamples/{}/{}.jpg" .format(str(category), str(timecode)), image) for n in readCSV(): vid_to_frame(n[0], n[1], n[2], n[3])
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/89776352
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89771506

http://stackoverflow.com/comment/89905674
type: Comment
comment on: http://stackoverflow.com/q/51468533
type: QuestionComment
has text: Check your `sys.path`. In one of the listed directories you should find your module.
score: 0

http://stackoverflow.com/comment/89807422
comment on: http://stackoverflow.com/q/51393049
type: QuestionComment
has text: This looks like a duplicate of https://stackoverflow.com/questions/38031705/http-error-429-too-many-requests-by-python-geopy
type: Comment
score: 0

http://stackoverflow.com/q/51399538
score: 1
tagged with: rasa-nlu
has body: I am trying to use RASA to build a chatbot but I have an issue with the installation of RASA_NLU Here is the line I entered pip install rasa_nlu[spacy] Segmentation fault (core dumped)
type: Question
downvote count: 0
tagged with: segmentation-fault
tagged with: ubuntu
has title: segmentation fault while installing rasa_nlu
answer count: 3
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/58054079
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/53405292
has answer: http://stackoverflow.com/a/51454969

http://stackoverflow.com/comment/89872905
type: QuestionComment
has text: Ah, you need to specify the path to the FireFox binary. Check this out: https://stackoverflow.com/questions/25713824/setting-path-to-firefox-binary-on-windows-with-selenium-webdriver
score: 1
comment on: http://stackoverflow.com/q/51451268
type: Comment

http://stackoverflow.com/q/51466828
type: UnansweredQuestion
type: Question
tagged with: pyaudio
score: 0
answer count: 1
has body: Actually I am recording every sound with the microphone, and I would like to filter the input in order to remove the system sound output, to understand clearly the user's voice when music is playing for example (like what Skype does). I am looking for a Python module which allows to do that in Ubuntu 16.04, or at least something which record the system output. Here's my script (I am using Pyaudio) : THRESHOLD = 1500 CHUNK_SIZE = 1024 FORMAT = pyaudio.paInt16 RATE = 44100 MAX_RECORDING_TIME = 7 # seconds MAX_SILENCE_UNITS = 65 def is_silent(snd_data): "Returns 'True' if below the 'silent' threshold" return max(snd_data) &lt; THRESHOLD def normalize(snd_data): "Average the volume out" MAXIMUM = 16384 times = float(MAXIMUM)/max(abs(i) for i in snd_data) r = array('h') for i in snd_data: r.append(int(i*times)) return r def record(): """ Record a word or words from the microphone and return the data as an array of signed shorts. Normalizes the audio. the recording stops after 7 seconds or a sequence of 65 silent recording units """ p = pyaudio.PyAudio() stream = p.open(format=FORMAT, channels=1, rate=RATE, input=True, output=False, frames_per_buffer=CHUNK_SIZE) num_silent = 0 snd_started = False r = array('h') begin_time = 0 while 1: # little endian, signed short snd_data = array('h', stream.read(CHUNK_SIZE)) if byteorder == 'big': snd_data.byteswap() if (snd_started): r.extend(snd_data) silent = is_silent(snd_data) if silent and snd_started: # we compute the number of silent units num_silent += 1 elif not silent and not snd_started: print("start recording !") snd_started = True begin_time = time.time() # we save the current time if not silent: num_silent = 0 now = int(time.time()) if snd_started and (now-begin_time&gt;MAX_RECORDING_TIME or num_silent &gt; MAX_SILENCE_UNITS): break print("recording finished !") sample_width = p.get_sample_size(FORMAT) stream.stop_stream() stream.close() p.terminate() r = normalize(r) return sample_width, r def record_to_file(path): "Reco…
has answer: http://stackoverflow.com/a/51473251
tagged with: microphone
tagged with: python
tagged with: audio-recording
tagged with: audio
has title: Remove the system sound output when recording with microphone in Python

http://stackoverflow.com/comment/89700455
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51364047
score: 5
has text: `df.apply(pd.to_numeric, errors='ignore')` ?

http://stackoverflow.com/comment/89675627
type: Comment
type: QuestionComment
has text: you want to predict `e and f ` at the same time e.g. new sample N has `e,f` = [0,1] or independently ??
score: 0
comment on: http://stackoverflow.com/q/51350585

http://stackoverflow.com/comment/89851160
has text: Oh ok thank you so much for answering I really appreciate it. I just wanted to say great work on the module really love it and ask one last question. Again apologies if this is a silly question since I'm new to alot of this but would it work with a proxy or no? Like can I use it on my computer to show the proxy what to click and what not to click or are proxies "headless" setups?
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51411719

http://stackoverflow.com/a/51452801
has body: You have to provide path of directory, which contains geckodriver.exe driver=webdriver.Firefox(executable_path="/home/user1/public_html/gecko")
answers question: http://stackoverflow.com/q/51451940
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/89876235
score: 1
has comment: http://stackoverflow.com/comment/89876535
upvote count: 1

http://stackoverflow.com/q/51385553
tagged with: module
has body: So here's the overall code one can run on his computer main.py from kivy.app import App from kivy.uix.floatlayout import FloatLayout class SnakeGame(FloatLayout): pass class SnakeGameApp(App): def build(self): return SnakeGame() if __name__ == '__main__': SnakeGameApp().run() snakegame.kv #: include snake.kv &lt;SnakeGame&gt;: Snake: pos: 300, 300 snake.py # Control object for the Snake view object in snake.kv class Snake(Widget): def move(self): print("Moving") snake.kv #: import Widget kivy.uix.widget.Widget &lt;Snake@Widget&gt;: size_hint: None, None size: 15, 15 canvas: Color: rgba: 1, 0, 0, 1 Rectangle: pos: self.pos size: self.size on_touch_down: self.move() # There is an error here: Snake object has # no attribute move. # How can i connect to the snake.py # file here the same it was automatically # connecting the SnakeGame class in the main.py # file with the SnakeGame class in the snakegame.py file # ??? There is an error in the snake.kv file: Snake object has no attribute move. How can i connect to the snake.py file here the same it was automatically connecting the SnakeGame class in the main.py file with the SnakeGame class in the snakegame.py file ??? Thanks a lot. I've already made extensive googling but couldn't find anything that helps.
type: Question
has answer: http://stackoverflow.com/a/51386064
tagged with: class
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51385646
tagged with: communication
has title: How to connect an arbitrary python file to an arbitrary kivy file?
type: UnansweredQuestion
tagged with: python
tagged with: kivy

http://stackoverflow.com/q/51435800
tagged with: machine-learning
tagged with: kaggle
tagged with: python
type: AnsweredQuestion
tagged with: anaconda
type: Question
possible better answer: http://stackoverflow.com/a/51436006
has comment: http://stackoverflow.com/comment/89841793
has answer: http://stackoverflow.com/a/51436006
tagged with: scikit-learn
has body: I'm a beginner in Machine Learning and I'm learning through the Kaggle competitions. I've started off with the Titanic competition and now I'm trying to measure the accuracy of my prediction with the scikit-learn accuracy_score function but the output does not really make sense. Here is the output I am getting: [1. 0. 1. 0. 1. 0. 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 0. 1. 1. 0. 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 0. 1. 0. 1.] &lt;function accuracy_score at 0x000001AA46EFBD90&gt; And here is my code: *imports have been omitted to avoid crowding train_path = "C:\\Users\\Omar\\Downloads\\Titanic Data\\train.csv" train_data = pd.read_csv(train_path) train_data['Sex'] = pd.factorize(train_data.Sex)[0] columns_of_interest = ['Survived','Pclass', 'Sex', 'Age'] filtered_titanic_data = train_data.dropna(axis=0) x = filtered_titanic_data[columns_of_interest] y = filtered_titanic_data.Survived train_x, val_x, train_y, val_y = train_test_split(x, y, random_state=0) titanic_model = DecisionTreeRegressor() titanic_model.fit(train_x, train_y) val_predictions = titanic_model.predict(val_x) accuracy_score(val_y, val_predictions) print(val_predictions) print(accuracy_score)
accepted answer: http://stackoverflow.com/a/51435837
score: 0
answer count: 2
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89874018
has answer: http://stackoverflow.com/a/51435837
has comment: http://stackoverflow.com/comment/89858818
favorite count: 0
has title: Scikit-Learn accuracy score does not show accuracy
has comment: http://stackoverflow.com/comment/89874873

http://stackoverflow.com/q/51466996
tagged with: python
has title: Simplify nested Python code
type: AnsweredQuestion
score: 1
type: Question
has answer: http://stackoverflow.com/a/51467032
accepted answer: http://stackoverflow.com/a/51467032
upvote count: 1
answer count: 1
downvote count: 0
favorite count: 0
has body: I have written a small helper function which I use to check if a navigation item is active. The code works as I expected, but it looks a little bit nested. Does anyone know how to simplify it? def url_name_active(view_name, name, exact=True, exclude=None): exclude_names = exclude.split(',') if exclude else None if exclude: for exclude_name in exclude_names: if exclude_name in view_name: return None if exact and name == view_name or \ not exact and name in view_name: return 'active'

http://stackoverflow.com/q/51340697
has answer: http://stackoverflow.com/a/51340760
downvote count: 1
favorite count: 0
has body: I have the following code: inv = {'gold coin': 42, 'rope': 1} dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] for i in range(len(dragonLoot) ): inv[i] = dragonLoot[i] ` and when I add list to dictionary I get this in OUTPUT: {'gold coin': 42, 'rope': 1, 0: 'gold coin', 1: 'dagger', 2: 'gold coin',3: 'gold coin', 4:'ruby'} and I don't know how to compare this key in one key and value in one value .
has title: How order multtiples key and value in dictonary python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89654991
has answer: http://stackoverflow.com/a/51340758
tagged with: python
tagged with: list
score: 1
type: Question
has comment: http://stackoverflow.com/comment/89655024
answer count: 2
has comment: http://stackoverflow.com/comment/89655045
has comment: http://stackoverflow.com/comment/89655032
upvote count: 2

http://stackoverflow.com/q/51333232
possible better answer: http://stackoverflow.com/a/52924167
tagged with: python
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/52924167
has body: I'm trying to do cython debugging on NixOS. I can easily install cython in a nix-shell (chosen for simplicity of example), like this: $ nix-shell -p 'python27.withPackages( p: [ p.cython ])' $ cat /nix/store/s0w3phb2saixi0a9bzk8pjbczjaz8d7r-python-2.7.14-env/bin/python #! /nix/store/jgw8hxx7wzkyhb2dr9hwsd9h2caaasdc-bash-4.4-p12/bin/bash -e export PYTHONHOME="/nix/store/s0w3phb2saixi0a9bzk8pjbczjaz8d7r-python-2.7.14-env" export PYTHONNOUSERSITE="true" exec "/nix/store/i3bx1iw2d0i3vh9sa1nf92ynlrw324w8-python-2.7.14/bin/python" "${extraFlagsArray[@]}" "$@" Then we do a normal nix-shell of just python and see what version of python we get. [henry@bollum:~/Projects/eyeserver/nixshell]$ nix-shell -p 'python27' $ which python /nix/store/i3bx1iw2d0i3vh9sa1nf92ynlrw324w8-python-2.7.14/bin/python # ^^^^^^^ # non-debug All is well -- we get a non-debug python in both cases. And if we gdb it, we get (no debugging symbols found). See the last line. $ gdb /nix/store/i3bx1iw2d0i3vh9sa1nf92ynlrw324w8-python-2.7.14/bin/python GNU gdb (GDB) 8.0.1 Copyright (C) 2017 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later &lt;http://gnu.org/licenses/gpl.html&gt; This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "x86_64-unknown-linux-gnu". Type "show configuration" for configuration details. For bug reporting instructions, please see: &lt;http://www.gnu.org/software/gdb/bugs/&gt;. Find the GDB manual and other documentation resources online at: &lt;http://www.gnu.org/software/gdb/documentation/&gt;. For help, type "help". Type "apropos word" to search for commands related to "word"... Reading symbols from /nix/store/i3bx1iw2d0i3vh9sa1nf92ynlrw324w8-python-2.7.14/bin/python...(no debugging symbols found)...done. When we use enableDebugging, on python by itself, we get different results. $ nix-shell -p 'enableDebugging pyt…
tagged with: cython
type: Question
tagged with: gdb
score: 10
has title: Nixos: How do I get get a python with debug info included with packages?
accepted answer: http://stackoverflow.com/a/51429410
tagged with: nixos
answer count: 2
upvote count: 10
favorite count: 0
has answer: http://stackoverflow.com/a/51429410
tagged with: nix

http://stackoverflow.com/comment/89707461
has text: Glad that it's solved :) Still consider using a proper admin file if you want to things right and allow more columns to be display for your models.
comment on: http://stackoverflow.com/a/51367336
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51432335
has comment: http://stackoverflow.com/comment/89864103
upvote count: 10
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89865432
downvote count: 0
answers question: http://stackoverflow.com/q/51423507
has comment: http://stackoverflow.com/comment/89836842
has comment: http://stackoverflow.com/comment/89863514
has body: If you want to play with TLS handshake, enable TLS on scapy using load_layer("tls"). That enables the TLS module, which supports handshake (requires scapy >= 2.4.0). Scapy will then correctly dissect TLS handshake/key... packets You should first try load_layer("tls") packets = sniff(prn=lambda x:x.summary(), lfilter=lambda x: TLS in x) And if you're using Scapy 2.4.4+, for better consistency you can even use sniff([...], session=TLSSession) Have a look on how the packets are built: Example: There is also a quite fancy guide here: https://github.com/secdev/scapy/blob/master/doc/notebooks/tls/notebook2_tls_protected.ipynb So summarize: You will find each packet when using load_layer("tls"). Note that there are a lot of packets and that TLSCertificate will only appear once. msg is a list because many informations can be contained in a single TLS packet
has comment: http://stackoverflow.com/comment/89863016
type: Answer
accepted answer of: http://stackoverflow.com/q/51423507
has comment: http://stackoverflow.com/comment/89864086
has comment: http://stackoverflow.com/comment/89848130
score: 10
has comment: http://stackoverflow.com/comment/89879693

http://stackoverflow.com/a/55159160
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51470373
upvote count: 3
score: 3
has body: I had this same issue using the newest pandas version - downgrading to pandas 0.22.0 fixes the problem. pip install pandas==0.22.0

http://stackoverflow.com/q/51336103
has comment: http://stackoverflow.com/comment/89647748
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89647760
tagged with: python
has comment: http://stackoverflow.com/comment/89647607
answer count: 0
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/89648400
upvote count: 1
tagged with: python-requests
has comment: http://stackoverflow.com/comment/89647215
has title: Python requests.post code limits results to 200. How to adjust code to get all 1000+ results?
type: Question
has comment: http://stackoverflow.com/comment/89647188
has comment: http://stackoverflow.com/comment/89647966
has comment: http://stackoverflow.com/comment/89647820
has comment: http://stackoverflow.com/comment/89647714
downvote count: 0
has body: I can't seem to figure our where to adjust any data limit in the requests.post statement. But there appears to be a 200 results limit in the output. Not very comfortable writing advanced requests.post scripts and could use some help with this issue. import requests r = requests.post('https://cares.myflfamilies.com/PublicSearch/Search?dcfSearchBox=Orange in Counties') openFile = open('flData', 'wb') for chunk in r.iter_content(100000): openFile.write(chunk)
favorite count: 0

http://stackoverflow.com/comment/89742378
type: QuestionComment
comment on: http://stackoverflow.com/q/51385215
score: 0
has text: There is no word boundary between `)` and following space.
type: Comment

http://stackoverflow.com/q/51341717
tagged with: matplotlib
tagged with: scatter-plot
accepted answer: http://stackoverflow.com/a/67541332
favorite count: 0
has answer: http://stackoverflow.com/a/51345033
has title: xlabel and ylabel values are not sorted in matplotlib scatterplot
has body: I have done tedious amounts of searching on the internet and it seems that I have not been able to figure out how to ask the right question to get the answer for what I want to do. I am trying to create a scatterplot with P/E ratio on the y-axis and Dividend Yield on the x-axis. I put the data into a CSV file and then imported each column into Python as individual lists. Here is how my scatterplot turns out below. I am confused why the x- and y- axes are not sorted numerically. I think I have to turn the elements within the list into floats and then do some sort of sort before turning it into a scatterplot. The other option I can think of is being able to sort the values in the process of creating the scatterplot. Neither of these have worked out and I have reached a dead end. Any help or pointing in the right direction would be much appreciated as I can only describe my problem, but don't seem to be able to be asking the right questions in my search. import csv import matplotlib.pyplot as plt etf_data = csv.reader(open('xlv_xlu_combined_td.csv', 'r')) for i, row in etf_data.iterrows(): symbol.append(row[0]) index.append(row[1]) dividend.append(row[2]) pe.append(row[3]) symbol.pop(0) index.pop(0) dividend.pop(0) pe.pop(0) indexes = [i.split('%', 1)[0] for i in index] dividend_yield = [d.split('%', 1)[0] for d in dividend] pe_ratio = [p.split('X', 1)[0] for p in pe] x = dividend_yield[:5] y = pe_ratio[:5] plt.scatter(x, y, label='Healthcare P/E &amp; Dividend', alpha=0.5) plt.xlabel('Dividend yield') plt.ylabel('Pe ratio') plt.legend() plt.show() xlv_xlu_combined_td.csv symbol,index,dividend,pe JNJ,10.11%,2.81%,263.00X UNH,7.27%,1.40%,21.93X PFE,6.48%,3.62%,10.19X MRK,4.96%,3.06%,104.92X ABBV,4.43%,4.01%,23.86X AMGN,3.86%,2.72%,60.93X MDT,3.50%,2.27%,38.10X ABT,3.26%,1.78%,231.74X GILD,2.95%,2.93%,28.69X BMY,2.72%,2.81%,97.81X TMO,2.55%,0.32%,36.98X LLY,2.49%,2.53%,81.83X
tagged with: python
possible better answer: http://stackoverflow.com/a/51345033
answer count: 4
score: 4
type: AnsweredQuestion
downvote count: 3
has answer: http://stackoverflow.com/a/67541332
has answer: http://stackoverflow.com/a/51342206
upvote count: 7
type: Question
has answer: http://stackoverflow.com/a/61994173

http://stackoverflow.com/q/51467164
type: Question
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/89902937
has comment: http://stackoverflow.com/comment/89902889
answer count: 3
upvote count: 1
possible better answer: http://stackoverflow.com/a/51467227
has comment: http://stackoverflow.com/comment/89902849
has answer: http://stackoverflow.com/a/51467227
has answer: http://stackoverflow.com/a/51467256
has title: How to use position within the string to change each string in a Pandas Dataframe column
has answer: http://stackoverflow.com/a/51467322
has body: I'm trying to remove the 3rd and 4th letter in every string in a column of a DF. It's a different letter each time, so I don't know how to use regex to do it. For example, if my DF is: {A B C '32435' 3 5 '45243' 2 4} I'm trying to turn it into: {A B C '325' 3 2 '453' 2 4}
type: AnsweredQuestion
downvote count: 0
score: 1
linked to: http://stackoverflow.com/q/509211
favorite count: 0
accepted answer: http://stackoverflow.com/a/51467256

http://stackoverflow.com/comment/89877244
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51453619
has text: switching from anaconda to normal python has the same issue: `File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/bdb.py", line 49, in trace_dispatch`
type: QuestionComment

scheme
tag name: scheme
tags question: http://stackoverflow.com/q/51327758
type: Tag

http://stackoverflow.com/comment/89713577
has text: This method may not suit because it doesn't filter for words in `Name`, e.g. `problematic` would be caught.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51365143
type: AnswerComment

http://stackoverflow.com/a/51364026
upvote count: 1
score: 1
downvote count: 0
has body: it's extracting the content of a word file. import docx2txt text= docx2txt.process("file_name.docx")
type: Answer
answers question: http://stackoverflow.com/q/51363727

http://stackoverflow.com/comment/89710993
comment on: http://stackoverflow.com/a/51368953
type: Comment
has text: yes you can access a column `df['x[0'] ` or `df.x[0]`
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89898810
type: AnswerComment
comment on: http://stackoverflow.com/a/51452053
has text: Do you know if it's possible to define the same function with intervals in a symbolic way with sympy?
score: 0
type: Comment

http://stackoverflow.com/comment/130652435
score: 0
type: Comment
has text: maybe this will help https://github.com/madmaze/pytesseract/tree/master/pytesseract LINE 182
type: AnswerComment
comment on: http://stackoverflow.com/a/56223263

http://stackoverflow.com/comment/89738588
score: 1
comment on: http://stackoverflow.com/q/51383352
has text: Is the css written in `my_html_file.html` or in a separate `.css` file?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89787326
comment on: http://stackoverflow.com/q/51407143
score: 0
has text: Initializing date before id does not seem to work.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89866869
has text: What do you mean by "difference"? You are getting shape error. Do you still get the same error? It does not have to do with rescaling values. Sure, post your code and I'll take a look at it, but please clearly explain what the problem is.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51445034

http://stackoverflow.com/comment/89641399
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51332748
has text: @AzatIbrakov Ah, like `def certain_find(elem, tag)` which handles the typing stuff once? Feel free to post it as an answer, it sounds reasonable.
score: 0

http://stackoverflow.com/a/51428382
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51428323
downvote count: 0
has body: Try this: ls = ['1a', 'b3', '1.45','apples','oranges','mangoes'] [l for l in ls if l.isalpha()] Output: ['apples', 'oranges', 'mangoes']

http://stackoverflow.com/a/51346007
type: Answer
has comment: http://stackoverflow.com/comment/89665122
downvote count: 0
score: 7
has comment: http://stackoverflow.com/comment/89666390
has comment: http://stackoverflow.com/comment/89665085
has comment: http://stackoverflow.com/comment/89665219
has comment: http://stackoverflow.com/comment/89665107
has body: Your logic is fine. The problem is that 2 ** 1000 is too big for all the digits to fit into a float, so the number gets rounded when you do a = int(a/10). A Python float only has 53 bits of precision, you can read about it in the official tutorial article: Floating Point Arithmetic: Issues and Limitations, and on Wikipedia: Double-precision floating-point format. Also see Is floating point math broken?. This is 2 ** 1000 10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376 But print(format(2**1000 / 10, 'f')) gives us this: 1071508607186267380429101388171324322483904737701556012694158454746129413355810495130824665231870799934327252763807170417136096893411236061781867579266085792026680021578208129860941078404632071895251811587214122307926025420797364998626502669722909817741077261714977537247847201331018951634334519394304.000000 You can see that the digits start going wrong after 10715086071862673. So you need to use integer arithmetic, which in Python has arbitrary precision (only limited by how much memory Python can access). To do that, use the // floor division operator. a = 2**1000 total = 0 while a &gt;= 1: temp = a % 10 total = total + temp a = a // 10 print(total) output 1366 We can condense that code a little by using augmented assignment operators. a = 2**1000 total = 0 while a: total += a % 10 a //= 10 print(total) Here's a faster way. Convert a to a string then convert each digit back to int and sum them. I use bit shifting to compute a because it's faster than exponentiation. print(sum(int(u) for u in str(1 &lt;&lt; 1000)))
has comment: http://stackoverflow.com/comment/89665226
has comment: http://stackoverflow.com/comment/89665052
accepted answer of: http://stackoverflow.com/q/51345904
upvote count: 7
has comment: http://stackoverflow.com/comment/89665058
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89666268
has comment: http://stackoverflow.com/comment/89665149
answers question: http://stackoverflow.com/q/51345904
has comment: http://stackoverflow.com/comment/89665154
has comment: http://stackoverflow.com/comment/89665192

http://stackoverflow.com/comment/89774440
type: Comment
has text: @RyanGadsdon not sure where i should clarify the server, i had my code in answer
comment on: http://stackoverflow.com/q/51399227
score: 0
type: QuestionComment

http://stackoverflow.com/q/51397230
tagged with: fabric
tagged with: python
has body: This is the code I have so far and is giving me bugs. path = os.path.dirname(__file__) cmd =["js %s/pre_src/common/app/main.js" % path , "build", path] '''local(" ".join(cmd))''' run(path + "/pre_src/common/app/main.js -s", use_sudo=True) What is the difference between local and run? How do I run the main.js? Any help appreciated.
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51432374
answer count: 1
has title: Trying to generate an extension in fabfile. What am i doing wrong?
score: 0
has comment: http://stackoverflow.com/comment/89781073
tagged with: google-chrome-extension

http://stackoverflow.com/comment/89870489
score: 0
type: Comment
has text: Thanks Adrej, It is a new language for me and it works great, How can get it from a File? because a file will be an entry for my a code in python. Thanks again
comment on: http://stackoverflow.com/a/51447533
type: AnswerComment

http://stackoverflow.com/q/51326863
tagged with: datetime
upvote count: 2
tagged with: string-formatting
has body: I am trying to convert now.month to decimal so it would look like 01 and not like 1. The code is: import datetime now = datetime.datetime.now() monthstr = ".%m" % now.month it works in this line with %d daystr = "file_%d" % now.day the error I get is ValueError: unsupported format character 'm' (0x6d) at index 2 I also tried with the new type {:%m}. The error is the same. Do i miss any libraries? Or is there another way except adding 0 to months from Jan to September Python v.3.6.3
has answer: http://stackoverflow.com/a/51326904
tagged with: python
has answer: http://stackoverflow.com/a/51326939
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51326904
has title: unsupported format character 'm'
type: Question
answer count: 2
score: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/51326939
favorite count: 0
has comment: http://stackoverflow.com/comment/89628875

qgraphicsitem
tags question: http://stackoverflow.com/q/51392167
type: Tag
tag name: qgraphicsitem

http://stackoverflow.com/q/51411717
tagged with: excel
has answer: http://stackoverflow.com/a/51411875
tagged with: xlsxwriter
type: Question
has body: I'm able to transfer data from datafile.xlsx to test.xlsx, but I don't know how to add the color red to specific cells in test.xlsx #The major components of the code are shown below import pandas as pd import xlsxwriter file = "datafile.xlsx" xlsx = pd.ExcelFile(file) sheet1 = xlsx.parse(0) writer = pd.ExcelWriter("test.xlsx") columns=["FirstName", "MiddleName", "LastName", ......] #--My code doesn't work when a sheet_name is added in the to_excel piece-- dfc = pd.DataFrame([columns]) dfc.to_excel(writer,sheet_name=sheet1, startrow=0, startcol=0, index=False, header=None) #The body of the code retrieves data from datafile.xlsx #example--&gt; row = sheet1.iloc[i].real #---This section has my new code for adding cell color----- #---cell color code(I define a workbook and worksheet) workbook = writer.book worksheet = writer.sheets['sheet1'] cell_format = workbook.add_format() cell_format.set_font_color('red') worksheet.write(0, 0, 'Foo', cell_format) #----cell color code dt = [row[0], row[1], row[2], .....] df1 = pd.DataFrame([dt]) df1.to_excel(writer, startrow=rownum, startcol=0, index=False, header=None) writer.save()
tagged with: pandas
answer count: 1
tagged with: python
has title: unable to add formatting to excel sheet using pandas and xlsxwriter
type: UnansweredQuestion
score: 0

http://stackoverflow.com/comment/89774939
type: Comment
has text: Thanks for the follow-up. Note that you can accept your own answer by clicking the check mark icon.
comment on: http://stackoverflow.com/a/51399654
type: AnswerComment
score: 0

http://stackoverflow.com/q/51430876
has title: Passing input parameters to class attributes
possible better answer: http://stackoverflow.com/a/51431094
has answer: http://stackoverflow.com/a/51431094
has answer: http://stackoverflow.com/a/51431116
type: AnsweredQuestion
has body: I'm devloping a module that works with another module. The other module requires class attributes to be set before the __init__ method (let's work under the assumption that the behavior of this other module cannot be changed). These class attributes (Signal in the example below) are derived partially from an object that comes from my code. The method shown below is a disaster for many reasons. For example, my_obj1 and my_obj2 are not guaranteed to exist; the import in the other module will fail in this case. There could be a need to create 2 different instances of OtherModuleVodoo1 using 2 different instances from my code (my_obj). This is a skeleton of the code to explain: import Signal, Device from my_module.setup import my_obj1, my_obj2 class OtherModuleVodoo1(Device): # The class signal attributes must be defined before the __init__ # and rely upon an object from my module x = Signal(my_obj1.cmds['thing_x'], 'thing_x') y = Signal(my_obj1.cmds['thing_y'], 'thing_y') # ... # ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class OtherModuleVodoo2(Device): x = Signal(my_obj2, 'thing1') y = Signal(my_obj2, 'thing2') # ... # ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # now in my file I do this dev1 = OtherModuleVodoo1() dev2 = OtherModuleVodoo2() # but would much prefer to do this dev1 = OtherModuleVodoo(my_object_input = my_obj1) # where I don't need ```Vodoo1, Vodoo2``` but can have a generic solution. Question: Is there a way to "input" parameters to the construction of a class (not to the initialization of a class instance)? What I tried and why each did not work. Metaclasses. These feel close to the right approach but I wasn't able to get it to work. __new__ but this doesn't populate the namespace within the class definition (before the __init__) Setting my_obj1 = None until an OtherModuleVodoo1 instance is needed and then modifying the class attribute before instantiating an object: An example of attempt…
has comment: http://stackoverflow.com/comment/89832995
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/51431116
has comment: http://stackoverflow.com/comment/89832897
score: 0
tagged with: python

http://stackoverflow.com/a/51432578
has body: While python will give you ways to do this, you REALLY don't want to. Function/classes/etc should not expose their internals to the calling code, as that breaks abstraction and makes code fragile. Functions should take in arguments and return output values, but the internal algorithm and especially variable names shouldn't be exposed.
has comment: http://stackoverflow.com/comment/89836144
has comment: http://stackoverflow.com/comment/89836232
has comment: http://stackoverflow.com/comment/89836080
upvote count: 2
has comment: http://stackoverflow.com/comment/89836201
answers question: http://stackoverflow.com/q/51432553
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/89836509
downvote count: 0

http://stackoverflow.com/q/51415800
answer count: 1
has body: I want to write a customize program in libtmux, that takes input of session name, stop that session and restart it. def new_function(): import libtmux server = libtmux.Server() print server.list_sessions() session= input('Enter Session Name:') print (session) my_session = server.find_where({"session_name": session}) server.attach_session(target_session=my_session) if __name__ == '__main__': print '............' new_function() It prints the sessions in tmux and takes a input but crash right after it. After entering the session name , I want it to stop that session and restarts it.
type: UnansweredQuestion
tagged with: tmux
tagged with: python
tagged with: unix
tagged with: process
type: Question
has answer: http://stackoverflow.com/a/51418502
has title: function that takes a tmux session and restarts it
score: 0

http://stackoverflow.com/comment/89798320
type: AnswerComment
comment on: http://stackoverflow.com/a/51413344
has text: Thanks, this one works! However, is removing the other columns, is there any way of preserving the other cols and removing its duplicates as well?
type: Comment
score: 0

http://stackoverflow.com/q/51478413
type: UnansweredQuestion
tagged with: openpyxl
tagged with: python
score: 12
type: Question
answer count: 2
upvote count: 13
has body: This is my current code. As you can see that I'm fetching a value from every cell from each row by specifying the column index. for row_cells in sheet.iter_rows(min_row=1, max_row=10): object = {"key1": str(row_cells[1].value), "Key2": str(row_cells[3].value), "Key3": str(row_cells[4].value), "Key4": str(row_cells[2].value), "Key5": str(row_cells[5].value)} Now, in the given excel sheet, the first row always contains the titles of each column. Is there a way, where instead of specifying the indexes, I specify the names of the columns and then get a value in the cell. The .upper() method does give us the value of the uppermost cell of a column.
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/67600055
has title: select a column by its name - openpyxl
has answer: http://stackoverflow.com/a/51581162

apache
tag name: apache
tags question: http://stackoverflow.com/q/51407885
tags question: http://stackoverflow.com/q/51379448
tags question: http://stackoverflow.com/q/51365716
type: Tag
tags question: http://stackoverflow.com/q/51403219

http://stackoverflow.com/q/51461306
possible better answer: http://stackoverflow.com/a/51461369
type: AnsweredQuestion
score: 3
downvote count: 0
type: Question
has answer: http://stackoverflow.com/a/51461398
accepted answer: http://stackoverflow.com/a/51461398
has answer: http://stackoverflow.com/a/51461673
has comment: http://stackoverflow.com/comment/89892328
has answer: http://stackoverflow.com/a/51461369
upvote count: 3
answer count: 3
has comment: http://stackoverflow.com/comment/89891848
favorite count: 0
tagged with: python-3.x
has title: How to refactor my for loop as python dictionary comprehension?
has body: I am using Python 3.6. I wrote following code, it's a for loop: Edit: I made a mistake when I wrote var l down, so I re-type it here. Thanks for @Ender Look ！！ l = [['a','1'], ['a','2'], ['a','3']] d = {} for i in l: d[i[0]] = d.get(i[0], '') + '\t' + i[1] print (d) So, the result is what I want: {'a': '\t1\t2\t3'} Then I refactor above code as comprehension: dict2 = {} dict2 = {i[0]: dict2.get(i[0], '') + '\t' + i[1] for i in l} print(dict2) I though they should return same output. But the dict2 is: {'a': '\t3'} I want to know what's the matter with my dict comprehension? Thanks a lot!
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/89891880
has comment: http://stackoverflow.com/comment/89892380

http://stackoverflow.com/q/51397439
downvote count: 1
has title: Why does this error appear?
favorite count: 0
has comment: http://stackoverflow.com/comment/89765945
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89766014
type: Question
has answer: http://stackoverflow.com/a/51397507
has body: I suspect the static method tag is not detected or something. &gt;class Employee: &gt; @staticmethod &gt; def dayIsWorkday(day): &gt; if day.weekday() == 5 or day.weekday() == 6: &gt; return False &gt; return True &gt; &gt; &gt;import datetime &gt;my_date = datetime.date(2018, 12, 5) &gt; &gt;print(Employee.dayIsWorkday(my_date)) File "C:/Users/tronc/PycharmProjects/oop_TEST/main.py", line 26 def dayIsWorkday(day): ^ SyntaxError: invalid syntax Process finished with exit code 1 You may think that it's not useful, i think that too, but it's for a tutorial i'm trying to follow and i don't wanna go any further till i get what i done wrong
score: 0
has comment: http://stackoverflow.com/comment/89765978
answer count: 2
has answer: http://stackoverflow.com/a/51397518
upvote count: 1

http://stackoverflow.com/comment/89660660
type: QuestionComment
comment on: http://stackoverflow.com/q/51343639
type: Comment
score: 0
has text: Did you try runner my the code you said you would do in MATLAB but in Python?

http://stackoverflow.com/q/51353162
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/89678954
type: Question
accepted answer: http://stackoverflow.com/a/51353226
has body: I am trying to set up a variables file for my Python project. I have a function that works fine: def resize_window(self): size_object = QDesktopWidget().screenGeometry(-1) # active screen screen_width = size_object.width() screen_height = size_object.height() However, when I try to set it up in separate file to be called I get an error. AttributeError: type object 'ScreenSize' has no attribute 'screen_width' This is how my separate file looks: class ScreenSize(object): def __init__(self, screen_width, screen_height): self.screen_width = screen_width self.screen_height = screen_height self.resize_window() def resize_window(self): size_object = QDesktopWidget().screenGeometry(-1) # active screen screen_width = size_object.width() screen_height = size_object.height() The call: self.frame_top.setMinimumSize(QtCore.QSize(3/4* ScreenSize.screen_width, 1/10*ScreenSize.screen_height)) self.frame_top.setMaximumSize(QtCore.QSize(3/4*ScreenSize.screen_width, 1/10*ScreenSize.screen_height)) The error is: AttributeError: type object 'ScreenSize' has no attribute 'screen_width' If I setup class with just this: class ScreenSize(object): screen_width = 500 screen_height = 300 It works. So my problem is calling the function from within the class. Thanks in advance for any help.
score: -2
tagged with: class
has comment: http://stackoverflow.com/comment/89678900
answer count: 2
has comment: http://stackoverflow.com/comment/89678940
tagged with: function
upvote count: 0
possible better answer: http://stackoverflow.com/a/51354052
has answer: http://stackoverflow.com/a/51354052
has title: Getting variables from another python file. No attribute error
favorite count: 0
has answer: http://stackoverflow.com/a/51353226
tagged with: python
tagged with: attributes
type: AnsweredQuestion
downvote count: 2

http://stackoverflow.com/comment/110409818
comment on: http://stackoverflow.com/a/53187564
type: Comment
has text: I think they're just explaining the function usage.
score: 1
type: AnswerComment

http://stackoverflow.com/q/51393081
has body: Looking to combine two list variables containing string elements. For example, if I have the below : mystring1 = ['Luke', 'Han'] mystring2 = ['Skywalker', 'Solo'] I am looking to combine them to be : mystring3 = ['LukeSkywalker', 'HanSolo'] I am sure I am missing something simple. Any guidance would be great!
has title: Combining two string lists
upvote count: 1
has comment: http://stackoverflow.com/comment/90104740
score: 1
has comment: http://stackoverflow.com/comment/89757896
type: Question
has comment: http://stackoverflow.com/comment/89757907
linked to: http://stackoverflow.com/q/19560044
has answer: http://stackoverflow.com/a/51393112
downvote count: 0
tagged with: string
has answer: http://stackoverflow.com/a/51393170
favorite count: 0
duplicate of: http://stackoverflow.com/q/19560044
has answer: http://stackoverflow.com/a/51393110
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/51393207
has answer: http://stackoverflow.com/a/51393125
type: UnansweredQuestion

http://stackoverflow.com/q/51343262
answer count: 1
has title: Update the input of a loop with a result from the previous iteration of the loop
has comment: http://stackoverflow.com/comment/89660078
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89660007
has answer: http://stackoverflow.com/a/51343478
tagged with: google-analytics-firebase
type: Question
has comment: http://stackoverflow.com/comment/89660022
has body: (I've added the google-analytics api tags but I suspect that my issue is more a fundamental flaw in my approach to a loop, detailed below) I'm using Python to query the Google Analytics API (V4). Having already successfully connected to the API with my credentials, I'm trying to loop over each 10k result set returned by the API to get the full results set. When querying the API you pass a dict that looks something like this: {'reportRequests':[{'viewId': '1234567', # my actual view id goes here of course 'pageToken': 'go', # can be any string initially (I think?) 'pageSize': 10000, 'samplingLevel': 'LARGE', 'dateRanges': [{'startDate': '2018-06-01', 'endDate': '2018-07-13'}], 'dimensions': [{'name': 'ga:date'}, {'name': 'ga:dimension1'}, {'name': 'ga:dimension2'}, {'name': 'ga:userType'}, {'name': 'ga:landingpagePath'}, {'name': 'ga:deviceCategory'}], 'metrics': [{'expression': 'ga:sessions'}, {'expression': 'ga:bounces'}, {'expression': 'ga:goal1Completions'}]}]} According to the documentation on Google Analytics API V4 on the pageToken parameter: "A continuation token to get the next page of the results. Adding this to the request will return the rows after the pageToken. The pageToken should be the value returned in the nextPageToken parameter in the response to the reports.batchGet request. " My understanding is that I need to query the API in chunks of 10,000 (max query result size allowed) and that to do this I must pass the value of nextPageToken field returned in each query result into the new query. In researching, it sounds like the nextPageToken field will be a empty string when all the results have been returned. So, I tried a while loop. To get to the loop stage I built some functions: ## generates the dimensions in the right format to use in the query def generate_dims(dims): dims_ar = [] for i in dims: d = {'name': i} dims_ar.append(d) return(dims_ar) ## generates the metrics in the right format to use in the query def generate_metrics(mets): mets_ar …
tagged with: python
has comment: http://stackoverflow.com/comment/89660138
tagged with: google-analytics-api
score: 0
has comment: http://stackoverflow.com/comment/89660075
accepted answer: http://stackoverflow.com/a/51343478
has comment: http://stackoverflow.com/comment/89660097

http://stackoverflow.com/a/51353882
type: Answer
has comment: http://stackoverflow.com/comment/89680975
has comment: http://stackoverflow.com/comment/89716649
accepted answer of: http://stackoverflow.com/q/51353827
has comment: http://stackoverflow.com/comment/89716041
score: 0
has comment: http://stackoverflow.com/comment/89756984
type: AcceptedAnswer
has body: Try sudo pip install beautifulsoup4 or, preferably, use virtualenv. You should be able to do either of these without changing permissions on the above directories.
answers question: http://stackoverflow.com/q/51353827

http://stackoverflow.com/q/51363815
accepted answer: http://stackoverflow.com/a/51364981
upvote count: 1
tagged with: inline-styles
type: AnsweredQuestion
tagged with: matplotlib
type: Question
has title: python pyplot produce linestyle cycles with different dashes parameters
answer count: 1
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51364981
favorite count: 0
has body: I'm writing a class in order to produce plot figures that matches my several needs ! In particular I'm focusing on the cycles (colors and linestyle) about the linestyle every pyplot users knows that there is 4 linestyle ('-', '--', '-.', ':') but there is an option .. "dashes=L,ES" (Line, Empty space) with the purpose to create lines with different spaces between to track ... how can I manage this in a linestyle loop ?? Well I know the sintax of tuple... but where I have to use it ? here is the style that I have defined so far def linestyles(self, style : str = 'ls1'): linestyle = {} linestyle['ls1'] = ['-', '--', ':', '-.','-','--',':','-.'] linestyle['ls10'] = ['-', '--', ':', '-.','-','--',':','-.','-','--'] linestyle['llt8'] = ['-','--','-','--','-','--','-','--'] linestyle['lp8'] = ['-',':','-',':','-',':','-',':'] linestyle['llt10'] = ['-','--','-','--','-','--','-','--','-','--'] linestyle['lp10'] = ['-',':','-',':','-',':','-',':','-',':'] return linestyle[style] Where I have to specify the dashes ?? EDIT the problem is that I don't know how is the right way to cycle into them : linestyle['ldash'] = ['(0, ()))','(0, (1, 10)))','(0, (1, 5)))','(0, (1, 1)))'] doesn't works if I insert this in my list EDIT sorry you told me at the begin of your answer could not be string !! I solved !! consider this post close ! thanks a lot
tagged with: python

console
tags question: http://stackoverflow.com/q/51406629
type: Tag
tag name: console
tags question: http://stackoverflow.com/q/51466944

http://stackoverflow.com/comment/89719645
type: QuestionComment
has text: yes, you are right. There was a line which I overlooked. x_train = np.array([np.bincount(doc, minlength=V) for doc in x_train])
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51334491

http://stackoverflow.com/q/51394107
accepted answer: http://stackoverflow.com/a/51394124
score: 0
answer count: 1
has title: running java using python
tagged with: shell
tagged with: command
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/51394124
has body: I am working on a project where I have to run java -jar program using python. If I had to run it on the command line, I would have to write this: java -jar pdfbox-app-2.0.11.jar ExtractText file.pdf Python attempt: import sys import os.path,subprocess def execute_java(): java_class,ext = os.path.splitext(java_file) cmd = ['java',"-jar pdfbox-app-2.0.11.jar ExtractText file.pdf"] subprocess.call(cmd, shell=False) What am I missing?
type: AnsweredQuestion
tagged with: java
type: Question

http://stackoverflow.com/comment/89934297
score: 0
type: QuestionComment
type: Comment
has text: @zhaguo don't hide important details like error messages in comments. [Edit] the question and explain what you saw so we can all share it.
comment on: http://stackoverflow.com/q/51482480

http://stackoverflow.com/q/51376568
score: 0
answer count: 1
tagged with: bloomberg
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51383323
tagged with: python
has comment: http://stackoverflow.com/comment/89730270
has title: Pdblp dataframe multiple securities
has comment: http://stackoverflow.com/comment/89730192
type: Question
has body: I am using below code for historical data via bbg api, question around df how should i define this df for multiple securities? it works fine for one security as below thanks import pdblp con = pdblp.BCon() con.start() con.bdh(['IBM US Equity', 'MSFT US Equity'], ['PX_LAST'], '20061227', '20061231', elms=[("periodicityAdjustment", "ACTUAL")]) df = con.bdh('IBM US Equity','PX_LAST','20061227', '20061231')

http://stackoverflow.com/comment/89813310
type: QuestionComment
has text: What do you now about `tkinter`? Have you read any tutorial? You just need to create a 9x9 grid of labels to display the sudoku and two buttons.
comment on: http://stackoverflow.com/q/51421185
score: 0
type: Comment

http://stackoverflow.com/comment/89691214
comment on: http://stackoverflow.com/a/51359437
type: AnswerComment
score: 0
type: Comment
has text: the column `allHoldingsFund['ratioBest']` is created by using np.where . Basically if values exists then i take the ratio of those values if they do not exist i just set the ratio to zero. `allHoldingsFund['ratioBest']=np.where (if values exist, take the ratio, 0 )`

http://stackoverflow.com/q/51411622
has comment: http://stackoverflow.com/comment/89795105
has comment: http://stackoverflow.com/comment/89797662
has answer: http://stackoverflow.com/a/51411667
score: -1
tagged with: pandas
upvote count: 0
answer count: 1
duplicate of: http://stackoverflow.com/q/176918
favorite count: 0
tagged with: python
has title: Determining the argument of a value in an iterable in python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/176918
accepted answer: http://stackoverflow.com/a/51411667
downvote count: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/89794884
has comment: http://stackoverflow.com/comment/89795026
has body: Is there a python or numpy function that returns the argument or index of some value (or set of values) that exists in an iterable? I want something that is similar to the functionality of: &gt;&gt;c= np.array([1,2,3]) &gt;&gt;np.argmin(c) 0 but is able to do: &gt;&gt;c.*somefunction*(2) 1 In the pandas library, you can create a boolean mask that returns only the values that match the condition, and from there you can return the indices of these values. But how might this be done without pandas?

http://stackoverflow.com/a/51423455
upvote count: 1
downvote count: 1
has body: abamert's answer did not work for me. Though this did, you might try skipping the first step, brew install mysql-connector-c brew install mysql brew link --overwrite mysql pip install MySQL-python
accepted answer of: http://stackoverflow.com/q/51343325
answers question: http://stackoverflow.com/q/51343325
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/51445170
has comment: http://stackoverflow.com/comment/89916888
upvote count: 0
answers question: http://stackoverflow.com/q/51444515
type: Answer
has body: I'm not quite sure if that answers your question 100 percent, but I thought better than no answer at all, especially since I'm pretty sure it can solve your problem, even though I haven't tested it in this release (no default port). # coding: utf-8 from fabric.api import env, execute # hosts from fabric.network import ssh from fabric.operations import get, run, sudo # put ssh.util.log_to_file("paramiko.log", 10) env.host_string = 'remotehostname.com' env.port = 10022 env.user = 'AB1239' env.password = 'password' # Attention: "rm -r" won't ask for password anymore! env.warn_only = True def blah(): sudo('ls') get('/tmp/lolo*.xml', '/tmp', use_sudo=True) # from remote to local # sudo('rm -r /tmp/what/no/') execute(blah)
has comment: http://stackoverflow.com/comment/89985169
downvote count: 2
score: -2

http://stackoverflow.com/q/51374068
tagged with: python
score: 11
has answer: http://stackoverflow.com/a/51374084
upvote count: 11
has comment: http://stackoverflow.com/comment/89719607
has body: I have to remove entire row with the column, which has no value my dataframe looks like Name place phonenum mike china 12344 ireland 897654 suzzi japan 09876 chang china 897654 Australia 897654 india 876543 required output should be Name place phonenum mike china 12344 suzzi japan 09876 chang china 897654 I have used df1=df[df.Name == ''] I got output Name place phonenum Please help me
type: Question
has title: how to remove a row which has empty column in a dataframe using pandas
answer count: 3
tagged with: pandas
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51374150
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/59796110

http://stackoverflow.com/comment/89717302
score: 0
type: Comment
has text: You aren't summing the total and your loop does an unnecessary lookup since you can iterate over the values instead of the keys.
type: AnswerComment
comment on: http://stackoverflow.com/a/51346068

http://stackoverflow.com/a/51450370
score: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89871240
type: Answer
has body: I ran your function and while loop and it was working but a little bit slow. Probably your problem is that it's taking too long to run. I would suggest you write a function and use df.apply(): def helper(row): return netaddr.iprange_to_cidrs(row.StartAddress, row.EndAddress) df["CIDR"] = df.apply(helper, axis=1) This gave me result instantly where as the while loop took much longer on your sample data.
answers question: http://stackoverflow.com/q/51449837
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51449837

http://stackoverflow.com/comment/89798446
type: Comment
comment on: http://stackoverflow.com/q/51408066
type: QuestionComment
has text: Your pagination seems to be working fine on my end; Could you post crawl log? You can do this via `scrapy crawl spider --logfile output.log` or `scrapy crawl spider 2>1 | tee output.log` commands (the later puts output to screen and file).
score: 0

http://stackoverflow.com/a/51389605
type: Answer
has body: Everything in the span tag is one attribute and that attribute's name is style. Everything else is a string within style. It is impossible to get the value of font-style attribute because it isn't a attribute.if 'font-style: italic' in x['style']: is how you check if font-style is italic or not. x['style'] returns the value of the style attribute as a string. Then its just checking if the 'font-style: italic' exists within the string that x['style'] returns.
accepted answer of: http://stackoverflow.com/q/51374189
score: 1
answers question: http://stackoverflow.com/q/51374189
upvote count: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89704085
type: AnswerComment
comment on: http://stackoverflow.com/a/51365215
type: Comment
has text: In my updated post, I have added links to recommended Kivy documentation in response to your question, "Are you aware of any online documentation that teaches people about Kivy from Square 1?"
score: 1

http://stackoverflow.com/q/51400498
tagged with: python
tagged with: nlp
upvote count: 2
score: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51400550
has body: I'm trying to figure out if there is any Python library which allows me to get the percentage value of probability if the string that I'm looking for exists in text or if there is any similar. To get it more clearly, here is the example: My string is 'Company Ltd' and in text it exists but under the phrase 'Company Limited'. The other example, 'Boeing BG' and in text it is present by 'Boeing B.G.' Is there any way for to get percentage value/probability that it exists in text or not?
tagged with: text-processing
answer count: 1
has title: Python - get probability/percentage value if string exists in text
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/51445190
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89862769
has title: Error with python packages
tagged with: python-unittest
has answer: http://stackoverflow.com/a/51446321
type: Question
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89862742
accepted answer: http://stackoverflow.com/a/51446321
tagged with: python-3.x
has body: I know my problem is redundant and there are lots of answers on the internet, but I have tried every suggested solution and I still can't manage to get it right. I'm trying to seperate my unit tests from my source code in python. So my directory looks like this : HelloWorld __init__.py source __init__.py helloworld.py test __init__.py test_helloworld.py My source/helloworld.py looks like this : class HelloWorld: def __init__(self): self.message = 'Hello, World!' And my test/test_helloworld.py looks like this : import unittest from source.helloworld import HelloWorld class MyTestCase(unittest.TestCase): def test_message(self): hw = HelloWorld() self.assertEqual(hw.message, 'Hello, World!') if __name__ == '__main__': unittest.main() Now when I run my test in PyCharm, after marking both directories (source and test) as Sources root, my test runs and says OK (the code passes the test) But when I try to run my tests from a terminal, I get the error ModuleNotFoundError: No module named 'source' I just can't seem to understand the problem. Do I necessarily need to modify PYTHONPATH ? Isn't that what the init.py files are supposed to do ?
tagged with: package

http://stackoverflow.com/a/51463945
has body: EDIT: the following can help only if you always want to round up or always down: import math math.ceil(2.5) #3 math.floor(2.5 #2 This sould work for your case: def myround(n): if n * 10 % 10 &gt; 5: return math.ceil(n) return math.floor(n)
has comment: http://stackoverflow.com/comment/89896693
has comment: http://stackoverflow.com/comment/90175129
has comment: http://stackoverflow.com/comment/89897324
has comment: http://stackoverflow.com/comment/89896678
score: -1
has comment: http://stackoverflow.com/comment/89897730
downvote count: 2
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51463918
has comment: http://stackoverflow.com/comment/89897616

http://stackoverflow.com/q/51436007
has comment: http://stackoverflow.com/comment/89842532
has answer: http://stackoverflow.com/a/51440180
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/54159141
linked to: http://stackoverflow.com/q/45662253
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/89842615
has body: I'm using keras and tensorflow as my backend. I connect to a server with two GPU (1080ti)on it. However ,when I run my code.My code just simply ignore my powerful resource. Here's some information $nvidia-smi while running code: One of my GPU information: And I do install tensorflow-gpu in version 1.9.0 $pip show tensorflow-gpu: It seems that it can detect my gpu successfully. So what's the problem?
has title: Keras Machine Learning Code are not using GPU
score: 0
answer count: 2
tagged with: keras

http://stackoverflow.com/a/51476299
score: 11
upvote count: 11
accepted answer of: http://stackoverflow.com/q/51476274
answers question: http://stackoverflow.com/q/51476274
has body: You can refer to a field with an F-expression [Django-doc]. So we can write it like: from django.db.models import F Mymodel.objects.filter(pickup_station_id=F('drop_station_id')) We can negate a query by using a Q-object [Django-doc]: from django.db.models import F, Q Mymodel.objects.filter(~Q(pickup_station_id=F('drop_station_id'))) Here the tilde (~) means we negate the condition that the Q object represents.
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/51476434
tagged with: deep-learning
tagged with: python
accepted answer: http://stackoverflow.com/a/51492901
has title: How to free GPU memory from keras model?
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/89925012
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/95159691
has body: I'm loading a keras model that I previously trained, to initialize another network with his weights. Unfortunately, the model I load fills my entire memory making the training of the new model impossible. Here is the code : import gc import keras from keras.models import model_from_json def loadModel (path, loss=None, optimizer=None): with open(path + '/model.json', 'r') as f: model = model_from_json(f.read()) model.load_weights(path + '/model.h5') if loss and optimizer: model.compile(loss=loss, optimizer=optimizer) return model model = loadModel('the/path/to/my/model') # The GPU memory is filled keras.backend.clear_session() # memory still filled del model gc.collect() # memory still filled I checked multiple posts, and usually gc.collect() or clear_session() does the trick, but for me, it doesn't work so far. Any idea? PS: I'm using tensorflow as backend.
type: Question
linked to: http://stackoverflow.com/q/43930871
has answer: http://stackoverflow.com/a/51492901
answer count: 1
tagged with: keras
has comment: http://stackoverflow.com/comment/89954391
score: 0

http://stackoverflow.com/a/51379661
accepted answer of: http://stackoverflow.com/q/51379050
answers question: http://stackoverflow.com/q/51379050
has body: Add the character you want to match in a character class [\w.-]. In you example you want to match piramal and in your regex you want to match ongoose. To match both of them you might use an alternation (?:ongoose|piramal) or match any non whitespace character using \S+ and replace with an empty string. To match a dot you have to escape it \. [\w.-]+@\S+\.com\|
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/89775492
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51402353
has text: `QGraphicsRectItem` doesn't inherit `QObject`.
type: AnswerComment

http://stackoverflow.com/q/51392736
type: UnansweredQuestion
type: Question
tagged with: google-cloud-storage
upvote count: 2
has title: How to access files on Google Cloud Storage using Python
answer count: 1
favorite count: 0
tagged with: google-compute-engine
tagged with: python
score: 2
has body: I have files in a Storage Bucket that I can't access from python using the Cloud Shell. I created this simple example: open('gs://iwc/panda.jpg') which results in this: jklieb@cloudshell:~$ python demo.py Traceback (most recent call last): File "demo.py", line 1, in &lt;module&gt; open('gs://iwc/panda.jpg') IOError: [Errno 2] No such file or directory: 'gs://iwc/panda.jpg' But the file is visible when using gsutil: jklieb@cloudshell:~$ gsutil ls gs://iwc gs://iwc/panda.jpg I created a separate virtual machine instance (not the temporary one associated with Cloud Shell) and had a similar result. I have also provisioned a TPU using ctpu and was similarly unable to access files in another storage bucket. The documentation on ctpu says that the permissions should be properly set up to allow access to storage buckets. Have I made some simple mistake that is too obvious for me to see?
has answer: http://stackoverflow.com/a/51448750
downvote count: 0

http://stackoverflow.com/q/51451464
has comment: http://stackoverflow.com/comment/89873160
score: 0
answer count: 3
accepted answer: http://stackoverflow.com/a/51451565
has answer: http://stackoverflow.com/a/51451563
tagged with: python
tagged with: python-requests
has comment: http://stackoverflow.com/comment/89873246
type: AnsweredQuestion
has title: Get request response text prints invalid characters
has body: I'm not an experienced coder at all so I apologize in advance. I often use BeautifulSoup and such for simple web scraping and go on my way. Lately, on some sites, I have been having an issue that I can't seem to search up or figure out myself. r = requests.get('https://www.sneakersnstuff.com/', headers=headers) print(r.text) When it prints, unlike usual, it comes out looking like this. Thanks in advance! Edit: r.content didnt work either. just a bunch of '\x83\xff\x7f\x8cH\xcd\xea\' etc. Headers: 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'en-US,en;q=0.9,ko-KR;q=0.8,ko;q=0.7', 'cache-control': 'max-age=0', 'referer': 'https://www.sneakersnstuff.com/en/858/new-arrivals', 'upgrade-insecure-requests': '1', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
possible better answer: http://stackoverflow.com/a/51451544
has answer: http://stackoverflow.com/a/51451565
type: Question
has answer: http://stackoverflow.com/a/51451544
has comment: http://stackoverflow.com/comment/89873254

http://stackoverflow.com/q/51372094
has title: Run sudo command for executable within script
answer count: 1
downvote count: 1
has body: I have found various answers around StackOverflow and elsewhere addressing this question, however, none of the answers provided have solved my issue. I have tried echo 018020 | underclock.sh as well as the sudo visudo method. None of the above mentioned have worked. Even with michallal ALL = NOPASSWD: /home/michalall/PycharmProjects/Mining/underclock.sh I still get the following message - sudo no tty present and no askpass program specified: Here's my code: import os ubu_path = '/home/michalall' os_path = ubu_path project_path = os_path + '/PycharmProjects/Mining/' os.system('chmod +x ' + project_path + 'nvidia_settings') os.system('cd ' + project_path + 'nvidia_settings/') os.system('sudo ' + project_path + 'underclock.sh') os.system('echo 018020 | underclock.sh') EDIT: When I run: os.system('underclock.sh') os.system('echo 018020 | underclock.sh') os.system('echo 018020 | sudo -S underclock.sh') I get the following output respectively: sh: 1: underclock.sh: not found. sudo no tty present and no askpass program specified sudo no tty present and no askpass program specified
tagged with: executable
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89716297
upvote count: 0
tagged with: shell
has comment: http://stackoverflow.com/comment/89716162
favorite count: 0
has comment: http://stackoverflow.com/comment/89716137
tagged with: linux
has comment: http://stackoverflow.com/comment/89732523
type: Question
has answer: http://stackoverflow.com/a/51372150
tagged with: python
has comment: http://stackoverflow.com/comment/89732416
has comment: http://stackoverflow.com/comment/89716641
score: -1

http://stackoverflow.com/comment/89710356
comment on: http://stackoverflow.com/a/51367744
has text: I've come across this problem before (https://stackoverflow.com/a/50545931/479863), might make sense to switch to JSON or something along the way but that's probably out of scope.
score: 1
type: AnswerComment
type: Comment

http
tags question: http://stackoverflow.com/q/51476961
tags question: http://stackoverflow.com/q/51407885
tags question: http://stackoverflow.com/q/51363497
tag name: http
tags question: http://stackoverflow.com/q/51381777
tags question: http://stackoverflow.com/q/51348075
tags question: http://stackoverflow.com/q/51400941
type: Tag
tags question: http://stackoverflow.com/q/51433473
tags question: http://stackoverflow.com/q/51352753

http://stackoverflow.com/a/51396977
type: Answer
downvote count: 1
score: 19
has body: One can do this by using: import threading threading.current_thread().name = "my_name"
upvote count: 20
answers question: http://stackoverflow.com/q/51396841

http://stackoverflow.com/q/51399744
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/49754385
tagged with: tkinter
answer count: 0
upvote count: 1
downvote count: 1
type: Question
has title: How to call a function in tkinter after an other function has finished to execute?
has comment: http://stackoverflow.com/comment/89778061
has body: Hi, I know that event driven programming is very different than "traditional programming" where the instructions are executed sequentially by the program. However, I am new to it, and I do not understand 100% how does event driven programming works, and I think this is the reason of my problem here. I built an example from the answer to this post:tkinter progress bar won&#39;t update when called from an other app In this example, I would like that my program do an action after it has finished to scan the given path. Naively, I tried adding the call to action routine after the call to walk: import sys import os import tkinter as tk import tkinter.ttk as ttk from tkinter.filedialog import askdirectory class App(ttk.Frame): def __init__(self, parent, title): #tk.Frame.__init__(self, parent) super(App, self).__init__(parent) parent.wm_withdraw() parent.wm_title(title) self.create_ui() self.grid(sticky = "news") parent.wm_protocol("WM_DELETE_WINDOW", self.on_destroy) parent.grid_rowconfigure(0, weight=1) parent.grid_columnconfigure(0, weight=1) parent.wm_deiconify() def create_ui(self): textframe = ttk.Frame(self) self.text = text = tk.Text(textframe) vs = ttk.Scrollbar(textframe, orient=tk.VERTICAL, command=text.yview) text.configure(yscrollcommand=vs.set) text.grid(row=0, column=0, sticky=tk.NSEW) vs.grid(row=0, column=1, sticky=tk.NS) textframe.grid_columnconfigure(0, weight=1) textframe.grid_rowconfigure(0, weight=1) textframe.grid(row=0, column=0, columnspan=2, sticky=tk.NSEW) self.progressvar = tk.IntVar() self.progress = ttk.Progressbar(self, variable=self.progressvar) test_button = ttk.Button(self, text="Walk", command=self.on_walk) exit_button = ttk.Button(self, text="Exit", command=self.on_destroy) self.progress.grid(row=1, column=0, sticky=tk.NSEW) test_button.grid(row=1, column=0, sticky=tk.SE) exit_button.grid(row=1, column=1, sticky=tk.SE) self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(0, weight=1) def on_destroy(self): self.master.destroy() …
score: 0
has comment: http://stackoverflow.com/comment/89773412
has comment: http://stackoverflow.com/comment/89777444
favorite count: 0

http://stackoverflow.com/comment/89704527
type: Comment
comment on: http://stackoverflow.com/q/51358964
score: 0
type: QuestionComment
has text: *"I tried using scipy.stats library to fit to a skew normal on the original data, but the fit does not work at all."* If you showed what you tried and what didn't work the way you expected, someone might be able to help you with that.

http://stackoverflow.com/q/51457672
has answer: http://stackoverflow.com/a/51457825
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89884797
has body: I have a python dataframe with a string column that I want to separate into several more columns. Some rows of the DF look like this: COLUMN ORDP//NAME/iwantthispart/REMI/MORE TEXT /REMI/SOMEMORETEXT /ORDP//NAME/iwantthispart/ADDR/SOMEADRESS /BENM//NAME/iwantthispart/REMI/SOMEMORETEXT So basically i want everything after '/NAME/' and up to the next '/'. However. Not every row has the '/NAME/iwantthispart/' field, as can be seen in the second row. I've tried using split functions, but ended up with the wrong results. mt['COLUMN'].apply(lambda x: x.split('/NAME/')[-1]) This just gave me everything after the /NAME/ part, and in the cases that there was no /NAME/ it returned the full string to me. Does anyone have some tips or solutions? Help is much appreciated! (the bullets are to make it more readable and are not actually in the data).
type: Question
has title: Extract substring between 2 strings in python
has answer: http://stackoverflow.com/a/51457957
tagged with: substring
score: 0
answer count: 2
tagged with: pandas
linked to: http://stackoverflow.com/q/47175817

http://stackoverflow.com/q/51453619
type: UnansweredQuestion
tagged with: python
score: 1
has body: I suddenly cannot set any breakpoint in my python program. Note there are two (Pdb) showing up. I wonder if the Pdb was damaged before. I did try to step into some compiled C++ code in an abc.so file using Pdb before this issue started happening: -&gt; print('haha') (Pdb) (Pdb) Traceback (most recent call last): File "high.py", line 38, in &lt;module&gt; print('haha') File "high.py", line 38, in &lt;module&gt; print('haha') File "/Users/ludaming/anaconda2/lib/python2.7/bdb.py", line 49, in trace_dispatch return self.dispatch_line(frame) File "/Users/ludaming/anaconda2/lib/python2.7/bdb.py", line 68, in dispatch_line if self.quitting: raise BdbQuit bdb.BdbQuit
has comment: http://stackoverflow.com/comment/89877244
upvote count: 1
tagged with: pdb
type: Question
has title: Pdb Crashed: Cannot set breakpoint
tagged with: debugging
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89935653
has answer: http://stackoverflow.com/a/51484042
favorite count: 0

http://stackoverflow.com/a/51329429
has body: I interpret this question as, "I want to construct a rainbow table by iterating through all strings that have the following qualities. The string has a length of 12, contains only the characters 0-9 and A-F, and it never has the same character appearing three times in a row." def iter_all_strings_without_triplicates(size, last_two_digits = (None, None)): a,b = last_two_digits if size == 0: yield "" else: for c in "0123456789ABCDEF": if a == b == c: continue else: for rest in iter_all_strings_without_triplicates(size-1, (b,c)): yield c + rest for s in iter_all_strings_without_triplicates(12): print(s) Result: 001001001001 001001001002 001001001003 001001001004 001001001005 001001001006 001001001007 001001001008 001001001009 00100100100A 00100100100B 00100100100C 00100100100D 00100100100E 00100100100F 001001001010 001001001011 ... Note that there will be several hundred terabytes' worth of values outputted, so you aren't saving much room compared to just saving every single string, triplicates or not.
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51328929
score: 1
downvote count: 0

http://stackoverflow.com/q/51453506
has answer: http://stackoverflow.com/a/51454575
tagged with: lstm
type: Question
answer count: 1
downvote count: 0
tagged with: keras
favorite count: 0
accepted answer: http://stackoverflow.com/a/51454575
tagged with: python
has title: conv_lstm.py example uses 'binary_crossentropy' loss for regression. Why not using 'mean_squared_error' instead?
tagged with: conv-neural-network
score: 1
has comment: http://stackoverflow.com/comment/89876705
has body: 2 questions: I was using keras team conv_lstm.py example on github to predict the next frame of the video created in that example. It is a regression problem obviously, since we are going to predict the next frame. I was wondering why they used this loss line 38: seq.compile(loss='binary_crossentropy', optimizer='adadelta') Instead, I believe using: seq.compile(loss='mean_squared_error', optimizer='rmsprop') would result in better predictions, since we are implementing a regression problem, rather than classification. Am I correct? In line 107 of the code, they left a comment saying that: feed it with the first 7 positions and then predict the new positions. here is the code they used to predict 7 frames given 7 input frames : which = 1004 track = noisy_movies[which][:7, ::, ::, ::] for j in range(16): new_pos = seq.predict(track[np.newaxis, ::, ::, ::, ::]) new = new_pos[::, -1, ::, ::, ::] track = np.concatenate((track, new), axis=0) Suppose I want to predict 7th frame of a test video. If I don't feed the model with the last 7 frames, instead feed it with just the 7th frame, would it make difference in prediction? Thanks.
upvote count: 1
type: AnsweredQuestion

http://stackoverflow.com/comment/89738694
score: 0
type: Comment
has text: @ThelMi - only need before `join` cast to strings
comment on: http://stackoverflow.com/a/51383128
type: AnswerComment

http://stackoverflow.com/comment/89733940
has text: Also take a look at https://github.com/crossbario/autobahn-python/tree/master/examples/twisted/websocket. The echo example is short and sweet.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51380145

http://stackoverflow.com/comment/89685427
score: 1
has text: Note that manual padding gives you slightly more control: In case of even filter size there needs to uneven padding, and the conv functions with "same" padding will (IIRC) always pad one more at the _end_ (right/bottom) whereas you might want to have it the other way around for some reason.
type: QuestionComment
comment on: http://stackoverflow.com/q/51356524
type: Comment

http://stackoverflow.com/a/51455201
accepted answer of: http://stackoverflow.com/q/51453526
score: 0
type: AcceptedAnswer
has body: The wrong answers are due to the fact that your current implementation does not ensure that the calculated r will be a positive number when a,b < 0. In fact, if you check the link provided you will see that the theorem defines 0 ≤ r < |b| Testing your current algorithm with input values a = -7 and b = -3 you will get q = 1 and r = -4. But as said we need r ≥ 0 Try the following code again with input values a = -7 and b = -3. This time you will get q = 3 and r = 2, which satisfies as well the a = b × q + r equation: -7 = -3 x 3 + 2 Finally - just to avoid misunderstandings - I added a condition to control and explicitly cover those inputs where b = 0, another situation not accepted by the Euclidean Division Theorem def euclidean_division(a, b): if(a < 0 and b > 0): q = int(a/b) - 1 r = a - (b*q) elif(a > 0 and b < 0): q = int(a/b) r = a - (b*q) elif(a > 0 and b > 0): q = int(a/b) r = a - (b*q) elif(a < 0 and b < 0): q = int((a+b)/b) r = a - (b*q) return q, r def main(): print("Please insert two integer values separated by a space") print("NOTE: the second integer is NOT allowed to be equal to zero") first_input, second_input = input().split() first_int=int(first_input) second_int=int(second_input) if(second_int != 0): first_output, second_output = euclidean_division(first_int, second_int) print("q = " + str(first_output) + " r = " + str(second_output)) else: print("Second integer must be other than 0") print("Try again\n") main() if __name__ == "__main__": main() NOTE: this example proves also the importance of having r ≥ 0 to guarantee the uniqueness of the solution
type: Answer
answers question: http://stackoverflow.com/q/51453526

http://stackoverflow.com/comment/89688575
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51356176
type: QuestionComment
has text: please provide code.i would suggest to resetting your index to numeric from the following command. df = df.reset_index() from the error it seems like Date is not inserted as Column, it is referred as index?

http://stackoverflow.com/a/51479183
has comment: http://stackoverflow.com/comment/89932028
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89931956
has body: Suppose you have your code performed by a Keras layer, either a custom layer or a Lambda layer. The best way I found to debug things was to create a very little model with only that layer to see what it outputs. If the problem lies within the code, then I gradually move the return statement up to a point where I believe the error is. debugModel = Sequential() debugModel.add(MyCustomLayer(...., input_shape=some_shape)) Create dummy or useful data: data = loadOrCreateSomeData() Or get the data from the previous layer with a submodel: subModel = Model(oldModel.inputs, oldModel.get_layer(nameOfATargetLayer).outputs) data = subModel.predict(inputData) After having suitable data for the test: result = debugModel.predict(data) Some comments about your code: Ungrouped dimensions In the following lines, you are inverting the dimensions in reshape, which often messes up your data completely, as dimensions lose meaning. (You're not doing a proper transpose, you're just regrouping numbers in a different way) pool_shape = (input_shape[-1], np.prod(input_shape[1:-1])*self.batch_size) x = K.reshape(x,pool_shape) I suppose you should be trying this: pool_shape = (-1, input_shape[-1]) x = K.reshape(x,pool_shape) And maybe this: x = K.permute_dimensions(x, (1,0)) #if you do want to invert the dimensions
has comment: http://stackoverflow.com/comment/89930290
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51478595
type: Answer
accepted answer of: http://stackoverflow.com/q/51478595

http://stackoverflow.com/a/51489458
score: 0
has body: The *args argument to your show_saved_conditions() method contains the Button instance that was pressed. So that method could be: def show_saved_conditions(self, btn_instance): self.label7 = Label(text = str(self.store[btn_instance.text], size_hint = (.3,.3), pos_hint = {'x':.3,'y':.5}, color = (0,0,1,1))) self.layout.add_widget(self.label7) Since you used self in the method, I have assumed that this is an instance method and the correct first arg is self. If it is not an instance method, then just remove the self arg, but then where does the method get the value for self? Of course, this method will overwrite self.label7 each time that it is executed.
type: Answer
answers question: http://stackoverflow.com/q/51463615

http://stackoverflow.com/q/51452281
has body: I have some data similar to: #Simulate some data d = { "id": [1,1,1,1,1,2,2,2,2], "action_order": [1,2,3,4,5,1,2,3,4], "n_actions": [5,5,5,5,5,4,4,4,4], "seed": ['1','2','3','4','5','10','11','12','13'], "time_spent": [0.3,0.4,0.5,0.6,0.7,10.1,11.1,12.1,13.1] } data = pd.DataFrame(d) I need a function that for each row will return the values from two columns (seed and time_spent) in that row AND ALL PREVIOUS ROWS within the group as a dictionary. I have attempted to use the apply function as follows but the results are not quite what I need. data \ .groupby(["profile_id"])"artist_seed", "tlh" \ .apply(lambda x: dict(zip(x["artist_seed"], x["tlh"]))) \ .tolist() data \ .groupby("profile_id")"artist_seed", "tlh", "action_order" \ .apply(lambda x: dict(zip(list(x["artist_seed"]), list(x["tlh"])))) The new DataFrame should look like this: id new_col 0 1 {u'1': 0.3} 1 1 {u'1': 0.3, u'2': 0.4} 2 1 {u'1': 0.3, u'3': 0.5, u'2': 0.4} ...
tagged with: python
has answer: http://stackoverflow.com/a/51452308
type: AnsweredQuestion
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/51452308
has title: Progressive value collection within a group in pandas
score: 0
possible better answer: http://stackoverflow.com/a/51452385
tagged with: pandas
has answer: http://stackoverflow.com/a/51452385

http://stackoverflow.com/comment/89639733
score: 1
comment on: http://stackoverflow.com/q/51332036
has text: I see- strictly greater than, not greater than or equal to. My bad
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89825258
score: 0
type: Comment
type: QuestionComment
has text: I cannot reproduce this. 1/30fps = 0.033 seconds. Instead running this code I see 0.047 seconds. Meaning the animation run *slower* than expected.
comment on: http://stackoverflow.com/q/51426647

http://stackoverflow.com/q/51480511
answer count: 0
type: UnansweredQuestion
has title: Measuring height of text using PIL
tagged with: image-processing
has comment: http://stackoverflow.com/comment/89931923
type: Question
has comment: http://stackoverflow.com/comment/89932043
score: 0
has body: I want to measure height of text fields on images programmatically (check attachment). example-image-attachment Is there any ideas how to do it using PIL/etc.?
tagged with: python
tagged with: text

http://stackoverflow.com/a/51352048
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51348788
downvote count: 0
has body: First problem There is no text but encoded text. If a file was written from text then the writer chose a character encoding. Communication of a text file includes the bytes and knowledge of the character encoding. You are telling the compiler (probably by default) that your file was encoded with UTF-8. It's saying that it can't be (and it's probably correct). So, you first have to tell it which encoding it is. On the other hand, since UTF-8 is a very common encoding for the Unicode character set and Unicode has all the characters you are likely to ever use, and it's the default for many, many programs, including Python, you could convert the file to UTF-8. Second problem @soon's answer deals with the secondary problem of using characters for syntax that aren't part of the syntax. They are confusables.

http://stackoverflow.com/q/51346083
favorite count: 0
accepted answer: http://stackoverflow.com/a/51352663
tagged with: shapely
tagged with: python
has title: Upload and fetch MySQL polygons to Python
score: 1
upvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51352663
tagged with: mysql
tagged with: sqlalchemy
type: Question
has body: I have to store some polygons in a MySQL database. I insert a polygon into the database using a query from the MySQL manual SET @g = 'POLYGON((0 0,10 0,10 10,0 10,0 0),(5 5,7 5,7 7,5 7, 5 5))'; INSERT INTO geom VALUES (111, ST_GeomFromText(@g)); The columns of the table are id and polygon, the type of the latter column is POLYGON, but I have the same issue if it is set to GEOMETRY. Then I fetch the polygon from the database (using sqlalchemy) and the result will be bytes. So I try to convert it into Shapely from shapely import wkb from sqlalchemy import create_engine import pandas as pd my_engine = ... # sqlalchemy engine connecting to the database df = pd.readsql('SELECT polygon FROM geom WHERE id = 111;', my_engine) p = df.polygon[0] wkb.loads(p) &gt;&gt;&gt; &lt;shapely.geometry.point.Point at 0x7f1896b01b38&gt; I get a point not a polygon. What could be the issue?
answer count: 1
downvote count: 0

http://stackoverflow.com/q/51448634
has comment: http://stackoverflow.com/comment/89867854
has comment: http://stackoverflow.com/comment/89868425
accepted answer: http://stackoverflow.com/a/51448947
has comment: http://stackoverflow.com/comment/89868273
has comment: http://stackoverflow.com/comment/89868654
has comment: http://stackoverflow.com/comment/89868468
has comment: http://stackoverflow.com/comment/89867936
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89868729
has title: Why are my ports not being mapped in docker-compose?
tagged with: docker
type: Question
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51448947
tagged with: flask
has comment: http://stackoverflow.com/comment/89868327
tagged with: python
has comment: http://stackoverflow.com/comment/89868262
has body: I currently have a small api written in Flask made for interacting with a CNN, I'm setting up the configuracion for running it in Docker and everything runs fine, this is my actual configuration: Dockerfile: FROM python:2.7.15-jessie RUN mkdir -p usr/src/app COPY . usr/src/app WORKDIR usr/src/app RUN which python RUN apt-get update &amp;&amp; apt-get install -y RUN pip install flask flask_uploads Werkzeug opencv-python numpy tensorflow ENV PORT 5000 EXPOSE 5000 CMD ["flask", "run"] Docker-compose: version: "2.2" services: api: container_name: "pyserver" build: . volumes: - ".:/usr/src/app" environment: FLASK_APP: server.py ports: - "5000:5000" command: ["flask", "run"] server.py import os from base64 import b64encode, b64decode from flask import Flask, redirect, request, url_for, json, send_file from flask_uploads import UploadSet, configure_uploads from werkzeug.utils import secure_filename from GW_predict import predict UPLOAD_FOLDER = 'CNN/Files' ALLOWED_EXTENSIONS = set(['txt', 'csv', 'png', 'jpg', 'jpeg']) app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.config["DEBUG"] = True def allowed_file(filename): ext = '.' in filename and \ filename.rsplit('.', 1)[1].lower() return ext, ext in ALLOWED_EXTENSIONS @app.route('/status', methods=['GET']) def status(): return create_response({ 'online': True, 'message': 'UP AND RUNNING @ 5000' }, 200) @app.route('/uploadFile', methods=['POST']) def upload_file(): if 'h1' not in request.files or 'l1' not in request.files: return create_response({'result': False, 'message': 'File missing'}, 422) h1_file = request.files['h1'] l1_file = request.files['l1'] if h1_file.filename == '' or l1_file.filename == '': return create_response({'result': False, 'message': 'File missing'}, 422) h1_ext, h1res = allowed_file(h1_file.filename) l1_ext, l1res = allowed_file(l1_file.filename) if h1_file and l1_file and h1res and l1res: h1_filename = secure_filename(h1_file.filename) l1_filename = secure_filename(l1_file.filenam…

http://stackoverflow.com/comment/89754613
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51390649
score: 0
has text: hi Warren, yes... the integral of a pdf function, from x = -infinity to +infinity = 1.0. That I could see and double-checked by using cdf_fitted = dist.cdf()... The cdf function generates the cumulative probability, which is just the integral. ... however, my understanding is that the pdf under scipy is the normalized instantaneous probability... so I thought the sum of all the given pdf points should be 1.0; because the sum of all points is effectively taking the integral, but over discrete buckets.

http://stackoverflow.com/comment/89823024
comment on: http://stackoverflow.com/q/51425638
has text: @harold storing the file as 25 bytes instead of 43 is a ~40% improvement, that seems worthwhile. What temporary result are you referring to?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/65354814
has comment: http://stackoverflow.com/comment/115543958
upvote count: 2
has body: import re n = int(input()) patt = r'^(?=(?:[a-z\d]*[A-Z]){2})(?=(?:\D*\d){3})(?:([a-zA-Z\d])(?!.*\1)){10}$' for x in range(n): match=re.match(patt,str(input())) if match: print("Valid") else: print("Invalid")
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51358885

http://stackoverflow.com/q/51422688
tagged with: tfidfvectorizer
has comment: http://stackoverflow.com/comment/89816740
has comment: http://stackoverflow.com/comment/89816575
tagged with: python
has answer: http://stackoverflow.com/a/51440464
accepted answer: http://stackoverflow.com/a/51440464
downvote count: 0
has comment: http://stackoverflow.com/comment/89816304
linked to: http://stackoverflow.com/q/51633775
type: Question
has body: In the context of an internship project, I have to perform a tfidf analyse over a large set of files (~18000). I am trying to use the TFIDF vectorizer from sklearn, but I'm facing the following issue : how can I avoid loading all the files at once in memory ? According to what I read on other posts, it seems to be feasible using an iterable, but if I use for instance [open(file) for file in os.listdir(path)] as the raw_documents input to the fit_transform() function, I am getting a 'too many open files' error. Thanks in advance for you suggestions ! Cheers ! Paul
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89816833
has title: Sklearn TFIDF on large corpus of documents
has comment: http://stackoverflow.com/comment/89816829
score: 5
answer count: 1
tagged with: scikit-learn
favorite count: 0
upvote count: 5

http://stackoverflow.com/comment/89871240
comment on: http://stackoverflow.com/a/51450370
score: 0
type: AnswerComment
has text: That is extremely fast and produced exactly what I was looking for. Thank you @Yilun Zhang
type: Comment

http://stackoverflow.com/comment/89626316
score: 0
type: AnswerComment
type: Comment
has text: thank you for your answer, i will try to apply it :)
comment on: http://stackoverflow.com/a/51325650

http://stackoverflow.com/a/51380890
has comment: http://stackoverflow.com/comment/89741816
has comment: http://stackoverflow.com/comment/89745871
answers question: http://stackoverflow.com/q/51368151
has comment: http://stackoverflow.com/comment/89741704
has comment: http://stackoverflow.com/comment/89740158
score: 0
has body: I think the problem is that the convolution calculation is incorrect. import numpy as np import scipy.optimize import matplotlib.pyplot as plt t = np.array([ -7200, -6300, -5400, -4500, -3600, -2700, -1800, -900, 0, 900, 1800, 2700, 3600, 4500, 5400, 6300, 7200, 8100, 9000, 9900, 10800]) g = np.array([ 4.7, 5.17, 4.93, 4.38, 4.47, 4.4, 3.36, 3.68, 4.58, 11.73, 18.23, 19.33, 19.04, 17.21, 12.98, 11.59, 9.26, 7.66, 6.59, 5.68, 5.1]) f = np.array([ 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 8.25, 3, 0.5, 0, 0, 0, 0, 0, 0, 0, 0]) lambda_1 = 0.000431062 lambda_2 = 0.000580525 delta_t = 900 # Define the exponential parts of the integrals x_1 = np.exp(-lambda_1 * t) x_2 = np.exp(-lambda_2 * t) # Define the convolution for a given 't' (in this case, using the index of 't') def convolution(n, x): return np.dot(f[:n], x[:n][::-1]) # The integrals do not vary as part of the optimization, so calculate them now integral_1 = delta_t * np.array([convolution(i, x_1) for i in range(len(t))]) integral_2 = delta_t * np.array([convolution(i, x_2) for i in range(len(t))]) #Definition of the function def convol(n,A,B,C): return A * integral_1[n] + B * integral_2[n] + C #Determination of fit parameters A,B,C popt, pcov = scipy.optimize.curve_fit(convol, range(len(t)), g) A,B,C= popt perr = np.sqrt(np.diag(pcov)) # Print out the coefficients determined by the optimization print(A, B, C) #Plot fit fit = convol(range(len(t)),A,B,C) plt.plot(t, fit) plt.scatter(t, g,s=50, color='black') plt.show() The values that I get for the coefficients are: A = 7.9742184468342304e-05 B = -1.0441976351760864e-05 C = 5.1089841502260178 I don't know if the negative value for B is reasonable or not so I have left it as-is. If you want coefficients that are positive, you can constrain them as shown by James.
has comment: http://stackoverflow.com/comment/89741439
has comment: http://stackoverflow.com/comment/89741032
type: Answer
has comment: http://stackoverflow.com/comment/89741472

http://stackoverflow.com/comment/89763155
comment on: http://stackoverflow.com/a/51395884
type: Comment
has text: But you are right. If you insist on having it. You don't need to specify it. I am making an edit.
type: AnswerComment
score: 0

azure-iot-hub
type: Tag
tags question: http://stackoverflow.com/q/51382338
tag name: azure-iot-hub
tags question: http://stackoverflow.com/q/51326739

http://stackoverflow.com/comment/89776128
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51401953
has text: yes..my bad.Corrected it now

http://stackoverflow.com/q/51375986
has comment: http://stackoverflow.com/comment/89723782
has comment: http://stackoverflow.com/comment/89723510
has comment: http://stackoverflow.com/comment/89723817
linked to: http://stackoverflow.com/q/3278077
type: Question
tagged with: python
duplicate of: http://stackoverflow.com/q/3278077
score: 0
has title: Delegation in Python
has comment: http://stackoverflow.com/comment/89723671
has body: I am stuck in a problem with delegation in Python. I read a program as following: class wrapper: def __init__(self,object): self.wrapped=object def __getattr__(self,attrname): #reload the dot-calculation print('Trace:', attrname) #print the attribute of the object return getattr(self.wrapped, attrname) #execute the attributes of the object i=[1,2,3] myWrapper=wrapper(i) wrapper.wrapped #execute the dot-calculation wrapper.append(4) #execute the dot-calculation In my opinion, both of these two executions of the dot-calculation should print 'Trace'. However, I only get Trace for one time. wrapper.wrapped #never print 'Trace' wrapper.append(4) #print ('Trace:', append') I can't understand this. Is funtion__getattr__ reloaded or not? Why there is nothing printed during the first execution? Thanks for your explanation!
has comment: http://stackoverflow.com/comment/89723887
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/51379239
score: 0
answers question: http://stackoverflow.com/q/51376555
has body: Need to call outfile.close(), otherwise data may only be flushed after exiting the programm, so you are missing the ()
type: Answer

http://stackoverflow.com/a/51336321
type: Answer
has body: You can unpack the tuple's data and use a condition: # if there is 2 elements in your tuple # Otherwise: # a, b, *c = ('n', 'y', 'c', ...) a, b = ('n', 'y') return a if a == 'y' else b
answers question: http://stackoverflow.com/q/51336271
score: 0

http://stackoverflow.com/comment/89815795
score: 0
type: QuestionComment
has text: List comprehension on `Hyperparameters` and get value where `key==contamination` ?
type: Comment
comment on: http://stackoverflow.com/q/51422428

http://stackoverflow.com/q/51456777
has answer: http://stackoverflow.com/a/51456846
has comment: http://stackoverflow.com/comment/89934659
tagged with: python
has body: I have an associative array which I want to sort items = {1: [5, 30, 0.16666666666666666], 2: [10, 20, 0.5]} I want to sort items by float value with descending order so after sorting I should get items = {2: [10, 20, 0.5], 1: [5, 30, 0.16666666666666666]} Note I want to sort mainly these 0.16666666666666666 and 0.5 Any help is welcomed!
type: UnansweredQuestion
upvote count: 1
downvote count: 1
tagged with: list
tagged with: associative
type: Question
has title: Python sort associative array with float values
tagged with: arrays
answer count: 1
favorite count: 0
score: 0

http://stackoverflow.com/comment/123914220
type: AnswerComment
score: 2
type: Comment
comment on: http://stackoverflow.com/a/51373253
has text: You can change the line `python3 -m pip ..` to a more detailed python3 version such as `python3.10 -m pip..`

http://stackoverflow.com/a/51461910
answers question: http://stackoverflow.com/q/51461844
has body: Your code indentation seems off. Not here in the post but maybe in the real code. I tried your program and the output was printed only once. The print statement should be outside the loop i.e. at the same indentation level.
type: Answer
has comment: http://stackoverflow.com/comment/89905193
score: 0

http://stackoverflow.com/comment/89644542
has text: How did you install Python 3? A python.org installer? Homebrew? Anaconda? Some other installer? Building the source and running `make install`?
comment on: http://stackoverflow.com/q/51334492
type: Comment
type: QuestionComment
score: 3

http://stackoverflow.com/q/51329903
has comment: http://stackoverflow.com/comment/89636687
tagged with: image-processing
upvote count: 1
has comment: http://stackoverflow.com/comment/89635488
answer count: 1
tagged with: opencv
has body: I am a beginner in image processing, opencv, and python. I want to display an image using jupyter notebook on Mac and close the window but its not working. In addition, python.app stops working so I have to force quit it, causing my kernel to die, which I then have to restart as well. I am using python 2.7 for this and opencv 3.4.1 import numpy as np import cv2 # Load an color image in grayscale img = cv2.imread('messi5.jpg',0) cv2.imshow('image',img) cv2.waitKey(0) cv2.destroyAllWindows() it is partially not duplicate as it tries to seek answer for jupyter notebook.
has comment: http://stackoverflow.com/comment/89635625
has answer: http://stackoverflow.com/a/51331109
linked to: http://stackoverflow.com/q/6116564
duplicate of: http://stackoverflow.com/q/6116564
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89636683
accepted answer: http://stackoverflow.com/a/51331109
type: Question
has comment: http://stackoverflow.com/comment/89635627
has title: python opencv: destroyallwindow does not work
tagged with: python
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/89638133
has comment: http://stackoverflow.com/comment/89635581

http://stackoverflow.com/comment/89714421
comment on: http://stackoverflow.com/q/51371024
type: Comment
type: QuestionComment
has text: @neerad29 It should be LIFO rather than FIFO for entries of the same priority. That's is the essence of the difference
score: 1

http://stackoverflow.com/q/51401455
tagged with: flask-login
tagged with: oauth
accepted answer: http://stackoverflow.com/a/52118007
possible better answer: http://stackoverflow.com/a/53442311
tagged with: flask-oauthlib
type: Question
has body: I am developing a Flask application that allows the user to login using OAuth (with Github as a provider), and the flask-dance library. For some reason I am not able to redirect, after a successful login, to the page from which I sent the user to the login page. When the user tries to connect to, e.g., http://localhost:6675/examples/tutorial.first/, the user is redirected to the login page, showing in the URL the page we should redirect to (http://localhost:6675/login?next=%2Fexamples%2Ftutorial.first%2F) The problem is that after I manage to login using Github, the application just goes back to the homepage. I was checking Flask-dance documentation and the documentation for the make_github_blueprint() function mentions the parameters redirect_to and redirect_url, but when I try using them I cannot even complete the login step. Furthermore, it seems that it would work only with static addresses, while ideally I would like to jump back to the page I was before logging in. I also checked this SO question, but the problem there seems to be different. Are there any examples on how to properly do redirection after logging in with Flask dance? Here some code snippets which could be relevant. In the init.py file: bp_github = make_github_blueprint( client_id="...", client_secret="...", ) login_manager = LoginManager() login_manager.login_github_view = 'github.login' login_manager.login_view = 'login' And in the app.py file: @app.route("/login", methods=['GET', 'POST']) def login(): if current_user.is_authenticated: return flask.redirect(flask.url_for('/')) return flask.render_template('login.html') @app.route("/logout") @login_required def logout(): logout_user() flask.flash("You have logged out") return flask.redirect(flask.url_for("login")) @oauth_authorized.connect_via(bp_github) def logged_in(blueprint, token): """ create/login local user on successful OAuth login with github :param blueprint: :param token: :return: """ if not token: flask.flash("Failed to log in.", cat…
upvote count: 5
has answer: http://stackoverflow.com/a/65011989
has answer: http://stackoverflow.com/a/71965336
has answer: http://stackoverflow.com/a/66752794
score: 5
has answer: http://stackoverflow.com/a/52118007
downvote count: 0
tagged with: flask
favorite count: 0
has title: Redirect to previous URL after OAuth login is completed (flask-dance)
answer count: 5
has answer: http://stackoverflow.com/a/53442311
tagged with: python
linked to: http://stackoverflow.com/q/49749572
type: AnsweredQuestion

http://stackoverflow.com/q/51471474
tagged with: python
score: 2
type: AnsweredQuestion
has body: Is there any function available for adding multiple Integer Column values and create a new column. For example: Multiple counts to single total count column. I hope concat will work only for String columns.
type: Question
tagged with: apache-spark-sql
has title: How to add multiple Integer column values and create a single column
tagged with: pyspark
has answer: http://stackoverflow.com/a/51472542
downvote count: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51472542
upvote count: 2

http://stackoverflow.com/q/51467820
has answer: http://stackoverflow.com/a/51468058
favorite count: 0
has comment: http://stackoverflow.com/comment/89904229
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51467850
upvote count: 1
downvote count: 1
type: Question
has body: My code is as below: def a(num): #if num == 2, then want to skip running b() and go on to next loop if a == 2: # i have tried break, pass and continue there # pass and continue return an error (SyntaxError: 'pass/continue' not properly in loop) def b(num): print('b:' str(num)) for x in range(1,10): a(x) b(x) How can I skip running b() when num is 2? I have tried pass, continue and break but no clue. Thanks for your great help. I finally use return to make this possible. Thanks mate!
has title: Break the for loop while calling dev
has comment: http://stackoverflow.com/comment/89904206
has answer: http://stackoverflow.com/a/51467965
score: 0
answer count: 3

http://stackoverflow.com/q/51376555
type: UnansweredQuestion
tagged with: file
has comment: http://stackoverflow.com/comment/89726591
has body: tempfile = "temp.txt" runc = get_config_ssh(ipSw,cisco_user,cisco_pass,"show switch") outfile = open(tempfile, "w") outfile.write(runc) outfile.close nstack = 0 with open(tempfile) as infp: data = infp.read() print data Tshoot: 1- temp.txt file after execution contains the data but if I try to read with python don't show any result. 2 - If I change the command, for example "show int status" that I issue to the switch, it works, it print the data readed by python scrypt 3 - show switch and show int status both command outputs are in clear text and both are present in the temp.txt file after execution. There is a problem with write method? SSH Connection write data int temp.txt file but when I read it later (witch open....) print data not show any result. Anyone can help me with this issue? Thanks
has comment: http://stackoverflow.com/comment/89724770
type: Question
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/89724686
has comment: http://stackoverflow.com/comment/89729819
tagged with: python
has comment: http://stackoverflow.com/comment/89741438
has title: Python not read file
has answer: http://stackoverflow.com/a/51379239
has answer: http://stackoverflow.com/a/51376579
has comment: http://stackoverflow.com/comment/89725058

http://stackoverflow.com/comment/89796304
type: QuestionComment
has text: Could you share the file you're trying to annotate? I think it was pretty fast when I tried parsing another data.
comment on: http://stackoverflow.com/q/51366811
score: 0
type: Comment

http://stackoverflow.com/a/51389385
answers question: http://stackoverflow.com/q/51369663
type: Answer
has body: b = a.sum() can't ever modify the original value of b in python syntax. numba gets around this by requiring every param to a gufunc be an array - scalars are just length 1, that you can then assign into. So you need both params as arrays, and the assignment must use [] @numba.guvectorize(["void(float64[:],float64[:])"],"(n)-&gt;()") def f(a,b): b[:] = a.sum() # or b[0] = a.sum() f(a) Out[246]: array([ 1., 5., 9., 13., 17.])
score: 8
has comment: http://stackoverflow.com/comment/89755924
downvote count: 0
upvote count: 8

http://stackoverflow.com/comment/89837845
type: AnswerComment
comment on: http://stackoverflow.com/a/51432625
score: 0
has text: Or no methods at all.. .
type: Comment

http://stackoverflow.com/q/51344164
answer count: 2
has comment: http://stackoverflow.com/comment/89661658
has comment: http://stackoverflow.com/comment/89661604
favorite count: 0
has comment: http://stackoverflow.com/comment/89661621
tagged with: operator-keyword
tagged with: python
has title: Python operator overloading not working
has comment: http://stackoverflow.com/comment/89661631
upvote count: 2
type: UnansweredQuestion
downvote count: 1
type: Question
tagged with: overloading
score: 1
has answer: http://stackoverflow.com/a/51344203
has body: I have a Vector2 class: class Vector2(): def __init__(self, x=0, y=0): self.x = x self.y = y def __add__(self, other): return Vector2(self.x + other.x, self.y + other.y) def __sub__(self, other): return Vector2(self.x - other.x, self.y - other.y) def __mul__(self, other): return Vector2(self.x * other, self.y * other) def __neg__(self): return Vector2(-self.x, -self.y) def magnitude(self): return math.sqrt(self.x ** 2 + self.y ** 2) @classmethod def distance(self, v1, v2): return math.sqrt((v2.x - v1.x) ** 2 + (v2.y - v1.y) ** 2) def normalize(self): return self * (1/self.magnitude()) When I try to do 1.0 * Vector2(), I get the error: TypeError: unsupported operand type(s) for *: 'float' and 'instance' However, sometimes it works as intended: #this works as intended, s is a float ball.pos -= ball.vel.normalize() * s ball.vel is a vector and I am able to multiply by a float. Vectors are multiplied by floats in many sections of my code without errors. Does anyone know where this inconsistency comes from? Thanks
has answer: http://stackoverflow.com/a/73421522

http://stackoverflow.com/comment/89722042
comment on: http://stackoverflow.com/a/51358490
type: AnswerComment
score: 0
type: Comment
has text: @ jezrael I have given Quarterly data can you give me the solution

dialogflow-es
tag name: dialogflow-es
tags question: http://stackoverflow.com/q/51471128
type: Tag
tags question: http://stackoverflow.com/q/51329594

sicp
tag name: sicp
type: Tag
tags question: http://stackoverflow.com/q/51327758

pygame
tags question: http://stackoverflow.com/q/51329797
tags question: http://stackoverflow.com/q/51409987
tags question: http://stackoverflow.com/q/51360409
tags question: http://stackoverflow.com/q/51327509
tags question: http://stackoverflow.com/q/51464455
tags question: http://stackoverflow.com/q/51450091
tags question: http://stackoverflow.com/q/51402490
tags question: http://stackoverflow.com/q/51477899
tags question: http://stackoverflow.com/q/51469366
tags question: http://stackoverflow.com/q/51404618
tags question: http://stackoverflow.com/q/51426583
tags question: http://stackoverflow.com/q/51425023
tags question: http://stackoverflow.com/q/51432649
tags question: http://stackoverflow.com/q/51451106
tags question: http://stackoverflow.com/q/51425190
tags question: http://stackoverflow.com/q/51460626
tags question: http://stackoverflow.com/q/51411713
tags question: http://stackoverflow.com/q/51370238
tags question: http://stackoverflow.com/q/51382344
tags question: http://stackoverflow.com/q/51405613
tags question: http://stackoverflow.com/q/51364153
tag name: pygame
tags question: http://stackoverflow.com/q/51417267
tags question: http://stackoverflow.com/q/51342088
tags question: http://stackoverflow.com/q/51384151
tags question: http://stackoverflow.com/q/51422672
tags question: http://stackoverflow.com/q/51358457
tags question: http://stackoverflow.com/q/51414290
tags question: http://stackoverflow.com/q/51405186
tags question: http://stackoverflow.com/q/51327011
tags question: http://stackoverflow.com/q/51471937
tags question: http://stackoverflow.com/q/51434957
tags question: http://stackoverflow.com/q/51341385
tags question: http://stackoverflow.com/q/51348903
tags question: http://stackoverflow.com/q/51350172
tags question: http://stackoverflow.com/q/51372910
tags question: http://stackoverflow.com/q/51427146
tags question: http://stackoverflow.com/q/51410608
type: Tag
tags question: http://stackoverflow.com/q/51472284

http://stackoverflow.com/comment/89902062
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51462779
has text: I just checked the code in my local and it is working, upgrade the pillow version to the latest if it is not Also, I updated my answer for PNG images

http://stackoverflow.com/a/53642148
type: Answer
score: 7
upvote count: 7
accepted answer of: http://stackoverflow.com/q/51432323
downvote count: 0
has body: Now you can use Layers to share libraries and code between your Functions. It is possible to base more then one Function on one Layer. You can create a zip file for the Layer pretty much the same way as you can do so for a Function. The only thing will be that all the common packages go to python/lib/python3.7/site-packages directory inside of zip and all your code goes to python directory. So if you have file structure like this: bundle.zip/ python/ common/ __init__.py lib.py Then from your Lambda Function's code you can reference it like this: from common.lib import ...
answers question: http://stackoverflow.com/q/51432323
type: AcceptedAnswer

http://stackoverflow.com/q/51476613
score: 0
answer count: 1
tagged with: python-3.x
has body: In tensorflow estimator I am facing a problem when I tried to working with japanese text. I try to find out it by debugging. The responsible line of code is net = tf.feature_column.input_layer(features, params['feature_columns']) from this line it raise a error and that is ValueError: 'こんにちは' is not a valid scope name I also go through depth of it and finally got the regex in ops.pythat is _VALID_OP_NAME_REGEX = re.compile("^[A-Za-z0-9.][A-Za-z0-9_.\-/]*$") _VALID_SCOPE_NAME_REGEX = re.compile("^[A-Za-z0-9_.\-/]*$") Any suggesstion to skip this or any valid suggestion for feeding any language charecter. Note: It's working fine when I am using English.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51477327
tagged with: python
tagged with: regex
has title: ValueError at scope name in tensorflow estimator
tagged with: tensorflow
type: Question
tagged with: tensorflow-estimator

http://stackoverflow.com/comment/105385981
has text: @MarineGalantin I'm sorry? The question doesn't make any reference to a non integer value. If you need help with a different set up, feel free to open a new question
score: 0
comment on: http://stackoverflow.com/a/51424171
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89893317
type: QuestionComment
comment on: http://stackoverflow.com/q/51462068
score: 0
has text: So how can i push the item_id of the productdetail page im on into the add_to_cart
type: Comment

http://stackoverflow.com/comment/89897170
has text: i dont know but if i remove def create() image will save and i can see it path in db... maybe def upload_to_custom_p is problem ????
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51463249

http://stackoverflow.com/comment/89845655
comment on: http://stackoverflow.com/a/51437753
has text: how to check where pandas is installed?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89759032
has text: define model and attach in admin
type: Comment
comment on: http://stackoverflow.com/q/51393327
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89681242
comment on: http://stackoverflow.com/q/51354097
type: Comment
type: QuestionComment
score: 0
has text: Possible duplicate of [Creating Threads in python](https://stackoverflow.com/questions/2905965/creating-threads-in-python)

http://stackoverflow.com/comment/89825313
comment on: http://stackoverflow.com/a/51427112
has text: Thanks got your approach.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51369080
tagged with: user-interface
has comment: http://stackoverflow.com/comment/89789096
has answer: http://stackoverflow.com/a/51369236
tagged with: tkinter
type: Question
has comment: http://stackoverflow.com/comment/89711546
tagged with: python
has body: I am writing an program for my job where I am working with the Smartsheet API. Here is my code: import smartsheet import logging from tkinter import * token = "API KEY HERE" matt_workspace = 7813091611174788 ss_client = smartsheet.Smartsheet(token) #Matt's workspace ss_client.errors_as_exceptions(True) #for gethering workspaces workspace_response = ss_client.Workspaces.list_workspaces(include_all=True) all_workspaces = workspace_response.data workspaces_name_and_id= [] for x in all_workspaces: workspaces_name_and_id.append(([str(x.name)], x.id)) selected_workspaces = [] def raise_frame(frame): frame.tkraise() #TODO set up UI root import tkinter as tk # python 3 from tkinter import font as tkfont # python 3 def set_selected_workspaces(listbox): for x in listbox.curselection(): selected_workspaces.append(workspaces_name_and_id[x]) return selected_workspaces class WorkspacesPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller label = tk.Label(self, text="Workspace Selection", font=controller.title_font) label.pack(side="top", fill="x", pady=10) wkdirections = tk.Label(self, text = "1. Press the 'gather' button to gather all your available workspaces. \n 2. Select the workspaces with sheets you want to edit from the list. (Holding ctrl selects individual, holding shift selects en masse)") wkdirections.pack(side=RIGHT, anchor=CENTER) WorkspaceList = Listbox(self, selectmode=EXTENDED, width=100, height=50) WorkspaceList.pack(side=LEFT) for x in workspaces_name_and_id: WorkspaceList.insert(END, (x)) button = tk.Button(self, text="Next", command=lambda: [controller.show_frame("FoldersPage"), set_selected_workspaces(WorkspaceList) ,print(selected_workspaces)], padx=20, pady=3) button.place(relx=0.975, rely=0.975, anchor=SE) I removed two classes from this code I included that are not necessary (too keep it less messy than it already is (including the main App/Tk app)). My problem is with the set_selected_workpla…
score: 0
accepted answer: http://stackoverflow.com/a/51369236
answer count: 1
has comment: http://stackoverflow.com/comment/89790024
tagged with: for-loop
has title: My Tkinter button command only runs through the loop once
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89747375

http://stackoverflow.com/q/51328560
has comment: http://stackoverflow.com/comment/89632730
score: 0
tagged with: comparator
answer count: 1
has answer: http://stackoverflow.com/a/51328656
has body: I'm trying to write a custom comparator in Python, that compares two node objects based on the following rules 1. Least frequency 2. Shortest length 3. Lexicographic ordering. Here's my node object class Node: def __init__(self, key: str, value: int): self.key = key self.value = value This is my Comparator class Comparator: def __init__(self, node): self.node = node def __lt__(self, other): if self.node.value &gt; other.value: return True elif len(self.node.key) &gt; len(other.key): return True elif self.node.key &gt; other.key: return True I'm trying to use this Comparator to push node items to a heap, this is my code, frequency_map = Counter(string) for k, v in frequency_map.items(): p = Node(k, v) heapq.heappush(self.heap, Comparator(p)) This throws up the following error, AttributeError: 'Comparator' object has no attribute 'value' What am I doing wrong here?
has comment: http://stackoverflow.com/comment/89632873
tagged with: heap
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89632961
type: Question
has comment: http://stackoverflow.com/comment/89632692
has title: Custom comparator in Python

http://stackoverflow.com/a/51776740
answers question: http://stackoverflow.com/q/51361630
upvote count: 1
has body: A 'dirty hack' workaround, but not so great because you won't know if the user deposits or withdraws while you're changing it, is in your admin.py file on your app. Example: from django.contrib import admin from .models import Transaction, Account @admin.register(Account) class AccountAdmin(admin.ModelAdmin): list_display = ('owner', 'account_number', 'account_balance') list_filter = ('account_balance', 'account_type', 'date_created') list_editable = ['account_balance'] After doing the above the account_balance will then be editable from the admin panel. The downside is if a user had $100 and the admin wanted to take out 50, but the user just tried to spend 60 at the same time. Or even worse: If you load the admin panel and the user has 100, and while your page is unrefreshed, they deposit 5000. Then you decide to take away 50 from the value you see because you didn't refresh it... Now they lose 4950. There are ways to make your own admin panel functions that can update it in real time. Check out how to do that there.
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/89824175
has text: this works.. Thanks.. But I would like to see if there is any other method to use..
type: AnswerComment
comment on: http://stackoverflow.com/a/51423259
score: 0
type: Comment

http://stackoverflow.com/q/51348718
has title: Spyder3 is crashing in Ubuntu 16.04
tagged with: spyder
has comment: http://stackoverflow.com/comment/89675291
type: Question
has body: My spyder 3 is crashing when it is initiated. I tried to uninstall and install again, but it didn't solve the problem: sudo apt remove spyder3 sudo apt-get install spyder3 I am not sure if the problem started when I installed Jupiter in my computer. Anyway, I also removed Jupyter and the problem persists: ProblemType: Crash CrashCounter: 1 CurrentDesktop: Unity Date: Sun Jul 15 09:32:04 2018 ExecutablePath: /usr/bin/spyder3 ExecutableTimestamp: 1455634443 InterpreterPath: /usr/bin/python3.5 ProcCmdline: /usr/bin/python3 /usr/bin/spyder3 ProcCwd: /home/daniel ProcEnviron: PATH=(custom, user) SHELL=/bin/bash LANG=pt_BR.UTF-8 LANGUAGE=pt_BR:pt:en XDG_RUNTIME_DIR=&lt;set&gt; Can you one suggest me how to solve this?
tagged with: python
has comment: http://stackoverflow.com/comment/89672054
has comment: http://stackoverflow.com/comment/89675731
has comment: http://stackoverflow.com/comment/89674038
score: 0
has comment: http://stackoverflow.com/comment/89672076
has comment: http://stackoverflow.com/comment/89675757
has comment: http://stackoverflow.com/comment/89671269
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/51437700
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89864875
type: Answer
has body: Here's a little recipe for a DelaydLogger class that puts all calls to logger's methods into a list instead of actually performing the call, until you finally do a flush where they are all fired up. from functools import partial class DelayedLogger: def __init__(self, logger): self.logger = logger self._call_stack = [] # list of (method, *args, **kwargs) tuples self._delayed_methods = { name : partial(self._delayed_method_proxy, getattr(logger, name)) for name in ["info", "debug", "warning", "error", "critical"] } def __getattr__(self, name): """ Proxy getattr to self.logger, except for self._delayed_methods. """ return self._delayed_methods.get(name, getattr(self.logger, name)) def _delayed_method_proxy(self, method, *args, **kwargs): self._call_stack.append((method, args, kwargs)) def flush(self): """ Flush self._call_stack to the real logger. """ for method, args, kwargs in self._call_stack: method(*args, **kwargs) self._call_stack = [] In your example, you could use it like so: import logging logger = logging.getLogger(__name__) def process_thing(thing, count): dlogger = DelayedLogger(logger) dlogger.info(f'starting processing for thing {count}') # Do some io related stuff dlogger.info(f'finished processing for thing {count}') dlogger.flush() process_thing(None, 10) There may be ways to beautfiy this or make it more compact, but it should get the job done if that's what you really want.
has comment: http://stackoverflow.com/comment/89878714
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89865058
answers question: http://stackoverflow.com/q/51432473
accepted answer of: http://stackoverflow.com/q/51432473

interprocess
tags question: http://stackoverflow.com/q/51350603
type: Tag
tag name: interprocess

http://stackoverflow.com/comment/89725679
score: 1
comment on: http://stackoverflow.com/a/51376683
type: AnswerComment
has text: If I understood correctly, you want that a for a single random number `T` in the `(1, 100)` range, the offset must be set to `15`, and similarly for `T` in the `(1, 10)` range with offset of `5`.
type: Comment

http://stackoverflow.com/q/51361356
has answer: http://stackoverflow.com/a/54367759
favorite count: 0
has comment: http://stackoverflow.com/comment/89702732
tagged with: dask
has title: A comparison between fastparquet and pyarrow?
upvote count: 103
tagged with: python
has answer: http://stackoverflow.com/a/56137860
type: AnsweredQuestion
tagged with: parquet
downvote count: 0
tagged with: pyarrow
has body: After some searching I failed to find a thorough comparison of fastparquet and pyarrow. I found this blog post (a basic comparison of speeds). and a github discussion that claims that files created with fastparquet do not support AWS-athena (btw is it still the case?) when/why would I use one over the other? what are the major advantages and disadvantages ? my specific use case is processing data with dask writing it to s3 and then reading/analyzing it with AWS-athena.
has answer: http://stackoverflow.com/a/51365247
has comment: http://stackoverflow.com/comment/89743498
has answer: http://stackoverflow.com/a/65416856
has comment: http://stackoverflow.com/comment/89747473
type: Question
tagged with: fastparquet
has comment: http://stackoverflow.com/comment/91887461
answer count: 6
possible better answer: http://stackoverflow.com/a/56137860
has answer: http://stackoverflow.com/a/77844771
accepted answer: http://stackoverflow.com/a/77844771
has answer: http://stackoverflow.com/a/57216489
score: 103

http://stackoverflow.com/comment/89860145
comment on: http://stackoverflow.com/a/51444890
score: 0
type: Comment
has text: I believe the range of SMAPE is (0,200) according to your formula. I don't understand the second part of the question -- are you suggesting that the samples are not being split correctly (70 - 30)? https://robjhyndman.com/hyndsight/smape/
type: AnswerComment

http://stackoverflow.com/a/51347249
downvote count: 0
has comment: http://stackoverflow.com/comment/89667345
has body: I think not all the "white" pixels in the image are [255,255,255]. Instead, make a threshold. Try [220,220,220] and above and convert them to [0, 0, 0].
type: Answer
answers question: http://stackoverflow.com/q/51347194
has comment: http://stackoverflow.com/comment/89667279
upvote count: 1
has comment: http://stackoverflow.com/comment/89667168
score: 1
has comment: http://stackoverflow.com/comment/89667487
has comment: http://stackoverflow.com/comment/89667936

http://stackoverflow.com/a/51354083
answers question: http://stackoverflow.com/q/51349893
has body: Instead of traversing the tree two times and joining the node sets, it would be better to do one pass looking for a * wild-card tag name and checking for the tag name via self:: (reference): tree.xpath("//*[self::p or self::title]") Demo: In [1]: from lxml.html import fromstring In [2]: html = """ ...: ...: Paragraph 1 ...: Other info ...: Title 1 ...: ...: Paragraph 2 ...: ...: Title 2 ...: ...: """ In [3]: root = fromstring(html) In [4]: [elm.text_content() for elm in root.xpath("//*[self::p or self::title]")] Out[4]: ['Paragraph 1', 'Title 1', 'Paragraph 2', 'Title 2']
score: 5
type: AcceptedAnswer
downvote count: 0
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/51349893

http://stackoverflow.com/q/51471061
has comment: http://stackoverflow.com/comment/89910410
score: -1
type: Question
has comment: http://stackoverflow.com/comment/89910798
answer count: 2
upvote count: 0
favorite count: 0
has body: Have a quick question. Trying to use a relational model in one DetailView. However, no matter what I try the data does not display. I've tried a few versions of template tags to no avail. html {% for parts in relatedparts %}{{ parts.name }} &lt;/div&gt;{% endfor %} views.py class ErrorCodeView(DetailView): context_object_name = 'error_code_details' model = models.ErrorCodes template_name = 'error_code_details.html' def get_context_data(self, **kwargs): # xxx will be available in the template as the related objects context = super(ErrorCodeView, self).get_context_data(**kwargs) context['relatedparts'] = RelatedParts.objects.filter(name=self.get_object()) return context models.py class ErrorCodes(models.Model): name = models.CharField(max_length=256) description = models.CharField(max_length=400) instructions = models.CharField(max_length=256) PartsNeeded = models.CharField(max_length=120, default='') usercomments = models.CharField(max_length=400, default='', blank=True) relpic = models.ImageField(upload_to='media/',blank=True) relpictwo = models.ImageField(upload_to='media/',blank=True) def __str__(self): return self.name def get_absolute_url(self): return reverse("errorcodes:errorcodeview",kwargs={'name':self.name}) class RelatedParts(models.Model): name = models.CharField(max_length=256) related_error_code = models.ForeignKey(ErrorCodes, on_delete=models.PROTECT) def __str__(self): return self.name
has comment: http://stackoverflow.com/comment/89910663
has answer: http://stackoverflow.com/a/51471508
tagged with: python
has title: Django view with get context not working
has answer: http://stackoverflow.com/a/51473460
type: UnansweredQuestion
tagged with: django
downvote count: 1
has comment: http://stackoverflow.com/comment/89911044

http://stackoverflow.com/a/51343877
answers question: http://stackoverflow.com/q/51343863
score: 2
has comment: http://stackoverflow.com/comment/89661008
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51343863
has comment: http://stackoverflow.com/comment/89661041
has comment: http://stackoverflow.com/comment/89661009
upvote count: 2
type: AcceptedAnswer
type: Answer
has body: That's because your second condition is just a string 'your name.', which is always true. You need to add name != 'your name.' to the second condition: while name != 'your name' or name != 'your name.':

http://stackoverflow.com/comment/89786538
has text: You have to use [`writerow`](https://docs.python.org/2/library/csv.html#csv.csvwriter.writerow) method to write rows to your csv. Also if you have any issues it would be better to update your question with your current code in order to be more easy for me to test it.
type: Comment
comment on: http://stackoverflow.com/a/51407002
score: 0
type: AnswerComment

http://stackoverflow.com/a/51331978
has body: I think that you are trying to get the program to act as a Client or as a Server just changing s.send() to conn.send() saddly it isn't that simple. Socket Initializzation The socket have to be initialized before sending or receiving data. For a client usually it's something like this. send_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # Create the socket send_socket.connect((serverIp, serverPort)) # Connect to the server send_socket.send(data) # Send the data to the server And like this for a Server: listen_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # Create the socket listen_socket.bind(("0.0.0.0", port)) # Set the socket to accept client from every interface on the port port listen_socket.listen(1) # Put the server on listen on the port setted before accept_socket, addr = self.listen_socket.accept() # when a client connect return the socket to talk with it data = self.accept_socket.recv(buffer_size) # Receive data form the client of max size buffer_size Docs examples From your question I guess that with s.send() and conn.send() you are talking about this example from the python 2.7 socket docs Here are four minimal example programs using the TCP/IP protocol: a server that echoes all data that it receives back (servicing only one client), and a client using it. Note that a server must perform the sequence socket(), bind(), listen(), accept() (possibly repeating the accept() to service more than one client), while a client only needs the sequence socket(), connect(). Also note that the server does not sendall()/recv() on the socket it is listening on but on the new socket returned by accept(). Client Echo client program import socket HOST = 'daring.cwi.nl' # The remote host PORT = 50007 # The same port as used by the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) s.sendall('Hello, world') data = s.recv(1024) s.close() print 'Received', repr(data) the client is pretty stright forward, it create the sock…
has comment: http://stackoverflow.com/comment/89639802
type: AcceptedAnswer
downvote count: 0
score: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/51331426
answers question: http://stackoverflow.com/q/51331426
has comment: http://stackoverflow.com/comment/89640297
upvote count: 3

http://stackoverflow.com/comment/89928654
comment on: http://stackoverflow.com/a/51479520
has text: I am getting few errors Unable to read registry value HKLM\SOFTWARE\Policies\Google\Chrome\MachineLevelUserCloudPolicyEnrollmentToken for writing result=2Unable to read registry value HKLM\SOFTWARE\Policies\Google\Chrome\MachineLevelUserCloudPolicyEnrollmentToken for writing result=2 and username = browser.find_element_by_name('LOGIN') #username form field File "C:\python3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 495, in find_element_by_name
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/98018954
has text: Please indicate how this related to the .ply and .pcd formats in question.
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/55665760

http://stackoverflow.com/comment/89641737
type: QuestionComment
has text: Times are `ns`, and depend on the calling details, not on the size of the array. Why should it matter? I rarely use `len(arr)`, since `shape[0]` is much more explicit (to human eyes). We'd have to dig into the `ndarray` code to see the calling sequence `len => .__len__ =>?`, `shape` must be coded as a property, not a pure attribute.
score: 1
comment on: http://stackoverflow.com/q/51332056
type: Comment

http://stackoverflow.com/comment/89769076
type: Comment
score: 3
has text: Do you have any error message with your code?
comment on: http://stackoverflow.com/q/51399077
type: QuestionComment

http://stackoverflow.com/comment/89850079
type: AnswerComment
has text: post your solution instead. It may help someone later.
type: Comment
comment on: http://stackoverflow.com/a/51439976
score: 0

http://stackoverflow.com/comment/89657401
score: 0
type: Comment
type: QuestionComment
has text: @jonrsharpe: isn't the fact that Martin *came from* C and Java somewhat relevant here? I know the switchlessness of Python has been a major headache for me, until I learned to avoid it.
comment on: http://stackoverflow.com/q/51341959

http://stackoverflow.com/comment/89830743
score: 1
comment on: http://stackoverflow.com/a/51429487
type: AnswerComment
has text: This works! I put the function inside the loop and I can do what I needed to. The logic would stay the same whether it is a text file or a json file too
type: Comment

http://stackoverflow.com/comment/89862760
has text: Like this:Traceback (most recent call last): File "C:/Users/Mavi/Desktop/Makale/SplitCSV/Splitted.py", line 5, in <module> your_list = list(reader) File "C:\Users\Mavi\AppData\Local\Programs\Python\Python36\lib\codecs.py", line 321, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 17-18: invalid continuation byte
score: 0
comment on: http://stackoverflow.com/a/51444256
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51481167
has comment: http://stackoverflow.com/comment/89940016
type: Answer
has comment: http://stackoverflow.com/comment/89932513
answers question: http://stackoverflow.com/q/51478869
has comment: http://stackoverflow.com/comment/90017142
has body: the second is missing so the browser doesn't do anything try this: python: if request.method=='POST': input_text=request.form['text'] if request.form['submit']=='Submit': final_result = 'stackoverflow rocks' return render_template('index.html', result=final_result, text=input_text) elif request.form['action']=='addToDataset': f = open('dataset/dataset.tsv', 'a') f.write(input_text) return redirect(url_for('index')) else: render_template('index.html') else: return render_template('index.html') html: Text: {% if result is not none %} {{ result }} Add to dataset Text: {% endif %}
score: 0
has comment: http://stackoverflow.com/comment/89933857

http://stackoverflow.com/a/51333865
type: Answer
has body: Taking that as the footer_copyright you can do: from bs4 import BeautifulSoup import urllib.request as url BeautifulSoup(url.urlopen(masterURL).read()).select("p.footer__copyright")
answers question: http://stackoverflow.com/q/51332185
upvote count: 0
has comment: http://stackoverflow.com/comment/89660525
score: -1
downvote count: 1

http://stackoverflow.com/a/51342282
has comment: http://stackoverflow.com/comment/89659421
has comment: http://stackoverflow.com/comment/89659577
has comment: http://stackoverflow.com/comment/89659509
has comment: http://stackoverflow.com/comment/89659701
type: Answer
has comment: http://stackoverflow.com/comment/89659357
has comment: http://stackoverflow.com/comment/89659842
has comment: http://stackoverflow.com/comment/89660108
score: 0
has body: Please use starts-with in xpath instead of contains. XPath: .//div[starts-with(@id, 'abstract-more')]/p" abstract = paper.find_element_by_xpath(".//div[starts-with(@id, 'abstract-more')]/p").text
answers question: http://stackoverflow.com/q/51342109

sqlalchemy
tags question: http://stackoverflow.com/q/51411651
tags question: http://stackoverflow.com/q/51470200
tags question: http://stackoverflow.com/q/51417786
tags question: http://stackoverflow.com/q/51445521
tags question: http://stackoverflow.com/q/51451427
tags question: http://stackoverflow.com/q/51407143
tags question: http://stackoverflow.com/q/51387359
tags question: http://stackoverflow.com/q/51361689
tags question: http://stackoverflow.com/q/51473487
tags question: http://stackoverflow.com/q/51335298
tags question: http://stackoverflow.com/q/51457187
tags question: http://stackoverflow.com/q/51391771
tags question: http://stackoverflow.com/q/51396560
tags question: http://stackoverflow.com/q/51342994
tags question: http://stackoverflow.com/q/51392243
tags question: http://stackoverflow.com/q/51372450
tags question: http://stackoverflow.com/q/51373771
tags question: http://stackoverflow.com/q/51399227
tags question: http://stackoverflow.com/q/51340466
tags question: http://stackoverflow.com/q/51368774
tags question: http://stackoverflow.com/q/51351063
tags question: http://stackoverflow.com/q/51463507
tags question: http://stackoverflow.com/q/51330300
tags question: http://stackoverflow.com/q/51419186
tags question: http://stackoverflow.com/q/51338728
tags question: http://stackoverflow.com/q/51352179
tag name: sqlalchemy
tags question: http://stackoverflow.com/q/51413299
tags question: http://stackoverflow.com/q/51370752
tags question: http://stackoverflow.com/q/51430390
tags question: http://stackoverflow.com/q/51394334
tags question: http://stackoverflow.com/q/51479279
tags question: http://stackoverflow.com/q/51349136
tags question: http://stackoverflow.com/q/51479511
tags question: http://stackoverflow.com/q/51376652
tags question: http://stackoverflow.com/q/51378773
tags question: http://stackoverflow.com/q/51336349
tags question: http://stackoverflow.com/q/51398090
tags question: http://stackoverflow.com/q/51346000
tags question: http://stackoverflow.com/q/51463912
tags question: http://stackoverflow.com/q/51471599
tags question: http://stackoverflow.com/q/51448741
tags question: http://stackoverflow.com/q/51351280
tags question: http://stackoverflow.com/q/51380749
tags question: http://stackoverflow.com/q/51453417
tags question: http://stackoverflow.com/q/51391039
tags question: http://stackoverflow.com/q/51349184
tags question: http://stackoverflow.com/q/51456539
tags question: http://stackoverflow.com/q/51477961
tags question: http://stackoverflow.com/q/51346083
tags question: http://stackoverflow.com/q/51451768
tags question: http://stackoverflow.com/q/51381424
tags question: http://stackoverflow.com/q/51449258
tags question: http://stackoverflow.com/q/51325583
tags question: http://stackoverflow.com/q/51432962
tags question: http://stackoverflow.com/q/51406836
tags question: http://stackoverflow.com/q/51390141
tags question: http://stackoverflow.com/q/51446322
tags question: http://stackoverflow.com/q/51419417
tags question: http://stackoverflow.com/q/51362902
type: Tag

http://stackoverflow.com/q/51463467
favorite count: 0
has comment: http://stackoverflow.com/comment/89896464
has comment: http://stackoverflow.com/comment/89896064
possible better answer: http://stackoverflow.com/a/51463586
tagged with: python
tagged with: jupyter-notebook
has title: My .txt Files Turn Into Gibberish In Python; How Do I Fix This?
score: 2
type: AnsweredQuestion
downvote count: 0
type: Question
accepted answer: http://stackoverflow.com/a/51463907
has answer: http://stackoverflow.com/a/51463586
upvote count: 2
answer count: 2
linked to: http://stackoverflow.com/q/491921
has answer: http://stackoverflow.com/a/51463907
has body: I've created a program that takes data from a .txt files and uses a series of regular expressions to turn it into useful information that can go into a Pandas Dataframe. When I was testing this program, I was simply copying and pasting bits of the data from the .txt files into variables in Python, rather than uploading the entire .txt files. But now that I've finished all the testing, I can't figure out how to get the .txt files uploaded in a useful way. I tried in both Google Colab and Jupyter Notebook. Here is the code for JN: file1 = open("sample_file.txt","r") file1.readlines() Unfortunately, I get output that looks like gibberish (though might be hexadecimal). 'ÿþG\x00a\x00m\x00e\x00 \x00s\x00t\x00a\x00r\x00t\x00e\x00d\x00 \x00a\x00t\x00:\x00 \x002\x000\x001\x008\x00/\x007\x00/\x002\x001\x00 \x006\x00:\x003\x003\x00:\x001\x004\x00\n' How do I fix this and make it readable so my program will run on it?
tagged with: file-upload

task
type: Tag
tag name: task
tags question: http://stackoverflow.com/q/51379567
tags question: http://stackoverflow.com/q/51376872

http://stackoverflow.com/a/51404222
type: Answer
has comment: http://stackoverflow.com/comment/89782115
score: 1
has comment: http://stackoverflow.com/comment/89780167
upvote count: 1
answers question: http://stackoverflow.com/q/51402943
accepted answer of: http://stackoverflow.com/q/51402943
type: AcceptedAnswer
downvote count: 0
has body: This is what you want to do. Please examine the code carefully. To save the selected variables import tensorflow as tf tf.reset_default_graph() # ============================================================================= # to save # ============================================================================= # create variables v1 = tf.get_variable(name="v1", initializer=[5, 5, 3]) v2 = tf.get_variable(name="v2", initializer=[5, 5, 3]) # initialize variables init_op = tf.global_variables_initializer() # ops to save variable v2 saver = tf.train.Saver({"my_v2": v2}) with tf.Session() as sess: sess.run(init_op) save_path = saver.save(sess, './tf_vars/model.ckpt') print("Model saved in file: %s" % save_path) 'Output': Model saved in file: ./tf_vars/model.ckpt To restore the saved variables # ============================================================================= # to restore # ============================================================================= # Create some variables. v1 = tf.Variable(initial_value=[0, 0, 0], name="v1") v2 = tf.Variable(initial_value=[0, 0, 0], name="v2") # initialize variables init_op = tf.global_variables_initializer() # ops to restore variable v2. saver = tf.train.Saver({"my_v2": v2}) with tf.Session() as sess: sess.run(init_op) # Restore variables from disk. saver.restore(sess, './tf_vars/model.ckpt') print("v1: %s" % v1.eval()) print("v2: %s" % v2.eval()) print("V2 variable restored.") 'Output': v1: [0 0 0] v2: [5 5 3] V2 variable restored.

http://stackoverflow.com/comment/89934886
comment on: http://stackoverflow.com/q/51482260
score: 0
type: Comment
has text: If inside the zip file, for each file stored there is a bit "old/last version", the sort is useless.
type: QuestionComment

http://stackoverflow.com/a/51454926
has body: This will do: edict = {d: sum(b for w, b in combine if w == d) for d in set(dayofweek)} Since you want your dict to be based every day of week that has appeared in split2, or a unique set of them, you can iterate over set(dayofweek), and then for a given day of week, generate the dict key on the day and the value being the sum of births of the day by iterating over combine and matching the day and outputting the births of the day with a generator to sum.
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51454807
answers question: http://stackoverflow.com/q/51454807

printing
tags question: http://stackoverflow.com/q/51449417
tags question: http://stackoverflow.com/q/51433423
tags question: http://stackoverflow.com/q/51455651
tags question: http://stackoverflow.com/q/51458170
tag name: printing
type: Tag
tags question: http://stackoverflow.com/q/51333688

http://stackoverflow.com/q/51353590
has title: ValueError: setting an array element with a sequence numpy
has comment: http://stackoverflow.com/comment/89679762
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89679760
has comment: http://stackoverflow.com/comment/89679767
score: -1
has comment: http://stackoverflow.com/comment/89680406
accepted answer: http://stackoverflow.com/a/51356940
has body: This is my code: X: A numpy array of shape (num_test, D) containing test data dists: A numpy array of shape (num_test, num_train) where dists[i, j] is the Euclidean distance between the ith test point and the jth training point. def compute_distances_two_loops(self, X): num_test = X.shape[0] num_train = self.X_train.shape[0] dists = np.zeros((num_test, num_train)) print(num_test,num_train) for i in range(num_test): for j in range(num_train): dists[i,j] = np.sqrt((np.pow(X[i],2) + np.pow(self.X_train[j],2)) return dists I am getting the following error: ValueError: setting an array element with a sequence
tagged with: numpy
upvote count: 0
answer count: 1
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89679976
tagged with: valueerror
has answer: http://stackoverflow.com/a/51356940
type: AnsweredQuestion

http://stackoverflow.com/q/51343325
has comment: http://stackoverflow.com/comment/89667732
tagged with: python-2.7
answer count: 3
tagged with: mysql-python
tagged with: macos
has title: command 'cc' failed with exit status 1 on OSX High Sierra
has comment: http://stackoverflow.com/comment/89662405
favorite count: 0
possible better answer: http://stackoverflow.com/a/51351548
has comment: http://stackoverflow.com/comment/89660070
upvote count: 5
has comment: http://stackoverflow.com/comment/89676156
has answer: http://stackoverflow.com/a/51741632
has comment: http://stackoverflow.com/comment/89676025
has answer: http://stackoverflow.com/a/51423455
has comment: http://stackoverflow.com/comment/89660089
accepted answer: http://stackoverflow.com/a/51423455
tagged with: python
has comment: http://stackoverflow.com/comment/89660066
has comment: http://stackoverflow.com/comment/89667737
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/89662238
has answer: http://stackoverflow.com/a/51351548
type: Question
score: 5
has body: I'm trying to run on Mac Os high Sierra pip install MySQL-python But I'm getting error: command 'cc' failed with exit status 1 I already tried the solution on this topic, but it didn't work. This is the full error message The directory '/Users/filipeferminiano/Library/Caches/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 directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/Users/filipeferminiano/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. Collecting MySQL-python Downloading https://files.pythonhosted.org/packages/a5/e9/51b544da85a36a68debe7a7091f068d802fc515a3a202652828c73453cad/MySQL-python-1.2.5.zip (108kB) 100% |████████████████████████████████| 112kB 289kB/s Installing collected packages: MySQL-python Running setup.py install for MySQL-python ... error Complete output from command /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python -u -c "import setuptools, tokenize;__file__='/private/tmp/pip-install-8I1X5u/MySQL-python/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /private/tmp/pip-record-z5HohX/install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build/lib.macosx-10.13-intel-2.7 copying _mysql_exceptions.py -&gt; build/lib.macosx-10.13-intel-2.7 creating build/lib.macosx-10.13-intel-2.7/MySQLdb copying MySQLdb/__init__.py -&gt; build/lib.macosx-10.13-intel-2.7/MySQLdb copying MySQLdb/converters.py -&gt; build/lib.macosx-10.13-intel-2.7/MySQLdb copying MySQLdb/connections.py -&gt; build/lib.macosx-10.13-intel-2.7/MySQLdb…
linked to: http://stackoverflow.com/q/22697440

http://stackoverflow.com/q/51362044
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51362304
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: pivot-table
has title: pandas : categorical column bugs pivot_table
tagged with: python
has answer: http://stackoverflow.com/a/51362304
upvote count: 1
answer count: 1
has body: Making a column categorical makes pivot_table unstable. Here an example : test = pd.DataFrame({'closing_mois': {6483: 'juillet', 19771: 'avril', 19105: 'avril', 8025: 'novembre', 22642: 'mai', 1216: 'juillet', 21634: 'décembre', 19230: 'décembre', 11429: 'décembre', 24755: 'juin'}, 'closing_week': {6483: 28, 19771: 16, 19105: 16, 8025: 48, 22642: 20, 1216: 31, 21634: 49, 19230: 49, 11429: 52, 24755: 25}, 'montant': {6483: 15830, 19771: 13637, 19105: 28197, 8025: 42671, 22642: 41290, 1216: 575, 21634: 898, 19230: 13814, 11429: 2006, 24755: 40633}}) test gives : closing_mois closing_week montant 1216 juillet 31 575 6483 juillet 28 15830 8025 novembre 48 42671 11429 décembre 52 2006 19105 avril 16 28197 19230 décembre 49 13814 19771 avril 16 13637 21634 décembre 49 898 22642 mai 20 41290 24755 juin 25 40633 And we have the correct groupby : test.groupby(["closing_mois", "closing_week"])["montant"].sum() closing_mois closing_week avril 16 41834 décembre 49 14712 52 2006 juillet 28 15830 31 575 juin 25 40633 mai 20 41290 novembre 48 42671 Name: montant, dtype: int64 But if I make the months categorical : mois = OrderedDict({1:"janvier", 2:"février", 3:"mars", 4:"avril", 5: "mai", 6:"juin", 7:"juillet", 8:"août", 9:"septembre", 10:"octobre", 11:"novembre", 12:"décembre"}) cat = pd.Categorical(list(mois.values()), ordered=True) test.closing_mois = test.closing_mois.astype(cat) I have an uncorrect pivot table : the months and values are not aligned : test.pivot_table(index="closing_mois", columns="closing_week", values="montant", aggfunc=pd.Series.sum) closing_week 16 20 25 28 31 48 49 52 closing_mois juillet 41834.0 NaN NaN NaN NaN NaN NaN NaN novembre NaN NaN NaN NaN NaN NaN 14712.0 2006.0 décembre NaN NaN NaN 15830.0 575.0 NaN NaN NaN avril NaN NaN 40633.0 NaN NaN NaN NaN NaN mai NaN 41290.0 NaN NaN NaN NaN NaN NaN juin NaN NaN NaN NaN NaN 42671.0 NaN NaN So here I have week 52 aligned with november instead of december. What do I do wrong ??? Edit Trying : mois = Ordered…

http://stackoverflow.com/q/51408678
has comment: http://stackoverflow.com/comment/89790729
tagged with: subprocess
has comment: http://stackoverflow.com/comment/89795442
has body: I am trying to create a python script which uses subprocess module to connect to database in a database server and do administrative activity on connected database. This is the sample script which i am trying to from subprocess import Popen , PIPE p = Popen(['cmd'], stdin=PIPE ,stdout = PIPE, stderr=PIPE) p.stdin.write(b'ipconfig\n') # write to stdin print (p.stdout.read()) # read stdout p.stdin.write(b'sqlplus sys/sys@orcl as sysdba\n') print (p.stdout.read()) p.stdin.write(b'shutdown immediate\n') print (p.stdout.read()) p.stdin.write(b'startup\n') print (p.stdout.read()) After every input i need to check the output to ensure there isn't any error. For any output or error a proper msg needs to be propagated back to the user or the calling program. The above script gets hanged may be after the first stdout.read thing. I checked various similar questions and articles but none of what i read provided something which works. Please let me know what can i do here.
type: Question
has comment: http://stackoverflow.com/comment/89790471
score: 0
upvote count: 1
tagged with: windows
downvote count: 1
favorite count: 0
has title: python subprocess provide input and read output multiple times [windows]
tagged with: blocking
answer count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/51470339
accepted answer of: http://stackoverflow.com/q/51470218
has comment: http://stackoverflow.com/comment/89923638
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51470218
has comment: http://stackoverflow.com/comment/89909014
upvote count: 1
has body: You may set date as the index and then sort dataframe based on the index but before that use CategoricalIndex as: df.index = pd.CategoricalIndex(df.index, categories=['Jan', 'Feb', 'Mar', 'Apr','May','Jun', 'Jul', 'Aug','Sep', 'Oct', 'Nov', 'Dec'], sorted=True) Adding to it; I did not know there is a Categorical function in Pandas as well as the CategoricalIndex. You may use it as well, refer to https://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.Categorical.html#pandas.Categorical
downvote count: 0
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/89908984
has comment: http://stackoverflow.com/comment/89909070

dicom
tag name: dicom
type: Tag
tags question: http://stackoverflow.com/q/51415024
tags question: http://stackoverflow.com/q/51446174

http://stackoverflow.com/q/51481066
downvote count: 2
type: Question
has answer: http://stackoverflow.com/a/51482706
has body: I have a list of strings, some of them are containing numbers. for instance: abc123 def3464 hello32 goodbye64 some numbers 1254324 I want to clean up all numbers in those strings, but keep specific numbers, such as 32 and 64, so the clean up will return this: abc def hello32 goodbye64 some numbers Note, that in the first example (def3464) the number 64 exists, but not alone, therefore it should be eliminated. Any ideas?
answer count: 2
favorite count: 0
possible better answer: http://stackoverflow.com/a/51481112
accepted answer: http://stackoverflow.com/a/51482706
has answer: http://stackoverflow.com/a/51481112
has title: How to replace all numbers, except specific numbers in python?
tagged with: python
tagged with: regex
type: AnsweredQuestion
upvote count: 3
score: 1

http://stackoverflow.com/q/51372775
has body: The program I'm writing is to "sell" seats in a theater after creating the seats as a 5 row 5 column two dimensional list. I've gotten it to work for the most part but if I choose a seat next to one that has been marked as sold, I get the message as if that seat was sold as well. Here is the criteria I am working with: Fill a 5 x 5 grid. Then do the following. Create a loop that will continue until the user says (Y/N) they want to quit, or all 25 seats are sold. Have the users ask for a seat position based on row and column (row, column) - remember that the list’s positions start at 0, but the user will ask for the seat starting at row or column position 1. Then when the user selects the seat, print out the user's price and mark an 'SS' (sold seat) in the List where the price was. Then print out all the seats so the user can select another. When the next user in the loop, asks for a seat make sure you check and see if that seat is already sold (has an ‘SS’ in the table). If it is sold, tell the user – otherwise return the price and mark the seat sold. After the user asks to quit or all the seats are sold, or the loop ends, then printout the list as shown below - showing the sold seats (SS) and unsold seats (the unsold seat should still have a price). And here is my Code: def main(): seatList = [ [50,50,50,50,50], [40,45,45,45,40], [30,35,35,35,30], [20,20,20,20,20], [10,10,10,10,10], ] cont = "y" while cont.lower() == "y": print("Here is the seating arrangement:") availableSeat = seatPrinter(seatList) totalRow = int(len(seatList)) - 1 totalColumn = int(len(seatList[0])) - 1 seatRow = int(input("Please enter a row number (1 to %d):"%totalRow)) seatColumn = int(input("Please enter a seat number (1 to %d):"%totalColumn)) seatStatus = seatAvailable(seatList, seatRow, seatColumn) cont = input("Would you like to reserve another seat?(Y/N)") def seatPrinter(seats): for i in range(len(seats[0])): print(seats[i]) def seatAvailable(seats, row, column): for i in range(len(seat…
tagged with: multidimensional-array
accepted answer: http://stackoverflow.com/a/51373004
has comment: http://stackoverflow.com/comment/89717357
tagged with: python
tagged with: python-3.x
has title: Altering more than one value in a two dimentional list with loops
upvote count: 1
type: Question
type: AnsweredQuestion
tagged with: list
score: 1
has answer: http://stackoverflow.com/a/51373004
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89717754
favorite count: 0

http://stackoverflow.com/comment/89654244
type: Comment
score: 0
has text: one way is to store it as `default_sysout` before assigning to `outfile` and then assign it back using `default_sysout` after outfile is closed, but just in case I didn't where can I get it?
type: QuestionComment
comment on: http://stackoverflow.com/q/51340347

http://stackoverflow.com/comment/89664835
score: 1
has text: In case it's not obvious, quoting the argument `-p "21, 22, 80"` would also work around the problem.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51344943

http://stackoverflow.com/comment/90025507
has text: `!pip install mayavi` throws error after the dependencies are installed. Details are updated in the main description.
comment on: http://stackoverflow.com/a/51435316
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89889276
type: AnswerComment
type: Comment
score: 1
has text: You need to run in a directory you can write to.
comment on: http://stackoverflow.com/a/51459622

http://stackoverflow.com/q/51423766
upvote count: 6
has answer: http://stackoverflow.com/a/51424171
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89819232
type: Question
accepted answer: http://stackoverflow.com/a/51424171
answer count: 2
has title: Pandas adding scalar value to numeric column?
tagged with: pandas
has comment: http://stackoverflow.com/comment/89818588
downvote count: 0
has body: Given a dataframe like this ImageId | Width | Height | lb0 | x0 | y0 | lb1 | x1 | y1 | lb2 | x2 | y2 0 abc | 200 | 500 | ijk | 115| 8 | zyx | 15 | 16 | www | 23 | 42 1 def | 300 | 800 | ijk | 91 | 23 | zyx | 16 | 15 | www | 8 | 4 2 ghi | 700 | 400 | ijk | 230| 16 | zyx | 17 | 24 | www | 43 | 109 3 jkl | 500 | 100 | ijk | 46 | 23 | | | | | | ... When I try to add to a column with df['x0'] = df['x0'] + 1 I now get column x0 as follows: 151 127 266 82 Question: How do I add a scalar value to a whole column in Pandas?
favorite count: 0
possible better answer: http://stackoverflow.com/a/51423881
has answer: http://stackoverflow.com/a/51423881
score: 6
tagged with: python

http://stackoverflow.com/q/51464744
tagged with: floating-point
type: Question
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/89898212
linked to: http://stackoverflow.com/q/47738537
upvote count: 1
answer count: 1
tagged with: string
favorite count: 0
tagged with: type-conversion
has answer: http://stackoverflow.com/a/51464813
accepted answer: http://stackoverflow.com/a/51464813
tagged with: python
has body: I am getting this error "TypeError: 'str' object is not callable" when i am trying to convert a str to float inorder to do summation. # To Find sum of no. s seperated by commas in a string t='' y='' z="" s = "1.23,2.4,3.123" for x in s: if x != ',': y += x else: t = z z = y y = '' print("y=",y,"z=",z,"t=",t) y = float(y) z = float(z) t = float(t) print("Sum is =",y+z+t) Screenshot of the error occurring when i run the code
has title: Cant convert str to float in python 3.6
has comment: http://stackoverflow.com/comment/89898211
tagged with: python-3.x
downvote count: 0

http://stackoverflow.com/a/51422882
type: Answer
has body: You can also return your inner function and call it from outside. For your current example, it might be an overkill. But this technique will surely be helpful when you get deeper into decorators. def foo(): print('hello from initial foo') def using_foo(): foo() def wrapper(func): def foo(): print('Now is overload foo') print('Hello from wrapper') return foo using_foo() call_inner_foo = wrapper(using_foo) call_inner_foo()
score: 0
answers question: http://stackoverflow.com/q/51422537

http://stackoverflow.com/a/51330316
score: 0
type: Answer
has body: Try using recursion: I believe you are looking for something like this: from random import randint as ri MAX_DICE_NUMBER = 20 def roll_dice(): attempt = ri(1, MAX_DICE_NUMBER) if attempt == MAX_DICE_NUMBER: return attempt + roll_dice() else: return attempt def action_roll_script(attribute): print("You got a " + attribute + " roll of " + str(roll_dice()) + "!") action_roll_script('power') &gt;&gt;&gt; You got a power roll of 16! I didn't understand why you needed score though... But this piece still might be useful :)
has comment: http://stackoverflow.com/comment/89714797
has comment: http://stackoverflow.com/comment/89698716
answers question: http://stackoverflow.com/q/51330174

http://stackoverflow.com/a/51476325
upvote count: 110
type: AcceptedAnswer
score: 110
accepted answer of: http://stackoverflow.com/q/51476300
type: Answer
answers question: http://stackoverflow.com/q/51476300
has comment: http://stackoverflow.com/comment/90006446
has comment: http://stackoverflow.com/comment/89921435
has comment: http://stackoverflow.com/comment/90141100
downvote count: 0
has body: First point in the release notes: Switch to a Calendar based versioning scheme. https://pip.pypa.io/en/stable/news/ More about calendar versioning: https://calver.org/

http://stackoverflow.com/comment/89697685
comment on: http://stackoverflow.com/q/51360562
has text: That looks very much like there is an active formatter somewhere in your execution context that tries to replace a placeholder named `context`. The following should show you all active format strings: `lgrs = {'root': logging.getLogger('')}`, `lgrs.update(logging.Logger.manager.loggerDict)`, `print("\n".join(["logger: {}, format:{}".format(n[0], n[1]) for n in[(k, [h.formatter._fmt for h in v.handlers if h.formatter is not None]) for k,v in lgrs.items()]]))`. Maybe this helps finding out which logger uses it and where it is configured.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89695436
type: Comment
has text: My bad, went too fast. You need to add python as your first argument to your subprocess call.
comment on: http://stackoverflow.com/a/51361391
type: AnswerComment
score: 0

http://stackoverflow.com/a/51432588
accepted answer of: http://stackoverflow.com/q/51431017
answers question: http://stackoverflow.com/q/51431017
type: AcceptedAnswer
type: Answer
has body: You are probably better off with using the pandas-module to load the content of the .txt into a pandas DataFrame and proceed from there. If you're unfamiliar with it...a DataFrame is as close to an Excelsheet as it can get with Python. pandas will handle reading the lines for you so you don't have to write your own loop. Assuming your textfile is four column, tab-separated, this would look like: # IPython for demo: import pandas as pd df = pd.read_csv('ballet.txt', sep='\t', header=None, names=['artists', 'tracks'], usecols=[2, 3]) # usecols here limits the Dataframe to only consist the 3rd and 4th column of your .txt Your DataFrame then could look like: df # Out: artists tracks 0 Spandau Ballet Through The Barricades 1 Berlin Ballet Swan Lake Access single columns by column names: df.artists # or by their index e.g. df.iloc[:, 0] # Out: 0 Spandau Ballet 1 Berlin Ballet Name: 2, dtype: object You can still put the data into an array at this point, but I can't think of a reason you really wanna do this if you're aware of the alternatives.
has comment: http://stackoverflow.com/comment/89873410
has comment: http://stackoverflow.com/comment/89873402
score: 0

http://stackoverflow.com/q/51411379
has comment: http://stackoverflow.com/comment/89897186
type: Question
has title: The result of the code is always 0
has comment: http://stackoverflow.com/comment/89794545
has body: Could anyone help please? The result of the code keeps showing 0. Where I went wrong? Thanks. import math def m_t(r_w,r_l,t_w,t_l): a = r_w/t_w b = r_l/t_l c = math.ceil(a) d = math.ceil(b) if isinstance(a,int) &amp; isinstance(b,int): return a*b elif isinstance(a,int) &amp; isinstance(b,float): return a*d elif isinstance(a,float) &amp; isinstance(b,int): return c*b else: return c*d m_t(4,4,2,2)
has comment: http://stackoverflow.com/comment/89794378
score: 0
has comment: http://stackoverflow.com/comment/89794393
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89794400
has comment: http://stackoverflow.com/comment/89794428

http://stackoverflow.com/comment/89880250
has text: Can you post an example of the current output and your expected output?
type: QuestionComment
comment on: http://stackoverflow.com/q/51455408
score: 1
type: Comment

http://stackoverflow.com/a/51452369
has body: I agree with @andrew_reece but if you want the data to be in a string do this: df = """ id,prescriber_last_name,prescriber_first_name,drug_name,drug_cost 1000000001,Smith,James,AMBIEN,100 1000000002,Garcia,Maria,AMBIEN,200 1000000003,Johnson,James,CHLORPROMAZINE,1000 1000000004,Rodriguez,Maria,CHLORPROMAZINE,2000 1000000005,Smith,David,BENZTROPINE MESYLATE,1500 """ import sys if sys.version_info[0] &lt; 3: from StringIO import StringIO else: from io import StringIO import pandas as pd TESTDATA = StringIO(df) df = pd.read_csv(TESTDATA) print(df.groupby("drug_name").drug_cost.agg(["count", "sum"])) Output: count sum drug_name AMBIEN 2 300 BENZTROPINE MESYLATE 1 1500 CHLORPROMAZINE 2 3000 Another way like @andrew_reece sad in the comments is to copy the data string then do: import pandas df = pd.read_clipboard() df=df.groupby("drug_name").drug_cost.agg(["count", "sum"]) df.to_csv(filename)
upvote count: 1
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51452279

http://stackoverflow.com/comment/89730873
score: 0
comment on: http://stackoverflow.com/q/51379723
type: Comment
type: QuestionComment
has text: Nevertheless if the only thing you add is a profile, you probably better do it in reverse: add a one-to-one field that refers to `User` in `Profile`.

http://stackoverflow.com/a/51438271
has comment: http://stackoverflow.com/comment/89852947
answers question: http://stackoverflow.com/q/51435117
has comment: http://stackoverflow.com/comment/89848517
has comment: http://stackoverflow.com/comment/89852673
has comment: http://stackoverflow.com/comment/89852815
has comment: http://stackoverflow.com/comment/89852768
has body: I tried to replicate your problem with the following model as I do not have access to the model file that you are using: from keras.applications.xception import Xception new_xception = Xception() I can make requests to this model without issues (python 3.6.4, tf 1.8.0, keras 2.2.0). What version of TF-serving are you using?
has comment: http://stackoverflow.com/comment/89885607
score: 0
has comment: http://stackoverflow.com/comment/89885461
type: Answer

http://stackoverflow.com/a/51388694
answers question: http://stackoverflow.com/q/51388565
score: 0
has body: You need to create a copy of the list, rather use the same instance in each append, e.g.: list1=[0,1,2] mega_list=[] for x in range(5): mega_list.append(list1[:]) list1.pop(0) list1.insert(2,list1[1]+1) print(mega_list) # [[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]] An alternative, is just use indexes into a full list of the input values, e.g.: list1=list(range(7)) # [0,1,2,3,4,5,6] mega_list=[] for i in range(len(list1)-3+1): mega_list.append(list1[i:i+3]) print(mega_list) # [[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]] One alternative is to create a generalized nwise() function using itertools: import itertools as it def nwise(iterable, n): ts = it.tee(list1, n) for c, t in enumerate(ts): next(it.islice(t, c, c), None) return zip(*ts) list1 = list(range(7)) mega_list = [x for x in nwise(list1, 3)] print(mega_list) # [(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)]
type: Answer

http://stackoverflow.com/q/51449704
type: Question
has comment: http://stackoverflow.com/comment/89869873
has comment: http://stackoverflow.com/comment/89870347
has body: I have a long measurement being written to a text file using Python. Is it safe to open the file in Notepad while my script is running?
upvote count: 2
score: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/89869956
tagged with: io
answer count: 1
favorite count: 0
type: UnansweredQuestion
has title: Safe to open file in text editor while writing to it in Python?
tagged with: python
has comment: http://stackoverflow.com/comment/89869918
has comment: http://stackoverflow.com/comment/89869932
has answer: http://stackoverflow.com/a/51449835
tagged with: file

python-requests
tags question: http://stackoverflow.com/q/51464939
tags question: http://stackoverflow.com/q/51393699
tags question: http://stackoverflow.com/q/51349340
tags question: http://stackoverflow.com/q/51367750
tags question: http://stackoverflow.com/q/51351472
tags question: http://stackoverflow.com/q/51368113
tags question: http://stackoverflow.com/q/51381692
type: Tag
tags question: http://stackoverflow.com/q/51431205
tags question: http://stackoverflow.com/q/51407885
tags question: http://stackoverflow.com/q/51374189
tags question: http://stackoverflow.com/q/51476961
tags question: http://stackoverflow.com/q/51325551
tags question: http://stackoverflow.com/q/51329757
tags question: http://stackoverflow.com/q/51391833
tags question: http://stackoverflow.com/q/51451760
tags question: http://stackoverflow.com/q/51343702
tags question: http://stackoverflow.com/q/51444908
tags question: http://stackoverflow.com/q/51343217
tags question: http://stackoverflow.com/q/51330656
tags question: http://stackoverflow.com/q/51381777
tags question: http://stackoverflow.com/q/51398543
tags question: http://stackoverflow.com/q/51369056
tags question: http://stackoverflow.com/q/51343313
tags question: http://stackoverflow.com/q/51365642
tags question: http://stackoverflow.com/q/51451464
tags question: http://stackoverflow.com/q/51412225
tags question: http://stackoverflow.com/q/51328884
tags question: http://stackoverflow.com/q/51372510
tags question: http://stackoverflow.com/q/51404369
tags question: http://stackoverflow.com/q/51426026
tags question: http://stackoverflow.com/q/51414752
tags question: http://stackoverflow.com/q/51459087
tags question: http://stackoverflow.com/q/51419625
tag name: python-requests
tags question: http://stackoverflow.com/q/51462743
tags question: http://stackoverflow.com/q/51372698
tags question: http://stackoverflow.com/q/51336103
tags question: http://stackoverflow.com/q/51351443
tags question: http://stackoverflow.com/q/51348075
tags question: http://stackoverflow.com/q/51383864
tags question: http://stackoverflow.com/q/51473693
tags question: http://stackoverflow.com/q/51400941
tags question: http://stackoverflow.com/q/51329509
tags question: http://stackoverflow.com/q/51412854
tags question: http://stackoverflow.com/q/51381302
tags question: http://stackoverflow.com/q/51455383
tags question: http://stackoverflow.com/q/51380295
tags question: http://stackoverflow.com/q/51481273
tags question: http://stackoverflow.com/q/51405658
tags question: http://stackoverflow.com/q/51391618
tags question: http://stackoverflow.com/q/51431392
tags question: http://stackoverflow.com/q/51423255

http://stackoverflow.com/comment/89820450
has text: If it can be useful if I reduce the number of queries in the list (from 30 to less than 10), then sometimes the script works... however, I would like to run the script with a list of 100 queries and unfortunately it does not work
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51421807
type: QuestionComment

http://stackoverflow.com/comment/89881009
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51455765
has text: Why do you want to do that ?

http://stackoverflow.com/q/51442423
downvote count: 0
score: 1
linked to: http://stackoverflow.com/q/34089436
type: Question
has answer: http://stackoverflow.com/a/51449086
has body: I have tried relentlessly to create a succesfull file upload from my JAVA/Android project to Django/Python backend. The file I am trying to upload is a wav audio file which is stored on the phone. I am trying to mix two sets of code. The Android code I am using is the one taken from: How to upload a WAV file using URLConnection. public class curlAudioToWatson extends AsyncTask&lt;String, Void, String&gt; { String asrJsonString=""; @Override protected String doInBackground(String... params) { String result = ""; try { Log.d("Msg","**** UPLOADING .WAV to ASR..."); URL obj = new URL(ASR_URL); HttpURLConnection conn = (HttpURLConnection) obj.openConnection(); //conn.setRequestProperty("X-Arg", "AccessKey=3fvfg985-2830-07ce-e998-4e74df"); conn.setRequestProperty("Content-Type", "audio/wav"); conn.setRequestProperty("enctype", "multipart/form-data"); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); String wavpath=mRcordFilePath; File wavfile = new File(wavpath); boolean success = true; if (wavfile.exists()) { Log.d("Msg","**** audio.wav DETECTED: "+wavfile); } else{ Log.d("Msg","**** audio.wav MISSING: " +wavfile); } String charset="UTF-8"; String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value. String CRLF = "\r\n"; // Line separator required by multipart/form-data. OutputStream output=null; PrintWriter writer=null; try { output = conn.getOutputStream(); writer = new PrintWriter(new OutputStreamWriter(output, charset), true); byte [] music=new byte[(int) wavfile.length()];//size &amp; length of the file InputStream is = new FileInputStream (wavfile); BufferedInputStream bis = new BufferedInputStream (is, 16000); DataInputStream dis = new DataInputStream (bis); // Create a DataInputStream to read the audio data from the saved file int i = 0; copyStream(dis,output); } catch(Exception e){ } conn.connect(); int responseCode = conn.getResponseCode(); Log.d("Msg","POST Response Code : " + responseC…
has title: Android Java file upload to Django backend
upvote count: 1
answer count: 1
tagged with: file-upload
tagged with: httpurlconnection
favorite count: 0
linked to: http://stackoverflow.com/q/4966910
type: UnansweredQuestion
tagged with: android
tagged with: django
tagged with: python

http://stackoverflow.com/comment/89871466
comment on: http://stackoverflow.com/q/51450526
has text: Did you make any code so far?
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/89732677
has text: Thanks for your help! For this example it works, but is there a way to expand it to a bigger example? I have a list with many different values instead of A, B and C and want to know, which of these keys contain the value 1 AND 2 (at the same time) in column B
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51380449
type: Comment

http://stackoverflow.com/a/51397362
downvote count: 0
type: AcceptedAnswer
upvote count: 3
has comment: http://stackoverflow.com/comment/89769673
type: Answer
has comment: http://stackoverflow.com/comment/89767791
has body: Does something like this work? import sys import glob import os from Bio import SeqIO file = sys.argv[1] output_extension = sys.argv[2] for f in glob.glob(file): filename, file_extension = os.path.splitext(f) outputfile = f.replace(file_extension, output_extension) with open(f, "rb") as input_handle: with open(outputfile, "w") as output_handle: sequences = SeqIO.parse(input_handle, "abi") count = SeqIO.write(sequences, output_handle, "fasta") print("Converted %i records" % count) You can call it like this: python converter.py '*.ab1' .fas
accepted answer of: http://stackoverflow.com/q/51397234
answers question: http://stackoverflow.com/q/51397234
has comment: http://stackoverflow.com/comment/89769904
score: 3

http://stackoverflow.com/a/74354202
has body: Generally, I like to leave the original command-line (argv) alone and work on a copy. That way, I can always see the original. Perhaps I want to compare what the user actually typed out with what I filled in later from environment variables, default values, or whatever. That's pretty handy while tracking down a problem. Consider the case where you are using argparse. The particular library isn't important and this is a good practice for just about anything. Instead of relying on a default source, such as sys.argv, always supply it. In this incomplete example, main() takes a list that you supply. That can be from sys.argv or whatever list you like. That's pretty handy for testing as you supply different lists to check various scenarios. This decoupling gives you quite a bit of flexibility: def main(options): parsed_args = process_args(options) ... rest of program ... def process_args(options): ...do stuff to fix up options, like enable things by env vars... parser = argparse.ArgumentParser(...) parser.add_argument(...) parsed_args = parser.parse_args(options) # argument instead of default ...fix up parsed_args for whatever you want to add... return parsed_args if __name__ == &quot;__main__&quot;: main(sys.argv[1:]) # remember the program name is the first item Magic or default variables are nice for quick and dirty things, but those generally constrain you too much for larger projects where consumers might want to do things you hadn't considered. Remember, Pythonic code likes to be explicit rather than implicit (yet, so many opportunities in core to be implicit!).
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51472873

http://stackoverflow.com/q/51469627
has answer: http://stackoverflow.com/a/51469812
tagged with: python
has title: Should a python file always include a class?
type: AnsweredQuestion
has body: I have been coding in python for a couple months now, and something has always been on my mind. I know you can have classes in your .py file, but you don't have to. My question is, is it good practice to always have your code in a class, or is it not necessary? FYI: I have been coding in Java for a few years, so I'm used to always having a "main" class and a main method that runs everything.
score: 1
tagged with: java
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51469812
downvote count: 0
has comment: http://stackoverflow.com/comment/89907619
tagged with: class
has comment: http://stackoverflow.com/comment/89907602
answer count: 1
tagged with: compilationunit
favorite count: 0

http://stackoverflow.com/comment/89715414
type: QuestionComment
score: 1
has text: If you look at [the docs](https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool.map), `map` explicitly gives you the outputs in order of the inputs, but there are variants like `map_async` and `imap_unordered` that do different things, and probably one of them does exactly what you want here.
comment on: http://stackoverflow.com/q/51371585
type: Comment

http://stackoverflow.com/a/77074572
has body: For the moment I am stuck on an old version of pandas. My task was to read a csv with "__" delimiters, clean it to remove personal identifying information, and write the results a new file. I need the result to have the same two-character delimiter. My preferred solution would have been to convert to numpy and save, like this: df = pandas.read_csv("patient_patient-final.txt", sep="__", engine="python") # remove personal identifying info from dataframe massaged = df.drop(['paternal_last', 'maternal_last', 'first', 'middle', 'suffix', 'prefix', 'street1', 'street2', 'phone1', 'phone2', 'email', 'emergencyfullname', 'emergencyphone', 'emergencyemail', 'curp', 'oldid'], axis=1) np_data = massaged.to_numpy() np.savetxt("patient_massaged.txt", np_data, fmt="%s", delimiter="__") However, to_numpy() isn't supported in the version of Pandas I have. So, my fix was to generate a csv with "}" as a temp delimiter, save that to a variable, do a string replace, and write the file myself: df = pandas.read_csv("patient_patient-final.txt", sep="__", engine="python") # remove personal identifying info from dataframe massaged = df.drop(['paternal_last', 'maternal_last', 'first', 'middle', 'suffix', 'prefix', 'street1', 'street2', 'phone1', 'phone2', 'email', 'emergencyfullname', 'emergencyphone', 'emergencyemail', 'curp', 'oldid'], axis=1) x = massaged.to_csv(sep="}", header=False, index=False) x = x.replace("}", "__") f=open("patient_massaged.txt", "w") f.write(x) f.close()
score: 0
answers question: http://stackoverflow.com/q/51328454
type: Answer

http://stackoverflow.com/comment/89676033
has text: @IonicSolutions Ah thank you, that solves the problem.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51351059

http://stackoverflow.com/comment/89771496
score: 0
has text: @RaymondNijland nop , here we have some values that is inserted from csv
comment on: http://stackoverflow.com/q/51400332
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51360683
upvote count: 3
tagged with: django
tagged with: python
tagged with: tesseract
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/89693669
has comment: http://stackoverflow.com/comment/89693955
has comment: http://stackoverflow.com/comment/89694464
has comment: http://stackoverflow.com/comment/89693455
type: Question
has comment: http://stackoverflow.com/comment/89694214
has title: No OCR tool found in python
has answer: http://stackoverflow.com/a/51452631
downvote count: 0
accepted answer: http://stackoverflow.com/a/51452631
answer count: 1
has comment: http://stackoverflow.com/comment/89693737
favorite count: 0
has body: I have downloaded Mayan EDMS-Electronic Document Management System from GitHub and I configured project using Django server. I had added the required libraries based on requirement. Now the project runs with error ocr.exceptions.OCRError: No OCR tool found When I searched this error, I found Pyocr looks for the OCR tools (Tesseract, Cuneiform, etc) installed on your system and just tells you what it has found. Then I tried to install tesseract using the command -->pip install tesseract-ocr. I got this error Requirement already satisfied: cython in ./venv2/lib/python2.7/site-packages (from tesseract-ocr) (0.28.4) running bdist_wheel running build running build_py file tesseract_ocr.py (for module tesseract_ocr) not found file tesseract_ocr.py (for module tesseract_ocr) not found running build_ext building 'tesseract_ocr' extension creating build creating build/temp.linux-x86_64-2.7 x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fdebug-prefix-map=/build/python2.7-l1RrwO/python2.7-2.7.14=. -fstack-protector-strong -Wformat -Werror=format-security -fPIC -I/usr/include/python2.7 -c tesseract_ocr.cpp -o build/temp.linux-x86_64-2.7/tesseract_ocr.o cc1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for C/ObjC but not for C++ tesseract_ocr.cpp:600:10: fatal error: leptonica/allheaders.h: No such file or directory #include "leptonica/allheaders.h" please help me to solve this issue. Thanks in advance.
has comment: http://stackoverflow.com/comment/89693799

http://stackoverflow.com/a/51388187
has comment: http://stackoverflow.com/comment/89748826
has comment: http://stackoverflow.com/comment/89748554
has comment: http://stackoverflow.com/comment/89748794
type: Answer
downvote count: 0
has body: You tables is not created... Run makemigrations to check if exist any migrations to be applied python manage.py makemigrations And then run migrate to apply all your migrations in your database python manage.py migrate EDIT How many databases you use? this error is throwed by sqlite too, are you using sqlite in your settings and your tests?
has comment: http://stackoverflow.com/comment/89748709
answers question: http://stackoverflow.com/q/51388089
has comment: http://stackoverflow.com/comment/89748267
has comment: http://stackoverflow.com/comment/89748563
has comment: http://stackoverflow.com/comment/89748505
score: 1
has comment: http://stackoverflow.com/comment/89748282
upvote count: 1

http://stackoverflow.com/a/66601730
answers question: http://stackoverflow.com/q/51359783
downvote count: 0
type: Answer
score: 1
upvote count: 1
has body: I tried with BFS approach, where I'm storing (parent,val) in queue only if val is dict type. def flattern_json(d): if len(d) == 0: return {} from collections import deque q = deque() res = dict() for key, val in d.items(): # This loop push the top most keys and values into queue. if not isinstance(val, dict): # If it's not dict if isinstance(val, list): # If it's list then check list values if it contains dict object. temp = list() # Creating temp list for storing the values that we will need which are not dict. for v in val: if not isinstance(v, dict): temp.append(v) else: q.append((key, v)) # if it's value is dict type then we push along with parent which is key. if len(temp) &gt; 0: res[key] = temp else: res[key] = val else: q.append((key, val)) while q: k, v = q.popleft() # Taking parent and the value out of queue for key, val in v.items(): new_parent = k + &quot;_&quot; + key # New parent will be old parent_currentval if isinstance(val, list): temp = list() for v in val: if not isinstance(v, dict): temp.append(v) else: q.append((new_parent, v)) if len(temp) &gt;= 0: res[new_parent] = temp elif not isinstance(val, dict): res[new_parent] = val else: q.append((new_parent, val)) return res It's working with the JSON that is given, I'm appending _ for flattening JSON instead of using 0 1 list indexing. from pprint import pprint print(pprint.pprint(flattern_json(d))) It gave following output: {'count': 13, 'virtualmachine_affinitygroup': [], 'virtualmachine_displayname': 'test-2', 'virtualmachine_hypervisor': 'KVM', 'virtualmachine_id': '1082e2ed-ff66-40b1-a41b-26061afd4a0b', 'virtualmachine_isdynamicallyscalable': False, 'virtualmachine_name': 'test-2', 'virtualmachine_nic': [], 'virtualmachine_nic_id': '3d7f2818-1f19-46e7-aa98-956526c5b1ad', 'virtualmachine_nic_networkid': 'b4648cfd-0795-43fc-9e50-6ee9ddefc5bd', 'virtualmachine_nic_traffictype': 'Guest', 'virtualmachine_securitygroup': [], 'virtualmachine_securitygroup_id': '9e649fbc-3e64-4395-9629-5e1215b34e58', '…

http://stackoverflow.com/q/51409295
favorite count: 0
has title: multiprocess plotting in matplotlib
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89790099
tagged with: python
has answer: http://stackoverflow.com/a/51409803
score: 3
linked to: http://stackoverflow.com/q/43571924
downvote count: 0
tagged with: matplotlib
tagged with: python-multiprocessing
tagged with: multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/89790473
has comment: http://stackoverflow.com/comment/89791104
upvote count: 3
tagged with: pandas
answer count: 1
has body: How can one visualize data using matplotlib by a function in parallel? I.e. I want to create figures in parallel processes and then display them in the main process. Here is an example: # input data import pandas as pd, matplotlib.pyplot as plt df = pd.DataFrame(data={'i':['A','A','B','B'], 'x':[1.,2.,3.,4.], 'y':[1.,2.,3.,4.]}) df.set_index('i', inplace=True) df.sort_index(inplace=True) # function which creates a figure from the data def Draw(df, i): fig = plt.figure(i) ax = fig.gca() df = df.loc[i,:] ax.scatter(df['x'], df['y']) return fig def DrawWrapper(x): return Draw(*x) # creating figures in parallel from multiprocessing import Pool poolSize = 2 with Pool(poolSize) as p: args = [(df,'A'), (df,'B')] figs = p.map(DrawWrapper, args) # attempt to visualize the results fig = plt.figure('A') plt.show() # FIXME: get "RuntimeError: main thread is not in main loop" How do I transfer the figure objects from the worker processes such as to be able to show the figures in the main process? Thank you for your help! [EDIT:] It was suggested that the problem might be solved by this thread Here is the corresponding code: # input data import pandas as pd, matplotlib.pyplot as plt df = pd.DataFrame(data={'i':['A','A','B','B'], 'x':[1.,2.,3.,4.], 'y':[1.,2.,3.,4.]}) df.set_index('i', inplace=True) df.sort_index(inplace=True) # function which creates a figure from the data def Draw(df, i): fig = plt.figure(i) ax = fig.gca() df = df.loc[i,:] ax.scatter(df['x'], df['y']) plt.show() # creating figures in parallel from multiprocessing import Process args = [(df,'A'), (df,'B')] for a in args: p = Process(target=Draw, args=a) p.start() # FIXME: result is the same (might be even worse since I do not # get any result which I could attempt to show): # ... # RuntimeError: main thread is not in main loop # RuntimeError: main thread is not in main loop Am I missing something?

http://stackoverflow.com/comment/89832290
comment on: http://stackoverflow.com/q/51430645
score: 0
type: QuestionComment
type: Comment
has text: the thing is that I load dataset via python but using azure itself

http://stackoverflow.com/q/51445839
possible better answer: http://stackoverflow.com/a/51446148
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89862138
has answer: http://stackoverflow.com/a/51445956
has comment: http://stackoverflow.com/comment/89861891
type: Question
has answer: http://stackoverflow.com/a/51445942
has comment: http://stackoverflow.com/comment/89861965
accepted answer: http://stackoverflow.com/a/51445925
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/51445925
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/51446148
has body: I am trying to use re twice to search and split data For example: [2018-07-10 15:04:11] USER INPUT "hello" [2018-07-10 15:04:12] SYSTEM RESPONSE: "Hello! How are you doing today" [2018-07-10 15:04:42] USER INPUT "I am doing good thank you" [2018-07-10 15:04:42] SYSTEM RESPONSE: "Good to know" I am finding all the substring within [] 2018-07-10 15:04:11, 2018-07-10 15:04:12, 2018-07-10 15:04:42, 2018-07-10 15:04:42, I am trying to split the space 2018-07-10,15:04:11,2018-07-10,15:04:12,2018-07-10,15:04:42,2018-07-10,15:04:42 and my code is: import re file = re.findall(r'\[(.*?)\]', file) m = re.split(r'\ +', file) but it's giving me an error- and not letting me use re twice any suggestions would be great! Thank you in advance
favorite count: 0
has title: Using re- regular expression twice
has comment: http://stackoverflow.com/comment/89861887
has answer: http://stackoverflow.com/a/51445894
answer count: 5

http://stackoverflow.com/comment/89682054
type: Comment
has text: Nothing to be sorry about. Sure you can do this with the [`$match`](https://docs.mongodb.com/manual/reference/operator/aggregation/match/) operator. simply `[{"$match": {"user_id": unique_id}}, {"$group": {"_id": None, "my_list": {"$push": "$name"}}}]`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51341142

http://stackoverflow.com/comment/89737160
score: 0
type: Comment
has text: As @khelwood said what are the problem you want to address, because there's a bunch. Also, make sure to include all the relevant code (Aka. `inputPlayerLetter()`).
type: QuestionComment
comment on: http://stackoverflow.com/q/51382583

http://stackoverflow.com/comment/89708853
type: Comment
comment on: http://stackoverflow.com/q/51368119
score: 0
type: QuestionComment
has text: I assume he means GB @JHBonarius

atomic
type: Tag
tag name: atomic
tags question: http://stackoverflow.com/q/51473354

http://stackoverflow.com/a/70874458
has body: def choose_best_sum(t, k, ls): from itertools import combinations ls.sort() p=combinations(ls,k) l=list(p) l=[sum(i) for i in l] l.sort() if t in l: return t if len(l)==0: return None l=l[::-1] for i in l: if i&lt;t: return i
score: 0
has comment: http://stackoverflow.com/comment/125299471
answers question: http://stackoverflow.com/q/51368440
type: Answer

http://stackoverflow.com/comment/89766828
type: QuestionComment
has text: Use existing utilities like [`train_test_split` in scikit-learn](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html)
type: Comment
comment on: http://stackoverflow.com/q/51394792
score: 0

http://stackoverflow.com/q/51368378
has comment: http://stackoverflow.com/comment/89751378
has comment: http://stackoverflow.com/comment/89745454
has comment: http://stackoverflow.com/comment/89718271
type: Question
tagged with: apache-kafka
tagged with: pyspark
has comment: http://stackoverflow.com/comment/89744136
has comment: http://stackoverflow.com/comment/89745015
has comment: http://stackoverflow.com/comment/89746024
has body: I'm trying to create a kafka stream and then do some transformations on that but It seems the stream that I create is null. I load a text file into producer then consume it through consumer and It works fine but it doesn't create the kafka stream. The input text file looks like this with 36000 entries: 10.000000 26.000000 -8.000000 -28.000000 ... And my python code is: sc = SparkContext(appName="STALTA") ssc = StreamingContext(sc, 2) broker, topic = sys.argv[1:] kvs = KafkaUtils.createStream(ssc, broker, "raw-event-streaming-consumer",{topic:1}) rdd = kvs.flatMap(lambda line: line.strip().split("\n")).map(lambda strelem: float(strelem)) print("****** ", rdd.count()) ssc.start() ssc.awaitTermination() rdd.count() should print 36000 but it's empty. The command that I run my script with is the following: bin/spark-submit --jars jars/spark-streaming-kafka-0-8-assembly_2.11-2.3.1.jar examples/src/main/python/streaming/sparkkafka.py localhost:2181 consumer6 I tried localhost:9092 also but it didn't work. Do you know what I'm doing wrong? Thank you.
has comment: http://stackoverflow.com/comment/89743773
has comment: http://stackoverflow.com/comment/89717129
score: 0
has comment: http://stackoverflow.com/comment/89789004
has title: How to create a kafka stream in PySpark?
tagged with: apache-spark
answer count: 1
has answer: http://stackoverflow.com/a/52312719
has comment: http://stackoverflow.com/comment/89746931
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89743837

http://stackoverflow.com/comment/89820504
score: 0
type: Comment
type: QuestionComment
has text: i am trying this since 4 days getting the same error.
comment on: http://stackoverflow.com/q/51424575

http://stackoverflow.com/comment/89911232
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51471394
type: Comment
has text: I've added an edit to the question details, where I've shown a workaround solution for the issue. It doesn't seem like `int` or `range` is causing the problem here. What do you think? Or is it just one of those coincidences that just "happens to work"?

http://stackoverflow.com/comment/89757216
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51392683
type: Comment
has text: thanks for the reply, i ran this and got an error on line: total+=int(line)

http://stackoverflow.com/a/57619995
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51456842
score: 1
upvote count: 1
has body: If you are using Tensorflow 2.0, then you might get an error saying AttributeError: module 'tf' has no attribute 'logging' Unfortunately tf.logging has been removed from tensorflow 2.0. Please execute the below commands: import logging logger = tf.get_logger() logger.setLevel(logging.ERROR)

http://stackoverflow.com/comment/89805314
comment on: http://stackoverflow.com/q/51417020
type: Comment
type: QuestionComment
score: 2
has text: Possible duplicate of [Source code for str.split?](https://stackoverflow.com/questions/40332743/source-code-for-str-split)

http://stackoverflow.com/q/51329489
tagged with: qsqlrelationaltablemodel
tagged with: python
tagged with: pyqt5
type: AnsweredQuestion
has body: I've modified the relational table model at https://doc.qt.io/qt-5/qtsql-relationaltablemodel-relationaltablemodel-cpp.html I want to be able to save my changes to my database, but it only saves the first two columns, not the primary key lookup row. Also, I can't delete the rows. I've searched but haven't found any information about how to do it. What am I doing wrong? Sample data I use is: CREATE TABLE `category` ( `Id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, `DrinkType` TEXT NOT NULL); INSERT INTO `category` VALUES (1,'Non-alcoholic'); INSERT INTO `category` VALUES (2,'Alcoholic'); CREATE TABLE "drinks" ( `Id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, `Name` TEXT NOT NULL, `Type` INTEGER ); INSERT INTO `drinks` VALUES (1,'Coca Cola',1); INSERT INTO `drinks` VALUES (2,'Pilsner',2); My code: def addRecord(): model.insertRow(model.rowCount()) def delRecord(): model.removeRow(view.currentIndex().row()) model.select() app = QtWidgets.QApplication(sys.argv) window = QtWidgets.QWidget() window.setWindowTitle("QRelationalSqlTableModel") con = QtSql.QSqlDatabase.addDatabase('QSQLITE') con.setDatabaseName('drinks.db') con.open() model = QtSql.QSqlRelationalTableModel(parent = window) model.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit) model. setTable('drinks') model.setRelation(2, QtSql.QSqlRelation('category', 'id', 'drinktype')) model.select() model.setHeaderData(1, QtCore.Qt.Horizontal, 'Name') model.setHeaderData(3, QtCore.Qt.Horizontal, 'Type of drink') vbox = QtWidgets.QVBoxLayout() view = QtWidgets.QTableView() view.setModel(model) view.setItemDelegate(QtSql.QSqlRelationalDelegate(view)) view.hideColumn(0) view.setColumnWidth(1, 150) view.setColumnWidth(2, 150) vbox.addWidget(view) btnAdd = QtWidgets.QPushButton("&amp;Add record") btnAdd.clicked.connect(addRecord) vbox.addWidget(btnAdd) btnDel = QtWidgets.QPushButton("&amp;Delete record") btnDel.clicked.connect(delRecord) vbox.addWidget(btnDel) window.setLayout(vbox) window.resize(430, 250) window.show()…
has answer: http://stackoverflow.com/a/51329751
type: Question
score: 0
tagged with: qsqltablemodel
tagged with: pyqt
accepted answer: http://stackoverflow.com/a/51329751
answer count: 1
has title: Commit QSqlRelationalTableModel model changes to database

http://stackoverflow.com/comment/89874728
has text: The windows filenames is a mere prop but I'll update my question to fix that.
comment on: http://stackoverflow.com/q/51452342
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89807996
type: Comment
has text: Well, you could try using OpenCv to do a bit of filtering. You know that all zeros have minor width than O letters. You can extract all digits and then, using Tesseract to identify numbers and letters (based on width dimension).
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51416685

http://stackoverflow.com/comment/89794989
score: 0
type: AnswerComment
has text: Thanks for accepting. I modified my answer and added two further solutions. Feel free to chose one :)
type: Comment
comment on: http://stackoverflow.com/a/51410781

http://stackoverflow.com/a/51379026
has comment: http://stackoverflow.com/comment/89729728
type: Answer
has comment: http://stackoverflow.com/comment/89730722
has comment: http://stackoverflow.com/comment/89730555
upvote count: 4
has comment: http://stackoverflow.com/comment/89732148
accepted answer of: http://stackoverflow.com/q/51378987
has comment: http://stackoverflow.com/comment/89732538
has comment: http://stackoverflow.com/comment/89732171
answers question: http://stackoverflow.com/q/51378987
has comment: http://stackoverflow.com/comment/89730628
downvote count: 0
has body: Use unstack with reset_index: df = (df.groupby(['TypeName', 'EventNumber'])['Average'] .quantile([0.25, 0.50]) .unstack() .reset_index()) print (df) TypeName EventNumber 0.25 0.5 0 Type A Event1 3.5 5.0 1 Type A Event2 12.5 14.0 2 Type B Event1 21.5 23.0 3 Type B Event2 30.5 32.0 Syntactic sugar solution - new column Average is not necessary, is possible use groupby with 3 Series: s = df'PricePart1', 'PricePart2', 'PricePart3'.mean(axis = 1) df = (s.groupby([df['TypeName'], df['EventNumber']]) .quantile([0.25, 0.50]) .unstack() .reset_index()) print (df) TypeName EventNumber 0.25 0.5 0 Type A Event1 3.5 5.0 1 Type A Event2 12.5 14.0 2 Type B Event1 21.5 23.0 3 Type B Event2 30.5 32.0
has comment: http://stackoverflow.com/comment/89732634
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89730051
has comment: http://stackoverflow.com/comment/89729627
has comment: http://stackoverflow.com/comment/89729583
score: 4
has comment: http://stackoverflow.com/comment/89732310
has comment: http://stackoverflow.com/comment/89730753
has comment: http://stackoverflow.com/comment/89730079
has comment: http://stackoverflow.com/comment/89730583
has comment: http://stackoverflow.com/comment/89729526

http://stackoverflow.com/comment/89825431
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51426895
has text: can you try celery -A news worker -l info, your code is working fine with redis. and try move every code in task.py to celery.py and check once again
type: QuestionComment

http://stackoverflow.com/q/51412320
has title: How to separate by comma all the elements of a nested list?
favorite count: 0
has comment: http://stackoverflow.com/comment/89796323
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51412361
has comment: http://stackoverflow.com/comment/89796356
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51509786
downvote count: 1
answer count: 4
has answer: http://stackoverflow.com/a/51412348
possible better answer: http://stackoverflow.com/a/51412362
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/51412362
type: Question
has answer: http://stackoverflow.com/a/51412361
has comment: http://stackoverflow.com/comment/89796308
score: 0
tagged with: multidimensional-array
has body: I have a long list with tokens like this: a_lis = [['hi how are you'], ['im fine thanks'], ['cool lets go to the restaurant'] ,..., ['I can't now']] I would like to separate each token or term with a comma like this (*): a_lis = [['hi', 'how', 'are', 'you'], ['im', 'fine', 'thanks'], ['cool', 'lets', 'go', 'to', 'the', 'restaurant'] ,..., ['I', 'can't', 'now']] I tried to: [x.replace(' ', ', ') for x in a_lis] However, is not working. Amy idea of how to get (*)?

http://stackoverflow.com/comment/89626725
type: QuestionComment
score: 2
has text: Reading this will clear up your misunderstanding: [Facts and myths about Python names and values](https://nedbatchelder.com/text/names.html)
comment on: http://stackoverflow.com/q/51325767
type: Comment

http://stackoverflow.com/q/51386851
has body: I have spent about two hours on this, but could not find the solution. The closes thing to what I need is probably this boolen mask, but I am still missing the next step. My neural network wasn't learning so I started looking at every step it performs. And sure enough I found a problem. The problem lies in the fact that due to sparsity on my input layer I get too many bias terms propagated throughout. Uniqueness of my set up though is that the last time matrices will be zero matrices. Let me show you, I will first show a screenshot of my notebook and will then present the code. screenshot: I do not want bias terms added to where the whole time is a zeros matrix. I thought I could perhaps perform an op on the boolean mask filtered matrix? Here is the code: import tensorflow as tf import numpy as np dim = 4 # batch x time x events x dim tensor = np.random.rand(1, 3, 4, dim) zeros_last_time = np.zeros((4, dim)) tensor[0][2] = zeros_last_time input_layer = tf.placeholder(tf.float64, shape=(None, None, 4, dim)) # These are supposed to perform operations on the non-zero times Wn = tf.Variable( tf.truncated_normal(dtype=dtype, shape=(dim,), mean=0, stddev=0.01), name="Wn") bn = tf.Variable(tf.truncated_normal(dtype=dtype, shape=(1,), mean=0, stddev=0.01), name="bn") # this is the op I want to be performed only on non-zero times op = tf.einsum('bted,d-&gt;bte', input_layer, Wn) + bn s = tf.Session() glob_vars = tf.global_variables_initializer() s.run(glob_vars) # first let's see what the bias term is s.run(bn, feed_dict={input_layer: tensor}) s.run(op, feed_dict={input_layer: tensor}) EDIT: So I believe tf.where is what I need.
has title: Tensorflow operation on non-zero vectors
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51388331
has answer: http://stackoverflow.com/a/51387179
type: UnansweredQuestion
tagged with: python
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/89693184
type: QuestionComment
comment on: http://stackoverflow.com/q/51360409
has text: As it stands, the code you have posted doesn't tell me what `g` is. Of course, some people can go read you github code. But then the question isn't self contained. If you change the code on github this question won't make sense to people in the future. Can you include a skimmed down version of your `Game` class that exhibits the same behaviour?
score: 0
type: Comment

http://stackoverflow.com/q/51358885
has comment: http://stackoverflow.com/comment/89690323
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51359047
type: Question
type: AnsweredQuestion
upvote count: 9
score: 9
has title: Regex No Character Should Repeat
has body: I have just started out on the regex part of python and I thought I understood this concept but when I started out the programming I wasn't able to get it. The problem statement which was given is to design a regex which It must contain at least 2 uppercase English alphabet characters It must contain at least 3 digits (0-9) it should only contain alphanumeric characters No characters should repeat There must be exactly 10 characters The code which I wrote is import re n=int(input()) patt=r'^(?=.*[A-Z]).{2,}(?=.*[0-9]).{3,}(?=.*[\w]?){10}$' for x in range(n): match=re.findall(patt,str(input())) #print(match) if match: print("Valid") else: print("Invalid") I first started out with the 1st part i.e should contain "It must contain at least 2 uppercase English alphabet characters" for which I wrote (?=.*[A-Z]).{2,} as it will search for more than two characters and will use lookahead assertions For the second part I applied the same and for the third part i.e it should only contain alphanumeric characters I applied (?=.*[\w]?) these three seems to work but when the fourth and fifth condition comes i.e No characters should repeat and There must be exactly 10 characters I tried to use {10} at last but it didn't work and the whole thing seems to be broken now. Can anyone guide me how to use regex and what exactly is a positive lookahead.
linked to: http://stackoverflow.com/q/18643157
linked to: http://stackoverflow.com/q/14590008
has comment: http://stackoverflow.com/comment/111764971
has answer: http://stackoverflow.com/a/69772080
possible better answer: http://stackoverflow.com/a/51359049
downvote count: 0
has answer: http://stackoverflow.com/a/51359049
has answer: http://stackoverflow.com/a/65354814
favorite count: 0
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/51359047
linked to: http://stackoverflow.com/q/12870489
answer count: 4

http://stackoverflow.com/comment/89948282
score: 0
type: Comment
has text: Thanks it works. The `squeeze` operation is the key!
comment on: http://stackoverflow.com/a/51477065
type: AnswerComment

mysql
tags question: http://stackoverflow.com/q/51334487
tags question: http://stackoverflow.com/q/51448741
tags question: http://stackoverflow.com/q/51380263
tags question: http://stackoverflow.com/q/51445473
tags question: http://stackoverflow.com/q/51329049
tags question: http://stackoverflow.com/q/51456910
tags question: http://stackoverflow.com/q/51405245
tags question: http://stackoverflow.com/q/51377580
tag name: mysql
tags question: http://stackoverflow.com/q/51393477
tags question: http://stackoverflow.com/q/51383418
tags question: http://stackoverflow.com/q/51346083
tags question: http://stackoverflow.com/q/51395470
tags question: http://stackoverflow.com/q/51449258
tags question: http://stackoverflow.com/q/51471434
tags question: http://stackoverflow.com/q/51359119
tags question: http://stackoverflow.com/q/51327600
tags question: http://stackoverflow.com/q/51424925
tags question: http://stackoverflow.com/q/51374762
tags question: http://stackoverflow.com/q/51437447
tags question: http://stackoverflow.com/q/51400332
tags question: http://stackoverflow.com/q/51417786
tags question: http://stackoverflow.com/q/51341440
tags question: http://stackoverflow.com/q/51372298
tags question: http://stackoverflow.com/q/51399865
tags question: http://stackoverflow.com/q/51402221
type: Tag
tags question: http://stackoverflow.com/q/51408463
tags question: http://stackoverflow.com/q/51384863
tags question: http://stackoverflow.com/q/51340466
tags question: http://stackoverflow.com/q/51448697
tags question: http://stackoverflow.com/q/51451747
tags question: http://stackoverflow.com/q/51330300
tags question: http://stackoverflow.com/q/51338728
tags question: http://stackoverflow.com/q/51471128
tags question: http://stackoverflow.com/q/51367067
tags question: http://stackoverflow.com/q/51381327
tags question: http://stackoverflow.com/q/51391771
tags question: http://stackoverflow.com/q/51472151
tags question: http://stackoverflow.com/q/51360140
tags question: http://stackoverflow.com/q/51388336
tags question: http://stackoverflow.com/q/51353945
tags question: http://stackoverflow.com/q/51455256
tags question: http://stackoverflow.com/q/51376963

http://stackoverflow.com/q/51366535
has body: I'm developing (in order to learn python) a simple hierarchy of classes with the aims to solve differential equation (ordinary or system of) in the case of system the dependent variable have to became an numpy.array in order to use each index (like y[0], y[1] ) to represent a 2 different variable that in mathematics are dy1/dt = f(y1) dy2/dt=f(y2) using this solver when you deal with ordinary equations the array y have shape = 1, and the size of the N elements. Now given all this boring theory I used to define the several equation (system) or the single equations by means of lambda function like in this case : func01 = lambda t,u : 1 - np.exp(-0.5*(t-5)) this represent the answer of a single step , indeed the analytical solution also given by lambda is the follow: anal01 = lambda x,y : 0 if x &lt; 5 else 1 but now I got a problem (is the first time that I use lambda with if conditions) the interpreter tell me this : anal01 = lambda x,y : 0 if x &lt; 5 else 1 ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() Now I'm already came across this problem ... when for example inside a solver the comparison of single value and y vector comes up .. and I've done like the compiler tell me to do .. and use the form error.all() = y_new- y_old (example) so finally .. the question is ... how to comes up in this case ??? edit there is no variable a in my code ...
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89706844
tagged with: lambda
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/10062954
downvote count: 0
has answer: http://stackoverflow.com/a/51367512
accepted answer: http://stackoverflow.com/a/51367512
has comment: http://stackoverflow.com/comment/89706935
type: Question
upvote count: 2
tagged with: vector
answer count: 1
has title: python difficults to set a lambda function

http://stackoverflow.com/comment/89849870
score: 0
has text: This is horribly inefficient. `list.pop(0)` is `O(n)` -- the entire list needs to be reallocated. Always avoid `list.pop(0), use a `deque` instead.
type: Comment
comment on: http://stackoverflow.com/a/51439791
type: AnswerComment

http://stackoverflow.com/q/51335085
downvote count: 0
has comment: http://stackoverflow.com/comment/89645712
tagged with: reindex
possible better answer: http://stackoverflow.com/a/51335322
has comment: http://stackoverflow.com/comment/89645698
favorite count: 0
has answer: http://stackoverflow.com/a/51335322
has comment: http://stackoverflow.com/comment/89645922
upvote count: 2
has comment: http://stackoverflow.com/comment/89645725
has title: how does pandas DataFrame use groupby() to split and combine data
tagged with: python
accepted answer: http://stackoverflow.com/a/51344433
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89646016
type: Question
linked to: http://stackoverflow.com/q/1764548
tagged with: dataframe
has body: I have data like this: (a smaller version of actual DataFrame structure ) week day val 1 0 8 1 1 9 1 2 6 1 3 3 1 4 4 1 5 2 1 6 6 1 7 9 2 0 3 2 1 1 2 2 2 2 3 6 2 4 8 2 5 9 2 6 6 2 7 3 3 0 4 3 1 2 3 2 6 3 3 7 3 4 4 3 5 2 3 6 5 3 7 7 1 0 1 1 1 2 1 2 6 1 3 8 1 4 9 1 5 1 1 6 7 1 7 4 2 0 2 2 1 1 2 2 2 2 3 6 2 4 8 2 5 9 2 6 1 2 7 7 3 0 4 3 1 2 3 2 8 3 3 9 3 4 7 3 5 9 3 6 3 3 7 7 and, I want to use "week" and "day" as the group keys. It just like what I have done below: data.loc[:,wd_val] = data.groupby([data['week'],data['day']]).mean() I got an error: ValueError: Buffer dtype mismatch, expected 'Python object' but got 'long long' so,(1) what does mean "longlong" ? Second，I add the parameter as_index: data.loc[:,'wd_val']= data'val'.groupby([data['week'],data['day']],as_index=False).mean() data but, the values of "wd_val" is NaN: week day val wd_val 0 1 0 8 NaN 1 1 1 9 NaN 2 1 2 6 NaN 3 1 3 3 NaN (2) why do I got the wrong? Third, I got a dataframe using the code below: temp = data'val'.groupby([data['week'],data['day']]).mean() temp val week day 1 1 5.5 2 6.0 3 5.5 4 6.5 5 1.5 6 6.5 7 6.5 2 0 2.5 1 1.0 2 2.0 and , I want to switch the index("week" and "day") into columns of DataFrame. How can I do that?
has answer: http://stackoverflow.com/a/51344433
answer count: 2

http://stackoverflow.com/comment/89804959
comment on: http://stackoverflow.com/q/51416302
score: 0
type: Comment
type: QuestionComment
has text: Also: is the indentation just like in your project?

http://stackoverflow.com/q/51424453
possible better answer: http://stackoverflow.com/a/51424611
type: Question
has title: Adding list with different length as a new column to a dataframe
answer count: 3
tagged with: pandas
upvote count: 21
has comment: http://stackoverflow.com/comment/89819941
favorite count: 0
has comment: http://stackoverflow.com/comment/89820069
has answer: http://stackoverflow.com/a/51424611
tagged with: python-3.x
has body: I am willing to add or insert the list values in the dataframe. The dataframe len is 49, whereas the length of list id 47. I am getting the following error while implementing the code. print("Lenght of dataframe: ",datasetTest.open.count()) print("Lenght of array: ",len(test_pred_list)) datasetTest['predict_close'] = test_pred_list The error is: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-105-68114a4e9a82&gt; in &lt;module&gt;() 5 # datasetTest = datasetTest.dropna() 6 # print(datasetTest.count()) ----&gt; 7 datasetTest['predict_close'] = test_pred_list 8 # test_shifted['color_predicted'] = test_shifted.apply(determinePredictedcolor, axis=1) 9 # test_shifted['color_original'] = c:\python35\lib\site-packages\pandas\core\frame.py in __setitem__(self, key, value) 2517 else: 2518 # set column -&gt; 2519 self._set_item(key, value) 2520 2521 def _setitem_slice(self, key, value): c:\python35\lib\site-packages\pandas\core\frame.py in _set_item(self, key, value) 2583 2584 self._ensure_valid_index(value) -&gt; 2585 value = self._sanitize_column(key, value) 2586 NDFrame._set_item(self, key, value) 2587 c:\python35\lib\site-packages\pandas\core\frame.py in _sanitize_column(self, key, value, broadcast) 2758 2759 # turn me into an ndarray -&gt; 2760 value = _sanitize_index(value, self.index, copy=False) 2761 if not isinstance(value, (np.ndarray, Index)): 2762 if isinstance(value, list) and len(value) &gt; 0: c:\python35\lib\site-packages\pandas\core\series.py in _sanitize_index(data, index, copy) 3119 3120 if len(data) != len(index): -&gt; 3121 raise ValueError('Length of values does not match length of ' 'index') 3122 3123 if isinstance(data, PeriodIndex): ValueError: Length of values does not match length of index How I can get rid of this error. Please help me.
has answer: http://stackoverflow.com/a/51424527
accepted answer: http://stackoverflow.com/a/51424527
tagged with: python
has answer: http://stackoverflow.com/a/51424826
type: AnsweredQuestion
downvote count: 0
score: 21

http://stackoverflow.com/comment/89727502
has text: Please update your code with the changes you made and post the new error message.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51376970
type: Comment

http://stackoverflow.com/a/51435848
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/51432887
has body: The site loads the products dynamically through Ajax. Looking at the Chrome/Firefox network inspector reveals the address of API. The site loads the product data from there (https://www.rebuy.de/api/search?page=1&amp;categorySanitizedPath=videospiele-nintendo-switch): import requests import json from pprint import pprint headers = {} # headers = {"Host":"www.rebuy.de", # "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", # "Cookie":"SET THIS TO PREVENT ACCESS DENIED", # "Accept-Encoding":"gzip,deflate,br", # "User-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36"} url = "https://www.rebuy.de/api/search?page={}&amp;categorySanitizedPath=videospiele-nintendo-switch" page = 1 r = requests.get(url.format(page), headers=headers) data = json.loads(r.text) pprint(data['products']) # print(json.dumps(data, indent=4, sort_keys=True)) Prints: {'docs': [{'avg_rating': 5, 'badges': [], 'blue_price': 1999, 'category_id': {'0': 94, '1': 3098}, 'category_is_accessory': False, 'category_name': 'Nintendo Switch', 'category_sanitized_name': 'nintendo-switch', 'cover_updated_at': 0, 'has_cover': True, 'has_percent_category': False, 'has_variant_in_stock': True, 'id': 10725297, 'name': 'FIFA 18', 'num_ratings': 1, 'price_min': 1999, 'price_recommended': 0, 'product_sanitized_name': 'fifa-18', 'root_category_name': 'Videospiele', 'variants': [{'label': 'A1', 'price': 2199, 'purchasePrice': 1456, 'quantity': 2}, {'label': 'A2', 'price': 1999, 'purchasePrice': 1919, 'quantity': 7}, {'label': 'A3', 'price': 1809, 'purchasePrice': 1919, 'quantity': 0}, {'label': 'A4', 'price': 1409, 'purchasePrice': 1919, 'quantity': 0}]}, ...and so on. One caveat, when many requests are made, the site returns Access Denied. To prevent this, you need to set headers with Cookie from your browser (to get the cookie, look inside Chrome/Firefox network inspector). Better solution would be use of Selenium.
score: 3
downvote count: 0

nltk
tags question: http://stackoverflow.com/q/51414876
tags question: http://stackoverflow.com/q/51343373
tags question: http://stackoverflow.com/q/51390568
tags question: http://stackoverflow.com/q/51330793
tags question: http://stackoverflow.com/q/51366811
tags question: http://stackoverflow.com/q/51427111
tags question: http://stackoverflow.com/q/51356244
tags question: http://stackoverflow.com/q/51406281
tags question: http://stackoverflow.com/q/51461263
tags question: http://stackoverflow.com/q/51326704
tags question: http://stackoverflow.com/q/51330099
tags question: http://stackoverflow.com/q/51341285
tags question: http://stackoverflow.com/q/51338824
tags question: http://stackoverflow.com/q/51351970
tags question: http://stackoverflow.com/q/51416277
tags question: http://stackoverflow.com/q/51337884
tag name: nltk
tags question: http://stackoverflow.com/q/51439724
tags question: http://stackoverflow.com/q/51482502
type: Tag
tags question: http://stackoverflow.com/q/51429260
tags question: http://stackoverflow.com/q/51369210
tags question: http://stackoverflow.com/q/51349233

http://stackoverflow.com/comment/89846098
score: 0
type: QuestionComment
type: Comment
has text: @PeterWood as in, the module isn't installed? I'm sure I should get a different error in that case
comment on: http://stackoverflow.com/q/51426618

point-clouds
tags question: http://stackoverflow.com/q/51420188
type: Tag
tags question: http://stackoverflow.com/q/51350493
tag name: point-clouds

http://stackoverflow.com/comment/89769545
score: 1
type: QuestionComment
has text: Is it necessary to make a commit ?
type: Comment
comment on: http://stackoverflow.com/q/51399342

http://stackoverflow.com/comment/89703557
type: AnswerComment
has text: @cricket_007 the integers are immutable so that's not a problem. Modifying `members` would lead to more questions (c:
type: Comment
comment on: http://stackoverflow.com/a/51362519
score: 1

cs50
tag name: cs50
type: Tag
tags question: http://stackoverflow.com/q/51463912

http://stackoverflow.com/a/51481753
type: Answer
has body: You can use regular expressions to parse the lines. I made a function find_lines_by_date() where you can supply the date string and it will return a list of lines with this date: data = """ [2018-07-11 20:57:08] SYSTEM RESPONSE: "hello" [2018-07-11 20:57:19] USER INPUT (xvp_dev-0): "hi! how is it going?" [2018-07-11 20:57:19] SYSTEM RESPONSE: "It's going pretty good. How about you?" [2018-07-11 14:05:20] USER INPUT (xvp_dev-0): I've been doing good too! Thank you. [2018-07-12 14:05:20] SYSTEM RESPONSE: "Hello!" How is your day going today? [2018-07-12 14:05:34] USER INPUT (xvp_dev-0): "Great! Can't complain" [2018-07-12 14:05:34] SYSTEM RESPONSE: "Okay. That's good" """ import re import pprint def find_lines_by_date(date='2018-07-11'): rv = [] groups = re.findall(r'(\[(.*?)\s+.*?\][^\[]+)', data) for g in groups: if g[-1] == date: rv.append(g[0].strip()) return rv pprint.pprint(find_lines_by_date(date='2018-07-12')) This will print: ['[2018-07-12 14:05:20] SYSTEM RESPONSE: "Hello!"\n' ' How is your day going today?', '[2018-07-12 14:05:34] USER INPUT (xvp_dev-0): "Great! Can\'t complain"', '[2018-07-12 14:05:34] SYSTEM RESPONSE: "Okay.\n That\'s good"'] EDIT: The regexp (\[(.*?)\s+.*?\][^\[]+) will match the string for all two-valued groups (first value in the group contains all the line for return value, second value in the group is the date for comparison). I made a simple example on external site with detailed explication:
accepted answer of: http://stackoverflow.com/q/51481431
answers question: http://stackoverflow.com/q/51481431
score: 5
type: AcceptedAnswer
upvote count: 5
downvote count: 0

http://stackoverflow.com/q/51460046
has comment: http://stackoverflow.com/comment/89889702
has comment: http://stackoverflow.com/comment/89889329
has comment: http://stackoverflow.com/comment/89889581
has comment: http://stackoverflow.com/comment/89890997
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89889547
type: Question
has answer: http://stackoverflow.com/a/51462388
has comment: http://stackoverflow.com/comment/89890042
score: 0
has body: I'm trying to run the below program but I keep getting connection error's: from socket import * from codecs import decode HOST = 'localhost' PORT = 5000 BUFSIZE = 1024 ADDRESS = (HOST, PORT) server = socket(AF_INET, SOCK_STREAM) server.connect(ADDRESS) dayAndTime = decode(server.recv(BUFSIZE), 'ascii') print(dayAndTime) server.close() ERROR: ConnectionRefusedError: [Errno 61] Connection refused Any idea what's going on?
has title: Python 3 localhost connection
answer count: 1

http://stackoverflow.com/comment/109283143
has text: I think this is much easier to do using Plotly, personally. Supply a dataframe to the plot you need and specify `hover` as the column of interest.
score: 1
comment on: http://stackoverflow.com/q/51349959
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89806325
type: AnswerComment
score: 0
type: Comment
has text: +1. But what's funny is that your answer contradicts this one here : https://stackoverflow.com/questions/51402369/how-to-bucketize-a-group-of-columns-in-pyspark
comment on: http://stackoverflow.com/a/51417421

http://stackoverflow.com/a/51412632
upvote count: 1
score: 1
has body: Let's consider a bigger dataframe for better visualization: DATE | price 01-01-2018 100 02-01-2018 101 03-01-2018 97 04-01-2018 102 05-01-2018 100 06-01-2018 107 07-01-2018 38 You have some problems in your code. You are trying to make a bool operations with arrays instead of a single value. A solution: def case1(x): # New df with a new column for shift prices df = x.assign(price_prevrow= x.shift(3)['price']) if np.isnan(df['price_prevrow']).all(): # Check ALL values pass else: # Slice df to get only rows with price greater than price_prevrow df = df.loc[df['price'] &gt; df['price_prevrow']] # Calculate difference diff = df['price_prevrow'] - df['price'] # Print all differences for d in diff: print('The diff is {}'.format(d)) The code above create a new dataframe with the shifted prices, than slice this dataframe with rows what have price value greater than the prevrow value. After this get the difference is easy. Output: "The diff is -2.0" "The diff is -10.0"
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51410478
type: Answer
answers question: http://stackoverflow.com/q/51410478

http://stackoverflow.com/a/51436561
has comment: http://stackoverflow.com/comment/89843272
score: 1
has body: You can user itertools.product for this. Simply provide range(10) as an argument, and the number of digits you want as the argument for repeat. Conveniently, the itertools iterator returns the elements in sorted order, so you do not have to perform a secondary sorting step by yourself. Below is an evaluation of my code: import timeit if __name__ == "__main__": # time run: 14.20635 print(timeit.timeit("np.array([list(str(i).zfill(4)) for i in range(10000)], dtype=int)", "import numpy as np", number=1000)) # time run: 5.00319 print(timeit.timeit("np.array(list(itertools.product(range(10), r=4)))", "import itertools; import numpy as np", number=1000))
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/89843051
has comment: http://stackoverflow.com/comment/89843133
has comment: http://stackoverflow.com/comment/89843484
answers question: http://stackoverflow.com/q/51436036
downvote count: 0
has comment: http://stackoverflow.com/comment/89843100

http://stackoverflow.com/comment/89891380
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51460879
has text: Your first `return 0` line should be indented. jshamble has removed the error you note. But if that is done, your code still returns wrong answers values of `amount` that end in the decimal digit `2`, `3`, `7`, or `8`. See my answer for working code.

http://stackoverflow.com/a/51359385
answers question: http://stackoverflow.com/q/51359128
type: Answer
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: First you need to correctly access your file with full path: for path, subdirs, files in os.walk("."): for filename in files: if filename == 'data.json': fullpath = os.path.join(path, filename) Then open it in desired mode, the one you included is read: with open(fullpath, 'r') as f: ... Read more about modes for open() here.
accepted answer of: http://stackoverflow.com/q/51359128

http://stackoverflow.com/q/51413403
score: 0
has title: Python-Pandas Join two columns by adding a character
answer count: 3
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51413447
has comment: http://stackoverflow.com/comment/89798379
has body: There are three different columns, col2 and col3 need to be joined with the character "/" between the two columns and after joining column name need to be col2. please help !!! col1 col2 col3 B 0.0.0.0 0 0 B 2.145.26.0 24 B 2.145.27.0 24 B 10.0.0.0 8 20 Expected output: col1 col2 B 0.0.0.0 0/0 B 2.145.26.0/24 B 2.145.27.0/24 B 10.0.0.0 8/20
has answer: http://stackoverflow.com/a/51413447
tagged with: python
type: AnsweredQuestion
type: Question
possible better answer: http://stackoverflow.com/a/51413476
has answer: http://stackoverflow.com/a/51413476
has answer: http://stackoverflow.com/a/51413503

http://stackoverflow.com/comment/89896894
comment on: http://stackoverflow.com/a/51464081
score: 0
type: AnswerComment
has text: Interesting use of `defaultdict` +1 !
type: Comment

http://stackoverflow.com/comment/91867048
has text: In fact, I traced the execution of the python ZipFile and found that it is optimal, but I discovered that I had to add the caching to make performance decent.
comment on: http://stackoverflow.com/a/52455004
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89630959
has text: @Prateek his expected output is shown by what he expects the print statements to print
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51327792
score: 4

http://stackoverflow.com/comment/89672564
type: QuestionComment
comment on: http://stackoverflow.com/q/51349982
score: 1
type: Comment
has text: can you provide some example lines? like it is on the csv file.

http://stackoverflow.com/a/51373782
has comment: http://stackoverflow.com/comment/89758883
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/89770917
has comment: http://stackoverflow.com/comment/89780088
has comment: http://stackoverflow.com/comment/89752179
has body: QSS does not support this type of url, a workaround is to save the content in a temporary file that is deleted when the application is closed, for this we use QTemporaryFile. On the other the url has the following format: data:image/svg+xml,<CONTENT>, that is the content you should use. from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(400, 300) self.horizontalLayout_2 = QtWidgets.QHBoxLayout(Form) self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.horizontalLayout_2.addLayout(self.horizontalLayout) self.retranslateUi(Form) contents = b" <g fill-rule='evenodd'><g id='hexagons' fill='#b0b0b0' fill-opacity='0.4' fill-rule='nonzero'><path d='M13.99 9.25l13 7.5v15l-13 7.5L1 31.75v-15l12.99-7.5zM3 17.9v12.7l10.99 6.34 11-6.35V17.9l-11-6.34L3 17.9zM0 15l12.98-7.5V0h-2v6.35L0 12.69v2.3zm0 18.5L12.98 41v8h-2v-6.85L0 35.81v-2.3zM15 0v7.5L27.99 15H28v-2.31h-.01L17 6.35V0h-2zm0 49v-8l12.99-7.5H28v2.31h-.01L17 42.15V49h-2z'/></g></g> " file = QtCore.QTemporaryFile(Form) if file.open(): file.write(contents) file.flush() Form.setStyleSheet("""background-color: #000000; background-image: url(%s);""" % file.fileName()) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): Form.setWindowTitle(QtWidgets.QApplication.translate("Form", "Form", None, -1)) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) Form = QtWidgets.QWidget() ui = Ui_Form() ui.setupUi(Form) Form.show() sys.exit(app.exec_()) It seems that PySide2 is a bit special, and it looks more like Qt since this problem was waiting for it in C ++ but not in Python. For a widget to support QSS should be implemented paintEvent using QStyle but for this we must create the class widget since the class Ui_Form is not a widget, it is just a class that serves to fill the widget. Below I show t…
has comment: http://stackoverflow.com/comment/89724746
accepted answer of: http://stackoverflow.com/q/51372928
answers question: http://stackoverflow.com/q/51372928
has comment: http://stackoverflow.com/comment/89752256
has comment: http://stackoverflow.com/comment/89759854
has comment: http://stackoverflow.com/comment/89724939
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89752382
has comment: http://stackoverflow.com/comment/89752421

http://stackoverflow.com/comment/89854487
type: QuestionComment
comment on: http://stackoverflow.com/q/51442309
has text: Can you paste a snippet of `travel.txt`?
score: 0
type: Comment

http://stackoverflow.com/q/51469178
has answer: http://stackoverflow.com/a/51469316
has comment: http://stackoverflow.com/comment/89906903
score: 1
has body: This is in micropython I'm creating an API to control some hardware. The API will be implemented in C with an interface in micropython. One example of my API is: device.set(curr_chan.BipolarRange, curr_chan.BipolarRange.state.ON) I'd like to be able to achieve the same functionality but shorten the second path by somehow implicitly referencing the first argument: device.set(curr_chan.BipolarRange, &lt;first arg?&gt;.state.ON) Is there anyway to do this? The only way to do something like this now would be device.set(curr_chan.BipolarRange.state.ON) and then put an upward pointing C-pointer on both the ON C-object and state C-object so that I know which entry in curr_chan is being referenced. The micropython runtime - and I assume CPython one - doesn't keep the entire object "tree" available to the developer in memory.
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/89907229
upvote count: 1
has comment: http://stackoverflow.com/comment/89906925
has title: how to reference previous arguments of a function call in later arguments?
favorite count: 0
has answer: http://stackoverflow.com/a/51469242
tagged with: micropython
downvote count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/51347477
has comment: http://stackoverflow.com/comment/89676180
score: 0
has body: I'm achieving exactly the same with Ansible and virtualenv with a requirements file for Debian, MacOsX (brew) and RedHat. As part of the playbook example: - name: Install prerequisite pip packages pip: requirements: "{{ _tmp.path }}/{{ required_pip_packages }}" virtualenv: "{{ venv_dir }}" Let me know if you require more information.
has comment: http://stackoverflow.com/comment/89670661
type: Answer
answers question: http://stackoverflow.com/q/51344299

http://stackoverflow.com/comment/89793581
comment on: http://stackoverflow.com/q/51410665
score: 0
type: Comment
type: QuestionComment
has text: Could you post an example? Then it is easier to help. And you might want to take a look at [this answer](https://stackoverflow.com/a/37977222/1534017).

http://stackoverflow.com/q/51461836
favorite count: 0
has comment: http://stackoverflow.com/comment/89892739
has body: I have some data with binary (0 and 1) labels. I am using pd.cut to discretize one feature continuous_value, before doing a pd.crosstab on the new field. The problem is that when I do crosstab, the output seems to mismatch the row names (which are the boundaries for each bin) with the corresponding counts. Here is my code for a minimal example of the issue. continuous_value is non-negative. 118 data points have continuous_value = 0, so the smallest bin edge is -1, to include these. In this minimal example, the data is cut into the two bins: (-1 to 0), which only includes those with 0 value, and (0 to 5000000) which includes all other data points. bins=[-1,0,5000000] input_df['discrete_value']=pd.cut(input_df['continuous_value'],bins=bins) pd.crosstab(input_df.discrete_value, input_df.label) As you can see in the attached picture, the bin names are mismatched. The count for the non-zero bin sums to 118, and the count for the zero bin sums to 10237. This should be the other way around. EDIT to include dummy data and code snippet that reproduces the error: values = [5100,5400,9400,10000,16000,10500,0,0,0,87500,14000,11250] d = {'continuous': values,'label': [0]*6+[1]*6} df = pd.DataFrame(data=d) bins = [-1, 0, 5000000] df['discrete'] = pd.cut(df['continuous'], bins=bins)
accepted answer: http://stackoverflow.com/a/51461837
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89892741
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89892736
has comment: http://stackoverflow.com/comment/89892740
has comment: http://stackoverflow.com/comment/89892735
tagged with: visualization
tagged with: pandas
answer count: 1
downvote count: 0
tagged with: dataset
has answer: http://stackoverflow.com/a/51461837
has title: Pandas Crosstab when used with Pandas cut : Row names of the output crosstab are mismatched
has comment: http://stackoverflow.com/comment/89892738
has comment: http://stackoverflow.com/comment/89892737

http://stackoverflow.com/comment/89940765
score: 0
has text: Does the SQL you shared actually execute and do what you expect it to? It looks very broken to me.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51478412

http://stackoverflow.com/a/57956057
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/51436686
accepted answer of: http://stackoverflow.com/q/51436686
type: AcceptedAnswer
downvote count: 0
has body: The pdfminer documentation here shows how to do it in section 2.4. For the record I'll copy-paste the relevant code here. from pdfminer.pdfparser import PDFParser from pdfminer.pdfdocument import PDFDocument # Open a PDF document. fp = open('mypdf.pdf', 'rb') parser = PDFParser(fp) document = PDFDocument(parser, password) # Get the outlines of the document. outlines = document.get_outlines() for(level,title,dest,a,se) in outlines: print (' '.join(title.split(' ')[1:])) The print statement was adapted to appropriately answer the question.
type: Answer

http://stackoverflow.com/q/51328208
type: Question
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/89633974
tagged with: python
has comment: http://stackoverflow.com/comment/89635436
upvote count: 1
tagged with: neural-network
answer count: 0
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89633520
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/89635328
has title: Shape Error while using SciKit Learn's MinMaxScaler
tagged with: scikit-learn
has body: I am getting the following error while trying to load a scaler to make a prediction on a trained neural network: ValueError: operands could not be broadcast together with shapes (317,257) (269,) (317,257) Some context: the first number (317, 257) is the shape of the data set I am trying to make a prediction on, while (269,) is the shape of the training set. I pickled the scaler and loaded it back in, but will get to that later. Before I apply OneHotEncoder, the data set only has 9 columns. After LabelEconder and OneHotEncoder is applied, it expands to 269 columns (there are a lot of large categorical variables within the data). My code: Applying OneHotEncoder after applying LabelEncoder: from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelencoder_X_1 = LabelEncoder() X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1]) labelencoder_X_4 = LabelEncoder() X[:, 3] = labelencoder_X_4.fit_transform(X[:, 3].astype(str)) labelencoder_X_5 = LabelEncoder() X[:, 4] = labelencoder_X_5.fit_transform(X[:, 4].astype(str)) labelencoder_X_6 = LabelEncoder() X[:, 5] = labelencoder_X_6.fit_transform(X[:, 5].astype(str)) labelencoder_X_7 = LabelEncoder() X[:, 6] = labelencoder_X_7.fit_transform(X[:, 6].astype(str)) labelencoder_X_8 = LabelEncoder() X[:, 7] = labelencoder_X_8.fit_transform(X[:, 7].astype(str)) labelencoder_X_9 = LabelEncoder() X[:, 8] = labelencoder_X_9.fit_transform(X[:, 8].astype(str)) onehotencoder_X = OneHotEncoder(categorical_features = [1,3,4,5,6,7,8]) X = onehotencoder_X.fit_transform(X).toarray() Fitting to the scaler during training: from sklearn.preprocessing import MinMaxScaler from sklearn.externals import joblib sc = MinMaxScaler() X_train = sc.fit_transform(X_train) joblib.dump(sc, 'scaler.pkl') X_test = sc.transform(X_test) Then retrieving the scaler and attempting to transform test data: from sklearn.externals import joblib sc = joblib.load('scaler.pkl') dataset = sc.transform(dataset) #Error happens here The test data set is pretty large sin…
score: 1
favorite count: 0

http://stackoverflow.com/q/51453576
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51454179
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89877116
has comment: http://stackoverflow.com/comment/89877184
has comment: http://stackoverflow.com/comment/89876799
tagged with: tkinter
has body: I want to create a window, and content all in center, but I don't know how should I do, please help me. def about_window(): win_about = tk.Toplevel(win) win_about.geometry("340x500") win_about.title("About Us") win_about.resizable(0,0) win_about.iconbitmap(r'C:/Users/810810/Desktop/python/eslogo.ico') frame = tk.Frame(win_about) frame.grid(row=0, column=2) img_png = tk.PhotoImage(file = 'est.gif') label = tk.Label(frame, image = img_png) label.img_png = img_png label.grid(row=0, column=1) Message = 'Version: 1.0' mess = tk.Label(frame, text=Message) mess.grid(row=1, column=0)
upvote count: 2
has title: Tkinter grid not working
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89876910
score: 2
has answer: http://stackoverflow.com/a/51453672
has comment: http://stackoverflow.com/comment/89877412

http://stackoverflow.com/a/54318451
has body: My issue with Truncate not working appears to be the Auto Commit setting wasn't working after I explicitly called con.close(): con = pyodbc.connect("conn", autocommit=True) Or you can explicitly perform commits before closing: con.commit() Ref: https://stackoverflow.com/a/31611279/845584
type: Answer
upvote count: 6
score: 6
answers question: http://stackoverflow.com/q/51423154
downvote count: 0

http://stackoverflow.com/comment/89643532
type: Comment
score: 0
has text: pretty much just an item name for the first item and then a list with random data. I have it sort of figured out using objectnames but it still isn't working too well for me trying that method.
type: QuestionComment
comment on: http://stackoverflow.com/q/51333771

http://stackoverflow.com/comment/89921567
score: 0
has text: @Datanovice - give me a sec.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51476462

http://stackoverflow.com/comment/89699694
score: 0
type: Comment
has text: What would happen with duplicate column names (probably bad practice, but good to know the impact)?
comment on: http://stackoverflow.com/a/51363743
type: AnswerComment

http://stackoverflow.com/comment/101365383
comment on: http://stackoverflow.com/a/51363672
score: 0
type: Comment
has text: @OD1995 have you tried including the same "random" string in request body?
type: AnswerComment

http://stackoverflow.com/q/51344694
tagged with: pip
has comment: http://stackoverflow.com/comment/89662728
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/89789461
has body: I've been struggling with getting tensorflow to work. Not sure what the problem is. I believe I have the latest version of pip, python, tensorflow, and protobuf (which seems to cause similar problems for others) installed. To get to the error message I do: $ cd targetdirectory $ source myenv/bin/activate (myenv)$ python3 &gt;&gt;&gt; import tensorflow This is my error message: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Users/dannyguy/targetDirectory/myenv/lib/python3.7/site-packages/tensorflow/__init__.py", line 22, in &lt;module&gt; from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import File "/Users/dannyguy/targetDirectory/myenv/lib/python3.7/site-packages/tensorflow/python/__init__.py", line 49, in &lt;module&gt; from tensorflow.python import pywrap_tensorflow File "/Users/dannyguy/targetDirectory/myenv/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in &lt;module&gt; from tensorflow.python.pywrap_tensorflow_internal import * File "/Users/dannyguy/targetDirectory/myenv/lib/python3.7/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 114 def TFE_ContextOptionsSetAsync(arg1, async): ^ SyntaxError: invalid syntax I had this error message before. Not really sure why there's a different one now. ModuleNotFoundError: No module named 'tensorflow' Any help would be greatly appreciated!
has comment: http://stackoverflow.com/comment/89662878
downvote count: 0
tagged with: virtualenv
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89664595
tagged with: python
has title: Error when importing tensorflow (with virtualenv) on MacOS
has comment: http://stackoverflow.com/comment/89663671
score: 2
has comment: http://stackoverflow.com/comment/89664708
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/89663229

http://stackoverflow.com/comment/89811081
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51419868
type: AnswerComment
has text: Too complicated for me at my current stage. Thanks still!

http://stackoverflow.com/q/51441532
has comment: http://stackoverflow.com/comment/89853750
has title: Djongo return empty QuerySet when exasing next page
type: Question
has comment: http://stackoverflow.com/comment/89874590
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/89853137
has comment: http://stackoverflow.com/comment/89854926
has comment: http://stackoverflow.com/comment/89853875
score: 0
tagged with: python
tagged with: djongo
has comment: http://stackoverflow.com/comment/89853073
answer count: 0
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/89852909
has body: This only happens when I made a model to have 2 inheritance from the same model: class Word(models.Model): cuvint = models.ForeignKey(KeyWordsMapping, on_delete=models.CASCADE, related_name="%(class)s_cuvint") frequency = models.IntegerField() is_stem = models.BooleanField() score_nr = models.ForeignKey(KeyWordsMapping, on_delete=models.CASCADE, related_name="%(class)s_score_nr") department_id = models.ForeignKey(Department, on_delete=models.CASCADE, blank=True, null=True) seniority_id = models.ForeignKey(Seniority, on_delete=models.CASCADE, blank=True, null=True) Everything works fine, but accessing the second page gives me an empty array: First page: { "count": 311, "next": "http://127.0.0.1:8000/api/words?limit=1&amp;offset=1", "previous": null, "results": [ { "cuvint": "QA", "frequency": 4, "is_stem": false, "score_nr": 100, "department_id": "Quality Assurance", "seniority_id": null } ] } Second page: { "count": 311, "next": "http://127.0.0.1:8000/api/words?limit=1&amp;offset=2", "previous": "http://127.0.0.1:8000/api/words?limit=1", "results": [] } I also looked in the admin panel and the same problem persists. The view: class WordList(mixins.ListModelMixin, mixins.RetrieveModelMixin, generics.GenericAPIView): queryset = Word.objects.all() serializer_class = WordSerializer def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) The serializer: class WordSerializer(serializers.ModelSerializer): seniority_id = serializers.SerializerMethodField() department_id = serializers.SerializerMethodField() score_nr = serializers.SerializerMethodField() cuvint = serializers.SerializerMethodField() class Meta: model = Word fields = ("cuvint", "frequency", "is_stem", "score_nr", "department_id", "seniority_id") def get_seniority_id(self, obj): if obj.seniority_id: return obj.seniority_id.name return None def get_department_id(self, obj): if obj.department_id: return obj.department_id.name return None def get_score_nr(self, obj): return obj.score_nr…
has comment: http://stackoverflow.com/comment/89878778

http://stackoverflow.com/comment/89782100
comment on: http://stackoverflow.com/q/51388347
score: 0
type: Comment
type: QuestionComment
has text: Have you tried saving it locally on the master node or on HDFS?

detection
tags question: http://stackoverflow.com/q/51455221
type: Tag
tag name: detection

http://stackoverflow.com/a/51401346
has comment: http://stackoverflow.com/comment/89915653
answers question: http://stackoverflow.com/q/51396045
score: 0
has body: I would suggest you to implement a serializer for your model and override to_representation method and return how you want the model to represent. Example class ChildSerializer(serializers.ModelSerializer): class Meta: model = Child fields = '__all__' def to_representation(self, instance): # Here instance is instance of your model # so you can build your dict however you like result = OrderedDict() result[instance.name] = {"age" : instance.age, "height" : instance.height} return result that's a problem since it will no longer be a dictionary. with this suggestion I will get: [ {"Alice": "age": 3, "height": 98 }, ... ] Ah, for this, i would suggest to create a view like this: class DictView(generics.GenericAPIView): queryset = Domain.objects.all() def _get_serialized_items(self, input): result = OrderedDict() for item in input: result[item.name] = {"age" : item.age, "height" : item.height} return result def get(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: return self.get_paginated_response(self._get_serialized_items(page)) return Response(self._get_serialized_items(queryset))
type: Answer
has comment: http://stackoverflow.com/comment/89898396

http://stackoverflow.com/comment/89778885
comment on: http://stackoverflow.com/q/51403945
has text: aren't you missing a comma at the end of the first dictionary?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51393616
type: Answer
accepted answer of: http://stackoverflow.com/q/51393576
answers question: http://stackoverflow.com/q/51393576
has body: Try this: b = {} for x in [0,1,2,3]: temp_1 = [] for y in [4,5]: temp_1.append(x*y) b[x] = temp_1 print("\n 3rd for loop output \n",b) In your first loop, you are multiplying a list [4,5] which is not what you want because it is not element-wise. Read http://thepythonguru.com/python-lists/ to see how operators work on Python lists. The second and third loops are the same; you just need to clear your temp_1 list in every iteration on x.
score: 5
has comment: http://stackoverflow.com/comment/89759145
upvote count: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/89759897
has comment: http://stackoverflow.com/comment/89759034
has comment: http://stackoverflow.com/comment/89759122
type: AcceptedAnswer

http://stackoverflow.com/q/51439825
has comment: http://stackoverflow.com/comment/89850297
type: AnsweredQuestion
has title: Warning: Error in py_run_file_impl: ModuleNotFoundError: No module named 'case1'
has comment: http://stackoverflow.com/comment/89851525
has comment: http://stackoverflow.com/comment/89851052
type: Question
has comment: http://stackoverflow.com/comment/89849823
tagged with: python-import
has body: I'm trying to run a Python script via user interface of Shiny in R. Below code is able to run it. (I'm successful in running task1.py via user interface of Shiny in server.R). But I'm getting error because of directory issue. Path of folders: D:\PycharmProjects\Tasks\applications\task1.py D:\PycharmProjects\Tasks\server.R D:\PycharmProjects\Tasks\case1\application_core.py server.R: observeEvent(input$action,{ py_run_file("applications/task1.py") }) task1.py: import sys import os from case1.application_core import AcousticScene By running server.R, I'm getting error Warning: Error in py_run_file_impl: ModuleNotFoundError: No module named 'case' 76: &lt;Anonymous&gt; Please don't mark this question as duplicate, I'm getting this in R not in Python. task1.py gives no error in Pycharm and run successfully in it. Anyone know how can I resolve this?
answer count: 1
tagged with: http://stackoverflow.com/tag/r
has comment: http://stackoverflow.com/comment/89852001
score: 0
tagged with: importerror
has answer: http://stackoverflow.com/a/51439967
accepted answer: http://stackoverflow.com/a/51439967
tagged with: python
has comment: http://stackoverflow.com/comment/89851607

http://stackoverflow.com/comment/89905081
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51451373
type: AnswerComment
has text: But the problem is we can't predict what these bad characters are; it could be anything (Eg: !,@,#). Is there a way wherein I can resolve this without hardcoding these bad characters in my script? Thanks.

http://stackoverflow.com/a/51340745
type: Answer
accepted answer of: http://stackoverflow.com/q/51338831
downvote count: 0
score: 1
has body: The outputs (and inputs) attribute of a Keras model returns a list of (tensor) outputs of the model. You can confirm this in your logs: vgg_output tensor: [&lt;tf.Tensor 'block5_pool/MaxPool:0' shape=(?, 1, 1, 512) dtype=float32&gt;] &lt;-- this is a list VGG16 has one output (i.e. is a sequential model) and you need to explicitly pass this one output tensor (i.e. the first element of returned list) to the next layer which is Flatten: model_tensor = Flatten()(vgg_output[0]) # pass the first element of output As a side note, If you would like to see the progress bar of training, don't pass verbose argument to fit method, or pass it with value of 1 (i.e. verbose=1).
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51338831

http://stackoverflow.com/a/51412109
has comment: http://stackoverflow.com/comment/89796010
has comment: http://stackoverflow.com/comment/90127677
has comment: http://stackoverflow.com/comment/89796024
answers question: http://stackoverflow.com/q/51412000
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/89795967
score: 1
has comment: http://stackoverflow.com/comment/89796703
has body: Most likely the Python process is not allowed to touch the window. Manipulating Windows of other processes is a privileged operation that require your app to be whitelisted. See https://apple.stackexchange.com/questions/291574/osascript-is-not-allowed-assistive-access-1728 To see if this is the case, inspect the stderr value returned from Popen and see if it contains something like “ osascript is not allowed assistive access”. Edit: In Mojave, Apple Events are now sandboxes and will have to be approved by the user. https://mjtsai.com/blog/2018/06/28/apple-event-sandboxing-in-macos-mojave-lacks-essential-apis/
downvote count: 0
has comment: http://stackoverflow.com/comment/89796156
has comment: http://stackoverflow.com/comment/89796054

http://stackoverflow.com/q/51430095
has answer: http://stackoverflow.com/a/51430268
accepted answer: http://stackoverflow.com/a/51430268
tagged with: python
tagged with: xpath
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51433235
downvote count: 0
has title: How to find a particular string within a Source code(Xpath) and extract the proceeding text?
tagged with: web-scraping
tagged with: scrapy
has body: From the following source code : ... ....... ....... . . n . . . . I want to extract the (bla bla) which is definetely coming after (,[null,") till the point ("]) The reason why I cannot go via script name id and div is because they are dynamic for every page I'm scraping via scrapy. Thus the code must look for (,[null,") and extract the proceeding text.
type: Question
score: 1
answer count: 2
possible better answer: http://stackoverflow.com/a/51433235
upvote count: 1
has comment: http://stackoverflow.com/comment/89831356
favorite count: 0

http://stackoverflow.com/q/51451626
has comment: http://stackoverflow.com/comment/89873779
downvote count: 1
has body: I was testing with something and I wrote this code for example purposes.I felt the output I got was weird.I expected that function calls are executed one after the other but according to this code both the print statements are getting executed after each other and then the return values are printed together.What does this mean and what is the flow of the code in this case? global num num=5 def demo(num): num+=1 print("hi") return(num) print(demo(num),demo(num)) output- hi hi 6 6
has answer: http://stackoverflow.com/a/51452163
has title: Print function calling functions together
accepted answer: http://stackoverflow.com/a/51451764
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51452163
has comment: http://stackoverflow.com/comment/89873510
has comment: http://stackoverflow.com/comment/89873583
linked to: http://stackoverflow.com/q/17686596
score: 1
has comment: http://stackoverflow.com/comment/89873491
favorite count: 0
tagged with: python-3.x
type: Question
upvote count: 2
answer count: 2
tagged with: python
has answer: http://stackoverflow.com/a/51451764

http://stackoverflow.com/comment/89762951
type: Comment
type: QuestionComment
has text: No error and no response after I click the link.
comment on: http://stackoverflow.com/q/51395373
score: 0

http://stackoverflow.com/comment/89806863
has text: I have many test items, and it can be choose by check button, and every test item has own function, like send commands, control equipment, read feedback and delay...etc
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51354343
type: Comment

http://stackoverflow.com/q/51428230
has title: How do I group dataframe from CSV by Time Value, So that I can count frequency for each hour?
type: AnsweredQuestion
type: Question
has body: Here is my dataset dataset_for_this_Question I want to group dataset according to 'Time' and 'Type', So that I can get frequency of 'Name' for each hourly basis. [Per Hour How many Types and what are their Names]. My first requirement is to group dataset according to 'Time' - Hourly basis. I am using Pandas in Python.
answer count: 2
tagged with: data-science
possible better answer: http://stackoverflow.com/a/51428328
has comment: http://stackoverflow.com/comment/89828029
has answer: http://stackoverflow.com/a/52219892
accepted answer: http://stackoverflow.com/a/52219892
score: 0
has answer: http://stackoverflow.com/a/51428328
tagged with: pandas-groupby
tagged with: pandas
tagged with: python

http://stackoverflow.com/comment/89922456
type: AnswerComment
comment on: http://stackoverflow.com/a/51472995
type: Comment
score: 0
has text: @RohitSharma Of course, but this question is not good as it is written - and I do not know what you want. You have a specific goal in mind - Ask a new question, write your goal what exactly you need of the matrix, and why the solution you used (`rand`) does not work. I do not know what you want to do, you need to write it down properly.

http://stackoverflow.com/comment/89937898
type: AnswerComment
type: Comment
score: 1
has text: Thanks! I knew it was something super simple that I was missing.
comment on: http://stackoverflow.com/a/51479402

http://stackoverflow.com/a/51777025
score: 1
upvote count: 3
downvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/90512480
has comment: http://stackoverflow.com/comment/90512449
has body: Unfortunately no. IOS is currently the only kivy platform not ready for python 3 this is do to lacking toolchain requirements and may take a while. There is currently an almost beta release for interfacing some python 3 with kivy using the method: kivy.compat.PY2 = False You can read more about this here. However, I highly recommend you don't use any of these because it's more trouble than it's worth right now especially if you want any stability in your app. Python 2.7 is time tested and stable with kivy though so I recommend this over a shaky beta version. If you have your heart set on using python 3 then you might want to take a look at BeeWare. It is currently up to date with python 3.6 and is similar to kivy.
has comment: http://stackoverflow.com/comment/90512568
has comment: http://stackoverflow.com/comment/90512519
answers question: http://stackoverflow.com/q/51386478

http://stackoverflow.com/comment/89924021
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51476065
has text: that is a separate problem -- check the API docs to make sure that you have formatted your query correctly.
score: 0

http://stackoverflow.com/q/51326616
has answer: http://stackoverflow.com/a/51326784
has comment: http://stackoverflow.com/comment/89628293
has comment: http://stackoverflow.com/comment/89628404
accepted answer: http://stackoverflow.com/a/51326784
type: AnsweredQuestion
tagged with: string
has body: I would like an output of Siti's father says, "Hello.". However, the closest I've gotten to is: s = "Siti's father says, \"Hello\"" with s being a variable to contain the required output. The problem arises when I do print("Siti's father says, \"Hello\"") and get the perfect output, but when I assign the the above text to a variable s, I get a different output when defining s. I get: 'Siti\'s father says, "Hello"' What should I change to get the perfect output, assuming I can only use escape codes to get the desired output?
favorite count: 0
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/89628928
has comment: http://stackoverflow.com/comment/89628406
upvote count: 3
score: 0
answer count: 2
downvote count: 3
has comment: http://stackoverflow.com/comment/89629117
has title: How to avoid printing a backslash with special characters in a string
has comment: http://stackoverflow.com/comment/89628418
has comment: http://stackoverflow.com/comment/89628566
possible better answer: http://stackoverflow.com/a/51327006
has answer: http://stackoverflow.com/a/51327006

http://stackoverflow.com/q/51383097
has body: I have a program with a main script (main.py) and a few modules (mod1.py, mod2.py, etc.). In main.py, I configured a root logger to write messages in my terminal and in a file. # main.py import logging LOG = logging.getLogger() def init_logger(): """...""" if __name__ == '__main__': init_logger() LOG.info("...") And in other modules, I use the standard idiom: # mod1.py import logging LOG = logging.getLogger(__name__) All is working fine and for each line in my log file, I know which module it originated from. For example, my log file contains something like: (...) 13:52:59 [INFO |root] (MainThread) Logger initialized (/some_path/logs/log.txt) 13:53:00 [DEBUG|mod1] (MainThread) Some message 13:53:01 [INFO |mod234] (thread_1) Some other message (...) But now, I wish to log some very specific messages in a separate file. I don't want it to pollute my existing log file and I still want to know messages origins (I guess I have to keep a root logger). ie. I don't want to filter by level (debug, info, error, etc.), but I want to filter by some kind of category. How do I achieve that ? Just for the record, my init_logger function, but I'm not sure it's relevant: LOG = logging.getLogger() def init_logger(): logger = logging.getLogger() stream_formatter = logging.Formatter("%(asctime)s :: %(levelname)s :: %(message)s") stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.INFO) stream_handler.setFormatter(stream_formatter) logger.addHandler(stream_handler) log_path = os.path.join(os.path.dirname(__file__), "logs", "log.txt") file_formatter = logging.Formatter(fmt="%(asctime)s [%(levelname)-5s|%(name)s] (%(threadName)-10s) %(message)s", datefmt="%H:%M:%S") file_handler = logging.FileHandler(log_path, mode='w') file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(file_formatter) logger.addHandler(file_handler) logger.setLevel(logging.DEBUG) for tp_module in ("easyprocess", "pyscreenshot", "PIL"): logging.getLogger(tp_module).setLevel(logging.CRITICA…
has answer: http://stackoverflow.com/a/51383762
type: Question
answer count: 1
score: 0
accepted answer: http://stackoverflow.com/a/51383762
has comment: http://stackoverflow.com/comment/89741711
has title: Python: log different data in different files, without losing module names
tagged with: python
has comment: http://stackoverflow.com/comment/89739368
tagged with: python-3.x
tagged with: logging
type: AnsweredQuestion

http://stackoverflow.com/comment/89860902
comment on: http://stackoverflow.com/a/51415036
type: AnswerComment
has text: I have executed line by line in Python and it does not work. I don't think timing is an issue.
score: 0
type: Comment

precision-recall
tags question: http://stackoverflow.com/q/51371356
type: Tag
tags question: http://stackoverflow.com/q/51425436
tag name: precision-recall

http://stackoverflow.com/comment/89780203
score: 0
comment on: http://stackoverflow.com/a/51381377
type: AnswerComment
type: Comment
has text: Right - also depending on exactly which part of C99 noncompliance is an issue, there are plenty of hacks/workarounds floating around the internet - e.g. a `<stdint.h>` replacement that's often useful - https://github.com/pandas-dev/pandas/blob/3cb64bd2953fd264a3d0762806e800f58800641d/pandas/_libs/src/headers/ms_stdint.h

http://stackoverflow.com/comment/89816842
type: Comment
type: QuestionComment
has text: The idea of using 'width' sounds promising. I will explore more and will update the forum with my findings.
score: 0
comment on: http://stackoverflow.com/q/51416685

http://stackoverflow.com/comment/89939233
has text: when I use the code: `gst-launch-1.0 fdsrc ! h264parse ! avdec_h264 ! filesink location=/dev/stdout` I get the displayed result. However when I use the code: `gst-launch-1.0 fdsrc fd=0 ! h264parse ! avdec_h264 ! xvimagesink sync=false` it works jest fine, but the image is displayed on separate widow (and not using opncv). That is the reason I think the output of `gst` is fine
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51458323

http://stackoverflow.com/comment/89763426
comment on: http://stackoverflow.com/q/51381335
has text: @T.Nel most of website these days use email to register and login. so what should i do to Authenticate using email ? do i have to change in default's ? if yes how do i do it ?
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89709085
score: 0
type: Comment
type: QuestionComment
has text: @ImportanceOfBeingErnest not worried about the label - that's a scaling issue. they are dates that are at flipped 90deg - I zoom in they are fine. Either way I care only about sorting it out for linux. I will look at the version thing thanks.
comment on: http://stackoverflow.com/q/51368187

http://stackoverflow.com/comment/89747880
score: 0
type: Comment
type: QuestionComment
has text: the presented variants return different things: some return a `list` and some are generators.
comment on: http://stackoverflow.com/q/51387973

http://stackoverflow.com/comment/89797551
comment on: http://stackoverflow.com/q/51412779
has text: where is you `i` in forloop
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89784140
comment on: http://stackoverflow.com/q/51406467
score: 0
type: Comment
type: QuestionComment
has text: Yes I do. Thanks. That's not a problem in my application.

http://stackoverflow.com/q/51330028
has answer: http://stackoverflow.com/a/51384834
type: AnsweredQuestion
type: Question
tagged with: numpy
has title: Overplot SunPy HEK polygon mask on custom numpy array instead of Sunpy Map
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/51384834
tagged with: astropy
score: 0
answer count: 1
tagged with: matplotlib-basemap
tagged with: python
has body: I'm working on sunspot detection and I'm trying to build ground truth masks using sunpy.net.hek client to download solar events from the knowledge base. I followed this tutorial. My problem is that I'm not able to get the polygon pixel coordinates after the rotation. That is: ch_boundary = SkyCoord( [(float(v[0]), float(v[1])) * u.arcsec for v in p3], obstime=ch_date, frame=frames.Helioprojective) rotated_ch_boundary = solar_rotate_coordinate(ch_boundary, aia_map.date) Where p3 holds the original coordinates of the event (they have to be rotated because your picture could not have the same timing as the event on hek). rotated_ch_boundary is an Astropy SkyCoord but cannot figure out how to get the coordinates in pixel relative to the image from that. Then in the tutorial it just plots the coordinates using Sunpy Map and matplotlib: aia_map.plot(axes=ax) ax.plot_coord(rotated_ch_boundary, color='c') I cannot do that because I want to print the polygon (filled) on a numpy array and save it. I also tried to build a custom Sunpy map and use the same function to plot: from sunpy.net.helioviewer import HelioviewerClient hv = HelioviewerClient() filepath = hv.download_jp2('2017/07/10 10:00:00', observatory='SDO', instrument='HMI', detector='HMI', measurement='continuum') hmi = sunpy.map.Map(filepath) # QUERY AND ROTATION CODE HERE... hmi.plot(axes=ax) ax.plot_coord(rotated_ch_boundary, color='c') but it doesn't even show the polygon on the plot, I don't know if it's for the different resolution or whatever. Do you have any idea on how I can plot the polygon on a custom image and save it in order to use it later? My purpose is to create a black image with a white polygon highlighted. The polygon should be in the exact same position as the sunspot in the corresponding image, let's say an SDO HMI intensitygram of the same day I downloaded from helioviewer.

http://stackoverflow.com/comment/89929779
comment on: http://stackoverflow.com/q/51479635
type: Comment
type: QuestionComment
has text: @BearBrown Maybe to do that in one transaction.
score: 0

http://stackoverflow.com/a/51362519
has comment: http://stackoverflow.com/comment/89697741
has comment: http://stackoverflow.com/comment/89703557
score: 0
has comment: http://stackoverflow.com/comment/89697362
has comment: http://stackoverflow.com/comment/89697493
type: Answer
answers question: http://stackoverflow.com/q/51362432
has comment: http://stackoverflow.com/comment/89705232
has body: Your class definitions are identical. Why not have one class definition: class track: number = 0 min_class = 0 members = [] and then create as many instances as you need? L = [] for i in range(x): L.append(track()) Now, you possibly want the class members to be instance members, so need to use self appropriately.

http://stackoverflow.com/comment/89921781
score: 0
comment on: http://stackoverflow.com/a/51474964
type: Comment
has text: Thnks its Working properly ,
type: AnswerComment

http://stackoverflow.com/q/51429975
possible better answer: http://stackoverflow.com/a/51430002
type: Question
upvote count: 1
tagged with: scikit-learn
favorite count: 0
accepted answer: http://stackoverflow.com/a/67001870
tagged with: python
tagged with: gensim
answer count: 4
has answer: http://stackoverflow.com/a/51430002
has answer: http://stackoverflow.com/a/68350213
has body: I try to use from gensim.sklearn_api import W2VTransformer and get ImportError: No module named 'gensim.sklearn_api' I used import gensim import sklearn from sklearn.base import BaseEstimator, TransformerMixin and get the same. In sklearn_api.w2vmodel – Scikit learn wrapper for word2vec model I could find no advice. How to install gensim.sklearn_api?
downvote count: 0
has answer: http://stackoverflow.com/a/67001870
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/66901629
has title: No module named 'gensim.sklearn_api'
score: 1

http://stackoverflow.com/comment/89750394
has text: @Omar Yes, just slice-assign the whole thing, like `ls[:] = [1, 2]` and now the inner list contains just `1` and `2`.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51388356

http://stackoverflow.com/a/51444903
accepted answer of: http://stackoverflow.com/q/51439723
score: 3
has comment: http://stackoverflow.com/comment/89894598
downvote count: 0
has comment: http://stackoverflow.com/comment/89870066
has body: As @Bart suggested, xarray is the way to go. Here's the answer w/o xarray. NetCDF4.date2index() is the answer. import netCDF4 import dateutil.parser nc = netCDF4.Dataset(file.nc, 'r') # all_times variable includes the time:units attribute all_times = nci.variables['time'] sdt = dateutil.parser.parse("2015-07-20T00:00:00") edt = dateutil.parser.parse("2015-07-24T23:00:00") st_idx = netCDF4.date2index(sdt, all_times) et_idx = netCDF4.date2index(edt, all_times) data = nc.variables['temperature'][st_idx:et_idx+1,:] #I want to read between 2015-07-20 00:00 to 2015-07-24 23:00
upvote count: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51439723
type: Answer

http://stackoverflow.com/q/51369184
has answer: http://stackoverflow.com/a/51370032
has comment: http://stackoverflow.com/comment/89711448
type: Question
has comment: http://stackoverflow.com/comment/89711844
downvote count: 0
has comment: http://stackoverflow.com/comment/89711806
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51370032
has comment: http://stackoverflow.com/comment/89711665
answer count: 1
favorite count: 0
has title: What's an efficient way of aggregating multiple columns with multiple custom functions that use multiple columns in a pandas dataframe?
upvote count: 2
tagged with: python
type: AnsweredQuestion
score: 2
has body: I have a grouped pandas dataframe. I want to aggregate multiple columns. For each column, there are multiple aggregate functions. This is pretty straightforward. The tricky part is that in each aggregate function, I want to access data in another column. How would I go about doing this efficiently? Here's the code I already have: import pandas data = [ { 'id': 1, 'A': 1, 'B': 1, 'C': 1, 'D': 1, 'E': 1, 'F': 1, }, { 'id': 1, 'A': 2, 'B': 2, 'C': 2, 'D': 2, 'E': 2, 'F': 2, }, { 'id': 2, 'A': 3, 'B': 3, 'C': 3, 'D': 3, 'E': 3, 'F': 3, }, { 'id': 2, 'A': 4, 'B': 4, 'C': 4, 'D': 4, 'E': 4, 'F': 4, }, ] df = pandas.DataFrame.from_records(data) def get_column(column, column_name): return df.iloc[column.index][column_name] def agg_sum_a_b(column_a): return column_a.sum() + get_column(column_a, 'B').sum() def agg_sum_a_b_divide_c(column_a): return (column_a.sum() + get_column(column_a, 'B').sum()) / get_column(column_a, 'C').sum() def agg_sum_d_divide_sum_e_f(column_d): return column_d.sum() / (get_column(column_d, 'E').sum() + get_column(column_d, 'F').sum()) def multiply_then_sum(column_e): return (column_e * get_column(column_e, 'F')).sum() df_grouped = df.groupby('id') df_agg = df_grouped.agg({ 'A': [agg_sum_a_b, agg_sum_a_b_divide_c, 'sum'], 'D': [agg_sum_d_divide_sum_e_f, 'sum'], 'E': [multiply_then_sum] }) This code produces this dataframe: A D E agg_sum_a_b agg_sum_a_b_divide_c sum agg_sum_d_divide_sum_e_f sum multiply_then_sum id 1 6 2 3 0.5 3 5 2 14 2 7 0.5 7 25 Am I doing this correctly? Is there a better way of doing this? I find the way I access data in another column within the aggregate function a little awkward. The real data and code I'm using has about 20 columns and around 40 aggregate functions. There could potentially be hundreds of groups as well with each group having hundreds of rows. When I do this using the real data and aggregate functions, it can take several minutes which is too slow for my purposes. Any way to make this more efficient? Edit: I'm…

http://stackoverflow.com/comment/89828977
type: Comment
type: QuestionComment
has text: The first 'cycle' starts from a small value and increases until reaching the maximum, the second 'cycle' starts from a lower value than the previous one to another maximum, and so on.
comment on: http://stackoverflow.com/q/51428597
score: 0

index-error
tags question: http://stackoverflow.com/q/51382748
tags question: http://stackoverflow.com/q/51340885
tags question: http://stackoverflow.com/q/51354714
tags question: http://stackoverflow.com/q/51469160
tag name: index-error
type: Tag

http://stackoverflow.com/comment/89838337
type: QuestionComment
comment on: http://stackoverflow.com/q/51433914
has text: This is merely the new matrix multiplication operator. It actually doesn't have any built in implementation, rather, it was added for scientific computing libraries like `numpy` to distinguish matrix multiplication from other types.
score: 0
type: Comment

http://stackoverflow.com/comment/89882501
type: QuestionComment
comment on: http://stackoverflow.com/q/51456497
score: 0
has text: Have you tried extending the calendar view class to add these features you want? Or otherwise find some other calendar library that does this?
type: Comment

http://stackoverflow.com/a/58563178
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51419785
answers question: http://stackoverflow.com/q/51419785
type: Answer
has comment: http://stackoverflow.com/comment/115140503
has body: you may use wikidata python module qwikidata from qwikidata.sparql import return_sparql_query_results query_string = """ SELECT $WDid WHERE { ?WDid (wdt:P279)* wd:Q4022 }""" res = return_sparql_query_results(query_string) for row in res["results"]["bindings"]: print(row["yourFieldName"]["value"])
downvote count: 0
score: 3

http://stackoverflow.com/q/51407175
has answer: http://stackoverflow.com/a/51407206
has body: I have this dataframe import pandas as pd x = pd.DataFrame.from_dict({'A':[1,2,0,4,0,6], 'B':[0, 0, 0, 44, 48, 81], 'C':[1,0,1,0,1,0]}) I try to change it like this, but it doesn't work x[x['A']&gt;3]['A'] = 33 # has no effect I also tried x.loc(x['A']&gt;3)['A'] = 33 # getting an error So what's the right way to do this?
type: Question
answer count: 1
score: 0
linked to: http://stackoverflow.com/q/48035493
tagged with: pandas
has comment: http://stackoverflow.com/comment/89785787
tagged with: python
duplicate of: http://stackoverflow.com/q/48035493
has title: Pandas DataFrame - modify in place based on criteria
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89785552
tagged with: dataframe

http://stackoverflow.com/q/51442628
has comment: http://stackoverflow.com/comment/89855138
tagged with: python
has answer: http://stackoverflow.com/a/51442689
has body: Im trying to find out how multiprocessing works in Python. The following example is what I made: import requests from multiprocessing import Process import time def f(name): print 'hello', name time.sleep(15) print 'ended', name if __name__ == '__main__': urls = [ 'http://python-requests.org', 'http://httpbin.org', 'http://python-guide.org' ] for url in urls: p = Process(target=f, args=(url,)) p.start() p.join() print("finished") What I tried to simulate in f is a request to a URL that has a timeout of 15 seconds. What I expected to happen is that all the request would start at almost the same time and finish at the same time. But what actually happens is they all start one after each other and wait till the previous one is finished. So the result is: hello http://python-requests.org ended http://python-requests.org hello http://httpbin.org ended http://httpbin.org hello http://python-guide.org ended http://python-guide.org So what actually happens? why would one use the code above instead of just doing: for url in urls: f(url)
tagged with: multiprocessing
possible better answer: http://stackoverflow.com/a/51442689
has answer: http://stackoverflow.com/a/51442690
downvote count: 0
score: 2
type: AnsweredQuestion
has title: Python multiprocessing wait for sleep
favorite count: 0
accepted answer: http://stackoverflow.com/a/51442690
type: Question
upvote count: 2
answer count: 2

http://stackoverflow.com/comment/89885724
comment on: http://stackoverflow.com/q/51458095
type: Comment
type: QuestionComment
has text: Also Thank you @JAponte.
score: 1

http://stackoverflow.com/a/55406869
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51471097
has body: The easiest way is to use binary_repr with vectorize, it will preserve the original array shape, e.g.: binary_repr_v = np.vectorize(np.binary_repr) x = np.arange(-9, 21).reshape(3, 2, 5) print(x) print() print(binary_repr_v(x, 8)) The output: [[[-9 -8 -7 -6 -5] [-4 -3 -2 -1 0]] [[ 1 2 3 4 5] [ 6 7 8 9 10]] [[11 12 13 14 15] [16 17 18 19 20]]] [[['11110111' '11111000' '11111001' '11111010' '11111011'] ['11111100' '11111101' '11111110' '11111111' '00000000']] [['00000001' '00000010' '00000011' '00000100' '00000101'] ['00000110' '00000111' '00001000' '00001001' '00001010']] [['00001011' '00001100' '00001101' '00001110' '00001111'] ['00010000' '00010001' '00010010' '00010011' '00010100']]]
upvote count: 2

http://stackoverflow.com/comment/89762442
has text: Also if values in column are `100-200` then can I replace them using (100+200)/2=150 using above technique.
type: AnswerComment
comment on: http://stackoverflow.com/a/51395596
score: 0
type: Comment

eclipse
tag name: eclipse
tags question: http://stackoverflow.com/q/51376060
tags question: http://stackoverflow.com/q/51431742
tags question: http://stackoverflow.com/q/51386630
tags question: http://stackoverflow.com/q/51331133
tags question: http://stackoverflow.com/q/51453681
type: Tag

http://stackoverflow.com/q/51418928
has comment: http://stackoverflow.com/comment/89817273
has body: I'm currently trying to get all window handles from a process started by subprocess.Popen looking like this: def openMP(): mp_p = os.path.abspath("C:\Program Files (x86)\Mobile Partner\Mobile Partner.exe") mp = subprocess.Popen(mp_p, stdin=None, stdout=None, stderr=None, close_fds=True) return mp.pid pid = openMP() wins = get_hwnds_for_pid(pid) for win in wins: print(win, "=&gt;", win32gui.GetWindowText(win)) this is using this function (found here): def get_hwnds_for_pid (pid): def callback (hwnd, hwnds): if win32gui.IsWindowVisible (hwnd) and win32gui.IsWindowEnabled (hwnd): _, found_pid = win32process.GetWindowThreadProcessId (hwnd) if found_pid == pid: hwnds.append (hwnd) return True hwnds = [] win32gui.EnumWindows (callback, hwnds) return hwnds This kind of works but not in the way i would like it too. it returns a single hwnd and i feel it is missing existing child windows. I've tested with the same pid using AutoIts WinList + a simple regex looking like this: ;THIS IS AUTOIT CODE Local $aWinList = WinList("[REGEXPTITLE:(?i)(.*Mobile Partner.*)]") and it indeed returns three instead of one hwnd. I would like my python code to get these three Handles aswell. I've tested around with win32.guiEnumChildWindows but cant get it to work it seems: parent = hwnd childs = [] def callback(hwnd,isx): print(hwnd) print(isx) childs.append(hwnd) ax = win32gui.EnumChildWindows(parent,callback,None) print(ax) for child in childs: print(child) sadly this just returns: pywintypes.error: (2, 'EnumChildWindows', 'The system cannot find the file specified.') i don't really know why. i'm aware that this is quite complicated but maybe you bright minds can help me. To sum it up again: I'm looking for a way to find each and every window handle spawned by a known process id using python (doesn't have to be nativ) on a windows 10 machine. It should return the same amount of handles AutoIts WinList does.
tagged with: python
has title: Find all window handles from a subprocess.Popen pid
has comment: http://stackoverflow.com/comment/89816813
answer count: 0
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89866513
tagged with: autoit
type: Question
has comment: http://stackoverflow.com/comment/89819199
linked to: http://stackoverflow.com/q/31278590
upvote count: 1
tagged with: pywin32
has comment: http://stackoverflow.com/comment/89816860
tagged with: windows-10
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/q/51459932
favorite count: 0
has comment: http://stackoverflow.com/comment/89889129
tagged with: tkinter
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51459948
has body: I'm building a GUI and when I press the search entry button I get the NoneType Error on line 12 of frontend.py. I'm not understanding what the error is telling me fully. Can someone explain a solution to this problem pleas? The search_command function in frontend.py is connected to the search function in backend.py. Maybe I'm missing something obvious. Here is my code frontend.py from tkinter import * import backend def view_command(): list1.delete(0,END) for row in backend.view(): list1.insert(END,row) def search_command(): list1.delete(0,END) for row in backend.search(title_text.get(),author_text.get(),year_text.get(),isbn_text.get()): list1.insert(END,row) window = Tk() # Label widgets l1=Label(window, text="Title") l1.grid(row=0,column=0) l2=Label(window, text="Author") l2.grid(row=0,column=2) l3=Label(window, text="Year") l3.grid(row=1,column=0) l4=Label(window, text="ISBN") l4.grid(row=1,column=2) # Entry widgets title_text=StringVar() e1=Entry(window,textvariable=title_text) e1.grid(row=0,column=1) author_text=StringVar() e2=Entry(window,textvariable=author_text) e2.grid(row=0,column=3) year_text=StringVar() e3=Entry(window,textvariable=year_text) e3.grid(row=1,column=1) isbn_text=StringVar() e4=Entry(window,textvariable=isbn_text) e4.grid(row=1,column=3) # List box list1=Listbox(window, height=6,width=35) list1.grid(row=2,column=0,rowspan=6,columnspan=2) # Scroll bar sb1=Scrollbar(window) sb1.grid(row=2,column=2,rowspan=6) list1.configure(yscrollcommand=sb1.set) sb1.configure(command=list1.yview) # Buttons b1=Button(window,text="View All", width=12,command=view_command) b1.grid(row=2,column=3) b2=Button(window,text="Search entry", width=12,command=search_command) b2.grid(row=3,column=3) b3=Button(window,text="Add Entry", width=12) b3.grid(row=4,column=3) b4=Button(window,text="Update", width=12) b4.grid(row=5,column=3) b5=Button(window,text="Delete", width=12) b5.grid(row=6,column=3) b6=Button(window,text="Close", width=12) b6.grid(row=7,column=3) window.mai…
downvote count: 1
type: Question
upvote count: 0
score: -1
has answer: http://stackoverflow.com/a/51459948
answer count: 1
has title: i get the TypeError: 'NoneType' object is not iterable when i press the Search button on my GUI.

http://stackoverflow.com/q/51423859
favorite count: 0
tagged with: python
upvote count: 4
tagged with: discord
has comment: http://stackoverflow.com/comment/89819841
possible better answer: http://stackoverflow.com/a/64550875
has title: Get profile picture from set user
downvote count: 0
type: Question
type: AnsweredQuestion
tagged with: discord.py
has comment: http://stackoverflow.com/comment/89818761
has answer: http://stackoverflow.com/a/64550875
has body: I'm looking to get my bot to reply to my command with a hard-coded user's profile picture. This is the code I have for now, as it is it replies with the message.author's pfp and I'm wondering if and how I could replace the user = message.author for it to target a hard-coded user. if message.content.upper().startswith('TEST'): userID = message.author.id user = message.author pfp = user.avatar_url embed = discord.Embed( title="test", description='&lt;@%s&gt;, test' % (userID), color=0xecce8b ) embed.set_image(url=pfp) await client.send_message(message.channel, embed=embed) ` I also know that if I switch to "for user in message.mentions" I can get it to pop out the mentioned user's pfp, but again, I want to be able to do this without mentioning anyone. Thank you for your time and any answers brought forward!
answer count: 2
has comment: http://stackoverflow.com/comment/89818677
has comment: http://stackoverflow.com/comment/89821031
score: 4
has answer: http://stackoverflow.com/a/51423962
accepted answer: http://stackoverflow.com/a/51423962

http://stackoverflow.com/q/51399222
tagged with: python
has answer: http://stackoverflow.com/a/51403760
has body: This was the original question: In Django, how can I make session work if the view function has a csrf_exempt decoration? I'm using Django as restful APIs and found that session doesn't work if a view has a csrf_exempt decoration. Here is some code: @csrf_exempt def scorer_login(request): request.session['username'] = request.POST['username'] I found that request.session doesn't change at all when I print request.session.get('username') in other views. However, if there isn't csrf_exempt, it works: def scorer_login(request): request.session['username'] = 'test_username' How can I fix it?
has comment: http://stackoverflow.com/comment/89770109
has title: Why vue-resource doesn't sent cookies in XHR so sessions don't work?
tagged with: django
type: Question
score: 0
has comment: http://stackoverflow.com/comment/89770812
answer count: 1
tagged with: web
tagged with: rest
type: UnansweredQuestion

http://stackoverflow.com/comment/89814633
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51421796
has text: I think there is main general problem - poor./ buggy working pandas functions with non scalar values in Series :(

communication
tag name: communication
type: Tag
tags question: http://stackoverflow.com/q/51385553

http://stackoverflow.com/q/51365019
downvote count: 1
has body: I have two dataframes, df_binary and df_pim. df_binary is shape (462,38) and df_pim is shape (36,34). They look like this: df_binary: Cust_ID Email Topwater Topwater Topwater ... Plastic Plastic Plastic 12345 i@me.com 1 0 0 1 1 0 ... df_pim: Bait Name Technique 1 Technique 2 Technique 3 ... Technique 33 Topwater 1 1 1 0 ... Plastic 1 0 0 1 I want the output to look like this: df_technique: Cust_ID Email Technique 1 Technique 2 Technique 3 ... Technique 33 12345 i@me.com 4 1 2 1 Where the 'technique' columns are the dot product of rows of df_binary and columns of df_pim. Been struggling with this for awhile, here are three tries from what I have so far: # Try 1 df_pim.iloc[:,1:].mul(df_binary) # Try 2 df_binary.iloc[:,2:].dot(df_pim.values) # Try 3 df_binary.iloc[:,2:].multiply(df_pim,axis='index')
tagged with: dataframe
type: Question
answer count: 1
favorite count: 0
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/51366246
has title: Multiplying two dataframes as matrices, preserving column and index headers
type: UnansweredQuestion
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/89906604
score: 0
comment on: http://stackoverflow.com/q/51468774
type: Comment
type: QuestionComment
has text: Aside: `atom_type == "CA" or "N" or "C"` doesn't do what you think it does. See the answer [here](https://stackoverflow.com/questions/20002503/why-does-a-b-or-c-or-d-always-evaluate-to-true).

http://stackoverflow.com/comment/89800618
type: AnswerComment
has text: This is what I wanted. It worked perfectly. Because, I have V and I both are nested lists. Each contains n lists and each list has m values. It is good one and worked for me.
comment on: http://stackoverflow.com/a/51409079
score: 0
type: Comment

http://stackoverflow.com/q/51409668
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/51409708
tagged with: python-3.x
upvote count: 2
possible better answer: http://stackoverflow.com/a/51409718
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51409933
has title: Getting python dictionary item that has min value in a namedtupple
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/51409718
favorite count: 0
accepted answer: http://stackoverflow.com/a/51409708
has body: In Python 3, I have a dictionary of namedtuples and I want to get the dictionary item that has the tuple with smallest (min) value for a given attribute. For example, given: Named = collections.namedtuple('Named', ['A', 'B']) named = {'id1': Named(9, 5), 'id2': Named(5, 4), 'id3': Named(7, 3)} I might want to get the minimum of B, which would be 'id3': Named(7, 3) If this was a list, I would do min(named, key=operator.attrgetter('B')) But, I'm having difficulty getting something similar to work with a dictionary.

http://stackoverflow.com/q/51458095
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51458214
tagged with: python
has comment: http://stackoverflow.com/comment/89886666
has title: Program not recognizing statement as a subcommand of if-elif statement. Why?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89885724
has body: I wrote the program below. Somehow, the program executes the if distance == "...": commands even though I wanted them only to be executed if pickup_location = "no". Probably there is just some basic thing I missed in my program, which brought me here, as I could not fix it and want to ask for your help. I'm perfectly fine with a hint, so I can figure it out. #This program calculates the final price, based on the base price of a car's production price #21.07 Author: 382df7181fcd71a41cfe9b793032c029d139ecb557a4af40ca5de3a148bbbc0d (SHA256) production_price = int(input("How much did it cost to produce the car?")) #parameters to be set sales_margin_percentage = 0.2 tax_rate = 0.23 license_rate = 0.12 dealers_cut = 0.05 delivery_fee_10_100 = 400 delivery_fee_100_250 = 1050 #calculations of extra fees sales_margin = production_price * sales_margin_percentage internal_sales_price = production_price+sales_margin tax = internal_sales_price * tax_rate license_fee = internal_sales_price * license_rate pre_external_sales_price = internal_sales_price + tax + license_fee dealer_prep = pre_external_sales_price * dealers_cut final_price = pre_external_sales_price + dealer_prep pickup_location = input("Do you want to collect the car at the dealer ship?") if pickup_location == "yes": print("Ok. Then the final price would be.", final_price, "We'll give you a call right away when we see the delivery truck from which point on you are free to" "collect it at any point in time.") elif pickup_location == "no": distance = int(input("How far away do you live away from the dealership in kilometers?")) if distance &lt;= 10: print("Nice. Tha:t will mean that you can profit of our free home delivery service and can receive " "your car for the final price of", final_price, "dollars.") elif distance &gt; 10 and distance &lt;= 100: print("Awesome. You can buy and get your car delivered to the front door for the final price of", final_price + delivery_fee_10_100, "Dollars.") elif distance &gt; 100 a…
score: 1
has comment: http://stackoverflow.com/comment/89885720
upvote count: 1
has comment: http://stackoverflow.com/comment/89885523
type: Question
has comment: http://stackoverflow.com/comment/89885601
has answer: http://stackoverflow.com/a/51458214
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/89650086
score: 0
type: AnswerComment
has text: @petrpulc thanks for comment! What do you mean by "this not minimal" - that the OP may have also connected to the wrong serial ?
type: Comment
comment on: http://stackoverflow.com/a/51337738

http://stackoverflow.com/q/51445945
accepted answer: http://stackoverflow.com/a/51446001
score: -4
type: AnsweredQuestion
favorite count: 0
has comment: http://stackoverflow.com/comment/89862466
has comment: http://stackoverflow.com/comment/89862080
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89882444
type: Question
upvote count: 2
tagged with: python
has title: Why is that Python 3 IDE in some sites doesn't support f string function?
has comment: http://stackoverflow.com/comment/89862265
answer count: 1
has answer: http://stackoverflow.com/a/51446001
downvote count: 6
tagged with: f-string
has comment: http://stackoverflow.com/comment/89862127
linked to: http://stackoverflow.com/q/50401632
has comment: http://stackoverflow.com/comment/89877938
has body: f string function print(f"{theString}") makes it easier to print the string than this print("{}".format(theString)) But Python 3 compiler in certain sites doesn't support this function. Is there some specific version of Python for this function to support this. Edit: Hackerrank.com like some other sites just mention it as Python 3 or 2 and no specific version
has comment: http://stackoverflow.com/comment/89862112
duplicate of: http://stackoverflow.com/q/50401632

http://stackoverflow.com/a/57745495
answers question: http://stackoverflow.com/q/51464455
score: 0
type: Answer
upvote count: 2
downvote count: 2
has body: For me, only this worked in python 3: import sys, os # Disable print def blockPrint(): sys.stdout = open(os.devnull, 'w') # Enable print def enablePrint(): sys.stdout = sys.__stdout__ blockPrint() import pygame enablePrint() (thanks for Brigand!)

http://stackoverflow.com/comment/89933047
has text: Thanks for answering, but it turns out I have to put str(user.id) in a variable first before putting it in jsonify
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51481868

http://stackoverflow.com/comment/89699705
type: QuestionComment
comment on: http://stackoverflow.com/q/51363584
has text: Probably 'wrong answer'?
score: 0
type: Comment

http://stackoverflow.com/q/51440692
tagged with: mailgun
type: Question
answer count: 1
score: 0
has title: MailGun API Batch Sending Python
tagged with: send
tagged with: python
has answer: http://stackoverflow.com/a/55097991
accepted answer: http://stackoverflow.com/a/55097991
has comment: http://stackoverflow.com/comment/89918563
type: AnsweredQuestion
has body: I am trying to define a send protocol on the MailGun API with Python. I followed their documentation but it doesn't seem to work. So, I have a dictionary like this: {'email1@domain.pt': {'filepath': 'XXX.pdf', 'ANF': 0000, 'folderfilepath': 'C:\XXX\XXX.pdf', 'index': 77, 'idt': XXX, 'Titulo': 'Estimado Dr. ', 'Farmacia': 'XXX', 'Nome': 'XXX XXX', 'Reports': 1, 'Campanhas': 1, 'Morada': 'XXX, XXX', 'CP': 'XXXX-XXX', 'Localidade': 'XXX', 'Distrito': 'XXX', 'Estado': 'Efetiva'}, {'email2@domain.pt': {'filepath': 'YYY.pdf', ... I created a list to get the keys like: maillist = ['email1@domain.pt', 'email2@domain.pt'] And I my function looks like this: def send_complex_message_batch(): return requests.post( "https://api.mailgun.net/v3/rede.XXX/messages", auth=("api", "key-XXXXXXX"), data={'recipient-variables': recipientVars, "from": "Excited User <geral@XXX.pt>", "to": maillist, "subject": "%recipient.Titulo%", "text": "Testing some Mailgun awesomness, %recipient.Farmacia%, Sr. %recipient.Nome%", "html": " HTML version of the body "}) And it just won't send, it returns ERROR CODE 400: Bad Request - Often missing a required parameter The thing is that it doesn't show on the MailGun Logs as the messages were not sent, so I can't check whats missing. I'm lost here, has anyone had a problem like this? And if I want to go even further, adding a variable attachment, it gets even worse: def send_complex_message_batch(): return requests.post( "https://api.mailgun.net/v3/rede.XXX/messages", auth=("api", "key-XXX"), data={'recipient-variables': recipientVars, "from": "Excited User <geral@XXX.pt>", "to": maillist, "subject": "%recipient.Titulo%", "text": "Testing some Mailgun awesomness, %recipient.Farmacia%, Sr. %recipient.Nome%", "html": " HTML version of the body "}, files=[("attachment", ("%recipient.filepath%", open("%recipient.folderfilepath%", "rb").read()))]) With error FileNotFoundError: [Errno 2] No such file or directory: '%recipient.folderfilepath%' I would be very gra…

http://stackoverflow.com/comment/89841646
type: QuestionComment
has text: If you are serious about nested brackets, you should split like this: [`re.split(r',\n*(?=(?:[^()]*\([^()]*\))*[^()]*$)`](https://ideone.com/3htUeD)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51433630

http://stackoverflow.com/q/51345535
accepted answer: http://stackoverflow.com/a/51346165
score: 0
has comment: http://stackoverflow.com/comment/89666186
answer count: 1
tagged with: keras
has title: CNN Keras Dog cat classification if image contain both dog and cat
has comment: http://stackoverflow.com/comment/89665460
has comment: http://stackoverflow.com/comment/89665061
has comment: http://stackoverflow.com/comment/89665330
tagged with: convolution
tagged with: python
tagged with: multilabel-classification
type: AnsweredQuestion
has body: I modified dog cat binary classification to make multi-class activation by using Sigmoid activation function in output layer to get prediction for each individual class, but it failed to get expected results. I created a image which have both dog and cat in single image. Expected Result: Dog : 70% or more than 70%, Cat : 70% or more than 70% Actual Results: Dog : 70 %, Cat : 25 % Why is it not predicting individual class with high accuracy? import numpy as np from keras.models import Sequential; from keras.layers import Conv2D, MaxPooling2D, Dense, Flatten; from keras.utils.np_utils import to_categorical from keras import optimizers classifier = Sequential(); classifier.add(Conv2D(32,(3,3),input_shape=(64,64,3),activation='relu')); classifier.add(MaxPooling2D((2,2))); classifier.add(Conv2D(32,(3,3),activation='relu')); classifier.add(MaxPooling2D((2,2))); classifier.add(Conv2D(32,(3,3),activation='relu')); classifier.add(MaxPooling2D((2,2))); classifier.add(Flatten()); classifier.add(Dense(100, activation='sigmoid')) classifier.add(Dense(2,activation='sigmoid')); classifier.compile(optimizer="adam", loss='categorical_crossentropy', metrics=['accuracy']) from keras.preprocessing.image import ImageDataGenerator trainingDataOptions = ImageDataGenerator(rescale=1./255,shear_range=0.2,zoom_range=0.2,horizontal_flip=True) testingDataOptions = ImageDataGenerator(rescale=1./255) trainingData = trainingDataOptions.flow_from_directory('dataset/training',target_size=(64,64),batch_size=32); testingData = testingDataOptions.flow_from_directory('dataset/testing',target_size=(64,64),batch_size=32); classifier.fit_generator(trainingData, samples_per_epoch=1757, nb_epoch=10, validation_data=testingData, nb_val_samples=308) classifier.save('model.h5') # Output from keras.preprocessing import image test_image = image.load_img('samples/319b5fa.jpg',target_size=(64,64)) test_image = image.img_to_array(test_image) test_image = np.expand_dims(test_image, axis=0) res = classifier.predict(t…
has comment: http://stackoverflow.com/comment/89665826
tagged with: machine-learning
type: Question
has answer: http://stackoverflow.com/a/51346165

http://stackoverflow.com/comment/89890058
has text: Which buttons?, shows your .ui
score: 0
comment on: http://stackoverflow.com/q/51456041
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51607498
type: Answer
has body: The srun command propagates all of the user's environment to the compute node by default. You can control which variables are to be exported with the --export parameter.
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51452723
answers question: http://stackoverflow.com/q/51452723

tcp
type: Tag
tags question: http://stackoverflow.com/q/51477487
tags question: http://stackoverflow.com/q/51382936
tags question: http://stackoverflow.com/q/51381936
tag name: tcp

http://stackoverflow.com/comment/89735101
comment on: http://stackoverflow.com/q/51381375
has text: updating question
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89911689
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51471699
has text: Can you show `urls.py`? In general you don't have to add `.html` to your django urls.
score: 0

http://stackoverflow.com/q/51436766
accepted answer: http://stackoverflow.com/a/51439808
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/51439808
favorite count: 0
has title: scipy interpolate 2D data imported from file
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89847760
tagged with: scipy
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/89848652
has body: This is the first time I will use python, scipy and all the concepts required for this task. I have used Mathematica to calculate and display a very complex function in a 3D plot. Exporting from Mathematica is a real pain and never gives publication ready figures in a reasonable time frame. Gnuplot also is not very good with 3D plots therefore I through about using matplotlib. Reading through the documentation I see that all examples of plotting involve simple functions and variables defined as vector by the user. My first problem is as follows: I can export the function data from Mathematica in a file with 3 tab separated columns (the separation can be something else if it helps!). First column is the x axis, second is y and third is z axis. What I need to plot basically is z(x,y). How does one import such data file for plotting? The second question is: In order to obtain a smooth surface plot, do I need to perform some kind of interpolation of the data? If this is the case, then how can it be done with data imported from the file I described? From this example here, the scipy.interpolate.interp2d function(?) needs two 1D vectors x and y and a 2D vector for z, in order to obtain an interpolated function z(x,y). But my data is x (first column) is 1D vector, y (second column) is 1D vector and z (third column) is 1D vector. The examples given there are a bit confusing to me because they use defined x and y vectors and a function for z which they then proceed to interpolate (i don't see the point of interpolation here). I am hopping someone will point me in the right direction with this!
tagged with: matplotlib

http://stackoverflow.com/comment/89848894
comment on: http://stackoverflow.com/q/51439032
has text: do you mean you want to pass the entire column 'feature1' instead of just an element of 'feature1' in each call?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51333358
tagged with: python
tagged with: properties
has title: class property conversions
has body: I have to use a class. I have to make sure that x and y are properties. If the values ​​provided are not convertible to an integer, raise an AttributeError. If we give a value less than 0 to x or y, it is assigned the value 0. If we give a value greater than 10 to x or y, it is assigned the value 10. Here is my code: class Point: def __init__(self, x, y): self.x = x self.y = y def getx(self): x=int() return self._x def gety(self): y=int() return self._y if x&gt;=0: return 0 else if x&lt;=10: return 10 I want to obtain this: p = Point(1,12) print(p.x, p.y) # output "1 10" p.x = 25 p.y = -5 print(p.x, p.y) # output "10 0"
type: Question
has comment: http://stackoverflow.com/comment/89647063
has comment: http://stackoverflow.com/comment/89642307
tagged with: class
score: 0
has comment: http://stackoverflow.com/comment/89642164
answer count: 1
has answer: http://stackoverflow.com/a/51333467
type: UnansweredQuestion

http://stackoverflow.com/comment/89781510
comment on: http://stackoverflow.com/q/51404807
score: 0
type: Comment
type: QuestionComment
has text: Did you try to call `task_done()` on queue in worker thread? https://docs.python.org/3/library/queue.html#queue.Queue.task_done

http://stackoverflow.com/comment/89679529
score: 0
type: AnswerComment
type: Comment
has text: My apologies. I have corrected the code. The values now match the original table added to the post.
comment on: http://stackoverflow.com/a/51352629

http://stackoverflow.com/comment/89915398
has text: Thank you so much for this answer, I didn't know you can work in Django without Virtualenv. I will search more about this.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51472200
type: AnswerComment

http://stackoverflow.com/q/51479468
score: 0
has body: According to the Microsoft documentation: "Installation of SQL Server 2017 Machine Learning Services adds the Anaconda distribution of Python. Specifically, the Anaconda 3 installers are used, based on the Anaconda 4.3 branch. The expected Python level for SQL Server 2017 is Python 3.5." I read quite a few documents linked from this site, but I couldn't find any answers to these two questions: Can one define different conda environments on the server where Machine Learning Services are activated? If (1) is possible, how can someone define which conda environment should be used when calling the sp_execute_external_script stored procedure?
has comment: http://stackoverflow.com/comment/89933799
answer count: 1
has answer: http://stackoverflow.com/a/51814472
tagged with: sql-server
tagged with: python
accepted answer: http://stackoverflow.com/a/51814472
has title: Microsoft SQL Server 2017 and conda environments
type: AnsweredQuestion
tagged with: anaconda
type: Question

http://stackoverflow.com/a/51346629
answers question: http://stackoverflow.com/q/51346551
has comment: http://stackoverflow.com/comment/89666551
type: AcceptedAnswer
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/89667681
has body: You can use nltk.tokenize.word_tokenize() in a list comprehension as in: In [112]: from nltk.tokenize import word_tokenize In [113]: tokenized = [word_tokenize(sent) for sent in text] which outputs: [['this', 'is', 'the', 'first', 'sentence', 'of', 'the', 'first', 'paragraph', '.', 'and', 'this', 'is', 'the', 'second', 'sentence', '.'], ['some', 'random', 'text', 'in', 'the', 'second', 'paragraph', . . . . ]]
accepted answer of: http://stackoverflow.com/q/51346551
score: 3
has comment: http://stackoverflow.com/comment/89666360
downvote count: 0

http://stackoverflow.com/a/51348839
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51348759
has body: You can try a simple try and except block to format the data accordingly. def format(x): try: return "{:,}".format(float(x)) except: return x df_both['col1'] = df_both['col1'].apply(lambda x: format(x))
answers question: http://stackoverflow.com/q/51348759
type: Answer
score: 0

mininet
tag name: mininet
tags question: http://stackoverflow.com/q/51459934
type: Tag

http://stackoverflow.com/comment/89920477
comment on: http://stackoverflow.com/a/51474573
type: AnswerComment
type: Comment
has text: Surely will try using matplotlib itself but want to wrap these up as fast as possible. With your seaborn example, almost worked except minor glitches. Matplotlib not seem to be spacing properly the title, it gets cut. More importantly, frames are redrawn, so earlier frame points not retained. My updated code [here](http://nbviewer.jupyter.org/gist/parthi2929/d85e691099d79f9e96e91163acba9e40), output screenshot [here](https://s22.postimg.cc/se3vd9npt/image.png), desired effect [here](https://www.khanacademy.org/computer-programming/unbiased-estimate-of-population-variance/1169428428)
score: 0

http://stackoverflow.com/comment/89833408
comment on: http://stackoverflow.com/q/51382162
score: 0
type: Comment
type: QuestionComment
has text: @jstein123 for splinter, how does it compare to bs4. My entire platform uses bs4 for scraping. (Let it be known this platform has over 35,000 lines of code a simple switch isn't easy if it involves rebuilding)

bash
tags question: http://stackoverflow.com/q/51452760
tags question: http://stackoverflow.com/q/51443998
tags question: http://stackoverflow.com/q/51472136
tags question: http://stackoverflow.com/q/51412941
tags question: http://stackoverflow.com/q/51468046
tags question: http://stackoverflow.com/q/51350574
tags question: http://stackoverflow.com/q/51397234
tags question: http://stackoverflow.com/q/51464677
tags question: http://stackoverflow.com/q/51406567
tags question: http://stackoverflow.com/q/51359946
tags question: http://stackoverflow.com/q/51479642
type: Tag
tags question: http://stackoverflow.com/q/51414103
tags question: http://stackoverflow.com/q/51452078
tags question: http://stackoverflow.com/q/51344158
tag name: bash
tags question: http://stackoverflow.com/q/51350762
tags question: http://stackoverflow.com/q/51345198

http://stackoverflow.com/comment/89827599
type: QuestionComment
has text: Let me know if the solution works for you!
score: 0
comment on: http://stackoverflow.com/q/51426697
type: Comment

http://stackoverflow.com/a/68522655
score: -1
upvote count: 0
has body: For some reason the import from django.contrib.auth.backends import BaseBackend caused this problem. I suspect that BaseBackend tries to use the user model, but can't because it's defined further down the file. However if you define your model BEFORE that import then it'll work just fine.
type: Answer
downvote count: 1
answers question: http://stackoverflow.com/q/51349736

http://stackoverflow.com/q/51386997
tagged with: gil
has comment: http://stackoverflow.com/comment/89817886
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51390341
tagged with: python
score: 2
has body: I have a Windows routine that uses the Python Library. I started out with 3.6.5 and a static library. Got it to work. Moved to a .dll Python library. Also works. Moved to 3.7. Does NOT work. It hangs when I attempt to close the embedded Python with a call to PyGILState_Ensure() and then Py_Finalize(). It hangs on the call to PyGILState_Ensure(). So I backed off a bit and went with Python 3.6.6. This also works. Same code, just a different library. Has anyone else noticed a change in behavior of the GIL stuff for Python 3.7? In the documentation, they mentioned they made some changes with the GIL.
upvote count: 2
type: Question
has title: Python 3.7 and PyGILState_Ensure() (Windows)
tagged with: python-3.6
tagged with: python-3.7
answer count: 1
downvote count: 0

http://stackoverflow.com/a/51361056
accepted answer of: http://stackoverflow.com/q/51360569
type: AcceptedAnswer
downvote count: 0
has body: The key is to add an item column if it isn't present. I wasn't sure what Null was so I inserted nan to keep with the default pandas format. import pandas as pd import numpy as np data = pd.DataFrame({ 'User': ['u1', 'u2', 'u3', 'u4', 'u5', 'u5', 'u1'], 'Item': ['i1', 'i2', 'i3', 'i1', 'i2', 'i4', 'i4'], 'Rating': [3, 4, 5, 2, 1, 3, 2] }) train_data = data.head(3) test_data = data.tail(4) train_pivot = pd.pivot_table( train_data, values='Rating', index=['User'], columns=['Item'] ) test_pivot = pd.pivot_table( test_data, values='Rating', index=['User'], columns=['Item'] ) unique_items = data['Item'].unique() for item in unique_items: if item not in test_pivot: test_pivot[item] = np.nan if item not in train_pivot: train_pivot[item] = np.nan # If you want the columns sorted alphabetically train_pivot = train_pivot.reindex_axis(sorted(train_pivot.columns), axis=1) test_pivot = test_pivot.reindex_axis(sorted(test_pivot.columns), axis=1) Results in the outputs: train_pivot: Item i1 i2 i3 i4 User u1 3.0 NaN NaN NaN u2 NaN 4.0 NaN NaN u3 NaN NaN 5.0 NaN test_pivot: Item i1 i2 i3 i4 User u1 NaN NaN NaN 2.0 u4 2.0 NaN NaN NaN u5 NaN 1.0 NaN 3.0
answers question: http://stackoverflow.com/q/51360569
type: Answer
upvote count: 3
score: 3

http://stackoverflow.com/comment/89716087
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51372034
has text: Then I don't understand what you're asking

http://stackoverflow.com/comment/89696903
type: QuestionComment
comment on: http://stackoverflow.com/q/51362250
score: 4
has text: Without posting the original image, it is impossible to ascertain what rotation you should be expecting. Additionally, it should be, `rotated = cv2.warpAffine(image, M, (w, h))`
type: Comment

http://stackoverflow.com/q/51396110
type: Question
has body: all - I'm trying to perform a regex on a bunch of science data, converting certain special symbols into ASCII-friendly characters. For example, I want to replace 'µ'(UTF-8 \xc2\xb5) to the string 'micro', and '±' with '+/-'. I cooked up a python script to do this, which looks like this: import re def stripChars(string): outString = (re.sub(r'\xc2\xb5+','micro', string)) #Metric 'micro (10^-6)' (Greek 'mu') letter outString = (re.sub(r'\xc2\xb1+','+/-', outString)) #Scientific 'Plus-Minus' symbol return outString However, for these two specific characters, I'm getting strange results. I dug into it a bit, and it looks like I'm suffering from the bug described here, in which certain characters come out wrong because they are UTF data being interpreted as Windows-1252 (or ISO 8859-1). I grepped the relevant data, and found that it is returning the erroneous result there as well (e.g. the 'µ' appears as 'Âµ') However, elsewhere in the same data set there exists datum in which the same symbol is displayed correctly. This may be due to a bug in the system which collected the data in the first place. The real weirdness is that it seems my current code only catches the incorrect version, letting the correct one pass through. In any case, I'm really stuck on how to proceed. I need to be able to come up with a series of regex substitutions which will catch both the correct and incorrect versions of these characters, but the identifier for the correct version is failing in this case. I must admit, I'm still fairly junior to programming, and anything more than the most basic regex is still like black magic to me. This problem seems a bit more intractable than any I've had to tackle before, and that's why I bring it to here to get some more eyes on it. Thanks!
linked to: http://stackoverflow.com/q/3710374
tagged with: ascii
answer count: 2
score: 3
has comment: http://stackoverflow.com/comment/89763635
downvote count: 0
has comment: http://stackoverflow.com/comment/89763572
favorite count: 0
has answer: http://stackoverflow.com/a/51409037
tagged with: iso-8859-1
has comment: http://stackoverflow.com/comment/89786755
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51415848
has comment: http://stackoverflow.com/comment/89788110
tagged with: regex
tagged with: text
upvote count: 3
has comment: http://stackoverflow.com/comment/89786687
has title: Regex conflict for certain characters (ISO-8859-1 Windows-1252)

http://stackoverflow.com/comment/89661094
comment on: http://stackoverflow.com/q/51340316
score: 0
has text: Isn't [this](https://stackoverflow.com/a/14946745/1566221) what you are asking for?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89888145
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51459335
has text: @Anthony Note that my solution will work for multiple values on a single line.
type: Comment

http://stackoverflow.com/comment/89676839
score: 0
type: Comment
type: QuestionComment
has text: the \s+ is a separator whitespace, i read it is the default separation for .dat file https://stackoverflow.com/questions/47038101/save-data-as-a-dat-file
comment on: http://stackoverflow.com/q/51352069

http://stackoverflow.com/comment/89646944
has text: Thank you. The between version is really neat
type: AnswerComment
comment on: http://stackoverflow.com/a/51335351
type: Comment
score: 2

http://stackoverflow.com/comment/89675219
type: Comment
comment on: http://stackoverflow.com/q/51351309
has text: If you really want it in a for loop, just use `print(l[x], end=' ')`
score: 1
type: QuestionComment

http://stackoverflow.com/a/51325536
upvote count: 2
has comment: http://stackoverflow.com/comment/89626540
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51325430
has body: Inserting rows is expensive. You can use groupby + last, concatenate two dataframes, and then sort_values: df_last = df.groupby('Car_ID', as_index=False).last().assign(Info='Changed') res = pd.concat([df, df_last], ignore_index=True)\ .sort_values('Car_ID')\ .reset_index(drop=True) print(res) Car_ID Date Driver Info 0 B332 2018-03-15 Alex Group_B 1 B332 2018-03-14 Alex Group_B 2 B332 2018-03-12 Alex Group_B 3 B332 2018-03-12 Alex Changed 4 C315 2018-03-15 Sara Group_C 5 C315 2018-03-14 Sara Group_C 6 C315 2018-03-13 Sara Group_C 7 C315 2018-03-12 Sara Group_C 8 C315 2018-03-11 Sara Group_C 9 C315 2018-03-11 Sara Changed 10 F310 2018-03-10 Franck Group_F 11 F310 2018-03-09 Franck Group_F 12 F310 2018-03-09 Franck Changed
accepted answer of: http://stackoverflow.com/q/51325430
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/51461444
score: 1
accepted answer of: http://stackoverflow.com/q/51461422
has comment: http://stackoverflow.com/comment/89892081
answers question: http://stackoverflow.com/q/51461422
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89892111
type: Answer
has comment: http://stackoverflow.com/comment/89892074
has comment: http://stackoverflow.com/comment/89892378
has body: getitem() is probably implemented in C and not Python, and does not support keyword arguments. Implementation of Python functions using the C API is considerably different to implementation using Python itself. In particular the argument parsing is more explicit when using the C API.
downvote count: 0

http://stackoverflow.com/comment/89894611
has text: That's a good point, Reblochon. The inverted picture is because of the use of `pcolor()`. The alternative (what you might like to see) is the use of `imshow()`, which will be in consonance with the printed array elements. The `pcolor` function puts the origin `(0,0)` like how we would normally do in a graph; the reason why I prefered it.
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51462787

http://stackoverflow.com/q/51374233
has body: This dockerfile will obviously not work: FROM python:3.7.0-alpine RUN pip install gevent since there is no compiler in alpine. Is it possible to install it in a different docker image and then copy it to my image? In other words, can i achieve that by replacing &lt;???&gt; with something? FROM python:3.7.0-streach as base RUN pip install gevent FROM python:3.7.0-alpine COPY --from=base &lt;???&gt;
tagged with: alpine-linux
tagged with: python
accepted answer: http://stackoverflow.com/a/58090886
tagged with: gevent
possible better answer: http://stackoverflow.com/a/51862086
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/58090886
type: Question
answer count: 2
score: -1
has answer: http://stackoverflow.com/a/51862086
tagged with: docker
has title: Build python's gevent in outer Docker image
downvote count: 1
favorite count: 0
upvote count: 0

http://stackoverflow.com/comment/89892652
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51461262
has text: The complete error message has been added to the question.

http://stackoverflow.com/comment/89662414
comment on: http://stackoverflow.com/q/51344512
type: Comment
type: QuestionComment
has text: I could not replicate your results either with the given code. Are you doing something else between the assignment of legal_drinker and shape commands?
score: 1

http://stackoverflow.com/comment/89872967
comment on: http://stackoverflow.com/a/51450548
has text: Nope. It's all in Crystal.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51453846
has body: First sorry for the false hint I gave you, there are far simpler things to do. In fact there are far simpler things to do than using a regex here. regex are far too powerful to do this, you can achieve the same result without. DNS message format is defined in RFC 1035 : "DOMAIN NAMES - IMPLEMENTATION AND SPECIFICATION" Name compression is explained in section 4.1.4. Note also that you have to take into account the case insensitive aspect, as outlined in section 2.3.3 It should be the case in the following code that can surely be optimized, with example names taken from RFC: #!/usr/bin/python3 names=['F.ISI.ARPA', 'FOO.F.ISI.ARPA', 'ARPA'] cache={} pos=0 results=[] for name in names: labels = name.split('.') while len(labels): key = '.'.join(labels) if key.lower() in cache: results.append((cache[key.lower()] + 2**15 + 2**14).to_bytes(2, 'big')) pos += 2 break else: label = labels.pop(0).encode('ascii') length = len(label).to_bytes(1, 'big') results.append(length + label) cache[key.lower()] = pos pos += len(label) + 1 else: results.append(b'0') pos += 1 print(results) which produces: [b'\x01F', b'\x03ISI', b'\x04ARPA', b'0', b'\x03FOO', b'\xc0\x00', b'\xc0\x06'] If instead using your example: names=['store.example.com', 'blog.example.com', 'my.blog.example.com'] it produces: [b'\x05store', b'\x07example', b'\x03com', b'0', b'\x04blog', b'\xc0\x06', b'\x02my', b'\xc0\x13']
score: 2
has comment: http://stackoverflow.com/comment/89877469
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51449468
has comment: http://stackoverflow.com/comment/89877658
answers question: http://stackoverflow.com/q/51449468
has comment: http://stackoverflow.com/comment/89886916
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89885762
type: Answer

http://stackoverflow.com/q/51355524
linked to: http://stackoverflow.com/q/52887227
linked to: http://stackoverflow.com/q/49404993
answer count: 2
has answer: http://stackoverflow.com/a/53860557
downvote count: 0
tagged with: keras
favorite count: 0
has title: Use multiple directories for flow_from_directory in Keras
has answer: http://stackoverflow.com/a/62694015
has body: My scenario is that we have multiple peers with their own data, located in different directories, with the same sub-directory structure. I want to train the model using those data, but if I copy all of them to one folder, I can't keep track of which data is from whose (the new data is also created occasionally so it's not suitable to keep copy the files every time) My data is now stored like this: -user01 -user02 -user03 ... (all of them have similar sub-directory structure) I have searched for solution, but I only found the multi-input case in here and here, which they concatenate multiple input into 1 single parallel input, which is not my case. I know that the flow_from_directory() can only be fed by 1 directory at a time, so how can I build a custom one that can be fed by multiple directory at a time? If my question is low-quality, please give advice on how to improve it, I have searched also on the github of keras but didn't find anything that I can adapt. Thank you.
tagged with: python
type: UnansweredQuestion
score: 7
upvote count: 7
tagged with: tensorflow
linked to: http://stackoverflow.com/q/46450184
type: Question

http://stackoverflow.com/q/51395590
has comment: http://stackoverflow.com/comment/89762654
answer count: 2
has answer: http://stackoverflow.com/a/51395834
downvote count: 0
has comment: http://stackoverflow.com/comment/89762864
favorite count: 0
has comment: http://stackoverflow.com/comment/89762617
has answer: http://stackoverflow.com/a/51396086
has body: I have a string contains datetimes, I am trying to split the string based on the datetime occurances, data="2018-03-14 06:08:18, he went on \n2018-03-15 06:08:18, lets play" what I am doing, out=re.split('^(2[0-3]|[01]?[0-9]):([0-5]?[0-9]):([0-5]?[0-9])$',data) what I get ["2018-03-14 06:08:18, he went on 2018-03-15 06:08:18, lets play"] What I want: ["2018-03-14 06:08:18, he went on","2018-03-15 06:08:18, lets play"]
tagged with: pandas
tagged with: datetime
tagged with: python
tagged with: regex
upvote count: 6
has title: regex pattern to match datetime in python
tagged with: python-3.x
score: 6
accepted answer: http://stackoverflow.com/a/51396086
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89762592
possible better answer: http://stackoverflow.com/a/51395834
type: Question

http://stackoverflow.com/q/51464763
has comment: http://stackoverflow.com/comment/89898482
has comment: http://stackoverflow.com/comment/98185463
tagged with: argparse
has comment: http://stackoverflow.com/comment/89898276
tagged with: python
has answer: http://stackoverflow.com/a/51465396
tagged with: python-3.x
type: UnansweredQuestion
score: 1
upvote count: 1
type: Question
has body: I use argparse (Python 3) to execute one of the subcommands. I want to initialize a class instance of a class which depends on the chosen subcommand. (However, all these classes have a common base class which contains fields common for all subcommands.) For example for chain subcommand I want to fill values in an object of TransformationAutomaticWorkflowElementOptions class. The question: What is a good way to create the object of the right type dependently on the user's subcommand? and how to fill its fields (both common fields of the base class (see options common for all subparsers) and special fields of this particular derived class) then? The problem is to call the constructor determined by a particular subcommand before processing all other options. Below is an (almost) real code: #!/usr/bin/env python import argparse parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description="Automatically process XML.") subparsers = parser.add_subparsers(title='subcommands') parser.add_argument('-p', '--preload', help='preload asset', action='append', metavar='NAMESPACE') parser.add_argument('-r', '--recursive', help='recursive download mode (none, breadth-first, depth-first)', choices=['none', 'breadth', 'depth']) parser.add_argument('-x', '--recursive-order', metavar='ORDER', help='recursive download order (comma separated "sources", "targets", "workflowtargets")') parser.add_argument('-d', '--downloaders', metavar='DOWNLOADERS', help='a plus-separated list of comma-separated lists of "builtin","ns"') chain_parser = subparsers.add_parser('chain', aliases=['c'], help='Automatically run a chain of transformations') chain_parser.add_argument('source', nargs='?', help='source document (defaults to stdin)') chain_parser.add_argument('-o', '--output', nargs=1, help='output file (defaults to stdout)') chain_parser.add_argument('-t', '--target', help='target namespace(s)', action='append', metavar='NAMESPACE') chain_parser.add_argument('-n',…
has comment: http://stackoverflow.com/comment/89902408
has title: argparse, subcommands, and inheritance
answer count: 1
downvote count: 0
tagged with: inheritance
favorite count: 0

http://stackoverflow.com/comment/89721465
type: Comment
has text: Is there a way I can get which `Xtalk #` does the value come under?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51374703

http://stackoverflow.com/q/51480139
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/89929015
tagged with: python
accepted answer: http://stackoverflow.com/a/51480344
score: 2
type: AnsweredQuestion
upvote count: 2
type: Question
has title: Python - Compare similar values in two columns from two different csv
has answer: http://stackoverflow.com/a/51480344
has comment: http://stackoverflow.com/comment/89929088
has body: I have two CSV files with the same row names: Name, Lastname. However, file2.csv has an extra column named Attention Each file has a different list of name and lastname (not in order). I'm trying to find a way to find to print the attention column, if the name and lastname are in both files. This is what I have so far: with open('result.csv') as r: set1 = set(x[0] for x in csv.reader(r)) with open('result2.csv') as r: set2 = set(x[0] for x in csv.reader(r)) for x, y in zip(set1, set2): if x[0] == y[0]: print("Matched") How can I read the first and second column for each file? Thank you edit: being more clear
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89928963

http://stackoverflow.com/q/51404585
has title: Using Python Pandas to re-organize data from lists into the table
has comment: http://stackoverflow.com/comment/89781010
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89781378
has comment: http://stackoverflow.com/comment/89782438
type: Question
accepted answer: http://stackoverflow.com/a/51406038
has body: I have developed a Vehicle Routing (VRP) model that can optimise the route planning by assigning right delivery locations to the right vehicle. The input of my model is a input.csv, which can be loaded as a data frame shown below, where each locations are assigned with a unique ID, GPS coordinates and delivery demand. The starting point is the distribution center. ID Location_name Location_Lat Location_Lon Date Demand 0 DC 51.4457678 -0.45613 3/4/2016 0 1 Customer_1 51.799089 -0.29716 3/4/2016 472 2 Customer_2 52.497911 -1.903832 3/4/2016 1488 3 Customer_3 53.74589 -2.379778 3/4/2016 5652 4 Customer_4 52.332395 -1.346753 3/4/2016 2348 5 Customer_5 52.276323 -1.579845 3/4/2016 12 6 Customer_6 52.254674 -0.265726 3/4/2016 2940 7 Customer_7 51.480381 0.332106 3/4/2016 2533 8 Customer_8 51.466844 -0.452952 3/4/2016 1142 9 Customer_9 51.714144 -0.462949 3/4/2016 115 10 Customer_10 50.918412 -0.14951 3/4/2016 325 11 Customer_11 52.042318 0.311799 3/4/2016 886 12 Customer_12 52.084242 0.457063 3/4/2016 412 13 Customer_13 52.126166 0.602327 3/4/2016 58 14 Customer_14 52.16809 0.747591 3/4/2016 161 15 Customer_15 52.210014 0.892855 3/4/2016 29 Then I run my model and I will get a output (a variable as list of lists): [[0,8,3,6,11,13,0],[0,12,9,5,0],[0,4,7,10,15,1,14,2,0]]. This means I have to use 3 vehicles: Routes for vehicle 0: [0,8,3,6,11,13,0] #always start and back to DC Routes for vehicle 1: [0,12,9,5,0] Routes for vehicle 2: [0,4,7,10,15,1,14,2,0] Now I want to add a new output function that allows the model to reorganise the above output result in a table format as below:(pay attention to the first/last three rows) ID Location_name Location_Lat Location_Lon Date demand Vehicle_ID Pos_in_routes 0 DC 51.4457678 -0.45613 3/4/2016 0 0 0 0 DC 51.4457678 -0.45613 3/4/2016 0 1 0 0 DC 51.4457678 -0.45613 3/4/2016 0 2 0 1 Customer_1 51.799089 -0.29716 3/4/2016 472 2 5 2 Customer_2 52.497911 -1.903832 3/4/2016 1488 2 7 3 Customer_3 53.74589 -2.379778 3/4/2016 5652 0 2 4 Custo…
score: 0
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/51406038
has comment: http://stackoverflow.com/comment/89784661

http://stackoverflow.com/comment/89890425
has text: it's part of the python install it's a cli program that you can execute. it should show you where the include directory is for python.
comment on: http://stackoverflow.com/q/51460264
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89670611
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51336298
has text: thanks a lot @eyllanesc, I was mislead by the QVariant methods toInt(), toFloat(), toBool(), ...
type: AnswerComment

http://stackoverflow.com/comment/89936648
type: QuestionComment
has text: Look at [`ctypes.PyDLL`](https://docs.python.org/2/library/ctypes.html#ctypes.PyDLL) - ctypes automatically releases the GIL and in your case this isn't helpful
comment on: http://stackoverflow.com/q/51443022
score: 1
type: Comment

http://stackoverflow.com/comment/89922220
score: 0
has text: @PeterWood: OK, you are right, but try to create a new file in Explorer and enter a colon. That will not succeed for the time being.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51476763

sorting
tags question: http://stackoverflow.com/q/51354466
tags question: http://stackoverflow.com/q/51449860
tags question: http://stackoverflow.com/q/51431380
tags question: http://stackoverflow.com/q/51435019
tags question: http://stackoverflow.com/q/51436534
tags question: http://stackoverflow.com/q/51333966
tags question: http://stackoverflow.com/q/51343367
tags question: http://stackoverflow.com/q/51455468
tags question: http://stackoverflow.com/q/51374995
tags question: http://stackoverflow.com/q/51449901
tags question: http://stackoverflow.com/q/51418552
type: Tag
tags question: http://stackoverflow.com/q/51434771
tags question: http://stackoverflow.com/q/51440046
tags question: http://stackoverflow.com/q/51446082
tags question: http://stackoverflow.com/q/51325462
tags question: http://stackoverflow.com/q/51331845
tag name: sorting
tags question: http://stackoverflow.com/q/51357333
tags question: http://stackoverflow.com/q/51367555

http://stackoverflow.com/comment/89738144
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51383095
score: 0
has text: You did a `print (poly)`, could we have the content of this variable?

http://stackoverflow.com/q/51385792
favorite count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 0
score: 1
tagged with: tensorflow
type: Question
has title: TensorFlow vid2depth icp_op load fails: dynamic module and init function
has answer: http://stackoverflow.com/a/53447545
upvote count: 1
answer count: 1
has body: Info formatted like requested on bug reports, but I figure I'll ask here first. System information What is the top-level directory of the model you are using: research/vid2depth Have I written custom code (as opposed to using a stock example script provided in TensorFlow): Build system fixes only OS Platform and Distribution (e.g., Linux Ubuntu 16.04): Ubuntu 16.04, Python 2.7 or Python 3.5 TensorFlow installed from (source or binary): pip TensorFlow version (use command below): ('v1.6.0-0-gd2e24b6039', '1.6.0') Bazel version (if compiling from source): Installed from package manager, 0.15.2 CUDA/cuDNN version: CUDA 9.0, cuDNN 7.1.2.21-1+cuda9.0 GPU model and memory: GTX 1080 Exact command to reproduce: After compiling icp_op.so, run the command: python train.py \ --data_dir ~/vid2depth/data/kitti_raw_eigen \ --seq_length 3 \ --reconstr_weight 0.85 \ --smooth_weight 0.05 \ --ssim_weight 0.15 \ --icp_weight 0 \ --checkpoint_dir ~/vid2depth/checkpoints Describe the problem Describe the problem clearly here. Be sure to convey here why it's a bug in TensorFlow or a feature request. There seems to be a bug in either the model.py script or the icp_op.so library compiled within vid2depth. I'm not a python expert so I'm looking for help on tracking down the issue. The command listed above is from the vid2depth wiki page, and results in the following error: Traceback (most recent call last): File "train.py", line 41, in import model File "/home/user/tensorflow_models/models/research/vid2depth/model.py", line 25, in from ops.icp_op import icp ImportError: dynamic module does not define init function (initicp_op) On python3, similar error but different init function name (PyInit_icp_op, I think).

google-api
tags question: http://stackoverflow.com/q/51329367
tags question: http://stackoverflow.com/q/51375833
tags question: http://stackoverflow.com/q/51468295
tags question: http://stackoverflow.com/q/51389982
tag name: google-api
tags question: http://stackoverflow.com/q/51349752
type: Tag

http://stackoverflow.com/a/51482242
has comment: http://stackoverflow.com/comment/89934080
has comment: http://stackoverflow.com/comment/89933999
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/51481884
has body: Another option would be to replace 0 with np.nan and then apply the min method. note: this doesn't address the &gt; 0 condidtion, but the test frame seems to be only non-negative values. using the same setup as others: df = pd.DataFrame([[0, 0, 0], [0, 10, 0], [4, 0, 0], [1, 2, 3]], columns=['first', 'second', 'third']) df.replace(0, np.nan).min() first 1.0 second 2.0 third 3.0 dtype: float64 posting this alternative as i found it to be slightly faster than the excellent answer by user3483203, which was also my first instinct at this problem %timeit df.replace(0, np.nan).min() 745 µs ± 2.72 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) %timeit df[df &gt; 0].min() 1.09 ms ± 14.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) note also that: %timeit df[df != 0].min() 1.1 ms ± 16.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) So, if one needs to ignore a specific value when calculating the aggregate, rather than a range, replace with np.nan seems to be the performant way to go
has comment: http://stackoverflow.com/comment/89933309
has comment: http://stackoverflow.com/comment/89933684
score: 4
has comment: http://stackoverflow.com/comment/89933375
downvote count: 0

http://stackoverflow.com/comment/89633271
has text: interesting, I will give it a try on Monday, since I am not in charge of the other_program (it is not in python)
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51328848

http://stackoverflow.com/comment/89849869
score: 1
type: Comment
has text: It's unclear, to me at least, what you are trying to do here. You say you want to compare frames in different videos - with what? to what end? Do you want to compare every frame in one video with a frame in another video? What do your videos look like?
type: QuestionComment
comment on: http://stackoverflow.com/q/51436675

distinct
tag name: distinct
tags question: http://stackoverflow.com/q/51443154
type: Tag

http://stackoverflow.com/a/51417962
has body: A copy and paste friendly vim solution :g/VRTX/normal f.xhhP;xhhP explanation: :g/{pattern}/command - executes command on every line matching pattern. In this case every VRTX line normal - the commands we want to execute are normal mode commands f. - find the first dot in current line xhhP - cut such character, move left two times, paste ; - find next occurrence xhhP - move dot again
type: Answer
answers question: http://stackoverflow.com/q/51415997
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/89823104
downvote count: 0

http://stackoverflow.com/comment/89679532
type: AnswerComment
comment on: http://stackoverflow.com/a/51353203
has text: @NateWalker Yeah the writerow should be at the end of the loop.
type: Comment
score: 0

http://stackoverflow.com/a/51427897
answers question: http://stackoverflow.com/q/51426623
has comment: http://stackoverflow.com/comment/89830318
downvote count: 0
has comment: http://stackoverflow.com/comment/89831817
has body: Here is a recursive solution: a = [95, 100] b = [1, 4] c = [1, 2] Params = (a, b, c) def GetValidParamValues(Params, constriantSum, prevVals): validParamValues = [] if (len(Params) == 1): if (constriantSum &gt;= Params[0][0] and constriantSum &lt;= Params[0][1]): validParamValues.append(constriantSum) for v in validParamValues: print(prevVals + v) return sumOfLowParams = sum([Params[x][0] for x in range(1, len(Params))]) sumOfHighParams = sum([Params[x][1] for x in range(1, len(Params))]) lowEnd = max(Params[0][0], constriantSum - sumOfHighParams) highEnd = min(Params[0][1], constriantSum - sumOfLowParams) + 1 if (len(Params) == 2): for av in range(lowEnd, highEnd): bv = constriantSum - av if (bv &lt;= Params[1][1]): validParamValues.append([av, bv]) for v in validParamValues: print(prevVals + v) return for av in range(lowEnd, highEnd): nexPrevVals = prevVals + [av] subSeParams = Params[1:] GetValidParamValues(subSeParams, constriantSum - av, nexPrevVals) GetValidParamValues(Params, 100) The idea is that if there were 2 parameters, a and b, we could list all the valid pairs by passing through the values of a, and taking (ai, S - ai) and just checking if S-ai is a valid value for b. This is improved on since we can calculate ahead of time which values of ai will make S-ai a valid value for b, so we never check values that don't work. When the number of params is more than 2, we can again look at every valid value of ai, and we know the sum of the other numbers must be S - ai. So the only thing we need is every possible way for the other numbers to add to S - ai, which is the same problem with one fewer parameter. So by using recursion we can get it go all the way down to size 2 and solve it.
has comment: http://stackoverflow.com/comment/89831414
upvote count: 1
has comment: http://stackoverflow.com/comment/89829746
type: Answer
has comment: http://stackoverflow.com/comment/89829316
has comment: http://stackoverflow.com/comment/89830287
score: 1
has comment: http://stackoverflow.com/comment/89830686

http://stackoverflow.com/comment/89825245
type: Comment
type: QuestionComment
score: 1
has text: A small trick I can think of is to first sort your parameters based on the mid of their ranges. Build up your possible combination starting from the parameter with the largest mid range. In this way, say you looked at `a=95`, you do not have to iterate any `b` if b's range is (30, 60)
comment on: http://stackoverflow.com/q/51426623

http://stackoverflow.com/comment/89677859
has text: You have to paste the code, select the code and press `Ctrl + K`
comment on: http://stackoverflow.com/q/51352470
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51429233
downvote count: 0
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/89829884
has answer: http://stackoverflow.com/a/51430033
tagged with: server
tagged with: containers
score: 4
has answer: http://stackoverflow.com/a/51429538
tagged with: docker
has body: I want to run jupyter in docker container. I am not able to launch the jupyter notebook. When I copy paste the URL given in the terminal.. server cannot be reached. Will appreciate any ideas to try
tagged with: jupyter-notebook
favorite count: 0
has comment: http://stackoverflow.com/comment/89830263
has title: Running Jupyter notebook in Docker
type: UnansweredQuestion
tagged with: python
upvote count: 4

http://stackoverflow.com/comment/89653609
comment on: http://stackoverflow.com/a/51339885
type: AnswerComment
has text: @user9371654 ok your wish. I didn't know that when I wrote the question
type: Comment
score: 0

http://stackoverflow.com/q/51413425
type: Question
downvote count: 4
answer count: 1
has comment: http://stackoverflow.com/comment/89798438
has body: I want to find all subsequences of length 3 within a list. My program's complexity is too high, so I want to reduce my program's time complexity. My code is here. def generate(lst): end = len(lst) for i in range(0, end - 2): for j in range(i + 1, end - 1): for k in range(j + 1, end): yield lst[i], lst[j], lst[k] for a, b, c in generate([6, 3, 88, 4]): print(a, b, c)
has comment: http://stackoverflow.com/comment/89798380
has comment: http://stackoverflow.com/comment/89798363
tagged with: python
has answer: http://stackoverflow.com/a/51413479
favorite count: 0
has comment: http://stackoverflow.com/comment/89798558
tagged with: python-3.x
upvote count: 0
has title: to reduce time complexity of my python programe
has comment: http://stackoverflow.com/comment/89798460
type: UnansweredQuestion
score: -4
has comment: http://stackoverflow.com/comment/89798622

http://stackoverflow.com/q/51369110
score: 1
upvote count: 1
type: Question
tagged with: multiprocessing
has title: python tqdm and logging
tagged with: tqdm
downvote count: 0
favorite count: 0
has body: I'm having a python script for accessing/manipulating network devices with netmiko. To speed up the processing, I'm using now tqdm and a process pool for multiprocessing. This is working fine except the logging stuff. The logger works fine for the main, but not for the processes created by tqdm. The important code snippets are as follows: def threaded_function(params): """the custom function :param kwargs params: device details packed as keyword arguments :returns: dictionary containing the results of each step """ logging.debug('TEST') logging.info('TEST2') logging.error('TEST3') def main_loop(): logging.getLogger("netmiko").propagate = False logging.getLogger("netmiko").disabled = True logging.getLogger("paramiko").propagate = False logging.getLogger("paramiko").disabled = True log_time = datetime.now().strftime("%Y%m%d-%H%M%S") LOG_FILE = os.path.basename(input_file) + '.txt' logger = logging.getLogger() logger.setLevel(logging.DEBUG) if args.log2file: log_format_file = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') rfh = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes=1048576, backupCount=10) rfh.setLevel(args.filelevel) rfh.setFormatter(log_format_file) logger.addHandler(rfh) if args.log2con: log_format_con = logging.Formatter('%(message)s') ch = logging.StreamHandler() ch.setLevel(args.conlevel) ch.setFormatter(log_format_con) logger.addHandler(ch) if not args.log2file and not args.log2con: logger.disabled = True logger.propagate = False logging.info("JOB STARTED: " + str(log_time)) pool = multiprocessing.Pool(max_cpu_count) with tqdm(total=len(input_list), ascii=True, unit="dev", desc='processing', disable=(False if args.log2con else True)) as t: for _ in pool.imap_unordered(threaded_function, input_list): t.update(1) results.append(_) if __name__ == "__main__": main_loop() Does anyone has an idea, where I'am wrong? I tried to pass a queue according the 2nd example from this doc (https://docs.python.org/3/howto/logging-cookbook.html#lo…
type: UnansweredQuestion
tagged with: python
tagged with: logging
answer count: 0

http://stackoverflow.com/comment/118099400
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51407938
has text: I recommend SageMath for this kind of thing https://www.sagemath.org/
score: 0

http://stackoverflow.com/comment/89626498
type: AnswerComment
has text: I edited the answer and added a link to the documentation for the tf.boolean_mask op. The examples there should be able to help you out.
type: Comment
comment on: http://stackoverflow.com/a/51325666
score: 0

http://stackoverflow.com/comment/89710760
comment on: http://stackoverflow.com/a/51369198
score: 0
type: AnswerComment
has text: @abarnert Didn't know it was slower, updated.
type: Comment

http://stackoverflow.com/a/51370959
has comment: http://stackoverflow.com/comment/102452304
answers question: http://stackoverflow.com/q/51370889
upvote count: 1
type: Answer
has body: Wrap your output in preformatted tags, i.e. &lt;pre&gt; shell output goes here &lt;/pre&gt; shell output goes here That tells the browser to use fixed pitch font and not to rewrap it.
downvote count: 0
score: 1

http://stackoverflow.com/comment/89938490
score: 0
type: Comment
type: QuestionComment
has text: Same here, unable to reproduce. Statement provided by OP works fine.
comment on: http://stackoverflow.com/q/51481489

http://stackoverflow.com/a/51426256
has comment: http://stackoverflow.com/comment/89823743
answers question: http://stackoverflow.com/q/51426118
downvote count: 0
type: AcceptedAnswer
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51426118
has body: You never add media_count to post_info, which is the dictionary that gets written to the csv. This change in the write part should fix your problem: with open('data.csv', 'a', newline='') as data_out: print('Writing Data for location id {0}.....'.format(tag)) print(media_count) post_info["MEDIA_COUNT"] = media_count csv_writer = csv.DictWriter(data_out, fieldnames=csv_headers) csv_writer.writerow(post_info)
score: 1

http://stackoverflow.com/q/51467709
has title: Yocto recipe written in python giving me an error when trying to build with Bitbake
answer count: 1
tagged with: python
type: AnsweredQuestion
has body: It's the first time i have come across a recipe file written in python and it's giving me an error. The error is: ../meta-intel/recipes-rt/images/core-image-rt.bb: Error executing a python function in &lt;code&gt;: This is a recipe which is coming from the meta-intel branch "[master] intel-vaapi-driver: 2.1.0 -> 2.2.0". My poky version is" [morty] documentation: Updated manual revision table for 2.2.4 release date. My BITBAKE version is: "BitBake Build Tool Core version 1.32.0" The contents of core-image-rt.bb are: require recipes-core/images/core-image-minimal.bb # Skip processing of this recipe if linux-intel-rt is not explicitly specified as the # PREFERRED_PROVIDER for virtual/kernel. This avoids errors when trying # to build multiple virtual/kernel providers. python () { if d.getVar("PREFERRED_PROVIDER_virtual/kernel") != "linux-intel-rt": raise bb.parse.SkipPackage("Set PREFERRED_PROVIDER_virtual/kernel to linux-intel-rt to enable it") } DESCRIPTION = "A small image just capable of allowing a device to boot plus a \ real-time test suite and tools appropriate for real-time use." DEPENDS += "linux-intel-rt" IMAGE_INSTALL += "rt-tests hwlatdetect" LICENSE = "MIT" If you need any additional information please let me know and i'll try and supply it. I can normally build images on my ubuntu machine but don't believe have ever had to build an image in which the recipes were written in python
has answer: http://stackoverflow.com/a/51471994
tagged with: recipe
tagged with: yocto
type: Question
accepted answer: http://stackoverflow.com/a/51471994
score: 0

http://stackoverflow.com/q/51333700
favorite count: 0
tagged with: bigtable
tagged with: python
accepted answer: http://stackoverflow.com/a/51334156
has body: I have a Cloud Bigtable table with two column families: small and large. I'd like to scan all rows and access the value in the small column: client = bigtable.Client(project=project_id, admin=False) instance = client.instance(instance_id) table = instance.table(table_id) for row in table.yield_rows(): key = row.row_key.decode('utf-8') small_value = row.cells[small_cf][b''][0].value print(key, small_value) This works, but will also fetch the value of the large CF which I don't care about. How do I only fetch the data from a particular set of CFs?
upvote count: 3
tagged with: google-cloud-bigtable
has title: How to read only some column families from Cloud Bigtable?
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51334156
type: Question
answer count: 1
downvote count: 0

http://stackoverflow.com/q/51390287
tagged with: cvxpy
tagged with: python
score: 0
answer count: 1
has title: Optimizing a cost function subject to second order cone constraints using cvxpy
type: UnansweredQuestion
has body: I have a problem of the form: Where X^_JW: and delta_R_LV: Where: -All uppercase deltas and epsilon are constants -R_WV is a 3,3 rotation matrix with 1000 samples -R^_LV is a 3,3 constant rotation matrix -I is a 3,3 rotation matrix -Delta_R_LV is a 3,3 matrix we wish to solve for -X_JLI is a 3,1 vector with 1000 samples -T_LV is a 3,1 vector we wish to solve for -T_VW is a 3,1 vector with 1000 samples -X*_JW is a 3,1 vector with 1000 samples I am having trouble understanding how to fit the 3,3 matrices with 1000 samples into a 2d form that would make sense to optimize upon. My idea was to flatten over the last dimension in order to then have matrices of dimension 1000,9 but I don't understand how these matrices could operate on a 3,1 vector. I understand how the examples work for a vector of samples of dim (N,1) and how to turn something like this into a matrix via the example: objective = cp.Minimize(cp.sum_squares(A*x - b)) constraints = [0 &lt;= x, x &lt;= 1] prob = cp.Problem(objective, constraints) # The optimal objective value is returned by `prob.solve()`. result = prob.solve() # The optimal value for x is stored in `x.value`. print(x.value) # The optimal Lagrange multiplier for a constraint is stored in # `constraint.dual_value`. print(constraints[0].dual_value) x = cp.Variable((1275,3)) objective = cp.Minimize(cvx.sum_squares(A*x - b)) constraints = [0 &lt;= x, x &lt;= 1] prob = cvx.Problem(objective, constraints) There is also another example which may be closer to my problem in this link: http://nbviewer.jupyter.org/github/cvxgrp/cvx_short_course/blob/master/intro/control.ipynb
tagged with: numpy
has answer: http://stackoverflow.com/a/51391240
tagged with: optimization
type: Question

http://stackoverflow.com/a/51430651
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51429788
has body: For instance I have an app with name task so to go the index of task I do http://localhost:8000/task the url has as name index from django.urls import path from . import views app_name = 'task' urlpatterns = [ path('', views.index, name='index'), path('add_task/', views.add_task, name='add_task'), path('add_subtask/&lt;int:task_id&gt;/', views.add_subtask, name='add_subtask'), ] So in my template I can do something like that to go to call the second url var add_task_url = "{% url 'task:index' %}add_task/" And to go to the next url var add_subtask_url = "{% url 'task:index' %}add_subtask/" + '1/' //you can replace '1/' by '{{day}}/' and add others one

http://stackoverflow.com/comment/90012683
has text: if you run `nltk.__version__` which version does it return? I ran your code in version `3.3` and didn't get an error.
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51482502

http://stackoverflow.com/a/51428338
has body: You can use pd.Grouper: data.groupby(pd.Grouper(key='date', freq='min'))['user'].value_counts() Full example, including how to create your dataframe in a much easier way, using pandas functions (I know that this wasn't the topic of your question, but I think the following makes it much easier rather than importing datetime): df = pd.DataFrame({'date':dates, 'user':f}) df['date'] = pd.to_datetime(df['date'], format='%Y%m%d%H%M%S') df.groupby(pd.Grouper(key='date', freq='min'))['user'].value_counts() The result: date user 2013-01-01 10:01:00 f0001 4 f0020 1 2013-01-01 10:02:00 f0002 2 f0001 1 f0005 1 f0008 1 f3203 1 2013-01-01 10:03:00 f0001 2 f0201 1 f0439 1 2013-01-01 10:04:00 f0003 1 f0005 1 f0008 1 f0009 1 f0233 1 Name: user, dtype: int64
downvote count: 0
has comment: http://stackoverflow.com/comment/89828488
answers question: http://stackoverflow.com/q/51428216
has comment: http://stackoverflow.com/comment/89827970
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/89828107
has comment: http://stackoverflow.com/comment/89828021
has comment: http://stackoverflow.com/comment/89828451

http://stackoverflow.com/comment/89740883
type: Comment
comment on: http://stackoverflow.com/q/51379567
score: 0
type: QuestionComment
has text: Add the Mail at one cronjob that will be schedule to check it everyday, when one event will be valid in condition (so 5 days to the event start) that will trigger your email, look for schedule tasks on Windows or Cron Jobs in Linux

http://stackoverflow.com/q/51434105
upvote count: 1
type: AnsweredQuestion
score: 1
type: Question
downvote count: 0
tagged with: string
has body: Say I have a bunch of lines ''' ......''' And I don't want every one of them popping out at the same time, how do I create a delay between them? Or better yet, everyone remember the matrix scene at the beginning with the "follow the white rabbit, knock knock". How do you do that, just have it look as if it's being written live. THanks guys in advance
has title: How to execute python string over time?
answer count: 1
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/51434144
accepted answer: http://stackoverflow.com/a/51434144
tagged with: time

http://stackoverflow.com/comment/89799060
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51413021
score: 0
has text: I'm sorry, actually, the break is correct. I formatted it wrong in this post. That is not the problem, I used it correctly when I ran it. My 2nd decisions are the ones that give me error signs.

http://stackoverflow.com/comment/89652085
comment on: http://stackoverflow.com/q/51334487
score: 0
type: Comment
type: QuestionComment
has text: My primary key is preset by Django, which is an INT(11) field named "id".

http://stackoverflow.com/comment/89860257
has text: No you did not got my point. I am saying after training model on train dataset now I want to make predictions on test dataset (not test data from train-test split). How to make predictions on test dataset which has only 495 rows (i,e target variable should be predicted)
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51444890

http://stackoverflow.com/comment/89634981
comment on: http://stackoverflow.com/a/51329437
type: AnswerComment
has text: @BoubacarTraoré, You'll have to do some debugging, e.g. print each line where you define a variable. I've also updated the code to simplify separating filename from extension.
type: Comment
score: 0

http://stackoverflow.com/q/51465066
has comment: http://stackoverflow.com/comment/89898669
has answer: http://stackoverflow.com/a/51465456
tagged with: python
type: AnsweredQuestion
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/51465456
has answer: http://stackoverflow.com/a/51465175
tagged with: inheritance
has title: Encapsulate the decision which child class to initialize
score: 0
possible better answer: http://stackoverflow.com/a/51465175
has comment: http://stackoverflow.com/comment/89898858
has body: I have a parent class and different child classes. I want to encapsulate the decision which child class is to initialize in the initialization. A simple example: class Person: def __init__(self, name): if self.name_is_male(name): real_instance = Male(name) else: real_instance = Female(name) return real_instance def name_is_male(self, name): if name == 'Donald': return True elif name == 'Daisy': return False else: raise ValueError('unknown name!') class Male(Person): def __init__(self, name): ... class Female(Person): def __init__(self, name): ... This simple example will end in a recursion and doesn’t work, but it’s for illustrating my question: how to encapsulate the decision which child class to initialize in the initialization of a parent class? Or is this altogether a stupid idea?

http://stackoverflow.com/a/51403480
has body: So I continued to work at this since it was blocking some bug fixes. Replace suds with suds_jurko which is just a fork that is still being maintained.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51388369

http://stackoverflow.com/a/51334501
has comment: http://stackoverflow.com/comment/89644762
has comment: http://stackoverflow.com/comment/89644836
score: -1
has comment: http://stackoverflow.com/comment/89645129
has comment: http://stackoverflow.com/comment/89644878
upvote count: 1
has comment: http://stackoverflow.com/comment/89644846
type: Answer
has comment: http://stackoverflow.com/comment/89645115
has body: Assuming you are using Python 3.4 or later in which pip is included by default, try the following command: python3 -m pip freeze When you use the -m command-line flag, python will search sys.path for the named module and execute its contents as the __main__ module. (more here) This solution will allow you to use pip by python3 -m pip, but in order to use pip3 directly you can: Install it via Homebrew: brew install pip3 Install it with get-pip.py: curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py python get-pip.py
has comment: http://stackoverflow.com/comment/89644904
downvote count: 2
has comment: http://stackoverflow.com/comment/89644886
has comment: http://stackoverflow.com/comment/89644778
answers question: http://stackoverflow.com/q/51334492
has comment: http://stackoverflow.com/comment/89644869

http://stackoverflow.com/comment/89909876
type: AnswerComment
has text: **task(n)** will always be executed (printing "done with n"). Any way to interrupt it in case of TimeoutException? I also tried the generator way, explicitly calling __next__(); with the same result.
type: Comment
comment on: http://stackoverflow.com/a/51464247
score: 1

http://stackoverflow.com/comment/89733118
has text: are you using socket.io ?
comment on: http://stackoverflow.com/q/51380533
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51472151
has comment: http://stackoverflow.com/comment/89912748
tagged with: mysql
tagged with: django
has comment: http://stackoverflow.com/comment/89912783
has comment: http://stackoverflow.com/comment/89912745
has body: my code is like that: def post_detail(request, year, month, day, slug): print(month, type(month)) post = get_object_or_404(Post, slug=slug, status='published', published__year=year ) print(post.published.month, type(post.published.month)) return render(request, 'blog/post/detail.html', {'post': post}) The output, when I'm calling that view: 7 &lt;class 'int'&gt; 7 &lt;class 'int'&gt; This shows, that the month is 7 (int), however when I modify it like: def post_detail(request, year, month, day, slug): print(month, type(month)) post = get_object_or_404(Post,## Heading ## slug=slug, status='published', published__year=year, published__month=month ) print(post.published.month, type(post.published.month)) return render(request, 'blog/post/detail.html', {'post': post}) I now get 404 from get_object_or_404. Weird thing, I have the same code on my local machine and it works. That one is on the server. My model is like: class PublishedManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Roboczy'), ('published', 'Opublikowany'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='published') author = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) body = models.TextField() published = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() active = PublishedManager() def get_absolute_url(self): date = timezone.localdate(self.published) return reverse('blog:post_detail', args=[date.year, date.strftime('%m'), date.strftime('%d'), self.slug]) class Meta: ordering = ('-published',) def __str__(self): return f'{self.title} by {self.author.username.title()}' I did makemigrations and migrate, somebody knows what cou…
has comment: http://stackoverflow.com/comment/89913586
has comment: http://stackoverflow.com/comment/89912584
type: Question
score: 0
has comment: http://stackoverflow.com/comment/89912942
tagged with: python
has comment: http://stackoverflow.com/comment/89912862
linked to: http://stackoverflow.com/q/21918802
has title: Django get_object_or_404 throws exception when getting by date
has comment: http://stackoverflow.com/comment/89913203
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/89922829
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51441167
has text: extra update in the beginpost
score: 0

http://stackoverflow.com/comment/89865040
score: 3
has text: If you want to continue to the next iteration of the loop, use `continue` instead of `break`
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51447318

http://stackoverflow.com/a/51477900
score: 0
type: Answer
has body: Check this one out - you'll get a dictionary of DataFrames, from which you can access each of the dataframes. import pandas as pd d={} sheets = ['xxx', 'yyy', 'zzz', 'aaa', 'bbb'] for sheet in sheets: d[sheet] = pd.read_excel('practice1.xlsx', sheetname=sheet) Here's the link to the resource: Create multiple dataframes in loop Edit: the answer above is actually better, as you don't have to specify sheet names. 'Sheet_name' didn't work for me, so I came up with this solution and only after I realized that typing 'sheetname' (without '_') does the trick for me.
answers question: http://stackoverflow.com/q/51476960

http://stackoverflow.com/q/51371660
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/89791400
score: 3
answer count: 0
has comment: http://stackoverflow.com/comment/89791556
has comment: http://stackoverflow.com/comment/89749231
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/89760422
has comment: http://stackoverflow.com/comment/89751963
has comment: http://stackoverflow.com/comment/89791030
has title: Cannot convert MotorCursor object to list in async function using standard method
type: Question
has comment: http://stackoverflow.com/comment/89745538
has comment: http://stackoverflow.com/comment/89754736
has comment: http://stackoverflow.com/comment/89790855
has body: I have been trying to have an async function get data from a Motor database in Python and get the list of data corresponding to the search. Here is the function to get the data and the one to print it: async def do_find_by_run_name(run_name): """ :param run_name: the name of a the run being searched for (string) :return: MotorCursor for run found """ cursor = db.data_collection.find({"run_name":run_name}) loop = asyncio.get_event_loop() return cursor async def print_arr(cursor): for d in await cursor.to_list(length=2): pprint.pprint(d) I have a PyQt slot which I want to use to call the find_by_run_name function on a button press. Here is the code for that slot: @pyqtSlot() def on_find_runs_button_clicked(self): try: new_loop = asyncio.get_event_loop() d = new_loop.run_until_complete(server.do_find_by_run_name("default")) print(d) new_loop = asyncio.get_event_loop() v = new_loop.run_until_complete(server.print_arr(d)) except Exception as err: try: raise TypeError("Again !?!") except: pass traceback.print_exc() When I press the button corresponding to this slot I see the following in my terminal: AsyncIOMotorCursor(&lt;pymongo.cursor.Cursor object at 0x06F51EB0&gt;) Traceback (most recent call last): File "C:/Users/Rohan Doshi/Documents/websockets/server\GUI.py", line 93, in on_find_runs_button_clicked v = new_loop.run_until_complete(server.print_arr(d)) File "C:\Users\Rohan Doshi\AppData\Local\Programs\Python\Python36-32\lib\asyncio\base_events.py", line 468, in run_until_complete return future.result() File "C:/Users/Rohan Doshi/Documents/websockets/server\server.py", line 130, in print_arr for d in await cursor.to_list(length=2): RuntimeError: Task &lt;Task pending coro=&lt;print_arr() running at C:/Users/Rohan Doshi/Documents/websockets/server\server.py:130&gt; cb=[_run_until_complete_cb() at C:\Users\Rohan Doshi\AppData\Local\Programs\Python\Python36-32\lib\asyncio\base_events.py:177]&gt; got Future &lt;Future pending&gt; attached to a different loop This indicat…
has comment: http://stackoverflow.com/comment/89790106
has comment: http://stackoverflow.com/comment/89790364
has comment: http://stackoverflow.com/comment/89722632
downvote count: 1
favorite count: 0
tagged with: tornado-motor
has comment: http://stackoverflow.com/comment/89791164
tagged with: python-asyncio
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89791580

http://stackoverflow.com/comment/89781511
type: Comment
comment on: http://stackoverflow.com/q/51404930
score: 0
has text: @NickA possibly, I'm just wondering if someone would have a trick that I could use. As I mentioned in the question, I'm assuming it has not been garbage collected yet :)
type: QuestionComment

http://stackoverflow.com/q/51463228
tagged with: python-3.x
tagged with: python
possible better answer: http://stackoverflow.com/a/51463458
has body: I am trying to create a function that returns the index of 3 similar consecutive elements in a list. For the list [1,2,3,3,3,4,5] the output sould be myFunc([1,2,3,3,3,4,5]) ---> 2 (or [2]). The following code does this job: def myFunc(a): lst = [] for i in range(len(a)-2): if a[i]==a[i+1]==a[i+2]: lst.append(i) return lst ... but it is time-consuming to check every element in a large list. The code: def myFunc(a): return any(a[i]==a[i+1]==a[i+2] for i in range(len(a)-2)) ... seems useful for the problem, but I am not sure wether there is a way to get the index of the similar consecutive elements from this (returns True or False) My question: Is there a way to determine the indexes of similar consecutive elements in a list without using a for loop to check every element? Is there a more elegant way to solve the problem?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51463458
tagged with: list
has answer: http://stackoverflow.com/a/51463485
type: Question
has title: Getting the index of similar consecutive elements in list (Python3)
has answer: http://stackoverflow.com/a/51466514
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/89895408
has comment: http://stackoverflow.com/comment/89895353
answer count: 3
has comment: http://stackoverflow.com/comment/89895447
downvote count: 0
accepted answer: http://stackoverflow.com/a/51466514
favorite count: 0

http://stackoverflow.com/comment/89888472
has text: Open a command prompt with Admin rights. Uninstall tweepy. Now install again, but carefully review for any error messages.
comment on: http://stackoverflow.com/q/51452957
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/51447235
has body: So I have installed the anytree package (after great effort; I had to add some environment variables on my system). Having done this I can use almost all functionalities of the anytree package - just not the one I want. I wish to use graphviz in conjunction with the anytree package in order to graph trees using the 'DotExporter' command. I have installed graphviz; its path is C:\Users\joel\Anaconda3_2\Lib\site-packages\graphviz, and I have also added the line of code 'from anytree.exporter import DotExporter' to my Python document (in addition to the other anytree imports needed to make trees). Therefore, having defined the root node 'root' of my tree, I should now be able to produce pngs and dot files of the tree using either of the commands 'DotExporter(root).to_picture('root.png')', however I get the following error message: 'FileNotFoundError: [WinError 2] The system cannot find the file specified'. Does anybody know what is going on? I am using Python 3.6.2 with the engine Spyder as a part of the Anaconda distribution (I have Anaconda 3.2). I am 99% certain I have the most recent versions of anytree and graphviz. UPDATE: So I learned that there has been a big compatibility issue between Anaconda and graphviz for about a year now and assumed that this was the problem. After trying all the solutions people suggested I still wasn't able to get my program to work so I ended up uninstalling Anaconda and instead started using PyCharm together with the standard Python interpreter. However the program still wouldn't work, so even though there are compatibility issues between Anaconda and graphviz, it turns out that wasn't the problem. I tried the program on my housemate's machine which also uses Anaconda and got the same error I had been getting. In the end I found the following workaround: I couldn't get the 'DotExporter(root).to_picture('root.png')' command to work, but the 'DotExporter(root).to_dotfile('root.dot')' command was working. '.dot' files contain code and …
tagged with: graphviz
type: Question
has comment: http://stackoverflow.com/comment/89871409
downvote count: 0
has answer: http://stackoverflow.com/a/54552442
has comment: http://stackoverflow.com/comment/89885016
answer count: 1
has title: Python, not able to graph trees using graphviz with the anytree package
favorite count: 0
tagged with: anytree
has comment: http://stackoverflow.com/comment/89884972
has comment: http://stackoverflow.com/comment/89865057
type: UnansweredQuestion
upvote count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/89866434
tagged with: tree
score: 3
tagged with: anaconda

http://stackoverflow.com/a/51452351
upvote count: 1
has comment: http://stackoverflow.com/comment/89874679
accepted answer of: http://stackoverflow.com/q/51452186
downvote count: 0
has comment: http://stackoverflow.com/comment/89875004
has comment: http://stackoverflow.com/comment/89874722
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89874712
answers question: http://stackoverflow.com/q/51452186
has body: The MultiValueDictKeyError error raises when you are trying to access favorite_meal from request.POST, but the favorite_meal doesn't exist in request.POST Try this @csrf_exempt def favorite_meal(request): if request.method == "POST": if not 'access_token' in request.POST: return JsonResponse({"status": "'access_token' missing in POST payload"}) access_token = AccessToken.objects.get(token=request.POST.get("access_token"), expires__gt=timezone.now()) customer = access_token.user.customer if not 'favorite_meal' in request.POST and not request.POST["favorite_meal"]: return JsonResponse({"status": "'favorite_meal' missing in POST payload"}) details = CustomerDetailSerializer( CustomerDetails.objects.create( customer=customer, favorite_mean=request.POST["favorite_meal"] )) return JsonResponse({"status": "success"}) Screenshot UPDATE @csrf_exempt def favorite_meal(request): if request.method == "POST": if not 'access_token' in request.POST: return JsonResponse({"status": "'access_token' missing in POST payload"}) access_token = AccessToken.objects.get(token=request.POST.get("access_token"), expires__gt=timezone.now()) customer = access_token.user.customer if not 'favorite_meal' in request.POST and not request.POST["favorite_meal"]: return JsonResponse({"status": "'favorite_meal' missing in POST payload"}) for favorite_meal in request.POST["favorite_meal"]: details = CustomerDetailSerializer( CustomerDetails.objects.create( customer=customer, favorite_mean=favorite_meal )) return JsonResponse({"status": "success"})
type: Answer
has comment: http://stackoverflow.com/comment/89874673
has comment: http://stackoverflow.com/comment/89875122
has comment: http://stackoverflow.com/comment/89874966
score: 1

python-itertools
tags question: http://stackoverflow.com/q/51375231
tag name: python-itertools
type: Tag
tags question: http://stackoverflow.com/q/51387980
tags question: http://stackoverflow.com/q/51427277
tags question: http://stackoverflow.com/q/51345814
tags question: http://stackoverflow.com/q/51466966
tags question: http://stackoverflow.com/q/51449857

http://stackoverflow.com/comment/90195916
comment on: http://stackoverflow.com/a/51327409
score: 0
type: AnswerComment
type: Comment
has text: Correct, just checked and the disk was running out of space. Was able to fix it before I checked the answer though. Thanks a lot however :)

http://stackoverflow.com/a/51396833
type: Answer
score: 19
has comment: http://stackoverflow.com/comment/135460326
has comment: http://stackoverflow.com/comment/138238402
has comment: http://stackoverflow.com/comment/138087274
has comment: http://stackoverflow.com/comment/135900762
downvote count: 2
upvote count: 21
has comment: http://stackoverflow.com/comment/135877914
accepted answer of: http://stackoverflow.com/q/51396047
answers question: http://stackoverflow.com/q/51396047
has body: You need root to run at port 80. sudo python app.py
type: AcceptedAnswer

http://stackoverflow.com/a/51402849
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51402315
has comment: http://stackoverflow.com/comment/89777413
type: Answer
has comment: http://stackoverflow.com/comment/89776777
downvote count: 0
has body: Solution using lxml.html: from lxml import html content = """ Zimmerbachstr. 51 74676 Niedernhall-Waldzimmern Germany """ source = html.fromstring(content) address = ", ".join([span.text for span in source.xpath("//div[@itemprop='address']/span[@itemprop='streetAddress' or @itemprop='postalCode' or @itemprop='addressLocality']")]) or address = ", ".join([span.text for span in source.xpath("//div[@itemprop='address']/span[not(@itemprop='addressCountry')]")]) Output: 'Zimmerbachstr. 51, 74676, Niedernhall-Waldzimmern'
score: 1
accepted answer of: http://stackoverflow.com/q/51402315
upvote count: 1

http://stackoverflow.com/comment/89877549
comment on: http://stackoverflow.com/a/51417421
type: AnswerComment
score: 0
has text: @Florian sure ! sorry about that. I will revert the question to what it was ! and open a new question.
type: Comment

http://stackoverflow.com/q/51349074
has comment: http://stackoverflow.com/comment/98906428
type: Question
has body: So I'm playing with the sys.settrace function. In Python 3.7, a new opcode event is added 'opcode' The interpreter is about to execute a new opcode (see dis for opcode details). The local trace function is called; arg is None; the return value specifies the new local trace function. Per-opcode events are not emitted by default: they must be explicitly requested by setting f_trace_opcodes to True on the frame. I was able to get those opcode events, however there seems to be no further information——I don't even know what the opcode is and what it's doing. Does this event only brings finer granularity, without giving any extra information?
has comment: http://stackoverflow.com/comment/98910258
has comment: http://stackoverflow.com/comment/98906418
has answer: http://stackoverflow.com/a/56140828
has comment: http://stackoverflow.com/comment/98910032
tagged with: python-3.7
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89671622
tagged with: python
has comment: http://stackoverflow.com/comment/98910077
has title: In Python 3.7, does the 'opcode' event from sys.settrace give any information about the bytecode itself?
accepted answer: http://stackoverflow.com/a/56140828
linked to: http://stackoverflow.com/q/56139425
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/89671415
upvote count: 2
has comment: http://stackoverflow.com/comment/98910060

http://stackoverflow.com/a/51354691
type: Answer
upvote count: 2
score: 1
answers question: http://stackoverflow.com/q/51354637
downvote count: 1
has body: Look at webcolors python package here: https://pypi.org/project/webcolors/1.3/. It looks like the rgb_to_name(rgb_triplet, spec='css3') function does exactly what you want. From the documentation, Convert a 3-tuple of integers, suitable for use in an rgb() color triplet, to its corresponding normalized color name, if any such name exists. The optional keyword argument spec determines which specification’s list of color names will be used; valid values are html4, css2, css21 and css3, and the default is css3. If there is no matching name, ValueError is raised. Example provided: &gt;&gt;&gt; rgb_to_name((0, 0, 0)) 'black'
has comment: http://stackoverflow.com/comment/89681877
has comment: http://stackoverflow.com/comment/106562417

http://stackoverflow.com/a/51429941
type: Answer
accepted answer of: http://stackoverflow.com/q/51429844
upvote count: 4
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/89831567
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51429844
has body: vals = [500,501,809,702,808,807,703,502,499] close_set = set() tolerance = 5 result = [] for e in vals: if e in close_set: continue else: result.append(e) close_set.update([*range(e-tolerance, e+tolerance+1)]) print(result) # [500, 809, 702] This should be pretty fast (I tested it on a list of 1,000,000 elements and it took ~3 seconds). For each element in the list, you check to see if a close value has been seen before by checking for membership in the set of close numbers, which is O(1). If it's not, you add it to your results and then update the set of close numbers.
has comment: http://stackoverflow.com/comment/89831592

http://stackoverflow.com/a/51372531
upvote count: 1
has body: Checking if 0 exists in a 2-D matrix is always going to cost O(n*m), which is rather inefficient especially since your loop is going to iterate many times. For your purpose I would suggest that you simply use a counter and increment it whenever your operation inside the loop sets an item of 0 to a non-0 value, so that you can use something like this as a condition for the while loop: while counter &lt; x * y:
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51372353
type: Answer

http://stackoverflow.com/comment/89874552
has text: Worked great. One last question. Say there was an small difference (epsilon) in the y coordinates so that the algorithm calculates they are on a different line, whereas this difference is imperceptible enough for us to think the points lie on the same line. Given Rectangle('D',3,1.01,4,2.01) , the version currently outputs [A,B,D,C] whereas it should be [A,B,C,D] since rectangle D lies to the right of C, and same y coordinate (except possibly the small difference 0.01)
comment on: http://stackoverflow.com/a/51450045
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89693757
comment on: http://stackoverflow.com/q/51360140
score: 0
type: Comment
has text: The term you're looking for is "transaction isolation level" (starting point: https://en.wikipedia.org/wiki/Isolation_(database_systems))
type: QuestionComment

http://stackoverflow.com/q/51336074
has comment: http://stackoverflow.com/comment/89647209
upvote count: 3
has comment: http://stackoverflow.com/comment/89647136
type: Question
score: 3
possible better answer: http://stackoverflow.com/a/51337094
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/89647166
has comment: http://stackoverflow.com/comment/89647173
tagged with: matplotlib
has title: Show original image pixels instead of mask in python
has answer: http://stackoverflow.com/a/51344881
tagged with: numpy
accepted answer: http://stackoverflow.com/a/51344881
answer count: 2
has comment: http://stackoverflow.com/comment/89647179
has comment: http://stackoverflow.com/comment/89647153
downvote count: 0
has comment: http://stackoverflow.com/comment/89647191
favorite count: 0
has answer: http://stackoverflow.com/a/51337094
tagged with: python
has body: I have a deep learning model which returns to me an array which when plotted like this res = deeplab_model.predict(np.expand_dims(resized2,0)) labels = np.argmax(res.squeeze(),-1) #remove single dimension values, gives the indices of maximum values in the array plt.imshow(labels[:-pad_x]) (the last line above just removes some unclear lines before plotting them) looks like this original image is like this when I do the print(labels[labels&gt;0]) print(labels.shape) print(len(labels)) I get this [12 12 12 ... 12 12 12] (512, 512) 512 I want to show the colored pixels in the original image where mask appears and turn everything else to black (or blur or some other color I'll choose), how can I do that?
type: AnsweredQuestion
tagged with: python-3.x

http://stackoverflow.com/a/51381767
answers question: http://stackoverflow.com/q/51381331
score: 4
type: Answer
has body: Move your validation into your .fit function like so: # Train the model model.fit( X, Y, epochs=50, shuffle=True, verbose=2, validation_data=(X_test, Y_test), callbacks=[logger] ) When you do it after the .fit function like you are, the logger cannot see the validation data. You can also set histogram_freq=0 if that doesnt work. Your histogram will not work then though.
upvote count: 4
downvote count: 0

http://stackoverflow.com/q/51421319
upvote count: 2
answer count: 2
downvote count: 3
has title: Why one step delay when binding with events in Tkinter and how to solve this?
accepted answer: http://stackoverflow.com/a/51421840
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89814599
tagged with: python
has answer: http://stackoverflow.com/a/51421840
type: AnsweredQuestion
tagged with: tkinter
duplicate of: http://stackoverflow.com/q/2458026
has comment: http://stackoverflow.com/comment/89855489
has body: Consider the following simple code: from tkinter import * startingWindow = Tk() entry = Entry(startingWindow) entry.grid(row=0, column=0) def writeWhatYouGet(): print((entry.get()).strip()) entry.bind('&lt;Key&gt;', lambda event:writeWhatYouGet()) startingWindow.mainloop() I expect that when I type "1", I get "1" printed right away. However, I only get "1", when I press the second key, which is "2" in this case. Like the following: and the printed output is like 1 12 123 However I expect the output to be like: 1 12 123 1234 How I can solve this so I get what I write right away?
linked to: http://stackoverflow.com/q/2458026
type: Question
possible better answer: http://stackoverflow.com/a/51421764
has comment: http://stackoverflow.com/comment/89821785
has answer: http://stackoverflow.com/a/51421764
score: -1
tagged with: python-3.6

http://stackoverflow.com/q/51409987
has comment: http://stackoverflow.com/comment/89791362
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89792750
linked to: http://stackoverflow.com/q/51139635
has comment: http://stackoverflow.com/comment/89791468
has title: Can't download pygame with pip on windows
type: Question
has body: Keep running into this issue trying to download pygame. How do i download it with pip? I use a 64bit windows 10 w/ python 3.7... Thanks C:\Users\Antoine&gt;python -m pip install -U pygame --user Collecting pygame Using cached https://files.pythonhosted.org/packages/61/06/3c25051549c252cc6fde01c8aeae90b96831370884504fe428a623316def/pygame-1.9.3.tar.gz Complete output from command python setup.py egg_info: WARNING, No "Setup" File Exists, Running "config.py" Using WINDOWS configuration... Path for SDL not found. Too bad that is a requirement! Hand-fix the "Setup" Path for FONT not found. Path for IMAGE not found. Path for MIXER not found. Path for PNG not found. Path for JPEG not found. Path for PORTMIDI not found. Path for COPYLIB_tiff not found. Path for COPYLIB_z not found. Path for COPYLIB_vorbis not found. Path for COPYLIB_ogg not found. If you get compiler errors during install, doublecheck the compiler flags in the "Setup" file. Continuing With "setup.py" Error with the "Setup" file, perhaps make a clean copy from "Setup.in". Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "C:\Users\Antoine\AppData\Local\Temp\pip-install-0c2lpkkq\pygame\setup.py", line 165, in &lt;module&gt; extensions = read_setup_file('Setup') File "C:\Python\Python37\lib\distutils\extension.py", line 171, in read_setup_file line = expand_makefile_vars(line, vars) File "C:\Python\Python37\lib\distutils\sysconfig.py", line 407, in expand_makefile_vars s = s[0:beg] + vars.get(m.group(1)) + s[end:] TypeError: can only concatenate str (not "NoneType") to str
tagged with: python
tagged with: pygame
has answer: http://stackoverflow.com/a/51425695
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89791419
has comment: http://stackoverflow.com/comment/89791536
score: 0
tagged with: pip
has comment: http://stackoverflow.com/comment/89830540
answer count: 1
linked to: http://stackoverflow.com/q/50392215

http://stackoverflow.com/q/51461463
answer count: 1
tagged with: unicode
tagged with: beautifulsoup
tagged with: python-3.x
tagged with: python
accepted answer: http://stackoverflow.com/a/51461561
type: AnsweredQuestion
type: Question
has title: How to Replace Unicode Character Codes in TXT Output
has body: I'm using the Beautiful Soup library to parse the contents of a web page and print the results into a .txt file. This mostly works but I can't get rid of certain unicode character codes that appear in the text output. For example: "Failed to investigate issue with customer\u2019s terminal." I have been using the "io" library to encode the output as utf-8. I have tried changing the encoding to ascii, but this doesn't work either. def open_file(file): with open((file), encoding='utf-8') as input_data: global soup soup = BeautifulSoup(input_data) return soup # stuff happens here to parse the html and prepare a list of dictionaries containing the content I want to print. # this prepares the output def dict_writer(dict_list, filename): with io.open('%s.txt' % filename, 'w', encoding="utf-8") as f: for dict in dict_list: content = json.dumps(dict.get("content")) loc_no = json.dumps(dict.get("location_number")) page_no = json.dumps(dict.get("page_number")) f.write("\n") f.write(content + " " + "(" + page_no + ", " + loc_no + ")" +"\n") f.write("\n") I read the article below to try to get a general understanding of how character encoding works. It seems like if I encoded the content in the open_file function, encoding the output in the same standard in the dict_writer function should work. https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/
score: 0
has answer: http://stackoverflow.com/a/51461561

http://stackoverflow.com/a/51477833
answers question: http://stackoverflow.com/q/51477735
has body: The problem is with this line: check = check.append(w_table.iloc[i, 4]) list.append is an in-place operation and returns None. Instead, just use: check.append(w_table.iloc[i, 4]) For better performance, use set and set.add: check = {'word'} ... check.add(w_table.iloc[i, 4]) Even better, you can use vectorised functionality to avoid loops altogether. For this, you should provide a complete example, probably in a separate question.
type: AcceptedAnswer
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51477735

http://stackoverflow.com/comment/89901900
type: QuestionComment
comment on: http://stackoverflow.com/q/51465846
score: 0
has text: Yes, I think it's just that it makes no sense to have this behaviour that is confusing me. I think I get it now, thanks. From what I can see if you provide a default value that is mutable such as a list, then it will just ruin your day because `menu=[]` doesn't mean the default for menu will be [], it means the default for menu could be any possible list based on the previous calls and you probably shouldn't be using it.
type: Comment

http://stackoverflow.com/comment/101922551
comment on: http://stackoverflow.com/a/51421873
score: 0
type: Comment
type: AnswerComment
has text: @ColoradoGranite The reason for the duplicates is that we have non-unique keys. We merge on 'name' and Micha is two times in that column. The only way to avoid duplicates would be to have unique keys, I think. So to answer your question, I can't find anything better with the above data.

http://stackoverflow.com/q/51382157
score: 0
answer count: 1
has title: Iterate over elements of strings at the same time
has answer: http://stackoverflow.com/a/51382779
type: UnansweredQuestion
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/89754501
has body: I have a dictionary containing sentences that is keyed by the book and the page from which it came from: # lists to build dictionary - for reproducibility pages = [12, 41, 50, 111, 1021, 121] bookCodes = ['M', 'P', 'A', 'C', 'A', 'M'] sentences = ['THISISASENTANCE', 'ANDHEREISONEMOREEXAMP', 'ALLFROMDIFFERENTBOOKS', 'ANDFROMDIFFERENTPAGES', 'MOSLTYTHESAMELENGTHSS', 'BUTSOMEWILLBABITSHORT' ] # Make dictionary coordinates = defaultdict(dict) for i in range(len(pages)): book = bookCodes[i] page = pages[i] sentence = sentences[i] coordinates[book][page] = sentence print coordinates defaultdict(&lt;type 'dict'&gt;, {'A': {50: 'ALLFROMDIFFERENTBOOKS', 1021: 'MOSLTYTHESAMELENGTHSS'}, 'P': {41: 'ANDHEREISONEMOREEXAMP'}, 'C': {111: 'ANDFROMDIFFERENTPAGES'}, 'M': {121: 'BUTSOMEWILLBABITSHORT', 12: 'THISISASENTANCE'}}) I also have a pool of vowels stored as a dictionary, so that each vowel starts with a count of 10: vowels = dict.fromkeys(['A', 'E', 'I', 'O', 'U'], 10) I want to iterate over the same element of each sentence (sentence[0][0]. sentence[n][0], ...) and each time I see a vowel (A, E, I, O, or U) reduce the count of this vowel from the vowels dictionary. Once a pool of vowels hits 0 I return the letter, position in the sentence, and sentence and break the loop. from collections import defaultdict import random def wordStopper(sentences): random.shuffle(sentences) vowels = dict.fromkeys(['A', 'E', 'I', 'O', 'U'], 10) for i in range(len(sentences[1])): for s in sentences: try: l = s[i:i + 1] except IndexError: continue if l in vowels: vowels[l] -= 1 print("Pos: %s, Letter: %s, Sentence: %s" % (i, l, s)) print("As = %s, Es = %s, Is = %s, Os = %s, Us = %s" %(vowels['A'], vowels['E'], vowels['I'], vowels['O'], vowels['U'])) if vowels[l] == 0: return(l, i, s) letter, location, sentence = wordStopper(sentences) print("Vowel %s exhausted here %s in sentence: %s" % (letter, location, sentence)) It's important that the sentences list is shuffled (and that I iterate over eleme…
has comment: http://stackoverflow.com/comment/89737134

http://stackoverflow.com/q/51482364
answer count: 1
has answer: http://stackoverflow.com/a/51483085
tagged with: python
has title: How to choose paths that the compute average path length is one, or two in networkx?
type: UnansweredQuestion
score: 0
has body: How to compute paths that the average path length is one, or two in networkx? For example, in this graph below, the average path length equals one is 6, and two is 2. import networkx as nx import matplotlib.pyplot as plt G=nx.DiGraph() G.add_edges_from([(1, 2), (1, 5), (1, 6), (1, 9), (2, 3), (2, 4), (6, 7)]) pos=nx.spring_layout(G, iterations=5000) plt.figure() nx.draw(G, pos)
tagged with: networkx
has comment: http://stackoverflow.com/comment/89934063
type: Question

http://stackoverflow.com/a/51361516
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51361095
has comment: http://stackoverflow.com/comment/89695327
answers question: http://stackoverflow.com/q/51361095
type: AcceptedAnswer
downvote count: 0
has body: It seems from your expected output that vowels are optional in the vowel-consonant-vowel pattern you're looking for, in which case the following will do: import re pos = 0 while True: match = re.search(r'[aeiouy]*[bcdfghkjlmnpqrstvwxz]+([aeiouy]*)', 'bookeeping'[pos:]) if not match: break print(match.group(0)) pos += match.start(1) This outputs: boo ookee eepi ing
has comment: http://stackoverflow.com/comment/89695198
type: Answer

http://stackoverflow.com/q/51343169
tagged with: conv-neural-network
tagged with: hdf5
type: Question
has answer: http://stackoverflow.com/a/51343356
has body: I am working to build a classifier that can classify Knots. Currently I have a dataset that contains 100,000 images of "unknots", 100,000 "plus trefoil", and 100,000 "minus trefoil". I have been trying to get a classifier working on this large data set for the last 4ish days. The list of problems I had so far were: 1) Data set does not fit in CPU main memory: fixed this by making a number of EArrays with PyTables and Hdf5 and appending them on disk. So now I have one 1.2Gb file which is the dataset. 2) Even a very simple neural network in Keras was hitting 100% GPU (nvidia k80) memory usage after the model compiled... hadn't even fit the model yet. I read this was due to Keras backend automatically allocating near 100% of available resources upon compile: I fixed this as well. 3) Once errors 1 and 2 were fixed, I was still getting strange accuracy from Keras fit_generator(). Questions: 1) Is the method I have described of merging small numpy arrays into one large EArray using PyTables a good way to make a very large (300,000 images 128x128, total size = 1.2Gb) dataset? 2) Should fit generator be used over train_on_batch in Keras? Will they return significantly different final loss/accuracy scores? 3) What is wrong with my generator method if I want to train the neural network on batches of 50 images from the hdf5 file, and after each training epoch, delete the images the network just trained on out of main memory? import tables hdf5_path = "300K_Knot_data.hdf5" extendable_hdf5_file = tables.open_file(hdf5_path, mode='r') def imageLoader(files, batch_size): L = len(files.root.train_data) #this line is just to make the generator infinite, keras needs that while True: batch_start = 0 batch_end = batch_size while batch_start &lt; L: limit = min(batch_end, L) X = files.root.train_data[batch_start:limit] X = np.reshape(X, (X.shape[0],128,128,3)) X = X/255 Y = files.root.train_label[batch_start:limit] yield (X,Y) #a tuple with two numpy arrays with batch_size samples batch…
has title: Is Keras fit_generator the best thing to use when handling data that does not fit in RAM?
has comment: http://stackoverflow.com/comment/89659914
has comment: http://stackoverflow.com/comment/89659932
score: 4
tagged with: deep-learning
downvote count: 0
answer count: 1
tagged with: keras
favorite count: 0
tagged with: python
upvote count: 4
accepted answer: http://stackoverflow.com/a/51343356
type: AnsweredQuestion

http://stackoverflow.com/q/51461275
tagged with: python
has title: Gmail API quickstart.py script returns KeyError '_module'
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51548611
downvote count: 0
score: 1
tagged with: oauth-2.0
type: Question
possible better answer: http://stackoverflow.com/a/51462628
has body: I enabled the Gmail API and downloaded the .json file containing the token. I placed it in the same folder as the script. When I try to run it, I get this error: Traceback (most recent call last): File "email_clean.py", line 14, in &lt;module&gt; creds = store.get() File "C:\Python27\lib\site-packages\oauth2client\client.py", line 407, in get return self.locked_get() File "C:\Python27\lib\site-packages\oauth2client\file.py", line 54, in locked_get credentials = client.Credentials.new_from_json(content) File "C:\Python27\lib\site-packages\oauth2client\client.py", line 302, in new_from_json module_name = data['_module'] KeyError: '_module' I am aware that there are several other questions on SO for this same issue, but those solutions did not help me. The token.json file is in the same folder as the script, and the URL appears to be spelled correctly as best I can tell. The JSON file looks correctly formatted. Any help would be greatly appreciated. Here is the script: """ Shows basic usage of the Gmail API. Lists the user's Gmail labels. """ from __future__ import print_function from apiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools # Setup the Gmail API SCOPES = 'https://www.googleapis.com/auth/gmail.readonly' store = file.Storage('token.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('credentials.json', SCOPES) creds = tools.run_flow(flow, store) service = build('gmail', 'v1', http=creds.authorize(Http())) # Call the Gmail API results = service.users().labels().list(userId='me').execute() labels = results.get('labels', []) if not labels: print('No labels found.') else: print('Labels:') for label in labels: print(label['name'])
has answer: http://stackoverflow.com/a/51462628
answer count: 2
upvote count: 1
favorite count: 0
tagged with: gmail-api
accepted answer: http://stackoverflow.com/a/51548611

http://stackoverflow.com/comment/89638886
has text: Well, that's odd. Is `c:\users\dsimard\python\lib\site-packages` on your `PYTHONPATH`? Show us the output of `print (sys.path)`.
comment on: http://stackoverflow.com/q/51331133
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89709995
type: Comment
has text: Thanks! but that is giving me the `unhashable type: 'numpy.ndarray'` error
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51368396

http://stackoverflow.com/q/51458338
type: Question
downvote count: 0
tagged with: filechooser
accepted answer: http://stackoverflow.com/a/51460621
has title: How to set file selected by tkinter filechooser (image) as the source to a Kivy image widget?
answer count: 1
tagged with: python
tagged with: kivy
has answer: http://stackoverflow.com/a/51460621
favorite count: 0
has body: I'm currently learning Kivy, I'm using tkinter filechooser to browse for images stored on my computer and want the selected image to be set as the source of the Images widget. The code below launches the tkinter filechooser on button click, how should I go about to set the obtained file as source for my image widgets. Thank you for your time. main.py from kivy.app import App from kivy.uix.label import Label from kivy.uix.button import Button from kivy.core.window import Window from kivy.uix.popup import Popup from kivy.uix.boxlayout import BoxLayout from kivy.properties import ObjectProperty from tkinter.filedialog import askopenfilename from tkinter import Tk class SampBoxLayout(BoxLayout): # Defines two FileChoosers. def get_image_one(self): # Select image file types, returned image should be used as source of Image widget. Tk().withdraw() # avoids window accompanying tkinter FileChooser img1 = askopenfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*"))) return img1 def get_image_two(self): Tk().withdraw() img2 = askopenfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*"))) return img2 class SampleApp(App): def build(self): # Set the background color for the window Window.clearcolor = (1, 1, 1, 1) return SampBoxLayout() sample_app = SampleApp() sample_app.run() sample.kv #: import CheckBox kivy.uix.checkbox &lt;ColoredBackground@Image&gt;: font_size: '48sp' color: (.9, .5, .4, 1) canvas.before: Color: rgb: (.9, .9, .9) Rectangle: pos: self.x + sp(2), self.y + sp(2) size: self.width - sp(5), self.height - sp(4) &lt;SampBoxLayout&gt;: orientation: "vertical" padding: 10 spacing: 10 # ---------- Button FileChooser ---------- BoxLayout: orientation: "horizontal" height: 30 Button: text: "FileChooser-1" on_press: root.get_image_one() Button: text: "FileChooser-2" on_press: root.get_image_two() # ---------- Display Images---------- BoxLayout: orientation: "horizontal" …
upvote count: 1
type: AnsweredQuestion
score: 1
tagged with: image

http://stackoverflow.com/q/51346511
type: Question
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
has body: I'm using the OpenStreetMap API to extract some data about a particular area using the code below: import requests import json overpass_url = "http://overpass-api.de/api/interpreter" overpass_query = """ [out:json]; area["ISO3166-1"="DE"][admin_level=2]; (node["amenity"="place_of_worship"](area); way["amenity"="place_of_worship"](area); rel["amenity"="place_of_worship"](area); ); out center; """ response = requests.get(overpass_url, params={'data': overpass_query}) data = response.json() I then try to print out all the 'names' from the above using the following code: for tags in data['elements']: print(tags['tags']['name']) This works fine for the first 12 or so results, but hits an issue when it comes across a result without a 'name' value within the 'tags' dictionary: Epiphanias Kirche Kirche St. Bilhildis Kleine Kreuzkirche Marienkapelle Kath. Kirche Heilige Familie St. Cyriakus Friedhofskapelle Ev. Hoffnungsgemeinde / Philippuszentrum Petrikirche Sankt Paulus Kapelle Höver Pfarrkirche St. Laurentius --------------------------------------------------------------------------- KeyError Traceback (most recent call last) &lt;ipython-input-81-5758361aa6f2&gt; in &lt;module&gt;() 1 for tags in data['elements']: ----&gt; 2 print(tags['tags']['name']) 3 4 #error occurs because not all have name tags KeyError: 'name' Is there a way I could skip any missing 'name' values and just keep on parsing?
has answer: http://stackoverflow.com/a/51346526
accepted answer: http://stackoverflow.com/a/51346526
answer count: 1
score: 0
has title: JSON parse loop skip if dictionary value not present
tagged with: python
tagged with: parsing

http://stackoverflow.com/comment/89735541
has text: BTW, Unicode handling is a lot nicer in Python 3. 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.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51381375
score: 0

http://stackoverflow.com/comment/89888999
has text: @rcgldr I am trying to replicate the same function without gf's. As you have said, I can generate N coefficients with encoding, and N data points throwing it to the lagrange interplortation. Beause isn't N+1 encoding, has to be solved with N+1 decoding? Not sure... im a newb in RS codes as I have said im trying it out thus im going with the simplest form as possible. Perhaps can you demonstrate how you would do it? Im getting your point and have reread the textbook. Even if the snippet is made on another language. Or just the flow perhaps?
comment on: http://stackoverflow.com/q/51456397
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89888216
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51459386
has text: Please provide a bit more detail about which part of the code isn't being executed and what you expect it to do.

http://stackoverflow.com/q/51420609
tagged with: filter
accepted answer: http://stackoverflow.com/a/51420694
has comment: http://stackoverflow.com/comment/89812295
upvote count: 0
answer count: 1
favorite count: 0
tagged with: parsing
tagged with: pattern-matching
tagged with: python
has body: I have the following string in python: Data sent by: zabbix The production server prod1 is unavailable https://zabbix.com/link/to/zabbix/dashboard Environment: prod1 Dep: dev How can i get Environment and Dep from that string to generate url from them? I tried to go line by line but it seems not a good solution. Please help i'm novice in python. Thanks
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51420694
has comment: http://stackoverflow.com/comment/89812149
has title: Get required values from multiline string python
has comment: http://stackoverflow.com/comment/89812192
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89812377
has comment: http://stackoverflow.com/comment/89812147
score: -1

http://stackoverflow.com/comment/89704843
type: QuestionComment
has text: is it helpful if i put the whole code? im new to this
comment on: http://stackoverflow.com/q/51366170
score: 0
type: Comment

http://stackoverflow.com/comment/89783256
comment on: http://stackoverflow.com/q/51372009
score: 0
type: Comment
type: QuestionComment
has text: It could be. Maybe try downloading it with a different tool (e.g., if you were using Firefox, try Chrome—or curl from the command line). Make sure the length of the file you get is exactly the same as the length on the server, and if they give a SHA hash or something (people often do when distributing large files), check it after the download.

http://stackoverflow.com/comment/89736075
score: 0
comment on: http://stackoverflow.com/q/51382162
type: Comment
type: QuestionComment
has text: What have you tried so far? Can you post your code?

http://stackoverflow.com/q/51349186
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/51349248
has title: ValueError: could not broadcast input array from shape (11253,1) into shape (11253)
tagged with: python
upvote count: 1
answer count: 1
tagged with: tensorflow
tagged with: neural-network
has body: I am creating a Neural Network using this example and I am getting the error "ValueError: could not broadcast input array from shape (11253,1)" into shape (11253), in the line : trainPredictPlot[look_back:len(trainPredict)+look_back] = trainPredicty My code is: import csv import math import numpy as np import pandas as pd from keras.models import Sequential from keras.layers import Dense import datetime import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split X1 = [1:16801] #16,800 values Y1 = [1:16801]#16,800 values train_size = int(len(X1) * 0.67) test_size = len(X1) - train_size train, test = X1[0:train_size,], X1[train_size:len(X1),] def Data(X1, look_back=1): dataX, dataY = [], [] for i in range(len(X1)-look_back-1): a = X1[i:(i+look_back), 0] dataX.append(a) dataY.append(Y1[i + look_back, 0]) return numpy.array(dataX), numpy.array(dataY) look_back = 1 trainX, testX = Data(train, look_back) testX, testY = Data(test, look_back) look_back = 1 trainX, testX = Data(train, look_back) testX, testY = Data(test, look_back) trainPredict = model.predict(trainX) testPredict = model.predict(testX) trainPredictPlot = numpy.empty_like(Y1) trainPredictPlot[look_back:len(trainPredict)+look_back] = trainPredict testPredictPlot = numpy.empty_like(Y1) testPredictPlot[len(trainPredict)+(look_back*2)+1:len(X1)-1] = testPredict I have 16,800 values for X1 which look like: [0.03454225 0.02062136 0.00186715 ... 0.92857565 0.64930691 0.20325924] And my Y1 data looks like: [ 2.25226244 1.44078451 0.99174488 ... 12.8397099 9.75722427 7.98525797] My traceback error message is: ValueError Traceback (most recent call last) &lt;ipython-input-9-e4da8990335b&gt; in &lt;module&gt;() 116 trainPredictPlot = numpy.empty_like(Y1) 117 --&gt; 118 trainPredictPlot[look_back:len(trainPredict)+look_back] = trainPredict 119 120 testPredictPlot = numpy.empty_like(Y1) ValueError: could not broadcast input array from shape (11253,1) into shape (11253)
has answer: http://stackoverflow.com/a/51349248
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/92751107

http://stackoverflow.com/comment/89792696
has text: @OndrejK. I understand the error message by your response, but i am not sure how to access the path, the configuration was just a trial, I am not sire about it, any leads would be really helpful.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51410089

http://stackoverflow.com/a/51391806
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/51391713
has body: save will almost always be hugely faster than savetxt. It just dumps the raw bytes, without having to format them as text. It also writes smaller files, which means less I/O. And you'll get equal benefits at load time: less I/O, and no text parsing. Everything else below is basically a variant on top of the benefits of save. And if you look at the times at the end, all of them are within an order of magnitude of each other, but all around two orders of magnitude faster than savetxt. So, you may just be happy with the 200:1 speedup and not care about trying to tweak things any farther. But, if you do need to optimize further, read on. savez_compressed saves the array with DEFLATE compression. This means you waste a bunch of CPU, but save some I/O. If it's a slow disk that's slowing you down, that's a win. Note that with smallish arrays, the constant overhead will probably hurt more than the compression speedup will help, and if you have a random array there's little to no compression possible. savez_compressed is also a multi-array save. That may seem unnecessary here, but if you chunk a huge array into, say, 20 smaller ones, this can sometimes go significantly faster. (Even though I'm not sure why.) The cost is that if you just load ip the .npz and stack the arrays back together, you don't get contiguous storage, so if that matters, you have to write more complicated code. Notice that my test below uses a random array, so the compression is just wasted overhead. But testing against zeros or arange would be just as misleading in the opposite direction, so… this is something to test on your real data. Also, I'm on a computer with a pretty fast SSD, so the tradeoff between CPU and I/O may not be as imbalanced as on whatever machine you're running on. numpy.memmap, or an array allocated into a stdlib mmap.mmap, is backed to disk with a write-through cache. This shouldn't reduce the total I/O time, but it means that the I/O doesn't happen all at once at the end, but is i…
downvote count: 0
score: 5
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51391713

http://stackoverflow.com/q/51335531
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51343944
has answer: http://stackoverflow.com/a/77065062
type: Question
tagged with: numpy
answer count: 2
possible better answer: http://stackoverflow.com/a/77065062
downvote count: 0
has body: I have a large 2D domain that is broken up into equally-sized 2D patches in several xarray DataArrays. So, for example, a simulation of what I have would be: a=xr.DataArray(np.random.rand(4,4)+0, dims=("x", "y"), coords=dict(x=range(4), y=range(4))) b=xr.DataArray(np.random.rand(4,4)+1, dims=("x", "y"), coords=dict(x=range(4,8), y=range(4))) c=xr.DataArray(np.random.rand(4,4)+2, dims=("x", "y"), coords=dict(x=range(4,8), y=range(4,8))) I am trying to put all these patches together to recreate the domain. So in the example case above, if I were to concatenate everything, I would have an 8 by 8 matrix at the end (with one of the "patches" as np.nan) and the other three patches corresponding to their respective DataArrays. I've been trying to automatize this with xarray but so far I've had no success. My closest attempt is using xr.concat: d=xr.concat([a,b,c], dim="x") d.plot.imshow(x="x") This produces the following image, which is obviously wrong: Note that in my case the patches are all scrambled, so I can't really rely on a specific order to concatenate. Here, for example, I could do d=xr.concat([xr.concat([a,b], dim="x"), c], dim="y"), but only because I know the order. PS: This may be somewhat related to this question, although it's not clear to me what this question actually asks.
tagged with: python-xarray
accepted answer: http://stackoverflow.com/a/51343944
tagged with: python
linked to: http://stackoverflow.com/q/47556078
has comment: http://stackoverflow.com/comment/89646406
favorite count: 0
has title: Concatenate xarray DataArrays simultaneously along 2 dimensions
upvote count: 1
has comment: http://stackoverflow.com/comment/89646157

http://stackoverflow.com/comment/89832281
type: Comment
type: QuestionComment
has text: You don't seem to ever call that function you defined.
comment on: http://stackoverflow.com/q/51430672
score: 4

http://stackoverflow.com/a/51459915
answers question: http://stackoverflow.com/q/51459160
score: 4
has comment: http://stackoverflow.com/comment/89901881
type: Answer
has body: The mistake in the algorithm is as follows. Look at what happens when you try to mark diagonals as visited. Let's draw the 4x4 board and assign each cell the number of positive-sloped diagonal it is located on (put i + j on the square located in the row i and col j): 0 1 2 3 1 2 3 4 2 3 4 5 3 4 5 6 Suppose that you put the first queen on the position (1,3). I know that your algorithm starts with row 0, but it doesn't matter in this case. Now the board looks as follows: 0 1 2 3 1 2 3 Q 2 3 4 5 3 4 5 6 Then you add 3 to visited_cols, add 3 + 1 = 4 to y_intercepts and add 3 - 1 = 2 to y_intercepts. We have cols = {3} and y_intercepts = {2,4}. Let's mark with X on the board the diagonal corresponding to the value 2 of y_intercept: 0 1 X 3 1 X 3 Q X 3 4 5 3 4 5 6 Now suppose we proceed with algorithm to row 2 and we try to put the second queen on square (2,0). This is a valid position because the first queen doesn't attack this square. But your algorithm will reject this position, because row + col = 2 + 0 = 2 is in the y_intercepts set. What happened? We did a positive-slope test for the square (2, 0) and it failed because there was 2 in the y_intercepts set. But note that this 2 was added there after checking the negative-sloped diagonal (remember 3 - 1 = 2 ?). So the tests for positive-sloped and negative-sloped diagonals got mixed which resulted in the incorrect rejection of square (2, 0). This is the reason why your program outputs the empty results vector - at some point of the algorithm there is a row such that all its squares are rejected (some are rejected correctly and others are rejected incorrectly similarly to what we just observed). One way to fix it is to create two separate sets for positive-sloped diagonals and negative-sloped diagonals and check row + col for positive-sloped ones and col - row for negative ones.
accepted answer of: http://stackoverflow.com/q/51459160
upvote count: 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/51366802
upvote count: 2
answers question: http://stackoverflow.com/q/51366730
has body: Since the string length is a constant, you can use a list comprehension to split each string into chunks with length eleven: n = 11 x = ['EDZ8 comdtyEDM1 comdtyEDU1 comdty', 'EDZ8 comdtyEDM1 comdtyEDZ1 comdty', 'EDZ8 comdtyEDM1 comdtyEDH2 comdty'] res = [[s[i:i+n] for i in range(0, len(s), n)] for s in x] Output: [['EDZ8 comdty', 'EDM1 comdty', 'EDU1 comdty'], ['EDZ8 comdty', 'EDM1 comdty', 'EDZ1 comdty'], ['EDZ8 comdty', 'EDM1 comdty', 'EDH2 comdty']]
has comment: http://stackoverflow.com/comment/89725020
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89740916
type: Answer

http://stackoverflow.com/q/51411210
has comment: http://stackoverflow.com/comment/89794160
has comment: http://stackoverflow.com/comment/89794731
has comment: http://stackoverflow.com/comment/89794728
answer count: 1
has comment: http://stackoverflow.com/comment/89795206
favorite count: 0
tagged with: python-3.x
has title: How to convert the arithmetic color to its RGB counterpart?
tagged with: python
has comment: http://stackoverflow.com/comment/89794305
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51411608
upvote count: 1
downvote count: 1
type: Question
tagged with: opencv
has body: When using an RGB color (255.0,0.0,0.0) (red) in openCV the output is blue instead. import cv2 import matplotlib.pyplot as plt plt.plot([1,2,3,4] , color=[1.0, 0.0, 0.0]) plt.savefig('tester.png') img = cv2.imread('tester.png') m_img = (cv2.line(img,(0,0),(100,100),(255.0,0.0,0.0),5)) cv2.imwrite('./update.png', m_img) tester.png : update.png : How to modify line m_img = (cv2.line(img,(0,0),(100,100),(255.0,0.0,0.0),5)) so that same RGB line colour from plt.plot([1,2,3,4] , color=[1.0, 0.0, 0.0]) is drawn ?
tagged with: matplotlib
has answer: http://stackoverflow.com/a/51411608
score: 0

http://stackoverflow.com/q/51392020
possible better answer: http://stackoverflow.com/a/51392150
has comment: http://stackoverflow.com/comment/89756203
has comment: http://stackoverflow.com/comment/89756184
score: 0
answer count: 2
has title: Making a 2 by 2 board centered
has comment: http://stackoverflow.com/comment/89755987
has answer: http://stackoverflow.com/a/51392155
favorite count: 0
accepted answer: http://stackoverflow.com/a/51392155
tagged with: python
has comment: http://stackoverflow.com/comment/89756765
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89756114
tagged with: list
has answer: http://stackoverflow.com/a/51392150
tagged with: whitespace
upvote count: 1
has body: Say I have a list: nlist = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0] And I have some code: def drawBoard(): count = 0 for i in range(16): print('|',nlist[i], end = ' ') count += 1 if count == 4: print("|\n-----------------") count = 0 print("") And this code displays the list like this: | 0 | 0 | 0 | 0 | ----------------- | 0 | 0 | 0 | 0 | ----------------- | 0 | 0 | 0 | 0 | ----------------- | 0 | 0 | 0 | 0 | ----------------- Right now the board looks fine but say I had a value like 128 instead of 1 of the zeros. That would unalign the board and make it look a little messy but when I get a whole bunch of numbers the board will just look plain out messy like this: | 128 | 0 | 4096 | 0 | ----------------- | 64 | 0 | 0 | 128 | ----------------- | 2048 | 0 | 0 | 8192 | ----------------- | 0 | 0 | 64 | 0 | ----------------- And now the board looks messed up and my lines under each number don't reach the end. How can I make the board look something like this(maybe change up the spacing between the straight lines) so that it doesn't look messy anymore: | 128 | 0 | 4096 | 0 | -------------------------- | 64 | 0 | 0 | 128 | -------------------------- | 2048 | 0 | 0 | 4096 | -------------------------- | 0 | 0 | 64 | 0 | --------------------------
downvote count: 1
type: Question

http://stackoverflow.com/comment/89883839
score: 0
type: Comment
type: QuestionComment
has text: @sacul Indeed, it's very similar to Python code. In fact, 0 means begin, 0.01 means step, 0.98 means end in MATLAB/Octave code.
comment on: http://stackoverflow.com/q/51457095

http://stackoverflow.com/comment/89880302
type: Comment
score: 0
has text: Yes but i dont find any sarisfied solution for that..!!
type: QuestionComment
comment on: http://stackoverflow.com/q/51455256

http://stackoverflow.com/comment/89703886
score: 0
has text: That is due to fail2ban. It performs two checks per line, I don’t need to check the date. I think the fail2ban datedetector removes the date from the test string.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51365716

http://stackoverflow.com/q/51398116
downvote count: 0
has comment: http://stackoverflow.com/comment/89767721
has answer: http://stackoverflow.com/a/51398429
linked to: http://stackoverflow.com/q/28840903
tagged with: regex
tagged with: string
has title: Regular Expression in Middle of a String in a List (Python)
favorite count: 0
has comment: http://stackoverflow.com/comment/89767316
linked to: http://stackoverflow.com/q/3640359
has comment: http://stackoverflow.com/comment/89767419
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51398438
accepted answer: http://stackoverflow.com/a/51398438
type: AnsweredQuestion
has body: I'm trying to use a regular expression to match a pattern in the middle of a string where the strings are also in a list. I can find the solution to one problem or the other, but confused on how to combine the two. First off, I'm using this solution as a template. I added text after "cat" and "cow", so they are now "cat named bob" and "cow also named bob". The goal is to extract the word "named" from those two strings in the list, and return them as items in a list (e.g. ['named', 'named']). mylist = ["dog", "cat named bob", "wildcat", "thundercat", "cow also named bob", "hooo"] r = re.compile('named') newlist = list(filter(r.search, mylist)) print(newlist) If I use r.search or r.findall, however, I get the entire string, rather than just the middle part. If I use r.match, I get no results. I found a few Stack Overflow queries on searching in the middle of a string, but they don't seem to go well with the solution for finding matches in a string. I tried the following code, but it didn't work: newlist = list(filter(r.match.group(1), mylist)) How would I combine these two tasks and extract text in the middle of a string inside of a list?
tagged with: list
score: 1
possible better answer: http://stackoverflow.com/a/51398429
type: Question
answer count: 2

http://stackoverflow.com/comment/89993500
type: Comment
comment on: http://stackoverflow.com/a/51463508
has text: I have the same issue with this as with L3viathan's solution. It does not merge my bus departures.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89677368
type: Comment
comment on: http://stackoverflow.com/a/51342742
has text: Also I could be wrong but I do not believe source is an attribute of slugrelatedfield. I just check the documentation and didn't see it mentioned anywhere and I never seen it used myself.
type: AnswerComment
score: 0

http://stackoverflow.com/q/51469559
tagged with: user-interface
type: UnansweredQuestion
tagged with: multithreading
tagged with: python
tagged with: qt
has comment: http://stackoverflow.com/comment/89938928
answer count: 0
has comment: http://stackoverflow.com/comment/89908179
has comment: http://stackoverflow.com/comment/89919100
has title: Integrating PyQt5 GUI with other python program
has comment: http://stackoverflow.com/comment/89930919
type: Question
has body: I have build a GUI with PyQt5 and I now want to integrate it with another python program. I have previously done this by placing GUI code written in TKinter in a separate thread. I want to know how to integrate this PyQt GUI into my other code the best way. My other program has 2 threads monitoring rotary encoders and the main thread works on a RFID reader + some database communication. Do the PyQt GUI have to be the main thread of the program? Here is the PyQt gui: from PyQt5 import QtGui from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QTableWidget, QTableWidgetItem, QVBoxLayout, QLabel from PyQt5.QtGui import QPixmap import sys class Reminder(): def __init__(self): self.activity = 'activity' # instance variable unique to each instance self.time = 0000 self.day = 'day' self.multiple_days = False class Window(QWidget): def __init__(self): super().__init__() self.titel = "GUI for Andreas" self.top = 150 self.left = 150 self.width = 500 self.height = 500 self.setWindowIcon(QtGui.QIcon("calender.png")) self.InitWindow() def InitWindow(self): self.setWindowTitle(self.titel) self.setGeometry(self.top,self.left,self.width,self.height) self.creatingTables(test_list) self.vBoxLayout = QVBoxLayout() self.vBoxLayout.addWidget(self.tableWidget) self.setLayout(self.vBoxLayout) self.textWidgets() self.vBoxLayout.addWidget(self.timelabel) self.vBoxLayout.addWidget(self.daylabel) self.show() def creatingTables(self, planned_activities): self.tableWidget = QTableWidget() self.tableWidget.setRowCount(len(planned_activities)) self.tableWidget.setColumnCount(4) count = 0 for i in planned_activities: index = 0 + count self.label = QLabel(self) self.label.setPixmap(QPixmap('%s.png' %i.activity)) self.tableWidget.setCellWidget(index,0, self.label) self.tableWidget.setItem(index,1, QTableWidgetItem(i.activity)) self.tableWidget.setItem(index,2, QTableWidgetItem(i.day)) self.tableWidget.setItem(index,3, QTableWidgetItem(str(i.time))) count +=1 def textWidgets(self): self.ti…
tagged with: pyqt
score: 0

http://stackoverflow.com/q/51440135
type: Question
has comment: http://stackoverflow.com/comment/118327937
has comment: http://stackoverflow.com/comment/89850458
score: 7
has comment: http://stackoverflow.com/comment/89850503
has answer: http://stackoverflow.com/a/75422528
answer count: 3
downvote count: 0
tagged with: keras
favorite count: 0
has answer: http://stackoverflow.com/a/59439972
has comment: http://stackoverflow.com/comment/89870807
linked to: http://stackoverflow.com/q/37293642
has answer: http://stackoverflow.com/a/51440256
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89850928
has body: I used the first example here as an example of network. How to stop the training when the loss reach a fixed value ? So, for example, I would like to fix a maximum of 3000 epochs and the training will stop when the loss will be under 0.2. I read this topic but it is not the solution I found. I would want to stop the training when the loss reach a value, not when there is no improvement like with this function proposed in the precedent topic. Here is the code: import keras from keras.models import Sequential from keras.layers import Dense, Dropout, Activation from keras.optimizers import SGD # Generate dummy data import numpy as np x_train = np.random.random((1000, 20)) y_train = keras.utils.to_categorical(np.random.randint(10, size=(1000, 1)), num_classes=10) x_test = np.random.random((100, 20)) y_test = keras.utils.to_categorical(np.random.randint(10, size=(100, 1)), num_classes=10) model = Sequential() # Dense(64) is a fully-connected layer with 64 hidden units. # in the first layer, you must specify the expected input data shape: # here, 20-dimensional vectors. model.add(Dense(64, activation='relu', input_dim=20)) model.add(Dropout(0.5)) model.add(Dense(64, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(10, activation='softmax')) sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True) model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy']) model.fit(x_train, y_train, epochs=3000, batch_size=128) score = model.evaluate(x_test, y_test, batch_size=128)
has title: TensorFlow - Stop training when losses reach a defined value
upvote count: 7
tagged with: tensorflow

http://stackoverflow.com/comment/89668640
score: 0
comment on: http://stackoverflow.com/q/51348016
type: Comment
type: QuestionComment
has text: The interactive interpreter in Python 3.6.0 (which I compiled myself) behaves as expected for me on a Debian derivative distro. Are you talking about IDLE?

http://stackoverflow.com/a/51411395
score: 0
answers question: http://stackoverflow.com/q/51411193
has body: You can use a pandas merge_asof once you rename Pred_class as below. dframe = dframe.rename(columns={'Pred_class':'Class'}) s = pd.merge_asof(X, dframe, on='Class') s['FinalQ'] = s['Quantity'] - s['Class'] Index Quantity Class Delta FinalQ 0 1 0 -0.04 1 1 5 0 -0.04 5 2 6 1 1.90 5 3 8 2 20.30 6 4 9 3 -7.00 6 5 0 4 6.60 -4
type: Answer

http://stackoverflow.com/comment/89948250
type: Comment
type: QuestionComment
has text: I think I would try to remove pycurl using pip, and then remove all the curl packages using apt/dpkg. Then reinstall curl and libcurl using apt, then reinstall pycurl using pip. Sorry, that's all I've got.
comment on: http://stackoverflow.com/q/51472336
score: 0

http://stackoverflow.com/comment/89955273
type: Comment
comment on: http://stackoverflow.com/a/51374313
has text: Hi @Eyal2000, I just added extra info on the answer
type: AnswerComment
score: 0

http://stackoverflow.com/q/51414013
tagged with: c++
score: 0
tagged with: python
has body: I use Python3.6 Generate tensorflow's Faster-RCNN's (on github: https://github.com/dBeker/Faster-RCNN-TensorFlow-Python3.5 ) .pb file and run this .pb file OK with Python3.6. I also write an MFC program (Win10 + VS2015 + C++ + Tensorflow1.8 both GPU and CPU version) to read and test this .pb file, but when I run the code : m_session-&gt;Run({ { strParaName1, m_TensorInput[0] }, { strParaName2, data_ } }, { opName1, opName2, opName3, opName4 }, {}, &amp;m_TensorOutput).ok()) MFC pop up a dialog box that says it needs pystate.c and suggests some bogues path: I downloaded a "pystate.c" file from https://github.com/python/cpython/blob/2.7/Python/pystate.c . When I select it, MFC shows error as below: Module: C:\ProgramData\Anaconda3\python36.dll The source file is different from the file when the module was generated. Do you want the debugger to use it? When I choose "yes", I get the source with an error message, as shown below: I guess this pystate.c is py2.7's version, my python version is 3.6, so this file may not be suitable.
tagged with: visual-studio
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51414544
has title: Visual Studio keeps asking for Python source file when running a Python extension project
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/51414544
has comment: http://stackoverflow.com/comment/89806874
answer count: 1

http://stackoverflow.com/q/51382266
possible better answer: http://stackoverflow.com/a/51382303
tagged with: pandas
has answer: http://stackoverflow.com/a/51382303
upvote count: 1
tagged with: datetime
favorite count: 0
has title: Converting dates into pd.datetime
tagged with: python
has body: I have a pandas dataframe with dates in the following formats: December 22, 2013 November 28, 2016 December 21, 2013 etc. Whats the easiest way to convert them to a datetime? Thanks in advance for any help!
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/51382297
accepted answer: http://stackoverflow.com/a/51382297
score: 1
tagged with: dataframe
type: Question
answer count: 2

http://stackoverflow.com/a/51430917
has body: Just iterate over all movies and compare the 7th column: made_usa = [] for l in movie_data: if l[6] == 'USA': made_usa.append(l) print (made_usa) To add only the movie name, it is just to do this: made_usa = [] for l in movie_data: if l[6] == 'USA': made_usa.append(l[0]) print (made_usa) To save if there is a match or not, you can use a dictionary like this: made_usa = {} for l in movie_data: if l[6] == 'USA': made_usa.update({l[0]: 'True'}) else: made_usa.update({l[0]: 'False'}) print (made_usa) After that, if you want to look if a certain move was made in USA or not. All you need to do is, for example: print(made_usa['Avatar']) Output: 'True'
has comment: http://stackoverflow.com/comment/89832972
downvote count: 0
has comment: http://stackoverflow.com/comment/89833644
has comment: http://stackoverflow.com/comment/89833099
type: Answer
has comment: http://stackoverflow.com/comment/89833464
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89833003
answers question: http://stackoverflow.com/q/51430857
has comment: http://stackoverflow.com/comment/89833046

http://stackoverflow.com/comment/89846492
type: AnswerComment
comment on: http://stackoverflow.com/a/51438067
score: 0
type: Comment
has text: Yes! This reduced the running time from 162 seconds to 0.05 seconds!

http://stackoverflow.com/a/51438879
score: 0
accepted answer of: http://stackoverflow.com/q/51438048
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51438048
has comment: http://stackoverflow.com/comment/89853356
type: Answer
has comment: http://stackoverflow.com/comment/89958002
has body: If I understand you correctly, you want to change the quantity of d1 with the (actual) quantity of df2. I think there is a more straightforward way to do so than what you are doing. Have a look: import pandas as pd df1 = pd.DataFrame({'DU ID':[102, 102, 102, 102, 102], 'Part Number':['00334567', '00334567', 'RRWQTDFG', '3456DDHE', 'DF033WW2'], 'Qty':[1, 2, 3, 4, 2], 'Unit':['PCS', 'PCS', 'PCS', 'PCS', 'PCS']}) df2 = pd.DataFrame({'DU ID':[102, 102, 102, 102], 'Part Number':['00334567', 'RRWQTDFG', '3456DDHE', 'DF033WW2'], 'Actual_Qty':[10, 3, 7, 0], 'Unit':['PCS', 'PCS', 'PCS', 'PCS']}) Now you merge the two dataframes: df1 = df1.merge(df2, on=['Part Number', 'DU ID', 'Unit']) DU ID Part Number Qty Unit Actual_Qty 0 102 00334567 1 PCS 10 1 102 00334567 2 PCS 10 2 102 RRWQTDFG 3 PCS 3 3 102 3456DDHE 4 PCS 7 4 102 DF033WW2 2 PCS 0 You can either stop here if you are okay with having both quantity columns or you clean up: df1 = df1'DU ID', 'Part Number', 'Actual_Qty', 'Unit' df1.columns = ['DU ID', 'Part Number', 'Qty', 'Unit'] DU ID Part Number Qty Unit 0 102 00334567 10 PCS 1 102 00334567 10 PCS 2 102 RRWQTDFG 3 PCS 3 102 3456DDHE 7 PCS 4 102 DF033WW2 0 PCS Edit: Apperently I misunderstood. Here is what you want (df1 and df2 same as before): index_df = df1.reset_index().groupby(by='Part Number').last().reset_index()'Part Number', 'index' quantities = pd.merge(df1.groupby(by='Part Number')['Qty'].sum().reset_index(), df2, on='Part Number') quantities['missing_qty'] = quantities.Actual_Qty - quantities.Qty quantities = quantities'Part Number', 'missing_qty' new_info = pd.merge(index_df, quantities, on='Part Number') new_info.set_index('index', inplace=True) df1.loc[new_info.index, 'Qty'] = df1.loc[new_info.index, 'Qty'] + new_info['missing_qty'] DU ID Part Number Qty Unit 0 102 00334567 1 PCS 1 102 00334567 9 PCS 2 102 RRWQTDFG 3 PCS 3 102 3456DDHE 7 PCS 4 102 DF033WW2 0 PCS
has comment: http://stackoverflow.com/comment/89848823

http://stackoverflow.com/comment/89892891
has text: good question mr rice
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51461115

http://stackoverflow.com/comment/89787180
score: 0
comment on: http://stackoverflow.com/q/51407461
has text: Curiously, you also get duplicate duplicate flags!
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51458478
score: 1
accepted answer: http://stackoverflow.com/a/51458516
has body: From a file structured like this: .............................. Delimiter [1] .............................. blablabla .............................. Delimiter CEO [2] .............................. blabla .............................. Delimiter [3] .............................. [...] .............................. Delimiter CEO [n-1] .............................. blablabla .............................. Delimiter [n] .............................. I wrote a code that extracts all the delimiters, but also some lines that I don't need. Those lines that I don't need cause my code to not run proprerly. I'd like to save in a new .txt file a line if in that line there's the regular expression " [ a number ]". So, to be more accurate in the extraction, I wrote this code in python (following this answer) using re: import re with open('testoestratto.txt','r',encoding='UTF-8') as myFile: text = myFile.readlines() text = [frase.rstrip('\n') for frase in text] regex = r'\[\d+\]' new_file=[] for lines in text: match = re.search(regex, lines, re.MULTILINE) if match: new_line = match.group() + '\n' new_file.append(new_line) with open('prova.txt', 'w') as f: f.seek(0) f.writelines(new_file) But, in the 'prova.txt' file I could find only the regular expressions so I have a file with [1], [2], ... [n-1], [n].
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89886944
favorite count: 0
has title: RegEx, find a match in a line and print it
tagged with: python
tagged with: regex
type: AnsweredQuestion
tagged with: python-3.x
linked to: http://stackoverflow.com/q/14840310
linked to: http://stackoverflow.com/q/51390741
has answer: http://stackoverflow.com/a/51458516
upvote count: 1
type: Question

http://stackoverflow.com/comment/89749284
comment on: http://stackoverflow.com/q/51388607
has text: fileName = part.get_filename() -> filePath = os.path.join(detach_dir, 'attachments', fileName) is an attack waiting to happen.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89850584
type: AnswerComment
score: 0
type: Comment
has text: Great. I got some lessons here. I am beginner to Python (5 days). Thanks a lot @https://stackoverflow.com/users/8300135/spghttcd
comment on: http://stackoverflow.com/a/51437134

http://stackoverflow.com/comment/120605561
type: Comment
has text: This solution requires you to install libvips as per https://libvips.github.io/libvips/install.html. If you already have InkScape or such like you may not want another editor. Libvips is pretty low level and techie.
score: 0
comment on: http://stackoverflow.com/a/62876618
type: AnswerComment

http://stackoverflow.com/a/51359764
upvote count: 1
has comment: http://stackoverflow.com/comment/89691753
answers question: http://stackoverflow.com/q/51359473
downvote count: 0
type: Answer
has body: Using a dict is the only sane solution here, period. Not only because it's the most explicit, obvious, readable and maintainable solution but also because you definitly want to have full control when it comes to mapping user inputs (anything that comes from the outside world) to executable code (security 101: never trust user inputs).
score: 1

http://stackoverflow.com/q/51447348
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51485900
type: Question
tagged with: visual-studio-code
score: 0
has title: Set shell command as Visual Studio Code include paths source
answer count: 1
has answer: http://stackoverflow.com/a/51485900
has body: I've written own Python based build system for my AVR project. Some of the defines and include paths are in dependence of current target (I build binaries to some MCUs and crystal frequencies). I want to set IntelliSense paths dependent of script stdout output. Is this possible or is there any extension to do that?
tagged with: python

http://stackoverflow.com/q/51415674
upvote count: 3
tagged with: selenium
has answer: http://stackoverflow.com/a/58893030
type: Question
has answer: http://stackoverflow.com/a/51415822
has comment: http://stackoverflow.com/comment/89802519
has answer: http://stackoverflow.com/a/51416150
tagged with: css-selectors
has answer: http://stackoverflow.com/a/51416219
has title: How to find and click the button by "onclick" with Selenium and Python?
downvote count: 0
accepted answer: http://stackoverflow.com/a/51415822
favorite count: 0
tagged with: xpath
possible better answer: http://stackoverflow.com/a/51415928
answer count: 5
has answer: http://stackoverflow.com/a/51415928
tagged with: python
tagged with: selenium-webdriver
type: AnsweredQuestion
has body: There are 2 buttons in a page, and the difference between these 2 buttons is "onclick". OK OK I was thinking to use xpath: driver.find_element_by_xpath("//form[@id='update-container-id']/div/div/div/div[2]/div/div[2]/table[1]/tbody/tr[1]/td[8]/div[3]/div/div/div/div[3]/button").click() But it responses the error as below: selenium.common.exceptions.ElementNotInteractableException: Message: Element could not be scrolled into view Does anyone can help me to click the 2nd button correctly? Thanks a lot.
score: 3

http://stackoverflow.com/comment/89887192
has text: Because the value in the string **is not** an integer variable, it's a `floating-point` variable.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51458908
score: 1

http://stackoverflow.com/q/51400461
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/51400512
has title: Setting dictionary value in python does not update the value?
has body: I am trying to simply replace missing date values from two strings, but splitting them into a dictionary of "year", "month", etc. However I am running into a very odd issue I did not find the answer for after 20 minutes googling. Here's my code: def date_split(date): parts = date.split('-') if len(parts) == 1: year = parts[0] dates = {'y' : year} if len(parts) == 2: year = parts[0] month = parts[1] dates = {'y' : year, 'm' : month} if len(parts) == 3: year = parts[0] month = parts[1] day = parts[2] dates = {'y' : year, 'm' : month, 'd' : day} return dates def recompile(date): lista = list(date.values()) date = "-".join(lista) return date std = "2018-07-18" x = "XXXX-01" if date_split(x)['y'] == 'XXXX': new = str(date_split(std)['y']) date_split(x)['y'] = new date = recompile(date_split(x)) print(date) I just began twiddling with it so it's very rough, but I am working on it. However, while date_split(std)['y'] prints out as 2018, after date_split(x)['y'] = new, the value of date_split(x)['y'] prints out as "XXXX" still. So the dictionary does not update the value. Is there something I'm missing about how dictionaries work in python? I'm quite new to it. I've tried also different forms of the dictionary update command. Using Python 3.6 with Anaconda.
has answer: http://stackoverflow.com/a/51400640
favorite count: 0
has answer: http://stackoverflow.com/a/51400512
has answer: http://stackoverflow.com/a/51401430
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/89779672
answer count: 4
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51400564
downvote count: 0
has comment: http://stackoverflow.com/comment/89771781
has answer: http://stackoverflow.com/a/51400564

http://stackoverflow.com/q/51482271
tagged with: webcam
has answer: http://stackoverflow.com/a/51482370
linked to: http://stackoverflow.com/q/35821763
type: Question
tagged with: raspberry-pi3
score: 0
has body: I will use two webcams to process image on Raspberrypi3. I want to fix device video number to each camera. Because I need to know which camera is leftside or rightside. How to fix video numbers to each camera? from collections import deque import numpy as np import argparse import imutils import cv2 import time from multiprocessing import Process, Queue class opencv: def __init__(self): self.FrameWidth = 1024 self.FrameHeight = 576 def rescale_frame(self, frame, percent=75): width = int(frame.shape[1] * percent/ 100) height = int(frame.shape[0] * percent/ 100) dim = (width, height) return cv2.resize(frame, dim, interpolation =cv2.INTER_AREA),width,height def cam(self, video): camera = cv2.VideoCapture(video) camera.set(3, self.FrameWidth) camera.set(4, self.FrameHeight) while True: (grab, frame) = camera0.read() frame,width,height = self.rescale_frame(frame, percent=50) # pixcel 50% cv2.imshow("Frame", frame) key = cv2.waitKey(60) &amp; 0xFF if (key == 27): break if (key == ord('i')): while True: cv2.imshow("Frame", frame) cv2.waitKey(0) if key == ord('i'): break camera.release() cv2.destroyAllWindows() if __name__ == "__main__": cam0 = opencv() cam1 = opencv() p1 = Process(target = cam0.cam, args = (0,)) p2 = Process(target = cam1.cam, args = (1,)) p1.start() p2.start()
answer count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89973879
tagged with: python
has title: How to assign a fix number to cameras
has comment: http://stackoverflow.com/comment/89933539

http://stackoverflow.com/comment/89674629
has text: `chr()` is problematic, too. I would collect the values into a list without `chr()` or any other conversion and then pass that list to `bytes()` when you're done looping.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51350462

http://stackoverflow.com/comment/89642195
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51333061
has text: Yes the optimal slope is y/x but for gradient descent, we take a step in direction of dloss/dw which would be 2(y-y_model)*x. Pardon my previous comment, I meant delta w will be dloss/dw not dloss/dx
type: Comment

http://stackoverflow.com/comment/89673855
type: Comment
comment on: http://stackoverflow.com/a/51350658
type: AnswerComment
score: 0
has text: Any recommendations where I should create that file? In the current working directory? In the directory where my program is located? Somewhere else?

http://stackoverflow.com/a/51372164
has comment: http://stackoverflow.com/comment/89746196
has comment: http://stackoverflow.com/comment/89716425
type: Answer
has comment: http://stackoverflow.com/comment/89716304
has comment: http://stackoverflow.com/comment/89756107
score: 1
accepted answer of: http://stackoverflow.com/q/51372151
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: If you ever heard of PyPdf, you might have a solid option there. import pyPdf reader = pyPdf.PdfFileReader(open("foo.pdf")) print reader.getNumPages() This should do what you are looking for
answers question: http://stackoverflow.com/q/51372151

http://stackoverflow.com/q/51482276
has comment: http://stackoverflow.com/comment/89933367
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89934105
has comment: http://stackoverflow.com/comment/89933636
tagged with: python
has title: Transformation of a csv into a dictionary and replace of words in a text
tagged with: replace
type: Question
tagged with: encoding
has comment: http://stackoverflow.com/comment/89933638
has body: I'm trying to convert a csv file into a dictionary and replace the keys with the values in a text. I tried several things and they didn't work. My csv file (en.csv): chat,chats noir,noirs km,k table,tables être,sont être,est cinema,cinemas fermer,fermés casser,cassées My script: import csv import re with open('fr.csv', 'r') as lemmas: lematizer = csv.reader(lemmas, delimiter = ',') text = "chats sont noirs tables sont cassées ils sont tristes la vie est belle cinemas sont fermés" tuples = [] for tokens in lematizer: tuples.append(tuple([tokens[1], tokens[0]])) result = dict(tuples) lemmatized_text = re.sub(r'\b(%s)\b' % '|'.join(result.keys()), lambda m:result.get(m.group(1), m.group(1)), text) print(lemmatized_text) Output is good! chat être noir table être casser il etre triste le vie etre beau cinema être fermer But when I try to do the same in a large text with many lines, it doesn't work: I only have text printed unmodified. And even worse: I also have this error (everything is in utf-8) colis livr� � Encodings: fr.csv: UTF-8 Unicode text text.csv: UTF-8 Unicode text, with very long lines .py: Python script, UTF-8 Unicode text executable
has comment: http://stackoverflow.com/comment/89934510
score: 0
linked to: http://stackoverflow.com/q/904041

http://stackoverflow.com/q/51338756
linked to: http://stackoverflow.com/q/10035541
has body: I'm fairly new to Python and I am having real trouble because I run into it this Segmentation fault: 11 error. Here is a simple code example that produces this error every time: import grequests class Url(object): pass a = Url() a.url = 'http://www.heroku.com' a.result = 0 b = Url() b.url = 'http://www.google.com' b.result = 0 c = Url() c.url = 'http://www.wordpress.com' c.result = 0 urls = [a, b, c] rs = (grequests.get(u.url) for i, u in enumerate(urls)) grequests.map(rs) What is absolutely bizarre is that if I replace the urls = ... line with this: urls = [a, b] Then I get no error, and the script runs fine. If I change that to just urls = [c] Then I also get no error, and the script runs fine. If I change c.url = ... to c.url = "http://yahoo.com" And revert urls = ... back to urls = [a, b, c] Then I do get the segmentation fault: 11 error. Being a memory issue sounds like a possibility though I'm not sure how to fix it. I've been stuck on this for a number of days, so any help, no matter how small, is greatly appreciated. For reference, I'm using macOS High Sierra (10.13.5) and installed Python 3.7.0 using Brew.
linked to: http://stackoverflow.com/q/9412156
duplicate of: http://stackoverflow.com/q/10035541
type: UnansweredQuestion
has title: What does Segmentation fault: 11 mean and how do you fix it?
has comment: http://stackoverflow.com/comment/89652025
has comment: http://stackoverflow.com/comment/89653375
score: 2
favorite count: 0
has answer: http://stackoverflow.com/a/51340555
type: Question
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/89653244
upvote count: 3
has comment: http://stackoverflow.com/comment/89653086
downvote count: 1

http://stackoverflow.com/q/51460868
type: Question
tagged with: numpy
score: 0
has answer: http://stackoverflow.com/a/51460878
answer count: 2
tagged with: array-broadcasting
has body: I have a M x N matrix X and a 1 x N matrix Y. What I would like to do is replace any 0-entry in X with the appropriate value from Y based on its column. So if X = np.array([[0, 1, 2], [3, 0, 5]]) and Y = np.array([10, 20, 30]) The desired end result would be [[10, 1, 2], [3, 20, 5]]. This can be done straightforwardly by generating a M x N matrix where every row is Y and then using filter arrays: Y = np.ones((X.shape[0], 1)) * Y.reshape(1, -1) X[X==0] = Y[X==0] But could this be done using numpy's broadcasting functionality?
tagged with: python
possible better answer: http://stackoverflow.com/a/51461553
accepted answer: http://stackoverflow.com/a/51460878
has title: Numpy: Can you use broadcasting to replace values by row?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51461553

http://stackoverflow.com/comment/89647215
type: QuestionComment
comment on: http://stackoverflow.com/q/51336103
has text: That's a restriction imposed by that specific website. Nothing to do with `requests`.
score: 4
type: Comment

http://stackoverflow.com/q/51352047
upvote count: 1
answer count: 1
has body: I'm writing a simple bouncing icon program (Python 3.7, Windows 10 x64) to get the feel for Tkinter and canvases. I've posted my code below. My problem with the program is that it clips the edges of the icon (in the direction of motion). If I slow the motion down a bit (by increasing the value in the after method) it no longer clips, but the motion is choppy. Maybe I'm overthinking this, it basically does what I've aimed for. But if this were a game or other project that mattered, how would this be prevented? from tkinter import * import os from PIL import Image, ImageTk xinc, yinc = 5, 5 def load_image(width, height, imgpath): loadimg = Image.open(imgpath) pwid, phi = loadimg.size pf1, pf2 = 1.0*width/pwid, 1.0*height/phi pfactor = min([pf1, pf2]) pwidth, pheight = int(pwid*pfactor), int(phi*pfactor) loaded = loadimg.resize((pwidth, pheight), Image.ANTIALIAS) loaded = ImageTk.PhotoImage(loaded) return loaded def bounce(): global xinc global yinc cwid = int(dash.cget('width')) chi = int(dash.cget('height')) x = dash.coords(dashposition)[0] y = dash.coords(dashposition)[1] if x &gt; cwid-10 or x &lt; 10: xinc = -xinc if y &gt; chi-10 or y &lt; 10: yinc = -yinc dash.move(dashposition, xinc, yinc) dash.after(15, bounce) root = Tk() root.configure(bg='black') dash = Canvas(root, bg='black', highlightthickness=0, width=400, height=300) dash.grid(row=0, column=0, padx=2, pady=2) imagepath = os.getcwd() + '/img/cloudy.png' image = load_image(20, 20, imagepath) x, y = 10, 10 dashposition = dash.create_image(x, y, anchor=CENTER, image=image, tags=('current')) bounce() root.mainloop() cloudy.png
type: UnansweredQuestion
has title: Tkinter - bouncing icon script
has answer: http://stackoverflow.com/a/51352489
downvote count: 0
has comment: http://stackoverflow.com/comment/89677423
favorite count: 0
type: Question
tagged with: python
score: 1
tagged with: tkinter

http://stackoverflow.com/comment/89837524
type: Comment
comment on: http://stackoverflow.com/q/51433394
score: 0
has text: Oh, didn't realize that is what you were trying to accomplish. In that case you probably need a while loop so that the program continues to loop until you `control-c` or otherwise purposefully exit. Does that sound like an accurate of what you are looking to accomplish?
type: QuestionComment

http://stackoverflow.com/comment/89841655
type: QuestionComment
type: Comment
has text: You might want to read these threads: [assigning a function to an object attribute](https://stackoverflow.com/questions/6478371/assigning-a-function-to-an-object-attribute) and [Python: bound and unbound method](https://stackoverflow.com/questions/1015307/python-bind-an-unbound-method/1015405#1015405)
comment on: http://stackoverflow.com/q/51435095
score: 0

http://stackoverflow.com/q/51479360
has body: I am having below issue and it keeps on continuing. It starts with missed heartbeats and whenever I try to give a task then this issue will keep on going. rabbit_1 | 2018-07-23 16:09:27.226 [warning] &lt;0.566.0&gt; closing AMQP connection &lt;0.566.0&gt; (172.18.0.10:33754 -&gt; 172.18.0.7:5672): rabbit_1 | missed heartbeats from client, timeout: 60s rabbit_1 | 2018-07-23 16:09:45.486 [warning] &lt;0.583.0&gt; closing AMQP connection &lt;0.583.0&gt; (172.18.0.9:35682 -&gt; 172.18.0.7:5672): rabbit_1 | missed heartbeats from client, timeout: 60s rabbit_1 | 2018-07-23 12:47:05.258 [info] &lt;0.31892.9&gt; connection &lt;0.31892.9&gt; (172.18.0.10:42580 -&gt; 172.18.0.8:5672): user 'guest' authenticated and granted access to vhost '/' rabbit_1 | 2018-07-23 12:47:05.260 [warning] &lt;0.31892.9&gt; closing AMQP connection &lt;0.31892.9&gt; (172.18.0.10:42580 -&gt; 172.18.0.8:5672, vhost: '/', user: 'guest'): rabbit_1 | client unexpectedly closed TCP connection rabbit_1 | 2018-07-23 12:47:05.266 [info] &lt;0.31907.9&gt; accepting AMQP connection &lt;0.31907.9&gt; (172.18.0.10:42582 -&gt; 172.18.0.8:5672) rabbit_1 | 2018-07-23 12:47:05.267 [info] &lt;0.31907.9&gt; connection &lt;0.31907.9&gt; (172.18.0.10:42582 -&gt; 172.18.0.8:5672): user 'guest' authenticated and granted access to vhost '/' rabbit_1 | 2018-07-23 12:47:05.269 [warning] &lt;0.31907.9&gt; closing AMQP connection &lt;0.31907.9&gt; (172.18.0.10:42582 -&gt; 172.18.0.8:5672, vhost: '/', user: 'guest'): rabbit_1 | client unexpectedly closed TCP connection rabbit_1 | 2018-07-23 12:47:05.284 [info] &lt;0.31922.9&gt; accepting AMQP connection &lt;0.31922.9&gt; (172.18.0.10:42584 -&gt; 172.18.0.8:5672) rabbit_1 | 2018-07-23 12:47:05.286 [info] &lt;0.31922.9&gt; connection &lt;0.31922.9&gt; (172.18.0.10:42584 -&gt; 172.18.0.8:5672): user 'guest' authenticated and granted access to vhost '/' rabbit_1 | 2018-07-23 12:47:05.292 [warning] &lt;0.31922.9&gt; closing AMQP connection &lt;0.31922.9&gt; (172.18.0.10:42584 -&g…
has comment: http://stackoverflow.com/comment/89927295
score: 0
has comment: http://stackoverflow.com/comment/89927970
has title: Celery stale issue
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: rabbitmq
tagged with: celery
type: Question

http://stackoverflow.com/comment/89736644
type: Comment
score: 0
type: AnswerComment
has text: @PM2Ring: The author of this answer addressed the most pressing problem of the OP first, namely syntax error. The next most pressing problem was that of correct output.
comment on: http://stackoverflow.com/a/51382271

http://stackoverflow.com/a/51388828
has comment: http://stackoverflow.com/comment/89754049
type: AcceptedAnswer
downvote count: 0
score: 7
answers question: http://stackoverflow.com/q/51388201
type: Answer
accepted answer of: http://stackoverflow.com/q/51388201
upvote count: 7
has comment: http://stackoverflow.com/comment/89749865
has body: I'd consider .map (#3) the idiomatic way to do this - but don't pass the .get - use the dictionary by itself, and should see a pretty significant improvement. df = pd.DataFrame({'label': np.random.randint(, 4, size=1000000, dtype='i8')}) %timeit df['output'] = df.label.map(lookup_dict.get) 261 ms ± 12.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) %timeit df['output'] = df.label.map(lookup_dict) 69.6 ms ± 3.08 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) If the number of conditions is small, and the comparison cheap (i.e. ints and your lookup table), direct comparison of the values (4 and especially 5) is faster than .map, but this wouldn't always true, e.g. if you had a set of strings. If your lookup labels really are contigous integers, you can exploit this and lookup using a take, which should be about as fast as numba. I think this is basically as fast as this can go - could write the the equivalent in cython, but won't be quicker. %%timeit lookup_arr = np.array(list(lookup_dict.values())) df['output'] = lookup_arr.take(df['label'] - 1) 8.68 ms ± 332 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

http://stackoverflow.com/a/51474462
has comment: http://stackoverflow.com/comment/89923424
score: 1
has comment: http://stackoverflow.com/comment/89923504
has body: You're mixing up a bit. Gunicorn is used to build dynamic API in a more efficient way, and typically you should use it in pair with nginx to actually gain in efficiency. I.e. Gunicorn to build dynamic APIs and nginx to redistribute the static ones. You can read here in more details https://serverfault.com/questions/331256/why-do-i-need-nginx-and-something-like-gunicorn Here is working Gunicorn setup: echo "--------------- Kill workers ---------------" ps aux | grep gunicorn | grep myniceappname | awk '{ print $2 }' | xargs kill -9 echo "--------------- Start workers ---------------" gunicorn run:app --name myniceappname --bind 0.0.0.0:5000 --workers 4 --reload
accepted answer of: http://stackoverflow.com/q/51434711
upvote count: 1
answers question: http://stackoverflow.com/q/51434711
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89919666
has comment: http://stackoverflow.com/comment/89919846
type: Answer
downvote count: 0

http://stackoverflow.com/comment/89654584
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51340142
has text: What is your distribution?
score: 0

http://stackoverflow.com/comment/89636559
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51325193
type: QuestionComment
has text: It was my silly mistake. I should have checked all the variables before posting a question One of the DUPLICATE_INCIDENT* variables was a string. That was causing the above issue. It is working as expected now..

wireshark
tags question: http://stackoverflow.com/q/51422768
type: Tag
tag name: wireshark

http://stackoverflow.com/a/51412851
accepted answer of: http://stackoverflow.com/q/51411980
score: 0
type: AcceptedAnswer
type: Answer
has body: So... Using Quotes within getRuntime().exec Apparently this is a thing. I just made every word in the command an array element instead, and inside the array, "show bgp scale" was entered without the quotes. After that, it worked.
answers question: http://stackoverflow.com/q/51411980

http://stackoverflow.com/comment/89669037
comment on: http://stackoverflow.com/q/51346750
type: Comment
type: QuestionComment
score: 0
has text: You should provide some information about what errors does the code raise. Also, don't expect people to guide you "line by line" though documentation.

http://stackoverflow.com/comment/89799058
has text: I'm sorry, actually, the break is correct. I formatted it wrong in this post. That is not the problem, I used it correctly when I ran it. My 2nd decisions are the ones that give me error signs. Also, I'm using python 3 not 2, so raw_input wouldn't work.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51412801

http://stackoverflow.com/comment/89875362
type: Comment
has text: @tripleee Ah, it's not even for old-style classes, but for pre-2.2 extension types… Nice find; I'll update the answer.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51451948

http://stackoverflow.com/q/51450004
type: Question
tagged with: apache-spark-sql
possible better answer: http://stackoverflow.com/a/51450099
has answer: http://stackoverflow.com/a/51450099
tagged with: pyspark
has answer: http://stackoverflow.com/a/67828313
has answer: http://stackoverflow.com/a/76555028
score: 22
upvote count: 22
tagged with: apache-spark
downvote count: 0
tagged with: string
has answer: http://stackoverflow.com/a/51450277
favorite count: 0
has body: I have a Spark dataframe with a column (assigned_products) of type string that contains values such as the following: "POWER BI PRO+Power BI (free)+AUDIO CONFERENCING+OFFICE 365 ENTERPRISE E5 WITHOUT AUDIO CONFERENCING" I would like to count the occurrences of + in the string for and return that value in a new column. I tried the following, but I keep returning errors. from pyspark.sql.functions import col DF.withColumn('Number_Products_Assigned', col("assigned_products").count("+")) I'm running my code in Azure Databricks on a cluster running Apache Spark 2.3.1.
accepted answer: http://stackoverflow.com/a/51450277
tagged with: python
has title: Count substring in string column using Spark dataframe
answer count: 4
type: AnsweredQuestion

http://stackoverflow.com/q/51369153
has comment: http://stackoverflow.com/comment/90953278
type: Question
has comment: http://stackoverflow.com/comment/89712034
tagged with: nginx
has comment: http://stackoverflow.com/comment/89711930
has comment: http://stackoverflow.com/comment/89711872
score: 0
has comment: http://stackoverflow.com/comment/89712117
has comment: http://stackoverflow.com/comment/89711748
tagged with: supervisord
has comment: http://stackoverflow.com/comment/89711427
has comment: http://stackoverflow.com/comment/89711373
has title: nginx supervisor django gunicorn 404
tagged with: gunicorn
has comment: http://stackoverflow.com/comment/89711478
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89711869
has comment: http://stackoverflow.com/comment/89712286
has comment: http://stackoverflow.com/comment/89711027
has body: I have been trying to deploy a django application through nginx following this tutorial: karzynski and here is my set up: supervisor: [program:eviotapro] command = /home/effect/Desktop/workspace/Eviota/gunicorn_start.bash; user = root ; User to run as stdout_logfile = /home/effect/Desktop/workspace/Eviota /logs/gunicorn_supervisor.log ; Where to write log messages redirect_stderr = true ; Save stderr in the same log environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 ; Set UTF-8 as default encoding when I run the supervisor Everything seems ok and no problem is shown. Here is my nginx configuration which I can't say I fully understand upstream eviotapro_server { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response (in case the Unicorn master nukes a # single worker for timing out). server unix:/home/effect/Desktop/workspace/Eviota/run/gunicorn.sock fail_timeout=0; } server { listen 8005; server_name &lt;ip address&gt;; client_max_body_size 4G; access_log /home/effect/Desktop/workspace/Eviota/logs/nginx-access.log; error_log /home/effect/Desktop/workspace/Eviota/logs/nginx-error.log; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/effect/Desktop/workspace/Eviota/eviotapro/static/; } location /media/ { alias /home/effect/Desktop/workspace/Eviota/eviotapro/media/; } location / { # an HTTP header important enough to have its own Wikipedia entry: # http://en.wikipedia.org/wiki/X-Forwarded-For proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # enable this if and only if you use HTTPS, this helps Rack # set the proper protocol for doing redirects: # proxy_set_header X-Forwarded-Proto https; # pass the Host: header from the client right along so redirects # can be set properly within the Rack application proxy_set_header Host $http_host; # we don't want nginx trying to do something clever with # redirects, we set the Host: header above already. proxy_redirect off; # set "…
answer count: 0
has comment: http://stackoverflow.com/comment/89711827

http://stackoverflow.com/q/51407667
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/22825349
answer count: 0
duplicate of: http://stackoverflow.com/q/22825349
type: Question
has title: Convert pandas Timestamp column to datetime
linked to: http://stackoverflow.com/q/49757871
has comment: http://stackoverflow.com/comment/89832160
has comment: http://stackoverflow.com/comment/89832342
score: 0
tagged with: pandas
has body: I have a data frame which looks like this: A 0 1900-01-01 08:00:00 1 1900-01-01 14:30:00 2 1900-01-01 17:00:00 3 1900-01-01 14:00:00 4 1900-01-01 19:00:00 Each of the values is a Timestamp: &lt;&lt;&lt;df.loc[0,"A"] Timestamp('1900-01-01 08:00:00') I'd like to create a new column where the values are datetime rather than Timestamp. I thought this was the way to do it: df["A2"] = pd.to_datetime(df["A"]) But the new column is also a series of Timestamps: A A2 0 1900-01-01 08:00:00 1900-01-01 08:00:00 1 1900-01-01 14:30:00 1900-01-01 14:30:00 2 1900-01-01 17:00:00 1900-01-01 17:00:00 3 1900-01-01 14:00:00 1900-01-01 14:00:00 4 1900-01-01 19:00:00 1900-01-01 19:00:00 &lt;&lt;&lt;df.loc[0,"A2"] Timestamp('1900-01-01 08:00:00') What am I doing wrong?
has comment: http://stackoverflow.com/comment/89786785
has comment: http://stackoverflow.com/comment/89786601

http://stackoverflow.com/q/51360372
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89693040
has comment: http://stackoverflow.com/comment/89693650
has body: Can some one tell me what I am doing wrong ?I am Getting this error.. went through the earlier post of similar error. couldn't able to understand.. import json import re import requests import subprocess res = requests.get('https://api.tempura1.com/api/1.0/recipes', auth=('12345','123'), headers={'App-Key': 'some key'}) data = res.text extracted_recipes = [] for recipe in data['recipes']: extracted_recipes.append({ 'name': recipe['name'], 'status': recipe['status'] }) print extracted_recipes TypeError: string indices must be integers data contains the below { "recipes": { "47635": { "name": "Desitnation Search", "status": "SUCCESSFUL", "kitchen": "eu", "active": "YES", "created_at": 1501672231, "interval": 5, "use_legacy_notifications": false }, "65568": { "name": "Validation", "status": "SUCCESSFUL", "kitchen": "us-west", "active": "YES", "created_at": 1522583593, "interval": 5, "use_legacy_notifications": false }, "47437": { "name": "Gateday", "status": "SUCCESSFUL", "kitchen": "us-west", "active": "YES", "created_at": 1501411588, "interval": 10, "use_legacy_notifications": false } }, "counts": { "total": 3, "limited": 3, "filtered": 3 } }
score: -1
has comment: http://stackoverflow.com/comment/89693287
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/51360701
has comment: http://stackoverflow.com/comment/89693166
has comment: http://stackoverflow.com/comment/89692946
has answer: http://stackoverflow.com/a/51360439
has comment: http://stackoverflow.com/comment/89693098
has comment: http://stackoverflow.com/comment/89693238
favorite count: 0
has comment: http://stackoverflow.com/comment/89693130
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89693054
tagged with: python
has comment: http://stackoverflow.com/comment/89693007
has title: python TypeError: string indices must be integers json
has comment: http://stackoverflow.com/comment/89693212
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/q/51463146
upvote count: 5
downvote count: 0
tagged with: webrtc
has answer: http://stackoverflow.com/a/76295238
has answer: http://stackoverflow.com/a/62410269
tagged with: speech-recognition
favorite count: 0
type: UnansweredQuestion
score: 5
tagged with: python
tagged with: voice-recognition
tagged with: audio
has title: python webrtc voice activity detection is wrong
type: Question
has comment: http://stackoverflow.com/comment/91179925
has body: I need to do voice activity detection as a step to classify audio files. Basically, I need to know with certainty if a given audio has spoken language. I am using py-webrtcvad, which I found in git-hub and is scarcely documented: https://github.com/wiseman/py-webrtcvad Thing is, when I try it on my own audio files, it works fine with the ones that have speech but keeps yielding false positives when I feed it with other types of audio (like music or bird sound), even if I set aggressiveness at 3. Audios are 8000 sample/hz The only thing I changed to the source code was the way I pass the arguments to main function (excluding sys.args). def main(file, agresividad): audio, sample_rate = read_wave(file) vad = webrtcvad.Vad(int(agresividad)) frames = frame_generator(30, audio, sample_rate) frames = list(frames) segments = vad_collector(sample_rate, 30, 300, vad, frames) for i, segment in enumerate(segments): path = 'chunk-%002d.wav' % (i,) print(' Writing %s' % (path,)) write_wave(path, segment, sample_rate) if __name__ == '__main__': file = 'myfilename.wav' agresividad = 3 #aggressiveness main(file, agresividad)
answer count: 2
has comment: http://stackoverflow.com/comment/109154926

http://stackoverflow.com/comment/89641080
type: QuestionComment
has text: Did you not find PIL's function [`histogram`](http://effbot.org/imagingbook/image.htm), or did you but you decided it does not fit your purpose because it does not work for a *set* of images?
comment on: http://stackoverflow.com/q/51332753
score: 0
type: Comment

http://stackoverflow.com/a/51426930
answers question: http://stackoverflow.com/q/51426929
score: 1
upvote count: 1
has body: It's caused by the feature called command echoing which is enabled by default but it may be disabled using the echo command. From the documentation: Syntax echo [on | off] Parameters [on | off] Turns on or off the command echoing feature. Command echoing is on by default. If you add echo off at the first line of the script, it will disable the command echoing for all subsequent commands but it will echo the echo off command itself. To suppress even echoing of that command, simply prefix it with @. At sign (@) as a command prefix has the same effect as echo off but only for a single command. So to summarize it: Simply add @echo off at the first line of the shell script (or batch in Windows terminology) and that's it. Only the output of command(s) executed in the script will be sent to stdout.
downvote count: 0
type: Answer

http://stackoverflow.com/comment/89648856
score: 0
has text: @gokulgupta added a way to do it without numpy if you need
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51336835

http://stackoverflow.com/a/51370307
has body: You could use testdf.loc[::-1, 'A'].expanding(min_periods=1).apply(lambda x: (x &gt; 2).any())[::-1] which yields 0 1.0 1 1.0 2 1.0 3 1.0 4 0.0 5 0.0 6 0.0 7 0.0 8 0.0 9 0.0 Name: A, dtype: float64 This applies an expanding window to the Series in reversed order, then reverses that result, thus making the window contract. Unfortunately, I don't think there is a option built into expanding for doing this.
answers question: http://stackoverflow.com/q/51369840
accepted answer of: http://stackoverflow.com/q/51369840
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/q/51422519
answer count: 1
favorite count: 0
has body: this is my code. but I have the above Error. I searched before but didn't help me to find the answer. What is not correct in this code? import numpy as np import math def sigmoid(x): s = np.array(None) for i in x: np.append(s,(1/(math.exp(-x)+1))) return s x = np.array([1, 2, 3]) sigmoid(x) &lt;ipython-input-31-8e002c20e792&gt; in sigmoid(x) 17 s = np.array(None)` 18 for i in x: ---&gt; 19 np.append(s,(1/(math.exp(-x)+1))) 20 return s TypeError: only length-1 arrays can be converted to Python scalars
tagged with: python
accepted answer: http://stackoverflow.com/a/51422559
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89815882
downvote count: 1
type: Question
tagged with: numpy
upvote count: 0
tagged with: arrays
score: -1
has comment: http://stackoverflow.com/comment/89816124
has answer: http://stackoverflow.com/a/51422559
has title: TypeError: only length-1 arrays can be converted to Python scalars Python Array and Numpy

http://stackoverflow.com/comment/89716716
score: 0
has text: You need to run the command `ulimit -Sn <**limit size**>` to set it up to a value <= 65536 -- i.e.) `ulimit -Sn 65536` and then run `ulimit -a` to view the changes.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51365431

anaconda
tags question: http://stackoverflow.com/q/51433227
tags question: http://stackoverflow.com/q/51351785
tags question: http://stackoverflow.com/q/51463548
tags question: http://stackoverflow.com/q/51390692
tags question: http://stackoverflow.com/q/51460318
type: Tag
tags question: http://stackoverflow.com/q/51445930
tags question: http://stackoverflow.com/q/51455221
tags question: http://stackoverflow.com/q/51384570
tags question: http://stackoverflow.com/q/51363574
tags question: http://stackoverflow.com/q/51474515
tags question: http://stackoverflow.com/q/51435579
tags question: http://stackoverflow.com/q/51455517
tags question: http://stackoverflow.com/q/51443081
tags question: http://stackoverflow.com/q/51478535
tags question: http://stackoverflow.com/q/51480428
tags question: http://stackoverflow.com/q/51472625
tags question: http://stackoverflow.com/q/51415865
tags question: http://stackoverflow.com/q/51407031
tags question: http://stackoverflow.com/q/51387969
tags question: http://stackoverflow.com/q/51336251
tags question: http://stackoverflow.com/q/51466294
tags question: http://stackoverflow.com/q/51413888
tags question: http://stackoverflow.com/q/51423438
tags question: http://stackoverflow.com/q/51352372
tags question: http://stackoverflow.com/q/51445338
tags question: http://stackoverflow.com/q/51468958
tags question: http://stackoverflow.com/q/51439724
tags question: http://stackoverflow.com/q/51466804
tags question: http://stackoverflow.com/q/51455571
tags question: http://stackoverflow.com/q/51470103
tags question: http://stackoverflow.com/q/51452957
tags question: http://stackoverflow.com/q/51408813
tags question: http://stackoverflow.com/q/51409457
tags question: http://stackoverflow.com/q/51331219
tag name: anaconda
tags question: http://stackoverflow.com/q/51479468
tags question: http://stackoverflow.com/q/51463334
tags question: http://stackoverflow.com/q/51447235
tags question: http://stackoverflow.com/q/51388707
tags question: http://stackoverflow.com/q/51395744
tags question: http://stackoverflow.com/q/51406464
tags question: http://stackoverflow.com/q/51437654
tags question: http://stackoverflow.com/q/51465212
tags question: http://stackoverflow.com/q/51452376
tags question: http://stackoverflow.com/q/51461944
tags question: http://stackoverflow.com/q/51339986
tags question: http://stackoverflow.com/q/51435800
tags question: http://stackoverflow.com/q/51424629
tags question: http://stackoverflow.com/q/51388174
tags question: http://stackoverflow.com/q/51463223
tags question: http://stackoverflow.com/q/51408649
tags question: http://stackoverflow.com/q/51389852
tags question: http://stackoverflow.com/q/51349752
tags question: http://stackoverflow.com/q/51413242
tags question: http://stackoverflow.com/q/51387306
tags question: http://stackoverflow.com/q/51411231

http://stackoverflow.com/q/51417186
score: 2
type: AnsweredQuestion
downvote count: 0
has title: Google App Engine - Multiple yaml files in one project share a lib
has answer: http://stackoverflow.com/a/51417452
has answer: http://stackoverflow.com/a/51419953
accepted answer: http://stackoverflow.com/a/51419953
type: Question
has body: I want to create a multi-serivce app engine app, using the first diagram shown on this page. https://cloud.google.com/appengine/docs/standard/python/configuration-files#an_example I want to use third party libraries so I used have a lib folder under the root directory, one yaml under the root directory. Then I want one microservice called predict. So I created a folder called predict under the root directory as well, then under this folder, I want to write py files using the packages in the lib as well. What I'm doing is like this: import os,sys,inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) vendor.add(os.path.join(parentdir, 'lib')) Which didn't work for me as the error says: ValueError: virtualenv: cannot access /base/data/home/apps/f~project-name/lib: No such virtualenv or site directory Obviously it didn't work for me, what's the right way to do this? Update: Dan's solution worked for me! So when I'm deploying my microservice predict, I need to go inside predict directory and deploy it. I think that's why it can't find lib. By symlink the lib library using bash. ln -s ../lib/ ./lib I solved this problem.
upvote count: 2
tagged with: python-2.7
answer count: 2
linked to: http://stackoverflow.com/q/34110178
linked to: http://stackoverflow.com/q/34973058
possible better answer: http://stackoverflow.com/a/51417452
favorite count: 0
tagged with: google-app-engine
tagged with: python

http://stackoverflow.com/comment/89862453
comment on: http://stackoverflow.com/q/51445874
score: 0
type: Comment
type: QuestionComment
has text: What does Books.csv look like? can you provide a sample with a couple of lines?

http://stackoverflow.com/a/51463066
accepted answer of: http://stackoverflow.com/q/51463058
answers question: http://stackoverflow.com/q/51463058
upvote count: 2
score: 2
type: AcceptedAnswer
downvote count: 0
has body: You can do this in a list comprehension: header_row = [mystring.replace(" ", "_") for mystring in header_row]
has comment: http://stackoverflow.com/comment/89895210
type: Answer

http://stackoverflow.com/comment/89835755
type: AnswerComment
has text: Actually the TextStim can take whatever units you choose to specify (norm, height, deg, pix, cm, etc). The issue here is likely that (as you identify), the OP thinks they are dealing with pixels but the stimulus is using (or inheriting) normalised coordinates. The issue would disappear if the units are explicitly specified.
type: Comment
score: 2
comment on: http://stackoverflow.com/a/51422276

http://stackoverflow.com/comment/89655045
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51340697
has text: exacly 'gold coin' : 45
score: 0

http://stackoverflow.com/comment/89764670
comment on: http://stackoverflow.com/q/51396366
score: 0
has text: I think you can keep the question, can you tell where this is documented? My answer below is also not relevant as its tf api for 1.9 while you are looking for 1.8
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51405519
answers question: http://stackoverflow.com/q/51405230
score: 1
has body: You can get a set of row values with row-wise apply df.apply(lambda x: list(set(x.dropna())), axis=1) which outputs 0 [mango, apples] 1 [grapes, oranges] 2 [bananas, apples] dtype: object
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/90106116
score: 0
type: Comment
has text: @MSeifert Actually the real reason for not accepting it was that I stupidly asked this question (which is really important for my work project) just before leaving on vacation, so I haven't had the appropriate time to tend to it. I did quickly try your algorithm in Cython, and it reduced the running time of the total simulation by 25%, so I trust your solution is good. I would like to do proper benchmarks and update the question to better reflect what I should have asked (which is what you answered to), but I can't do that right now.
comment on: http://stackoverflow.com/a/51467813
type: AnswerComment

http://stackoverflow.com/a/51449183
has body: try this: def sure_ok(future): try: with open('out.txt', 'a') as f: f.write(str(future.result()[0]) + '\n') except: pass with concurrent.futures.ThreadPoolExecutor(max_workers=2500): for element in json.load(open('30_million_strings.json','r')): resolv = dns.resolver.Resolver() resolv.timeout = 1 future = executor.submit(resolv.query, target + '.com', 'MX') future.add_done_callback(sure_ok) remove global bucket as it is redundant, and not needed. remove reference of the 30+ million futures in a dictionary, also redundant. also you're probably not using a new enough version of concurrent.futures: https://github.com/python/cpython/commit/5cbca0235b8da07c9454bcaa94f12d59c2df0ad2
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51411806

http://stackoverflow.com/comment/90026939
has text: @Gextra11 What I'm saying is that object 21 will be not be the same object for different block sizes. It might be the same object but with pixels added or removed, or it might be a different object altogether, because even the number of objects could change. To check on your objects, use `plt.imshow(color.label2rgb(thresh))` for different thresholded images.
comment on: http://stackoverflow.com/a/51471489
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/51346750
has comment: http://stackoverflow.com/comment/89679141
tagged with: dataframe
score: -1
answer count: 2
upvote count: 1
tagged with: scikit-learn
possible better answer: http://stackoverflow.com/a/51358873
has comment: http://stackoverflow.com/comment/89679220
favorite count: 0
accepted answer: http://stackoverflow.com/a/51356427
tagged with: roc
tagged with: python
has answer: http://stackoverflow.com/a/51356427
has comment: http://stackoverflow.com/comment/89678412
has title: How to plot a ROC curve using dataframe converted from CSV file
has comment: http://stackoverflow.com/comment/89678475
downvote count: 2
has comment: http://stackoverflow.com/comment/89669037
tagged with: machine-learning
has answer: http://stackoverflow.com/a/51358873
type: Question
type: AnsweredQuestion
has body: I was trying to plot a ROC curve by using the documentation provided by sklearn. My data is in a CSV file, and it looks like this.It has two classes 'Good'and 'Bad' screenshot of my CSV file And my code looks like this import numpy as np import matplotlib.pyplot as plt from itertools import cycle import sys from sklearn import svm, datasets from sklearn.metrics import roc_curve, auc from sklearn.model_selection import train_test_split from sklearn.preprocessing import label_binarize from sklearn.multiclass import OneVsRestClassifier from scipy import interp from sklearn.neighbors import KNeighborsClassifier from sklearn.naive_bayes import MultinomialNB # Import some data to play with df = pd.read_csv("E:\\autodesk\\TTI ROC curve.csv") X =df'TTI','Max TemperatureF','Mean TemperatureF','Min TemperatureF',' Min Humidity'.values y = df['TTI_Category'].as_matrix() # Binarize the output y = label_binarize(y, classes=['Good','Bad']) n_classes = y.shape[1] # shuffle and split training and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.5, random_state=0) # Learn to predict each class against the other classifier = OneVsRestClassifier(svm.SVC(kernel='linear', probability=True, random_state=random_state)) y_score = classifier.fit(X_train, y_train).decision_function(X_test) # Compute ROC curve and ROC area for each class fpr = dict() tpr = dict() roc_auc = dict() for i in range(n_classes): fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i]) roc_auc[i] = auc(fpr[i], tpr[i]) # Compute micro-average ROC curve and ROC area fpr["micro"], tpr["micro"], _ = roc_curve(y_test.ravel(), y_score.ravel()) roc_auc["micro"] = auc(fpr["micro"], tpr["micro"]) plt.figure() lw = 2 plt.plot(fpr[2], tpr[2], color='darkorange', lw=lw, label='ROC curve (area = %0.2f)' % roc_auc[2]) plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.tit…

http://stackoverflow.com/comment/116848302
has text: just remove https:// from starts of your host
comment on: http://stackoverflow.com/q/51476065
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51366194
answers question: http://stackoverflow.com/q/51365270
type: Answer
has body: I use python main.py for python 2, and python3 main.py for python 3. You should see the environment variables in your PATH file to resolve any problems. Also, you can create a virtualenv with -p python3 parameters.
accepted answer of: http://stackoverflow.com/q/51365270
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/89656506
has text: @user1443098: Just edit the typo. No need to leave extraneous comments.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51329642

http://stackoverflow.com/q/51470049
linked to: http://stackoverflow.com/q/48350850
favorite count: 0
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/48350850
tagged with: python
tagged with: dataframe
downvote count: 1
type: Question
has title: Best way to manipulate array data in data frame?
has comment: http://stackoverflow.com/comment/89909620
has comment: http://stackoverflow.com/comment/89908621
has body: I have a data frame with positional data stored like this: r1_x r1_y r1_z r2_x r2_y r2_z 0 17.670965 19.857307 27.178185 17.555960 20.653801 27.641266 1 17.670965 19.857307 27.178185 16.950911 4.216056 12.901429 2 17.670965 19.857307 27.178185 11.737829 26.097181 3.230895 3 17.670965 19.857307 27.178185 16.254911 12.062716 12.170364 4 17.670965 19.857307 27.178185 16.504757 11.673612 12.406663 5 17.670965 19.857307 27.178185 16.717722 27.935490 28.795826 Here the x, y, and z denote the components of a 3d vector. What is the best way to go about performing vector operations on such a data frame element wise? For example, what if I wanted to calculate r2-r1 for each row, or take a dot product? I am using pandas to store this data.
score: -1
has comment: http://stackoverflow.com/comment/89909697
tagged with: pandas
upvote count: 0
has comment: http://stackoverflow.com/comment/89909721
answer count: 1
has answer: http://stackoverflow.com/a/51470170

http://stackoverflow.com/q/51348473
has comment: http://stackoverflow.com/comment/89670109
tagged with: python-3.x
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/89669963
has comment: http://stackoverflow.com/comment/89669943
tagged with: dockerpy
has comment: http://stackoverflow.com/comment/89670162
tagged with: docker-api
has comment: http://stackoverflow.com/comment/89670136
score: 0
has comment: http://stackoverflow.com/comment/89670186
has comment: http://stackoverflow.com/comment/89670063
type: UnansweredQuestion
tagged with: docker
has body: I'm working on a project with Python(3.6) in which I need to implement Docker Hub API to create a repository on user's docker hub account and push his docker image. Real Scenario: User will provide his source code along with Dockerfile, his username and apikey of docker cloud, then I have to create a repository on his account and build a Docker image of his source code and push to his docker hub account. Here's what I have tried: tempdir = tempfile.mkdtemp() saved_unmask = os.umask(0o077) temp_dir_path = os.path.join(tempdir) archive_path = os.path.join(settings.MEDIA_ROOT, 'archives/', deployment.sourceFile.name) print(archive_path) # Extract uploaded archive inside temporary dir patoolib.extract_archive(archive_path, outdir=temp_dir_path) # Try to retrieve path of dockerfile directory docker_glob = os.path.join(temp_dir_path, "*", "Dockerfile") print(docker_glob) docker_file = glob.glob(docker_glob)[0] docker_folder = os.path.dirname(docker_file) print(docker_folder) docker_client = docker.from_env() print("Start Building your docker image...") docker_client.login(username='USERNAME', password='PASSWORD') docker_client.images.build(path=docker_folder, gzip=False, tag=deployment.deploymentName) image = docker_client.images.get(deployment.deploymentName) shutil.rmtree(tempdir) img_id = image.short_id print(img_id) As you can see currently I'm pushing the image to my own default/repo but I want to create a repo on user's account and then push the image to his own account. AND also, can I use apikey instead of password in login() method? How can I achieve this thing? Help me, please! Thank You, Abdul
has title: DockerHub API Authentication using Python 3
answer count: 0
has comment: http://stackoverflow.com/comment/89669891

http://stackoverflow.com/comment/89667394
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51347341
has text: Possible duplicate of [PermissionError: \[WinError 5\] Access is denied python using moviepy to write gif](https://stackoverflow.com/questions/26091530/permissionerror-winerror-5-access-is-denied-python-using-moviepy-to-write-gif)

http://stackoverflow.com/comment/89821204
has text: Why not use `csv`? See [Python csv string to array](https://stackoverflow.com/questions/3305926/python-csv-string-to-array) for an example of usage.
type: Comment
type: QuestionComment
score: 6
comment on: http://stackoverflow.com/q/51425084

http://stackoverflow.com/q/51451747
has body: I'm a bit of a novice. So I'm trying to parse html pages and put the contents in a column in MySQL, however I can't seem to get the actual foreign characters to appear, such as instead of á I get xc3xa1. My table has utf8mb4 as its character set and collation utf8mb4_unicode_ci. I have the following set-up: Database_cnx = pymysql.connect(user='XXXX', password='XXXX', host='XXXX', database='XXXX', use_unicode=True, charset='utf8mb4') article_content = str(row[3].encode("utf-8")).replace("'", "\'").replace("\"", "\'") q_i = ("INSERT INTO article_items (" + ", ".join(article_table_col_name_new) + ")" "VALUES ({:d}, \"{:s}\", \"{:s}\", \"{:s}\", \"{:s}\", \"{:s}\", \"{:s}\")".format(row[0], urlparse(row[1]).netloc, row[1], row[2].replace("\"", "'"), article_content, datetime.fromtimestamp(row[4]).strftime("%Y-%m-%d"), updated) ) So how can I have it that only the actual article content appears in my column, instead of the b' byte and the utf-8 literals. thanks
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: mysql
upvote count: 1
has answer: http://stackoverflow.com/a/51451825
possible better answer: http://stackoverflow.com/a/51452191
type: Question
has answer: http://stackoverflow.com/a/51452191
tagged with: utf8mb4
tagged with: python-3.5
has title: How to avoid b' and UTF-8 literals in MySQL using Python 3
answer count: 2
accepted answer: http://stackoverflow.com/a/51451825
downvote count: 0
tagged with: utf-8
favorite count: 0

http://stackoverflow.com/comment/89767854
comment on: http://stackoverflow.com/a/51398438
type: Comment
has text: This solution applies the same search twice for every matching item in `mylist`, which seems wasteful.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/138872482
type: QuestionComment
comment on: http://stackoverflow.com/q/51404476
has text: For Windows: read this [thread](https://stackoverflow.com/q/1230669/6609485). For Linux (Posix): read this [thread](https://stackoverflow.com/q/4789837/6609485).
score: 0
type: Comment

http://stackoverflow.com/a/51413418
has comment: http://stackoverflow.com/comment/89798516
type: Answer
accepted answer of: http://stackoverflow.com/q/51413212
has comment: http://stackoverflow.com/comment/89798388
has comment: http://stackoverflow.com/comment/89798502
score: 2
has comment: http://stackoverflow.com/comment/89798589
answers question: http://stackoverflow.com/q/51413212
type: AcceptedAnswer
has body: You aren't using the values of bigDictA and bigDictB, so you don't need to use the dict.items() method. len() works on sets too, so no need to convert a set to a list in order to get its size. As soon as there's one match above the threshold and you add bigDictAkey to setOfMatches, there is no need to test the rest of the items in bigDictB and you should immediately break the inner loop to check the next item in bigDictA. The improved code as follows: setOfMatches = set() for bigDictAkey in bigDictA: for bigDictBkey in bigDictB: numberOfItemsInCommon = len(bigDictAkey &amp; bigDictBkey) valForComparison = THRESHOLD*len(bigDictAkey) if (numberOfItemsInCommon &gt;= valForComparison): setOfMatches.add(bigDictAkey) break
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/90107255
has text: did you fix your problem?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51466944

http://stackoverflow.com/comment/89684555
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51356176
type: Comment
has text: You can reset index without dropping. Also, once I reset the index, your code works fine for me, no errors. Check if there are any spaces in your column names.

http://stackoverflow.com/comment/89706154
type: QuestionComment
comment on: http://stackoverflow.com/q/51366354
score: 0
has text: you're my hero...it worked. why did it work?
type: Comment

http://stackoverflow.com/q/51470100
favorite count: 0
score: 0
has answer: http://stackoverflow.com/a/51470348
tagged with: python
has body: Here's my code, it seems kind of repetitive, but I couldn't figure out a way to make it differently. (It works okay btw, but it seems to me it's a bit "unclean") while True: try: num1 = int(input("Type in the first parameter: ")) num2 = int(input("Type in the second parameter: ")) num3 = int(input("Type in the third parameter: ")) break except ValueError: print("You have to type in a number. ") while True: if num1 &gt; num2 and num1 &gt; num3: c = num1 if c * c == num2 * num2 + num3 * num3: print("Your triangle is a pythagorean triangle") else: print("Your triangle isn't a pythagorean triangle") elif num2 &gt; num1 and num2 &gt; num3: # c - hypotenuse c = num2 if c * c == num1 * num1 + num3 * num3: print("Your triangle is a pythagorean triangle") else: print("Your triangle isn't a pythagorean triangle") elif num3 &gt; num1 and num3 &gt; num2: c = num3 if c * c == num2 * num2 + num1 * num1: print("Your triangle is a pythagorean triangle") else: print("Your triangle isn't a pythagorean triangle") elif num1 == num2 and num2 == num3 and num1 == num3: print("There's no such thing as a pythagorean triangle with all sides the same, try again") again = str(input("Do you want to continue? [Y/n]\n")) if again == "Y" or again == "y": pass else: break
has comment: http://stackoverflow.com/comment/89908541
tagged with: python-3.x
has title: Is there any alternative to repetitive if statements in python
upvote count: 1
possible better answer: http://stackoverflow.com/a/51470195
downvote count: 1
has answer: http://stackoverflow.com/a/51470195
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51470348
tagged with: if-statement
has comment: http://stackoverflow.com/comment/89908783
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/89908549

http://stackoverflow.com/comment/89776552
comment on: http://stackoverflow.com/q/51402904
score: 0
type: QuestionComment
has text: It is a proxy object that walks over the MRO and thus looks for the first implementation in the ancestors (according to the MRO).
type: Comment

http://stackoverflow.com/q/51433041
tagged with: attributeerror
has answer: http://stackoverflow.com/a/51433727
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/89837189
type: UnansweredQuestion
tagged with: pickle
tagged with: python
has answer: http://stackoverflow.com/a/51433349
has comment: http://stackoverflow.com/comment/89837199
has title: Attribute error after pickle
tagged with: machine-learning
has body: First I followed an iris tutorial and it worked great! the program ran fine and did everything it was supposed to do. Then I started working on a pickle tutorial to pickle data then open it again ... then everything went crazy. Now I have a pycache folder in my code folder that wasn't there and I am getting the following error: AttributeError: module 'numpy' has no attribute 'dtype' So far I have tried completely wiping scipy, numpy, sklearn, and pandas from my computer and reinstalling. Then I tried disabling rapport (I'm on an Ubuntu machine) because a part of the bug long error code kept talking about it. Below is the program I ran that I think caused this. Save Model Using Pickle import pandas from sklearn import model_selection from sklearn.linear_model import LogisticRegression import pickle url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv" names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'] dataframe = pandas.read_csv(url, names=names) array = dataframe.values X = array[:,0:8] Y = array[:,8] test_size = 0.33 seed = 7 X_train, X_test, Y_train, Y_test = model_selection.train_test_split(X, Y, test_size=test_size, random_state=seed) # Fit the model on 33% model = LogisticRegression() model.fit(X_train, Y_train) # save the model to disk filename = 'finalized_model.sav' pickle.dump(model, open(filename, 'wb'))
type: Question

http://stackoverflow.com/comment/89735615
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51380801
has text: Thanks a lot, it's what I was looking for!

http://stackoverflow.com/comment/89730051
comment on: http://stackoverflow.com/a/51379026
type: Comment
score: 1
type: AnswerComment
has text: You are a god. I hope I work hard enough to come to your level.

http://stackoverflow.com/comment/89846212
comment on: http://stackoverflow.com/q/51424177
score: 0
has text: You assign the same **global variable** - `d` - for all keys of `c`. So you have the same value for all keys. Also, by assigning `c[key]` in a loop, you rewrite previous value for the key.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51377170
has comment: http://stackoverflow.com/comment/89758183
has comment: http://stackoverflow.com/comment/89758491
upvote count: 1
score: 1
has body: So, you installed the graphviz library for python, but you haven't installed Graphviz software I guess. You can install it from here and make sure that the directory containing the dot executable is on your systems’ path. Good luck in ML journey! :-)
has comment: http://stackoverflow.com/comment/89775268
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51376756

http://stackoverflow.com/comment/89678592
comment on: http://stackoverflow.com/q/51352964
score: 1
has text: This seems like a totally unnecessary class.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51449325
downvote count: 0
has body: You can use groupby from itertools: from itertools import groupby Owners = ('Bob', 'Bob', 'Bob', 'Jeff', 'Jeff', 'Mary', 'Ana') Pets = ('Snake', 'Bird', 'Cat', 'Dog', 'Cat', 'Bird', 'Cat') print([tuple(v) for g, v in groupby(Pets, key=lambda v, c=iter(Owners): next(c))]) Output: [('Snake', 'Bird', 'Cat'), ('Dog', 'Cat'), ('Bird',), ('Cat',)] And if you want to add Owner to the result print({g: tuple(v) for g, v in groupby(Pets, key=lambda v, c=iter(Owners): next(c))}) Prints: {'Bob': ('Snake', 'Bird', 'Cat'), 'Jeff': ('Dog', 'Cat'), 'Mary': ('Bird',), 'Ana': ('Cat',)}
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51449283
type: Answer

http://stackoverflow.com/comment/89891781
type: Comment
has text: Such basics are easily found in [the official tutorial](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files). If you already tried that but it somehow failed, add that code to your question
type: QuestionComment
comment on: http://stackoverflow.com/q/51461263
score: 0

http://stackoverflow.com/a/51324619
has body: I believe you need pandas.join. res = df1.join(df2.set_index('DAY'), on='DAY') and rename the size column/ fill N/A as 0's.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51324463
score: 1
upvote count: 1

http://stackoverflow.com/comment/89728742
has text: That depends on which order you run the methods. You would have to run `test_auth()` before `test_profile()` in order for it to exist.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51378214

http://stackoverflow.com/comment/89782710
has text: From a glance at the documentation, this doesn't appear to be a usage that `sh` supports.
score: 1
comment on: http://stackoverflow.com/q/51405723
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51405790
tagged with: python
has comment: http://stackoverflow.com/comment/89786166
tagged with: pyfits
tagged with: fits
has comment: http://stackoverflow.com/comment/89786898
has title: Is something wrong with my fits file?
has answer: http://stackoverflow.com/a/51426333
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89828148
upvote count: 0
answer count: 1
tagged with: astropy
score: -1
has comment: http://stackoverflow.com/comment/89855592
has body: I am currently trying to display this fits image, but I keep running into different errors. At first it couldn't print the non-ASCII characters in the header so I went ahead and deleted them (they seemed like just blank spaces in the header, it started a ' but didn't it close it with another ' so I figured it was that and put another ' to close it (?), specifically in the "BUNIT" section and the "INSTRU" one). This is how I'm trying to show the image: from astropy.io import fits from astropy import wcs import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_axes(111, projection=wcs.WCS('uwc.fits')) ax.imshow(fits.getdata('uwc.fits')) This is how the header looked after I deleted the whole BUNIT and INSTRU thing: SIMPLE = T / FILE IN FITS FORMAT BITPIX = 16 / SIZE OF PIXELS NAXIS = 3 / NUMBER OF AXES NAXIS1 = 181 / NAXIS2 = 91 / NAXIS3 = 1 / BSCALE = .831495E-02 / REAL = TAPE*BSCALE+BZERO BZERO = .319702E+02 / ZERO CORRECTION BUNIT = ' ' / UNITS OF BRIGHTNESS DATAMAX = .302206E+03 / MAXIMUM DATA VALUE IN FILE DATAMIN = .319702E+02 / MINIMUM DATA VALUE IN FILE BLANK = -15751 / BLANK VALUE (C279 HEX) OBJECT = 'C Band (0.16-0.2' / IMAGE NAME DATE = '05/02/89' / DATE DATOBS = ' ' / DATE OBJECT OBSERVED INSTRU = ' ' / INSTRUMENT OBSERV = ' ' / NAME OF OBSERVER ORIGIN = 'PENN STATE' / TAPE ORIGIN CTYPE1 = 'GLON-AIT' / CRVAL1 = .000000 / CRPIX1 = 91.000010 / CDELT1 = -1.800000 / CROTA1 = .000000 / CTYPE2 = 'GLAT-AIT' / CRVAL2 = .000000 / CRPIX2 = 46.000000 / CDELT2 = 1.800000 / CROTA2 = .000000 / CTYPE3 = ' ' / CRVAL3 = .000000 / CRPIX3 = .000000 / CDELT3 = .000000 / CROTA3 = .000000 / END Then it had another error. Specifically it looked like this: SingularMatrixError: ERROR 3 in wcsset() at line 2218 of file cextern/wcslib/C/wcs.c: Linear transformation matrix is singular. ERROR 3 in linset() at line 638 of file cextern/wcslib/C/lin.c: PCi_ja matrix is singular. &lt;Figure size 432x288 with 0 Axes&gt; I don't know what this error means and I don't know how to fix …
has comment: http://stackoverflow.com/comment/89782655
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/comment/113146759
type: Comment
has text: There is a pretty big difference between 'import X' and 'from X import *': https://stackoverflow.com/questions/12270954/difference-between-import-x-and-from-x-import/12270980#12270980
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51367553

http://stackoverflow.com/q/51434481
tagged with: python
possible better answer: http://stackoverflow.com/a/51434551
tagged with: regex
has answer: http://stackoverflow.com/a/51434535
has answer: http://stackoverflow.com/a/51434551
type: AnsweredQuestion
downvote count: 0
score: 1
has body: I have a series of strings in the format of: 12345678ABC 12345678ABCDEF 12345A6789AB 12A3456ABC I would like to split only on the beginning of the trailing letters and output like so: 1 12345678 ABC 2 12345678 ABCDEF 3 12345A6789 AB 4 12A3456 ABC The preceeding 'number' string can contain some A-Z characters like 3&amp;4. 'number' and 'letter' are of variable length (letter being capped at maximum of 6). I tried to do df['ID'].str.split('[a-zA-Z]') with hopes to grab the last -1 split but the output contains no letters. Hoping to complete this in pandas if possible without resorting to re. Thanks
type: Question
answer count: 2
tagged with: pandas
upvote count: 1
has title: Pandas - Split by Numbers and Letters and save last split
accepted answer: http://stackoverflow.com/a/51434535
favorite count: 0

http://stackoverflow.com/comment/89639573
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51331991
type: Comment
has text: I'm wondering why is not working without `.reset_index()`.

http://stackoverflow.com/a/51378298
has comment: http://stackoverflow.com/comment/110517415
has comment: http://stackoverflow.com/comment/110517509
has comment: http://stackoverflow.com/comment/89733281
has comment: http://stackoverflow.com/comment/110517038
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89733975
type: Answer
has comment: http://stackoverflow.com/comment/110516218
has body: The solution in this case is to create a TaskManager class that is responsible for handling the sequentiality between the tasks. import sys from PyQt5 import QtCore, QtWidgets from functools import partial class TaskManager(QtCore.QObject): started = QtCore.pyqtSignal() finished = QtCore.pyqtSignal() progressChanged = QtCore.pyqtSignal(int, QtCore.QByteArray) def __init__(self, parent=None): QtCore.QObject.__init__(self, parent) self._process = QtCore.QProcess(self) self._process.finished.connect(self.handleFinished) self._progress = 0 def start_tasks(self, tasks): self._tasks = iter(tasks) self.fetchNext() self.started.emit() self._progress = 0 def fetchNext(self): try: task = next(self._tasks) except StopIteration: return False else: self._process.start(*task) return True def processCurrentTask(self): output = self._process.readAllStandardOutput() self._progress += 1 self.progressChanged.emit(self._progress, output) def handleFinished(self): self.processCurrentTask() if not self.fetchNext(): self.finished.emit() class gui(QtWidgets.QMainWindow): def __init__(self): super(gui, self).__init__() self.initUI() def dataReady(self, progress, result): self.output.append(str(result, "utf-8")) self.progressBar.setValue(progress) def callProgram(self): tasks = [("ping", ["8.8.8.8"]), ("ping", ["8.8.8.8"]), ("ping", ["8.8.8.8"])] self.progressBar.setMaximum(len(tasks)) self.manager.start_tasks(tasks) def initUI(self): layout = QtWidgets.QVBoxLayout() self.runButton = QtWidgets.QPushButton('Run') self.runButton.clicked.connect(self.callProgram) self.output = QtWidgets.QTextEdit() self.progressBar = QtWidgets.QProgressBar() layout.addWidget(self.output) layout.addWidget(self.runButton) layout.addWidget(self.progressBar) centralWidget = QtWidgets.QWidget() centralWidget.setLayout(layout) self.setCentralWidget(centralWidget) self.manager = TaskManager(self) self.manager.progressChanged.connect(self.dataReady) self.manager.started.connect(partial(self.runButton.setEnabled, False)…
has comment: http://stackoverflow.com/comment/89734078
has comment: http://stackoverflow.com/comment/89734314
has comment: http://stackoverflow.com/comment/110518995
has comment: http://stackoverflow.com/comment/89733877
upvote count: 7
accepted answer of: http://stackoverflow.com/q/51364552
answers question: http://stackoverflow.com/q/51364552
has comment: http://stackoverflow.com/comment/89734748
has comment: http://stackoverflow.com/comment/89732745
score: 7
has comment: http://stackoverflow.com/comment/89744128
has comment: http://stackoverflow.com/comment/89734547

http://stackoverflow.com/comment/89817753
score: 1
has text: It's like `d[key]`, except instead of raising a `KeyError` it can return a default value. So `{}.get(key, 0)` will always be `0`, and `d.get(key, key)` will return `key` if there is no value for `key` in `d`
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51423308

http://stackoverflow.com/comment/89752271
type: Comment
comment on: http://stackoverflow.com/q/51390037
type: QuestionComment
has text: `df.max().max() ` ?
score: 0

visual-studio-code
tags question: http://stackoverflow.com/q/51368960
tags question: http://stackoverflow.com/q/51413242
tags question: http://stackoverflow.com/q/51351728
tags question: http://stackoverflow.com/q/51350907
tag name: visual-studio-code
type: Tag
tags question: http://stackoverflow.com/q/51368286
tags question: http://stackoverflow.com/q/51447348
tags question: http://stackoverflow.com/q/51422391

http://stackoverflow.com/q/51338159
tagged with: python
downvote count: 0
score: 1
type: Question
has title: google-drive-sdk export Daily Limit unauthenticated use
has body: I am trying to download/export a file according to the v3 example published by google. I am getting the "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup." error. I have searched here and elsewhere and all of the links suggest I am missing setting up the credentials. However, I am building on top of the basic quickstart example and am able to list out the contents of my drive folder in this same application. And yes, I have changed the requested scope from drive.metadata.readonly to drive.readonly to support downloading. What am I missing? from __future__ import print_function from apiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools import io from googleapiclient.http import MediaIoBaseDownload # Setup the Drive v3 API SCOPES = 'https://www.googleapis.com/auth/drive.readonly' store = file.Storage('credentials.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store) drive_service = build('drive', 'v3', http=creds.authorize(Http())) # Call the Drive v3 API to list first 10 items (this works) # example from google. results = drive_service.files().list( pageSize=10, fields="nextPageToken, files(id, name)").execute() items = results.get('files', []) if not items: print('No files found.') else: print('Files:') for item in items: print('{0} ({1})'.format(item['name'], item['id'])) # Try to download the first item (it's a google doc I can edit, this FAILS) # code pretty much lifted from google file_id = items[0]['id'] print (file_id) request = drive_service.files().export_media(fileId=file_id, mimeType='application/pdf') fh = io.BytesIO() downloader = MediaIoBaseDownload(fh, request) done = False while done is False: status, done = downloader.next_chunk() print ( "Download %d%%." % int(status.progress() * 100) )
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/51349463
favorite count: 0
tagged with: google-drive-api
type: UnansweredQuestion

http://stackoverflow.com/a/51395596
has comment: http://stackoverflow.com/comment/89763377
has comment: http://stackoverflow.com/comment/89762719
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89763337
has comment: http://stackoverflow.com/comment/89766614
has comment: http://stackoverflow.com/comment/89762442
has comment: http://stackoverflow.com/comment/89762513
has comment: http://stackoverflow.com/comment/89763174
has comment: http://stackoverflow.com/comment/89762806
type: Answer
accepted answer of: http://stackoverflow.com/q/51395527
has comment: http://stackoverflow.com/comment/89763128
answers question: http://stackoverflow.com/q/51395527
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89763213
has body: Use replace by substrings and then pandas.eval: df['col2'] = pd.eval(df['col1'].replace(['&gt;','&lt;'], ['35+','0+'], regex=True)) / 2 print (df) col1 col2 0 &gt;20 27.5 1 &lt;5 2.5 2 &lt;1 0.5 3 &gt;10 22.5 EDIT: df['col2'] = pd.eval(df['col1'].replace(['&gt;','&lt;','-'], ['35+','0+','+'], regex=True)) / 2 print (df) col1 col2 0 &gt;20 27.5 1 &lt;5 2.5 2 &lt;1 0.5 3 &gt;10 22.5 4 100-200 150 5 10-20 15 EDIT: Probl solution above is it working only to 100rows (see bug), so need alternative solution: df = pd.read_csv('train_jqd04QH(1).csv', usecols=['experience', 'company_size']) s1 = df['experience'].replace(['&gt;','&lt;', '-'], ['35+','0+', '+'], regex=True) #added anothr repalce string, `\+$` is match last + like 1000+ s2 = df['company_size'].replace(['&gt;','&lt;', '-', '/', '\+$'], ['35+','0+', '+', '+', '+35'], regex=True) df['experience'] = s1.str.split('+', expand=True).astype(float).mean(axis=1) df['company_size'] = s2.str.split('+', expand=True).astype(float).mean(axis=1) print (df.head()) experience company_size 0 3.0 300.0 1 14.0 5.0 2 6.0 74.5 3 14.0 74.5 4 8.0 NaN
has comment: http://stackoverflow.com/comment/89763514
upvote count: 2

http://stackoverflow.com/a/51548381
answers question: http://stackoverflow.com/q/51426379
type: Answer
has body: Turns out that running this process within one python file in a threaded way is very complicated. The solution is to run them in concurrently with bash and then make the power script check if the other process is running. Sample code bellow: def measurePower(): tmp = os.popen("ps -Af").read() process_name = "PROCESSTOBEMEASURED.PY" power_measurement = [] '''One checks if the other process is still running, if yes it measures power again.''' while(process_name in tmp[:]): measurementPower = os.popen("nvidia-smi -i 0 -q").read() tmp = os.popen("ps -Af").read() power_measurement.append(nvidiaSmiParser(measurementPower, ["Power Draw"],num)) return power_measurement
score: 0

http://stackoverflow.com/a/51449250
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: What's the purpose of this line? spher_results = np.array(spherical_results) It makes an array from a list. But you don't use spher_results in the following code.
type: Answer
accepted answer of: http://stackoverflow.com/q/51448700
answers question: http://stackoverflow.com/q/51448700
score: 1
has comment: http://stackoverflow.com/comment/89870430

http://stackoverflow.com/q/51331775
favorite count: 0
has comment: http://stackoverflow.com/comment/89639357
upvote count: 5
duplicate of: http://stackoverflow.com/q/17709270
tagged with: python
has answer: http://stackoverflow.com/a/51331979
has body: I have a dataframe with a date column and I would like to create a new column that tells me how many identical dates the dataset contains. This is a min example of the original data set: df1: date 2017/01/03 2017/01/03 2017/01/04 2017/01/04 2017/01/04 2017/01/05 I would like to create this date_count, so the target data set is: df1: date date_count 2017/01/03 2 2017/01/03 2 2017/01/04 3 2017/01/04 3 2017/01/04 3 2017/01/05 1 The actual code to create df1: dict1 = [{'date': '2017/01/03', 'date_count': 2},{'date': '2017/01/03', 'date_count': 2}, {'date': '2017/01/04', 'date_count': 3},{'date': '2017/01/04', 'date_count': 3}, {'date': '2017/01/04', 'date_count': 3},{'date': '2017/01/05', 'date_count': 1}] df = pd.DataFrame(dict1, index=['s1', 's2','s3','s1','s2','s3'])
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89639177
has answer: http://stackoverflow.com/a/51331991
type: Question
has comment: http://stackoverflow.com/comment/89639376
has title: Count identical dates in pandas dataframe
linked to: http://stackoverflow.com/q/17709270
has comment: http://stackoverflow.com/comment/89639445
tagged with: date
score: 4
has comment: http://stackoverflow.com/comment/89639362
has comment: http://stackoverflow.com/comment/89639369
answer count: 2
tagged with: pandas
downvote count: 1
has comment: http://stackoverflow.com/comment/89639504
has comment: http://stackoverflow.com/comment/89639294

http://stackoverflow.com/a/56883881
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/51440475
downvote count: 0
score: 4
has body: Here is what i did to get tensorflow working with windows. Download python 3.7.0 (64 bit from Python Releases for Windows) Install it and check python version by running below command in cmd: python --version Python 3.7.0 Then run below command to upgrade pip to latest python -m pip install --upgrade pip Now install tensorflow using pip pip install tensorflow That's it you have installed tensorflow on windows. Below image shows what happens when you type above commands link for tensorflow for python 3x https://pypi.org/project/tensorflow/#files tensorflow-1.14.0-cp37-cp37m-win_amd64.whl (68.3 MB)

http://stackoverflow.com/a/51356013
has comment: http://stackoverflow.com/comment/89686797
type: Answer
answers question: http://stackoverflow.com/q/51355425
has body: It seems like you are reading a CSV file. It will be a lot easier to use pandas library to process the file. import pandas as pd # read the CSV file with space as delimiter df = pd.read_csv('the.txt', delimiter=' ', header = None) df.head() # there are two spaces, so a the number of columns is twice # remove the columns with NaN values df = df.dropna(axis=1, how='all') df.head() # subtract the column one by 10 df[0] = df[0].apply(lambda x: x - 10) df.head() # subtract the rest of the columns by 1 df[[2,4,6,8]] = df[[2,4,6,8]].apply(lambda x: x -1) df.head() # convert the dataframe to tuples records = [tuple(x) for x in df.to_records(index=False)] # Write the records to the the file with open('a.txt','w') as outfile: for record in records: outfile.write('Values{};\n'.format(record))
score: 0
has comment: http://stackoverflow.com/comment/89686516
has comment: http://stackoverflow.com/comment/89686050

http://stackoverflow.com/q/51463166
tagged with: read-the-docs
tagged with: sidebar
answer count: 2
downvote count: 0
has title: Toctree Activates Current Page and Main Page on Sidebar
has answer: http://stackoverflow.com/a/51465022
favorite count: 0
has body: There is no problem on de index.rst it seems as below: However, when I go to another page, in my case it is annotation-module.rst, the sidebar selects and shows both index and annotation-module, as seen below: However, I want to have only Annotation Module page to be activated and show its subsections. My conf.py only uses html_theme by looking for the READTHEDOCS environment variable as below: if not on_rtd: # only import and set the theme if we're building docs locally try: import sphinx_rtd_theme html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] except Exception: pass My index.rst: Welcome to exceptive's documentation! ===================================== .. toctree:: :maxdepth: 2 :caption: Contents: index annotation-module Here I have some introductory text. And annotation-module.rst doesn't even include any toctree,I only have sections under it. So, how do I only activate current documents sections on sidebar? Here is the source directory of docs as requested by Steve Piercy. Environment Python 3.5 Sphinx 1.7.6 sphinx-rtd-theme 0.4.0
tagged with: python
has answer: http://stackoverflow.com/a/67976544
score: 2
has comment: http://stackoverflow.com/comment/89896078
upvote count: 2
tagged with: python-sphinx
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89896265
type: Question
tagged with: toctree

http://stackoverflow.com/comment/89783005
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51405580
score: 0
has text: You may need to run `pip install` as root/super_user or install in a virtual environment

http://stackoverflow.com/q/51460601
has title: Class not creating new instance variables
tagged with: python
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/1132941
type: Question
linked to: http://stackoverflow.com/q/1132941
answer count: 1
tagged with: static-methods
score: 0
tagged with: initialization
has body: I have the following Python (3.6.0) class: class SampleClass(object): @staticmethod def create(*data): sample_instance = SampleClass() sample_instance.add_data(*data) return sample_instance def __init__(self, data_map={}): super(SampleClass, self).__init__() self.data_map = data_map def add_data(self, *data): for key, value in data: self.data_map.setdefault(key, []).append(value) Where the static method create is a convenience method for initializing a new instance. However, when invoking create multiple times, the data_map property is not recreated. For example: sample_instance1 = SampleClass.create(('a', 1), ('b', 2), ('c', 3)) sample_instance2 = SampleClass.create() sample_instance1.data_map == sample_instance2.data_map # True sample_instance1.data_map is sample_instance2.data_map # True If I change the __init__ method to this, the issue goes away: def __init__(self): super(SampleClass, self).__init__() self.data_map = {} Could someone help me understand what's going on here?
has answer: http://stackoverflow.com/a/51460619
accepted answer: http://stackoverflow.com/a/51460619
tagged with: python-3.x

http://stackoverflow.com/comment/89789198
comment on: http://stackoverflow.com/q/51408828
score: 0
has text: is the terminal using python 3.7 also ? `$>python -V`
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51440876
answers question: http://stackoverflow.com/q/51440815
has comment: http://stackoverflow.com/comment/89852858
has body: for longitude in range(cls.MIN_LONGITUDE_DEGREES, cls.MAX_LONGITUDE_DEGREES, WIDTH_DEGREES) should be for longitude in range(cls.MIN_LONGITUDE_DEGREES, cls.MAX_LONGITUDE_DEGREES, cls.WIDTH_DEGREES) Next time, post your full error traceback
downvote count: 0
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/89731867
score: 2
has text: What do you mean by "websocket client using twisted"? Twisted is a server framework. For a websocket client in Python just google it.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51380145

http://stackoverflow.com/a/51436216
has comment: http://stackoverflow.com/comment/89842898
accepted answer of: http://stackoverflow.com/q/51435019
has comment: http://stackoverflow.com/comment/89894170
has comment: http://stackoverflow.com/comment/89842694
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51435019
has body: Remove reset_index(drop=True) from your code and sort later may work for you. import pandas as pd d = ({ 'time' : ['08:00:00 am','12:00:00 pm','16:00:00 pm','20:00:00 pm','2:00:00 am','13:00:00 pm','3:00:00 am'], 'code' : ['A','B','C','A','B','C','A'], }) df = pd.DataFrame(data=d) df['time'] = pd.to_timedelta(df['time']) cutoff, day = pd.to_timedelta(['3.5H', '24H']) x = df.time.apply(lambda x: x if x &gt; cutoff else x + day).dt.components df['time'] = x.apply(lambda x: '{:02d}:{:02d}:{:02d}'.format(x.days*24+x.hours, x.minutes, x.seconds), axis=1) df = df.sort_values('time') print(df) Pandas do alignment via index. reset_index(drop=True) destructed the original index and caused the sorted time column assigned back sequentially. This is probably why you didn't get what you what. original time column. 0 08:00:00 1 12:00:00 2 16:00:00 3 20:00:00 4 02:00:00 5 13:00:00 6 03:00:00 after sort_values(). 4 02:00:00 6 03:00:00 0 08:00:00 1 12:00:00 5 13:00:00 2 16:00:00 3 20:00:00 after reset_index(drop=True) 0 02:00:00 1 03:00:00 2 08:00:00 3 12:00:00 4 13:00:00 5 16:00:00 6 20:00:00
score: 0
type: Answer

http://stackoverflow.com/q/51378961
tagged with: list
score: -1
has comment: http://stackoverflow.com/comment/89729508
has answer: http://stackoverflow.com/a/51379115
type: Question
has comment: http://stackoverflow.com/comment/89729423
has comment: http://stackoverflow.com/comment/89729520
answer count: 3
has body: I have two python list having equal no of elements. i need to subtract only the int and float element of two list ignoring string elements. list_1 = [1, 2, 3.0, 'test', 6.5] list_2 = [2, 3, 10.0, 'test', 12.5] now third list should be the final diff of the elements of two lists list_3 = [1, 1, 7.0, 'test', 6.0] i am all-right in keeping the string value in list_3 of either of the list.
favorite count: 0
has answer: http://stackoverflow.com/a/51379615
has comment: http://stackoverflow.com/comment/89729483
has title: subtract elements of two python list of different data types
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/51379059
upvote count: 1

http://stackoverflow.com/a/51328006
upvote count: 1
has body: You can use a binary tree whose insertion process attempts to find nodes that precede the value: class Tree: def __init__(self, val=None): self.left, self.value, self.right = None, val, None def insert_val(self, _val): if self.value is None or _val.startswith(self.value): self.value = _val else: if _val &lt; self.value: getattr(self.left, 'insert_val', lambda x:setattr(self, 'left', Tree(x)))(_val) else: getattr(self.right, 'insert_val', lambda x:setattr(self, 'right', Tree(x)))(_val) def flatten(self): return [*getattr(self.left, 'flatten', lambda :[])(), self.value, *getattr(self.right, 'flatten', lambda :[])()] t = Tree() for i in open('filename.txt'): t.insert_val(i.strip('\n')) print(t.flatten()) Output: ['ABCDEFGHIJKLMNO', 'CEST', 'DBTSFDEO', 'EAEUDNBNUW', 'EOEUDNBNUW', 'FGH']
answers question: http://stackoverflow.com/q/51327765
downvote count: 2
type: Answer
score: -1

http://stackoverflow.com/q/51333212
type: Question
has title: Gnuwin32: makefile on windows "The syntax of the command is incorrect."
accepted answer: http://stackoverflow.com/a/51333249
answer count: 1
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/45889953
has body: I'm trying to call make to compile my code but I keep getting this error: C:\Users\lovel\Anaconda3\S4&gt;make mkdir -p build mkdir -p build / S4k The syntax of the command is incorrect. make: *** [objdir] Error 1 Here's part of my makefile code in python: objdir: mkdir -p $(OBJDIR) mkdir -p $(OBJDIR) / S4k mkdir -p $(OBJDIR) / modules S4_LIBOBJS = \ $(OBJDIR)/S4k/S4.o \ $(OBJDIR)/S4k/rcwa.o \ $(OBJDIR)/S4k/fmm_common.o \ $(OBJDIR)/S4k/fmm_FFT.o \ $(OBJDIR)/S4k/fmm_kottke.o \ $(OBJDIR)/S4k/fmm_closed.o \ $(OBJDIR)/S4k/fmm_PolBasisNV.o \ $(OBJDIR)/S4k/fmm_PolBasisVL.o \ $(OBJDIR)/S4k/fmm_PolBasisJones.o \ $(OBJDIR)/S4k/fmm_experimental.o \ $(OBJDIR)/S4k/fft_iface.o \ $(OBJDIR)/S4k/pattern.o \ $(OBJDIR)/S4k/intersection.o \ $(OBJDIR)/S4k/predicates.o \ $(OBJDIR)/S4k/numalloc.o \ $(OBJDIR)/S4k/gsel.o \ $(OBJDIR)/S4k/sort.o \ $(OBJDIR)/S4k/kiss_fft.o \ $(OBJDIR)/S4k/kiss_fftnd.o \ $(OBJDIR)/S4k/SpectrumSampler.o \ $(OBJDIR)/S4k/cubature.o \ $(OBJDIR)/S4k/Interpolator.o \ $(OBJDIR)/S4k/convert.o` I'm working on Windows. I changed the '/' to '\' and it didn't work, I also added '\' in the end did not work either.
tagged with: python-2.x
has comment: http://stackoverflow.com/comment/89641857
tagged with: makefile
upvote count: 1
tagged with: python
tagged with: gnuwin32
has answer: http://stackoverflow.com/a/51333249
tagged with: build
type: AnsweredQuestion
score: 1

http://stackoverflow.com/q/51415879
has comment: http://stackoverflow.com/comment/89805369
tagged with: python
tagged with: blueprint
answer count: 0
has comment: http://stackoverflow.com/comment/89804389
type: Question
has comment: http://stackoverflow.com/comment/89805824
has title: Python: pipe request to blueprint endpoint through another endpoint
tagged with: flask
score: 0
has body: I have a Flask application that inherits a library with some blueprints already defined (that I can't change). Now I need to be able to filter out some of the requests that goes to one of the pre-defined endpoints. The endpoint /updateuser is defined in the blueprint, but now I need to stop certain requests from getting to that endpoint, and instead return a message in my application. I've figured out how to overwrite an endpoint in a blueprint, but that's not what I want. I'd like to add this /updateuser endpoint in my flask application, and either return a message OR send them to the original endpoint that's defined in the library, without the user being exposed to this extra layer. Is there any good way to achieve this?
type: UnansweredQuestion

http://stackoverflow.com/comment/89646519
has text: Thanks @JoshAdel, But your 2nd poin gives this error - print "calci : ", time.time() - start ^ SyntaxError: invalid syntax
comment on: http://stackoverflow.com/a/51325845
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51424054
answer count: 3
has comment: http://stackoverflow.com/comment/89819300
accepted answer: http://stackoverflow.com/a/51424370
downvote count: 0
has comment: http://stackoverflow.com/comment/89819478
favorite count: 0
possible better answer: http://stackoverflow.com/a/51424388
has answer: http://stackoverflow.com/a/51424388
tagged with: python
has comment: http://stackoverflow.com/comment/89890784
score: 4
type: AnsweredQuestion
type: Question
has title: In Python how to pass a common object to different module files
has answer: http://stackoverflow.com/a/51424370
has body: I have various module files and want to share a common object (in this case a logger) to each of them. What is the best way to do this? I have a solution but it does not feel just right. In pseudo code: module_1.py global logger # module_1 def pass_logger_module1(plogger): global logger logger = plogger module_2.py global logger # module_2 def pass_logger_module2(plogger): global logger logger = plogger main_module.py from module_1 import pass_logger_module1 from module_2 import pass_logger_module2 logger = set_logger(logfile, logformat, 'DEBUG') pass_logger_module1(logger) pass_logger_module2(logger)
upvote count: 4
has answer: http://stackoverflow.com/a/51424443

http://stackoverflow.com/comment/97990561
type: Comment
has text: "By the way you should ask these type of question first to google :P" This is now the first hit on Google.
comment on: http://stackoverflow.com/a/51335689
score: 3
type: AnswerComment

http://stackoverflow.com/comment/89728316
type: QuestionComment
has text: Is the directory that the file `chatbot_run` is located in, on your python path?
comment on: http://stackoverflow.com/q/51378194
score: 0
type: Comment

google-app-engine
tags question: http://stackoverflow.com/q/51456299
tag name: google-app-engine
type: Tag
tags question: http://stackoverflow.com/q/51342244
tags question: http://stackoverflow.com/q/51480380
tags question: http://stackoverflow.com/q/51350506
tags question: http://stackoverflow.com/q/51443767
tags question: http://stackoverflow.com/q/51480055
tags question: http://stackoverflow.com/q/51457401
tags question: http://stackoverflow.com/q/51417186
tags question: http://stackoverflow.com/q/51386090

import
type: Tag
tags question: http://stackoverflow.com/q/51403126
tag name: import
tags question: http://stackoverflow.com/q/51432562
tags question: http://stackoverflow.com/q/51480869
tags question: http://stackoverflow.com/q/51391328
tags question: http://stackoverflow.com/q/51351970
tags question: http://stackoverflow.com/q/51434866
tags question: http://stackoverflow.com/q/51336897
tags question: http://stackoverflow.com/q/51334847
tags question: http://stackoverflow.com/q/51468533
tags question: http://stackoverflow.com/q/51472607

http://stackoverflow.com/comment/89712693
score: 0
type: Comment
has text: Possible duplicate of [Iterating over dictionaries using 'for' loops](https://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops)
type: QuestionComment
comment on: http://stackoverflow.com/q/51368349

http://stackoverflow.com/comment/89786703
type: QuestionComment
has text: @Kenny You did a good job explaining this time. +1
comment on: http://stackoverflow.com/q/51406699
score: 1
type: Comment

for-loop
tags question: http://stackoverflow.com/q/51471063
tags question: http://stackoverflow.com/q/51473799
tags question: http://stackoverflow.com/q/51411040
tags question: http://stackoverflow.com/q/51408498
tags question: http://stackoverflow.com/q/51369080
tags question: http://stackoverflow.com/q/51368443
tags question: http://stackoverflow.com/q/51404215
tags question: http://stackoverflow.com/q/51380372
tags question: http://stackoverflow.com/q/51466966
tags question: http://stackoverflow.com/q/51430132
tags question: http://stackoverflow.com/q/51455875
tags question: http://stackoverflow.com/q/51419701
tags question: http://stackoverflow.com/q/51387783
tags question: http://stackoverflow.com/q/51343451
tags question: http://stackoverflow.com/q/51372910
tags question: http://stackoverflow.com/q/51472720
tags question: http://stackoverflow.com/q/51354223
tags question: http://stackoverflow.com/q/51461110
tag name: for-loop
tags question: http://stackoverflow.com/q/51369473
tags question: http://stackoverflow.com/q/51408638
tags question: http://stackoverflow.com/q/51344283
tags question: http://stackoverflow.com/q/51470248
tags question: http://stackoverflow.com/q/51344106
tags question: http://stackoverflow.com/q/51353831
tags question: http://stackoverflow.com/q/51451709
tags question: http://stackoverflow.com/q/51351309
tags question: http://stackoverflow.com/q/51342472
tags question: http://stackoverflow.com/q/51405490
tags question: http://stackoverflow.com/q/51356368
tags question: http://stackoverflow.com/q/51448811
tags question: http://stackoverflow.com/q/51449292
tags question: http://stackoverflow.com/q/51325657
tags question: http://stackoverflow.com/q/51437226
type: Tag
tags question: http://stackoverflow.com/q/51445252
tags question: http://stackoverflow.com/q/51404807
tags question: http://stackoverflow.com/q/51432604
tags question: http://stackoverflow.com/q/51388808
tags question: http://stackoverflow.com/q/51350115
tags question: http://stackoverflow.com/q/51477283
tags question: http://stackoverflow.com/q/51399865
tags question: http://stackoverflow.com/q/51423460
tags question: http://stackoverflow.com/q/51460895
tags question: http://stackoverflow.com/q/51459559

http://stackoverflow.com/q/51388018
has answer: http://stackoverflow.com/a/51392260
type: UnansweredQuestion
has body: I am trying to scrape all the hospital data from this website. https://www.german-hospital-directory.com/search/Bundesland/Baden-Wuerttemberg.html. After looking at the requests,it makes a form request. And it is not accessible through scrapy shell And in the response payload,it gives the entire html content. How do I extract each of the hospital data such as URL,NAME, IMAGE and traverse through all the hospitals. Any help would be appreciated as I am new to scrapy. Do I need to use selenium or can I somehow achieve this using scrapy.
tagged with: python
score: 1
tagged with: scrapy
type: Question
has title: Scraping data from Ajax Form Requests using Scrapy
tagged with: web-crawler
upvote count: 1
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/51388818
has comment: http://stackoverflow.com/comment/89749748
has title: Setdiff R command equivalent in Python
tagged with: python
has comment: http://stackoverflow.com/comment/89749797
score: 2
answer count: 0
has comment: http://stackoverflow.com/comment/89749590
type: Question
has comment: http://stackoverflow.com/comment/89749735
downvote count: 0
has comment: http://stackoverflow.com/comment/89749641
has body: is there an equivalent of the setdiff() R function in the python library pandas ? I need to replicate a function like setdiff(x, y) that one can find in R!
tagged with: http://stackoverflow.com/tag/r
linked to: http://stackoverflow.com/q/3462143
duplicate of: http://stackoverflow.com/q/3462143
favorite count: 0
has comment: http://stackoverflow.com/comment/89749841
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/89665015
type: Comment
type: QuestionComment
score: 0
has text: PermissionError: [Errno 13] Permission denied: 'GameExcel.xlsx'. wonder if there is a work around, should this be a private chat? an idea is to have two identical spreadsheets where one updates and opens and the other one closes and updates
comment on: http://stackoverflow.com/q/51345910

http://stackoverflow.com/comment/89790841
type: QuestionComment
has text: It would even be easier to get the symbols with `from sympy.abc import x,y,z,a,b,c,d,e,f,g,h` …
score: 1
comment on: http://stackoverflow.com/q/51407938
type: Comment

http://stackoverflow.com/a/51369154
score: 1
upvote count: 1
type: Answer
has body: Normally, you want to change the child process to work like a typical Unix userland tool: the logging and other side-band information goes to stderr (or to a file, or syslog, etc.), and only the actual output goes to stdout. Then, the problem is easy: just capture stdout to a PIPE that you process, and either capture stderr to a different PIPE, or pass it through to real stderr. If that's not appropriate for some reason, you need to come up with some other mechanism for IPC: Unix or Windows named pipes, anonymous pipes that you pass by leaking the file descriptor across the fork/exec and then pass the fd as an argument, Unix-domain sockets, TCP or UDP localhost sockets, a higher-level protocol like a web service on top of TCP sockets, mmapped files, anonymous mmaps or pipes that you pass between processes via a Unix-domain socket or Windows API calls, … As you can see, there are a huge number of options. Without knowing anything about your problem other than that you want "custom messages", it's impossible to tell you which one you want. While we're at it: If you can rewrite your code around multiprocessing rather than subprocess, there are nice high-level abstractions built in to that module. For example, you can use a Queue that automatically manages synchronization and blocking, and also manages pickling/unpickling so you can just pass any (picklable) object rather than having to worry about serializing to text and parsing the text. Or you can create shared memory holding arrays of int32 objects, or NumPy arrays, or arbitrary structures that you define with ctypes. And so on. Of course you could build the same abstractions yourself, without needing to use multiprocessing, but it's a lot easier when they're there out of the box. Finally, while your question is tagged ipc and pipe, and titled "Interprocess Communication", your description refers to threads, not processes. If you actually are using a bunch of threads in a single process, you don't need any of this. …
answers question: http://stackoverflow.com/q/51369002
downvote count: 0

wsgi
type: Tag
tags question: http://stackoverflow.com/q/51400638
tag name: wsgi

http://stackoverflow.com/a/51375741
type: Answer
score: 2
upvote count: 2
has body: So as far as I understood you have a sequence of max 50 events, which you want to make predictions for. These events have text data attached, which can be treated as another sequence of word embeddings. Here is an article about a similar architecture. I would propose a solution which involves LSTMs for the text part an 1D-convolution for the "real" sequence part. Every LSTM layer is concatenated with the numerical data. This involves 50 LSTM layers, which can be time consuming to train, even if you use shared weights. It would be also possible to use only convolution layers for the text part, which is faster, but does not model long term dependencies. (I have the experience, that these long term dependencies are often not that important in text mining). Text -> LSTM or 1DConv -> concat with numerical data -> 1DConv -> Output Here is some exmaple code, which shows how to do use shard weights numeric_input = Input(shape=(x_numeric_train.values.shape[1],), name='numeric_input') nlp_seq = Input(shape=(number_of_messages ,seq_length,), name='nlp_input'+str(i)) # shared layers emb = TimeDistributed(Embedding(input_dim=num_features, output_dim=embedding_size, input_length=seq_length, mask_zero=True, input_shape=(seq_length, )))(nlp_seq) x = TimeDistributed(Bidirectional(LSTM(32, dropout=0.3, recurrent_dropout=0.3, kernel_regularizer=regularizers.l2(0.01))))(emb) c1 = Conv1D(filter_size, kernel1, padding='valid', activation='relu', strides=1, kernel_regularizer=regularizers.l2(kernel_reg))(x) p1 = GlobalMaxPooling1D()(c1) c2 = Conv1D(filter_size, kernel2, padding='valid', activation='relu', strides=1, kernel_regularizer=regularizers.l2(kernel_reg))(x) p2 = GlobalMaxPooling1D()(c2) c3 = Conv1D(filter_size, kernel3, padding='valid', activation='relu', strides=1, kernel_regularizer=regularizers.l2(kernel_reg))(x) p3 = GlobalMaxPooling1D()(c3) x = concatenate([p1, p2, p3, numeric_input]) x = Dense(1, activation='sigmoid')(x) model = Model(inputs=[nlp_seq, meta_input] , outputs=…
has comment: http://stackoverflow.com/comment/89741546
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51332144
has comment: http://stackoverflow.com/comment/89751381
accepted answer of: http://stackoverflow.com/q/51332144

http://stackoverflow.com/comment/89887261
score: 1
comment on: http://stackoverflow.com/q/51458644
type: QuestionComment
has text: @VikasNS I think each code number is one name in the column Major_Project_Theme (except missing value) so he wants to fill the missing value with the name associated to the code in the row
type: Comment

http://stackoverflow.com/comment/89818492
score: 0
type: Comment
has text: Extended my answer to cover the last case.
type: AnswerComment
comment on: http://stackoverflow.com/a/51400731

http://stackoverflow.com/q/51472141
possible better answer: http://stackoverflow.com/a/51472809
favorite count: 0
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51473004
upvote count: 2
has title: Handling NaNs in linear regression -- scipy?
tagged with: scipy
type: Question
tagged with: linear-regression
accepted answer: http://stackoverflow.com/a/51473004
has answer: http://stackoverflow.com/a/51472809
tagged with: numpy
answer count: 2
tagged with: pandas
has body: I have a data set with NaNs scattered amongst the data. I'm using pandas to extract the data from a file, and numpy to process it. This is my code for reading the data: import pandas as pd import numpy as np def makeArray(band): """ Takes as argument a string as the name of a wavelength band. Converts the list of magnitudes in that band into a numpy array, replacing invalid values (where invalid == -999) with NaNs. Returns the array. """ array_name = band + '_mag' array = np.array(df[array_name]) array[array==-999]=np.nan return array # Read data file fields = ['no', 'NED', 'z', 'obj_type','S_21', 'power', 'SI_flag', 'U_mag', 'B_mag', 'V_mag', 'R_mag', 'K_mag', 'W1_mag', 'W2_mag', 'W3_mag', 'W4_mag', 'L_UV', 'Q', 'flag_uv'] magnitudes = ['U_mag', 'B_mag', 'V_mag', 'R_mag', 'K_mag', 'W1_mag', 'W2_mag', 'W3_mag', 'W4_mag'] df = pd.read_csv('todo.dat', sep = ' ', names = fields, index_col = False) # Define axes for processing redshifts = np.array(df['z']) y = np.log(makeArray('K')) mask = np.isnan(y) I guess a minimal working example would be: import numpy as np import matplotlib.pyplot as plt from scipy import stats randomNumberGenerator = np.random.RandomState(1000) x = 4 * randomNumberGenerator.rand(100) y = 4 * x - 1+ randomNumberGenerator.randn(100) y[50] = np.nan slope, intercept, r_value, p_value, std_err = stats.linregress(x,y) fit = slope*x + intercept plt.scatter(x, y) plt.plot(x, fit) plt.show() Commenting out the y[50] = np.nan line in the MWE produces a nice graph, but including it produces the same error message as with my actual data: C:\Users\Jeremy\Anaconda3\lib\site-packages\scipy\stats\_distn_infrastructure.py:879: RuntimeWarning: invalid value encountered in greater return (self.a &lt; x) &amp; (x &lt; self.b) C:\Users\Jeremy\Anaconda3\lib\site-packages\scipy\stats\_distn_infrastructure.py:879: RuntimeWarning: invalid value encountered in less return (self.a &lt; x) &amp; (x &lt; self.b) C:\Users\Jeremy\Anaconda3\lib\site-packages\scipy\stats\_distn…
downvote count: 0

http://stackoverflow.com/comment/89625833
type: QuestionComment
type: Comment
has text: Can you *post the error*?
score: 1
comment on: http://stackoverflow.com/q/51325438

http://stackoverflow.com/comment/90643414
has text: Yes. Pyramid was `request.has_permission()` that can be used in the context of traverable resources. https://websauna.org/docs/narrative/user/permissions.html?highlight=checking%20permission#manually-checking-a-permission
type: Comment
comment on: http://stackoverflow.com/a/51504456
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89647166
comment on: http://stackoverflow.com/q/51336074
has text: I still don't understand
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89774259
type: QuestionComment
has text: Thanks it works now
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51391398

http://stackoverflow.com/comment/89644853
comment on: http://stackoverflow.com/a/51334615
type: Comment
score: 1
has text: I think Imiguelvargasf was downvoting competitively. I cannot demonstrate this, but I believe I saw his score go down after voting mine down. If this is false, I apologize in advance to him, but that's just what is seems like given that all the other posts had exactly 1 downvote before I downvoted his post.
type: AnswerComment

http://stackoverflow.com/q/51365788
answer count: 1
downvote count: 0
has body: I am looking at A.Mele Django by Example,chapter1 def post_list(request, category=None): object_list = Post.published.all() paginator = Paginator(object_list, 3) # 3 posts in each page page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page posts = paginator.page(1) except EmptyPage: # If page is out of range deliver last page of results posts = paginator.page(paginator.num_pages) return render(request, 'blog/post/list.html', {'page': page, 'posts': posts}) This line that gets page is what I really do not understand. page = request.GET.get('page') Get method sends user information with the request. But what is get actually doing? This is blog/post/list.html {% extends "blog/base.html" %} {% block title %}My blog{% endblock %} {% block content %} {% include "pagination.html" with page=posts %} My Blog {% for post in posts %} {{ post.title }} Published {{ post.publish }} by {{ post.author }} {% endfor %} {% endblock %}
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/51365928
score: 2
type: AnsweredQuestion
tagged with: django
has title: What is request.GET.get doing?
has answer: http://stackoverflow.com/a/51365928
type: Question
upvote count: 2

http://stackoverflow.com/a/51331326
has comment: http://stackoverflow.com/comment/89638741
accepted answer of: http://stackoverflow.com/q/51330846
has comment: http://stackoverflow.com/comment/89638561
has comment: http://stackoverflow.com/comment/89641702
answers question: http://stackoverflow.com/q/51330846
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89638582
has comment: http://stackoverflow.com/comment/89638438
has comment: http://stackoverflow.com/comment/89638671
type: Answer
has body: Your own message.py is unrelated, as the class is coming from telegram.message which is the telegram module. The documentation for .text says it is optional - maybe the message you're dealing with has no text? EDIT: I have created a new token, and tried running your code, and I can't reproduce your issues. Here are my findings: your own message.py is completely unrelated. Deleting it from the project does nothing. Adding a syntax error inside it does nothing. It is not even being imported. I put a jpg file named message.py instead, and nothing happens. I tried printing update.message.text and it works fine here! While update.message.id fails, it seems that id is not in the documentation for the Message class that you linked. I'm using update.message.message_id instead and it works fine here! I modified the function to answer the message, as below, and it works fine, as you can see in the screenshot: Modification: def receive_message(self, bot, update, user_data): bot.send_message( chat_id=update.message.chat_id, text="You said {} with id {}".format( update.message.text, update.message.message_id ), )

http://stackoverflow.com/q/51429309
upvote count: 8
accepted answer: http://stackoverflow.com/a/51433166
favorite count: 0
has body: Edit The accepted answer works for sets that satisfy the requirements of a strict partially ordered set, so that a directed acyclic graph can be constructed: irreflexivity not a &lt; a: the list does not contain items like ['a','a'] transitivity if a &lt; b and b &lt; c then a &lt; c: the list does not contain items like ['a','b'],['b','c'],['c','a'] asymmetryif a &lt; b then not b &lt; a: the list does not contain items like ['a','b'],['b','a'] Take this list of lists: [['b', 'c'], ['a', 'c'], ['b', 'a'], ['a', 'c', 'd'], ] and flatten it to a single list, sorted depending on a value's neighbor(s): the first sublist tells you that b comes before c then a before c b before a and finally d after c The overall ordering between sublists is consistent, meaning there won't be sublists like these: ['b','c'],['c','b']. So the result should be: ['b', 'a', 'c', 'd'] After a (long) while I came up with this ugly mess: def get_order(_list): order = _list[0] for sublist in _list[1:]: if not sublist: continue if len(sublist) == 1: if sublist[0] not in order: order.append(sublist[0]) continue new_order = order.copy() for index, value in enumerate(sublist): inserted = False new_order_index = None if value in new_order: new_order_index = new_order.index(value) new_order.remove(value) for previous_value in sublist[:index][::-1]: if previous_value in new_order: insert_index = new_order.index(previous_value) + 1 print('inserting', value, 'at position', insert_index, 'after', previous_value) new_order.insert(insert_index, value) inserted = True break if inserted: continue for next_value in sublist[index:]: if next_value in new_order: insert_index = new_order.index(next_value) print('inserting', value, 'at position', insert_index, 'before', next_value) new_order.insert(insert_index, value) inserted = True break if inserted: continue if new_order_index is None: print('appending', value) new_order.append(value) else: print('leaving', value, 'at position', new_order_index) new_order.insert…
tagged with: python
has comment: http://stackoverflow.com/comment/89829867
has comment: http://stackoverflow.com/comment/89829832
has comment: http://stackoverflow.com/comment/89830025
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89829811
has title: Logically sorting a list of lists (partially ordered set -> topological sort)
has answer: http://stackoverflow.com/a/51429520
has answer: http://stackoverflow.com/a/51433166
type: Question
answer count: 2
score: 8
downvote count: 0
possible better answer: http://stackoverflow.com/a/51429520

http://stackoverflow.com/comment/89870239
type: QuestionComment
score: 1
has text: Itertools won't get you far on its own, since its `permutations` and `combinations` methods only work on a single iterable. Would not comprehensions be better for this?
comment on: http://stackoverflow.com/q/51449857
type: Comment

http://stackoverflow.com/a/51354877
type: Answer
answers question: http://stackoverflow.com/q/51354714
has body: change count=0 at first,because members index from 0
score: 0
has comment: http://stackoverflow.com/comment/89688278

http://stackoverflow.com/q/51403479
downvote count: 0
has answer: http://stackoverflow.com/a/51476127
accepted answer: http://stackoverflow.com/a/51476127
favorite count: 0
upvote count: 2
tagged with: path
possible better answer: http://stackoverflow.com/a/70937512
tagged with: python
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/89920537
tagged with: pth
type: Question
has answer: http://stackoverflow.com/a/70937512
has title: pth file is not processed
has comment: http://stackoverflow.com/comment/89778264
answer count: 2
has body: I was trying to add some folders to my path, so I added a .pth file to my site-packages folder. When it didn't work (I printed sys.path and it doesn't contain any of the paths I wrote in the file) , I tried to find the .pth file from within python and I noticed that the name of one of the folders in the path contains a . in it. Could that be the reason why the .pth file wasn't processed? or any other suggestions why Its not working? I don't think I can change the folder name, it was created when I created a virtual environment, and I think that if I'll change it, it might mess up other things. The path to the .pth is - home/pomicelltohar/venv/3_6/lib/python3.6/site-packages/pomicell.pth sys.path is ['', '/home/pomicelltohar/venv/3_6/lib/python36.zip', '/home/pomicelltohar/venv/3_6/lib/python3.6', '/home/pomicelltohar/venv/3_6/lib/python3.6/lib-dynload', '/home/pomicelltohar/anaconda3/lib/python3.6', '/home/pomicelltohar/venv/3_6/lib/python3.6/site-packages']
tagged with: pythonpath

http://stackoverflow.com/comment/89793332
comment on: http://stackoverflow.com/a/51410457
has text: thanks leaving open in case this is already implemented (although I found little in the docs)
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51390918
linked to: http://stackoverflow.com/q/13686009
linked to: http://stackoverflow.com/q/682504
has comment: http://stackoverflow.com/comment/89755103
favorite count: 0
has comment: http://stackoverflow.com/comment/89755230
type: Question
has comment: http://stackoverflow.com/comment/89768557
has title: In Python, do we need to keep track of dynamically-declared instances?
tagged with: python
has body: One thing that I am struggling with while trying to learn concepts of OOP is creation of class instances. Most of the tutorials online will explain basic principles like Init, Self, Inheritance etc.. but when it comes to creating instances of the class itself it is usually reduced to something like that: emp1 = Employee("John") emp2 = Employee("Leviticus") In reality most of us beginners will want to create instance of a class dynamically (On press of button etc..) not directly in code and also will be interessted in keeping track of our instances. What I was able to come up is this: from tkinter import * import random class Point: _registry = [] def __init__(self, x_pos, y_pos): self._registry.append(self) self.x_pos = x_pos self.y_pos = y_pos print(self.x_pos, self.y_pos) def create_point(): Point(random.randint(1,20),random.randint(1,20)) window = Tk() button = Button(window, text = "Add point", command=create_point) button.pack() window.mainloop() Can someone advise if this is a proper way to do this? Shouldnt the fnction create_point be within Point class? What is the proper way to keep track of instances and later delete them? Shall I use some sort of ID attribute to keep track and "itemize" my instances? Is there any good source with tutorial that deals with that? Thank you Jacob
has comment: http://stackoverflow.com/comment/89755060
has comment: http://stackoverflow.com/comment/89755437
has comment: http://stackoverflow.com/comment/89754979
has comment: http://stackoverflow.com/comment/89755197
tagged with: tkinter
score: 0
linked to: http://stackoverflow.com/q/31410640
has comment: http://stackoverflow.com/comment/89755025
upvote count: 1
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89755085
tagged with: oop
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89755137
has comment: http://stackoverflow.com/comment/89755414
has comment: http://stackoverflow.com/comment/89754938
has comment: http://stackoverflow.com/comment/89755271
has answer: http://stackoverflow.com/a/51412104

http://stackoverflow.com/q/51335371
accepted answer: http://stackoverflow.com/a/51335922
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: tensorflow
type: Question
has body: layer_1 = tf.layers.dense(inputs=layer_c, units=512, activation=tf.nn.tanh, name='layer1') layer_2 = tf.layers.dense(inputs=1, units=512, activation=tf.nn.tanh, name='layer2') Here my layer_2 output is [batch_size,512]. I need to send this layer_2 output through a single lstm unit. But when I tried tf.nn.static_rnn it gives an error saying my input should be a sequence. How can I perform this task?
has answer: http://stackoverflow.com/a/51335922
tagged with: lstm
tagged with: deep-learning
has title: How can I create a lstm cell with only single time step in tensorflw?
answer count: 1

http://stackoverflow.com/a/51406225
has comment: http://stackoverflow.com/comment/89783751
score: 2
answers question: http://stackoverflow.com/q/51406127
downvote count: 0
has body: You could have a reference to the function (notice the lack of () after writeFunction) in the dict, then check whether the object you retrieve to sysResponse is callable; if it is, call it to replace the actual value. This has the added bonus that if writeFunction has side-effects or is slow to execute, it'll only be executed if it's chosen. switch = { 'Option 1': writeFunction, 'Option 2': 'Answer 2', 'Option 3': 'Answer 3' } sysResponse = switch.get(arg, "Value not in list") if callable(sysResponse): sysResponse = sysResponse()
upvote count: 2
has comment: http://stackoverflow.com/comment/89783621
type: Answer

http://stackoverflow.com/comment/89812122
has text: First question I've ever posted so cut some slack eh. But thanks for the help :)
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51419625

http://stackoverflow.com/q/51431428
has comment: http://stackoverflow.com/comment/89834132
has title: OpenAI Gym not rendering colors correctly in console environments
has comment: http://stackoverflow.com/comment/89833950
linked to: http://stackoverflow.com/q/16755142
linked to: http://stackoverflow.com/q/36760127
answer count: 2
has comment: http://stackoverflow.com/comment/89834980
downvote count: 0
favorite count: 0
has body: So I've just started using Gym from OpenAI and I'm trying to render an environment in the console. Specifically, it's the Taxi-v2 environment. And where it's supposed to show colors it only shows symbols (their ANSI code I think) so I'd believe it's not parsing correctly. I've tried other environments that also render in console, same problem. I've tried using the Git Bash console as well as the Windows one, and it's the same problem as well. Any help? Code to render: import gym env = gym.make('Taxi-v2') env.render() Output in console: +---------+ |?[35mR?[0m: | : :G| | : : :?[43m ?[0m: | | : : : : | | | : | : | |Y| : |?[34;1mB?[0m: | +---------+
linked to: http://stackoverflow.com/q/42605769
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/58789951
upvote count: 3
tagged with: openai-gym
has comment: http://stackoverflow.com/comment/89834082
type: Question
has answer: http://stackoverflow.com/a/58259609
score: 3
tagged with: console-application

http://stackoverflow.com/comment/89877181
has text: This is exactly the kind of answer I was looking for! I didn't necessarily need code, just an idea on how to do it :)
comment on: http://stackoverflow.com/a/51446780
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/51452931
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/113459746
type: Question
score: 5
upvote count: 5
has body: Using Platypus, I created a simple application which runs the following shell script: cd if [ -e /Applications/Music.app/Contents/Resources/Music.py ]; then export PATH=$PATH:/Applications/Music.app/Contents/Resources cd "/Applications/Music.app/Contents/Resources" EXTENSION=`osascript -e 'tell application (path to frontmost application as text) to display dialog "Do you want to enable extensions during this session?" buttons {"Yes", "No"} with icon file "Applications:Music.app:Contents:Resources:alert.icns"'` if [ "$EXTENSION" == "button returned:Yes" ]; then python Music.py arg1 &gt;&gt; music.txt &amp; else python Music.py arg2 &gt;&gt; music.txt &amp; fi else osascript -e 'tell application (path to frontmost application as text) to display dialog "Please move this application into your native applications folder (/Applications)." buttons {"OK"} with icon stop' osascript -e 'quit app "Music.app"' fi The "Music.py" script runs in an infinite loop, constantly selecting one of about 80 URLs to load on Selenium using chromedriver. Each URL loads a particular song, and, when the song is finished playing, the Python script randomly selects another position on the array of possible song URLs and loads the corresponding song (so it basically shuffles through a given playlist). The playback can be paused using the kill -STOP [pid] and resumed using the kill -CONT [pid] commands. However, I want to be able to pause it by clicking on the "Music.app" icon on my Mac's dock (to bring this application to the foreground and ensures that it receives all keystrokes) and using a keyboard shortcut. After some experimenting, I found that by running the commands: bind '"^P":"ID_PARENT=`pgrep chromedriver` &amp;&amp; ID_CHILD=`pgrep -P $ID_PARENT` &amp;&amp; echo $ID_CHILD &amp;&amp; kill -STOP $ID_CHILD\n"' bind '"^R":"ID_PARENT=`pgrep chromedriver` &amp;&amp; ID_CHILD=`pgrep -P $ID_PARENT` &amp;&amp; echo $ID_CHILD &amp;&amp; kill -CONT $ID_CHILD\n"' in my normal command line, I am a…
tagged with: platypus
has title: How can I make a Platypus-created shell application respond to a keyboard command?
downvote count: 0
tagged with: shell

http://stackoverflow.com/q/51443124
type: Question
score: 3
tagged with: duplicates
tagged with: dataframe
upvote count: 3
answer count: 2
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/51443608
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/59767076
tagged with: python
has body: I have a question regarding duplicating rows in a pandas dataframe. I have allocated relevant dates to each observation in the column "relevant shocks" in lists. Observation 22 has an empty list, 23 a list with one date, 24 a list with two dates and 25 a list with three dates (as seen in column "listlength"). My aim is to expand the dataframe in the way that observations with empty lists remain in the dataset with one row while rows with x observations get duplicated x times - as such, rows 22 and 23 should stay in the dataframe once (22 despite the empty list and 23 because it has one relevant date), row 24 should get duplicated once and thus be in the dataframe twice and observation 25 should be duplicated twice and thus be in the dataframe thrice. As such, each row should be in the dataframe as many times as it has relevant shocks (as measured by listlength). Except for the ones with list length 0, they should still remain in the dataframe. Further, I want to create a new column "relevant shock" which is filled by each of the relevant shocks once and separately. This is the current dataframe: quarter year pddate relevant shocks listlength 22 1 2012 2012-02-15 [] 0.0 23 4 2011 2011-11-15 [2011-08-18 00:00:00] 1.0 24 3 2011 2011-08-15 [2011-08-18 00:00:00, 2011-09-22 00:00:00] 2.0 25 2 2011 2011-05-13 [2011-08-04 00:00:00, 2011-08-08 00:00:00, 2011-08-10 00:00:00 3.0 The new dataframe should have 7 rows and look as follows: quarter year pddate relevant shocks listlength relevant shock 22 1 2012 2012-02-15 [] 0.0 23 4 2011 2011-11-15 [2011-08-18 00:00:00] 1.0 2011-08-18 00:00:00 24 3 2011 2011-08-15 [2011-08-18 00:00:00, 2011-09-22 00:00:00] 2.0 2011-08-18 00:00:00 25 3 2011 2011-08-15 [2011-08-18 00:00:00, 2011-09-22 00:00:00] 2.0 2011-09-22 00:00:00 26 2 2011 2011-05-13 [2011-08-04 00:00:00, 2011-08-08 00:00:00, 2011-08-10 00:00:00 3.0 2011-08-04 00:00:00 27 2 2011 2011-05-13 [2011-08-04 00:00:00, 2011-08-08 00:00:00, 2011-08-10 00:00:00 3.0 2011-08-08 00:00:00 28…
tagged with: list
has title: Duplicate rows in pandas dataframe based on list and fill new column with list entries

http://stackoverflow.com/comment/89830967
score: 0
comment on: http://stackoverflow.com/q/51429760
type: Comment
type: QuestionComment
has text: It responds with a 302, not that it was blocked entirely. You can retrieve google search results programmatically and without using a browser, though you must do so in the appropriate way.

http://stackoverflow.com/q/51441828
has body: I am trying to use pool from multiprocessing to speed up my read/write function. However, when I try to use pyinstaller and run it with an exe. The result is a new process that spawns a new process that spawns a new process ad infinitum until I log out and the OS forcefully terminates all my user processes. I have no idea what is happening There is no problem when running in the pycharm or even running the code with running the .py. The version is python 3.6.3. Platform: Windows 7 The code will be like: if __name__ == "__main__": pool = Pool(2) pool.map(readwritevalue, [file for file in gettxtpath()]) pool.close() pool.join() GetFormated() ##Get the Final output of .csv Getxlsx() ##Get the Report.xls GetDocx() ##Get the docx format t1 = time.time() print("Parallel time{t}s".format(t=time.time() - t1)) Would you please shed some lights on this? I searched the Google and some answers are to put the multiprocessing module under the "__name__=="__main__"", However, I already did that. So what else will cause that infinite explosion of processes? Thank you very much.
has comment: http://stackoverflow.com/comment/89914890
score: 3
has comment: http://stackoverflow.com/comment/89915028
answer count: 1
downvote count: 0
favorite count: 0
has title: python multiprocessing module cause infinite loop
linked to: http://stackoverflow.com/q/32672596
has comment: http://stackoverflow.com/comment/89925934
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/2073942
has comment: http://stackoverflow.com/comment/89854234
upvote count: 3
has answer: http://stackoverflow.com/a/51478808
duplicate of: http://stackoverflow.com/q/2073942
tagged with: multiprocessing
type: Question

http://stackoverflow.com/comment/89819931
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51423459
has text: I have edited my question and added more details. thank you for your remarks.

http://stackoverflow.com/a/51392150
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51392020
has body: The code below finds the length of the largest number in the list and then adds padding to the sides of every number accordingly. After that we print every line by iterating over the list 4 steps at a time. In: L = [128,0,4096,0,64,0,0,128,2048,0,0,4096,0,0,64,0] m = len(str(max(L))) + 2 L = [ str(x).center(m,' ') for x in L] step = 4 for i in range(0,len(L),step): s = '|' + '|'.join(L[i:i+step]) + '|' print(s) print('-'*len(s)) Out: | 128 | 0 | 4096 | 0 | ----------------------------- | 64 | 0 | 0 | 128 | ----------------------------- | 2048 | 0 | 0 | 4096 | ----------------------------- | 0 | 0 | 64 | 0 | ----------------------------- If you want larger or smaller tables, just change the value of the step. In: L = [128,0,4096,0,64,0,0,128,2048,0,0,4096,0,0,64,0] m = len(str(max(L))) + 2 L = [ str(x).center(m,' ') for x in L] step = 8 for i in range(0,len(L),step): s = '|' + '|'.join(L[i:i+step]) + '|' print(s) print('-'*len(s)) Out: | 128 | 0 | 4096 | 0 | 64 | 0 | 0 | 128 | --------------------------------------------------------- | 2048 | 0 | 0 | 4096 | 0 | 0 | 64 | 0 | --------------------------------------------------------- However, if you want the padding to be as tight as possible for every column without looking ugly, things get a little bit more complicated. In: L = [128,0,4096,0,64,0,0,128,2048,0,0,4096,0,0,64,0] step = 4 # We calculate the padding for every column and store it in sz[]. # The padding for a column is the same as the minimum padding for its largest element. sz = [] for index,item in enumerate(L): column = [L[i] for i in range(index,len(L),step)] padding = len( str( max(column) ) ) + 2 sz.append(padding) if index == step + 1: break # Now we iterate over the columns ( not linearly over the array ) # and we apply the appropriate padding we have just found out. i = 0 while i &lt; step + 1: for j in range(i,len(L),step): L[j] = str(L[j]).center(sz[i],' ') i += 1 # Now simply iterate linearly over the array and print a new line # every step. for …
type: Answer

http://stackoverflow.com/q/51475254
tagged with: encode
tagged with: python
type: AnsweredQuestion
upvote count: 0
duplicate of: http://stackoverflow.com/q/24085680
has answer: http://stackoverflow.com/a/75123495
linked to: http://stackoverflow.com/q/24085680
type: Question
possible better answer: http://stackoverflow.com/a/75123495
tagged with: decode
has body: I have a string like this: '\\xac\\x85' and I want to encode these string like this another: '\xac\x85' I tried a lot of things like encode tu utf-8, replace \\x, etc. But when I print the result it always is with \\x. Any idea?
score: -1
has answer: http://stackoverflow.com/a/51475332
accepted answer: http://stackoverflow.com/a/51475332
answer count: 2
downvote count: 1
tagged with: utf-8
has title: \\x to \x with python
favorite count: 0

http://stackoverflow.com/q/51343702
tagged with: python-requests
type: Question
has body: I'm using newsapi.org and trying to pull chinese articles. When I print them, it can't seem to read chinese characters. u'\u8fdd\u89c4 shows up instead. {u'articles': [{u'author': u'chinanews', u'description': u'\u8fdd\u89c4 \u539f\u6599\u836f\u5904\u65b9\u836f\u6d41\u5165\u5e02\u573a\u3000\u3000\u5206\u6790\u5404\u5730\u8b66\u65b9\u516c\u5e03\u7684\u5236\u552e\u6709\u6bd2\u6709\u5bb3\u4fdd\u5065\u54c1\u6848\u60c5\u4e0d\u96be\u53d1\u73b0\uff0c\u8fd9\u4e9b\u6709\u5bb3\u4fdd\u5065\u54c1\u7684\u751f\u4ea7\u539f\u6750\u6599\u4e3b\u8981\u6709\u4e24\u5927\u6e90\u5934\u3002', u'publishedAt': u'2018-07-14T20:50:00Z', u'source': {u'id': None, u'name': u'Chinanews.com'}, My code is import requests url = ('https://newsapi.org/v2/top-headlines?' 'country=cn&amp;' 'apiKey=16a6cd0345d84e799600cdb9ead6f05d') response = requests.get(url) pprint(response.json())
has answer: http://stackoverflow.com/a/51344585
tagged with: python-2.7
score: 0
answer count: 2
has title: Decoding chinese characters in python requests
tagged with: python
has answer: http://stackoverflow.com/a/51344515
type: UnansweredQuestion

http://stackoverflow.com/comment/89660538
type: QuestionComment
has text: An url that fails to load _should_ throw an error, right ? If you have a reasonable case to deviate from the pattern, skip printing the 'Failed to open url' message. To deal with timeouts specifically try adding a handler for the `TimeoutError` exception class parallel to the `ConnectionError` handler.
score: 0
comment on: http://stackoverflow.com/q/51341984
type: Comment

http://stackoverflow.com/a/51347924
score: 2
accepted answer of: http://stackoverflow.com/q/51346000
has comment: http://stackoverflow.com/comment/89707100
has comment: http://stackoverflow.com/comment/89694691
has comment: http://stackoverflow.com/comment/89686104
downvote count: 0
has body: You could replace at least some of the joins for filters with EXISTS subquery expressions, or semijoins in a way. This way your query avoids producing multiple rows for single activity. It is ok to still join against Type, since it's a many to one relationship: records = m.Activity.query.\ join(m.Activity.type).\ filter(m.Activity.events.any(name=keyword)).\ filter(m.Activity.goals.any(name=...)).\ filter(...).\ order_by(m.Type.name.desc()).\ limit(limit).\ offset((page - 1) * limit) Passing keyword arguments to any() is a similar shorthand as filter_by(). It accepts complex criterion expressions as well, as positional arguments. The distinct(m.Activity.id), or DISTINCT ON, should've worked as well, as long as you then use the results as a subquery, to which you then apply the ordering and limit: records = m.Activity.query.\ join(m.Activity.events).\ join(m.Activity.date_locations).\ join(m.Activity.goals).\ filter(m.Event.name == keyword).\ filter(...).\ distinct(m.Activity.id).\ from_self().\ join(m.Activity.type).\ order_by(m.Type.name.desc()).\ limit(limit).\ offset((page - 1) * limit)
has comment: http://stackoverflow.com/comment/89706479
answers question: http://stackoverflow.com/q/51346000
has comment: http://stackoverflow.com/comment/89694440
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89707197
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/89692483

http://stackoverflow.com/q/51479054
has body: I'm working for a text classificator in Python using Keras. For now I tried so make model only with the words of my dataset, using bag of words. Now I would use in my classifier other custom features (like polarity) but I don't know how to add there in my code. My dataset is like: Text | Polarity | Number of words | Classification Hello my name is John | 0,05 | 5 | 0 How old are you? | 0,00 | 4 | 1 I'm very hungry | -0,05 | 4 | 0 The middle two colums are my custom features that i want add to my classifier but I don't know how. train_x = tokenizer.sequences_to_matrix(allWordIndices, mode='binary') train_x2 = train_x train_x = train_x[1000:] test_x = train_x2[:1000] train_y = keras.utils.to_categorical(train_y, 2) train_y2 = train_y train_y = train_y[1000:] test_y = train_y2[:1000] from keras.models import Sequential from keras.layers import Dense, Dropout, Activation model = Sequential() model.add(Dense(30, input_shape=(max_words,), activation='relu')) model.add(Dropout(0.45)) model.add(Dense(100, activation='softplus')) model.add(Dropout(0.45)) model.add(Dense(2, activation='softmax')) model.compile(loss='categorical_crossentropy',optimizer='RMSProp',metrics=['accuracy']) history = model.fit(train_x,train_y,batch_size=32,epochs=10,verbose=1,validation_split=0.1,shuffle=True) score = model.evaluate(test_x,test_y, batch_size=128) In this example i use only bag of words feature of the content f first column and i want add other 2 column like features (polarity, number of words). Someone has an idea how add these? Thanks in advance.
tagged with: python
has answer: http://stackoverflow.com/a/51480697
tagged with: classification
tagged with: text-classification
type: Question
has title: How use custom features in Keras for text classification
score: 0
answer count: 1
tagged with: keras
tagged with: data-analysis
type: UnansweredQuestion

http://stackoverflow.com/comment/89783327
score: 0
comment on: http://stackoverflow.com/q/51406125
type: Comment
type: QuestionComment
has text: @WillemVanOnsem so that would be, `return JsonResponse(payload)` in my case, or does it save me a few more more steps?

http://stackoverflow.com/comment/89796159
type: Comment
comment on: http://stackoverflow.com/q/51412225
type: QuestionComment
has text: In particular, on <3.7, make `data` an `OrderedDict`
score: 0

http://stackoverflow.com/comment/89854683
type: QuestionComment
has text: Sorry i posted it non completely: When I try to instal pip by command "python -m ensurepip --default-pip", CD writes me beck: Ignoring indexes: https://pypi.python.org/simple Requirement already satisfied (use --upgrade to upgrade): setuptools in c:\program files\ibm\spss\statistics\24\python3\lib\site-packages Requirement already satisfied (use --upgrade to upgrade): pip in c:\program files\ibm\spss\statistics\24\python3\lib\site-packages
comment on: http://stackoverflow.com/q/51441521
score: 0
type: Comment

http://stackoverflow.com/comment/89917567
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51469764
has text: There is no possibility of a equivalent js script that gets generated to redo the live view update that happens for a particular output ipython cell?

http://stackoverflow.com/q/51426108
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has body: Can't really find an answer in the Doc / google. Is it possible to use pyinstaller to generate build withing the python script? or the only right option is to execute command line command by subprocess module, ex: from subprocess import PIPE, run, run(['pyinstaller', '--onefile', 'file.py'], stdout=PIPE, stderr=PIPE, universal_newlines=True, timeout=20) pseudo-code for what i want to do: from pyinstaller import PyInstaller build = PyInstaller.build('file.py', onefile=true, distpath=*path*, workpath=*path*) file_path = build.get_path()
tagged with: python
score: 2
downvote count: 0
type: Question
has title: Pyinstaller usage within python script
upvote count: 2
has answer: http://stackoverflow.com/a/51448246
tagged with: pyinstaller
answer count: 1

http://stackoverflow.com/comment/89746242
comment on: http://stackoverflow.com/a/51386880
type: AnswerComment
has text: Instead of join and creating a mask, you can use `isin` as in `file[file.title.isin(search_for)]`
score: 0
type: Comment

http://stackoverflow.com/comment/108160500
type: Comment
has text: great answer! for a different structure of the json, refer to https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_json.html
score: 3
comment on: http://stackoverflow.com/a/60119920
type: AnswerComment

http://stackoverflow.com/q/51402579
has answer: http://stackoverflow.com/a/51567778
type: Question
has comment: http://stackoverflow.com/comment/89776707
favorite count: 0
has comment: http://stackoverflow.com/comment/89776075
has title: Module Seaborn has no attribute '<any graph>'
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/51402703
has comment: http://stackoverflow.com/comment/89776177
has answer: http://stackoverflow.com/a/51412350
tagged with: python-3.x
has body: I am having trouble switching from ggplot2 into seaborn. Currently using Anaconda v. 4.5.8 and Python 3.6.3 Any graph I use cannot be found. For example I can take any code from seaborn's site and run: import matplotlib as plt import seaborn as sns sns.set(style="ticks") dots = sns.load_dataset("dots") # Define a palette to ensure that colors will be # shared across the facets palette = dict(zip(dots.coherence.unique(), sns.color_palette("rocket_r", 6))) # Plot the lines on two facets sns.relplot(x="time", y="firing_rate", hue="coherence", size="choice", col="align", size_order=["T1", "T2"], palette=palette, height=5, aspect=.75, facet_kws=dict(sharex=False), kind="line", legend="full", data=dots) sns.plt.show() #this was not on site code but tried it(plt.show() as referenced by other posts) Error message: File "&lt;ipython-input-8-893759310442&gt;", line 13, in &lt;module&gt; sns.relplot(x="time", y="firing_rate", AttributeError: module 'seaborn' has no attribute 'relplot' Looked at these posts( among others) (1) AtributeError: 'module' object has no attribute 'plt' - Seaborn (2) Seaborn ImportError: DLL load failed: The specified module could not be found (3) ImportError after successful pip installation (4) Error importing Seaborn module in Python and tried the install/uninstall methods they described ( python -m pip install seaborn, uninstall seaborn/ reinstall - etc.) I did this in both conda using conda and cmd using pip. I haven't spent much time with PATHs but here are screenshots: Any ideas? Many Thanks
score: 33
tagged with: seaborn
possible better answer: http://stackoverflow.com/a/51412350
downvote count: 1
upvote count: 34
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51402703
has comment: http://stackoverflow.com/comment/89776125
has comment: http://stackoverflow.com/comment/89776101
has comment: http://stackoverflow.com/comment/89775942

http://stackoverflow.com/comment/89934504
comment on: http://stackoverflow.com/q/51481756
score: 0
has text: Unfortunately, the model's resolution limited to the hour so it wouldn't be able to generate predictions by the minute. However, you could utilize linear interpolation between two predicted points to estimate the prediction at two points.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51330198
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89636058
accepted answer: http://stackoverflow.com/a/51330272
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89636474
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89636286
has title: Looking for a better way to generate key's for a dictonary, global integers?
has answer: http://stackoverflow.com/a/51330272
has body: I want each key to be in succession of the previous key for this list. For instance, the first key should be 1 and the next will 2, then 3...n for each method call. My code works: all_randomly_generated_intigers = {} def new_ID(): y = random.randint(0,5) x = 0 while x in all_randomly_generated_integers: x+=1 all_randomly_generated_integers[x] = y However, the loop will run x times for each call on new_ID(). I figured I could just call x global but my method doesn't see x if I do that: all_randomly_generated_intigers = {} global x def new_ID(): y = random.randint(0,5) while x in all_randomly_generated_integers: x+=1 all_randomly_generated_integers[x] = y Why doesn't this work?
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/89757360
comment on: http://stackoverflow.com/a/51392683
has text: how do i do that? -brand new to this
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/comment/89778809
score: 0
type: Comment
type: QuestionComment
has text: yes, i actually got this string from a json dump which yields that result
comment on: http://stackoverflow.com/q/51403945

http://stackoverflow.com/a/51461208
accepted answer of: http://stackoverflow.com/q/51461177
answers question: http://stackoverflow.com/q/51461177
has comment: http://stackoverflow.com/comment/89891679
has comment: http://stackoverflow.com/comment/89891672
has comment: http://stackoverflow.com/comment/89891676
score: 8
has comment: http://stackoverflow.com/comment/89891965
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89891661
has comment: http://stackoverflow.com/comment/89891686
upvote count: 8
type: Answer
has body: For debugging. If you can't cast a thing to a string, you can't print it. If you want to print a data structure for debugging, you need to be able to cast each element to a string. That's what str is documented to do... Return a string containing a nicely printable representation of an object. If what is written in code is to be treated this way, how does this work ... >>> str(not True) 'False' not True resolves to False which is then passed to str. It's similar to how with foo(1 + 1) foo receives 2. Second, it's not obvious it's for consistency, as >>> bool(str(False)) True Casting is not guaranteed to round trip. Examples are int(float(2.34)) or int(unichr(97)). There's an important difference between converting something to a string for humans, which is what str does, and converting something to a string for marshalling which must round trip. There are specialized packages like marshal or json for marshalling. But casting is the wrong way to think about bool and str in Python. As above, str returns a printable representation, not a machine-readable one. bool is for asking "what is the truthiness of this expression"? From the docs... x is converted using the standard truth testing procedure. "True" and "False" are both true. If they added a special case just for bool that would be very inconsistent.

http://stackoverflow.com/comment/89864552
score: 0
type: AnswerComment
has text: Thanks for your reply - the only issue with the above is that the Jan values should represent those in the original data series. So 2017-01-31 should be 75.0 etc. I either need to set the Jan's as NaNs before updating with the originals (via df.update() ) or just directly replace the Jan values in the above with the originals.
type: Comment
comment on: http://stackoverflow.com/a/51446682

http://stackoverflow.com/q/51344299
has title: Deploying Python as a single executable
tagged with: deployment
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/51347488
has body: I would like to find a way to deploy Python programs as an executable on Debian where I would be able to bundle: the dependencies and third party libs the code that might need to be installed on the host machine. Typically some libs in Python like pilow or snappy are depending on shared libraries within /usr/lib I think you can achieve (1) and (2) separately. To achieve (1), I believe that there exists different ways to ship virtualenv, and for (2) I've seen some people using Docker image or Ansible to install tool/module on the host OS. To me, it feels that by having 2 systems to achieve (1) and (2) there is a risk to have them unsynced. It feels very error prone to think that if someone adds an external dependency in its Python program he might also has to change a Docker image. So I'm wondering if there something that does both.
has answer: http://stackoverflow.com/a/51347477
score: 0
has answer: http://stackoverflow.com/a/51344686
type: UnansweredQuestion
answer count: 3

http://stackoverflow.com/q/51441521
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89925065
favorite count: 0
has body: I have wanted to get numpy and wxPython packages into spss. When I searched for the answer, I found informations that confused me little bit. On one side it is written that you can use only packages supported by IBM, for the other side you can find informations that you can use many modules in spss or in some texts directly works with packages which are not part of the basic installation of spss (for e. g. wxPython package is used in the Programming-and-Data-Management-for-IBM-SPSS-Statistics-24 on the page 140. Their example follows: BEGIN PROGRAM. import wx app = wx.PySimpleApp() dlg = wx.MessageDialog(None, "Ok to reformat hard disk?", caption="Important Question", style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION) ret = dlg.ShowModal() if ret == wx.ID_YES: # put Yes action code here print "You said yes" else: # put No action code here print "You said No" dlg.Destroy() app.Destroy() END PROGRAM. So I tried directly install package through -pip "way", tried to focus on Custom Dialog Builder or to find some modules with .spe and .spd ending and add them... Everything failed. Maybe there is a way in these attempts but I stopped trying too early. Please can someone guide me to get on the right path? Or how to undestand that? Thanks a lot! Jan
has title: How can I get new (not directly supported by IBM) Python packages to SPSS? Is it possible at all?
has comment: http://stackoverflow.com/comment/89854602
has comment: http://stackoverflow.com/comment/89854739
type: UnansweredQuestion
tagged with: package
has comment: http://stackoverflow.com/comment/89853487
tagged with: python
tagged with: module
has comment: http://stackoverflow.com/comment/89854683
has comment: http://stackoverflow.com/comment/89854635
score: 1
has comment: http://stackoverflow.com/comment/89855140
has comment: http://stackoverflow.com/comment/89854773
type: Question
tagged with: spss
has answer: http://stackoverflow.com/a/57274652
upvote count: 1

http://stackoverflow.com/a/51453916
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51453844
upvote count: 2
has body: Create another dictionary for reverse lookup &gt;&gt;&gt; my_list = [{'name': "Julia", 'Hello': 123}, {'name': "Carl", 'Hello': 456}, {'name': "John", 'Hello': 789}] &gt;&gt;&gt; my_dict = {d[k]:d for d in my_list for k in d} Now you can find the dict containing the needed value easily &gt;&gt;&gt; my_dict[123] {'name': 'Julia', 'Hello': 123} &gt;&gt;&gt; my_dict['Carl'] {'name': 'Carl', 'Hello': 456}

http://stackoverflow.com/comment/89890702
type: AnswerComment
comment on: http://stackoverflow.com/a/51460155
type: Comment
has text: I did this by using a z after the second for. at first z=0 but then this z is equal to the previous number_of_hosts and instead of n+1 at the for loop of hosts, I used z+n+1 .
score: 0

http://stackoverflow.com/a/51421809
type: Answer
answers question: http://stackoverflow.com/q/51421654
has body: Using ElementTree Demo: import xml.etree.ElementTree et = xml.etree.ElementTree.parse(filename) root = et.getroot() for cc in root.findall('cc'): #Find all cc tags print(cc.find("dd").text) #Print current text cc.find("dd").text = "NewValue" #Update dd tags with new value et.write(filename) #Write back to xml
score: 0

http://stackoverflow.com/a/51433411
has comment: http://stackoverflow.com/comment/119323079
score: 328
has comment: http://stackoverflow.com/comment/137802702
has comment: http://stackoverflow.com/comment/121396911
has comment: http://stackoverflow.com/comment/124183173
has comment: http://stackoverflow.com/comment/121672850
has body: model.train() tells your model that you are training the model. This helps inform layers such as Dropout and BatchNorm, which are designed to behave differently during training and evaluation. For instance, in training mode, BatchNorm updates a moving average on each new batch; whereas, for evaluation mode, these updates are frozen. More details: model.train() sets the mode to train (see source code). You can call either model.eval() or model.train(mode=False) to tell that you are testing. It is somewhat intuitive to expect train function to train model but it does not do that. It just sets the mode.
answers question: http://stackoverflow.com/q/51433378
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/124186154
has comment: http://stackoverflow.com/comment/119324012
has comment: http://stackoverflow.com/comment/121672003
has comment: http://stackoverflow.com/comment/121606386
upvote count: 328
type: Answer
accepted answer of: http://stackoverflow.com/q/51433378

http://stackoverflow.com/comment/89826422
has text: I've posted the code below and put lookup_num to good use. Check it out.
comment on: http://stackoverflow.com/q/51405822
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/51339946
has comment: http://stackoverflow.com/comment/89653351
tagged with: python
has answer: http://stackoverflow.com/a/51340194
has comment: http://stackoverflow.com/comment/89653597
has comment: http://stackoverflow.com/comment/89653748
has comment: http://stackoverflow.com/comment/89653538
accepted answer: http://stackoverflow.com/a/51340194
tagged with: file
downvote count: 1
has body: I'm trying to read binary file with encryption key and load it to ciphertable (always 64bytes to 8x8 table). Tried to google without results. I'm sure the solution is simple but I can't find what I'm doing wrong. Error: self.cphtbl[i][j] = int.from_bytes(byte, byteorder = 'big') TypeError: 'int' object does not support item assignment My code: ... def createCipherTable(self): keyFile = open(self.keyFilePath, "rb") self.__cphtbl__ = [0,0,0,0,0,0,0,0] *8 for i in range(8): for j in range(8): byte = keyFile.read(1) self.__cphtbl__[i][j] = int.from_bytes(byte, byteorder = 'big') .... I also tried: int(from_bytes(byte, byteorder = 'big') but the output is: NameError: name 'from_bytes' is not defined Also tried: self.__cphtbl__[i][j].from_bytes(byte, byteorder = 'big') But then it says: TypeError: 'int' object is not subscriptable
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89653447
has comment: http://stackoverflow.com/comment/89653900
score: -1
has comment: http://stackoverflow.com/comment/89653709
has comment: http://stackoverflow.com/comment/89653782
has answer: http://stackoverflow.com/a/51340215
type: Question
has comment: http://stackoverflow.com/comment/89653409
answer count: 2
has comment: http://stackoverflow.com/comment/89653965
upvote count: 0
has title: From binary file to int Python
possible better answer: http://stackoverflow.com/a/51340215
favorite count: 0
has comment: http://stackoverflow.com/comment/89653638
has comment: http://stackoverflow.com/comment/89653670

http://stackoverflow.com/comment/89786850
has text: Tkinter has a lot of cross platform problems (including, but not limited to the fact that it WILL NOT RUN on macosx). There are problems porting Tkinter into executables because the windows remain and do not play nicely with the rest of the application. Consider using easygui or some other gui replacement with better stability.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51406763
type: Comment

http://stackoverflow.com/comment/89799293
type: Comment
comment on: http://stackoverflow.com/a/51413828
score: 0
type: AnswerComment
has text: It is still giving me an error saying "unable to locate element"

http://stackoverflow.com/comment/95927822
score: 1
has text: No such directory exists in OpenCV 3.1.0 nor 4.0.0-alpha obtained at https://sourceforge.net/projects/opencvlibrary/files
comment on: http://stackoverflow.com/a/51468634
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89836592
has text: Of course there is, even if you have to read [Microsoft's tough documentation](https://msdn.microsoft.com/en-us/library/cc313153(v=office.12).aspx) on the Word format. But such an answer would be *far* too long for Stack Overflow... FYI, I wrote my own OLE-wrapper a while ago and adjusting it for Word's `WordDocument` stream gave me `This text is a test @ ánti çSã GO.ΣΗΜΕΙΩΣΗ ...` (etc.) so yeah, it is *definitely* possible.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51411434
type: Comment

http://stackoverflow.com/comment/89684913
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51356360
type: AnswerComment
has text: the question specifically says changing the c++ source code is impossible

http://stackoverflow.com/q/51335013
has answer: http://stackoverflow.com/a/51335313
has comment: http://stackoverflow.com/comment/89645391
accepted answer: http://stackoverflow.com/a/51335313
linked to: http://stackoverflow.com/q/12485718
has body: I am running a parser file to parse files from .txt files from a local directory. Now these files are moved to HDFS cluster and I would like to configure my Pycharm to access the HDFS cluster. Can someone assist me in doing this?
score: 0
answer count: 1
tagged with: hdfs
tagged with: python
has comment: http://stackoverflow.com/comment/89645420
type: AnsweredQuestion
has title: Parse HDFS Files from Pycharm
type: Question
tagged with: hadoop

http://stackoverflow.com/q/51338028
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52097467
has body: Currently my dataframe looks something similar to: ID Year Str1 Str2 Value 0 1 2014 high black 120 1 1 2015 high blue 20 2 2 2014 medium red 10 3 2 2014 medium blue 50 4 3 2015 low blue 30 5 3 2015 high blue .5 6 3 2015 high red 10 Desired: ID Year Str1 Str2 Value 0 1 2014 high black 120 1 1 2015 high blue 20 2 2 2014 medium red, blue 60 3 3 2015 low, high blue, red 40.5 Trying to group by columns ID and Name, then getting sum of the numbers but a list of the strings. If removing duplicate strings is possible as in the example, that'd be helpful but not necessary. This operation will be done to ~100 dataframes, ID and Year are the only column names which can be found in every dataframe. The dataframes do vary slightly: they have either value column, str columns or both. I have browsed stackoverflow a lot and tried: df.groupby(['ID', 'Year'], as_index=False).agg(lambda x: x.sum() if x.dtype=='int64' else ', '.join(x)) Which gave the error DataFrame object has no attribute dtype (which makes sense, since grouping by multiple columns returns more dataframes). I also tried looping the columns one by one, and then if column has numbers, it would count the sum, else make a list: for col in df: if col in ['ID', 'Year']: continue if df[col].dtype.kind == 'i' or df[col].dtype.kind == 'f': df = df.groupby(['ID', 'Year'])[col].apply(sum) else: df = df.groupby(['ID', 'Year'])[col].unique().reset_index() However, after doing the operation the first time, it got rid of all the other columns. Thanks in advance.
has answer: http://stackoverflow.com/a/52097467
answer count: 2
accepted answer: http://stackoverflow.com/a/51338058
downvote count: 0
favorite count: 0
has title: Python pandas groupby multiple columns, creating list of strings but summing numbers
linked to: http://stackoverflow.com/q/19900202
tagged with: pandas-groupby
tagged with: pandas
tagged with: python
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/51338058
type: Question

http://stackoverflow.com/comment/89871332
type: QuestionComment
comment on: http://stackoverflow.com/q/51449242
has text: im getting a key error on 'LAST_NAME' even though it is a column
score: 0
type: Comment

http://stackoverflow.com/q/51352179
has comment: http://stackoverflow.com/comment/89707728
has answer: http://stackoverflow.com/a/51354576
tagged with: sqlite
answer count: 1
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/46712393
tagged with: python
accepted answer: http://stackoverflow.com/a/51354576
type: AnsweredQuestion
has title: How to create a SQLite Table with a JSON column using SQLAlchemy?
upvote count: 3
tagged with: http://stackoverflow.com/tag/json
tagged with: sqlalchemy
type: Question
score: 3
has body: According to this answer SQLite supports JSON data since version 3.9. I use version 3.24 in combination with SQLALchemy (1.2.8) and Python 3.6, but I cannot create any tables containing JSON columns. What am I missing or doing wrong? A minimal (not) working example is given below: import sqlalchemy as sa import os import tempfile metadata = sa.MetaData() foo = sa.Table( 'foo', metadata, sa.Column('bar', sa.JSON) ) tmp_dir = tempfile.mkdtemp() dbname = os.path.join(tmp_dir, 'foo.db') engine = sa.create_engine('sqlite:////' + dbname) metadata.bind = engine metadata.create_all() This fails giving the following error: sqlalchemy.exc.CompileError: (in table 'foo', column 'bar'): Compiler &lt;sqlalchemy.dialects.sqlite.base.SQLiteTypeCompiler object at 0x7f1eae1dab70&gt; can't render element of type &lt;class 'sqlalchemy.sql.sqltypes.JSON'&gt; Thanks!

http://stackoverflow.com/comment/89717066
has text: Sure, please post if you find something different. Thanks.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51353616
score: 1

recaptcha
tag name: recaptcha
tags question: http://stackoverflow.com/q/51434467
type: Tag

http://stackoverflow.com/comment/89663761
type: QuestionComment
has text: The issue isn't your modifications. The unmodified code from the 2013 edition of the book (using the command in the book) gives the same error.
comment on: http://stackoverflow.com/q/51344943
score: 1
type: Comment

axes
tag name: axes
tags question: http://stackoverflow.com/q/51432598
type: Tag
tags question: http://stackoverflow.com/q/51382053

http://stackoverflow.com/q/51477729
has answer: http://stackoverflow.com/a/51477887
has answer: http://stackoverflow.com/a/51478021
type: Question
has title: create multiple objects in a for loop
tagged with: keras
tagged with: lstm
has answer: http://stackoverflow.com/a/51477810
accepted answer: http://stackoverflow.com/a/51477810
possible better answer: http://stackoverflow.com/a/51477887
downvote count: 0
favorite count: 0
upvote count: 2
has body: I want to create multiple objects in a for loop. My code is like this: regressor1 = Sequential() # Adding the first LSTM layer and some Dropout regularisation regressor1.add(LSTM(units = 50, return_sequences = True, input_shape = (X_train.shape[1], 6))) regressor1.add(Dropout(0.2)) regressor2 = Sequential() # Adding the first LSTM layer and some Dropout regularisation regressor2.add(LSTM(units = 50, return_sequences = True, input_shape = (X_train.shape[1], 6))) regressor2.add(Dropout(0.2)) . . . regressor20 = Sequential() # Adding the first LSTM layer and some Dropout regularisation regressor20.add(LSTM(units = 50, return_sequences = True, input_shape = (X_train.shape[1], 6))) regressor20.add(Dropout(0.2)) How do i do this in a for loop? Thanks for your help.
has answer: http://stackoverflow.com/a/51477884
tagged with: python
answer count: 4
type: AnsweredQuestion
score: 2

http://stackoverflow.com/q/51430675
has answer: http://stackoverflow.com/a/51430914
has comment: http://stackoverflow.com/comment/89834951
downvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: django
upvote count: 1
tagged with: python
has title: Program Doesnt Print the Correct CSV Output
score: 1
has comment: http://stackoverflow.com/comment/89857412
type: Question
has body: I'm using Django to develop a web app for users to upload 2 different csv files, then the web app finds those differences, mark the differences respectively, and then print it as an output. When I run the code, it doesnt give me the correct output. Here is views.py from django.shortcuts import render from django.http import HttpResponse import difflib import datetime import csv from django.http import HttpResponseRedirect from django.http import FileResponse from .forms import FileForm from .forms import UploadFileForm def handle_uploaded_file(file1,file2): # handle_uploaded_file is a function that takes 2 files uploaded by the users fileone = file1.readlines() # define fileone and read lines from 1st file filetwo = file2.readlines() # define filetwo and read lines from 2nd file fileone =[line.decode("utf-8").strip() for line in fileone] filetwo =[line.decode("utf-8").strip() for line in filetwo] csv_old = csv.reader(fileone, delimiter=',') count = 0 header = next(csv_old) old_data = {} for row in csv_old: old_data[count] = row count += 1 csv_new = csv.reader(filetwo, delimiter=',') count = 0 header = next(csv_new) new_data = {} for row in csv_new: new_data[count] = row count += 1 set_new_data = set(new_data) set_old_data = set(old_data) added = [['Added'] + new_data[v] for v in set_new_data - set_old_data] deleted = [['Deleted'] + old_data[v] for v in set_old_data - set_new_data] in_both = set_old_data &amp; set_new_data changed = [['Changed'] + new_data[v] for v in in_both if old_data[v] != new_data[v]] with open('results.csv', 'w', newline='') as f_output: csv_output = csv.writer(f_output, delimiter=',') csv_output.writerow(['History'] + header) csv_output.writerows(sorted(added + deleted + changed, key=lambda x: x[1:])) def index(request): # index is a function for the upload button if request.method == 'POST': # POST method inserts something to the server print(request.FILES) form = UploadFileForm(request.POST, request.FILES) print(form.errors) if form.is_valid…

http://stackoverflow.com/comment/89883008
type: Comment
comment on: http://stackoverflow.com/q/51456472
type: QuestionComment
score: 0
has text: can you define: *Large dataset* ?

http://stackoverflow.com/a/51410395
has comment: http://stackoverflow.com/comment/89792342
accepted answer of: http://stackoverflow.com/q/51410272
score: 1
answers question: http://stackoverflow.com/q/51410272
has comment: http://stackoverflow.com/comment/89792558
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: You simply need to use plot_date from matplotlib. from matplotlib.dates import YearLocator, MonthLocator, DateFormatter years = YearLocator() # every year months = MonthLocator() # every month monthsFmt = DateFormatter('%b') Then fig, ax = plt.subplots() ax.plot_date(df1.index, df1[0], '-') ax.plot_date(df2.index, df2[0], '-') ax.xaxis.set_major_locator(months) ax.xaxis.set_major_formatter(monthsFmt) ax.xaxis.set_minor_locator(months) ax.autoscale_view() Output:
downvote count: 0

http://stackoverflow.com/a/51357800
has body: start_value = foo[0] start_position = 0 for entry in range(1, len(foo)): if start_value == foo[entry]: pass else: print(str(start_position+1) + " - " + str(entry) + " = " + start_value) start_value = foo[entry] start_position = entry
type: Answer
answers question: http://stackoverflow.com/q/51357333
score: 0

http://stackoverflow.com/q/51353604
has body: I was trying to get a set of images for a dataset to train tiny-yolo on so I followed this tutorial https://www.youtube.com/watch?v=Lg4T9iJkwhE&amp;index=5&amp;list=PLX-LrBk6h3wSGvuTnxB2Kj358XfctL4BM The first file that was written in the tutorial goes like this: import os import urllib.request as ulib from bs4 import BeautifulSoup as Soup import json url_a = 'https://www.google.com/search?ei=1m7NWePfFYaGmQG51q7IBg&amp;hl=en&amp;q={}' url_b = '\&amp;tbm=isch&amp;ved=0ahUKEwjjovnD7sjWAhUGQyYKHTmrC2kQuT0I7gEoAQ&amp;start={}' url_c = '\&amp;yv=2&amp;vet=10ahUKEwjjovnD7sjWAhUGQyYKHTmrC2kQuT0I7gEoAQ.1m7NWePfFYaGmQG51q7IBg' url_d = '\.i&amp;ijn=1&amp;asearch=ichunk&amp;async=_id:rg_s,_pms:s' url_base = ''.join((url_a, url_b, url_c, url_d)) headers = {'User-Agent': 'Chrome/67.0.3396.99 Safari/537.36'} def get_links(search_name): search_name = search_name.replace(' ', '+') url = url_base.format(search_name, 0) request = ulib.Request(url, None, headers) json_string = ulib.urlopen(request).read() page = json.loads(json_string) new_soup = Soup(page[1][1], 'lxml') images = new_soup.find_all('img') links = [image['src'] for image in images] return links def save_images(links, search_name): directory = search_name.replace(' ', '_') if not os.path.isdir(directory): os.mkdir(directory) for i, link in enumerate(links): savepath = os.path.join(directory, '{:06}.png'.format(i)) ulib.urlretrieve(link, savepath) if __name__ == '__main__': search_name = 'my search query' links = get_links(search_name) save_images(links, search_name) The only thing I changed was the headers variable since my User-agent is different than the guy in the tutorial's one. To my supprise the script returned this error urllib.error.HTTPError: HTTP Error 400: Bad Request Can anyone tell me what's wrong?
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89681094
has answer: http://stackoverflow.com/a/51354310
has title: urllib.error.HTTPError: HTTP Error 400: Bad Request from trying to get a set of images
type: Question
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89681110
score: 1

http://stackoverflow.com/comment/110469625
comment on: http://stackoverflow.com/a/51456885
has text: This method is extremely effective, but involves handling all of the OAuth backend. It also offers a great deal more functionality and allows access to almost all Drive functions. The file stream and extended attributes of NT/OS X are significantly easier to manage as the File Stream application manages all of the OAuth flow.
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89680624
type: AnswerComment
comment on: http://stackoverflow.com/a/51354040
type: Comment
has text: Woot, the latter solution worked for me! Thanks a lot. Would you be able to explain what might have been the issue and how openssl solved it?
score: 0

http://stackoverflow.com/comment/89927371
has text: @Divakar This is not a duplicate of the marked question, because the other question has the special constraint that it must not use `np.matmul` or `np.einsum`. I'm looking for the most basic standard solution without such specific constraints.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51479148

http://stackoverflow.com/comment/89637505
type: AnswerComment
has text: I tried this and got the error: `django.db.utils.OperationalError: no such table: Monitor_monitoredcomponent`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51330889

http://stackoverflow.com/comment/89848478
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51439167
has text: if you do a `df.values` it will give a nice numpy array as you want it to. df here is the name of the pandas dataframe.

http://stackoverflow.com/a/51391571
answers question: http://stackoverflow.com/q/51391488
score: 0
has body: You can call plt.autoscale() such that the limits are adjusted to the content of the axes. Example: import numpy as np import matplotlib.pyplot as plt def get(offs=0): # Generate some test data x = np.random.randn(8873)+offs y = np.random.randn(8873)+offs heatmap, xedges, yedges = np.histogram2d(x, y, bins=50) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] heatmap, xedges, yedges = np.histogram2d(x, y, bins=50) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] return heatmap, extent h1,e1 = get(-3) h2,e2 = get(+3) plt.imshow(h1, extent=e1, origin='lower', cmap="RdBu") plt.imshow(h2, extent=e2, origin='lower', cmap="YlGnBu") plt.autoscale() plt.show()
type: Answer
has comment: http://stackoverflow.com/comment/89755148

http://stackoverflow.com/q/51343085
tagged with: typeerror
has comment: http://stackoverflow.com/comment/89660312
tagged with: python
accepted answer: http://stackoverflow.com/a/51345146
type: AnsweredQuestion
has title: TypeError: unsupported format string passed to Member.__format__
upvote count: 1
type: Question
has body: server = ctx.message.server msg = "" if server.id not in self.slowed_db: await self.bot.say(error("There isn't anyone in Slow Mode in this server.")) return names = [server.get_member(x).name for x in self.slowed_db[server.id]] names_len = len(max(names, key=len)) for key, value in self.slowed_db[server.id].items(): try: member = server.get_member(key) msg += "{:&lt;{names_len}} {}\n".format(member, value['seconds'], names_len=names_len) except AttributeError: # User isn't in server continue if msg: await self.bot.say(box(msg, lang="css")) else: await self.bot.say(error("There isn't anyone in Slow Mode in this server.")) return Can anyone explain why this doesn't work? The error is on this line: msg += "{:&lt;{names_len}} {}\n".format(member, value['seconds'], names_len=names_len) names_len prints just fine as an integer so I'm very confused.
has answer: http://stackoverflow.com/a/51345146
answer count: 1
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/comment/89783325
has text: So other then this, there is no way to run a "first command"?
type: AnswerComment
comment on: http://stackoverflow.com/a/51405676
score: 0
type: Comment

http://stackoverflow.com/comment/89672036
comment on: http://stackoverflow.com/q/51345904
score: 0
type: Comment
type: QuestionComment
has text: @PM2Ring your answer's great. When I left the link, I was hoping to see if the community think if it's a dupe if not, a relevant post. I guess the verdict (at least by two other voters) was it's a close-enough dupe. Feel free to spark a reopen vote:)

http://stackoverflow.com/comment/131375374
type: Comment
comment on: http://stackoverflow.com/a/72584888
type: AnswerComment
has text: Awesome library!
score: 3

http://stackoverflow.com/a/51406025
downvote count: 0
has body: The package is simply broken, as it is missing the setup.py file. $ tar tzvf behave-parallel-1.2.4a1.tar.gz | grep setup.py $ You might be able to download the source from Github or wherever and package it yourself (python setup.py bdist_wheel), then install that wheel (pip install ../../dist/behave-parallel...whl).
upvote count: 8
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51405580
answers question: http://stackoverflow.com/q/51405580
type: Answer
score: 8

http://stackoverflow.com/comment/89655138
score: 0
type: AnswerComment
has text: You didn't complete your comment and I mistakenly upvoted it :)
comment on: http://stackoverflow.com/a/51340571
type: Comment

http://stackoverflow.com/comment/89813882
has text: @gyx-hh, thank you. I have added sample CSV data to the end of the post. (I didn't see how to attach a CSV file here, but perhaps you can copy-paste into e.g. TextEdit and save it as CSV.) I would very much appreciate learning better code. (I am essentially out of time and trying both to learn and code as quickly as possible.) I will try to resume working on this -- and come back here to check for new responses -- in about 12 hours.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51414262
type: Comment

http://stackoverflow.com/q/51420456
favorite count: 0
tagged with: python-3.x
has body: I need to generate fixed length, no collisions identifiers based on varying in length input strings (hundreds of unique inputs). The ids need to be deterministic as identified objects will be accessed later knowing only the input strings. I could use simply MD5, SHA-1 hashing but was wondering if there is a simple or better way to solve this?
tagged with: hash
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89812152
has title: Generate a fixed length, deterministic identifiers from strings
tagged with: python
has comment: http://stackoverflow.com/comment/89812426
has comment: http://stackoverflow.com/comment/89812188
score: 2
has comment: http://stackoverflow.com/comment/89811855
answer count: 0
upvote count: 3
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89814067
has comment: http://stackoverflow.com/comment/89812621
has comment: http://stackoverflow.com/comment/89811994
has comment: http://stackoverflow.com/comment/89812463
has comment: http://stackoverflow.com/comment/89812305
has comment: http://stackoverflow.com/comment/89812693

http://stackoverflow.com/a/51362240
score: 1
has comment: http://stackoverflow.com/comment/89710654
has comment: http://stackoverflow.com/comment/89714295
has body: The function have to be the entire flow calculation (unless there is some constant part, but this depend on the formula you use). The function have to be defined using a regular python function. It has to be a function of one argument only. If there is additional parameters, you could use the option args=(param1, param2) for example: def cash_flow_calculation(p, param1, param2): # compute the cash_flow return cash_flow p_start = 0 param1, param2 = 4, 5 p_min = minimize(cash_flow_calculation, p_start, method='BFGS', options={ 'maxiter': 1000}, args=(param1, param2))
accepted answer of: http://stackoverflow.com/q/51352538
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89710915
type: Answer
has comment: http://stackoverflow.com/comment/89726509
upvote count: 1
answers question: http://stackoverflow.com/q/51352538

http://stackoverflow.com/q/51364741
tagged with: odoo-10
score: 2
downvote count: 0
tagged with: http://stackoverflow.com/tag/xml
favorite count: 0
type: Question
upvote count: 2
tagged with: python
answer count: 1
has body: I'm trying to make a filter in a search view with a domain depending on the attribute of a specific record, whose XML ID I have. The problem is that I don't know how to get the object and use its attribute in that situation. This is what I want, but it throws the error "ref unknown": &lt;filter string="My filter" name="my_filter" domain="[('my_field','=',ref('my_module.my_xml_id').name)]"/&gt; Using %(my_module.my_xml_id)d isn't a valid option since I can't get the attribute of an integer and I need the name of the object. So I was wondering if there's a better solution than creating a stored computed field in the model to have the name available in the filters. It would be awful because I would be storing the same value in each record... Any ideas? Thank you!
has answer: http://stackoverflow.com/a/60710516
tagged with: odoo
has title: How to emulate "self.env.ref" in the domain of a search view in Odoo 10?
type: UnansweredQuestion

http://stackoverflow.com/q/51414775
tagged with: python-3.x
downvote count: 0
type: UnansweredQuestion
has body: I have a csv file that contains data that has each days data split into a separate column. 'Time', 'Sun 01', 'Mon 02', 'Tue 03', 'Wed 04', 'Thu 05', 'Fri 06', 'Sat 07', 'Sun 08', 'Mon 09', 'Tue 10', 'Wed 11', 'Thu 12', 'Fri 13', 'Sat 14', 'Sun 15', 'Mon 16', 'Tue 17', 'Wed 18', 'Thu 19', 'Fri 20', 'Sat 21', 'Sun 22', 'Mon 23', 'Tue 24', 'Wed 25', 'Thu 26', 'Fri 27', 'Sat 28', 'Sun 29', 'Mon 30' '00:00-00:05', '0.30', '0.30', '0.30', '0.30', '0.30', '0.40', '0.10', '0.20', '0.20', '0.20', '0.10', '0.20', '0.20', '0.30', '0.30', '0.10', '0.20', '0.20', '0.10', '0.10', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.20', '0.10', '0.10' '00:05-00:10', '0.30', '0.30', '0.30', '0.30', '0.30', '0.50', '0.20', '0.10', '0.10', '0.20', '0.10', '0.30', '0.10', '0.20', '0.30', '0.10', '0.20', '0.10', '0.20', '0.20', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.10', '0.10', '0.10' '00:10-00:15', '0.30', '0.30', '0.30', '0.30', '0.30', '0.40', '0.20', '0.20', '0.20', '0.20', '0.20', '0.30', '0.10', '0.30', '0.30', '0.20', '0.10', '0.20', '0.10', '0.10', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.20', '0.20', '0.10' '00:15-00:20', '0.30', '0.30', '0.30', '0.30', '0.40', '0.50', '0.10', '0.10', '0.10', '0.20', '0.10', '0.30', '0.20', '0.30', '0.30', '0.10', '0.20', '0.20', '0.20', '0.20', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.10', '0.10', '0.00' '00:20-00:25', '0.30', '0.30', '0.40', '0.40', '0.30', '0.40', '0.20', '0.20', '0.20', '0.20', '0.10', '0.30', '0.10', '0.30', '0.30', '0.10', '0.20', '0.10', '0.20', '0.10', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '0.20', '0.10', '0.20' Using python, is there a way to rearrange the data so that each days data is added to the end of the previous days data having one long collumn? Example: Date, Time, Value, 01-01-2000, 00:00, 0.01 01-01-2000, 00:00, 0.01 01-01-2000, 00:05, 0.01 01-01-2000, 00:10, 0.01 02-01-2000, 00:00, 0.01 02-01-2000, 00:05, 0.01 02-01-2000, 00:…
linked to: http://stackoverflow.com/q/47152691
has comment: http://stackoverflow.com/comment/89801682
has title: Rearranging .csv data using Python
tagged with: format
score: 1
has comment: http://stackoverflow.com/comment/89892269
has answer: http://stackoverflow.com/a/51415653
type: Question
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/89895149
duplicate of: http://stackoverflow.com/q/47152691
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python

http://stackoverflow.com/comment/89671785
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51343961
has text: Yes I have seen that GitHub issue. I checked my pip.py file and all of the mentions of https are there instead of http like they said in the issue. My error only occurs when I try to install discord.py[voice]. I have used it to install the basic discord.py module but I want the full voice support as well.

http://stackoverflow.com/comment/89764285
has text: Can you accept the answer by clicking the tick if it solves your problem?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51361461
score: 0

http://stackoverflow.com/comment/89877077
comment on: http://stackoverflow.com/q/51453650
score: 0
has text: Same as any other class
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89821751
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51423194
has text: @Harry Maguire if the code generates the dataframe, you could adjust the generation process to not create a header. But I can't help you on that without seing what you are doing. Also, what exactly is the error that you get when running my code?

http://stackoverflow.com/comment/89930775
comment on: http://stackoverflow.com/q/51480392
score: 0
type: QuestionComment
type: Comment
has text: Note that in your code ``Employee`` overrides ``__init__``, whereas in your reference ``Booking`` does not.

http://stackoverflow.com/q/51369917
type: UnansweredQuestion
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/89712254
has comment: http://stackoverflow.com/comment/89712094
type: Question
upvote count: 0
score: -1
tagged with: java-io
has comment: http://stackoverflow.com/comment/89712457
has title: Error installing java package in Python
answer count: 1
favorite count: 0
has body: I need to use for a project the java.io package in a Python environment, but I am encountering this error while trying to install it: Collecting java Cache entry deserialization failed, entry ignored Could not find a version that satisfies the requirement java (from versions: ) No matching distribution found for java Image of the error: here
has answer: http://stackoverflow.com/a/51371737

http://stackoverflow.com/comment/89658435
has text: Show where you're calling `print(conn.recv(1024))` in relation to the code you posted as a [mcve]. If you're calling it from a different function, it won't be in scope.
comment on: http://stackoverflow.com/q/51342544
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/q/51369419
has body: I have a data set of 5 classes each with roughly 100 256x256 images. The code is mildly altered from the basic pytorch tutorials. Using vgg16 I get an accuracy of 77% for the classification. Then I switch the architecture to do regression by the following line of code: model_ft.classifier[6] = nn.Linear(4096, 1) Doing so I get a binned accuracy of 56% by rounding classification scores. Additionally I switch my loss to MSE resulting in a loss of .2698 . Are there any ideas why the regression performs worse than the classification model? In depth Code Snippet: from __future__ import print_function, division import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler from torch.autograd import Variable import torchvision import numpy as np from torchvision import datasets, models, transforms import matplotlib.pyplot as plt import time import os import copy import argparse import transfer_learning_depths import vgg_r plt.ion() # interactive mode ############################################################################### def labelToConts(target): """ 'continous' classes- normalizes classes 0,1,2,3,4 to the domain [0,1] """ target = target.numpy().astype(float) for i in range(0,target.size): #target[i] = math.floor((target[i] - 2)/2) for neg classes? target[i] = ((target[i])/4) #print(target[i]) target = torch.from_numpy(target) return target ############################################################################### """my accuracy metric""" def my_correct(outputs,labels): outputs_4 = outputs * 4 outputs_4 = torch.round(outputs_4) outputs_4 = outputs_4 / 4 return torch.sum(outputs_4 == labels.data.float()) ############################################################################### def train_model_classify(model,optimizer, scheduler, args): since = time.time() criterion = nn.CrossEntropyLoss() best_model_wts = copy.deepcopy(model.state_dict()) #keep track of best model? best_acc = 0.0 for epoch in range(args.epochs): prin…
type: UnansweredQuestion
tagged with: python
tagged with: conv-neural-network
tagged with: pytorch
tagged with: machine-learning
type: Question
score: 0
has answer: http://stackoverflow.com/a/51371768
answer count: 1
has title: convnet better classification than regression performance

http://stackoverflow.com/comment/89845423
score: 0
comment on: http://stackoverflow.com/q/51437654
type: Comment
type: QuestionComment
has text: In the script they are imported yes . It is obvious that the issue is steps earlier since they are not recognised in the cmd at all as you can see from the code existing in the question

http://stackoverflow.com/a/51405972
type: Answer
accepted answer of: http://stackoverflow.com/q/51405913
score: 5
upvote count: 5
answers question: http://stackoverflow.com/q/51405913
type: AcceptedAnswer
downvote count: 0
has body: For the case of 2 names, you can use str.join with reversed and str.split: ex1 = 'John Doe' ex2 = ', '.join(reversed(ex1.split())) # 'Doe, John' You can also use f-strings (Python 3.6+) via an anonymous function: ex2 = (lambda x: f'{x[1]}, {x[0]}')(ex1.split()) # 'Doe, John' It's not clear what you'd like to see for multiple names, e.g. if middle names are provided.

http://stackoverflow.com/comment/89659867
type: Comment
score: 1
has text: If the timestamp is supposed to be the current time, just get it from within the Python script.
comment on: http://stackoverflow.com/q/51343230
type: QuestionComment

http://stackoverflow.com/q/51363120
possible better answer: http://stackoverflow.com/a/51363417
has body: I'm trying to add 1 to the count each time there's a new letter and keep track of the doubled letters, but python isn't going into the if statement, despite line 6 showing the conditions for the if statement are met. What am I missing? def duplicate_count(text): count = 0 doubled_letters = [] for i in text: print (i) print(i in doubled_letters) if i in doubled_letters == False: count += 1 doubled_letters.append(i) print(count) print(doubled_letters) return count duplicate_count("abbcdea") this returns: a False b False b False c False d False e False a False 0 []
has answer: http://stackoverflow.com/a/51363417
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/51363175
tagged with: if-statement
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51363175
type: Question
tagged with: python
linked to: http://stackoverflow.com/q/24842852
has title: Python if statement not recognized though conditions appear to be met

http://stackoverflow.com/q/51331102
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/89637943
has answer: http://stackoverflow.com/a/51331165
tagged with: arrays
answer count: 3
downvote count: 0
favorite count: 0
tagged with: operators
accepted answer: http://stackoverflow.com/a/51331165
has body: Input: dt = [6,7,8,9,10] data = [1,2,3,4,5] b = 8.0 b = np.require(b, dtype=np.float) data += dt &lt; b data Output: array([2, 3, 3, 4, 5]) I tried to input different number but still couldn't figure out what's the "&lt;" doing there.... Also, it seems to work only when b is np.float (hence the conversion).
has answer: http://stackoverflow.com/a/51331980
tagged with: python
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/51333307
has title: What is the '<' doing in this line?: data += dt < b
upvote count: 3
has answer: http://stackoverflow.com/a/51333307

http://stackoverflow.com/comment/89893059
type: QuestionComment
has text: Simply run aggregation. No loops needed.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51452279

http://stackoverflow.com/comment/89847172
type: QuestionComment
has text: I've already tried them but numpy-stl and python-stl don't have method to cut .stl files. Pymesh has it (not 100% sure), but I can't install it in PyCharm (don't know why)
comment on: http://stackoverflow.com/q/51437280
score: 0
type: Comment

http://stackoverflow.com/comment/89746880
type: QuestionComment
has text: Alternatively, if you know the modules work on both py2 and py3 then you could just add the modules and not the entire py3 instillation.
comment on: http://stackoverflow.com/q/51387408
score: 0
type: Comment

http://stackoverflow.com/a/51471986
type: Answer
answers question: http://stackoverflow.com/q/51471848
score: 0
has body: You need to call loop.run_until_complete(main()), not just a function main (without parenthesis). The next thing is you don't need async keyword in soup.select(). I also changed a select string, to parse something: import requests from bs4 import BeautifulSoup import asyncio import aiohttp res = requests.get('https://www.rottentomatoes.com/top/') soup = BeautifulSoup(res.text,'lxml') movie_list=[] for link in soup.select('section li a[href]'): movie_list.append('https://www.rottentomatoes.com'+link.get('href')) async def request(url): async with aiohttp.ClientSession() as session: async with session.get(url) as resp: body = await resp.text(encoding='utf-8') soup = BeautifulSoup(body,'lxml') movie = [] # no need to call async for here! for link in soup.select('section#top_movies_main table a'): movie.append(link['href']) return movie async def main(): results = await asyncio.gather(*[request(url) for url in movie_list]) print(results) return results print(movie_list) loop = asyncio.get_event_loop() results = loop.run_until_complete(main()) # you need to create coroutine Prints: ['https://www.rottentomatoes.com/top/bestofrt/top_100_action__adventure_movies/', 'https://www.rottentomatoes.com/top/bestofrt/top_100_animation_movies/', 'https://www.rottentomatoes.com/top/bestofrt/top_100_art_house__international_movies/', 'https://www.rottentomatoes.com/top/bestofrt/top_100_classics_movies/', 'https://www.rottentomatoes.com/top/bestofrt/top_100_comedy_movies/', 'https://www.rottentomatoes.com/top/bestofrt/top_100_documentary_movies/', 'https://www.rottentomatoes.com/top/bestofrt/top_100_drama_movies/', 'https://www.rottentomatoes.com/top/bestofrt/top_100_horror_movies/', 'https://www.rottentomatoes.com/top/bestofrt/top_100_kids__family_movies/', 'https://www.rottentomatoes.com/top/bestofrt/top_100_musical__performing_arts_movies/', 'https://www.rottentomatoes.com/top/bestofrt/top_100_mystery__suspense_movies/', 'https://www.rottentomatoes.com/top/bestofrt/top_100_romance_m…

http://stackoverflow.com/a/51375633
has body: Ok so here is what is my test script: print("original sys.argv output\n" + (sys.argv[1])) string_temp=(yaml.load(sys.argv[1])) print ("first transformation\n" +string_temp) string_temp=string_temp.replace(":",": ") dict_in=yaml.load(string_temp) print("This is the dictionary") print(dict_in) This is what I type into the console python test_script.py """{foo:bar, id:23}""" And This is the output original sys.argv output "{foo:bar, id:23}" first transformation {foo:bar, id:23} This is the dictionary {'foo': 'bar', 'id': 23} This only workds if I use tripple quotes ("""). If I use (") or (') to define the input string I get an error. Alternatively one can remove the (") from the sys.argv[1] print("original sys.argv output\n" + (sys.argv[1])) string_temp=(sys.argv[1])[1:-1] print ("first transformation\n" +string_temp) string_temp=string_temp.replace(":",": ") dict_in=yaml.load(string_temp) print("This is the dictionary") print(dict_in)
answers question: http://stackoverflow.com/q/51328566
score: 0
type: Answer

http://stackoverflow.com/q/51435407
answer count: 1
tagged with: keyword-argument
tagged with: variables
favorite count: 0
has answer: http://stackoverflow.com/a/51435444
linked to: http://stackoverflow.com/q/36901
has title: Using Variable as Keyword Argument for Function
tagged with: python
tagged with: parameter-passing
type: AnsweredQuestion
downvote count: 0
score: 1
has body: I have the following piece of code: quantity_of_units = int(funding_time_left.split[0]) unit_of_measurement = funding_time_left.split()[1] now = datetime.datetime.now() if unit_of_measurement == 'days': end = (now + timedelta(days=quantity_of_units)).strftime('%Y-%m-%d') elif unit_of_measurement == 'hours': end = (now + timedelta(hours=quantity_of_units)).strftime('%Y-%m-%d') else: # unit_of_measure == 'minutes' end = (now + timedelta(minutes=quantity_of_units)).strftime('%Y-%m-%d') funding.append([aeles.get_attribute('href'), end]) I was wondering if it is possible to use a variable (unit_of_measurement) as the keyword argument (days, hours, minutes)? If it is indeed possible, I could scrap the if elif else block altogether and turn it all into a single line. Below is what I'm hoping to do. quantity_of_units = int(funding_time_left.split[0]) unit_of_measurement = funding_time_left.split()[1] now = datetime.datetime.now() end = (now + timedelta(unit_of_measurement=quantity_of_units)).strftime('%Y-%m-%d') funding.append([aeles.get_attribute('href'), end])
type: Question
tagged with: function
accepted answer: http://stackoverflow.com/a/51435444
upvote count: 1

http://stackoverflow.com/comment/89845171
type: QuestionComment
has text: I could not attache it, so I put the dropbox link to download it. Hope it works
comment on: http://stackoverflow.com/q/51437280
score: 0
type: Comment

http://stackoverflow.com/a/51360810
answers question: http://stackoverflow.com/q/51358987
downvote count: 0
has comment: http://stackoverflow.com/comment/89697480
type: Answer
upvote count: 1
score: 1
has body: Look if you have pylint in /Users/erc/Library/Python/2.7/bin/. If yes — add the directory to your $PATH. If no — list files using pip show --files pylint.

http://stackoverflow.com/q/51405739
has comment: http://stackoverflow.com/comment/89782965
has comment: http://stackoverflow.com/comment/89783402
has comment: http://stackoverflow.com/comment/89820178
has comment: http://stackoverflow.com/comment/89820954
tagged with: python
has comment: http://stackoverflow.com/comment/89820340
has comment: http://stackoverflow.com/comment/89820756
answer count: 0
type: UnansweredQuestion
tagged with: pyside2
has comment: http://stackoverflow.com/comment/89820554
has body: I am converting a tool to Pyside2 and am using a QTableWidget. I need to retrieve the cell data, but am having an issue with understanding if I need to cast it to a python object (.toPyObject in PyQt4). In my old version table query, I had: item_text = item.text() item_data = item.data(QtCore.Qt.UserRole).toPyObject() Where item_text is the retrieval of the cell. I have looked through the docs and online, but have not found out if or what the PySide2 equivalent is. I saw some info relating to QVariant, but unclear if that is a substitute to use or if I have just overlooked something in the PySide2 docs.
has comment: http://stackoverflow.com/comment/89821111
type: Question
has comment: http://stackoverflow.com/comment/89819899
has title: PySide2, QTableWidget, data to python object
score: 0
has comment: http://stackoverflow.com/comment/89783205
has comment: http://stackoverflow.com/comment/89783669

http://stackoverflow.com/comment/89916614
type: QuestionComment
comment on: http://stackoverflow.com/q/51455027
has text: instead of `if request.method == 'POST'` try to use `if form.validate_on_submit()` (it will also check csrf)
score: 0
type: Comment

http://stackoverflow.com/comment/89644778
comment on: http://stackoverflow.com/a/51334501
has text: @GregSchmit, the problem is that I cannot provide a more specific answer since the one who asked the question is not providing further information. That is why I have added, _Assuming you are using Python 3.4+_
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51332396
answers question: http://stackoverflow.com/q/51331758
type: Answer
has body: def recursiveSort(sensor_list,n,t): #Recursive Sort if (n == 0): return sensor_list else: for i in range(n-1): if sensor_list[i][t] &gt; sensor_list[i + 1][t]: temp = sensor_list[i] sensor_list[i] =sensor_list[i + 1] sensor_list[i + 1] = temp return recursiveSort(sensor_list,n - 1,t) Dict = {'4213' : ('STEM Center', 0), '4201' : ('Foundations Lab', 1), '4204' : ('CS Lab', 2), '4218' : ('Workshop Room', 3), '4205' : ('Tiled Room', 4), 'out' : ('Outside', 5), } sensor_list=[] [ sensor_list.append((key,Dict[key][0],Dict[key][1])) for key in Dict ] #Adding values to a dictionary into a tuple using list comprehension print(sensor_list) print recursiveSort(sensor_list,len(sensor_list),0) print recursiveSort(sensor_list,len(sensor_list),1) print sensor_list
score: 0

http://stackoverflow.com/a/51415615
has comment: http://stackoverflow.com/comment/89803605
has comment: http://stackoverflow.com/comment/89803406
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51415383
answers question: http://stackoverflow.com/q/51415383
has body: There is problem d values are not numeric. So you can convert d column to timedeltas and then to seconds: df1['d'] = pd.to_timedelta(df1['d']).dt.total_seconds() print (df1) M d time 0 1081083 26200.0 2018-07-04 05:42:20 1 1081083 35800.0 2018-07-04 05:43:03 2 1081085 58200.0 2018-07-04 05:43:12 3 1081083 26200.0 2018-07-04 05:43:51 4 1081085 19800.0 2018-07-04 05:44:01 Or if possible omit: df1['d']=df1['d'].apply(lambda x: time.strftime("%H:%M:%S",time.localtime(x)))
type: Answer
has comment: http://stackoverflow.com/comment/89803223
downvote count: 0
has comment: http://stackoverflow.com/comment/89803810
has comment: http://stackoverflow.com/comment/89803552
has comment: http://stackoverflow.com/comment/89803715
score: 1

http://stackoverflow.com/comment/89677694
comment on: http://stackoverflow.com/q/51352359
has text: Thank you for the reply. Output is as in the dummy example. I'm expecting a new df column 'combined' with value returned from the function. Please advise if you know how to do this without apply.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89717895
type: QuestionComment
has text: @ReblochonMasque I am doing OCR from physical exam reports. As you know there will be lots of numeric data. They are recognized from Google Vision API as strings, but should be stored and presented to users as numbers. Since 40 and 40.0 can have different meanings in different tests, that's why I need this.
comment on: http://stackoverflow.com/q/51373015
score: 0
type: Comment

http://stackoverflow.com/q/51450573
downvote count: 0
has title: Why is there both a tf.round and a tf.rint function in tensorflow?
favorite count: 0
tagged with: python
upvote count: 4
type: UnansweredQuestion
tagged with: tensorflow
has body: Tensorflow has two functions to round a number to its closest integer, tf.round and tf.rint. As far as I can tell, those functions are doing the same thing, but they operate on different type sets, which makes none of them more general than the other (for example tf.rint can operate on tf.bfloat, while tf.round can operate on... tf.int32?!?). So, Why do we have two functions operating on different types rather than just one operating on all types? Why do we need a tf.round operating on tf.int32 and tf.int64 anyway?
has answer: http://stackoverflow.com/a/51450650
score: 4
has answer: http://stackoverflow.com/a/51450721
type: Question
answer count: 2

http://stackoverflow.com/comment/89653333
type: Comment
comment on: http://stackoverflow.com/a/51338217
has text: Like this: 1 Write short notes on the anatomy of the Circle of Willis including normal variants. 2 Write short notes on the anatomy of the axis (C2 vertebra).
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89821837
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51422559
type: Comment
has text: @EshaghMoutabi NumPy arrays are immutable. The value is appended to a copy of the original and returned but you are returning the `s` not the appended copy. Also I think you meant `math.exp(-i)` but not `-x`

http://stackoverflow.com/q/51423459
score: -1
tagged with: distribution
has comment: http://stackoverflow.com/comment/89819931
downvote count: 1
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51424448
has comment: http://stackoverflow.com/comment/89818512
accepted answer: http://stackoverflow.com/a/51424448
tagged with: random
answer count: 2
has comment: http://stackoverflow.com/comment/89818254
has comment: http://stackoverflow.com/comment/89818478
upvote count: 0
has body: 0I want to generate a random sequence of Integer numbers that I can somehow configure. I want the sequence to be configurable in terms of frequencies of appearance of certain numbers and the spacing between every two consecutive appearances. The numbers in my sequence are within a determined range. The idea is I want to have different sequences that have some patterns in them since I am interested in analyzing the impact of the pattern itself when taken as input for another program I wrote. could you please direct me to where I can find algorithms that can help me with this? I searched online, all I found is uniform distributions which is not what I want in this case. here I have the code I have for just my basic referential sequence but I don't know how to move from here. import random from random import randint f= open('Sequence.txt' , 'w+') random.seed() NumberOfVar = random.randint(10000, 100000) random.seed(3) NumberOfLines = random.randint(10000, 50000000) for Iterator in range(0, NumberOfLines): Var = random.randint(0, NumberOfVar) S = str(Var )+ "\n" f.write(S) f.close() thank you
has title: configurable sequence of Integer numbers
favorite count: 0
possible better answer: http://stackoverflow.com/a/51427196
has comment: http://stackoverflow.com/comment/89825566
has answer: http://stackoverflow.com/a/51427196
tagged with: python

http://stackoverflow.com/comment/89668523
has text: Or use `dict.setdefault` - ... `for topic in topics: result.setdefault(topic, []).append(year)`... which does exactly what your code is doing here... just more concisely...
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51347948
type: AnswerComment

http://stackoverflow.com/q/51354343
downvote count: 0
answer count: 1
score: 1
has title: Python - Abort current function without stop running tkinter mainloop
favorite count: 0
has body: I'm new in Python, if it is possible to realize abort immediately as in the following situation. Condition : 2 button : Start &amp; Abort When I press the Start button, the code should start to do a function, and if I press Abort button, the function will stop immediately no matter what it did, and become initial state (before pressing the Start button). Besides, I know "signal.CTRL_C_EVENT / CTRL_BREAK_EVENT", but it will close all code including Tkinter mainloop.
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89686366
tagged with: tkinter
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89806863
has comment: http://stackoverflow.com/comment/89707314
type: Question
has answer: http://stackoverflow.com/a/51367748

http://stackoverflow.com/comment/89894744
comment on: http://stackoverflow.com/q/51462548
has text: I agree that *I* can see the different paths, but it's not clear how the computer would know that. For example, you can draw a line from *any* of the points to the center; how does your program know that say, any of the points on the bottom path should go along the path at all? I'm not sure if it would work *in general* for any of your use cases, but if you can narrow down pictures that look this good typically, then the Euclidean minimum spanning tree should give you the exact tree you're looking for and the maximal node (most edges) would be the center. IIRC MST is linear, `O(n)`.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51360222
has body: You're assuming that both languages generate JSON that looks identical. &gt;&gt;&gt; json.dumps({"candidate" : 5, "data": 1}, sort_keys=True) '{"candidate": 5, "data": 1}' js&gt; JSON.stringify({"candidate" : 5, "data": 1}) "{\"candidate\":5,\"data\":1}" Fortunately, they can. &gt;&gt;&gt; a = json.dumps({"candidate" : 5, "data": 1}, sort_keys=True, indent=2) '{\n "candidate": 5,\n "data": 1\n}' js&gt; var a = JSON.stringify({"candidate" : 5, "data": 1}, null, 2) "{\n \"candidate\": 5,\n \"data\": 1\n}" And now the hashes would be same as well. Python: &gt;&gt;&gt; hashlib.md5(a.encode("utf-8")).hexdigest() &gt;&gt;&gt; d77982d217ec5a9bcbad5be9bee93027 JS: &gt;&gt;&gt; md5(a) &gt;&gt;&gt; d77982d217ec5a9bcbad5be9bee93027
upvote count: 49
downvote count: 1
accepted answer of: http://stackoverflow.com/q/51359943
has comment: http://stackoverflow.com/comment/126820555
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89693407
score: 48
type: Answer
answers question: http://stackoverflow.com/q/51359943

http://stackoverflow.com/a/51342909
score: 5
answers question: http://stackoverflow.com/q/51342774
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51342774
has body: Your code for flipping is correct (depends on how you want to perform your flip, but anyway) but you should create your img2 "outside" of your for loop only once. def flipv(imgg): img2= np.zeros([480, 640, 3], np.uint8) for i in range(480): img2[i,:]=imgg[480-i-1,:] return img2
has comment: http://stackoverflow.com/comment/89659237
type: Answer
upvote count: 5

http://stackoverflow.com/q/51345806
type: AnsweredQuestion
tagged with: python
score: 1
has body: I used scrapy to crawl several bullying forums and used the results as a dictionary. What I'm trying to do now is extracting the keywords of a sentence, e.g. He harassed me in the chat, which would give the keywords Harassed and chat, and comparing these keywords to my dictionary of words and assigning a value to how relevant it is (which in this case would obviously provide a high value close to 1.0 since it is extremely relevant to bullying). I've gotten the keyword extraction down, so right now I just need know how I can do the comparison. I've taken a look at using pandas, scikit and nltk but they seem to work best for dictionaries with multiple fields, whereas I only have a bag of words. Is there some NLP library out there that does this for me? If not, what would be the best way to go about this?
tagged with: nlp
favorite count: 0
has answer: http://stackoverflow.com/a/51347862
type: Question
has comment: http://stackoverflow.com/comment/89664690
has comment: http://stackoverflow.com/comment/89665115
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/51347862
has title: Comparing word to dictionary and assigning value
downvote count: 0

http://stackoverflow.com/a/51443095
answers question: http://stackoverflow.com/q/51443048
score: 2
upvote count: 2
has body: You do not need a regex for this, you just need str.rindex: text = text[:text.rindex('\\')] If you realle want to use a regex then you can use re.sub, use $ to match the end of string and [^\\] to match everything that is not \: import re text = re.sub(r'\\[^\\]*$', '', text) There are other N ways to match the same thing, but I believe it's an overkill in this case.
type: Answer
downvote count: 0

http://stackoverflow.com/comment/89763309
comment on: http://stackoverflow.com/a/51379153
type: AnswerComment
score: 0
type: Comment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/176223/discussion-between-magnetron-and-jack).

http://stackoverflow.com/comment/89692940
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51359731
has text: see `tf.while_loop` for details
score: 0

http://stackoverflow.com/q/51382748
has comment: http://stackoverflow.com/comment/89737389
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51382924
tagged with: index-error
score: 1
type: Question
accepted answer: http://stackoverflow.com/a/51382856
has comment: http://stackoverflow.com/comment/89737381
downvote count: 0
answer count: 7
favorite count: 0
has answer: http://stackoverflow.com/a/51382852
has answer: http://stackoverflow.com/a/51382899
has answer: http://stackoverflow.com/a/51382897
has title: Python - IndexError: list index out of range NOT being thrown when it should be
has comment: http://stackoverflow.com/comment/89737407
has answer: http://stackoverflow.com/a/51382823
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51382856
has answer: http://stackoverflow.com/a/51382877
has body: Not sure if this is BECAUSE of Jupyter Notebook or just that Python HANDLES the exception, but I was solving a problem involving algorithms with a friend While whiteboarding the code, I used Python! exampleList = ['a', 'b', 'c', 'd', 'e'] for i in range(0, len(exampleList)): for j in range(i + 1, len(exampleList)): print(exampleList[i], exampleList[j]) Basically, the debate was that.. This code (a similar one, I have used a simple example to illustrate) involving two for loops MUST throw an error! Because, index i reached len(exampleList) - 1, and index j technically will become len(exampleList) and at that point, print(exampleList[i], exampleList[j]) cannot work! It looks like while running the code, it does print out perfectly, and I think HANDLES the IndexError: list index out of range exception! My question is.. Is this supposed to be intended behaviour in Python? Because the person I was debating with ended up telling me that 'The people conducting your interview notice these things! You must be able to explain every line.' I would like to understand how this part is handled so I can explain why this does not throw an error!
has comment: http://stackoverflow.com/comment/89737375
possible better answer: http://stackoverflow.com/a/51382823
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89737499

http://stackoverflow.com/q/51422664
score: 0
has comment: http://stackoverflow.com/comment/89821206
has body: I have the following string: 'none; but currently has appt with new HJH PCP Rachel Salas, MD on October. 11, 2013 Other Agency Involvement: No\n')' and I am trying to get "October. 11, 2013" out of it. The comma after the 11 needs to be optional. The code I am using is: re.findall(r'(\S+)\s*\d+,*\s([2][0]\d\d|[1][9]\d\d)', raw_data[i]) and the output I am getting is skipping the 11: [('October.', '2013')] explanation of my logic: (\S+)\s* # limit the word before the number to max 1 occurence, and avoid the full sentence. optional space between word and number \d+,* # catch the number between the month and the year, with an optional comma \s([2][0]\d\d|[1][9]\d\d) # catch the year after the space I am very grateful for your help.
has title: python regex for date with words and numbers in long string
type: UnansweredQuestion
tagged with: python
tagged with: regex
answer count: 0
linked to: http://stackoverflow.com/q/31915018
type: Question
has comment: http://stackoverflow.com/comment/89816333
duplicate of: http://stackoverflow.com/q/31915018

http://stackoverflow.com/a/51350133
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89672953
has comment: http://stackoverflow.com/comment/89672952
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51350115
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89672930
has body: Though this isn't tagged numpy, I think you would greatly benefit from np.cumsum (cumulative sum) rather than looping: import numpy as np np.cumsum(month) array([ 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365]) Alternatively, you could use this list comprehension: [sum(month[:i+1]) for i in range(len(month))] [31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365] As pointed out by @PatrickHaugh, you could also use itertools.accumulate: import itertools # Cast it to list to see results (not necessary depending upon what you want to do with your results) list(itertools.accumulate(month)) [31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365]
has comment: http://stackoverflow.com/comment/89672998
answers question: http://stackoverflow.com/q/51350115

http://stackoverflow.com/q/51357819
has title: Changing the starting index of a list (from 0 to 2)
has body: a=[1,2,3,4,5] b=[] how can i append a to b such that my starting index of b is 2.Rather than 0 being my starting index my index should start at 2
has comment: http://stackoverflow.com/comment/89687823
has answer: http://stackoverflow.com/a/51357904
favorite count: 0
has answer: http://stackoverflow.com/a/51357883
has comment: http://stackoverflow.com/comment/89687781
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/89688116
tagged with: python
upvote count: 1
type: Question
answer count: 2
score: -1

http://stackoverflow.com/q/51386947
tagged with: contourf
score: 1
tagged with: matplotlib
has answer: http://stackoverflow.com/a/54190055
type: Question
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51387384
favorite count: 0
tagged with: python
has title: contourf() plots white space over finite data
type: UnansweredQuestion
upvote count: 1
has body: I'm attempting to plot a 3D chart using matplotlib.pyplot.contourf() with the following program: import numpy as np import matplotlib.pyplot as plt import scipy # calculates Fast Fourier transforms for each value in the 1D array "Altitude" # and stacks them vertically to form a 2D array of fft values called "Fourier" Fourier = np.array([]) for i in range(len(Altitude)): Ne_fft = Ne_lowpass[i,:]/np.average(Ne_lowpass[i,:]) Ne_fft = Ne_fft - Ne_fft.mean() W = scipy.fftpack.fftfreq(10*Ne_fft.size, d=(Time[-1]-Time[0])/len(Ne_fft)) P = 1/abs(W) FFT = abs(scipy.fftpack.fft(Ne_fft, n=10*len(Ne_fft))) FFT = FFT**2 if len(Fourier) == 0: Fourier = FFT else: Fourier = np.vstack((Fourier,FFT)) # plots the 2D contourf plot of "Fourier", with respect to "Altitude" and period "P" plt.figure(5) C = plt.contourf(P,Altitude,Fourier,100,cmap='jet') plt.xscale('log') plt.xlim([1,P[np.argmax(P)+1]]) plt.ylim([59,687]) plt.ylabel("Altitude") plt.xlabel("Period") plt.title("Power spectrum of Ne") cbar = plt.colorbar(C) cbar.set_label("Power", fontsize = 16) For the most part it is working fine; however, in some places useless white space is plotted. the plot produced can be found here (sorry, I don't have enough reputation points to attach images directly) The purpose of this program is to calculate a series of Fast Fourier Transforms across 1 axis of a 2 dimensional numpy array, and stack them up to display a contour plot depicting which periodicities are most prominent in the data. I checked the parts of the plotted quantity that appear white, and finite values are still present, although much smaller than noticable quantities elsewhere in the plot: print(Fourier[100:,14000:]) [[ 2.41147887e-03 1.50783490e-02 4.82620482e-02 ..., 1.49769976e+03 5.88859945e+02 1.31930217e+02] [ 2.12684922e-03 1.44076962e-02 4.65881565e-02 ..., 1.54719976e+03 6.14086374e+02 1.38727145e+02] [ 1.84414615e-03 1.38162140e-02 4.51940720e-02 ..., 1.56478339e+03 6.23619105e+02 1.41367042e+02] ..., [ 3.51539440e-…
tagged with: scipy

series
tag name: series
type: Tag
tags question: http://stackoverflow.com/q/51400727
tags question: http://stackoverflow.com/q/51358500
tags question: http://stackoverflow.com/q/51384816
tags question: http://stackoverflow.com/q/51461280

http://stackoverflow.com/q/51388089
tagged with: python-3.x
tagged with: python
has body: I have encountered a strange situation. What's wrong? When I run python manage.py shell from the project directory, import a model (any model), and try to access its Model.objects (objects.all(), objects.create(), ...), it throws an OperationalError as quoted below. &gt;&gt;&gt; from Interface.models import ClientUser &gt;&gt;&gt; ClientUser.objects.all() django.db.utils.OperationalError: no such table: Interface_clientuser &gt;&gt;&gt; ClientUser.objects.create() django.db.utils.OperationalError: no such table: Interface_clientuser I have tried deleting the database and then running python manage.py migrate, closing everything and restarting my computer, and staring really hard at the code (lol), but to no avail.. Interestingly, my unit tests all pass; including, for instance, ones that call ClientUser.objects.create() Here is the ClientUser model, though I don't think the model is the problem (error occurs for all models and unittests pass..) class ClientUser(models.Model): guid = models.UUIDField(null=True, unique=True) username = models.CharField(max_length=256, null=True, unique=True) first_name = models.CharField(max_length=256, null=True) last_name = models.CharField(max_length=256, null=True) email = models.CharField(max_length=256, null=True) def most_recent_device(self): return self.devices.order_by('-pk').first() # I just put this classmethod in. I'm not sure if this will work, and went to the shell to try it, and that's when I noticed this issue. I've tried commenting it out and it makes no difference. @classmethod def get_by_guid(cls, guid): return cls.objects.get(guid=guid) Here is the complete stacktrace from the shell (above): &gt;&gt;&gt; from Interface.models import ClientUser &gt;&gt;&gt; ClientUser.objects.all() Traceback (most recent call last): File "C:\Program Files\Python37\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Program Files\Python37\lib\site-packages\django\db\ba…
type: UnansweredQuestion
tagged with: django
has answer: http://stackoverflow.com/a/51388187
has answer: http://stackoverflow.com/a/51388416
has title: Django - Why am I getting an OperationalError (only) when I am using the shell?
type: Question
score: 0
answer count: 2

http://stackoverflow.com/comment/89792098
type: QuestionComment
comment on: http://stackoverflow.com/q/51399077
score: 0
has text: I also want to thank you all for such a speedy response!
type: Comment

http://stackoverflow.com/q/51331600
has comment: http://stackoverflow.com/comment/89638933
upvote count: 2
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/89639374
has answer: http://stackoverflow.com/a/51342690
tagged with: python
score: 2
tagged with: ubuntu-16.04
has comment: http://stackoverflow.com/comment/89647592
type: Question
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90164908
tagged with: suricata
has body: I got an errors that I can't fix when I'm trying to run Scirius project on my Ubuntu 16.04 LTS and I'm newbie in this field. can someone help me out, I need to run this project that I cloned from https://github.com/StamusNetworks/scirius python manage.py migrate &gt; Traceback (most recent call last): File "manage.py", line 10, in &gt; &lt;module&gt; &gt; execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", &gt; line 353, in execute_from_command_line &gt; utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", &gt; line 345, in execute &gt; self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", &gt; line 348, in run_from_argv &gt; self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", &gt; line 398, in execute &gt; self.check() File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", &gt; line 426, in check &gt; include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python2.7/dist-packages/django/core/checks/registry.py", &gt; line 75, in run_checks &gt; new_errors = check(app_configs=app_configs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", &gt; line 13, in check_url_config &gt; return check_resolver(resolver) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", &gt; line 23, in check_resolver &gt; for pattern in resolver.url_patterns: File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", &gt; line 33, in __get__ &gt; res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", &gt; line 417, in url_patterns &gt; patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File &gt; "/usr/local/lib/python2.7/dist-packages/django/ut…
has title: error when running manage.py migrate
favorite count: 0

http://stackoverflow.com/comment/89929746
type: QuestionComment
comment on: http://stackoverflow.com/q/51479635
score: 0
has text: @BearBrown Hmm, thats true... didn't think about that this way...
type: Comment

http://stackoverflow.com/a/51342995
answers question: http://stackoverflow.com/q/51342724
type: Answer
score: 2
upvote count: 2
has body: So as your data is multidimensional (D, in your case specifically D=15), you need to model the mean of the data (D dimensional) and the covariance (D^2 dimensional). You can easily implement it using numpy as follows import numpy as np def gaussian_mle(data): mu = data.mean(axis=0) var = (data-mu).T @ (data-mu) / data.shape[0] # this is slightly suboptimal, but instructive return mu, var To see that it works, lets run it on some artificial data: mean = [1.0, 3.14] cov = [[2.0, 0.5], [0.5, 10]] data = np.random.multivariate_normal(mean, cov, 10000) print(gaussian_mle(data)) Which gives us, after custom formating (as we sample randomly, results may differ slightly): ( array([1.00981014, 3.1217965 ]), # sample mean array([[2.0266404 , 0.43036865], [0.43036865, 9.87599803]]) # sample covariance )
downvote count: 0

http://stackoverflow.com/q/51409288
score: 5
tagged with: python
has title: Can I [de]serialize a dictionary of dataframes in the arrow/js implementation?
tagged with: pyarrow
answer count: 1
tagged with: apache-arrow
tagged with: ipc
has answer: http://stackoverflow.com/a/56085704
upvote count: 5
tagged with: javascript
type: UnansweredQuestion
has body: I want to use Apache Arrow to send data from a Django backend to a Angular frontend. I want to use a dictionary of dataframes/tables as payload in messages. It's posssible with pyarrow to share data in this way between python microservices, but i cant find a way with the javascript implementation of arrow. Is there a way to deserialize/serialize a dictionary with strings as keys and dataframes/tables as values in the javascript side with Arrow?
downvote count: 0
favorite count: 0
type: Question